Skip to content

textual

Class info

Re-exported classes

Class Module Description
Editor promptantic.textual.editors Base of all editors: a node, its path in the value, and an error line.
FormApp promptantic.textual.view A one-form app; :meth:run_async returns the result (None: cancelled).
FormCancelledError promptantic.form.target The user closed the form without submitting it.
FormPanel promptantic.textual.view A titled :class:FormView with Submit / Cancel buttons.
FormScreen promptantic.textual.view A modal form; dismisses with the validated result, or None when cancelled.
FormView promptantic.textual.view A form for a :class:~promptantic.form.FormTarget, validated on submit.

🛈 DocStrings

Textual renderer (pip install promptantic[textual]).

Embed :class:FormView or :class:FormScreen in a Textual app, or call :func:fill_inline from a plain CLI.

Editor

Bases: Widget

Base of all editors: a node, its path in the value, and an error line.

Source code in src/promptantic/textual/editors.py
class Editor(Widget):
    """Base of all editors: a node, its path in the value, and an error line."""

    DEFAULT_CSS = """
    Editor { height: auto; }
    Editor > .pa-errors { color: $text-error; height: auto; }
    Editor > .pa-errors.-empty { display: none; }
    """

    def __init__(self, node: FormNode, path: Path, initial: Any, register: Registry) -> None:
        super().__init__()
        self.node = node
        self.path = path
        self.initial = initial
        self._register = register

    def on_mount(self) -> None:
        self._register(self.path, self)

    def errors_widget(self) -> Static:
        return Static("", classes="pa-errors -empty")

    def get_value(self) -> Any | Unset:
        """The value entered so far (:data:`UNSET`: nothing).

        Raises:
            FieldError: Input that can't become a value (e.g. text in a number field).
        """
        raise NotImplementedError

    def show_errors(self, messages: list[str]) -> None:
        errors = self.query_children(".pa-errors").first(Static)
        errors.update("\n".join(messages))
        errors.set_class(not messages, "-empty")

    def check(self) -> None:
        """Show what's wrong with this field alone (on every change)."""
        try:
            value = self.get_value()
        except FieldError as exc:
            self.show_errors([str(exc)])
            return
        self.show_errors([] if value is UNSET else field_errors(self.node, value))

check

check() -> None

Show what's wrong with this field alone (on every change).

Source code in src/promptantic/textual/editors.py
def check(self) -> None:
    """Show what's wrong with this field alone (on every change)."""
    try:
        value = self.get_value()
    except FieldError as exc:
        self.show_errors([str(exc)])
        return
    self.show_errors([] if value is UNSET else field_errors(self.node, value))

get_value

get_value() -> Any | Unset

The value entered so far (:data:UNSET: nothing).

Raises:

Type Description
FieldError

Input that can't become a value (e.g. text in a number field).

Source code in src/promptantic/textual/editors.py
def get_value(self) -> Any | Unset:
    """The value entered so far (:data:`UNSET`: nothing).

    Raises:
        FieldError: Input that can't become a value (e.g. text in a number field).
    """
    raise NotImplementedError

FormApp

Bases: App[Any]

A one-form app; :meth:run_async returns the result (None: cancelled).

Source code in src/promptantic/textual/view.py
class FormApp(App[Any]):
    """A one-form app; :meth:`run_async` returns the result (``None``: cancelled)."""

    CSS = "Screen { height: auto; overflow: hidden; } FormPanel { padding: 0 1; }"
    BINDINGS: ClassVar = [
        Binding("ctrl+s", "submit", "Submit", priority=True),
        Binding("escape", "cancel", "Cancel"),
    ]

    def __init__(
        self,
        target: FormTarget[Any],
        *,
        title: str | None = None,
        initial: Mapping[str, Any] | None = None,
    ) -> None:
        super().__init__()
        self.panel = FormPanel(target, title=title, initial=initial)
        self.cancelled = False

    def compose(self) -> ComposeResult:
        yield self.panel

    def action_submit(self) -> None:
        self.panel.form.submit()

    def action_cancel(self) -> None:
        self.cancelled = True
        self.exit(None)

    def on_form_view_submitted(self, event: FormView.Submitted) -> None:
        self.exit(event.result)

    def on_form_view_cancelled(self, _event: FormView.Cancelled) -> None:
        self.action_cancel()

FormCancelledError

Bases: Exception

The user closed the form without submitting it.

Source code in src/promptantic/form/target.py
class FormCancelledError(Exception):
    """The user closed the form without submitting it."""

FormPanel

Bases: Vertical

A titled :class:FormView with Submit / Cancel buttons.

Source code in src/promptantic/textual/view.py
class FormPanel(Vertical):
    """A titled :class:`FormView` with Submit / Cancel buttons."""

    DEFAULT_CSS = """
    FormPanel { height: auto; }
    FormPanel > #pa-title { text-style: bold; margin: 0 0 1 0; }
    FormPanel > #pa-buttons { height: auto; margin: 1 0 0 0; }
    FormPanel > #pa-buttons Button { margin: 0 1 0 0; }
    """

    def __init__(
        self, target: FormTarget[Any], *, title: str | None, initial: Mapping[str, Any] | None
    ) -> None:
        super().__init__()
        self.form = FormView(target, initial=initial)
        self.title_text = title or target.title

    def compose(self) -> ComposeResult:
        if self.title_text:
            yield Label(self.title_text, id="pa-title")
        yield self.form
        with Horizontal(id="pa-buttons"):
            yield Button("Submit", variant="primary", id="pa-submit")
            yield Button("Cancel", id="pa-cancel")

    def on_button_pressed(self, event: Button.Pressed) -> None:
        event.stop()
        if event.button.id == "pa-submit":
            self.form.submit()
        elif event.button.id == "pa-cancel":
            self.form.cancel()

FormScreen

Bases: ModalScreen[Any]

A modal form; dismisses with the validated result, or None when cancelled.

Source code in src/promptantic/textual/view.py
class FormScreen(ModalScreen[Any]):
    """A modal form; dismisses with the validated result, or ``None`` when cancelled."""

    DEFAULT_CSS = """
    FormScreen { align: center middle; }
    FormScreen > FormPanel {
        width: 90%; max-width: 110; max-height: 90%;
        border: thick $accent; background: $surface; padding: 0 1;
    }
    """
    BINDINGS: ClassVar = [
        Binding("ctrl+s", "submit", "Submit", priority=True),
        Binding("escape", "cancel", "Cancel"),
    ]

    def __init__(
        self,
        target: FormTarget[Any] | type[Any] | Mapping[str, Any],
        *,
        title: str | None = None,
        initial: Mapping[str, Any] | None = None,
    ) -> None:
        super().__init__()
        self.panel = FormPanel(_as_target(target), title=title, initial=initial)

    def compose(self) -> ComposeResult:
        yield self.panel

    def action_submit(self) -> None:
        self.panel.form.submit()

    def action_cancel(self) -> None:
        self.dismiss(None)

    def on_form_view_submitted(self, event: FormView.Submitted) -> None:
        self.dismiss(event.result)

    def on_form_view_cancelled(self, _event: FormView.Cancelled) -> None:
        self.dismiss(None)

FormView

Bases: Widget

A form for a :class:~promptantic.form.FormTarget, validated on submit.

Source code in src/promptantic/textual/view.py
class FormView(Widget):
    """A form for a :class:`~promptantic.form.FormTarget`, validated on submit."""

    DEFAULT_CSS = """
    FormView { height: auto; }
    FormView > #pa-fields { height: auto; max-height: 70vh; }
    FormView .pa-field { margin: 0 0 1 0; }
    FormView > #pa-summary { color: $text-error; height: auto; }
    FormView > #pa-summary.-empty { display: none; }
    """

    class Submitted(Message):
        """The form validated; ``result`` is the dict or model instance."""

        def __init__(self, view: FormView, result: Any) -> None:
            super().__init__()
            self.view = view
            self.result = result

    class Cancelled(Message):
        """The form was closed without a result."""

        def __init__(self, view: FormView) -> None:
            super().__init__()
            self.view = view

    def __init__(
        self,
        target: FormTarget[Any],
        *,
        initial: Mapping[str, Any] | None = None,
        id: str | None = None,  # noqa: A002 (Textual widget convention)
    ) -> None:
        super().__init__(id=id)
        self.target = target
        self.root = build_form(target.schema)
        self.initial = dict(initial) if initial is not None else UNSET
        self._editors: dict[Path, Editor] = {}

    def compose(self) -> ComposeResult:
        with VerticalScroll(id="pa-fields"):
            yield make_editor(self.root, (), self.initial, self._register)
        yield Static("", id="pa-summary", classes="-empty")

    def on_mount(self) -> None:
        self.call_after_refresh(self.focus_first)

    def focus_first(self) -> None:
        """Focus the first input, so typing goes straight into the form."""
        for widget in self.query_one("#pa-fields").query("*"):
            if widget.focusable:
                widget.focus()
                return

    def _register(self, path: Path, editor: Editor) -> None:
        self._editors[path] = editor

    def value(self) -> Any:
        """The value entered so far, unvalidated.

        Raises:
            FieldError: Some input can't become a value.
        """
        root = self.query_one("#pa-fields").query_children(Editor).first()
        value = root.get_value()
        return {} if value is UNSET else value

    def submit(self) -> None:
        """Validate; post :class:`Submitted`, or show the problems at their fields."""
        for editor in self._editors.values():
            if editor.is_attached:
                editor.show_errors([])
        try:
            value = self.value()
        except FieldError as exc:
            self._summary([str(exc)])
            return
        try:
            result = self.target.validate(value)
        except FormValidationError as exc:
            unplaced: list[str] = []
            for issue in exc.issues:
                if editor := self._editor_for(issue.path):
                    editor.show_errors([issue.message])
                else:
                    unplaced.append(issue.message)
            self._summary(unplaced or ["Please fix the marked fields"])
            return
        self._summary([])
        self.post_message(self.Submitted(self, result))

    def cancel(self) -> None:
        self.post_message(self.Cancelled(self))

    def _editor_for(self, path: Path) -> Editor | None:
        """The editor of the longest prefix of ``path`` that's on screen."""
        for end in range(len(path), 0, -1):
            editor = self._editors.get(path[:end])
            if editor is not None and editor.is_attached:
                return editor
        return None

    def _summary(self, messages: list[str]) -> None:
        summary = self.query_one("#pa-summary", Static)
        summary.update("\n".join(messages))
        summary.set_class(not messages, "-empty")

Cancelled

Bases: Message

The form was closed without a result.

Source code in src/promptantic/textual/view.py
class Cancelled(Message):
    """The form was closed without a result."""

    def __init__(self, view: FormView) -> None:
        super().__init__()
        self.view = view

Submitted

Bases: Message

The form validated; result is the dict or model instance.

Source code in src/promptantic/textual/view.py
class Submitted(Message):
    """The form validated; ``result`` is the dict or model instance."""

    def __init__(self, view: FormView, result: Any) -> None:
        super().__init__()
        self.view = view
        self.result = result

focus_first

focus_first() -> None

Focus the first input, so typing goes straight into the form.

Source code in src/promptantic/textual/view.py
def focus_first(self) -> None:
    """Focus the first input, so typing goes straight into the form."""
    for widget in self.query_one("#pa-fields").query("*"):
        if widget.focusable:
            widget.focus()
            return

submit

submit() -> None

Validate; post :class:Submitted, or show the problems at their fields.

Source code in src/promptantic/textual/view.py
def submit(self) -> None:
    """Validate; post :class:`Submitted`, or show the problems at their fields."""
    for editor in self._editors.values():
        if editor.is_attached:
            editor.show_errors([])
    try:
        value = self.value()
    except FieldError as exc:
        self._summary([str(exc)])
        return
    try:
        result = self.target.validate(value)
    except FormValidationError as exc:
        unplaced: list[str] = []
        for issue in exc.issues:
            if editor := self._editor_for(issue.path):
                editor.show_errors([issue.message])
            else:
                unplaced.append(issue.message)
        self._summary(unplaced or ["Please fix the marked fields"])
        return
    self._summary([])
    self.post_message(self.Submitted(self, result))

value

value() -> Any

The value entered so far, unvalidated.

Raises:

Type Description
FieldError

Some input can't become a value.

Source code in src/promptantic/textual/view.py
def value(self) -> Any:
    """The value entered so far, unvalidated.

    Raises:
        FieldError: Some input can't become a value.
    """
    root = self.query_one("#pa-fields").query_children(Editor).first()
    value = root.get_value()
    return {} if value is UNSET else value

fill_inline async

fill_inline(
    target: FormTarget[Any] | type[Any] | Mapping[str, Any],
    *,
    title: str | None = None,
    initial: Mapping[str, Any] | None = None,
) -> Any

Show the form below the prompt and return the validated result.

Raises:

Type Description
FormCancelledError

The user cancelled.

Source code in src/promptantic/textual/view.py
async def fill_inline(
    target: FormTarget[Any] | type[Any] | Mapping[str, Any],
    *,
    title: str | None = None,
    initial: Mapping[str, Any] | None = None,
) -> Any:
    """Show the form below the prompt and return the validated result.

    Raises:
        FormCancelledError: The user cancelled.
    """
    app = FormApp(_as_target(target), title=title, initial=initial)
    result = await app.run_async(inline=True)
    if app.cancelled:
        raise FormCancelledError
    return result

make_editor

make_editor(node: FormNode, path: Path, initial: Any, register: Registry) -> Editor

The editor for node (initial: its starting value, or :data:UNSET).

Source code in src/promptantic/textual/editors.py
def make_editor(node: FormNode, path: Path, initial: Any, register: Registry) -> Editor:  # noqa: PLR0911
    """The editor for ``node`` (``initial``: its starting value, or :data:`UNSET`)."""
    if initial is UNSET:
        initial = node.meta.default
    match node:
        case StringNode() | NumberNode() | AnyNode():
            return TextEditor(node, path, initial, register)
        case BooleanNode():
            return BooleanEditor(node, path, initial, register)
        case ChoiceNode():
            return ChoiceEditor(node, path, initial, register)
        case NullNode():
            return NullEditor(node, path, initial, register)
        case ArrayNode() if node.multi_choice:
            return MultiChoiceEditor(node, path, initial, register)
        case ArrayNode() | TupleNode():
            return ListEditor(node, path, initial, register)
        case ObjectNode() if node.is_map:
            return MapEditor(node, path, initial, register)
        case ObjectNode():
            return ObjectEditor(node, path, initial, register)
        case UnionNode():
            return UnionEditor(node, path, initial, register)