Introducing a new way to review your PRs.

Read the announcement

petalframework / petal_components

Phoenix + Live View HEEX Components

View on GitHub

24 documents · Updated Sep 2, 2026

docs / hierarchical-data-and-manipulation

Hierarchical data and manipulation

This part of Petal Components gives users clear ways to explore nested records, scan collections, change a view, and set a lasting order. The components keep display state and user actions separate from application data so a LiveView can decide what to fetch, save, or show next.

Data browsing surfaces

The library uses different surfaces for different kinds of collection work. A tree exposes relationships between records, a table exposes fields across records, and a sortable list lets the user change collection order.

Component roles

PetalComponents.Tree is for exploring things with parent-child relationships. PetalComponents.Table is a low-level tabular surface, while the stateful data-table layer adds search, filters, sorting, paging, and column controls around it. PetalComponents.Sortable changes the order of one list or grid through an application event.

User needSurfaceResult owned by the application
Explore nested recordsTreeExpanded branches and optional selected record
Read records by fieldTable or data tableRows and the meaning of each column
Narrow a collectionData-table filters or standalone filter barThe query state and resulting records
Change visible orderSortable list or gridThe saved order after the reorder event

References: lib/…/tree.ex• L1-18 lib/…/table.ex• L1-16 lib/…/data_table.ex• L1-49 lib/…/sortable.ex• L1-14

Hierarchical records

The tree presents nested records as one navigable exploration surface. It supports arbitrary depth, branch expansion, optional single selection, and a custom row body without making the consuming application rebuild the tree semantics.

Tree structure

The tree receives a nested list of node maps. Each node needs a unique id and a visible label; a non-empty children list makes it a branch. Extra node data remains available to the custom item content, so the same hierarchy can show names, roles, icons, or other record details.

Branches can load their children later. A lazy branch remains part of the hierarchy while it waits for the server, which lets the application avoid loading a large subtree until the user opens it.

References: lib/…/tree.ex• L14-42 lib/…/tree.ex• L176-184 lib/…/tree.ex• L76-109

Tree expansion and selection

Expansion can be local to the rendered page or controlled by the server. The local mode is suited to a tree that renders once, while server control keeps open branches stable across LiveView updates and supports lazy loading. In both cases, the tree keeps the same visible and accessibility model.

Selection is optional and single-valued. When enabled, a node click reports its id to the application and gives immediate visual feedback; when selection is not configured, the tree remains an exploration surface without selected-state semantics. A row can expand and select in one click, or expansion can stay on the chevron when the row click already performs another action.

The following flow shows how a tree action becomes either local display state or application-owned state.

flowchart LR
    A[User clicks or focuses a node] --> B{Action}
    B -->|Expand or collapse| C{Expansion model}
    C -->|Local| D[Update visible branch]
    C -->|Server controlled| E[Send branch id]
    E --> F[Application loads or stores branch state]
    F --> G[Render updated tree]
    B -->|Select| H[Update highlight]
    H --> I[Optional selection event]

References: lib/…/tree.ex• L45-109 lib/…/tree.ex• L133-163 assets/…/petal_components.js• L8067-8267 lib/…/tree.ex• L43-109

Tree keyboard model

The tree behaves as one keyboard control rather than a set of unrelated links. A roving tab stop keeps one node in the tab order, and the arrow keys move through visible nodes or change the user's level in the hierarchy.

KeyTree action
Up or DownMove to the previous or next visible node
RightOpen a branch or move to its first child
LeftClose a branch or move to its parent
Home or EndMove to the first or last visible node
Enter or SpaceSelect the focused node when selection is enabled
*Open the focused node's sibling branches

References: lib/…/tree.ex• L94-109 assets/…/petal_components.js• L8174-8266

Tabular collections

Tables organize records by shared fields so users can compare values across rows. The simple table supplies the presentation surface, and the stateful data table adds controls that change which records or columns are visible.

Table presentation

lib/petal_components/table.ex defines the base table surface. Columns render their own cell content from each row, while optional empty, footer, and action content gives the application places for collection status and row work. Density, stripes, sticky headers, and visual variants change how users scan the same records without changing their meaning.

A sortable header reports the chosen column and its direction through an application event or JavaScript command. The table does not reorder the data by itself; the application decides how that sort request changes the source rows.

References: lib/…/table.ex• L6-71 lib/…/table.ex• L83-158 lib/…/table.ex• L8-40

Collection view state

The data-table layer uses one shared state value to describe the requested collection view. Search, filters, sort order, page, and page size belong to query state; selection, column visibility, and column order belong to presentation state. This split lets a URL describe a shareable query while the current user's table layout remains local UI state.

The data source receives the query state and returns the rows for that view. The table then renders the same state beside those rows, which keeps sort indicators, filter controls, range text, and empty messages aligned with the result.

For the full data-table state contract and its paging behavior, see Data tables.

References: lib/…/data_table.ex• L1-49 lib/…/data_table.ex• L243-317 lib/…/state.ex• L1-20 lib/…/state.ex• L123-199

Collection filters

Filters let users describe which records belong in a collection without requiring a separate search screen. The same filter meaning can appear in a column popover or in a filter bar above a table, list, card grid, or other query-driven surface.

Filter vocabulary

The filter state describes user intent rather than a database expression. Text fields can match or compare text, numeric and date fields can use ordered comparisons or ranges, choice fields can select one or many values, and empty-value operators can find blank records.

Filter editors choose a suitable value control for the field. This keeps a date range, a list of choices, and a boolean choice understandable while allowing all of them to use the same state and event meaning.

Field kindUser input
TextText plus a match operator
NumberNumber or inclusive range
DateDate or date range
SelectOne choice plus an operator
Multiple choiceA set of choices
BooleanYes or No

References: lib/…/state.ex• L22-80 lib/…/filter_editor.ex• L16-25 lib/…/filters.ex• L65-81

Filter bar

PetalComponents.Filters is the standalone filter bar. It shows active filters as removable chips and opens a short field-to-operator-to-value flow for a new filter. Because it uses the same state as the data table, a filter added in the bar appears in the table and a filter added in a table column appears as a chip.

The bar supports URL mode for shareable views and event mode for LiveView-owned updates. In either mode, removing one filter or clearing all filters uses the same filter operations as the data table, so the application does not need a second filter grammar.

References: lib/…/filters.ex• L1-45 lib/…/filters.ex• L47-63 lib/…/filters.ex• L187-235 lib/…/filters.ex• L45-102

Filter synchronization

The table and filter bar must point to the same state and the same URL or event path when they are used together. The application then runs one query after each change and renders both controls from the resulting state. This relationship prevents a chip from describing a filter that the table did not apply.

The browser layer supports the parts that need live DOM state, such as filter-panel disclosure, option narrowing, focus return, and URL patching in link mode. The server still owns the accepted fields and the resulting query state.

References: lib/…/filters.ex• L47-63 lib/…/data_table.ex• L281-317 assets/…/petal_components.js• L6687-6751 assets/…/petal_components.js• L6760-6785

Ordered collections

Sortable collections let users change the order of one list or grid through direct manipulation. The component makes the browser movement feel immediate, then reports one ordered move so the application can validate and persist it.

Sortable list and grid

PetalComponents.Sortable renders a single reorderable container. In list mode, movement follows one vertical order; in grid mode, arrow keys follow the live two-dimensional layout. Handle mode limits the drag start area so links, checkboxes, and other row controls remain usable.

Each item has a stable identity. Disabled items cannot be lifted, but they can move when a nearby item is repositioned. A stream-backed list can use its DOM id for rendering while the event still carries the record's stable id.

References: lib/…/sortable.ex• L16-57 lib/…/sortable.ex• L165-204 lib/…/sortable.ex• L18-56

Reorder lifecycle

The browser reorders the visible items first. On drop, on_reorder receives the item id and its old and new positions. The application should treat the id as the stable identity, validate the requested destination against current data, save the order, and render the accepted order again.

The same lifecycle works with keyboard input. Space starts and ends a move, arrow keys change its position, Escape cancels it, and a live region announces the transition. A pointer drag uses a long press on touch, while a tap or scroll remains a normal page gesture.

sequenceDiagram
    participant U as User
    participant S as Sortable surface
    participant L as LiveView
    participant A as Application data
    U->>S: Drag or lift an item
    S->>S: Move visible item optimistically
    U->>S: Drop or cancel
    S-->>L: id, from, to on accepted drop
    L->>A: Validate and persist order
    A-->>L: Accepted or rejected order
    L-->>S: Render the server order

For a reorderable data table's columns, use the data-table column layout controls instead. They change presentation order and do not change the order of records.

References: lib/…/sortable.ex• L45-109 lib/…/sortable.ex• L117-149 assets/…/petal_components.js• L6360-6394 assets/…/petal_components.js• L6551-6676

Interaction boundaries

These components provide the visual interaction and event shape, but the consuming application remains the authority for data. The boundary is useful because a visible move or filter change can be immediate without making an unvalidated browser state permanent.

State ownership

Use query state for changes that define which records belong in the view. Use presentation state for changes that only affect how the current view looks. Use application data state for changes that alter the records themselves, such as saving a new sortable order.

State typeExamplesTypical owner
Query stateSearch, filters, sort, pageURL or LiveView event handler
Presentation stateSelected rows, hidden columns, column order, open tree branchesLiveView assigns or UI state store
Data stateSaved record order, loaded lazy childrenDomain or application data layer

References: lib/…/data_table.ex• L33-49 lib/…/data_table.ex• L187-207 lib/…/tree.ex• L45-62 lib/…/sortable.ex• L59-83

URL mode makes table and filter changes restorable and shareable. Event mode sends operation-shaped payloads to a LiveView. Sortable changes always need an application event because the new order must be checked and stored; tree selection and server-controlled expansion also report ids when the application owns those states.

The browser hooks add focus, keyboard, disclosure, and optimistic movement behavior. They do not replace the server's field allow-list, query, or persistence rules.

References: lib/…/data_table.ex• L7-31 lib/…/filters.ex• L12-45 lib/…/sortable.ex• L5-14 lib/…/tree.ex• L58-87 assets/…/petal_components.js• L6140-6157 assets/…/petal_components.js• L6679-6687

Change checklist

When these files or sections are changed, remember to consider these:

  • When a tree node changes from a leaf to a branch or becomes lazy, keep its expansion event and child-loading behavior aligned with the new node shape.
  • When table fields gain or lose sort or filter support, update the state field allow-list, the query source, and the matching column or filter declaration together.
  • When a filter value changes shape, keep the field editor, URL form, event payload, state parser, and query engine compatible.
  • When a table or filter bar changes its URL or event mode, keep both surfaces on the same state and operation contract.
  • When a sortable list uses streams, keep the stream DOM id separate from the stable record id used in reorder persistence.
  • When sortable or tree markup changes, keep the matching browser hook selectors and accessibility state in sync.

Important failure modes

TriggerConsequenceGuard
A tree uses client-side expansion while LiveView patches the treeOpen branches reset to their initial stateUse server-controlled expansion and handle the branch event
A lazy tree branch has no server-controlled expansion pathThe branch cannot load its children when openedPass the expanded state and expansion event together
A sortable handler trusts the old index after another reorderThe wrong record can moveUse the stable item id as the primary identity and treat from as a check
A rejected stream reorder sends no stream updateThe browser keeps an order that differs from the serverRestream the accepted server order or reset the stream on rejection
A table and filter bar use different state or event pathsVisible filters and returned rows disagreeShare one state value and one query operation contract
A sort or filter field is not in the state allow-listThe control appears to work but the requested change is ignoredKeep declared fields and state parsing fields aligned
A data-table hook is not registeredLink-mode controls, filter menus, or DOM-only state do not workRegister the bundled PetalDataTable hook in the consuming LiveView

Key files

FileWhy to read it
lib/petal_components/tree.exDefines the nested record model, expansion choices, selection, and tree keyboard contract
assets/…/petal_components.jsDefines browser behavior for tree focus and keyboard movement, sortable interaction, and data-table controls
lib/petal_components/table.exDefines the base table presentation and sortable header contract
lib/petal_components/data_table.exDefines the stateful table surface, filters, column layout, and interaction modes
lib/petal_components/data_table/state.exDefines query state, filter meaning, URL decoding, and event operations
lib/petal_components/data_table/filter_editor.exDefines the shared value shapes used by table and standalone filter editors
lib/petal_components/filters.exDefines the standalone filter bar and its composition with a data table
lib/petal_components/sortable.exDefines reorder events, list and grid behavior, disabled items, and stream expectations
lib/petal_components/showcase/tree.exShows nested, selected, lazy, custom-row, and empty tree uses
lib/petal_components/showcase/sortable.exShows list, handle, grid, and disabled reorder uses
Data presentation and browsingPlaces these collection surfaces in the wider data presentation group
Data tablesGives the detailed data-table state and rendering guide
Charts, paging, and progressCovers the related paging and progress surfaces