Theme
Version
GitHub PyPI Discord
On this page

Tree

Use CTree for compact hierarchical application data such as files or object structures. Use disclosure navigation for ordinary site links.

Tree at a glance

Tree at a glance
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class TreeAtAGlance(Component):
    template = """
      <c-CTree label="Project files" c-expanded="['src']" c-selected="['app']" variant="soft">
        <c-CTreeItem value="src" label="src">
          <c-CTreeItem value="app" label="app.py" />
          <c-CTreeItem value="styles" label="styles.css" />
        </c-CTreeItem>
        <c-CTreeItem value="tests" label="tests" />
        <c-CTreeItem value="readme" label="README.md" />
      </c-CTree>
    """


preview = TreeAtAGlance()
preview  # noqa: B018

Control expansion

Control expanded branches
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class ControlledExpansion(Component):
    template = """
      <section x-data="{ expanded: ['docs'] }">
        <c-CTree
          label="Knowledge base"
          $c-props="{ expanded, onExpandedChange: (next) => expanded = next }"
        >
          <c-CTreeItem value="docs" label="Documentation">
            <c-CTreeItem value="guides" label="Guides" />
            <c-CTreeItem value="reference" label="Reference" />
          </c-CTreeItem>
          <c-CTreeItem value="examples" label="Examples" />
        </c-CTree>
        <output x-text="expanded.join(', ') || 'All branches collapsed'"></output>
      </section>
    """


preview = ControlledExpansion()
preview  # noqa: B018

Select one Item

Select one Item
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class TreeSingleSelection(Component):
    template = """
      <section x-data="{ selected: ['mercury'] }">
        <c-CTree
          label="Planets"
          c-selected="['mercury']"
          $c-props="{ selected, onSelectionChange: (next) => selected = next }"
        >
          <c-CTreeItem value="mercury" label="Mercury" />
          <c-CTreeItem value="venus" label="Venus" />
          <c-CTreeItem value="earth" label="Earth" />
        </c-CTree>
        <output x-text="selected[0] ?? 'No selection'"></output>
      </section>
    """


preview = TreeSingleSelection()
preview  # noqa: B018

Select multiple Items

Select multiple Items
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class TreeMultipleSelection(Component):
    template = """
      <section x-data="{ selected: ['alder'] }">
        <c-CTree
          label="Specimens"
          selection_mode="multiple"
          c-selected="['alder']"
          $c-props="{ selected, onSelectionChange: (next) => selected = next }"
        >
          <c-CTreeItem value="alder" label="Alder" />
          <c-CTreeItem value="birch" label="Birch" />
          <c-CTreeItem value="cedar" label="Cedar" />
        </c-CTree>
        <output x-text="selected.join(', ')"></output>
      </section>
    """


preview = TreeMultipleSelection()
preview  # noqa: B018

Down and Up move through visible Items. Right expands or enters a branch; Left collapses or returns to its parent. Home, End, and buffered typeahead follow the ARIA Tree pattern.

Navigate a Tree
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class KeyboardTree(Component):
    template = """
      <c-CTree label="Keyboard explorer" c-expanded="['animals']" variant="outline">
        <c-CTreeItem value="animals" label="Animals">
          <c-CTreeItem value="badger" label="Badger" />
          <c-CTreeItem value="beaver" label="Beaver" />
        </c-CTreeItem>
        <c-CTreeItem value="minerals" label="Minerals" />
        <c-CTreeItem value="plants" label="Plants" />
      </c-CTree>
    """


preview = KeyboardTree()
preview  # noqa: B018

Disable Items

Disable Tree Items
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class TreeDisabledItems(Component):
    template = """
      <c-CTree label="Deployment targets" c-expanded="['regions']">
        <c-CTreeItem value="regions" label="Regions">
          <c-CTreeItem value="eu" label="Europe" />
          <c-CTreeItem value="us" label="United States" disabled />
        </c-CTreeItem>
        <c-CTreeItem value="archive" label="Archived targets" disabled />
      </c-CTree>
    """


preview = TreeDisabledItems()
preview  # noqa: B018

Customize Tree

Customize Tree
Show code
import citry_ui
from citry import Component, citry

citry.register_library(citry_ui)


class CustomizedTree(Component):
    template = """
      <div class="brand-tree">
        <style>
          .brand-tree {
            --cui-tree-indent: 1.75rem;
            --cui-tree-radius: 1rem;
            --cui-tree-selected-background: rebeccapurple;
            --cui-tree-selected-color: white;
          }
        </style>
        <c-CTree label="Branded catalog" c-selected="['ferns']" variant="outline" size="lg">
          <c-CTreeItem value="mosses" label="Mosses" />
          <c-CTreeItem value="ferns" label="Ferns" />
          <c-CTreeItem value="orchids" label="Orchids" />
        </c-CTree>
      </div>
    """


preview = CustomizedTree()
preview  # noqa: B018

Accessibility and behavior

The named root uses role="tree"; Items use role="treeitem" and nested children use role="group". One visible Item is in the Tab order. Expansion, selection, focus, and application action are separate states. Space selects, Enter selects and invokes onAction, and double-click invokes the action.

API reference

Inputs

CTree server inputs

Server inputs are passed in a template through <c-CTree ... /> or in Python through CTree(...).

InputTypeDefaultEffect
labelstrrequiredNames the Tree widget.
expandedSequence[str]()Sets initially expanded branch values.
selectedSequence[str]()Sets initially selected Item values.
selection_mode"none" | "single" | "multiple" (CTreeSelectionMode)"single"Selects no-selection single-selection or independent multi-selection behavior.
disabledboolFalseDisables expansion selection and action throughout the Tree.
variant"plain" | "soft" | "outline" (CTreeVariant)"plain"Selects surface treatment.
size"sm" | "md" | "lg" (CTreeSize)"md"Selects row and indentation geometry.
class_CClassValue | None (CClassValue)NoneAdds root classes.
styleCStyleValue | None (CStyleValue)NoneAdds root inline styles.
attrsMapping[str, object] | NoneNoneAdds trusted root attributes without replacing owned semantics focus state structure or runtime.

CTree client inputs

Client inputs are passed in the browser through the $c-props="{ ... }" attribute on <c-CTree />.

InputTypeOmitted behaviorEffect
expandedstring[] | nullUses uncontrolled committed expansion.Controls expanded branches while supplied; null releases control.
selectedstring[] | nullUses uncontrolled committed selection.Controls selected Items while supplied; null releases control.
selectionMode"none" | "single" | "multiple" (CTreeSelectionMode)Uses the server value.Reactively changes selection behavior.
disabledboolUses the server value.Reactively disables Tree operations.
variant"plain" | "soft" | "outline" (CTreeVariant)Uses the server value.Reactively changes presentation.
size"sm" | "md" | "lg" (CTreeSize)Uses the server value.Reactively changes geometry.
onExpandedChange((expanded: string[], detail: CTreeExpandedChangeDetail) => void) | undefinedNo component callback runs.Receives branch expansion requests.
onSelectionChange((selected: string[], detail: CTreeSelectionChangeDetail) => void) | undefinedNo component callback runs.Receives Item selection requests.
onAction((value: string, detail: CTreeActionDetail) => void) | undefinedNo component callback runs.Receives enabled Enter or double-click actions.

CTreeItem server inputs

Server inputs are passed in a template through <c-CTreeItem ... /> or in Python through CTreeItem(...).

InputTypeDefaultEffect
valuestrrequiredSupplies stable unique Item identity.
labelstrrequiredSupplies visible text accessible naming and typeahead text.
disabledboolFalseKeeps the Item focusable by Tree navigation but prevents operations.
class_CClassValue | None (CClassValue)NoneAdds classes to the concrete Item.
styleCStyleValue | None (CStyleValue)NoneAdds inline styles to the concrete Item.
attrsMapping[str, object] | NoneNoneAdds trusted Item attributes without replacing owned semantics identity focus state or children.

Slots

Slots are passed as nested content or <c-fill> tags in a template, or through the slots={...} argument in Python.

CTree slots

SlotRequiredDataFallback
defaultyes{} (CTreeDefaultSlotData)None. Requires one or more direct CTreeItem declarations.

CTreeItem slots

SlotRequiredDataFallback
defaultno{parent_value, level} (CTreeItemDefaultSlotData)Omitted for a leaf; otherwise accepts child CTreeItem declarations only.

Events

Component events are callback inputs supplied through $c-props. Native browser events remain available through Alpine @... attributes.

CTree events

EventSignatureTrigger and timingDetailControlled and cancellation behavior
onExpandedChange(expanded: string[], detail: CTreeExpandedChangeDetail) => void (CTreeExpandedChangeDetail)Enabled pointer-indicator or keyboard branch request.{value, expanded, previousExpanded, controlled, source, item, sourceEvent} (CTreeExpandedChangeDetail)Commits immediately when uncontrolled and waits when controlled.
onSelectionChange(selected: string[], detail: CTreeSelectionChangeDetail) => void (CTreeSelectionChangeDetail)Enabled row click Space or Enter in a selectable mode.{value, selected, previousSelected, controlled, source, item, sourceEvent} (CTreeSelectionChangeDetail)Applies single or independent multiple selection policy.
onAction(value: string, detail: CTreeActionDetail) => void (CTreeActionDetail)Enabled Enter or double-click.{value, item, sourceEvent} (CTreeActionDetail)Notifies application action without navigation or form submission.

Methods

-

CSS

CSS variables to theme the components. Set them on an ancestor or the component itself.

CTree CSS variables

Apply these variables to CTree or one of its ancestors.

VariableTypePurposeDefault
--cui-tree-indentlengthLogical child indentation.sm 1rem; md 1.25rem; lg 1.5rem
--cui-tree-row-gaplengthGap between sibling rows.0.125rem
--cui-tree-row-paddinglengthRow block and inline padding.size-derived
--cui-tree-radiuslengthRoot and row corner radius.0.5rem
--cui-tree-backgroundcolorRoot background.plain and outline transparent; soft subtle CanvasText mix
--cui-tree-border-colorcolorOutline border.light #d0d5dd; dark #535862
--cui-tree-hover-backgroundcolorEnabled row hover background.7% CanvasText mix
--cui-tree-selected-backgroundcolorSelected row background.light #dbeafe; dark #1e3a5f
--cui-tree-selected-colorcolorSelected row foreground.light #1849a9; dark #d1e9ff
--cui-tree-muted-colorcolorDisabled Item foreground.light #667085; dark #a4a7ae
--cui-tree-focus-colorcolorRoving focus outline.Highlight

Attributes

HTML attributes defined on the components that you can refer to for CSS, inspection, and testing. Read-only.

CTree attributes

AttributeElementTypeMeaning
roleRoot or Item/group divtree | treeitem | groupOwns Tree hierarchy semantics.
aria-labelRoot or Item divstringNames the Tree and each Item.
tabindexItem div0 | -1Implements one roving visible Tab stop.
aria-disabledItem divtrue | falseReflects effective Item unavailability.
aria-expandedBranch Item divtrue | falseReflects branch visibility; omitted on leaves.
aria-selectedSelectable Item divtrue | falseReflects selection; omitted in none mode.
data-selection-modeRoot divnone | single | multipleMirrors effective selection model.
data-disabledRoot or Item divpresent-or-absentReflects effective unavailability.
data-variantRoot divplain | soft | outlineMirrors effective presentation.
data-sizeRoot divsm | md | lgMirrors effective geometry.
data-valueItem divstringExposes canonical Item identity.
data-levelItem divpositive-integer-stringExposes settled hierarchy depth.
data-expandedBranch Item divpresent-or-absentPresent while expanded.
data-selectedItem divpresent-or-absentPresent while selected.
hiddenChild group divpresent-or-absentRemoves collapsed descendants from rendering.
inertChild group divpresent-or-absentGuards collapsed descendants from interaction.

Selectors

Selectors for the DOM nodes in the components that you can use for CSS, inspection, and testing.

CTree selectors

SelectorElementPurpose
[data-citry-ui-part="tree"]Root divStable root and attrs destination.
[data-citry-ui-part="item"]Tree Item divStable Item attrs and state surface.
[data-citry-ui-part="row"]Row spanStable visible Item surface.
[data-citry-ui-part="indicator"]Decorative spanPointer expansion target and branch indicator.
[data-citry-ui-part="label"]Label spanStable visible and typeahead text.
[data-citry-ui-part="group"]Child group divStable nested collection and visibility surface.

Interfaces

Aliases and data shapes referenced above.

Input type aliases

InterfaceDefinition
CClassValuestr | Mapping[str, bool] | Sequence[CClassValue]
CStyleValuestr | Mapping[str, object] | Sequence[CStyleValue]
CTreeSelectionModeLiteral["none", "single", "multiple"]
CTreeVariantLiteral["plain", "soft", "outline"]
CTreeSizeLiteral["sm", "md", "lg"]
CTreeChangeSourceLiteral["pointer", "keyboard", "structure"]

CTreeDefaultSlotData

Empty dataclass: {}.

CTreeItemDefaultSlotData

FieldTypeDefaultMeaning
parent_valuestr-Canonical parent Item identity.
levelint-One-based child hierarchy level.

CTreeExpandedChangeDetail

FieldTypeDefaultMeaning
valuestr-Changed branch identity.
expandedbool-Requested branch state.
previousExpandedstring[]-Prior vector.
controlledbool-Whether client expanded controls state.
source"pointer" | "keyboard" | "structure" (CTreeChangeSource)-Request source.
itemHTMLElement-Changed Item.
sourceEventEvent-Native source event.

CTreeSelectionChangeDetail

FieldTypeDefaultMeaning
valuestr-Changed Item identity.
selectedbool-Requested selection state.
previousSelectedstring[]-Prior vector.
controlledbool-Whether client selected controls state.
source"pointer" | "keyboard" | "structure" (CTreeChangeSource)-Request source.
itemHTMLElement-Changed Item.
sourceEventEvent-Native source event.

CTreeActionDetail

FieldTypeDefaultMeaning
valuestr-Activated Item identity.
itemHTMLElement-Activated Item.
sourceEventEvent-Native Enter or double-click event.

Translation keys

-