Skip to content

FormView

Base classes

Name Children Inherits
Widget
textual.widget
A Widget is the base class for Textual widgets.

⋔ Inheritance diagram

graph TD
  2597639567["view.FormView"]
  4188532303["widget.Widget"]
  3946681048["dom.DOMNode"]
  53685856["message_pump.MessagePump"]
  2751680898["builtins.object"]
  4188532303 --> 2597639567
  3946681048 --> 4188532303
  53685856 --> 3946681048
  2751680898 --> 53685856

🛈 DocStrings

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

:fa-brands-github: Show source on GitHub