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 / browser-hooks

Browser hooks

Browser hooks are the client-side behavior layer for Petal Components. They attach to LiveView-rendered elements and add the interaction, focus, timing, and DOM state that a server render cannot provide on its own. The bundle works with the broader component runtime and asset model and uses the same visual state tokens described in styling and icon assets.

Hook bundle

LiveView lifecycle

The hook bundle is a set of named Phoenix LiveView hooks that an application registers with its LiveSocket. A component marks an element with phx-hook and data attributes. LiveView then gives the matching hook control of browser-only behavior while the server remains the source of rendered content and form state.

The bundle also includes small page-level behaviors that do not need a hook per component. For example, one shared accordion listener handles accordion events for all accordions on the page, including accordions reached through LiveView navigation.

The main relationship is:

flowchart LR
    S[LiveView render] --> M[Hook mount]
    M --> B[Browser interaction]
    B --> D[DOM state and visual feedback]
    B --> E[LiveView event or form change]
    E --> S
    S --> U[Hook update]
    U --> D

Hooks use the LiveView lifecycle to attach listeners when an element mounts, re-apply client state after a server patch, and release timers or observers when the element is removed. This keeps browser state useful without making the server render duplicate every transient detail.

References: assets/…/petal_components.js• L1-8 assets/…/petal_components.js• L15-51 assets/…/petal_components.js• L1489-1597 assets/…/petal_components.js• L9907-9950

Hook families

The bundle groups behavior around common component needs rather than around one shared page flow. The following families cover the main product capabilities:

FamilyUser-facing purposeRepresentative hooks
Chat and feedbackStream content, submit messages, copy text, and preserve scroll positionPetalChatStream, PetalChatComposer, PetalChatScroll, PetalCopy, PetalCodeCopy
Form controlsReveal passwords, copy or clear values, manage ranges, enter numbers, and render one-time codesPetalPasswordToggle, PetalCopyInput, PetalClearableInput, PetalRangeFill, PetalDualRangeSlider, PetalSlider, PetalNumberField, PetalInputOTP
Choice and search controlsFilter choices, manage keyboard selection, keep a native form value, and support remote resultsPetalCommand, PetalComboBox, PetalCalendar, PetalDatePicker
Overlays and menusPosition popovers, dismiss menus, manage dialogs, drawers, and context actionsPetalPopover, PetalDropdown, PetalCommandDialog, PetalAlertDialog, PetalDrawer, PetalContextMenu, PetalNavMenu, PetalDataTable
Layout and navigationReorder content, resize panels, move through trees, and mark the section in viewPetalSortable, PetalResizable, PetalTree, PetalScrollspy, accordion behavior
Display and motionAnimate numbers or text, localize time, show charts, carousels, aurora effects, and confettiPetalNumberTicker, PetalLocalTime, PetalChart, PetalCarousel, PetalAurora, PetalConfetti, PetalWordRotate, PetalTypingEffect, PetalSpotlight
Global feedback and preferencesShow toasts and synchronize the color schemePetalToast, PetalColorScheme

This grouping is a mental model for choosing the right hook. It does not change the registration contract: each component still needs the named hook that its rendered markup requests.

References: assets/…/petal_components.js• L15-1935 assets/…/petal_components.js• L1971-2991 assets/…/petal_components.js• L2996-4124 assets/…/petal_components.js• L4144-5860 assets/…/petal_components.js• L6106-9003 assets/…/petal_components.js• L9044-9950

Interaction behavior

Input and selection behavior

Input hooks turn simple server-rendered controls into usable browser controls while keeping form submission meaningful. They place the caret where the user expects it, update visible affordances such as clear buttons and range fills, and send native input or change events when a value changes.

The command palette and combo box use the same broad interaction model: text narrows the visible choices, keyboard movement sets a highlighted choice, and Enter commits that choice. The combo box keeps a real select as the form value. This lets LiveView forms and validation continue to receive a normal control value even though the visible picker is richer than a native select.

The chat composer follows the same rule for text entry. Enter submits a non-empty message, while Shift+Enter keeps text entry in the field. The hook also grows the field to fit short messages, forwards pasted files to the LiveView upload control, and preserves focus when the server asks the client to replace the draft.

Number fields, one-time-code fields, calendars, and date pickers add browser-side editing to values that still have a normal form or LiveView path. They keep typed values usable during partial input, move focus through dates or code slots, and update the visible state when the server changes the rendered control.

References: assets/…/petal_components.js• L53-149 assets/…/petal_components.js• L255-475 assets/…/petal_components.js• L1585-1935 assets/…/petal_components.js• L2194-2358 assets/…/petal_components.js• L4629-5860 assets/…/petal_components.js• L9044-9891 lib/…/input.ex• L140-302 lib/…/command.ex• L55-210 lib/…/combo_box.ex• L260-300

Overlay and menu behavior

Overlay hooks make menus and dialogs usable across viewport sizes and input types. They open or close panels, keep a panel near its trigger, choose another side when the first side has no room, and close on the expected Escape, outside-press, or focus change.

The hooks preserve the distinction between browser-owned state and server-owned markup. An open panel, active highlight, or focused control may need to survive a LiveView patch even when the server sends fresh rows or attributes. The hook restores that transient state after the patch and lets the server continue to own the durable content.

Dialogs, drawers, context menus, and command palettes also manage the page behind the overlay. Opening a modal command palette or alert dialog moves focus into the intended action area and prevents background scrolling. A drawer can follow a touch drag before it settles or closes, while a context menu opens at the requested pointer or keyboard location. Closing these surfaces releases their temporary state and returns focus to the surrounding control when possible.

References: assets/…/petal_components.js• L1971-2188 assets/…/petal_components.js• L2194-2742 assets/…/petal_components.js• L2735-2767 assets/…/petal_components.js• L2776-2991 assets/…/petal_components.js• L6687-7176 assets/…/petal_components.js• L7747-8668 lib/…/popover.ex• L150-185 lib/…/command.ex• L110-205

Conversation and feedback behavior

Chat and toast hooks connect server events to immediate browser feedback. Chat streams append or replace content in a protected message area and keep a reader at the live edge only when that reader was already following the conversation. Toasts receive LiveView events or browser events then present temporary feedback with a timer, progress state, hover pause, and swipe dismissal.

These hooks also define important ownership boundaries. The chat stream owns the changing message display during a stream. The toast group owns its visible stack. Server updates can still change the surrounding component, but they must not unexpectedly erase a client-managed interaction in progress.

References: assets/…/petal_components.js• L10-149 assets/…/petal_components.js• L179-253 assets/…/petal_components.js• L4126-4620 lib/…/chat.ex• L70-190 lib/…/chat.ex• L410-445 lib/…/toast.ex• L1-150

Timing and DOM state

Timed display behavior

Timing hooks add effects that depend on browser time or visibility. A number ticker starts when it enters view and animates toward the value supplied by LiveView. Local time formats a server-provided instant in the browser's locale and refreshes relative labels as they age. Text effects rotate, type, or erase content without requiring a server round trip for each visual step.

LiveView remains responsible for the target data. When a patch changes that data, the hook treats the new render as a new target or source and updates the visual effect. When a tab becomes visible again, time-based display hooks refresh because background browsers can slow their timers.

References: assets/…/petal_components.js• L1145-1227 assets/…/petal_components.js• L1392-1473 assets/…/petal_components.js• L2996-3106 assets/…/petal_components.js• L8670-9003 lib/…/number_ticker.ex• L1-90 lib/…/local_time.ex• L1-95 lib/…/text_animation.ex• L80-145

DOM state synchronization

Hooks use DOM state for short-lived facts that are not useful as server assigns. Examples include whether a panel is open, which option is highlighted, whether a toast is paused, whether a range track is filled, and which carousel slide is active. The state is expressed through text, classes, attributes, styles, focus, or browser properties.

The hook re-synchronizes this state after LiveView changes the element. It also emits browser events for higher-level consumers, such as carousel changes, completed one-time-code entry, reordered items, resized panels, and collapsed panes. This pattern lets a component expose a stable browser contract without making every visual transition part of the server state.

References: assets/…/petal_components.js• L365-661 assets/…/petal_components.js• L1585-1935 assets/…/petal_components.js• L2364-2742 assets/…/petal_components.js• L3110-4124 assets/…/petal_components.js• L4629-5860 assets/…/petal_components.js• L6106-8668 assets/…/petal_components.js• L9044-9891

Theme and chart state

The chart hook bridges server-provided chart options to a browser chart engine. It reads the current visual tokens from the chart's surrounding page, applies a light or dark theme, and rebuilds the chart when those tokens change. A color-scheme hook provides the matching browser interaction and keeps multiple scheme controls in sync through a window event.

This means charts follow the page theme without requiring the server to calculate final browser colors. The chart engine is an optional browser dependency supplied by the consuming application. If it is absent, the hook cannot create the chart and reports that condition in the browser console.

References: assets/…/petal_components.js• L672-1077 assets/…/petal_components.js• L1082-1143 lib/…/chart.ex• L100-135 lib/…/color_scheme_switch.ex• L120-210

Accessibility and user preferences

Focus and keyboard behavior

Focus is part of the hook contract, not an afterthought. Menus return focus when they close, command dialogs focus their search field, combo boxes keep the search field active while choices are made, and carousels expose keyboard movement alongside pointer controls. Trees use one tab stop for visible nodes, splitters support keyboard resizing, sortable items support keyboard reorder, and calendars move through dates without a server round trip for each key.

Hooks also maintain the browser-facing state that assistive technology reads. They update expanded, selected, current, disabled, invalid, and live-region information as the user moves through a component. The server-rendered control remains the durable form or content source where possible, while the hook keeps the visible interaction state aligned with it.

References: assets/…/petal_components.js• L1585-1935 assets/…/petal_components.js• L1971-2358 assets/…/petal_components.js• L2364-2742 assets/…/petal_components.js• L3110-4124 assets/…/petal_components.js• L4629-5860 assets/…/petal_components.js• L6106-6677 assets/…/petal_components.js• L8067-8267 assets/…/petal_components.js• L9044-9891 lib/…/input_otp.ex• L35-65 lib/…/carousel.ex• L150-185

Motion and viewport preferences

Motion hooks check the user's reduced-motion preference before starting automatic or decorative movement. This affects number animation, typing and word rotation, confetti, carousel movement, drawer settling, alert-dialog exit effects, and other time-based effects. When motion is reduced, the component favors its final or still state.

Viewport-aware hooks also account for scrolling, resizing, mobile keyboards, and visibility. Popovers, menus, drawers, and context menus stay inside the visible region when they can, while chat, carousel, and scrollspy behavior responds to user movement rather than forcing the viewport to an unwanted position.

References: assets/…/petal_components.js• L1145-1473 assets/…/petal_components.js• L1971-2188 assets/…/petal_components.js• L2502-2733 assets/…/petal_components.js• L2776-2991 assets/…/petal_components.js• L3110-4124 assets/…/petal_components.js• L6106-8056 assets/…/petal_components.js• L8269-9003

Change checklist

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

  • Keep each phx-hook name in component markup aligned with the bundle's named export and its default export registration.
  • Preserve the data attributes and browser events that connect server-rendered markup to hook behavior. A missing marker can leave a control visible but inactive.
  • When a hook changes form values, keep its native input and change event contract aligned with the LiveView form that receives it.
  • When a hook owns DOM during a stream, toast stack, or remote result view, preserve the matching phx-update ownership boundary so server patches do not erase active client state.
  • When changing overlay or menu markup, keep trigger IDs, panel IDs, focus targets, and ARIA state consistent across the hook and the component render.
  • When changing native dialog behavior, keep open state, close events, scroll locking, focus return, and exit motion on one close path.
  • When changing theme tokens or chart options, consider both the browser chart engine contract and the CSS token contract used to derive its visual state.
  • When changing calendar or date-picker rendering, keep date movement, typed-date parsing, range painting, and server-owned versus client-owned value paths aligned.
  • When changing sortable, resizable, drawer, or context-menu markup, preserve the state and event boundaries that let an active pointer or keyboard gesture finish safely.

Important failure modes

TriggerConsequenceGuard
The application does not register the bundle with LiveSocketElements with phx-hook render without their browser interactionRegister the default hook map when creating the LiveSocket
A component's phx-hook name or data marker no longer matches the bundleThe control can render but its focus, input, timing, or DOM behavior does not startTreat hook names and data markers as a shared component contract
More than one toast group receives global toast eventsThe same toast can appear in multiple stacksKeep one toast group for a page-level event stream
A server patch removes client-owned open or selection stateAn active menu, dialog, or picker closes or loses its current interactionLet the hook restore transient state after updates and keep durable values server-rendered
An alert dialog closes outside the hook's close pathThe exit state or page scroll lock can remain out of sync with the visible dialogRoute Escape, actions, and programmatic close requests through the dialog close funnel
The chart engine is not loadedChart content does not initializeSupply the browser chart dependency before mounting chart hooks
A timed hook ignores reduced-motion or teardown behaviorUsers can receive unwanted motion or stale timers can update removed DOMKeep preference checks and lifecycle cleanup part of the hook behavior
A LiveView patch changes a sortable, resizable, drawer, or date-picker subtree during an active gestureThe gesture can end against detached elements or restore stale valuesReconcile client state after patches and abandon pointer work when its DOM no longer exists
A calendar or date picker uses local-midnight date mathDates can move across a day at time-zone or daylight-saving boundariesKeep calendar values as validated ISO dates and use UTC date arithmetic

Key files

FileWhy to read it
assets/…/petal_components.jsPrimary browser behavior layer and the registration map for all named hooks
lib/petal_components/chat.exServer-rendered chat structure and the event boundaries used by stream, composer, scroll, and copy behavior
lib/petal_components/command.exCommand palette and dialog markup that defines keyboard, focus, and overlay contracts
lib/petal_components/combo_box.exRich choice control that connects visible search behavior to a native form select
lib/petal_components/toast.exToast group markup and the page-level feedback contract
lib/petal_components/chart.exServer-side chart option boundary and browser chart mount point
lib/petal_components/input.exInput variants that opt into password, copy, clear, and range hooks
lib/petal_components/carousel.exCarousel structure and the hook's navigation and accessibility surface
lib/petal_components/color_scheme_switch.exColor-scheme controls and their shared browser preference contract