// // Copyright 2026 DXOS.org // // @import-as-namespace import { createListCollection } from '@ark-ui/react/collection'; import { Listbox as ListboxPrimitive, type UseListboxContext, useListboxContext } from '@ark-ui/react/listbox'; import React, { Children, type ComponentPropsWithoutRef, type ReactNode, type RefObject, createContext, forwardRef, useContext, useId, useMemo, useRef, useState, } from 'react'; import { useComposedRefs } from '@dxos/react-hooks'; import { mx } from '@dxos/ui-theme'; import { type ThemedClassName } from '@dxos/ui-types'; import { recipes } from '../../recipes.ts'; import { type Size } from '../../sizes.ts'; import { composable, composableProps } from '../../util/slots.ts'; import { type ContainerProps, containerAttributes } from '../Container/Container.tsx'; import { Empty } from '../Empty/Empty.tsx'; import * as Icon from '../Icon/Icon.tsx'; import * as ScrollArea from '../ScrollArea/ScrollArea.tsx'; import { RowContext, handleGridKeyDown, isFromControl, useRowTabStops } from './grid.ts'; import { type VirtualMode, VirtualSpacer, isWindowed, useVirtualRows } from './virtual.tsx'; type ListboxOption = { value: string; label: string; disabled?: boolean; /** Leading icon of the default row. */ icon?: string; /** Second line of the default row. */ description?: string; }; /** `none` keeps zag's focus, keyboard and typeahead with no selection (AUDIT §6 group B: every list runs the machine). */ type ListboxSelectionMode = 'single' | 'multiple' | 'extended' | 'none'; type RootContextValue = { items: readonly ListboxOption[]; selectionMode: ListboxSelectionMode; columns?: string; virtual?: VirtualMode; /** Set by Content when it windows its rows; zag calls it to bring a highlighted row it has not mounted into view. */ scrollToIndexRef: RefObject<((index: number) => void) | null>; }; const RootContext = createContext(undefined); const useRootContext = (part: string) => { const context = useContext(RootContext); if (!context) { throw new Error(`Listbox.${part} must be inside Listbox.Root`); } return context; }; // // Root // type ListboxRootProps = ThemedClassName, 'defaultValue' | 'onSelect'>> & { items: readonly ListboxOption[]; /** * `single` by default; `multiple` toggles each item; `extended` selects one on a click and adds with Cmd/Ctrl or a * Shift range, as a desktop list does; `none` selects nothing but keeps navigation and typeahead. */ selectionMode?: ListboxSelectionMode; value?: string[]; defaultValue?: string[]; onValueChange?: (value: string[]) => void; /** The row keyboard or pointer navigation moved to (null when none). */ onHighlightChange?: (value: string | null) => void; /** Clicking the selected item of a single-selection list clears it. */ deselectable?: boolean; disabled?: boolean; /** Arrow keys wrap from the last item to the first and back. */ loopFocus?: boolean; /** * Custom tracks for every row, declared once: rows become subgrids of these columns and place their children in * order. Without it rows lay out by part (a leading cell, the text over its description, trailing parts). */ columns?: string; /** Long lists: `fixed` windows equal-height rows, `measured` windows rows of any height, `variable` defers off-screen rows (`content-visibility`). */ virtual?: VirtualMode; size?: Size; }; /** * Ark listbox: single, multiple or no selection, with keyboard navigation, typeahead and `aria-selected` from zag. A * flex column that caps itself at its parent's height, so a long list scrolls in its Content. */ const ListboxRoot = forwardRef( ( { classNames, items, selectionMode = 'single', value, defaultValue, onValueChange, onHighlightChange, deselectable, disabled, loopFocus, columns, virtual, size, children, ...props }, forwardedRef, ) => { const collection = useMemo( () => createListCollection({ items: [...items], itemToValue: (item) => item.value, itemToString: (item) => item.label, isItemDisabled: (item) => item.disabled ?? false, }), [items], ); const scrollToIndexRef = useRef<((index: number) => void) | null>(null); const context = useMemo( () => ({ items, selectionMode, columns, virtual, scrollToIndexRef }), [items, selectionMode, columns, virtual], ); return ( {...props} collection={collection} selectionMode={selectionMode} value={value} defaultValue={defaultValue} onValueChange={onValueChange && (({ value }) => onValueChange(value))} onHighlightChange={onHighlightChange && (({ highlightedValue }) => onHighlightChange(highlightedValue))} deselectable={deselectable} disabled={disabled} loopFocus={loopFocus} scrollToIndexFn={isWindowed(virtual) ? ({ index }) => scrollToIndexRef.current?.(index) : undefined} data-size={size} className={mx(recipes.listbox(), classNames)} ref={forwardedRef} > {children} ); }, ); ListboxRoot.displayName = 'Listbox.Root'; // // Label // type ListboxLabelProps = ThemedClassName; /** Names the list (`aria-labelledby` on its Content). */ const ListboxLabel = forwardRef(({ classNames, ...props }, forwardedRef) => ( )); ListboxLabel.displayName = 'Listbox.Label'; // // Viewport // /** True under a `Listbox.Viewport`: the list scrolls itself rather than in its host. */ const ViewportContext = createContext(false); type ListboxViewportProps = ThemedClassName> & { /** The `Listbox.Content`, which becomes the scrolling element. */ children: ReactNode; }; /** * A thin overlay ScrollArea (decision 5) that grows to fill the Root, for a list that owns its scrolling (a picker, a * fixed-height panel). Its `Content` is the scrolling element, so the thumb sits in the Content's end gutter. Omit it * inside a host that already scrolls, which would otherwise trap wheel and trackpad gestures in a nested scroller. */ const ListboxViewport = forwardRef( ({ classNames, mode, width, native, children }, forwardedRef) => ( {children} ), ); ListboxViewport.displayName = 'Listbox.Viewport'; // // Content // type ListboxContentProps = ThemedClassName> & Pick; /** * The listbox element: zag's content props with the grid keyboard in front of them, a Container's attributes so a * `Viewport`'s slot merges onto it, and the Root's `virtual` windowing over its direct children (the rows). Under a * `Viewport` it is the scrolling element (`inset` gutter by default); otherwise its host scrolls and the rows inherit the * host's rails (`inherit`). A windowed (`virtual`) list measures its scroller, so it needs a `Viewport`. */ const ListboxContent = composable, 'className'>>( ({ gutter, gap, padBlock, onKeyDown, onFocus, onBlur, children, ...props }, forwardedRef) => { const api = useListboxContext(); const { columns, virtual, scrollToIndexRef } = useRootContext('Content'); const inViewport = useContext(ViewportContext); const [element, setElement] = useState(null); const rows = Children.toArray(children); const windowing = useVirtualRows({ mode: virtual, count: rows.length }); scrollToIndexRef.current = isWindowed(virtual) ? windowing.scrollToIndex : null; const ref = useComposedRefs(forwardedRef, setElement, windowing.listRef); useRowTabStops(element); const { style, ...attributes } = containerAttributes({ gutter: gutter ?? (inViewport ? 'inset' : 'inherit'), gap, columns, padBlock, }); const { className, style: ownStyle, ...rest } = composableProps(props, { classNames: [recipes.container(), recipes.listboxContent()], }); const contentProps = api.getContentProps(); return (
{ contentProps.onFocus?.(event); onFocus?.(event); }} onBlur={(event) => { contentProps.onBlur?.(event); onBlur?.(event); }} onKeyDown={(event) => { onKeyDown?.(event); if (event.defaultPrevented && event.target === event.currentTarget) { return; } if (handleGridKeyDown(event)) { return; } contentProps.onKeyDown?.(event); if (!inViewport && !isWindowed(virtual)) { // zag scrolls the highlighted row into view only when the listbox itself overflows; here the host scrolls. const content = event.currentTarget; requestAnimationFrame(() => content.querySelector('[data-highlighted]')?.scrollIntoView({ block: 'nearest' }), ); } }} ref={ref} > {isWindowed(virtual) ? ( <> {rows.slice(windowing.first, windowing.last + 1)} ) : ( children )}
); }, ); ListboxContent.displayName = 'Listbox.Content'; /** True inside a `Listbox.Viewport`, for parts that act on the scrolling element (e.g. drag auto-scroll). */ const useListboxViewport = (): boolean => useContext(ViewportContext); // // Empty // type ListboxEmptyProps = ComponentPropsWithoutRef; /** `Empty`, rendered only while the Root has no items. */ const ListboxEmpty = forwardRef((props, forwardedRef) => { const { items } = useRootContext('Empty'); return items.length === 0 ? : null; }); ListboxEmpty.displayName = 'Listbox.Empty'; // // Item // // The option an Item renders, so its parts default to the option's icon, label and description. const ItemContext = createContext(undefined); const useItem = (part: string) => { const item = useContext(ItemContext); if (!item) { throw new Error(`Listbox.${part} must be inside Listbox.Item`); } return item; }; type ListboxItemProps = ThemedClassName, 'children'>> & { item: ListboxOption; /** "You are here" (`aria-current`), distinct from selection. */ current?: boolean; /** Pointer movement highlights the item, as the keyboard does. */ highlightOnHover?: boolean; /** Replaces the whole row, composed from `ItemIcon`, `ItemText`, `ItemDescription`, `ItemIndicator` and controls. */ children?: ReactNode; }; /** * A row (`option`) at least one block tall: without children, the option's icon, label and description; with them, * the caller's parts, which the theme places by part (leading cells, text over description, then trailing cells) or, * under Root `columns`, in order across the shared tracks. Pointer presses on a row control stay with the control: they * neither select the row nor take focus from the control. */ const ListboxItem = forwardRef( ( { classNames, item, current, highlightOnHover, children, style, onMouseDown, onClick, onFocus, ...props }, forwardedRef, ) => { const api = useListboxContext(); const { columns, selectionMode } = useRootContext('Item'); const textId = useId(); const row = useMemo(() => ({ textId }), [textId]); // Under Root `columns` the row is a subgrid of the Content's tracks (theme); otherwise it has its own template. const { style: columnsStyle, ...attributes } = containerAttributes( columns ? {} : { columns: 'var(--dx-item-columns)' }, ); const itemProps = api.getItemProps({ item, highlightOnHover }); const content = children ?? ( <> {item.icon && } {item.description != null && } ); return (
{ onMouseDown?.(event); if (!isFromControl(event.currentTarget, event.target)) { itemProps.onMouseDown?.(event); } }} onClick={(event) => { onClick?.(event); if (!isFromControl(event.currentTarget, event.target)) { itemProps.onClick?.(event); } }} onFocus={(event) => { onFocus?.(event); // A row control took focus (a click or the grid keyboard): the row is the list's current row. if (event.target !== event.currentTarget && api.highlightedValue !== item.value) { api.highlightValue(item.value); } }} ref={forwardedRef} > {content}
); }, ); ListboxItem.displayName = 'Listbox.Item'; // // ItemIcon // type ListboxItemIconProps = ThemedClassName> & Partial>; /** A block-sized leading cell, so the labels of every row start at the same x; `hue` and the rest reach the Icon. */ const ListboxItemIcon = forwardRef( ({ classNames, icon, hue, valence, label, children, ...props }, forwardedRef) => { const item = useItem('ItemIcon'); const glyph = icon ?? item.icon; return (
{children ?? (glyph && )}
); }, ); ListboxItemIcon.displayName = 'Listbox.ItemIcon'; // // ItemText // type ListboxItemTextProps = ThemedClassName> & { /** `muted` reads as secondary text, as Typography's tone. */ tone?: 'default' | 'muted'; }; /** * The row's label, truncated to one line; the option's `label` by default, which typeahead matches either way. Its id * names the row's controls (a Remove button, a disclosure caret). */ const ListboxItemText = forwardRef( ({ classNames, tone, children, ...props }, forwardedRef) => { const item = useItem('ItemText'); const row = useContext(RowContext); return (

{children ?? item.label}

); }, ); ListboxItemText.displayName = 'Listbox.ItemText'; // // ItemDescription // type ListboxItemDescriptionProps = ThemedClassName>; /** A second line under the text in `--color-fg-muted`; the option's `description` by default. */ const ListboxItemDescription = forwardRef( ({ classNames, children, ...props }, forwardedRef) => { const item = useItem('ItemDescription'); return (

{children ?? item.description}

); }, ); ListboxItemDescription.displayName = 'Listbox.ItemDescription'; // // ItemIndicator // type ListboxItemIndicatorProps = ThemedClassName>; /** Shown while its item is selected: a check by default, in an icon-sized cell. */ const ListboxItemIndicator = forwardRef( ({ classNames, children, ...props }, forwardedRef) => { const api = useListboxContext(); const item = useItem('ItemIndicator'); return (
{children ?? }
); }, ); ListboxItemIndicator.displayName = 'Listbox.ItemIndicator'; // // ItemGroup // type ListboxItemGroupProps = ThemedClassName>; /** * A `group` of items named by the `ItemGroupLabel` inside it; an inheriting Container, so its rows keep the list's * rails. Order groups as the Root's `items` are ordered, or keyboard order and reading order diverge. */ const ListboxItemGroup = forwardRef( ({ classNames, style, children, ...props }, forwardedRef) => { const { style: containerStyle, ...attributes } = containerAttributes({}); return ( {children} ); }, ); ListboxItemGroup.displayName = 'Listbox.ItemGroup'; // // ItemGroupLabel // type ListboxItemGroupLabelProps = ThemedClassName>; /** A small caption naming its group, like `Select.ItemGroupLabel`. */ const ListboxItemGroupLabel = forwardRef( ({ classNames, ...props }, forwardedRef) => ( ), ); ListboxItemGroupLabel.displayName = 'Listbox.ItemGroupLabel'; // // useContext // type ListboxContext = UseListboxContext; /** Ark's listbox api (`value`, `selectedItems`, `setValue`, `clearValue`, …) for parts inside the Root, e.g. a detail pane. */ const useListboxRootContext = (): ListboxContext => useListboxContext(); export type { ListboxContentProps as ContentProps, ListboxContext as Context, ListboxEmptyProps as EmptyProps, ListboxItemDescriptionProps as ItemDescriptionProps, ListboxItemGroupLabelProps as ItemGroupLabelProps, ListboxItemGroupProps as ItemGroupProps, ListboxItemIconProps as ItemIconProps, ListboxItemIndicatorProps as ItemIndicatorProps, ListboxItemProps as ItemProps, ListboxItemTextProps as ItemTextProps, ListboxLabelProps as LabelProps, ListboxRootProps as RootProps, ListboxViewportProps as ViewportProps, }; export { ListboxContent as Content, ListboxEmpty as Empty, ListboxItem as Item, ListboxItemDescription as ItemDescription, ListboxItemGroup as ItemGroup, ListboxItemGroupLabel as ItemGroupLabel, ListboxItemIcon as ItemIcon, ListboxItemIndicator as ItemIndicator, ListboxItemText as ItemText, ListboxLabel as Label, ListboxRoot as Root, ListboxViewport as Viewport, useListboxRootContext as useContext, useListboxViewport as useViewport, }; export type { ListboxOption as Option, ListboxSelectionMode as SelectionMode }; export { RowContext, type RowContextValue } from './grid.ts'; export * from './virtual.tsx';