Skip to content

MapEditor

Base classes

Name Children Inherits
Editor
promptantic.textual.editors
Base of all editors: a node, its path in the value, and an error line.

⋔ Inheritance diagram

graph TD
  2025618216["editors.MapEditor"]
  2997256436["editors.Editor"]
  4188532303["widget.Widget"]
  3946681048["dom.DOMNode"]
  53685856["message_pump.MessagePump"]
  2751680898["builtins.object"]
  2997256436 --> 2025618216
  4188532303 --> 2997256436
  3946681048 --> 4188532303
  53685856 --> 3946681048
  2751680898 --> 53685856

🛈 DocStrings

Bases: Editor

Free keys with values of one kind (dict[str, X]).

Source code in src/promptantic/textual/editors.py
class MapEditor(Editor):
    """Free keys with values of one kind (``dict[str, X]``)."""

    node: ObjectNode
    DEFAULT_CSS = """
    MapEditor > .pa-rows { height: auto; padding-left: 2; }
    MapEditor .pa-key { width: 20; }
    MapEditor > .pa-add { width: auto; }
    """

    def compose(self) -> ComposeResult:
        with Vertical(classes="pa-rows"):
            if isinstance(self.initial, dict):
                for key, value in self.initial.items():
                    yield self._row(str(key), value)
        yield Button("+ Add", classes="pa-add", compact=True)
        yield self.errors_widget()

    def _row(self, key: str, value: Any) -> _Row:
        value_node = self.node.additional
        assert value_node is not None  # is_map
        editor = make_editor(value_node, (*self.path, key), value, self._register)
        editor.add_class("pa-entry")
        return _Row(
            Input(value=key, placeholder="key", classes="pa-key", compact=True),
            editor,
            Button("✕", classes="pa-remove", compact=True),
        )

    def get_value(self) -> Any | Unset:
        result: dict[str, Any] = {}
        rows = self.query_children(".pa-rows").first(Vertical)
        for row in rows.query_children(_Row):
            key = row.query_children(Input).first().value
            if key:
                value = row.query_children(Editor).first().get_value()
                result[key] = None if value is UNSET else value
        return result

    async def on_button_pressed(self, event: Button.Pressed) -> None:
        event.stop()
        if event.button.has_class("pa-add"):
            await self.query_children(".pa-rows").first(Vertical).mount(self._row("", UNSET))
        elif event.button.has_class("pa-remove") and isinstance(event.button.parent, _Row):
            await event.button.parent.remove()

:fa-brands-github: Show source on GitHub