Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ rich = ">=14.2.0"
typing-extensions = "^4.4.0"
platformdirs = ">=3.6.0,<5"
metaclass-registry = { git = "https://github.com/OpenHCSDev/metaclass-registry", branch = "main" }
formbridge = { git = "https://github.com/OpenHCSDev/formbridge.git", branch = "main" }

# start of [syntax] extras
# Require tree-sitter >= 0.25.0 and python >= 3.10
Expand Down
16 changes: 14 additions & 2 deletions src/textual/binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from __future__ import annotations

import dataclasses
from abc import abstractmethod
from dataclasses import dataclass, field
from inspect import iscoroutinefunction
from types import FunctionType
Expand All @@ -29,9 +30,9 @@

from textual._callback import invoke, invoke_sync
from textual.actions import SkipAction
from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation
from formbridge.key_declarations import DeclaredKey, KeyDeclaration, KeyInvocation, UndecodedKey

from textual.keys import DeclaredKey, UndecodedKey, _character_to_key
from textual.keys import _character_to_key

if TYPE_CHECKING:
from textual.document._editing import EditingMode
Expand Down Expand Up @@ -434,6 +435,17 @@ def key_identity(self) -> str:
NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True)


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
def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]:
"""The declaration's defaults in one active editing mode."""
raise NotImplementedError


@dataclass(frozen=True, kw_only=True)
class CommandBinding(ModeBinding, Generic[NodeT]):
"""The callable is the command itself, including its invocation identity."""
Expand Down
11 changes: 1 addition & 10 deletions src/textual/document/_editing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING

from metaclass_registry.key_declarations import InputMode, ModalInputMode
from formbridge.key_declarations import InputMode, ModalInputMode

from textual.binding import Binding, MethodBinding
from textual.cursor_shape import CursorShape, SteadyBlock, TextEntryCursor
Expand All @@ -13,7 +13,6 @@

if TYPE_CHECKING:
from textual.events import Key
from textual.keys import NavigationKey
from textual.widgets import TextArea


Expand All @@ -24,10 +23,6 @@ class EditingFailure(RuntimeError):
class EditingMode(InputMode):
"""Native text entry, with overridable document and input ownership."""

@classmethod
def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]:
return (key.key.value,)

@property
def accepts_text(self) -> bool:
return True
Expand Down Expand Up @@ -167,10 +162,6 @@ def allows_application_commands(self) -> bool:
class VimMode(EditingMode, ModalInputMode, ABC):
"""Modal binding capability, not a second implementation of Vim."""

@classmethod
def navigation_spellings(cls, key: type[NavigationKey]) -> tuple[str, ...]:
return (*super().navigation_spellings(key), key.modal)

@property
def cursor_shape(self) -> CursorShape:
return SteadyBlock()
Expand Down
2 changes: 1 addition & 1 deletion src/textual/dom.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
from textual.geometry import Size
from textual.css.tokenize import IDENTIFIER
from textual.message_pump import MessagePump
from textual.keys import BindingDeclaration
from textual.binding import BindingDeclaration
from textual.reactive import Reactive, ReactiveError, _Mutated, _StoredReactiveAccess, _watch
from textual.timer import Timer
from textual.walk import walk_breadth_first, walk_breadth_search_id, walk_depth_first
Expand Down
125 changes: 0 additions & 125 deletions src/textual/keys.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,9 @@
from __future__ import annotations

import unicodedata
from abc import abstractmethod
from typing import TYPE_CHECKING, ClassVar, TypeVar
from enum import Enum
from dataclasses import dataclass
from functools import lru_cache

if TYPE_CHECKING:
from textual.binding import Binding
from textual.document._editing import EditingMode
from textual.dom import DOMNode
from textual.events import Key

from metaclass_registry.key_declarations import KeyDeclaration, KeyInvocation

NodeT = TypeVar("NodeT", bound="DOMNode", contravariant=True)


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
def bindings_for(cls, mode: type[EditingMode]) -> tuple[Binding, ...]:
"""The declaration's defaults in one active editing mode."""
raise NotImplementedError


# 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]
Expand Down Expand Up @@ -224,107 +200,6 @@ def value(self) -> str:
ShiftControlEnd = ControlShiftEnd


@dataclass(frozen=True)
class DeclaredKey:
"""A decoded native input identity, distinct from its configured spelling."""

def decoded(self, key: str) -> DeclaredKey:
return self

def spellings(self, mode: type[EditingMode], spelling: str) -> tuple[str, ...]:
return (spelling,)

def invocations(self, defaults: tuple[KeyInvocation, ...]) -> tuple[KeyInvocation, ...]:
return defaults

def preempts(self, event: Key, target: DOMNode) -> bool:
return False

def input_bindings(self, spelling: str) -> tuple[tuple[str, str], ...]:
"""Native input aliases for an external editing engine."""
return ()


class UndecodedKey(DeclaredKey):
"""Only Binding.make_bindings sees an external declaration's key spelling."""

def decoded(self, key: str) -> DeclaredKey:
return NavigationKey.from_key(key)


class NavigationKey(DeclaredKey, KeyInvocation):
"""One preference for an arrow, independent of the focused control's effect.

Bindings keep their native callable, availability and order. Only the saved
input identity is shared: configuring Up must not mean configuring TextArea,
a table, a tree and every future arrow control separately.
"""

key: ClassVar[Keys]
modal: ClassVar[str]
_by_key: ClassVar[dict[str, type[NavigationKey]]] = {}

def __init_subclass__(cls, *, key: Keys, modal: str, **kwargs: object) -> None:
super().__init_subclass__(**kwargs)
cls.key = key
cls.modal = modal
cls._by_key[key.value] = cls

@classmethod
def from_key(cls, key: str) -> DeclaredKey:
"""Decode a declared native key once, before any preference changes it."""
try:
declaration = cls._by_key[key]
except KeyError:
return DeclaredKey()
return declaration()

def invocations(self, defaults: tuple[KeyInvocation, ...]) -> tuple[KeyInvocation, ...]:
return (self,)

def spellings(self, mode: type[EditingMode], spelling: str) -> tuple[str, ...]:
return mode.navigation_spellings(type(self))

def preempts(self, event: Key, target: DOMNode) -> bool:
"""Arrow aliases precede search, never the target's literal text input."""
return event.is_printable and not target.takes_typed_text

def key_identity(self) -> str:
return self.qualified(type(self))

def input_bindings(self, spelling: str) -> tuple[tuple[str, str], ...]:
return ((spelling, self.key.value),)

def key_title(self) -> str:
return f"Cursor {self.key.value}"

def key_summary(self) -> str:
return f"Use these keys wherever the focused control handles {self.key.value}."

def key_system(self) -> bool:
return False

def visible_for_focus(self, focused: bool) -> bool:
"""Global arrow preferences remain editable even from a non-arrow focus."""
return True


class UpKey(NavigationKey, key=Keys.Up, modal="k"):
pass


class DownKey(NavigationKey, key=Keys.Down, modal="j"):
pass


class LeftKey(NavigationKey, key=Keys.Left, modal="h"):
pass


class RightKey(NavigationKey, key=Keys.Right, modal="l"):
pass


# Unicode db contains some obscure names
# This mapping replaces them with more common terms
KEY_NAME_REPLACEMENTS = {
Expand Down
5 changes: 3 additions & 2 deletions src/textual/navigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
from typing import ClassVar

from textual.actions import SkipAction
from textual.binding import Binding, CommandBinding
from formbridge.key_declarations import DeclaredKey, DownKey, LeftKey, RightKey, UndecodedKey, UpKey

from textual.binding import Binding, BindingDeclaration, CommandBinding
from textual.document._editing import EditingMode
from textual.dom import DOMNode
from textual.keys import BindingDeclaration, DeclaredKey, DownKey, LeftKey, RightKey, UndecodedKey, UpKey


class NavigationCommand(BindingDeclaration["Navigation"]):
Expand Down
3 changes: 2 additions & 1 deletion src/textual/screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,9 +545,10 @@ async def dispatch_remapped_key(self, event: events.Key, target: Widget) -> bool
second delivery. Native editor bindings forward it to their mode owner;
ordinary controls execute their own declared action.
"""
printable_outside_text = event.is_printable and not target.takes_typed_text
for node, bindings in self._modal_binding_chain:
for binding in bindings.key_to_bindings.get(event.key, ()):
if binding.declared_key.preempts(event, target):
if binding.declared_key.preempts(printable_outside_text):
if await binding.run_before_text(self.app, node, event, target):
return True
return False
Expand Down
3 changes: 1 addition & 2 deletions tests/input/test_input_key_movement_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@

from textual.app import App, ComposeResult
from textual.document._editing import EditingMode
from metaclass_registry.key_declarations import KeyInvocation
from textual.keys import LeftKey, RightKey
from formbridge.key_declarations import KeyInvocation, LeftKey, RightKey
from textual.widgets import Input


Expand Down
6 changes: 3 additions & 3 deletions tests/test_navigation_spellings.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
"""Arrow identities supply modal spellings, including controls not hand-patched."""
from formbridge.key_declarations import DownKey, NavigationKey
from textual import widgets
from textual.app import App, ComposeResult
from textual.containers import VerticalScroll
from textual.document._editing import EditingMode, VimMode
from textual.dom import DOMNode
from textual.events import Key
from textual.keys import DownKey, NavigationKey
from textual.screen import Screen
from textual.widgets import Input, TextArea, Tree

Expand All @@ -20,11 +20,11 @@ def test_navigation_spellings_follow_every_declared_context() -> None:
modal = owner.binding_defaults(VimMode)
for direction in NavigationKey.__subclasses__():
arrows = tuple(
binding for binding in modal.key_to_bindings.get(direction.key.value, ())
binding for binding in modal.key_to_bindings.get(direction.key, ())
if binding.declared_key == direction()
)
if any(binding.declared_key == direction()
for binding in standard.key_to_bindings.get(direction.key.value, ())):
for binding in standard.key_to_bindings.get(direction.key, ())):
assert arrows, (owner, direction)
for arrow in arrows:
assert arrow.with_key(direction.modal) in modal.key_to_bindings.get(direction.modal, ()), (owner, direction)
Expand Down
3 changes: 1 addition & 2 deletions tests/text_area/test_edit_via_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
from textual.app import App, ComposeResult
from textual.document._editing import EditingMode
from textual.events import Paste
from metaclass_registry.key_declarations import KeyInvocation
from textual.keys import LeftKey
from formbridge.key_declarations import KeyInvocation, LeftKey
from textual.widgets import TextArea
from textual.widgets.text_area import Selection

Expand Down