From 3ffb1e9c3d33613f463c38b97b0a529a5bd88665 Mon Sep 17 00:00:00 2001 From: Tristan Simas Date: Mon, 16 Nov 2026 14:44:35 -0500 Subject: [PATCH] Key declarations come from metaclass_registry; Textual's copy is deleted KeyDeclarationType, KeyInvocation, KeyTitle and KeyDeclaration live in metaclass_registry.key_declarations (metaclass-registry #14), so a client without Textual declares actions with their keys. EditingMode and VimMode subclass its InputMode and ModalInputMode, which hold which mode a key belongs to; the engine behaviour stays here. Every importer is repointed. bindings_for, Textual's projection of a declaration into bindings, stays here as BindingDeclaration, which DOM key families and NavigationCommand use. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016gZLdupVQyBzHTmHBC9Cyn --- src/textual/binding.py | 4 +- src/textual/document/_editing.py | 12 +- src/textual/dom.py | 13 +- src/textual/keys.py | 125 +----------------- src/textual/navigation.py | 4 +- .../input/test_input_key_movement_actions.py | 3 +- tests/text_area/test_edit_via_bindings.py | 3 +- 7 files changed, 26 insertions(+), 138 deletions(-) diff --git a/src/textual/binding.py b/src/textual/binding.py index d61e2b21e6..d98a56609b 100644 --- a/src/textual/binding.py +++ b/src/textual/binding.py @@ -29,7 +29,9 @@ from textual._callback import invoke, invoke_sync from textual.actions import SkipAction -from textual.keys import DeclaredKey, KeyDeclaration, KeyInvocation, UndecodedKey, _character_to_key +from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation + +from textual.keys import DeclaredKey, UndecodedKey, _character_to_key if TYPE_CHECKING: from textual.document._editing import EditingMode diff --git a/src/textual/document/_editing.py b/src/textual/document/_editing.py index 26aa222e68..d1acc77638 100644 --- a/src/textual/document/_editing.py +++ b/src/textual/document/_editing.py @@ -4,9 +4,11 @@ from abc import ABC, abstractmethod from typing import TYPE_CHECKING +from metaclass_registry.key_declarations import InputMode, ModalInputMode + from textual.binding import Binding, MethodBinding from textual.cursor_shape import CursorShape, SteadyBlock, TextEntryCursor -from textual.document._document import EditResult, Location, Selection +from textual.document._document import EditResult, Selection from textual.document._edit import Edit, InsertionPoint if TYPE_CHECKING: @@ -19,11 +21,9 @@ class EditingFailure(RuntimeError): """The engine failed; preserve its displayed draft and never replay input.""" -class EditingMode: +class EditingMode(InputMode): """Native text entry, with overridable document and input ownership.""" - modal = False - @classmethod def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]: return (key.key.value,) @@ -164,11 +164,9 @@ def allows_application_commands(self) -> bool: return self.key_mode().allows_application_commands -class VimMode(EditingMode, ABC): +class VimMode(EditingMode, ModalInputMode, ABC): """Modal binding capability, not a second implementation of Vim.""" - modal = True - @classmethod def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]: return (*super().navigation_spellings(key), key.modal) diff --git a/src/textual/dom.py b/src/textual/dom.py index 26c011715f..0c97fd15bb 100644 --- a/src/textual/dom.py +++ b/src/textual/dom.py @@ -10,7 +10,6 @@ import threading from weakref import ref from functools import lru_cache, partial -from dataclasses import replace from inspect import getfile from typing import ( TYPE_CHECKING, @@ -53,9 +52,8 @@ from textual.geometry import Size from textual.css.tokenize import IDENTIFIER from textual.message_pump import MessagePump -from textual.keys import KeyDeclaration +from textual.keys import BindingDeclaration from textual.reactive import Reactive, ReactiveError, _Mutated, _StoredReactiveAccess, _watch -from textual.style import NULL_STYLE from textual.timer import Timer from textual.walk import walk_breadth_first, walk_breadth_search_id, walk_depth_first from textual.worker_manager import WorkerManager @@ -71,7 +69,6 @@ from textual.screen import Screen from textual.widget import Widget from textual.events import Key - from textual.widgets import TextArea from textual.worker import Worker, WorkType, ResultType from typing_extensions import Literal @@ -529,8 +526,8 @@ def _component_styles(self) -> dict[str, RenderStyles]: return {} _declared_key_bindings: ClassVar[tuple[MethodBinding, ...]] = () - _own_key_families: ClassVar[tuple[type[KeyDeclaration], ...]] = () - key_families: ClassVar[tuple[type[KeyDeclaration], ...]] = () + _own_key_families: ClassVar[tuple[type[BindingDeclaration], ...]] = () + key_families: ClassVar[tuple[type[BindingDeclaration], ...]] = () @classmethod def contexts(cls) -> tuple[type[DOMNode], ...]: @@ -556,7 +553,7 @@ def native_bindings(cls, mode: type[EditingMode]) -> tuple[ModeBinding, ...]: for projected in binding.for_mode(mode)) @classmethod - def present_binding(cls, declaration: type[KeyDeclaration], binding: Binding) -> Binding: + def present_binding(cls, declaration: type[BindingDeclaration], binding: Binding) -> Binding: return binding @classmethod @@ -1005,7 +1002,7 @@ def __init_subclass__( inherit_css: bool = True, inherit_bindings: bool = True, inherit_component_classes: bool = True, - key_families: tuple[type[KeyDeclaration], ...] = (), + key_families: tuple[type[BindingDeclaration], ...] = (), ) -> None: cls._own_key_families = key_families cls.key_families = tuple(dict.fromkeys( diff --git a/src/textual/keys.py b/src/textual/keys.py index b01df3aac4..f2bc05d014 100644 --- a/src/textual/keys.py +++ b/src/textual/keys.py @@ -1,10 +1,8 @@ from __future__ import annotations import unicodedata -import inspect -import re -from abc import ABC, ABCMeta, abstractmethod -from typing import TYPE_CHECKING, Callable, ClassVar, Generic, Iterator, TypeVar +from abc import abstractmethod +from typing import TYPE_CHECKING, ClassVar, TypeVar from enum import Enum from dataclasses import dataclass from functools import lru_cache @@ -15,113 +13,14 @@ from textual.dom import DOMNode from textual.events import Key -NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True) - - -class KeyDeclarationType(ABCMeta): - """A key-declaring class, including declarations supplied by a metaclass.""" - - def permits_key_overlap(cls, other: KeyDeclarationType) -> bool: - """An explicitly declared alternative may share this declaration's key.""" - return False - - -class KeyInvocation(ABC): - """The concrete command a binding invokes, independent of its active mode.""" - - @staticmethod - def qualified(declaration: type | Callable[..., object]) -> str: - return f"{declaration.__module__}.{declaration.__qualname__}" - - @abstractmethod - def key_identity(self) -> str: ... - - @abstractmethod - def key_title(self) -> str: ... - - @abstractmethod - def key_summary(self) -> str: ... - - @abstractmethod - def key_system(self) -> bool: ... - - def binding_identity(self, mode: type[EditingMode]) -> str: - return self.in_mode(self.key_identity(), mode) - - @staticmethod - def in_mode(identity: str, mode: type) -> str: - return f"{identity}:{KeyInvocation.qualified(mode)}" - - def visible_for_focus(self, focused: bool) -> bool: - """Local commands follow their declaration's actual prior-focus membership.""" - return focused - - def permits_invocation_overlap(self, other: KeyInvocation) -> bool: - return False - - def overlaps_declaration(self, other: KeyDeclarationType) -> bool: - return False - - -class KeyTitle: - """Human text derived from the declaration rather than a second title roster.""" - - def __get__(self, instance: object, owner: type[KeyDeclaration]) -> str: - return owner.default_title() - +from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation -class KeyDeclaration(KeyInvocation, Generic[NodeT], metaclass=KeyDeclarationType): - """Shared metadata for application actions and native editor commands. - - Each provider retains its existing family registry. This view discovers the - provider declarations through inheritance; no menu supplies their names. - """ - - title = KeyTitle() - system: ClassVar[bool] = False - _declared: ClassVar[list[type[KeyDeclaration]]] = [] - - def __init_subclass__(cls, **kwargs) -> None: - super().__init_subclass__(**kwargs) - KeyDeclaration._declared.append(cls) - - @classmethod - def default_title(cls) -> str: - return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", cls.__name__).capitalize() - - @classmethod - def identity(cls) -> str: - return cls.qualified(cls) - - @classmethod - def binding_id(cls, mode: type) -> str: - return cls.binding_id_for(cls, mode) - - @staticmethod - def binding_id_for(declaration: type | Callable[..., object], mode: type) -> str: - """Class and native callable declarations use the same mode-qualified identity.""" - return KeyInvocation.in_mode(KeyInvocation.qualified(declaration), mode) - - def key_identity(self) -> str: - return type(self).identity() - - def key_title(self) -> str: - return self.title - - def key_summary(self) -> str: - return self.summary() - - def key_system(self) -> bool: - return self.system - - def permits_invocation_overlap(self, other: KeyInvocation) -> bool: - return other.overlaps_declaration(type(self)) +NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True) - def overlaps_declaration(self, other: KeyDeclarationType) -> bool: - return type(self).permits_key_overlap(other) - @abstractmethod - def __call__(self, node: NodeT) -> object: ... +class BindingDeclaration(KeyDeclaration[NodeT]): + """A key declaration whose class projects its own Textual bindings, as a DOM node's + key families ask it to.""" @classmethod @abstractmethod @@ -129,16 +28,6 @@ def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]: """The declaration's defaults in one active editing mode.""" raise NotImplementedError - @classmethod - def summary(cls) -> str: - return inspect.cleandoc(cls.__doc__ or "") - - @classmethod - def declarations(cls) -> Iterator[type[KeyDeclaration]]: - """Project each key family from the declaration owner's registry.""" - return (member for member in KeyDeclaration._declared - if issubclass(member, cls) and not inspect.isabstract(member)) - # Adapted from prompt toolkit https://github.com/prompt-toolkit/python-prompt-toolkit/blob/master/prompt_toolkit/keys.py class Keys(str, Enum): # type: ignore[no-redef] diff --git a/src/textual/navigation.py b/src/textual/navigation.py index 07b61abf91..4fe42b6cac 100644 --- a/src/textual/navigation.py +++ b/src/textual/navigation.py @@ -8,10 +8,10 @@ from textual.binding import Binding, CommandBinding from textual.document._editing import EditingMode from textual.dom import DOMNode -from textual.keys import DeclaredKey, DownKey, KeyDeclaration, LeftKey, RightKey, UndecodedKey, UpKey +from textual.keys import BindingDeclaration, DeclaredKey, DownKey, LeftKey, RightKey, UndecodedKey, UpKey -class NavigationCommand(KeyDeclaration["Navigation"]): +class NavigationCommand(BindingDeclaration["Navigation"]): """A list command owns its keys; controls own the operation it requests.""" keys: ClassVar[tuple[str, ...]] = () diff --git a/tests/input/test_input_key_movement_actions.py b/tests/input/test_input_key_movement_actions.py index 29fc9a0aba..74c6e4d8eb 100644 --- a/tests/input/test_input_key_movement_actions.py +++ b/tests/input/test_input_key_movement_actions.py @@ -4,7 +4,8 @@ from textual.app import App, ComposeResult from textual.document._editing import EditingMode -from textual.keys import KeyInvocation, LeftKey, RightKey +from metaclass_registry.key_declarations import KeyInvocation +from textual.keys import LeftKey, RightKey from textual.widgets import Input diff --git a/tests/text_area/test_edit_via_bindings.py b/tests/text_area/test_edit_via_bindings.py index 271e5bf50b..004c405cf2 100644 --- a/tests/text_area/test_edit_via_bindings.py +++ b/tests/text_area/test_edit_via_bindings.py @@ -12,7 +12,8 @@ from textual.app import App, ComposeResult from textual.document._editing import EditingMode from textual.events import Paste -from textual.keys import KeyInvocation, LeftKey +from metaclass_registry.key_declarations import KeyInvocation +from textual.keys import LeftKey from textual.widgets import TextArea from textual.widgets.text_area import Selection