Skip to content

ObjectEditor

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
  1007918288["editors.ObjectEditor"]
  2997256436["editors.Editor"]
  4188532303["widget.Widget"]
  3946681048["dom.DOMNode"]
  53685856["message_pump.MessagePump"]
  2751680898["builtins.object"]
  2997256436 --> 1007918288
  4188532303 --> 2997256436
  3946681048 --> 4188532303
  53685856 --> 3946681048
  2751680898 --> 53685856

🛈 DocStrings

Bases: Editor

Named fields; nested objects fold (the outermost one doesn't).

Fields with only one possible value (const, e.g. a union's discriminator) aren't shown; their value is still part of the result. An object that may be null starts with a switch: off means null, on shows its fields.

Source code in src/promptantic/textual/editors.py
class ObjectEditor(Editor):
    """Named fields; nested objects fold (the outermost one doesn't).

    Fields with only one possible value (``const``, e.g. a union's discriminator) aren't
    shown; their value is still part of the result. An object that may be ``null``
    starts with a switch: off means ``null``, on shows its fields.
    """

    node: ObjectNode
    fold = True
    """Show as a folding section (off at the root and for a union's chosen variant)."""
    heading: str | None = None
    """Title of the folding section (the field's label, set by the containing object)."""

    DEFAULT_CSS = """
    ObjectEditor .pa-field { height: auto; margin: 0 0 1 0; }
    ObjectEditor .pa-label { text-style: bold; }
    ObjectEditor .pa-help { color: $text-muted; }
    ObjectEditor Collapsible { padding-left: 1; }
    ObjectEditor > .pa-toggle { height: auto; }
    ObjectEditor .pa-fields { height: auto; }
    ObjectEditor .pa-fields.-off { display: none; }
    """

    def compose(self) -> ComposeResult:
        self._editors: dict[str, Editor] = {}
        enabled = not self.node.nullable or isinstance(self.initial, dict)
        if self.node.nullable:
            with Horizontal(classes="pa-toggle"):
                yield Switch(value=enabled, classes="pa-enabled")
                yield Label(self.heading or self.node.meta.title or "Fill in")
        fields = Vertical(*self._fields(), classes="pa-fields")
        fields.set_class(not enabled, "-off")
        if self.path and self.fold and not self.node.nullable:
            with Collapsible(title=self.heading or self.node.meta.title or "", collapsed=False):
                yield fields
        else:
            yield fields
        yield self.errors_widget()

    def _fields(self) -> list[Widget]:
        initial = self.initial if isinstance(self.initial, dict) else {}
        widgets: list[Widget] = []
        for prop in self.node.properties:
            if prop.node.meta.read_only:
                continue
            editor = make_editor(
                prop.node, (*self.path, prop.name), initial.get(prop.name, UNSET), self._register
            )
            self._editors[prop.name] = editor
            if isinstance(prop.node, ChoiceNode) and prop.node.fixed:
                editor.display = False
                widgets.append(editor)
                continue
            label = f"{prop.label}{' *' if prop.required else ''}"
            parts: list[Widget] = []
            if isinstance(editor, ObjectEditor):
                editor.heading = label  # its section (or switch) carries the label
            else:
                parts.append(Label(label, classes="pa-label"))
            if description := prop.node.meta.description:
                parts.append(Static(description, classes="pa-help"))
            parts.append(editor)
            widgets.append(Vertical(*parts, classes="pa-field"))
        return widgets

    def _enabled(self) -> bool:
        if not self.node.nullable:
            return True
        return self.query_children(".pa-toggle").first().query_children(Switch).first().value

    def get_value(self) -> Any | Unset:
        if not self._enabled():
            return None
        result: dict[str, Any] = {}
        if self.node.additional is not None and isinstance(self.initial, dict):
            # free keys allowed: keep the extra starting values (no editor for them)
            declared = {prop.name for prop in self.node.properties}
            result.update({k: v for k, v in self.initial.items() if k not in declared})
        for name, editor in self._editors.items():
            value = editor.get_value()
            if value is not UNSET:
                result[name] = value
        return result

    def on_switch_changed(self, event: Switch.Changed) -> None:
        if not event.switch.has_class("pa-enabled"):
            return
        event.stop()
        self.query_children(".pa-fields").first().set_class(not event.value, "-off")

fold class-attribute instance-attribute

fold = True

Show as a folding section (off at the root and for a union's chosen variant).

heading class-attribute instance-attribute

heading: str | None = None

Title of the folding section (the field's label, set by the containing object).

:fa-brands-github: Show source on GitHub