Skip to content

UnionEditor

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

🛈 DocStrings

Bases: Editor

Pick the kind first, then fill that kind's editor.

Source code in src/promptantic/textual/editors.py
class UnionEditor(Editor):
    """Pick the kind first, then fill that kind's editor."""

    node: UnionNode
    DEFAULT_CSS = "UnionEditor > .pa-variant { height: auto; padding-left: 2; margin: 1 0 0 0; }"

    def compose(self) -> ComposeResult:
        variants = self.node.variants
        index = self._initial_variant()
        yield Select(
            [(variant.label, i) for i, variant in enumerate(variants)],
            value=index,
            allow_blank=self.node.nullable,
            prompt="(none)",
            compact=True,
        )
        with Vertical(classes="pa-variant"):
            if isinstance(index, int):
                yield self._variant_editor(index, self.initial)
        yield self.errors_widget()

    def _initial_variant(self) -> int | Any:
        """The variant the initial value belongs to (by discriminator), else the first."""
        variants = self.node.variants
        if self.initial is None and self.node.nullable:
            return Select.NULL
        if self.node.discriminator and isinstance(self.initial, dict):
            tag = self.initial.get(self.node.discriminator)
            for i, variant in enumerate(variants):
                if variant.label == tag:
                    return i
        return 0 if variants else Select.NULL

    def get_value(self) -> Any | Unset:
        holder = self.query_children(".pa-variant").first(Vertical)
        editors = list(holder.query_children(Editor))
        if not editors:
            return None if self.node.nullable else UNSET
        return editors[0].get_value()

    async def on_select_changed(self, event: Select.Changed) -> None:
        if event.select.parent is not self:
            return
        event.stop()
        holder = self.query_children(".pa-variant").first(Vertical)
        await holder.remove_children()
        if isinstance(event.value, int):
            await holder.mount(self._variant_editor(event.value, UNSET))

    def _variant_editor(self, index: int, initial: Any) -> Editor:
        editor = make_editor(self.node.variants[index].node, self.path, initial, self._register)
        if isinstance(editor, ObjectEditor):
            editor.fold = False  # the select above already names it
        return editor

:fa-brands-github: Show source on GitHub