@pdanpdan/headless-combobox-react 0.0.0-stage → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # @pdanpdan/headless-combobox-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Accessible, renderless combobox for React. The state machine comes from [`@pdanpdan/headless-combobox-core`](../headless-combobox-core); this package adds React state synchronization and event-name mapping.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @pdanpdan/headless-combobox-react
9
+ ```
10
+
11
+ `react@>=18` is a peer dependency.
12
+
13
+ ## Usage
14
+
15
+ ```tsx
16
+ import { HeadlessCombobox, toReactProps } from '@pdanpdan/headless-combobox-react';
17
+ import { useState } from 'react';
18
+
19
+ const users = [
20
+ { id: 1, name: 'Wade Cooper' },
21
+ { id: 2, name: 'Arlene Mccoy' },
22
+ ];
23
+
24
+ export function Example() {
25
+ const [ value, setValue ] = useState<typeof users[ number ] | null>(null);
26
+
27
+ return (
28
+ <HeadlessCombobox
29
+ options={users}
30
+ optionLabel={(user) => user.name}
31
+ value={value}
32
+ onChange={(next) => setValue(next as typeof users[ number ] | null)}
33
+ >
34
+ {(scope) => (
35
+ <div ref={scope.setContainerRef}>
36
+ <button ref={scope.setTriggerRef} type="button" {...toReactProps(scope.triggerProps)}>
37
+ {value?.name ?? 'Select…'}
38
+ </button>
39
+ <ul ref={scope.setDropdownRef} {...toReactProps(scope.listboxProps)}>
40
+ {scope.filteredOptions.map((user, index) => (
41
+ <li
42
+ key={user.id}
43
+ ref={(el) => scope.setOptionRef(user, el)}
44
+ {...toReactProps(scope.getOptionProps(user, index))}
45
+ >
46
+ {user.name}
47
+ </li>
48
+ ))}
49
+ </ul>
50
+ </div>
51
+ )}
52
+ </HeadlessCombobox>
53
+ );
54
+ }
55
+ ```
56
+
57
+ - `value` + `onChange` for controlled usage; omit `value` and pass `defaultValue` for uncontrolled.
58
+ - `toReactProps` maps the core's `onKeydown` / `onMousedown` / `onMousemove` handlers to React's `onKeyDown` / `onMouseDown` / `onMouseMove`.
59
+ - `useHeadlessCombobox(options)` returns the same scope without the component wrapper.
60
+
61
+ The same focus, filtering, validation, and keyboard behavior is tested once in the core and shared with every adapter.
@@ -0,0 +1,13 @@
1
+ import { UseHeadlessComboboxOptions } from './useHeadlessCombobox';
2
+ import { HeadlessComboboxSnapshot } from '../../headless-combobox-core/src/index.ts';
3
+ import { ReactNode } from 'react';
4
+ /** Props for the render-prop component: hook options plus a scope renderer. */
5
+ export interface HeadlessComboboxProps<O, V = O, Q = string> extends UseHeadlessComboboxOptions<O, V, Q> {
6
+ children: (scope: HeadlessComboboxSnapshot<O, V, Q>) => ReactNode;
7
+ }
8
+ /**
9
+ * Render-prop wrapper around {@link useHeadlessCombobox}. Prefer the hook when
10
+ * the markup does not need to be nested under a component.
11
+ */
12
+ export declare function HeadlessCombobox<O, V = O, Q = string>(props: HeadlessComboboxProps<O, V, Q>): ReactNode;
13
+ //# sourceMappingURL=HeadlessCombobox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HeadlessCombobox.d.ts","sourceRoot":"","sources":["../src/HeadlessCombobox.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACxE,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AACjF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAIvC,+EAA+E;AAC/E,MAAM,WAAW,qBAAqB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CACzD,SAAQ,0BAA0B,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IAC3C,QAAQ,EAAE,CAAC,KAAK,EAAE,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC;CACnE;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EACnD,KAAK,EAAE,qBAAqB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GACpC,SAAS,CAGX"}
package/dist/index.cjs ADDED
@@ -0,0 +1,2 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("@pdanpdan/headless-combobox-core"),t=require("react");var n=[`options`,`multiple`,`minLength`,`maxLength`,`required`,`disabled`,`readonly`,`closeOnSelect`,`closeOnClickOutside`,`clickOutsideFilter`,`selectOnTab`,`optionValue`,`optionLabel`,`optionFilter`,`id`,`alignSelected`,`inputOnOpen`,`errorMessages`];function r(n){let r=`value`in n,[i,a]=(0,t.useState)(()=>n.defaultValue??null),s=r?n.value??null:i,c=(0,t.useRef)(n);c.current=n;let l=(0,t.useRef)(r);l.current=r;let u=(0,t.useId)(),d=(0,t.useRef)(null),f=(0,t.useRef)([]),[,p]=(0,t.useReducer)(e=>e+1,0);d.current=()=>{let{promise:e,resolve:t}=Promise.withResolvers();return f.current.push(t),p(),e};let[m]=(0,t.useState)(()=>(0,e.createCombobox)({props:o(c.current,s),onChange:e=>{l.current||a(e),c.current.onChange?.(e)},runtime:{nextTick:()=>d.current(),createId:()=>u}})),h=(0,t.useSyncExternalStore)(m.subscribe,m.getSnapshot,m.getSnapshot);return(0,t.useEffect)(()=>{m.setProps(o(c.current,s))}),(0,t.useEffect)(()=>{let e=f.current;f.current=[];for(let t of e)t()}),(0,t.useEffect)(()=>(m.mount(),()=>m.destroy()),[m]),h}var i={onKeydown:`onKeyDown`,onMousedown:`onMouseDown`,onMousemove:`onMouseMove`};function a(e){let t={};for(let[n,r]of Object.entries(e))t[i[n]??n]=r;return t}function o(e,t){let r={};for(let t of n)r[t]=e[t];return r.modelValue=t,r}function s(e){let t=r(e);return e.children(t)}exports.HeadlessCombobox=s,exports.toReactProps=a,exports.useHeadlessCombobox=r;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["useState","useRef","useId","useReducer","createCombobox","useSyncExternalStore","_pdanpdan_headless_combobox_core","react","CORE_PROP_KEYS","useHeadlessCombobox","controlled","options","uncontrolled","setUncontrolled","modelValue","optionsRef","controlledRef","id","tickRef","resolversRef","forceRender","n","resolve","promise","store","toCoreProps","value","snapshot","resolvers","REACT_EVENT_NAMES","toReactProps","adapted","key","props","resolved","HeadlessCombobox","scope"],"sources":["../src/useHeadlessCombobox.ts","../src/HeadlessCombobox.tsx"],"sourcesContent":["import type {\n HeadlessComboboxProps as CoreComboboxProps,\n HeadlessComboboxSnapshot,\n} from '@pdanpdan/headless-combobox-core';\n\nimport { createCombobox } from '@pdanpdan/headless-combobox-core';\nimport {\n useEffect,\n useId,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\n/** Options accepted by the React hook and component. */\nexport type UseHeadlessComboboxOptions<O, V = O, Q = string>\n = Omit<CoreComboboxProps<O, V, Q>, 'modelValue'> & {\n /** Controlled value (`value` present) or omit for uncontrolled. */\n value?: V | V[] | null;\n /** Initial value for uncontrolled usage. */\n defaultValue?: V | V[] | null;\n /** Called for every selection change. */\n onChange?: (value: V | V[] | null) => void;\n };\n\nconst CORE_PROP_KEYS = [\n 'options',\n 'multiple',\n 'minLength',\n 'maxLength',\n 'required',\n 'disabled',\n 'readonly',\n 'closeOnSelect',\n 'closeOnClickOutside',\n 'clickOutsideFilter',\n 'selectOnTab',\n 'optionValue',\n 'optionLabel',\n 'optionFilter',\n 'id',\n 'alignSelected',\n 'inputOnOpen',\n 'errorMessages',\n] as const;\n\n/**\n * React adapter for the framework-independent combobox core.\n *\n * State is read through `useSyncExternalStore`, so any `select`/`open`/`close`\n * call (from this hook or a child) re-renders the component tree.\n */\nexport function useHeadlessCombobox<O, V = O, Q = string>(\n options: UseHeadlessComboboxOptions<O, V, Q>,\n): HeadlessComboboxSnapshot<O, V, Q> {\n const controlled = 'value' in options;\n const [ uncontrolled, setUncontrolled ] = useState<V | V[] | null>(() => options.defaultValue ?? null);\n const modelValue = controlled\n ? (options.value ?? null)\n : uncontrolled;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const controlledRef = useRef(controlled);\n controlledRef.current = controlled;\n\n const id = useId();\n const tickRef = useRef<(() => Promise<void>) | null>(null);\n const resolversRef = useRef<Array<() => void>>([]);\n const [ , forceRender ] = useReducer((n: number) => n + 1, 0);\n\n // Resolve the next tick after React has committed the DOM. A forced render\n // guarantees a layout effect even when the state change produced no new\n // store snapshot (e.g. only a DOM ref was involved).\n tickRef.current = () => {\n const { promise, resolve } = Promise.withResolvers<void>();\n resolversRef.current.push(resolve);\n forceRender();\n return promise;\n };\n\n const [ store ] = useState(() => createCombobox<O, V, Q>({\n props: toCoreProps(optionsRef.current, modelValue),\n onChange: (value) => {\n if (!controlledRef.current) {\n setUncontrolled(value);\n }\n optionsRef.current.onChange?.(value);\n },\n runtime: {\n nextTick: () => tickRef.current!(),\n createId: () => id,\n },\n }));\n\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n\n // Push each render's props into the core. The store no-ops when shallow-equal.\n useEffect(() => {\n store.setProps(toCoreProps(optionsRef.current, modelValue));\n });\n\n useEffect(() => {\n const resolvers = resolversRef.current;\n resolversRef.current = [];\n for (const resolve of resolvers) {\n resolve();\n }\n });\n\n useEffect(() => {\n store.mount();\n return () => store.destroy();\n }, [ store ]);\n\n return snapshot;\n}\n\nconst REACT_EVENT_NAMES: Record<string, string> = {\n onKeydown: 'onKeyDown',\n onMousedown: 'onMouseDown',\n onMousemove: 'onMouseMove',\n};\n\n/**\n * Adapt a core ARIA prop bag to React's event prop names:\n *\n * ```tsx\n * <button {...toReactProps(scope.triggerProps)} />\n * ```\n */\nexport function toReactProps<T extends object>(props: T): Record<string, unknown> {\n const adapted: Record<string, unknown> = {};\n for (const [ key, value ] of Object.entries(props)) {\n adapted[ REACT_EVENT_NAMES[ key ] ?? key ] = value;\n }\n return adapted;\n}\n\nfunction toCoreProps<O, V, Q>(\n options: UseHeadlessComboboxOptions<O, V, Q>,\n modelValue: V | V[] | null,\n): CoreComboboxProps<O, V, Q> {\n const resolved: Record<string, unknown> = {};\n for (const key of CORE_PROP_KEYS) {\n resolved[ key ] = options[ key ];\n }\n resolved.modelValue = modelValue;\n return resolved as unknown as CoreComboboxProps<O, V, Q>;\n}\n","import type { UseHeadlessComboboxOptions } from './useHeadlessCombobox';\nimport type { HeadlessComboboxSnapshot } from '@pdanpdan/headless-combobox-core';\nimport type { ReactNode } from 'react';\n\nimport { useHeadlessCombobox } from './useHeadlessCombobox';\n\n/** Props for the render-prop component: hook options plus a scope renderer. */\nexport interface HeadlessComboboxProps<O, V = O, Q = string>\n extends UseHeadlessComboboxOptions<O, V, Q> {\n children: (scope: HeadlessComboboxSnapshot<O, V, Q>) => ReactNode;\n}\n\n/**\n * Render-prop wrapper around {@link useHeadlessCombobox}. Prefer the hook when\n * the markup does not need to be nested under a component.\n */\nexport function HeadlessCombobox<O, V = O, Q = string>(\n props: HeadlessComboboxProps<O, V, Q>,\n): ReactNode {\n const scope = useHeadlessCombobox<O, V, Q>(props);\n return props.children(scope);\n}\n"],"mappings":"A,wIA0BA,IAAMQ,EAAiB,CACrB,UACA,WACA,YACA,YACA,WACA,WACA,WACA,gBACA,sBACA,qBACA,cACA,cACA,cACA,eACA,KACA,gBACA,cACA,eACF,EAQA,SAAgBC,EACd,EACmC,CACnC,IAAMC,EAAa,UAAWC,EACxB,CAAEC,EAAcC,IAAA,EAAoBb,EAAAA,SAAAA,KAA+BW,EAAQ,cAAgB,IAAI,EAC/FG,EAAaJ,EACdC,EAAQ,OAAS,KAClBC,EAEEG,GAAA,EAAad,EAAAA,OAAAA,CAAOU,CAAO,EACjC,EAAW,QAAUA,EACrB,IAAMK,GAAA,EAAgBf,EAAAA,OAAAA,CAAOS,CAAU,EACvC,EAAc,QAAUA,EAExB,IAAMO,GAAA,EAAKf,EAAAA,MAAAA,CAAM,EACXgB,GAAA,EAAUjB,EAAAA,OAAAA,CAAqC,IAAI,EACnDkB,GAAA,EAAelB,EAAAA,OAAAA,CAA0B,CAAC,CAAC,EAC3C,EAAImB,IAAA,EAAgBjB,EAAAA,WAAAA,CAAY,GAAckB,EAAI,EAAG,CAAC,EAK5D,EAAQ,YAAgB,CACtB,GAAM,CAAE,UAAS,WAAY,QAAQ,cAAoB,EAGzD,OAFAF,EAAa,QAAQ,KAAKG,CAAO,EACjCF,EAAY,EACLG,CACT,EAEA,GAAM,CAAEC,IAAA,EAAUxB,EAAAA,SAAAA,MAAAA,EAAeI,EAAAA,eAAAA,CAAwB,CACvD,MAAOqB,EAAYV,EAAW,QAASD,CAAU,EACjD,SAAW,GAAU,CACdE,EAAc,SACjBH,EAAgBa,CAAK,EAEvBX,EAAW,QAAQ,WAAWW,CAAK,CACrC,EACA,QAAS,CACP,aAAgBR,EAAQ,QAAS,EACjC,aAAgBD,CAClB,CACF,CAAC,CAAC,EAEIU,GAAA,EAAWtB,EAAAA,qBAAAA,CACfmB,EAAM,UACNA,EAAM,YACNA,EAAM,WACR,EAoBA,OAjBA,EAAAjB,EAAA,UAAA,KAAgB,CACdiB,EAAM,SAASC,EAAYV,EAAW,QAASD,CAAU,CAAC,CAC5D,CAAC,GAED,EAAAP,EAAA,UAAA,KAAgB,CACd,IAAMqB,EAAYT,EAAa,QAC/B,EAAa,QAAU,CAAC,EACxB,IAAK,IAAMG,KAAWM,EACpBN,EAAQ,CAEZ,CAAC,GAED,EAAAf,EAAA,UAAA,MACEiB,EAAM,MAAM,MACCA,EAAM,QAAQ,GAC1B,CAAEA,CAAM,CAAC,EAELG,CACT,CAEA,IAAME,EAA4C,CAChD,UAAW,YACX,YAAa,cACb,YAAa,aACf,EASA,SAAgBC,EAA+B,EAAmC,CAChF,IAAMC,EAAmC,CAAC,EAC1C,IAAK,GAAM,CAAEC,EAAKN,KAAW,OAAO,QAAQO,CAAK,EAC/C,EAASJ,EAAmBG,IAASA,GAAQN,EAE/C,OAAOK,CACT,CAEA,SAASN,EACP,EACA,EAC4B,CAC5B,IAAMS,EAAoC,CAAC,EAC3C,IAAK,IAAMF,KAAOxB,EAChB,EAAUwB,GAAQrB,EAASqB,GAG7B,MADA,GAAS,WAAalB,EACfoB,CACT,CC1IA,SAAgBC,EACd,EACW,CACX,IAAMC,EAAQ3B,EAA6BwB,CAAK,EAChD,OAAOA,EAAM,SAASG,CAAK,CAC7B,C"}
@@ -0,0 +1,6 @@
1
+ export type { HeadlessComboboxComboboxInputProps, HeadlessComboboxErrorCode, HeadlessComboboxInputProps, HeadlessComboboxListboxProps, HeadlessComboboxOptionProps, HeadlessComboboxPopupStyle, HeadlessComboboxSnapshot, HeadlessComboboxTriggerProps, } from '../../headless-combobox-core/src/index.ts';
2
+ export type { UseHeadlessComboboxOptions } from './useHeadlessCombobox';
3
+ export type { HeadlessComboboxProps } from './HeadlessCombobox';
4
+ export { HeadlessCombobox } from './HeadlessCombobox';
5
+ export { toReactProps, useHeadlessCombobox } from './useHeadlessCombobox';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,kCAAkC,EAClC,yBAAyB,EACzB,0BAA0B,EAC1B,4BAA4B,EAC5B,2BAA2B,EAC3B,0BAA0B,EAC1B,wBAAwB,EACxB,4BAA4B,GAC7B,MAAM,kCAAkC,CAAC;AAC1C,YAAY,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACxE,YAAY,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAEhE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,74 @@
1
+ import { createCombobox as e } from "@pdanpdan/headless-combobox-core";
2
+ import { useEffect as t, useId as n, useReducer as r, useRef as i, useState as a, useSyncExternalStore as o } from "react";
3
+ // src/useHeadlessCombobox.ts
4
+ var s = [
5
+ "options",
6
+ "multiple",
7
+ "minLength",
8
+ "maxLength",
9
+ "required",
10
+ "disabled",
11
+ "readonly",
12
+ "closeOnSelect",
13
+ "closeOnClickOutside",
14
+ "clickOutsideFilter",
15
+ "selectOnTab",
16
+ "optionValue",
17
+ "optionLabel",
18
+ "optionFilter",
19
+ "id",
20
+ "alignSelected",
21
+ "inputOnOpen",
22
+ "errorMessages"
23
+ ];
24
+ function c(s) {
25
+ let c = "value" in s, [l, u] = a(() => s.defaultValue ?? null), f = c ? s.value ?? null : l, p = i(s);
26
+ p.current = s;
27
+ let m = i(c);
28
+ m.current = c;
29
+ let h = n(), g = i(null), _ = i([]), [, v] = r((e) => e + 1, 0);
30
+ g.current = () => {
31
+ let { promise: e, resolve: t } = Promise.withResolvers();
32
+ return _.current.push(t), v(), e;
33
+ };
34
+ let [y] = a(() => e({
35
+ props: d(p.current, f),
36
+ onChange: (e) => {
37
+ m.current || u(e), p.current.onChange?.(e);
38
+ },
39
+ runtime: {
40
+ nextTick: () => g.current(),
41
+ createId: () => h
42
+ }
43
+ })), b = o(y.subscribe, y.getSnapshot, y.getSnapshot);
44
+ return t(() => {
45
+ y.setProps(d(p.current, f));
46
+ }), t(() => {
47
+ let e = _.current;
48
+ _.current = [];
49
+ for (let t of e) t();
50
+ }), t(() => (y.mount(), () => y.destroy()), [y]), b;
51
+ }
52
+ var l = {
53
+ onKeydown: "onKeyDown",
54
+ onMousedown: "onMouseDown",
55
+ onMousemove: "onMouseMove"
56
+ };
57
+ function u(e) {
58
+ let t = {};
59
+ for (let [n, r] of Object.entries(e)) t[l[n] ?? n] = r;
60
+ return t;
61
+ }
62
+ function d(e, t) {
63
+ let n = {};
64
+ for (let t of s) n[t] = e[t];
65
+ return n.modelValue = t, n;
66
+ }
67
+ // src/HeadlessCombobox.tsx
68
+ function f(e) {
69
+ let t = c(e);
70
+ return e.children(t);
71
+ }
72
+ export { f as HeadlessCombobox, u as toReactProps, c as useHeadlessCombobox };
73
+
74
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["CORE_PROP_KEYS","useHeadlessCombobox","controlled","options","uncontrolled","setUncontrolled","useState","modelValue","optionsRef","useRef","controlledRef","id","useId","tickRef","resolversRef","forceRender","useReducer","n","resolve","promise","store","createCombobox","toCoreProps","value","snapshot","useSyncExternalStore","useEffect","resolvers","REACT_EVENT_NAMES","toReactProps","adapted","key","props","resolved","HeadlessCombobox","scope"],"sources":["../src/useHeadlessCombobox.ts","../src/HeadlessCombobox.tsx"],"sourcesContent":["import type {\n HeadlessComboboxProps as CoreComboboxProps,\n HeadlessComboboxSnapshot,\n} from '@pdanpdan/headless-combobox-core';\n\nimport { createCombobox } from '@pdanpdan/headless-combobox-core';\nimport {\n useEffect,\n useId,\n useReducer,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\n\n/** Options accepted by the React hook and component. */\nexport type UseHeadlessComboboxOptions<O, V = O, Q = string>\n = Omit<CoreComboboxProps<O, V, Q>, 'modelValue'> & {\n /** Controlled value (`value` present) or omit for uncontrolled. */\n value?: V | V[] | null;\n /** Initial value for uncontrolled usage. */\n defaultValue?: V | V[] | null;\n /** Called for every selection change. */\n onChange?: (value: V | V[] | null) => void;\n };\n\nconst CORE_PROP_KEYS = [\n 'options',\n 'multiple',\n 'minLength',\n 'maxLength',\n 'required',\n 'disabled',\n 'readonly',\n 'closeOnSelect',\n 'closeOnClickOutside',\n 'clickOutsideFilter',\n 'selectOnTab',\n 'optionValue',\n 'optionLabel',\n 'optionFilter',\n 'id',\n 'alignSelected',\n 'inputOnOpen',\n 'errorMessages',\n] as const;\n\n/**\n * React adapter for the framework-independent combobox core.\n *\n * State is read through `useSyncExternalStore`, so any `select`/`open`/`close`\n * call (from this hook or a child) re-renders the component tree.\n */\nexport function useHeadlessCombobox<O, V = O, Q = string>(\n options: UseHeadlessComboboxOptions<O, V, Q>,\n): HeadlessComboboxSnapshot<O, V, Q> {\n const controlled = 'value' in options;\n const [ uncontrolled, setUncontrolled ] = useState<V | V[] | null>(() => options.defaultValue ?? null);\n const modelValue = controlled\n ? (options.value ?? null)\n : uncontrolled;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n const controlledRef = useRef(controlled);\n controlledRef.current = controlled;\n\n const id = useId();\n const tickRef = useRef<(() => Promise<void>) | null>(null);\n const resolversRef = useRef<Array<() => void>>([]);\n const [ , forceRender ] = useReducer((n: number) => n + 1, 0);\n\n // Resolve the next tick after React has committed the DOM. A forced render\n // guarantees a layout effect even when the state change produced no new\n // store snapshot (e.g. only a DOM ref was involved).\n tickRef.current = () => {\n const { promise, resolve } = Promise.withResolvers<void>();\n resolversRef.current.push(resolve);\n forceRender();\n return promise;\n };\n\n const [ store ] = useState(() => createCombobox<O, V, Q>({\n props: toCoreProps(optionsRef.current, modelValue),\n onChange: (value) => {\n if (!controlledRef.current) {\n setUncontrolled(value);\n }\n optionsRef.current.onChange?.(value);\n },\n runtime: {\n nextTick: () => tickRef.current!(),\n createId: () => id,\n },\n }));\n\n const snapshot = useSyncExternalStore(\n store.subscribe,\n store.getSnapshot,\n store.getSnapshot,\n );\n\n // Push each render's props into the core. The store no-ops when shallow-equal.\n useEffect(() => {\n store.setProps(toCoreProps(optionsRef.current, modelValue));\n });\n\n useEffect(() => {\n const resolvers = resolversRef.current;\n resolversRef.current = [];\n for (const resolve of resolvers) {\n resolve();\n }\n });\n\n useEffect(() => {\n store.mount();\n return () => store.destroy();\n }, [ store ]);\n\n return snapshot;\n}\n\nconst REACT_EVENT_NAMES: Record<string, string> = {\n onKeydown: 'onKeyDown',\n onMousedown: 'onMouseDown',\n onMousemove: 'onMouseMove',\n};\n\n/**\n * Adapt a core ARIA prop bag to React's event prop names:\n *\n * ```tsx\n * <button {...toReactProps(scope.triggerProps)} />\n * ```\n */\nexport function toReactProps<T extends object>(props: T): Record<string, unknown> {\n const adapted: Record<string, unknown> = {};\n for (const [ key, value ] of Object.entries(props)) {\n adapted[ REACT_EVENT_NAMES[ key ] ?? key ] = value;\n }\n return adapted;\n}\n\nfunction toCoreProps<O, V, Q>(\n options: UseHeadlessComboboxOptions<O, V, Q>,\n modelValue: V | V[] | null,\n): CoreComboboxProps<O, V, Q> {\n const resolved: Record<string, unknown> = {};\n for (const key of CORE_PROP_KEYS) {\n resolved[ key ] = options[ key ];\n }\n resolved.modelValue = modelValue;\n return resolved as unknown as CoreComboboxProps<O, V, Q>;\n}\n","import type { UseHeadlessComboboxOptions } from './useHeadlessCombobox';\nimport type { HeadlessComboboxSnapshot } from '@pdanpdan/headless-combobox-core';\nimport type { ReactNode } from 'react';\n\nimport { useHeadlessCombobox } from './useHeadlessCombobox';\n\n/** Props for the render-prop component: hook options plus a scope renderer. */\nexport interface HeadlessComboboxProps<O, V = O, Q = string>\n extends UseHeadlessComboboxOptions<O, V, Q> {\n children: (scope: HeadlessComboboxSnapshot<O, V, Q>) => ReactNode;\n}\n\n/**\n * Render-prop wrapper around {@link useHeadlessCombobox}. Prefer the hook when\n * the markup does not need to be nested under a component.\n */\nexport function HeadlessCombobox<O, V = O, Q = string>(\n props: HeadlessComboboxProps<O, V, Q>,\n): ReactNode {\n const scope = useHeadlessCombobox<O, V, Q>(props);\n return props.children(scope);\n}\n"],"mappings":";;;AA0BA,IAAMA,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAQA,SAAgBC,EACd,GACmC;CACnC,IAAMC,IAAa,WAAWC,GACxB,CAAEC,GAAcC,KAAoBC,QAA+BH,EAAQ,gBAAgB,IAAI,GAC/FI,IAAaL,IACdC,EAAQ,SAAS,OAClBC,GAEEI,IAAaC,EAAON,CAAO;CACjC,EAAW,UAAUA;CACrB,IAAMO,IAAgBD,EAAOP,CAAU;CACvC,EAAc,UAAUA;CAExB,IAAMS,IAAKC,EAAM,GACXC,IAAUJ,EAAqC,IAAI,GACnDK,IAAeL,EAA0B,CAAC,CAAC,GAC3C,GAAIM,KAAgBC,GAAY,MAAcC,IAAI,GAAG,CAAC;CAK5D,EAAQ,gBAAgB;EACtB,IAAM,EAAE,YAAS,eAAY,QAAQ,cAAoB;EAGzD,OAFAH,EAAa,QAAQ,KAAKI,CAAO,GACjCH,EAAY,GACLI;CACT;CAEA,IAAM,CAAEC,KAAUd,QAAee,EAAwB;EACvD,OAAOC,EAAYd,EAAW,SAASD,CAAU;EACjD,WAAW,MAAU;GAInB,AAHKG,EAAc,WACjBL,EAAgBkB,CAAK,GAEvBf,EAAW,QAAQ,WAAWe,CAAK;EACrC;EACA,SAAS;GACP,gBAAgBV,EAAQ,QAAS;GACjC,gBAAgBF;EAClB;CACF,CAAC,CAAC,GAEIa,IAAWC,EACfL,EAAM,WACNA,EAAM,aACNA,EAAM,WACR;CAoBA,OAjBAM,QAAgB;EACd,EAAM,SAASJ,EAAYd,EAAW,SAASD,CAAU,CAAC;CAC5D,CAAC,GAEDmB,QAAgB;EACd,IAAMC,IAAYb,EAAa;EAC/B,EAAa,UAAU,CAAC;EACxB,KAAK,IAAMI,KAAWS,GACpB,EAAQ;CAEZ,CAAC,GAEDD,SACEN,EAAM,MAAM,SACCA,EAAM,QAAQ,IAC1B,CAAEA,CAAM,CAAC,GAELI;AACT;AAEA,IAAMI,IAA4C;CAChD,WAAW;CACX,aAAa;CACb,aAAa;AACf;AASA,SAAgBC,EAA+B,GAAmC;CAChF,IAAMC,IAAmC,CAAC;CAC1C,KAAK,IAAM,CAAEC,GAAKR,MAAW,OAAO,QAAQS,CAAK,GAC/C,EAASJ,EAAmBG,MAASA,KAAQR;CAE/C,OAAOO;AACT;AAEA,SAASR,EACP,GACA,GAC4B;CAC5B,IAAMW,IAAoC,CAAC;CAC3C,KAAK,IAAMF,KAAO/B,GAChB,EAAU+B,KAAQ5B,EAAS4B;CAG7B,OADA,EAAS,aAAaxB,GACf0B;AACT;;AC1IA,SAAgBC,EACd,GACW;CACX,IAAMC,IAAQlC,EAA6B+B,CAAK;CAChD,OAAOA,EAAM,SAASG,CAAK;AAC7B"}
@@ -0,0 +1,26 @@
1
+ import { HeadlessComboboxProps as CoreComboboxProps, HeadlessComboboxSnapshot } from '../../headless-combobox-core/src/index.ts';
2
+ /** Options accepted by the React hook and component. */
3
+ export type UseHeadlessComboboxOptions<O, V = O, Q = string> = Omit<CoreComboboxProps<O, V, Q>, 'modelValue'> & {
4
+ /** Controlled value (`value` present) or omit for uncontrolled. */
5
+ value?: V | V[] | null;
6
+ /** Initial value for uncontrolled usage. */
7
+ defaultValue?: V | V[] | null;
8
+ /** Called for every selection change. */
9
+ onChange?: (value: V | V[] | null) => void;
10
+ };
11
+ /**
12
+ * React adapter for the framework-independent combobox core.
13
+ *
14
+ * State is read through `useSyncExternalStore`, so any `select`/`open`/`close`
15
+ * call (from this hook or a child) re-renders the component tree.
16
+ */
17
+ export declare function useHeadlessCombobox<O, V = O, Q = string>(options: UseHeadlessComboboxOptions<O, V, Q>): HeadlessComboboxSnapshot<O, V, Q>;
18
+ /**
19
+ * Adapt a core ARIA prop bag to React's event prop names:
20
+ *
21
+ * ```tsx
22
+ * <button {...toReactProps(scope.triggerProps)} />
23
+ * ```
24
+ */
25
+ export declare function toReactProps<T extends object>(props: T): Record<string, unknown>;
26
+ //# sourceMappingURL=useHeadlessCombobox.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useHeadlessCombobox.d.ts","sourceRoot":"","sources":["../src/useHeadlessCombobox.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,IAAI,iBAAiB,EAC1C,wBAAwB,EACzB,MAAM,kCAAkC,CAAC;AAY1C,wDAAwD;AACxD,MAAM,MAAM,0BAA0B,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,IACvD,IAAI,CAAC,iBAAiB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,EAAE,YAAY,CAAC,GAAG;IACjD,mEAAmE;IACnE,KAAK,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC;IACvB,4CAA4C;IAC5C,YAAY,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC;IAC9B,yCAAyC;IACzC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,IAAI,KAAK,IAAI,CAAC;CAC5C,CAAC;AAuBJ;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,EACtD,OAAO,EAAE,0BAA0B,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,GAC3C,wBAAwB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAkEnC;AAQD;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAMhF"}
package/package.json CHANGED
@@ -1,6 +1,78 @@
1
1
  {
2
2
  "name": "@pdanpdan/headless-combobox-react",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "type": "module",
4
+ "version": "3.0.1",
5
+ "description": "Accessible renderless combobox for React, built on the framework-independent core",
6
+ "author": "Dan Popescu",
7
+ "license": "MIT",
8
+ "homepage": "https://pdanpdan.github.io/headless-components",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/pdanpdan/headless-components.git",
12
+ "directory": "packages/headless-combobox-react"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/pdanpdan/headless-components/issues"
16
+ },
17
+ "keywords": [
18
+ "react",
19
+ "combobox",
20
+ "headless",
21
+ "renderless",
22
+ "select",
23
+ "autocomplete",
24
+ "accessibility",
25
+ "typescript"
26
+ ],
27
+ "sideEffects": false,
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.mjs",
32
+ "require": "./dist/index.cjs"
33
+ },
34
+ "./source": {
35
+ "types": "./src/index.ts",
36
+ "import": "./src/index.ts"
37
+ }
38
+ },
39
+ "main": "./dist/index.cjs",
40
+ "module": "./dist/index.mjs",
41
+ "types": "./dist/index.d.ts",
42
+ "files": [
43
+ "dist",
44
+ "src"
45
+ ],
46
+ "peerDependencies": {
47
+ "react": ">=18.0.0"
48
+ },
49
+ "dependencies": {
50
+ "@pdanpdan/headless-combobox-core": "3.0.1"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public",
54
+ "registry": "https://registry.npmjs.org/"
55
+ },
56
+ "devDependencies": {
57
+ "@types/react": "^19.3.0",
58
+ "@types/react-dom": "^19.3.0",
59
+ "@vitest/coverage-v8": "^5.1.1",
60
+ "jsdom": "^31.0.1",
61
+ "react": "^19.3.1",
62
+ "react-dom": "^19.3.1",
63
+ "typescript": "^6.0.3",
64
+ "vite": "^8.3.8",
65
+ "vite-plugin-dts": "^5.1.2",
66
+ "vitest": "^5.1.1"
67
+ },
68
+ "scripts": {
69
+ "build": "vite build",
70
+ "lint": "pnpm --dir ../.. lint",
71
+ "test": "vitest run",
72
+ "test:watch": "vitest",
73
+ "test:coverage": "vitest run --coverage",
74
+ "typecheck": "tsc -p tsconfig.app.json --noEmit && tsc -p tsconfig.vitest.json --noEmit",
75
+ "test:all": "pnpm lint && pnpm typecheck && pnpm test",
76
+ "release:npm": "pnpm publish"
77
+ }
6
78
  }
@@ -0,0 +1,22 @@
1
+ import type { UseHeadlessComboboxOptions } from './useHeadlessCombobox';
2
+ import type { HeadlessComboboxSnapshot } from '@pdanpdan/headless-combobox-core';
3
+ import type { ReactNode } from 'react';
4
+
5
+ import { useHeadlessCombobox } from './useHeadlessCombobox';
6
+
7
+ /** Props for the render-prop component: hook options plus a scope renderer. */
8
+ export interface HeadlessComboboxProps<O, V = O, Q = string>
9
+ extends UseHeadlessComboboxOptions<O, V, Q> {
10
+ children: (scope: HeadlessComboboxSnapshot<O, V, Q>) => ReactNode;
11
+ }
12
+
13
+ /**
14
+ * Render-prop wrapper around {@link useHeadlessCombobox}. Prefer the hook when
15
+ * the markup does not need to be nested under a component.
16
+ */
17
+ export function HeadlessCombobox<O, V = O, Q = string>(
18
+ props: HeadlessComboboxProps<O, V, Q>,
19
+ ): ReactNode {
20
+ const scope = useHeadlessCombobox<O, V, Q>(props);
21
+ return props.children(scope);
22
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ export type {
2
+ HeadlessComboboxComboboxInputProps,
3
+ HeadlessComboboxErrorCode,
4
+ HeadlessComboboxInputProps,
5
+ HeadlessComboboxListboxProps,
6
+ HeadlessComboboxOptionProps,
7
+ HeadlessComboboxPopupStyle,
8
+ HeadlessComboboxSnapshot,
9
+ HeadlessComboboxTriggerProps,
10
+ } from '@pdanpdan/headless-combobox-core';
11
+ export type { UseHeadlessComboboxOptions } from './useHeadlessCombobox';
12
+ export type { HeadlessComboboxProps } from './HeadlessCombobox';
13
+
14
+ export { HeadlessCombobox } from './HeadlessCombobox';
15
+ export { toReactProps, useHeadlessCombobox } from './useHeadlessCombobox';
@@ -0,0 +1,155 @@
1
+ import type {
2
+ HeadlessComboboxProps as CoreComboboxProps,
3
+ HeadlessComboboxSnapshot,
4
+ } from '@pdanpdan/headless-combobox-core';
5
+
6
+ import { createCombobox } from '@pdanpdan/headless-combobox-core';
7
+ import {
8
+ useEffect,
9
+ useId,
10
+ useReducer,
11
+ useRef,
12
+ useState,
13
+ useSyncExternalStore,
14
+ } from 'react';
15
+
16
+ /** Options accepted by the React hook and component. */
17
+ export type UseHeadlessComboboxOptions<O, V = O, Q = string>
18
+ = Omit<CoreComboboxProps<O, V, Q>, 'modelValue'> & {
19
+ /** Controlled value (`value` present) or omit for uncontrolled. */
20
+ value?: V | V[] | null;
21
+ /** Initial value for uncontrolled usage. */
22
+ defaultValue?: V | V[] | null;
23
+ /** Called for every selection change. */
24
+ onChange?: (value: V | V[] | null) => void;
25
+ };
26
+
27
+ const CORE_PROP_KEYS = [
28
+ 'options',
29
+ 'multiple',
30
+ 'minLength',
31
+ 'maxLength',
32
+ 'required',
33
+ 'disabled',
34
+ 'readonly',
35
+ 'closeOnSelect',
36
+ 'closeOnClickOutside',
37
+ 'clickOutsideFilter',
38
+ 'selectOnTab',
39
+ 'optionValue',
40
+ 'optionLabel',
41
+ 'optionFilter',
42
+ 'id',
43
+ 'alignSelected',
44
+ 'inputOnOpen',
45
+ 'errorMessages',
46
+ ] as const;
47
+
48
+ /**
49
+ * React adapter for the framework-independent combobox core.
50
+ *
51
+ * State is read through `useSyncExternalStore`, so any `select`/`open`/`close`
52
+ * call (from this hook or a child) re-renders the component tree.
53
+ */
54
+ export function useHeadlessCombobox<O, V = O, Q = string>(
55
+ options: UseHeadlessComboboxOptions<O, V, Q>,
56
+ ): HeadlessComboboxSnapshot<O, V, Q> {
57
+ const controlled = 'value' in options;
58
+ const [ uncontrolled, setUncontrolled ] = useState<V | V[] | null>(() => options.defaultValue ?? null);
59
+ const modelValue = controlled
60
+ ? (options.value ?? null)
61
+ : uncontrolled;
62
+
63
+ const optionsRef = useRef(options);
64
+ optionsRef.current = options;
65
+ const controlledRef = useRef(controlled);
66
+ controlledRef.current = controlled;
67
+
68
+ const id = useId();
69
+ const tickRef = useRef<(() => Promise<void>) | null>(null);
70
+ const resolversRef = useRef<Array<() => void>>([]);
71
+ const [ , forceRender ] = useReducer((n: number) => n + 1, 0);
72
+
73
+ // Resolve the next tick after React has committed the DOM. A forced render
74
+ // guarantees a layout effect even when the state change produced no new
75
+ // store snapshot (e.g. only a DOM ref was involved).
76
+ tickRef.current = () => {
77
+ const { promise, resolve } = Promise.withResolvers<void>();
78
+ resolversRef.current.push(resolve);
79
+ forceRender();
80
+ return promise;
81
+ };
82
+
83
+ const [ store ] = useState(() => createCombobox<O, V, Q>({
84
+ props: toCoreProps(optionsRef.current, modelValue),
85
+ onChange: (value) => {
86
+ if (!controlledRef.current) {
87
+ setUncontrolled(value);
88
+ }
89
+ optionsRef.current.onChange?.(value);
90
+ },
91
+ runtime: {
92
+ nextTick: () => tickRef.current!(),
93
+ createId: () => id,
94
+ },
95
+ }));
96
+
97
+ const snapshot = useSyncExternalStore(
98
+ store.subscribe,
99
+ store.getSnapshot,
100
+ store.getSnapshot,
101
+ );
102
+
103
+ // Push each render's props into the core. The store no-ops when shallow-equal.
104
+ useEffect(() => {
105
+ store.setProps(toCoreProps(optionsRef.current, modelValue));
106
+ });
107
+
108
+ useEffect(() => {
109
+ const resolvers = resolversRef.current;
110
+ resolversRef.current = [];
111
+ for (const resolve of resolvers) {
112
+ resolve();
113
+ }
114
+ });
115
+
116
+ useEffect(() => {
117
+ store.mount();
118
+ return () => store.destroy();
119
+ }, [ store ]);
120
+
121
+ return snapshot;
122
+ }
123
+
124
+ const REACT_EVENT_NAMES: Record<string, string> = {
125
+ onKeydown: 'onKeyDown',
126
+ onMousedown: 'onMouseDown',
127
+ onMousemove: 'onMouseMove',
128
+ };
129
+
130
+ /**
131
+ * Adapt a core ARIA prop bag to React's event prop names:
132
+ *
133
+ * ```tsx
134
+ * <button {...toReactProps(scope.triggerProps)} />
135
+ * ```
136
+ */
137
+ export function toReactProps<T extends object>(props: T): Record<string, unknown> {
138
+ const adapted: Record<string, unknown> = {};
139
+ for (const [ key, value ] of Object.entries(props)) {
140
+ adapted[ REACT_EVENT_NAMES[ key ] ?? key ] = value;
141
+ }
142
+ return adapted;
143
+ }
144
+
145
+ function toCoreProps<O, V, Q>(
146
+ options: UseHeadlessComboboxOptions<O, V, Q>,
147
+ modelValue: V | V[] | null,
148
+ ): CoreComboboxProps<O, V, Q> {
149
+ const resolved: Record<string, unknown> = {};
150
+ for (const key of CORE_PROP_KEYS) {
151
+ resolved[ key ] = options[ key ];
152
+ }
153
+ resolved.modelValue = modelValue;
154
+ return resolved as unknown as CoreComboboxProps<O, V, Q>;
155
+ }