UNPKG

@ark-ui/solid

Version:

A collection of unstyled, accessible UI components for Solid, utilizing state machines for seamless interaction.

1,138 lines (1,112 loc) 40.6 kB
import { createMachine } from "./ETB2BIQZ.jsx"; import { createSplitProps } from "./6WEDGJKQ.jsx"; import { ark } from "./UFYZ7HLU.jsx"; import { useEnvironmentContext } from "./6J5H27AQ.jsx"; import { runIfFn } from "./KGOB2IMX.jsx"; import { useLocaleContext } from "./YUC6JE7K.jsx"; import { createContext } from "./TVCIHLER.jsx"; import { __export } from "./7IUG3E2V.jsx"; // src/components/listbox/use-listbox-context.ts var [ListboxProvider, useListboxContext] = createContext({ hookName: "useListboxContext", providerName: "<ListboxProvider />" }); // src/components/listbox/listbox-context.tsx function ListboxContext(props2) { return props2.children(useListboxContext()); } // src/components/listbox/listbox-content.tsx import { mergeProps } from "@zag-js/solid"; var ListboxContent = (props2) => { const listbox = useListboxContext(); const mergedProps = mergeProps(() => listbox().getContentProps(), props2); return <ark.div {...mergedProps} />; }; // src/components/listbox/listbox-input.tsx import { mergeProps as mergeProps2 } from "@zag-js/solid"; var ListboxInput = (props2) => { const [inputProps, localProps] = createSplitProps()(props2, ["autoHighlight"]); const listbox = useListboxContext(); const mergedProps = mergeProps2(() => listbox().getInputProps(inputProps), localProps); return <ark.input {...mergedProps} />; }; // src/components/listbox/listbox-item.tsx import { mergeProps as mergeProps3 } from "@zag-js/solid"; // src/components/listbox/use-listbox-item-context.ts var [ListboxItemProvider, useListboxItemContext] = createContext({ hookName: "useListboxItemContext", providerName: "<ListboxItemProvider />" }); // src/components/listbox/use-listbox-item-props-context.ts var [ListboxItemPropsProvider, useListboxItemPropsContext] = createContext({ hookName: "useListboxItemPropsContext", providerName: "<ListboxItemPropsProvider />" }); // src/components/listbox/listbox-item.tsx var ListboxItem = (props2) => { const [itemProps2, localProps] = createSplitProps()(props2, ["item", "highlightOnHover"]); const listbox = useListboxContext(); const mergedProps = mergeProps3(() => listbox().getItemProps(itemProps2), localProps); const itemState = () => listbox().getItemState(itemProps2); return <ListboxItemPropsProvider value={itemProps2}> <ListboxItemProvider value={itemState()}> <ark.div {...mergedProps} /> </ListboxItemProvider> </ListboxItemPropsProvider>; }; // src/components/listbox/listbox-item-group.tsx import { mergeProps as mergeProps4 } from "@zag-js/solid"; import { createUniqueId } from "solid-js"; // src/components/listbox/use-listbox-item-group-props-context.ts var [ListboxItemGroupPropsProvider, useListboxItemGroupPropsContext] = createContext({ hookName: "useListboxItemGroupPropsContext", providerName: "<ListboxItemGroupPropsProvider />" }); // src/components/listbox/listbox-item-group.tsx var ListboxItemGroup = (props2) => { const id = createUniqueId(); const [_itemGroupProps, localProps] = createSplitProps()(props2, ["id"]); const itemGroupProps2 = { id, ..._itemGroupProps }; const listbox = useListboxContext(); const mergedProps = mergeProps4(() => listbox().getItemGroupProps(itemGroupProps2), localProps); return <ListboxItemGroupPropsProvider value={itemGroupProps2}> <ark.div {...mergedProps} /> </ListboxItemGroupPropsProvider>; }; // src/components/listbox/listbox-item-group-label.tsx import { mergeProps as mergeProps5 } from "@zag-js/solid"; var ListboxItemGroupLabel = (props2) => { const listbox = useListboxContext(); const itemGroupProps2 = useListboxItemGroupPropsContext(); const mergedProps = mergeProps5(() => listbox().getItemGroupLabelProps({ htmlFor: itemGroupProps2.id }), props2); return <ark.div {...mergedProps} />; }; // src/components/listbox/listbox-item-indicator.tsx import { mergeProps as mergeProps6 } from "@zag-js/solid"; var ListboxItemIndicator = (props2) => { const listbox = useListboxContext(); const itemProps2 = useListboxItemPropsContext(); const mergedProps = mergeProps6(() => listbox().getItemIndicatorProps(itemProps2), props2); return <ark.div {...mergedProps} />; }; // src/components/listbox/listbox-item-text.tsx import { mergeProps as mergeProps7 } from "@zag-js/solid"; var ListboxItemText = (props2) => { const listbox = useListboxContext(); const itemProps2 = useListboxItemPropsContext(); const mergedProps = mergeProps7(() => listbox().getItemTextProps(itemProps2), props2); return <ark.div {...mergedProps} />; }; // src/components/listbox/listbox-label.tsx import { mergeProps as mergeProps8 } from "@zag-js/solid"; var ListboxLabel = (props2) => { const listbox = useListboxContext(); const mergedProps = mergeProps8(() => listbox().getLabelProps(), props2); return <ark.label {...mergedProps} />; }; // src/components/listbox/listbox-root.tsx import { mergeProps as mergeProps9 } from "@zag-js/solid"; // ../../node_modules/@zag-js/listbox/dist/index.mjs import { createAnatomy } from "@zag-js/anatomy"; import { Selection, ListCollection, GridCollection, isGridCollection } from "@zag-js/collection"; import { raf, observeAttributes, getByTypeahead, scrollIntoView, dataAttr, isSelfTarget, getEventKey, getEventTarget as getEventTarget2, isEditableElement, ariaAttr, isCtrlOrMetaKey, isComposingEvent, getNativeEvent, getWindow as getWindow2 } from "@zag-js/dom-query"; import { isEqual, createSplitProps as createSplitProps2, ensure } from "@zag-js/utils"; // ../../node_modules/@zag-js/focus-visible/dist/index.mjs import { getWindow, getDocument, getEventTarget, isVirtualClick, isMac } from "@zag-js/dom-query"; function isValidKey(e) { return !(e.metaKey || !isMac() && e.altKey || e.ctrlKey || e.key === "Control" || e.key === "Shift" || e.key === "Meta"); } var nonTextInputTypes = /* @__PURE__ */ new Set(["checkbox", "radio", "range", "color", "file", "image", "button", "submit", "reset"]); function isKeyboardFocusEvent(isTextInput, modality, e) { const target = e ? getEventTarget(e) : null; const win = getWindow(target); isTextInput = isTextInput || target instanceof win.HTMLInputElement && !nonTextInputTypes.has(target?.type) || target instanceof win.HTMLTextAreaElement || target instanceof win.HTMLElement && target.isContentEditable; return !(isTextInput && modality === "keyboard" && e instanceof win.KeyboardEvent && !Reflect.has(FOCUS_VISIBLE_INPUT_KEYS, e.key)); } var currentModality = null; var changeHandlers = /* @__PURE__ */ new Set(); var listenerMap = /* @__PURE__ */ new Map(); var hasEventBeforeFocus = false; var hasBlurredWindowRecently = false; var FOCUS_VISIBLE_INPUT_KEYS = { Tab: true, Escape: true }; function triggerChangeHandlers(modality, e) { for (let handler of changeHandlers) { handler(modality, e); } } function handleKeyboardEvent(e) { hasEventBeforeFocus = true; if (isValidKey(e)) { currentModality = "keyboard"; triggerChangeHandlers("keyboard", e); } } function handlePointerEvent(e) { currentModality = "pointer"; if (e.type === "mousedown" || e.type === "pointerdown") { hasEventBeforeFocus = true; triggerChangeHandlers("pointer", e); } } function handleClickEvent(e) { if (isVirtualClick(e)) { hasEventBeforeFocus = true; currentModality = "virtual"; } } function handleFocusEvent(e) { const target = getEventTarget(e); if (target === getWindow(target) || target === getDocument(target)) { return; } if (!hasEventBeforeFocus && !hasBlurredWindowRecently) { currentModality = "virtual"; triggerChangeHandlers("virtual", e); } hasEventBeforeFocus = false; hasBlurredWindowRecently = false; } function handleWindowBlur() { hasEventBeforeFocus = false; hasBlurredWindowRecently = true; } function setupGlobalFocusEvents(root) { if (typeof window === "undefined" || listenerMap.get(getWindow(root))) { return; } const win = getWindow(root); const doc = getDocument(root); let focus = win.HTMLElement.prototype.focus; function patchedFocus() { currentModality = "virtual"; triggerChangeHandlers("virtual", null); hasEventBeforeFocus = true; focus.apply(this, arguments); } Object.defineProperty(win.HTMLElement.prototype, "focus", { configurable: true, value: patchedFocus }); doc.addEventListener("keydown", handleKeyboardEvent, true); doc.addEventListener("keyup", handleKeyboardEvent, true); doc.addEventListener("click", handleClickEvent, true); win.addEventListener("focus", handleFocusEvent, true); win.addEventListener("blur", handleWindowBlur, false); if (typeof win.PointerEvent !== "undefined") { doc.addEventListener("pointerdown", handlePointerEvent, true); doc.addEventListener("pointermove", handlePointerEvent, true); doc.addEventListener("pointerup", handlePointerEvent, true); } else { doc.addEventListener("mousedown", handlePointerEvent, true); doc.addEventListener("mousemove", handlePointerEvent, true); doc.addEventListener("mouseup", handlePointerEvent, true); } win.addEventListener( "beforeunload", () => { tearDownWindowFocusTracking(root); }, { once: true } ); listenerMap.set(win, { focus }); } var tearDownWindowFocusTracking = (root, loadListener) => { const win = getWindow(root); const doc = getDocument(root); if (!listenerMap.has(win)) { return; } win.HTMLElement.prototype.focus = listenerMap.get(win).focus; doc.removeEventListener("keydown", handleKeyboardEvent, true); doc.removeEventListener("keyup", handleKeyboardEvent, true); doc.removeEventListener("click", handleClickEvent, true); win.removeEventListener("focus", handleFocusEvent, true); win.removeEventListener("blur", handleWindowBlur, false); if (typeof win.PointerEvent !== "undefined") { doc.removeEventListener("pointerdown", handlePointerEvent, true); doc.removeEventListener("pointermove", handlePointerEvent, true); doc.removeEventListener("pointerup", handlePointerEvent, true); } else { doc.removeEventListener("mousedown", handlePointerEvent, true); doc.removeEventListener("mousemove", handlePointerEvent, true); doc.removeEventListener("mouseup", handlePointerEvent, true); } listenerMap.delete(win); }; function getInteractionModality() { return currentModality; } function isFocusVisible() { return currentModality === "keyboard"; } function trackFocusVisible(props2 = {}) { const { isTextInput, autoFocus, onChange, root } = props2; setupGlobalFocusEvents(root); onChange?.({ isFocusVisible: autoFocus || isFocusVisible(), modality: currentModality }); const handler = (modality, e) => { if (!isKeyboardFocusEvent(!!isTextInput, modality, e)) return; onChange?.({ isFocusVisible: isFocusVisible(), modality }); }; changeHandlers.add(handler); return () => { changeHandlers.delete(handler); }; } // ../../node_modules/@zag-js/listbox/dist/index.mjs import { createProps } from "@zag-js/types"; var anatomy = createAnatomy("listbox").parts( "label", "input", "item", "itemText", "itemIndicator", "itemGroup", "itemGroupLabel", "content", "root", "valueText" ); var parts = anatomy.build(); var collection = (options) => { return new ListCollection(options); }; collection.empty = () => { return new ListCollection({ items: [] }); }; var gridCollection = (options) => { return new GridCollection(options); }; gridCollection.empty = () => { return new GridCollection({ items: [], columnCount: 0 }); }; var getRootId = (ctx) => ctx.ids?.root ?? `select:${ctx.id}`; var getContentId = (ctx) => ctx.ids?.content ?? `select:${ctx.id}:content`; var getLabelId = (ctx) => ctx.ids?.label ?? `select:${ctx.id}:label`; var getItemId = (ctx, id) => ctx.ids?.item?.(id) ?? `select:${ctx.id}:option:${id}`; var getItemGroupId = (ctx, id) => ctx.ids?.itemGroup?.(id) ?? `select:${ctx.id}:optgroup:${id}`; var getItemGroupLabelId = (ctx, id) => ctx.ids?.itemGroupLabel?.(id) ?? `select:${ctx.id}:optgroup-label:${id}`; var getContentEl = (ctx) => ctx.getById(getContentId(ctx)); var getItemEl = (ctx, id) => ctx.getById(getItemId(ctx, id)); function connect(service, normalize) { const { context, prop, scope, computed, send } = service; const disabled = prop("disabled"); const collection2 = prop("collection"); const layout = isGridCollection(collection2) ? "grid" : "list"; const value = context.get("value"); const highlightedValue = context.get("highlightedValue"); const highlightedItem = context.get("highlightedItem"); const selectedItems = context.get("selectedItems"); const isTypingAhead = computed("isTypingAhead"); const interactive = computed("isInteractive"); const ariaActiveDescendant = highlightedValue ? getItemId(scope, highlightedValue) : void 0; function getItemState(props2) { const itemDisabled = collection2.getItemDisabled(props2.item); const value2 = collection2.getItemValue(props2.item); ensure(value2, () => `[zag-js] No value found for item ${JSON.stringify(props2.item)}`); return { value: value2, disabled: Boolean(disabled || itemDisabled), highlighted: highlightedValue === value2 && context.get("focused"), selected: context.get("value").includes(value2) }; } return { empty: value.length === 0, highlightedItem, highlightedValue, clearHighlightedValue() { send({ type: "HIGHLIGHTED_VALUE.SET", value: null }); }, selectedItems, hasSelectedItems: computed("hasSelectedItems"), value, valueAsString: context.get("valueAsString"), collection: collection2, disabled: !!disabled, selectValue(value2) { send({ type: "ITEM.SELECT", value: value2 }); }, setValue(value2) { send({ type: "VALUE.SET", value: value2 }); }, selectAll() { if (!computed("multiple")) { throw new Error("[zag-js] Cannot select all items in a single-select listbox"); } send({ type: "VALUE.SET", value: collection2.getValues() }); }, highlightValue(value2) { send({ type: "HIGHLIGHTED_VALUE.SET", value: value2 }); }, clearValue(value2) { if (value2) { send({ type: "ITEM.CLEAR", value: value2 }); } else { send({ type: "VALUE.CLEAR" }); } }, getItemState, getRootProps() { return normalize.element({ ...parts.root.attrs, dir: prop("dir"), id: getRootId(scope), "data-orientation": prop("orientation"), "data-disabled": dataAttr(disabled) }); }, getInputProps(props2 = {}) { return normalize.input({ ...parts.input.attrs, dir: prop("dir"), disabled, "data-disabled": dataAttr(disabled), autoComplete: "off", autoCorrect: "off", "aria-haspopup": "listbox", "aria-controls": getContentId(scope), "aria-autocomplete": "list", "aria-activedescendant": ariaActiveDescendant, spellCheck: false, enterKeyHint: "go", onFocus() { queueMicrotask(() => { const contentEl = getContentEl(scope); const win = getWindow2(contentEl); const focusInEvt = new win.FocusEvent("focusin", { bubbles: true, cancelable: true }); contentEl?.dispatchEvent(focusInEvt); }); }, onBlur(event) { if (event.defaultPrevented) return; const contentEl = getContentEl(scope); const win = getWindow2(contentEl); const focusOutEvt = new win.FocusEvent("focusout", { bubbles: true, cancelable: true }); contentEl?.dispatchEvent(focusOutEvt); }, onInput(event) { if (!props2.autoHighlight) return; const node = event.currentTarget; queueMicrotask(() => { if (!node.isConnected) return; send({ type: "HIGHLIGHTED_VALUE.SET", value: node.value ? prop("collection").firstValue : null }); }); }, onKeyDown(event) { if (event.defaultPrevented) return; if (isComposingEvent(event)) return; const nativeEvent = getNativeEvent(event); switch (nativeEvent.key) { case "ArrowDown": case "ArrowUp": case "Home": case "End": { if ((event.key === "Home" || event.key === "End") && !highlightedValue && event.shiftKey) { return; } event.preventDefault(); const win = scope.getWin(); const keyboardEvent = new win.KeyboardEvent(nativeEvent.type, nativeEvent); getContentEl(scope)?.dispatchEvent(keyboardEvent); break; } case "Enter": event.preventDefault(); send({ type: "ITEM.CLICK", value: highlightedValue }); break; } } }); }, getLabelProps() { return normalize.element({ dir: prop("dir"), id: getLabelId(scope), ...parts.label.attrs, "data-disabled": dataAttr(disabled) }); }, getValueTextProps() { return normalize.element({ ...parts.valueText.attrs, dir: prop("dir"), "data-disabled": dataAttr(disabled) }); }, getItemProps(props2) { const itemState = getItemState(props2); return normalize.element({ id: getItemId(scope, itemState.value), role: "option", ...parts.item.attrs, dir: prop("dir"), "data-value": itemState.value, "aria-selected": itemState.selected, "data-selected": dataAttr(itemState.selected), "data-layout": layout, "data-state": itemState.selected ? "checked" : "unchecked", "data-orientation": prop("orientation"), "data-highlighted": dataAttr(itemState.highlighted), "data-disabled": dataAttr(itemState.disabled), "aria-disabled": ariaAttr(itemState.disabled), onPointerMove(event) { if (!props2.highlightOnHover) return; if (itemState.disabled || event.pointerType !== "mouse") return; if (itemState.highlighted) return; send({ type: "ITEM.POINTER_MOVE", value: itemState.value }); }, onMouseDown(event) { event.preventDefault(); getContentEl(scope)?.focus(); }, onClick(event) { if (event.defaultPrevented) return; if (itemState.disabled) return; send({ type: "ITEM.CLICK", value: itemState.value, shiftKey: event.shiftKey, anchorValue: highlightedValue, metaKey: isCtrlOrMetaKey(event) }); } }); }, getItemTextProps(props2) { const itemState = getItemState(props2); return normalize.element({ ...parts.itemText.attrs, "data-state": itemState.selected ? "checked" : "unchecked", "data-disabled": dataAttr(itemState.disabled), "data-highlighted": dataAttr(itemState.highlighted) }); }, getItemIndicatorProps(props2) { const itemState = getItemState(props2); return normalize.element({ ...parts.itemIndicator.attrs, "aria-hidden": true, "data-state": itemState.selected ? "checked" : "unchecked", hidden: !itemState.selected }); }, getItemGroupLabelProps(props2) { const { htmlFor } = props2; return normalize.element({ ...parts.itemGroupLabel.attrs, id: getItemGroupLabelId(scope, htmlFor), dir: prop("dir"), role: "presentation" }); }, getItemGroupProps(props2) { const { id } = props2; return normalize.element({ ...parts.itemGroup.attrs, "data-disabled": dataAttr(disabled), "data-orientation": prop("orientation"), "data-empty": dataAttr(collection2.size === 0), id: getItemGroupId(scope, id), "aria-labelledby": getItemGroupLabelId(scope, id), role: "group", dir: prop("dir") }); }, getContentProps() { return normalize.element({ dir: prop("dir"), id: getContentId(scope), role: "listbox", ...parts.content.attrs, "data-activedescendant": ariaActiveDescendant, "aria-activedescendant": ariaActiveDescendant, "data-orientation": prop("orientation"), "aria-multiselectable": computed("multiple") ? true : void 0, "aria-labelledby": getLabelId(scope), tabIndex: 0, "data-layout": layout, "data-empty": dataAttr(collection2.size === 0), style: { "--column-count": isGridCollection(collection2) ? collection2.columnCount : 1 }, onFocus() { send({ type: "CONTENT.FOCUS" }); }, onBlur() { send({ type: "CONTENT.BLUR" }); }, onKeyDown(event) { if (!interactive) return; if (!isSelfTarget(event)) return; const shiftKey = event.shiftKey; const keyMap = { ArrowUp(event2) { let nextValue = null; if (isGridCollection(collection2) && highlightedValue) { nextValue = collection2.getPreviousRowValue(highlightedValue); } else if (highlightedValue) { nextValue = collection2.getPreviousValue(highlightedValue); } if (!nextValue && (prop("loopFocus") || !highlightedValue)) { nextValue = collection2.lastValue; } if (!nextValue) return; event2.preventDefault(); send({ type: "NAVIGATE", value: nextValue, shiftKey, anchorValue: highlightedValue }); }, ArrowDown(event2) { let nextValue = null; if (isGridCollection(collection2) && highlightedValue) { nextValue = collection2.getNextRowValue(highlightedValue); } else if (highlightedValue) { nextValue = collection2.getNextValue(highlightedValue); } if (!nextValue && (prop("loopFocus") || !highlightedValue)) { nextValue = collection2.firstValue; } if (!nextValue) return; event2.preventDefault(); send({ type: "NAVIGATE", value: nextValue, shiftKey, anchorValue: highlightedValue }); }, ArrowLeft() { if (!isGridCollection(collection2) && prop("orientation") === "vertical") return; let nextValue = highlightedValue ? collection2.getPreviousValue(highlightedValue) : null; if (!nextValue && prop("loopFocus")) { nextValue = collection2.lastValue; } if (!nextValue) return; event.preventDefault(); send({ type: "NAVIGATE", value: nextValue, shiftKey, anchorValue: highlightedValue }); }, ArrowRight() { if (!isGridCollection(collection2) && prop("orientation") === "vertical") return; let nextValue = highlightedValue ? collection2.getNextValue(highlightedValue) : null; if (!nextValue && prop("loopFocus")) { nextValue = collection2.firstValue; } if (!nextValue) return; event.preventDefault(); send({ type: "NAVIGATE", value: nextValue, shiftKey, anchorValue: highlightedValue }); }, Home(event2) { event2.preventDefault(); let nextValue = collection2.firstValue; send({ type: "NAVIGATE", value: nextValue, shiftKey, anchorValue: highlightedValue }); }, End(event2) { event2.preventDefault(); let nextValue = collection2.lastValue; send({ type: "NAVIGATE", value: nextValue, shiftKey, anchorValue: highlightedValue }); }, Enter() { send({ type: "ITEM.CLICK", value: highlightedValue }); }, a(event2) { if (isCtrlOrMetaKey(event2) && computed("multiple") && !prop("disallowSelectAll")) { event2.preventDefault(); send({ type: "VALUE.SET", value: collection2.getValues() }); } }, Space(event2) { if (isTypingAhead && prop("typeahead")) { send({ type: "CONTENT.TYPEAHEAD", key: event2.key }); } else { keyMap.Enter?.(event2); } }, Escape(event2) { if (prop("deselectable") && value.length > 0) { event2.preventDefault(); event2.stopPropagation(); send({ type: "VALUE.CLEAR" }); } } }; const exec = keyMap[getEventKey(event)]; if (exec) { exec(event); return; } const target = getEventTarget2(event); if (isEditableElement(target)) { return; } if (getByTypeahead.isValidEvent(event) && prop("typeahead")) { send({ type: "CONTENT.TYPEAHEAD", key: event.key }); event.preventDefault(); } } }); } }; } var machine = createMachine({ props({ props: props2 }) { return { loopFocus: false, composite: true, defaultValue: [], multiple: false, typeahead: true, collection: collection.empty(), orientation: "vertical", selectionMode: "single", ...props2 }; }, context({ prop, bindable }) { return { value: bindable(() => ({ defaultValue: prop("defaultValue"), value: prop("value"), isEqual, onChange(value) { const items = prop("collection").findMany(value); return prop("onValueChange")?.({ value, items }); } })), highlightedValue: bindable(() => ({ defaultValue: prop("defaultHighlightedValue") || null, value: prop("highlightedValue"), sync: true, onChange(value) { prop("onHighlightChange")?.({ highlightedValue: value, highlightedItem: prop("collection").find(value), highlightedIndex: prop("collection").indexOf(value) }); } })), highlightedItem: bindable(() => ({ defaultValue: null })), selectedItems: bindable(() => { const value = prop("value") ?? prop("defaultValue") ?? []; const items = prop("collection").findMany(value); return { defaultValue: items }; }), valueAsString: bindable(() => { const value = prop("value") ?? prop("defaultValue") ?? []; return { defaultValue: prop("collection").stringifyMany(value) }; }), focused: bindable(() => ({ defaultValue: false })) }; }, refs({ prop }) { return { typeahead: { ...getByTypeahead.defaultOptions }, prevCollection: prop("collection") }; }, computed: { hasSelectedItems: ({ context }) => context.get("value").length > 0, isTypingAhead: ({ refs }) => refs.get("typeahead").keysSoFar !== "", isInteractive: ({ prop }) => !prop("disabled"), selection: ({ context, prop }) => { const selection = new Selection(context.get("value")); selection.selectionMode = prop("selectionMode"); selection.deselectable = !!prop("deselectable"); return selection; }, multiple: ({ prop }) => prop("selectionMode") === "multiple" || prop("selectionMode") === "extended" }, initialState() { return "idle"; }, watch({ context, prop, track, action }) { track([() => context.get("value").toString()], () => { action(["syncSelectedItems"]); }); track([() => context.get("highlightedValue")], () => { action(["syncHighlightedItem"]); }); track([() => prop("collection").toString()], () => { action(["syncCollection"]); }); }, effects: ["trackFocusVisible"], on: { "HIGHLIGHTED_VALUE.SET": { actions: ["setHighlightedItem"] }, "ITEM.SELECT": { actions: ["selectItem"] }, "ITEM.CLEAR": { actions: ["clearItem"] }, "VALUE.SET": { actions: ["setSelectedItems"] }, "VALUE.CLEAR": { actions: ["clearSelectedItems"] }, "CLEAR.CLICK": { actions: ["clearSelectedItems"] } }, states: { idle: { effects: ["scrollToHighlightedItem"], on: { "CONTENT.FOCUS": { actions: ["setFocused"] }, "CONTENT.BLUR": { actions: ["clearFocused"] }, "ITEM.CLICK": { actions: ["setHighlightedItem", "selectHighlightedItem"] }, "CONTENT.TYPEAHEAD": { actions: ["highlightMatchingItem"] }, "ITEM.POINTER_MOVE": { actions: ["highlightItem"] }, "ITEM.POINTER_LEAVE": { actions: ["clearHighlightedItem"] }, NAVIGATE: { actions: ["setHighlightedItem", "selectWithKeyboard"] } } } }, implementations: { effects: { trackFocusVisible: ({ scope }) => { return trackFocusVisible({ root: scope.getRootNode?.() }); }, scrollToHighlightedItem({ context, prop, scope }) { const exec = (immediate) => { const highlightedValue = context.get("highlightedValue"); if (highlightedValue == null) return; const modality = getInteractionModality(); if (modality !== "keyboard") return; const itemEl = getItemEl(scope, highlightedValue); const contentEl2 = getContentEl(scope); const scrollToIndexFn = prop("scrollToIndexFn"); if (scrollToIndexFn) { const highlightedIndex = prop("collection").indexOf(highlightedValue); scrollToIndexFn?.({ index: highlightedIndex, immediate }); return; } scrollIntoView(itemEl, { rootEl: contentEl2, block: "nearest" }); }; raf(() => exec(true)); const contentEl = () => getContentEl(scope); return observeAttributes(contentEl, { defer: true, attributes: ["data-activedescendant"], callback() { exec(false); } }); } }, actions: { selectHighlightedItem({ context, prop, event, computed }) { const value = event.value ?? context.get("highlightedValue"); if (value == null) return; const selection = computed("selection"); const collection2 = prop("collection"); if (event.shiftKey && computed("multiple") && event.anchorValue) { const next = selection.extendSelection(collection2, event.anchorValue, value); invokeOnSelect(selection, next, prop("onSelect")); context.set("value", Array.from(next)); } else { const next = selection.select(collection2, value, event.metaKey); invokeOnSelect(selection, next, prop("onSelect")); context.set("value", Array.from(next)); } }, selectWithKeyboard({ context, prop, event, computed }) { const selection = computed("selection"); const collection2 = prop("collection"); if (event.shiftKey && computed("multiple") && event.anchorValue) { const next = selection.extendSelection(collection2, event.anchorValue, event.value); invokeOnSelect(selection, next, prop("onSelect")); context.set("value", Array.from(next)); return; } if (prop("selectOnHighlight")) { const next = selection.replaceSelection(collection2, event.value); invokeOnSelect(selection, next, prop("onSelect")); context.set("value", Array.from(next)); } }, highlightItem({ context, event }) { context.set("highlightedValue", event.value); }, highlightMatchingItem({ context, prop, event, refs }) { const value = prop("collection").search(event.key, { state: refs.get("typeahead"), currentValue: context.get("highlightedValue") }); if (value == null) return; context.set("highlightedValue", value); }, setHighlightedItem({ context, event }) { context.set("highlightedValue", event.value); }, clearHighlightedItem({ context }) { context.set("highlightedValue", null); }, selectItem({ context, prop, event, computed }) { const collection2 = prop("collection"); const selection = computed("selection"); const next = selection.select(collection2, event.value); invokeOnSelect(selection, next, prop("onSelect")); context.set("value", Array.from(next)); }, clearItem({ context, event, computed }) { const selection = computed("selection"); const value = selection.deselect(event.value); context.set("value", Array.from(value)); }, setSelectedItems({ context, event }) { context.set("value", event.value); }, clearSelectedItems({ context }) { context.set("value", []); }, syncCollection({ context, prop, refs }) { const collection2 = prop("collection"); const highlightedItem = collection2.find(context.get("highlightedValue")); if (highlightedItem) context.set("highlightedItem", highlightedItem); const selectedItems = collection2.findMany(context.get("value")); context.set("selectedItems", selectedItems); const valueAsString = collection2.stringifyItems(selectedItems); context.set("valueAsString", valueAsString); const highlightedValue = syncHighlightedValue( collection2, refs.get("prevCollection"), context.get("highlightedValue") ); queueMicrotask(() => { context.set("highlightedValue", highlightedValue); refs.set("prevCollection", collection2); }); }, syncSelectedItems({ context, prop }) { const collection2 = prop("collection"); const prevSelectedItems = context.get("selectedItems"); const value = context.get("value"); const selectedItems = value.map((value2) => { const item = prevSelectedItems.find((item2) => collection2.getItemValue(item2) === value2); return item || collection2.find(value2); }); context.set("selectedItems", selectedItems); context.set("valueAsString", collection2.stringifyItems(selectedItems)); }, syncHighlightedItem({ context, prop }) { const collection2 = prop("collection"); const highlightedValue = context.get("highlightedValue"); const highlightedItem = highlightedValue ? collection2.find(highlightedValue) : null; context.set("highlightedItem", highlightedItem); }, setFocused({ context }) { context.set("focused", true); }, clearFocused({ context }) { context.set("focused", false); } } } }); var diff = (a, b) => { const result = new Set(a); for (const item of b) result.delete(item); return result; }; function invokeOnSelect(current, next, onSelect) { const added = diff(next, current); for (const item of added) { onSelect?.({ value: item }); } } function syncHighlightedValue(collection2, prevCollection, highlightedValue) { if (highlightedValue != null && !collection2.find(highlightedValue) && prevCollection) { const startIndex = prevCollection.indexOf(highlightedValue); const prevItems = [...prevCollection.items]; const items = [...collection2.items]; const diff2 = (prevItems?.length ?? 0) - (items?.length ?? 0); let index = Math.min( diff2 > 1 ? Math.max((startIndex ?? 0) - diff2 + 1, 0) : startIndex ?? 0, (items?.length ?? 0) - 1 ); let newValue = null; let isReverseSearching = false; while (index >= 0) { if (!collection2.getItemDisabled(items[index])) { newValue = collection2.getItemValue(items[index]); break; } if (index < items.length - 1 && !isReverseSearching) { index++; } else { isReverseSearching = true; if (index > (startIndex ?? 0)) { index = startIndex ?? 0; } index--; } } return newValue; } return null; } var props = createProps()([ "collection", "defaultHighlightedValue", "defaultValue", "dir", "disabled", "deselectable", "disallowSelectAll", "getRootNode", "highlightedValue", "id", "ids", "loopFocus", "onHighlightChange", "onSelect", "onValueChange", "orientation", "scrollToIndexFn", "selectionMode", "selectOnHighlight", "typeahead", "value" ]); var splitProps = createSplitProps2(props); var itemProps = createProps()(["item", "highlightOnHover"]); var splitItemProps = createSplitProps2(itemProps); var itemGroupProps = createProps()(["id"]); var splitItemGroupProps = createSplitProps2(itemGroupProps); var itemGroupLabelProps = createProps()(["htmlFor"]); var splitItemGroupLabelProps = createSplitProps2(itemGroupLabelProps); // src/components/listbox/use-listbox.ts import { normalizeProps, useMachine } from "@zag-js/solid"; import { createMemo, createUniqueId as createUniqueId2 } from "solid-js"; var useListbox = (props2) => { const id = createUniqueId2(); const locale = useLocaleContext(); const environment = useEnvironmentContext(); const machineProps = createMemo(() => ({ id, dir: locale().dir, getRootNode: environment().getRootNode, ...runIfFn(props2) })); const service = useMachine(machine, machineProps); return createMemo(() => connect(service, normalizeProps)); }; // src/components/listbox/listbox-root.tsx var ListboxRoot = (props2) => { const [useListboxProps, localProps] = createSplitProps()(props2, [ "collection", "defaultHighlightedValue", "defaultValue", "deselectable", "disabled", "disallowSelectAll", "highlightedValue", "id", "ids", "loopFocus", "onHighlightChange", "onSelect", "onValueChange", "orientation", "scrollToIndexFn", "selectionMode", "selectOnHighlight", "typeahead", "value" ]); const listbox = useListbox(useListboxProps); const mergedProps = mergeProps9(() => listbox().getRootProps(), localProps); return <ListboxProvider value={listbox}> <ark.div {...mergedProps} /> </ListboxProvider>; }; // src/components/listbox/listbox-root-provider.tsx import { mergeProps as mergeProps10 } from "@zag-js/solid"; var ListboxRootProvider = (props2) => { const [{ value: listbox }, localProps] = createSplitProps()(props2, ["value"]); const mergedProps = mergeProps10(() => listbox().getRootProps(), localProps); return <ListboxProvider value={listbox}> <ark.div {...mergedProps} /> </ListboxProvider>; }; // src/components/listbox/listbox-value-text.tsx import { mergeProps as mergeProps11 } from "@zag-js/solid"; import { children } from "solid-js"; var ListboxValueText = (props2) => { const { placeholder, ...localprops } = props2; const listbox = useListboxContext(); const mergedProps = mergeProps11(() => listbox().getValueTextProps(), localprops); const resolved = children(() => props2.children); return <ark.span {...mergedProps}>{resolved() || listbox().valueAsString || placeholder}</ark.span>; }; // src/components/listbox/listbox.ts var listbox_exports = {}; __export(listbox_exports, { Content: () => ListboxContent, Context: () => ListboxContext, Input: () => ListboxInput, Item: () => ListboxItem, ItemGroup: () => ListboxItemGroup, ItemGroupLabel: () => ListboxItemGroupLabel, ItemIndicator: () => ListboxItemIndicator, ItemText: () => ListboxItemText, Label: () => ListboxLabel, Root: () => ListboxRoot, RootProvider: () => ListboxRootProvider, ValueText: () => ListboxValueText }); export { useListboxContext, ListboxContext, ListboxContent, ListboxInput, useListboxItemContext, ListboxItem, ListboxItemGroup, ListboxItemGroupLabel, ListboxItemIndicator, ListboxItemText, ListboxLabel, anatomy, useListbox, ListboxRoot, ListboxRootProvider, ListboxValueText, listbox_exports };