@vielzeug/focus 2.1.1 → 26.10.0

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.
@@ -0,0 +1,2 @@
1
+ const e=require("./errors.cjs");let t=require("@vielzeug/keymap");var n={first:[`Home`],last:[`End`],next:[`ArrowRight`],nextRow:[`ArrowDown`],prev:[`ArrowLeft`],prevRow:[`ArrowUp`]},r={...n,next:[`ArrowLeft`],prev:[`ArrowRight`]},i=[`first`,`last`,`next`,`nextRow`,`prev`,`prevRow`],resolve=(e,t)=>typeof e==`function`?e():e??t,createGridNavigation=a=>{let o=new Map;for(let t of i)for(let n of a.keys?.[t]??[]){let r=o.get(n);if(r&&r!==t)throw new e.FocusConfigError(`Key "${n}" is assigned to both ${r} and ${t}`);o.set(n,t)}let s=-1,resolveColumns=()=>{let t=resolve(a.columns,1);if(!Number.isInteger(t)||t<1)throw new e.FocusConfigError(`columns must resolve to a positive integer, got: ${t}`);return t},activeIndex=e=>{let t=a.getActiveIndex?.();return t!==void 0&&(s=t>=0&&t<e.length?t:-1),s},commitIndex=(e,t,n,r)=>(s=t,Object.freeze({action:n,event:r,index:t,item:e[t]})),navigateWithItems=(e,t,n)=>{if(!e.length)return s=-1,null;if(t===`first`)return commitIndex(e,0,t,n);if(t===`last`)return commitIndex(e,e.length-1,t,n);let r=resolveColumns(),i=t===`next`?1:t===`prev`?-1:t===`nextRow`?r:-r,o=activeIndex(e),c=o<0?i>0?0:e.length-1:o+i;if(a.loop)return commitIndex(e,(c%e.length+e.length)%e.length,t,n);let l=Math.min(e.length-1,Math.max(0,c));return l===o?null:commitIndex(e,l,t,n)},resolveKeyAction=e=>{let o=resolve(a.direction,`ltr`)===`rtl`?r:n;for(let n of i)if((a.keys?.[n]??o[n]).some(n=>(0,t.matchKey)(e,n)))return n},handleKeydown=e=>{if(e.defaultPrevented||e.isComposing||resolve(a.disabled,!1))return null;let t=resolveKeyAction(e);if(!t)return null;let n=navigateWithItems(a.getItems(),t,e);return e.preventDefault(),Object.freeze({change:n,handled:!0})},navigate=e=>navigateWithItems(a.getItems(),e),set=e=>{let t=a.getItems();if(!Number.isInteger(e)||e<0||!t.length){s=-1;return}s=Math.min(e,t.length-1)},reset=()=>{s=-1},getIndex=()=>activeIndex(a.getItems()),getActiveItem=()=>{let e=a.getItems(),t=activeIndex(e);return t>=0?e[t]:void 0};return{getActiveItem,getIndex,handleKeydown,navigate,reset,set}};exports.createGridNavigation=createGridNavigation;
2
+ //# sourceMappingURL=grid-navigation.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grid-navigation.cjs","names":[],"sources":["../src/grid-navigation.ts"],"sourcesContent":["import { matchKey } from '@vielzeug/keymap';\n\nimport { FocusConfigError } from './errors.js';\nimport type { MaybeGetter } from './list-navigation.js';\n\nexport type GridNavigationAction = 'first' | 'last' | 'next' | 'nextRow' | 'prev' | 'prevRow';\n\nexport type GridNavigationChange<T> = {\n readonly action: GridNavigationAction;\n readonly event?: KeyboardEvent;\n readonly index: number;\n readonly item: T;\n};\n\nexport type GridKeyResult<T> = {\n readonly change: GridNavigationChange<T> | null;\n readonly handled: true;\n};\n\n/**\n * Columns per row: a fixed count, or a getter resolved on every navigation. Responsive grids\n * read a media query or computed style; measured grids read the rendered row length.\n */\nexport type GridColumns = number | (() => number);\n\nexport type GridNavigationOptions<T> = {\n /** Columns per row, resolved on every navigation. */\n columns: GridColumns;\n direction?: MaybeGetter<'ltr' | 'rtl'>;\n disabled?: MaybeGetter<boolean>;\n /**\n * Reads the active index from the outside (usually the index of `document.activeElement`\n * among the items), so focus moved by pointer or Tab stays in sync. When omitted, the\n * navigation tracks the index internally through `set()`.\n */\n getActiveIndex?: () => number;\n getItems: () => readonly T[];\n keys?: Partial<Record<GridNavigationAction, readonly string[]>>;\n /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */\n loop?: boolean;\n};\n\nexport type GridNavigation<T> = {\n getActiveItem(): T | undefined;\n getIndex(): number;\n handleKeydown(event: KeyboardEvent): GridKeyResult<T> | null;\n navigate(action: GridNavigationAction): GridNavigationChange<T> | null;\n reset(): void;\n set(index: number): void;\n};\n\nconst DEFAULT_KEYS: Record<GridNavigationAction, readonly string[]> = {\n first: ['Home'],\n last: ['End'],\n next: ['ArrowRight'],\n nextRow: ['ArrowDown'],\n prev: ['ArrowLeft'],\n prevRow: ['ArrowUp'],\n};\n\nconst DEFAULT_KEYS_RTL: typeof DEFAULT_KEYS = {\n ...DEFAULT_KEYS,\n next: ['ArrowLeft'],\n prev: ['ArrowRight'],\n};\n\nconst GRID_ACTIONS = ['first', 'last', 'next', 'nextRow', 'prev', 'prevRow'] as const;\n\nconst resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n/**\n * Keyboard navigation over a two-dimensional grid of items: horizontal arrows step one\n * item, vertical arrows step one row (the column count), Home/End jump to the ends.\n *\n * Unlike `createListNavigation`, items are not skipped when disabled — skipping in two\n * dimensions would break row alignment. Focus (or otherwise activate) the item reported\n * by the returned change; `handleKeydown` calls `preventDefault()` for every recognized\n * key so unhandled arrows never scroll the page.\n */\nexport const createGridNavigation = <T>(options: GridNavigationOptions<T>): GridNavigation<T> => {\n const owners = new Map<string, GridNavigationAction>();\n\n for (const action of GRID_ACTIONS) {\n for (const key of options.keys?.[action] ?? []) {\n const owner = owners.get(key);\n if (owner && owner !== action)\n throw new FocusConfigError(`Key \"${key}\" is assigned to both ${owner} and ${action}`);\n owners.set(key, action);\n }\n }\n\n let index = -1;\n\n const resolveColumns = (): number => {\n const columns = resolve(options.columns, 1);\n if (!Number.isInteger(columns) || columns < 1)\n throw new FocusConfigError(`columns must resolve to a positive integer, got: ${columns}`);\n return columns;\n };\n\n const activeIndex = (items: readonly T[]): number => {\n const derived = options.getActiveIndex?.();\n if (derived !== undefined) index = derived >= 0 && derived < items.length ? derived : -1;\n return index;\n };\n\n const commitIndex = (\n items: readonly T[],\n nextIndex: number,\n action: GridNavigationAction,\n event?: KeyboardEvent,\n ): GridNavigationChange<T> => {\n index = nextIndex;\n return Object.freeze({ action, event, index: nextIndex, item: items[nextIndex] });\n };\n\n const navigateWithItems = (\n items: readonly T[],\n action: GridNavigationAction,\n event?: KeyboardEvent,\n ): GridNavigationChange<T> | null => {\n if (!items.length) {\n index = -1;\n return null;\n }\n\n if (action === 'first') return commitIndex(items, 0, action, event);\n if (action === 'last') return commitIndex(items, items.length - 1, action, event);\n\n const columns = resolveColumns();\n const offset = action === 'next' ? 1 : action === 'prev' ? -1 : action === 'nextRow' ? columns : -columns;\n const current = activeIndex(items);\n const base = current < 0 ? (offset > 0 ? 0 : items.length - 1) : current + offset;\n\n if (options.loop) {\n return commitIndex(items, ((base % items.length) + items.length) % items.length, action, event);\n }\n\n const clamped = Math.min(items.length - 1, Math.max(0, base));\n if (clamped === current) return null;\n\n return commitIndex(items, clamped, action, event);\n };\n\n const resolveKeyAction = (event: KeyboardEvent): GridNavigationAction | undefined => {\n const keyTable = resolve(options.direction, 'ltr') === 'rtl' ? DEFAULT_KEYS_RTL : DEFAULT_KEYS;\n\n for (const action of GRID_ACTIONS) {\n if ((options.keys?.[action] ?? keyTable[action]).some((pattern) => matchKey(event, pattern))) return action;\n }\n\n return undefined;\n };\n\n const handleKeydown = (event: KeyboardEvent): GridKeyResult<T> | null => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return null;\n\n const action = resolveKeyAction(event);\n if (!action) return null;\n\n const change = navigateWithItems(options.getItems(), action, event);\n event.preventDefault();\n return Object.freeze({ change, handled: true });\n };\n\n const navigate = (action: GridNavigationAction): GridNavigationChange<T> | null =>\n navigateWithItems(options.getItems(), action);\n\n const set = (nextIndex: number): void => {\n const items = options.getItems();\n\n if (!Number.isInteger(nextIndex) || nextIndex < 0 || !items.length) {\n index = -1;\n return;\n }\n\n index = Math.min(nextIndex, items.length - 1);\n };\n\n const reset = (): void => {\n index = -1;\n };\n\n const getIndex = (): number => activeIndex(options.getItems());\n\n const getActiveItem = (): T | undefined => {\n const items = options.getItems();\n const current = activeIndex(items);\n return current >= 0 ? items[current] : undefined;\n };\n\n return {\n getActiveItem,\n getIndex,\n handleKeydown,\n navigate,\n reset,\n set,\n };\n};\n"],"mappings":"kEAmDA,IAAM,EAAgE,CACpE,MAAO,CAAC,MAAM,EACd,KAAM,CAAC,KAAK,EACZ,KAAM,CAAC,YAAY,EACnB,QAAS,CAAC,WAAW,EACrB,KAAM,CAAC,WAAW,EAClB,QAAS,CAAC,SAAS,CACrB,EAEM,EAAwC,CAC5C,GAAG,EACH,KAAM,CAAC,WAAW,EAClB,KAAM,CAAC,YAAY,CACrB,EAEM,EAAe,CAAC,QAAS,OAAQ,OAAQ,UAAW,OAAQ,SAAS,EAErE,SAAc,EAAmC,IACrD,OAAO,GAAU,WAAc,EAAkB,EAAK,GAAS,EAWpD,qBAA2B,GAAyD,CAC/F,IAAM,EAAS,IAAI,IAEnB,IAAK,IAAM,KAAU,EACnB,IAAK,IAAM,KAAO,EAAQ,OAAO,IAAW,CAAC,EAAG,CAC9C,IAAM,EAAQ,EAAO,IAAI,CAAG,EAC5B,GAAI,GAAS,IAAU,EACrB,MAAM,IAAI,EAAA,iBAAiB,QAAQ,EAAI,wBAAwB,EAAM,OAAO,GAAQ,EACtF,EAAO,IAAI,EAAK,CAAM,CACxB,CAGF,IAAI,EAAQ,GAEN,mBAA+B,CACnC,IAAM,EAAU,QAAQ,EAAQ,QAAS,CAAC,EAC1C,GAAI,CAAC,OAAO,UAAU,CAAO,GAAK,EAAU,EAC1C,MAAM,IAAI,EAAA,iBAAiB,oDAAoD,GAAS,EAC1F,OAAO,CACT,EAEM,YAAe,GAAgC,CACnD,IAAM,EAAU,EAAQ,iBAAiB,EAEzC,OADI,IAAY,IAAA,KAAW,EAAQ,GAAW,GAAK,EAAU,EAAM,OAAS,EAAU,IAC/E,CACT,EAEM,aACJ,EACA,EACA,EACA,KAEA,EAAQ,EACD,OAAO,OAAO,CAAE,SAA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AEM,SAAY,GAChB,kBAAkB,EAAQ,SAAS,EAAG,CAAM,EAExC,IAAO,GAA4B,CACvC,IAAM,EAAQ,EAAQ,SAAS,EAE/B,GAAI,CAAC,OAAO,UAAU,CAAS,GAAK,EAAY,GAAK,CAAC,EAAM,OAAQ,CAClE,EAAQ,GACR,MACF,CAEA,EAAQ,KAAK,IAAI,EAAW,EAAM,OAAS,CAAC,CAC9C,EAEM,UAAoB,CACxB,EAAQ,EACV,EAEM,aAAyB,YAAY,EAAQ,SAAS,CAAC,EAEvD,kBAAqC,CACzC,IAAM,EAAQ,EAAQ,SAAS,EACzB,EAAU,YAAY,CAAK,EACjC,OAAO,GAAW,EAAI,EAAM,GAAW,IAAA,EACzC,EAEA,MAAO,CACL,cACA,SACA,cACA,SACA,MACA,GACF,CACF"}
@@ -0,0 +1,52 @@
1
+ import type { MaybeGetter } from './list-navigation.js';
2
+ export type GridNavigationAction = 'first' | 'last' | 'next' | 'nextRow' | 'prev' | 'prevRow';
3
+ export type GridNavigationChange<T> = {
4
+ readonly action: GridNavigationAction;
5
+ readonly event?: KeyboardEvent;
6
+ readonly index: number;
7
+ readonly item: T;
8
+ };
9
+ export type GridKeyResult<T> = {
10
+ readonly change: GridNavigationChange<T> | null;
11
+ readonly handled: true;
12
+ };
13
+ /**
14
+ * Columns per row: a fixed count, or a getter resolved on every navigation. Responsive grids
15
+ * read a media query or computed style; measured grids read the rendered row length.
16
+ */
17
+ export type GridColumns = number | (() => number);
18
+ export type GridNavigationOptions<T> = {
19
+ /** Columns per row, resolved on every navigation. */
20
+ columns: GridColumns;
21
+ direction?: MaybeGetter<'ltr' | 'rtl'>;
22
+ disabled?: MaybeGetter<boolean>;
23
+ /**
24
+ * Reads the active index from the outside (usually the index of `document.activeElement`
25
+ * among the items), so focus moved by pointer or Tab stays in sync. When omitted, the
26
+ * navigation tracks the index internally through `set()`.
27
+ */
28
+ getActiveIndex?: () => number;
29
+ getItems: () => readonly T[];
30
+ keys?: Partial<Record<GridNavigationAction, readonly string[]>>;
31
+ /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */
32
+ loop?: boolean;
33
+ };
34
+ export type GridNavigation<T> = {
35
+ getActiveItem(): T | undefined;
36
+ getIndex(): number;
37
+ handleKeydown(event: KeyboardEvent): GridKeyResult<T> | null;
38
+ navigate(action: GridNavigationAction): GridNavigationChange<T> | null;
39
+ reset(): void;
40
+ set(index: number): void;
41
+ };
42
+ /**
43
+ * Keyboard navigation over a two-dimensional grid of items: horizontal arrows step one
44
+ * item, vertical arrows step one row (the column count), Home/End jump to the ends.
45
+ *
46
+ * Unlike `createListNavigation`, items are not skipped when disabled — skipping in two
47
+ * dimensions would break row alignment. Focus (or otherwise activate) the item reported
48
+ * by the returned change; `handleKeydown` calls `preventDefault()` for every recognized
49
+ * key so unhandled arrows never scroll the page.
50
+ */
51
+ export declare const createGridNavigation: <T>(options: GridNavigationOptions<T>) => GridNavigation<T>;
52
+ //# sourceMappingURL=grid-navigation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grid-navigation.d.ts","sourceRoot":"","sources":["../src/grid-navigation.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAAC;AAE9F,MAAM,MAAM,oBAAoB,CAAC,CAAC,IAAI;IACpC,QAAQ,CAAC,MAAM,EAAE,oBAAoB,CAAC;IACtC,QAAQ,CAAC,KAAK,CAAC,EAAE,aAAa,CAAC;IAC/B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;CAClB,CAAC;AAEF,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI;IAC7B,QAAQ,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAChD,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:[`End`],next:[`ArrowRight`],nextRow:[`ArrowDown`],prev:[`ArrowLeft`],prevRow:[`ArrowUp`]},r={...n,next:[`ArrowLeft`],prev:[`ArrowRight`]},i=[`first`,`last`,`next`,`nextRow`,`prev`,`prevRow`],resolve=(e,t)=>typeof e==`function`?e():e??t,createGridNavigation=a=>{let o=new Map;for(let t of i)for(let n of a.keys?.[t]??[]){let r=o.get(n);if(r&&r!==t)throw new e(`Key "${n}" is assigned to both ${r} and ${t}`);o.set(n,t)}let s=-1,resolveColumns=()=>{let t=resolve(a.columns,1);if(!Number.isInteger(t)||t<1)throw new e(`columns must resolve to a positive integer, got: ${t}`);return t},activeIndex=e=>{let t=a.getActiveIndex?.();return t!==void 0&&(s=t>=0&&t<e.length?t:-1),s},commitIndex=(e,t,n,r)=>(s=t,Object.freeze({action:n,event:r,index:t,item:e[t]})),navigateWithItems=(e,t,n)=>{if(!e.length)return s=-1,null;if(t===`first`)return commitIndex(e,0,t,n);if(t===`last`)return commitIndex(e,e.length-1,t,n);let r=resolveColumns(),i=t===`next`?1:t===`prev`?-1:t===`nextRow`?r:-r,o=activeIndex(e),c=o<0?i>0?0:e.length-1:o+i;if(a.loop)return commitIndex(e,(c%e.length+e.length)%e.length,t,n);let l=Math.min(e.length-1,Math.max(0,c));return l===o?null:commitIndex(e,l,t,n)},resolveKeyAction=e=>{let o=resolve(a.direction,`ltr`)===`rtl`?r:n;for(let n of i)if((a.keys?.[n]??o[n]).some(n=>t(e,n)))return n},handleKeydown=e=>{if(e.defaultPrevented||e.isComposing||resolve(a.disabled,!1))return null;let t=resolveKeyAction(e);if(!t)return null;let n=navigateWithItems(a.getItems(),t,e);return e.preventDefault(),Object.freeze({change:n,handled:!0})},navigate=e=>navigateWithItems(a.getItems(),e),set=e=>{let t=a.getItems();if(!Number.isInteger(e)||e<0||!t.length){s=-1;return}s=Math.min(e,t.length-1)},reset=()=>{s=-1},getIndex=()=>activeIndex(a.getItems()),getActiveItem=()=>{let e=a.getItems(),t=activeIndex(e);return t>=0?e[t]:void 0};return{getActiveItem,getIndex,handleKeydown,navigate,reset,set}};export{createGridNavigation};
2
+ //# sourceMappingURL=grid-navigation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grid-navigation.js","names":[],"sources":["../src/grid-navigation.ts"],"sourcesContent":["import { matchKey } from '@vielzeug/keymap';\n\nimport { FocusConfigError } from './errors.js';\nimport type { MaybeGetter } from './list-navigation.js';\n\nexport type GridNavigationAction = 'first' | 'last' | 'next' | 'nextRow' | 'prev' | 'prevRow';\n\nexport type GridNavigationChange<T> = {\n readonly action: GridNavigationAction;\n readonly event?: KeyboardEvent;\n readonly index: number;\n readonly item: T;\n};\n\nexport type GridKeyResult<T> = {\n readonly change: GridNavigationChange<T> | null;\n readonly handled: true;\n};\n\n/**\n * Columns per row: a fixed count, or a getter resolved on every navigation. Responsive grids\n * read a media query or computed style; measured grids read the rendered row length.\n */\nexport type GridColumns = number | (() => number);\n\nexport type GridNavigationOptions<T> = {\n /** Columns per row, resolved on every navigation. */\n columns: GridColumns;\n direction?: MaybeGetter<'ltr' | 'rtl'>;\n disabled?: MaybeGetter<boolean>;\n /**\n * Reads the active index from the outside (usually the index of `document.activeElement`\n * among the items), so focus moved by pointer or Tab stays in sync. When omitted, the\n * navigation tracks the index internally through `set()`.\n */\n getActiveIndex?: () => number;\n getItems: () => readonly T[];\n keys?: Partial<Record<GridNavigationAction, readonly string[]>>;\n /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */\n loop?: boolean;\n};\n\nexport type GridNavigation<T> = {\n getActiveItem(): T | undefined;\n getIndex(): number;\n handleKeydown(event: KeyboardEvent): GridKeyResult<T> | null;\n navigate(action: GridNavigationAction): GridNavigationChange<T> | null;\n reset(): void;\n set(index: number): void;\n};\n\nconst DEFAULT_KEYS: Record<GridNavigationAction, readonly string[]> = {\n first: ['Home'],\n last: ['End'],\n next: ['ArrowRight'],\n nextRow: ['ArrowDown'],\n prev: ['ArrowLeft'],\n prevRow: ['ArrowUp'],\n};\n\nconst DEFAULT_KEYS_RTL: typeof DEFAULT_KEYS = {\n ...DEFAULT_KEYS,\n next: ['ArrowLeft'],\n prev: ['ArrowRight'],\n};\n\nconst GRID_ACTIONS = ['first', 'last', 'next', 'nextRow', 'prev', 'prevRow'] as const;\n\nconst resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n/**\n * Keyboard navigation over a two-dimensional grid of items: horizontal arrows step one\n * item, vertical arrows step one row (the column count), Home/End jump to the ends.\n *\n * Unlike `createListNavigation`, items are not skipped when disabled — skipping in two\n * dimensions would break row alignment. Focus (or otherwise activate) the item reported\n * by the returned change; `handleKeydown` calls `preventDefault()` for every recognized\n * key so unhandled arrows never scroll the page.\n */\nexport const createGridNavigation = <T>(options: GridNavigationOptions<T>): GridNavigation<T> => {\n const owners = new Map<string, GridNavigationAction>();\n\n for (const action of GRID_ACTIONS) {\n for (const key of options.keys?.[action] ?? []) {\n const owner = owners.get(key);\n if (owner && owner !== action)\n throw new FocusConfigError(`Key \"${key}\" is assigned to both ${owner} and ${action}`);\n owners.set(key, action);\n }\n }\n\n let index = -1;\n\n const resolveColumns = (): number => {\n const columns = resolve(options.columns, 1);\n if (!Number.isInteger(columns) || columns < 1)\n throw new FocusConfigError(`columns must resolve to a positive integer, got: ${columns}`);\n return columns;\n };\n\n const activeIndex = (items: readonly T[]): number => {\n const derived = options.getActiveIndex?.();\n if (derived !== undefined) index = derived >= 0 && derived < items.length ? derived : -1;\n return index;\n };\n\n const commitIndex = (\n items: readonly T[],\n nextIndex: number,\n action: GridNavigationAction,\n event?: KeyboardEvent,\n ): GridNavigationChange<T> => {\n index = nextIndex;\n return Object.freeze({ action, event, index: nextIndex, item: items[nextIndex] });\n };\n\n const navigateWithItems = (\n items: readonly T[],\n action: GridNavigationAction,\n event?: KeyboardEvent,\n ): GridNavigationChange<T> | null => {\n if (!items.length) {\n index = -1;\n return null;\n }\n\n if (action === 'first') return commitIndex(items, 0, action, event);\n if (action === 'last') return commitIndex(items, items.length - 1, action, event);\n\n const columns = resolveColumns();\n const offset = action === 'next' ? 1 : action === 'prev' ? -1 : action === 'nextRow' ? columns : -columns;\n const current = activeIndex(items);\n const base = current < 0 ? (offset > 0 ? 0 : items.length - 1) : current + offset;\n\n if (options.loop) {\n return commitIndex(items, ((base % items.length) + items.length) % items.length, action, event);\n }\n\n const clamped = Math.min(items.length - 1, Math.max(0, base));\n if (clamped === current) return null;\n\n return commitIndex(items, clamped, action, event);\n };\n\n const resolveKeyAction = (event: KeyboardEvent): GridNavigationAction | undefined => {\n const keyTable = resolve(options.direction, 'ltr') === 'rtl' ? DEFAULT_KEYS_RTL : DEFAULT_KEYS;\n\n for (const action of GRID_ACTIONS) {\n if ((options.keys?.[action] ?? keyTable[action]).some((pattern) => matchKey(event, pattern))) return action;\n }\n\n return undefined;\n };\n\n const handleKeydown = (event: KeyboardEvent): GridKeyResult<T> | null => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return null;\n\n const action = resolveKeyAction(event);\n if (!action) return null;\n\n const change = navigateWithItems(options.getItems(), action, event);\n event.preventDefault();\n return Object.freeze({ change, handled: true });\n };\n\n const navigate = (action: GridNavigationAction): GridNavigationChange<T> | null =>\n navigateWithItems(options.getItems(), action);\n\n const set = (nextIndex: number): void => {\n const items = options.getItems();\n\n if (!Number.isInteger(nextIndex) || nextIndex < 0 || !items.length) {\n index = -1;\n return;\n }\n\n index = Math.min(nextIndex, items.length - 1);\n };\n\n const reset = (): void => {\n index = -1;\n };\n\n const getIndex = (): number => activeIndex(options.getItems());\n\n const getActiveItem = (): T | undefined => {\n const items = options.getItems();\n const current = activeIndex(items);\n return current >= 0 ? items[current] : undefined;\n };\n\n return {\n getActiveItem,\n getIndex,\n handleKeydown,\n navigate,\n reset,\n set,\n };\n};\n"],"mappings":"2FAmDA,IAAM,EAAgE,CACpE,MAAO,CAAC,MAAM,EACd,KAAM,CAAC,KAAK,E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AAoB,CACxB,EAAQ,EACV,EAEM,aAAyB,YAAY,EAAQ,SAAS,CAAC,EAEvD,kBAAqC,CACzC,IAAM,EAAQ,EAAQ,SAAS,EACzB,EAAU,YAAY,CAAK,EACjC,OAAO,GAAW,EAAI,EAAM,GAAW,IAAA,EACzC,EAEA,MAAO,CACL,cACA,SACA,cACA,SACA,MACA,GACF,CACF"}
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./list-navigation.cjs"),t=require("./restore-focus.cjs");exports.captureFocus=t.captureFocus,exports.createListNavigation=e.createListNavigation,exports.restoreFocus=t.restoreFocus;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./errors.cjs"),t=require("./grid-navigation.cjs"),n=require("./list-navigation.cjs"),r=require("./restore-focus.cjs");exports.FocusConfigError=e.FocusConfigError,exports.FocusError=e.FocusError,exports.captureFocus=r.captureFocus,exports.createGridNavigation=t.createGridNavigation,exports.createListNavigation=n.createListNavigation,exports.rescueFocus=r.rescueFocus,exports.restoreFocus=r.restoreFocus;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
- export type { ListKeyAction, ListNavigation, ListNavigationAction, ListNavigationChange, ListNavigationOptions, ListNavigationTypeaheadOptions, MaybeGetter, } from './list-navigation';
2
- export { createListNavigation } from './list-navigation';
3
- export type { CaptureFocusOptions, FocusRestorer, FocusTarget, RestoreFocusOptions, } from './restore-focus';
4
- export { captureFocus, restoreFocus } from './restore-focus';
1
+ export { FocusConfigError, FocusError } from './errors.js';
2
+ export type { GridColumns, GridKeyResult, GridNavigation, GridNavigationAction, GridNavigationChange, GridNavigationOptions, } from './grid-navigation.js';
3
+ export { createGridNavigation } from './grid-navigation.js';
4
+ export type { ListKeyAction, ListKeyResult, ListNavigation, ListNavigationAction, ListNavigationChange, ListNavigationOptions, ListNavigationTypeaheadOptions, MaybeGetter, } from './list-navigation.js';
5
+ export { createListNavigation } from './list-navigation.js';
6
+ export type { CaptureFocusOptions, FocusRestorer, FocusTarget, RestoreFocusOptions, } from './restore-focus.js';
7
+ export { captureFocus, rescueFocus, restoreFocus } from './restore-focus.js';
5
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,aAAa,EACb,cAAc,EACd,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,8BAA8B,EAC9B,WAAW,GACZ,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,YAAY,EACV,mBAAmB,EACnB,aAAa,EACb,WAAW,EACX,mBAAmB,GACpB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC3D,YAAY,EACV,WAAW,EACX,aAAa,EACb,cAAc,EACd,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,YAAY,EACV,aAAa,EACb,aAAa,EACb,cAAc,EACd,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,8BAA8B,EAC9B,WAAW,GACZ,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,YAAY,EACV,mBAAmB,EACnB,aAAa,EACb,WAAW,EACX,mBAAmB,GACpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC"}
package/dist/index.js CHANGED
@@ -1,3 +1 @@
1
- import { createListNavigation as e } from "./list-navigation.js";
2
- import { captureFocus as t, restoreFocus as n } from "./restore-focus.js";
3
- export { t as captureFocus, e as createListNavigation, n as restoreFocus };
1
+ import{FocusConfigError as e,FocusError as t}from"./errors.js";import{createGridNavigation as n}from"./grid-navigation.js";import{createListNavigation as r}from"./list-navigation.js";import{captureFocus as i,rescueFocus as a,restoreFocus as o}from"./restore-focus.js";export{e as FocusConfigError,t as FocusError,i as captureFocus,n as createGridNavigation,r as createListNavigation,a as rescueFocus,o as restoreFocus};
@@ -1,2 +1,2 @@
1
- var e={both:{first:[`Home`],last:[`End`],next:[`ArrowDown`,`ArrowRight`],prev:[`ArrowUp`,`ArrowLeft`]},horizontal:{first:[`Home`],last:[`End`],next:[`ArrowRight`],prev:[`ArrowLeft`]},vertical:{first:[`Home`],last:[`End`],next:[`ArrowDown`],prev:[`ArrowUp`]}},t={both:{first:[`Home`],last:[`End`],next:[`ArrowDown`,`ArrowLeft`],prev:[`ArrowUp`,`ArrowRight`]},horizontal:{first:[`Home`],last:[`End`],next:[`ArrowLeft`],prev:[`ArrowRight`]},vertical:e.vertical},n=500,r=(e,t)=>typeof e==`function`?e():e??t,i=(e,t,n)=>{for(let r=t;r<e.length;r++)if(n(e[r],r))return r;return-1},a=(e,t,n)=>{for(let r=t;r>=0;r--)if(n(e[r],r))return r;return-1},o=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?e:n,s=n=>{let s=new AbortController,c=-1,l=!1,u=``,d=0,f,p=(e,t)=>n.isItemDisabled?.(e,t)??!1,m=(e,t)=>t>=0&&t<e.length&&!p(e[t],t),h=e=>(m(e,c)||(c=-1),c),g=()=>{u=``,d=0},_=(e,t,r,i)=>m(e,t)?(c=t,n.onNavigate?.({action:r,event:i,index:t,item:e[t]}),c):(c=-1,c),v=(e,t,n)=>n===`forward`?i(e,t,(e,t)=>!p(e,t)):a(e,t,(e,t)=>!p(e,t)),y=(e,t,r)=>{let i=h(e);if(!e.length)return c=-1,c;let a=i<0?t===`forward`?0:e.length-1:t===`forward`?i+1:i-1,o=v(e,a,t),s=t===`forward`?`next`:`prev`;if(o>=0)return _(e,o,s,r);if(n.loop){let n=t===`forward`?0:e.length-1,i=v(e,n,t);if(i>=0)return _(e,i,s,r)}return c},b=(e,t,n)=>(g(),h(e),e.length?t===`first`?_(e,v(e,0,`forward`),t,n):t===`last`?_(e,v(e,e.length-1,`backward`),t,n):y(e,t===`next`?`forward`:`backward`,n):(c=-1,c)),x=(e,t,r)=>{let i=h(e),a=i<0?0:r?i:i+1;for(let r=0;r<e.length;r++){let i=(a+r)%e.length,o=e[i];if(!p(o,i)&&n.typeahead?.getLabel(o,i).toLocaleLowerCase().startsWith(t))return i}return-1},S=(e,t)=>{if(!n.typeahead||e.key.length!==1||e.ctrlKey||e.altKey||e.metaKey)return!1;let r=Date.now(),i=e.key.toLocaleLowerCase(),a=o(n.typeahead.delayMs);r-d>=a&&(u=``),d=r;let s=u+i;u=s.length>1&&[...s].every(e=>e===i)?i:s;let c=x(t,u,u.length>1);return c<0&&u.length>1&&(u=i,c=x(t,u,!1)),c<0?!1:(_(t,c,`typeahead`,e),!0)},C=e=>{if(l)return-1;let t=n.getItems();if(h(t),g(),e<0||!t.length)return c=-1,c;let r=Math.min(e,t.length-1);return m(t,r)?(c=r,c):(c=-1,c)},w=e=>l?-1:b(n.getItems(),e),T=()=>{if(l)return;let e=n.getItems(),t=h(e);return t>=0?e[t]:void 0},E=()=>{l||(c=-1,g())},D=()=>l?-1:h(n.getItems()),O=i=>{let a=n.keys,o=(r(n.direction,`ltr`)===`rtl`?t:e)[r(n.orientation,`vertical`)];for(let e of[`next`,`prev`,`first`,`last`])if((a?.[e]??o[e]).includes(i))return e},k=e=>{if(l||r(n.disabled,!1))return!1;let t=n.getItems();h(t);let i=O(e.key);return i?(e.preventDefault(),b(t,i,e),!0):S(e,t)},A=()=>{l||(l=!0,c=-1,g(),f?.(),f=void 0,s.abort())};return n.signal?.aborted?A():n.signal&&(n.signal.addEventListener(`abort`,A,{once:!0}),f=()=>n.signal?.removeEventListener(`abort`,A)),{get disposalSignal(){return s.signal},dispose:A,get disposed(){return l},getActiveItem:T,getIndex:D,handleKeydown:k,navigate:w,reset:E,set:C,[Symbol.dispose]:A}};exports.createListNavigation=s;
1
+ const e=require("./errors.cjs");let t=require("@vielzeug/keymap");var n={both:{first:[`Home`],last:[`End`],next:[`ArrowDown`,`ArrowRight`],prev:[`ArrowUp`,`ArrowLeft`]},horizontal:{first:[`Home`],last:[`End`],next:[`ArrowRight`],prev:[`ArrowLeft`]},vertical:{first:[`Home`],last:[`End`],next:[`ArrowDown`],prev:[`ArrowUp`]}},r={both:{first:[`Home`],last:[`End`],next:[`ArrowDown`,`ArrowLeft`],prev:[`ArrowUp`,`ArrowRight`]},horizontal:{first:[`Home`],last:[`End`],next:[`ArrowLeft`],prev:[`ArrowRight`]},vertical:n.vertical},i=500,findForward=(e,t,n)=>{for(let r=t;r<e.length;r++)if(n(e[r],r))return r;return-1},findBackward=(e,t,n)=>{for(let r=t;r>=0;r--)if(n(e[r],r))return r;return-1},resolveTypeaheadDelay=t=>{if(t===void 0)return i;if(!Number.isFinite(t)||t<=0)throw new e.FocusConfigError(`Typeahead delay must be a positive finite number`);return t},createListNavigation=i=>{let a=resolveTypeaheadDelay(i.typeahead?.delayMs),o=new Map;for(let t of[`next`,`prev`,`first`,`last`])for(let n of i.keys?.[t]??[]){let r=o.get(n);if(r&&r!==t)throw new e.FocusConfigError(`Key "${n}" is assigned to both ${r} and ${t}`);o.set(n,t)}let s=-1,c=``,l=0,isItemDisabled=(e,t)=>i.isItemDisabled?.(e,t)??!1,isUsableIndex=(e,t)=>t>=0&&t<e.length&&!isItemDisabled(e[t],t),normalizeIndex=e=>(isUsableIndex(e,s)||(s=-1),s),resetTypeahead=()=>{c=``,l=0},commitIndex=(e,t,n,r)=>isUsableIndex(e,t)?(s=t,Object.freeze({action:n,event:r,index:t,item:e[t]})):(s=-1,null),findEnabledIndex=(e,t,n)=>n===`forward`?findForward(e,t,(e,t)=>!isItemDisabled(e,t)):findBackward(e,t,(e,t)=>!isItemDisabled(e,t)),move=(e,t,n)=>{let r=normalizeIndex(e);if(!e.length)return s=-1,null;let a=r<0?t===`forward`?0:e.length-1:t===`forward`?r+1:r-1,o=findEnabledIndex(e,a,t),c=t===`forward`?`next`:`prev`;if(o>=0)return commitIndex(e,o,c,n);if(i.loop){let r=t===`forward`?0:e.length-1,i=findEnabledIndex(e,r,t);if(i>=0)return commitIndex(e,i,c,n)}return null},navigateWithItems=(e,t,n)=>(resetTypeahead(),normalizeIndex(e),e.length?t===`first`?commitIndex(e,findEnabledIndex(e,0,`forward`),t,n):t===`last`?commitIndex(e,findEnabledIndex(e,e.length-1,`backward`),t,n):move(e,t===`next`?`forward`:`backward`,n):(s=-1,null)),findTypeaheadMatch=(e,t,n)=>{let r=normalizeIndex(e),a=r<0?0:n?r:r+1;for(let n=0;n<e.length;n++){let r=(a+n)%e.length,o=e[r];if(!isItemDisabled(o,r)&&i.typeahead?.getLabel(o,r).toLocaleLowerCase().startsWith(t))return r}return-1},handleTypeahead=(e,t)=>{if(!i.typeahead||e.key.length!==1||e.ctrlKey||e.altKey||e.metaKey)return null;let n=performance.now(),r=e.key.toLocaleLowerCase();n-l>=a&&(c=``),l=n;let o=c+r;c=o.length>1&&[...o].every(e=>e===r)?r:o;let s=findTypeaheadMatch(t,c,c.length>1);return s<0&&c.length>1&&(c=r,s=findTypeaheadMatch(t,c,!1)),s<0?null:commitIndex(t,s,`typeahead`,e)},set=e=>{let t=i.getItems();if(normalizeIndex(t),resetTypeahead(),!Number.isInteger(e)||e<0||!t.length)return s=-1,s;let n=Math.min(e,t.length-1);return isUsableIndex(t,n)?(s=n,s):(s=-1,s)},navigate=e=>navigateWithItems(i.getItems(),e),getActiveItem=()=>{let e=i.getItems(),t=normalizeIndex(e);return t>=0?e[t]:void 0},reset=()=>{s=-1,resetTypeahead()},getIndex=()=>normalizeIndex(i.getItems()),resolve=(e,t)=>typeof e==`function`?e():e??t,resolveKeyAction=e=>{let a=i.keys,o=(resolve(i.direction,`ltr`)===`rtl`?r:n)[resolve(i.orientation,`vertical`)];for(let n of[`next`,`prev`,`first`,`last`])if((a?.[n]??o[n]).some(n=>(0,t.matchKey)(e,n)))return n},handleKeydown=e=>{if(e.defaultPrevented||e.isComposing||resolve(i.disabled,!1))return null;let t=i.getItems();normalizeIndex(t);let n=resolveKeyAction(e);if(n){let r=navigateWithItems(t,n,e);return e.preventDefault(),Object.freeze({change:r,handled:!0})}let r=handleTypeahead(e,t);return r?(i.typeahead?.preventDefault&&e.preventDefault(),Object.freeze({change:r,handled:!0})):null};return{getActiveItem,getIndex,handleKeydown,navigate,reset,set}};exports.createListNavigation=createListNavigation;
2
2
  //# sourceMappingURL=list-navigation.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"list-navigation.cjs","names":[],"sources":["../src/list-navigation.ts"],"sourcesContent":["export type MaybeGetter<T> = T | (() => T);\n\nexport type ListNavigationAction = 'first' | 'last' | 'next' | 'prev';\nexport type ListKeyAction = ListNavigationAction | 'typeahead';\n\nexport type ListNavigationChange<T> = {\n action: ListKeyAction;\n event?: KeyboardEvent;\n index: number;\n item: T;\n};\n\nexport type ListNavigationTypeaheadOptions<T> = {\n delayMs?: number;\n getLabel: (item: T, index: number) => string;\n};\n\nexport type ListNavigationOptions<T> = {\n direction?: MaybeGetter<'ltr' | 'rtl'>;\n disabled?: MaybeGetter<boolean | undefined>;\n getItems: () => readonly T[];\n isItemDisabled?: (item: T, index: number) => boolean;\n keys?: Partial<Record<ListNavigationAction, readonly string[]>>;\n loop?: boolean;\n onNavigate?: (change: ListNavigationChange<T>) => void;\n orientation?: MaybeGetter<'both' | 'horizontal' | 'vertical'>;\n signal?: AbortSignal;\n typeahead?: ListNavigationTypeaheadOptions<T>;\n};\n\nexport type ListNavigation<T> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getActiveItem(): T | undefined;\n getIndex(): number;\n handleKeydown(event: KeyboardEvent): boolean;\n navigate(action: ListNavigationAction): number;\n reset(): void;\n set(index: number): number;\n};\n\nconst DEFAULT_KEYS: Record<'both' | 'horizontal' | 'vertical', Record<ListNavigationAction, readonly string[]>> = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowRight'], prev: ['ArrowUp', 'ArrowLeft'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowRight'], prev: ['ArrowLeft'] },\n vertical: { first: ['Home'], last: ['End'], next: ['ArrowDown'], prev: ['ArrowUp'] },\n};\n\nconst DEFAULT_KEYS_RTL: typeof DEFAULT_KEYS = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowLeft'], prev: ['ArrowUp', 'ArrowRight'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowLeft'], prev: ['ArrowRight'] },\n vertical: DEFAULT_KEYS.vertical,\n};\n\nconst DEFAULT_TYPEAHEAD_DELAY_MS = 500;\n\nconst read = <T>(value: MaybeGetter<T> | undefined, fallback: T): T =>\n typeof value === 'function' ? (value as () => T)() : (value ?? fallback);\n\nconst findForward = <T>(items: readonly T[], start: number, predicate: (item: T, index: number) => boolean): number => {\n for (let index = start; index < items.length; index++) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst findBackward = <T>(\n items: readonly T[],\n start: number,\n predicate: (item: T, index: number) => boolean,\n): number => {\n for (let index = start; index >= 0; index--) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst resolveTypeaheadDelay = (delay: number | undefined): number =>\n typeof delay === 'number' && Number.isFinite(delay) && delay > 0 ? delay : DEFAULT_TYPEAHEAD_DELAY_MS;\n\nexport const createListNavigation = <T>(options: ListNavigationOptions<T>): ListNavigation<T> => {\n const disposalController = new AbortController();\n let index = -1;\n let disposed = false;\n let typeaheadBuffer = '';\n let lastTypeaheadAt = 0;\n let removeExternalAbortListener: (() => void) | undefined;\n\n const isItemDisabled = (item: T, itemIndex: number): boolean => options.isItemDisabled?.(item, itemIndex) ?? false;\n\n const isUsableIndex = (items: readonly T[], itemIndex: number): boolean =>\n itemIndex >= 0 && itemIndex < items.length && !isItemDisabled(items[itemIndex], itemIndex);\n\n const normalizeIndex = (items: readonly T[]): number => {\n if (!isUsableIndex(items, index)) index = -1;\n\n return index;\n };\n\n const resetTypeahead = (): void => {\n typeaheadBuffer = '';\n lastTypeaheadAt = 0;\n };\n\n const commitIndex = (\n items: readonly T[],\n nextIndex: number,\n action: ListKeyAction,\n event?: KeyboardEvent,\n ): number => {\n if (!isUsableIndex(items, nextIndex)) {\n index = -1;\n\n return index;\n }\n\n index = nextIndex;\n options.onNavigate?.({ action, event, index: nextIndex, item: items[nextIndex] });\n\n return index;\n };\n\n const findEnabledIndex = (items: readonly T[], start: number, direction: 'forward' | 'backward'): number => {\n if (direction === 'forward')\n return findForward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n\n return findBackward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n };\n\n const move = (items: readonly T[], direction: 'forward' | 'backward', event?: KeyboardEvent): number => {\n const current = normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return index;\n }\n\n const start =\n current < 0\n ? direction === 'forward'\n ? 0\n : items.length - 1\n : direction === 'forward'\n ? current + 1\n : current - 1;\n\n const nextIndex = findEnabledIndex(items, start, direction);\n const action: ListNavigationAction = direction === 'forward' ? 'next' : 'prev';\n\n if (nextIndex >= 0) return commitIndex(items, nextIndex, action, event);\n\n if (options.loop) {\n const wrapStart = direction === 'forward' ? 0 : items.length - 1;\n const wrapped = findEnabledIndex(items, wrapStart, direction);\n\n if (wrapped >= 0) return commitIndex(items, wrapped, action, event);\n }\n\n return index;\n };\n\n const navigateWithItems = (items: readonly T[], action: ListNavigationAction, event?: KeyboardEvent): number => {\n resetTypeahead();\n normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return index;\n }\n\n if (action === 'first') {\n return commitIndex(items, findEnabledIndex(items, 0, 'forward'), action, event);\n }\n\n if (action === 'last') {\n return commitIndex(items, findEnabledIndex(items, items.length - 1, 'backward'), action, event);\n }\n\n return move(items, action === 'next' ? 'forward' : 'backward', event);\n };\n\n const findTypeaheadMatch = (items: readonly T[], search: string, includeCurrent: boolean): number => {\n const current = normalizeIndex(items);\n const start = current < 0 ? 0 : includeCurrent ? current : current + 1;\n\n for (let offset = 0; offset < items.length; offset++) {\n const itemIndex = (start + offset) % items.length;\n const item = items[itemIndex];\n\n if (isItemDisabled(item, itemIndex)) continue;\n\n if (options.typeahead?.getLabel(item, itemIndex).toLocaleLowerCase().startsWith(search)) {\n return itemIndex;\n }\n }\n\n return -1;\n };\n\n const handleTypeahead = (event: KeyboardEvent, items: readonly T[]): boolean => {\n if (!options.typeahead || event.key.length !== 1 || event.ctrlKey || event.altKey || event.metaKey) return false;\n\n const now = Date.now();\n const key = event.key.toLocaleLowerCase();\n const delay = resolveTypeaheadDelay(options.typeahead.delayMs);\n\n if (now - lastTypeaheadAt >= delay) typeaheadBuffer = '';\n\n lastTypeaheadAt = now;\n\n const candidate = typeaheadBuffer + key;\n const repeatedCharacter = candidate.length > 1 && [...candidate].every((character) => character === key);\n typeaheadBuffer = repeatedCharacter ? key : candidate;\n\n let nextIndex = findTypeaheadMatch(items, typeaheadBuffer, typeaheadBuffer.length > 1);\n\n if (nextIndex < 0 && typeaheadBuffer.length > 1) {\n typeaheadBuffer = key;\n nextIndex = findTypeaheadMatch(items, typeaheadBuffer, false);\n }\n\n if (nextIndex < 0) return false;\n\n commitIndex(items, nextIndex, 'typeahead', event);\n\n return true;\n };\n\n const set = (nextIndex: number): number => {\n if (disposed) return -1;\n\n const items = options.getItems();\n normalizeIndex(items);\n resetTypeahead();\n\n if (nextIndex < 0 || !items.length) {\n index = -1;\n\n return index;\n }\n\n const clamped = Math.min(nextIndex, items.length - 1);\n\n if (!isUsableIndex(items, clamped)) {\n index = -1;\n\n return index;\n }\n\n index = clamped;\n\n return index;\n };\n\n const navigate = (action: ListNavigationAction): number => {\n if (disposed) return -1;\n\n return navigateWithItems(options.getItems(), action);\n };\n\n const getActiveItem = (): T | undefined => {\n if (disposed) return undefined;\n\n const items = options.getItems();\n const current = normalizeIndex(items);\n\n return current >= 0 ? items[current] : undefined;\n };\n\n const reset = (): void => {\n if (disposed) return;\n\n index = -1;\n resetTypeahead();\n };\n\n const getIndex = (): number => {\n if (disposed) return -1;\n\n return normalizeIndex(options.getItems());\n };\n\n const resolveKeyAction = (eventKey: string): ListNavigationAction | undefined => {\n const keys = options.keys;\n const keyTable = read(options.direction, 'ltr') === 'rtl' ? DEFAULT_KEYS_RTL : DEFAULT_KEYS;\n const defaults = keyTable[read(options.orientation, 'vertical')];\n\n for (const action of ['next', 'prev', 'first', 'last'] as const) {\n if ((keys?.[action] ?? defaults[action]).includes(eventKey)) return action;\n }\n\n return undefined;\n };\n\n const handleKeydown = (event: KeyboardEvent): boolean => {\n if (disposed || read(options.disabled, false)) return false;\n\n const items = options.getItems();\n normalizeIndex(items);\n\n const action = resolveKeyAction(event.key);\n\n if (action) {\n event.preventDefault();\n navigateWithItems(items, action, event);\n\n return true;\n }\n\n return handleTypeahead(event, items);\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n index = -1;\n resetTypeahead();\n removeExternalAbortListener?.();\n removeExternalAbortListener = undefined;\n disposalController.abort();\n };\n\n if (options.signal?.aborted) {\n dispose();\n } else if (options.signal) {\n options.signal.addEventListener('abort', dispose, { once: true });\n removeExternalAbortListener = () => options.signal?.removeEventListener('abort', dispose);\n }\n\n return {\n get disposalSignal() {\n return disposalController.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getActiveItem,\n getIndex,\n handleKeydown,\n navigate,\n reset,\n set,\n [Symbol.dispose]: dispose,\n };\n};\n"],"mappings":"AA2CA,IAAM,EAA4G,CAChH,KAAM,CAAE,MAAO,CAAC,MAAM,EAAG,KAA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AC,EAChE,MAAoC,EAAQ,QAAQ,oBAAoB,QAAS,CAAO,GAGnF,CACL,IAAI,gBAAiB,CACnB,OAAO,EAAmB,MAC5B,EACA,UACA,IAAI,UAAW,CACb,OAAO,CACT,EACA,gBACA,WACA,gBACA,WACA,QACA,OACC,OAAO,SAAU,CACpB,CACF"}
1
+ {"version":3,"file":"list-navigation.cjs","names":[],"sources":["../src/list-navigation.ts"],"sourcesContent":["import { matchKey } from '@vielzeug/keymap';\n\nimport { FocusConfigError } from './errors.js';\n\nexport type ListNavigationAction = 'first' | 'last' | 'next' | 'prev';\nexport type ListKeyAction = ListNavigationAction | 'typeahead';\n\nexport type ListNavigationChange<T> = {\n readonly action: ListKeyAction;\n readonly event?: KeyboardEvent;\n readonly index: number;\n readonly item: T;\n};\n\nexport type ListKeyResult<T> = {\n readonly change: ListNavigationChange<T> | null;\n readonly handled: true;\n};\n\nexport type ListNavigationTypeaheadOptions<T> = {\n delayMs?: number;\n getLabel: (item: T, index: number) => string;\n preventDefault?: boolean;\n};\n\nexport type MaybeGetter<T> = T | (() => T);\n\nexport type ListNavigationOptions<T> = {\n direction?: MaybeGetter<'ltr' | 'rtl'>;\n disabled?: MaybeGetter<boolean>;\n getItems: () => readonly T[];\n isItemDisabled?: (item: T, index: number) => boolean;\n keys?: Partial<Record<ListNavigationAction, readonly string[]>>;\n loop?: boolean;\n orientation?: MaybeGetter<'both' | 'horizontal' | 'vertical'>;\n typeahead?: ListNavigationTypeaheadOptions<T>;\n};\n\nexport type ListNavigation<T> = {\n getActiveItem(): T | undefined;\n getIndex(): number;\n handleKeydown(event: KeyboardEvent): ListKeyResult<T> | null;\n navigate(action: ListNavigationAction): ListNavigationChange<T> | null;\n reset(): void;\n set(index: number): number;\n};\n\nconst DEFAULT_KEYS: Record<'both' | 'horizontal' | 'vertical', Record<ListNavigationAction, readonly string[]>> = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowRight'], prev: ['ArrowUp', 'ArrowLeft'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowRight'], prev: ['ArrowLeft'] },\n vertical: { first: ['Home'], last: ['End'], next: ['ArrowDown'], prev: ['ArrowUp'] },\n};\n\nconst DEFAULT_KEYS_RTL: typeof DEFAULT_KEYS = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowLeft'], prev: ['ArrowUp', 'ArrowRight'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowLeft'], prev: ['ArrowRight'] },\n vertical: DEFAULT_KEYS.vertical,\n};\n\nconst DEFAULT_TYPEAHEAD_DELAY_MS = 500;\n\nconst findForward = <T>(items: readonly T[], start: number, predicate: (item: T, index: number) => boolean): number => {\n for (let index = start; index < items.length; index++) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst findBackward = <T>(\n items: readonly T[],\n start: number,\n predicate: (item: T, index: number) => boolean,\n): number => {\n for (let index = start; index >= 0; index--) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst resolveTypeaheadDelay = (delay: number | undefined): number => {\n if (delay === undefined) return DEFAULT_TYPEAHEAD_DELAY_MS;\n if (!Number.isFinite(delay) || delay <= 0)\n throw new FocusConfigError('Typeahead delay must be a positive finite number');\n return delay;\n};\n\nexport const createListNavigation = <T>(options: ListNavigationOptions<T>): ListNavigation<T> => {\n const typeaheadDelay = resolveTypeaheadDelay(options.typeahead?.delayMs);\n const owners = new Map<string, ListNavigationAction>();\n\n for (const action of ['next', 'prev', 'first', 'last'] as const) {\n for (const key of options.keys?.[action] ?? []) {\n const owner = owners.get(key);\n if (owner && owner !== action)\n throw new FocusConfigError(`Key \"${key}\" is assigned to both ${owner} and ${action}`);\n owners.set(key, action);\n }\n }\n\n let index = -1;\n let typeaheadBuffer = '';\n let lastTypeaheadAt = 0;\n\n const isItemDisabled = (item: T, itemIndex: number): boolean => options.isItemDisabled?.(item, itemIndex) ?? false;\n\n const isUsableIndex = (items: readonly T[], itemIndex: number): boolean =>\n itemIndex >= 0 && itemIndex < items.length && !isItemDisabled(items[itemIndex], itemIndex);\n\n const normalizeIndex = (items: readonly T[]): number => {\n if (!isUsableIndex(items, index)) index = -1;\n\n return index;\n };\n\n const resetTypeahead = (): void => {\n typeaheadBuffer = '';\n lastTypeaheadAt = 0;\n };\n\n const commitIndex = (\n items: readonly T[],\n nextIndex: number,\n action: ListKeyAction,\n event?: KeyboardEvent,\n ): ListNavigationChange<T> | null => {\n if (!isUsableIndex(items, nextIndex)) {\n index = -1;\n\n return null;\n }\n\n index = nextIndex;\n\n return Object.freeze({ action, event, index: nextIndex, item: items[nextIndex] });\n };\n\n const findEnabledIndex = (items: readonly T[], start: number, direction: 'forward' | 'backward'): number => {\n if (direction === 'forward')\n return findForward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n\n return findBackward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n };\n\n const move = (\n items: readonly T[],\n direction: 'forward' | 'backward',\n event?: KeyboardEvent,\n ): ListNavigationChange<T> | null => {\n const current = normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return null;\n }\n\n const start =\n current < 0\n ? direction === 'forward'\n ? 0\n : items.length - 1\n : direction === 'forward'\n ? current + 1\n : current - 1;\n\n const nextIndex = findEnabledIndex(items, start, direction);\n const action: ListNavigationAction = direction === 'forward' ? 'next' : 'prev';\n\n if (nextIndex >= 0) return commitIndex(items, nextIndex, action, event);\n\n if (options.loop) {\n const wrapStart = direction === 'forward' ? 0 : items.length - 1;\n const wrapped = findEnabledIndex(items, wrapStart, direction);\n\n if (wrapped >= 0) return commitIndex(items, wrapped, action, event);\n }\n\n return null;\n };\n\n const navigateWithItems = (\n items: readonly T[],\n action: ListNavigationAction,\n event?: KeyboardEvent,\n ): ListNavigationChange<T> | null => {\n resetTypeahead();\n normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return null;\n }\n\n if (action === 'first') {\n return commitIndex(items, findEnabledIndex(items, 0, 'forward'), action, event);\n }\n\n if (action === 'last') {\n return commitIndex(items, findEnabledIndex(items, items.length - 1, 'backward'), action, event);\n }\n\n return move(items, action === 'next' ? 'forward' : 'backward', event);\n };\n\n const findTypeaheadMatch = (items: readonly T[], search: string, includeCurrent: boolean): number => {\n const current = normalizeIndex(items);\n const start = current < 0 ? 0 : includeCurrent ? current : current + 1;\n\n for (let offset = 0; offset < items.length; offset++) {\n const itemIndex = (start + offset) % items.length;\n const item = items[itemIndex];\n\n if (isItemDisabled(item, itemIndex)) continue;\n\n if (options.typeahead?.getLabel(item, itemIndex).toLocaleLowerCase().startsWith(search)) {\n return itemIndex;\n }\n }\n\n return -1;\n };\n\n const handleTypeahead = (event: KeyboardEvent, items: readonly T[]): ListNavigationChange<T> | null => {\n if (!options.typeahead || event.key.length !== 1 || event.ctrlKey || event.altKey || event.metaKey) return null;\n\n const now = performance.now();\n const key = event.key.toLocaleLowerCase();\n\n if (now - lastTypeaheadAt >= typeaheadDelay) typeaheadBuffer = '';\n\n lastTypeaheadAt = now;\n\n const candidate = typeaheadBuffer + key;\n const repeatedCharacter = candidate.length > 1 && [...candidate].every((character) => character === key);\n typeaheadBuffer = repeatedCharacter ? key : candidate;\n\n let nextIndex = findTypeaheadMatch(items, typeaheadBuffer, typeaheadBuffer.length > 1);\n\n if (nextIndex < 0 && typeaheadBuffer.length > 1) {\n typeaheadBuffer = key;\n nextIndex = findTypeaheadMatch(items, typeaheadBuffer, false);\n }\n\n if (nextIndex < 0) return null;\n\n return commitIndex(items, nextIndex, 'typeahead', event);\n };\n\n const set = (nextIndex: number): number => {\n const items = options.getItems();\n normalizeIndex(items);\n resetTypeahead();\n\n if (!Number.isInteger(nextIndex) || nextIndex < 0 || !items.length) {\n index = -1;\n\n return index;\n }\n\n const clamped = Math.min(nextIndex, items.length - 1);\n\n if (!isUsableIndex(items, clamped)) {\n index = -1;\n\n return index;\n }\n\n index = clamped;\n\n return index;\n };\n\n const navigate = (action: ListNavigationAction): ListNavigationChange<T> | null => {\n return navigateWithItems(options.getItems(), action);\n };\n\n const getActiveItem = (): T | undefined => {\n const items = options.getItems();\n const current = normalizeIndex(items);\n\n return current >= 0 ? items[current] : undefined;\n };\n\n const reset = (): void => {\n index = -1;\n resetTypeahead();\n };\n\n const getIndex = (): number => {\n return normalizeIndex(options.getItems());\n };\n\n const resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n const resolveKeyAction = (event: KeyboardEvent): ListNavigationAction | undefined => {\n const keys = options.keys;\n const keyTable = resolve(options.direction, 'ltr') === 'rtl' ? DEFAULT_KEYS_RTL : DEFAULT_KEYS;\n const defaults = keyTable[resolve(options.orientation, 'vertical')];\n\n for (const action of ['next', 'prev', 'first', 'last'] as const) {\n if ((keys?.[action] ?? defaults[action]).some((pattern) => matchKey(event, pattern))) return action;\n }\n\n return undefined;\n };\n\n const handleKeydown = (event: KeyboardEvent): ListKeyResult<T> | null => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return null;\n\n const items = options.getItems();\n normalizeIndex(items);\n\n const action = resolveKeyAction(event);\n\n if (action) {\n const change = navigateWithItems(items, action, event);\n event.preventDefault();\n return Object.freeze({ change, handled: true });\n }\n\n const change = handleTypeahead(event, items);\n if (!change) return null;\n if (options.typeahead?.preventDefault) event.preventDefault();\n return Object.freeze({ change, handled: true });\n };\n\n return {\n getActiveItem,\n getIndex,\n handleKeydown,\n navigate,\n reset,\n set,\n };\n};\n"],"mappings":"kEA+CA,IAAM,EAA4G,CAChH,KAAM,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,YAAa,YAAY,EAAG,KAAM,CAAC,UAAW,WAAW,CAAE,EAC1G,WAAY,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,YAAY,EAAG,KAAM,CAAC,WAAW,CAAE,EACxF,SAAU,CAAE,MAAO,CAAC,MAAM,EAAG,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Q,WAAW,gBAAgB,EAAM,eAAe,EACrD,OAAO,OAAO,CAAE,SAAQ,QAAS,EAAK,CAAC,GAF1B,IAGtB,EAEA,MAAO,CACL,cACA,SACA,cACA,SACA,MACA,GACF,CACF"}
@@ -1,37 +1,36 @@
1
- export type MaybeGetter<T> = T | (() => T);
2
1
  export type ListNavigationAction = 'first' | 'last' | 'next' | 'prev';
3
2
  export type ListKeyAction = ListNavigationAction | 'typeahead';
4
3
  export type ListNavigationChange<T> = {
5
- action: ListKeyAction;
6
- event?: KeyboardEvent;
7
- index: number;
8
- item: T;
4
+ readonly action: ListKeyAction;
5
+ readonly event?: KeyboardEvent;
6
+ readonly index: number;
7
+ readonly item: T;
8
+ };
9
+ export type ListKeyResult<T> = {
10
+ readonly change: ListNavigationChange<T> | null;
11
+ readonly handled: true;
9
12
  };
10
13
  export type ListNavigationTypeaheadOptions<T> = {
11
14
  delayMs?: number;
12
15
  getLabel: (item: T, index: number) => string;
16
+ preventDefault?: boolean;
13
17
  };
18
+ export type MaybeGetter<T> = T | (() => T);
14
19
  export type ListNavigationOptions<T> = {
15
20
  direction?: MaybeGetter<'ltr' | 'rtl'>;
16
- disabled?: MaybeGetter<boolean | undefined>;
21
+ disabled?: MaybeGetter<boolean>;
17
22
  getItems: () => readonly T[];
18
23
  isItemDisabled?: (item: T, index: number) => boolean;
19
24
  keys?: Partial<Record<ListNavigationAction, readonly string[]>>;
20
25
  loop?: boolean;
21
- onNavigate?: (change: ListNavigationChange<T>) => void;
22
26
  orientation?: MaybeGetter<'both' | 'horizontal' | 'vertical'>;
23
- signal?: AbortSignal;
24
27
  typeahead?: ListNavigationTypeaheadOptions<T>;
25
28
  };
26
29
  export type ListNavigation<T> = {
27
- [Symbol.dispose](): void;
28
- readonly disposalSignal: AbortSignal;
29
- dispose(): void;
30
- readonly disposed: boolean;
31
30
  getActiveItem(): T | undefined;
32
31
  getIndex(): number;
33
- handleKeydown(event: KeyboardEvent): boolean;
34
- navigate(action: ListNavigationAction): number;
32
+ handleKeydown(event: KeyboardEvent): ListKeyResult<T> | null;
33
+ navigate(action: ListNavigationAction): ListNavigationChange<T> | null;
35
34
  reset(): void;
36
35
  set(index: number): number;
37
36
  };
@@ -1 +1 @@
1
- {"version":3,"file":"list-navigation.d.ts","sourceRoot":"","sources":["../src/list-navigation.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;AAE3C,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AACtE,MAAM,MAAM,aAAa,GAAG,oBAAoB,GAAG,WAAW,CAAC;AAE/D,MAAM,MAAM,oBAAoB,CAAC,CAAC,IAAI;IACpC,MAAM,EAAE,aAAa,CAAC;IACtB,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,CAAC,CAAC;CACT,CAAC;AAEF,MAAM,MAAM,8BAA8B,CAAC,CAAC,IAAI;IAC9C,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;CAC9C,CAAC;AAEF,MAAM,MAAM,qBAAqB,CAAC,CAAC,IAAI;IACrC,SAAS,CAAC,EAAE,WAAW,CAAC,KAAK,GAAG,KAAK,CAAC,CAAC;IACvC,QAAQ,CAAC,EAAE,WAAW,CAAC,OAAO,GAAG,SAAS,CAAC,CAAC;IAC5C,QAAQ,EAAE,MAAM,SAAS,CAAC,EAAE,CAAC;IAC7B,cAAc,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC;IACrD,IAAI,CAAC,EAAE,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;IAChE,IAAI,CA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AAC,IAAI;IAC9B,aAAa,IAAI,CAAC,GAAG,SAAS,CAAC;IAC/B,QAAQ,IAAI,MAAM,CAAC;IACnB,aAAa,CAAC,KAAK,EAAE,aAAa,GAAG,aAAa,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IAC7D,QAAQ,CAAC,MAAM,EAAE,oBAAoB,GAAG,oBAAoB,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC;IACvE,KAAK,IAAI,IAAI,CAAC;IACd,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;CAC5B,CAAC;AA2CF,eAAO,MAAM,oBAAoB,GAAI,CAAC,EAAE,SAAS,qBAAqB,CAAC,CAAC,CAAC,KAAG,cAAc,CAAC,CAAC,CA0P3F,CAAC"}
@@ -1,123 +1,2 @@
1
- //#region src/list-navigation.ts
2
- var e = {
3
- both: {
4
- first: ["Home"],
5
- last: ["End"],
6
- next: ["ArrowDown", "ArrowRight"],
7
- prev: ["ArrowUp", "ArrowLeft"]
8
- },
9
- horizontal: {
10
- first: ["Home"],
11
- last: ["End"],
12
- next: ["ArrowRight"],
13
- prev: ["ArrowLeft"]
14
- },
15
- vertical: {
16
- first: ["Home"],
17
- last: ["End"],
18
- next: ["ArrowDown"],
19
- prev: ["ArrowUp"]
20
- }
21
- }, t = {
22
- both: {
23
- first: ["Home"],
24
- last: ["End"],
25
- next: ["ArrowDown", "ArrowLeft"],
26
- prev: ["ArrowUp", "ArrowRight"]
27
- },
28
- horizontal: {
29
- first: ["Home"],
30
- last: ["End"],
31
- next: ["ArrowLeft"],
32
- prev: ["ArrowRight"]
33
- },
34
- vertical: e.vertical
35
- }, n = 500, r = (e, t) => typeof e == "function" ? e() : e ?? t, i = (e, t, n) => {
36
- for (let r = t; r < e.length; r++) if (n(e[r], r)) return r;
37
- return -1;
38
- }, a = (e, t, n) => {
39
- for (let r = t; r >= 0; r--) if (n(e[r], r)) return r;
40
- return -1;
41
- }, o = (e) => typeof e == "number" && Number.isFinite(e) && e > 0 ? e : n, s = (n) => {
42
- let s = new AbortController(), c = -1, l = !1, u = "", d = 0, f, p = (e, t) => n.isItemDisabled?.(e, t) ?? !1, m = (e, t) => t >= 0 && t < e.length && !p(e[t], t), h = (e) => (m(e, c) || (c = -1), c), g = () => {
43
- u = "", d = 0;
44
- }, _ = (e, t, r, i) => m(e, t) ? (c = t, n.onNavigate?.({
45
- action: r,
46
- event: i,
47
- index: t,
48
- item: e[t]
49
- }), c) : (c = -1, c), v = (e, t, n) => n === "forward" ? i(e, t, (e, t) => !p(e, t)) : a(e, t, (e, t) => !p(e, t)), y = (e, t, r) => {
50
- let i = h(e);
51
- if (!e.length) return c = -1, c;
52
- let a = i < 0 ? t === "forward" ? 0 : e.length - 1 : t === "forward" ? i + 1 : i - 1, o = v(e, a, t), s = t === "forward" ? "next" : "prev";
53
- if (o >= 0) return _(e, o, s, r);
54
- if (n.loop) {
55
- let n = t === "forward" ? 0 : e.length - 1, i = v(e, n, t);
56
- if (i >= 0) return _(e, i, s, r);
57
- }
58
- return c;
59
- }, b = (e, t, n) => (g(), h(e), e.length ? t === "first" ? _(e, v(e, 0, "forward"), t, n) : t === "last" ? _(e, v(e, e.length - 1, "backward"), t, n) : y(e, t === "next" ? "forward" : "backward", n) : (c = -1, c)), x = (e, t, r) => {
60
- let i = h(e), a = i < 0 ? 0 : r ? i : i + 1;
61
- for (let r = 0; r < e.length; r++) {
62
- let i = (a + r) % e.length, o = e[i];
63
- if (!p(o, i) && n.typeahead?.getLabel(o, i).toLocaleLowerCase().startsWith(t)) return i;
64
- }
65
- return -1;
66
- }, S = (e, t) => {
67
- if (!n.typeahead || e.key.length !== 1 || e.ctrlKey || e.altKey || e.metaKey) return !1;
68
- let r = Date.now(), i = e.key.toLocaleLowerCase(), a = o(n.typeahead.delayMs);
69
- r - d >= a && (u = ""), d = r;
70
- let s = u + i;
71
- u = s.length > 1 && [...s].every((e) => e === i) ? i : s;
72
- let c = x(t, u, u.length > 1);
73
- return c < 0 && u.length > 1 && (u = i, c = x(t, u, !1)), c < 0 ? !1 : (_(t, c, "typeahead", e), !0);
74
- }, C = (e) => {
75
- if (l) return -1;
76
- let t = n.getItems();
77
- if (h(t), g(), e < 0 || !t.length) return c = -1, c;
78
- let r = Math.min(e, t.length - 1);
79
- return m(t, r) ? (c = r, c) : (c = -1, c);
80
- }, w = (e) => l ? -1 : b(n.getItems(), e), T = () => {
81
- if (l) return;
82
- let e = n.getItems(), t = h(e);
83
- return t >= 0 ? e[t] : void 0;
84
- }, E = () => {
85
- l || (c = -1, g());
86
- }, D = () => l ? -1 : h(n.getItems()), O = (i) => {
87
- let a = n.keys, o = (r(n.direction, "ltr") === "rtl" ? t : e)[r(n.orientation, "vertical")];
88
- for (let e of [
89
- "next",
90
- "prev",
91
- "first",
92
- "last"
93
- ]) if ((a?.[e] ?? o[e]).includes(i)) return e;
94
- }, k = (e) => {
95
- if (l || r(n.disabled, !1)) return !1;
96
- let t = n.getItems();
97
- h(t);
98
- let i = O(e.key);
99
- return i ? (e.preventDefault(), b(t, i, e), !0) : S(e, t);
100
- }, A = () => {
101
- l || (l = !0, c = -1, g(), f?.(), f = void 0, s.abort());
102
- };
103
- return n.signal?.aborted ? A() : n.signal && (n.signal.addEventListener("abort", A, { once: !0 }), f = () => n.signal?.removeEventListener("abort", A)), {
104
- get disposalSignal() {
105
- return s.signal;
106
- },
107
- dispose: A,
108
- get disposed() {
109
- return l;
110
- },
111
- getActiveItem: T,
112
- getIndex: D,
113
- handleKeydown: k,
114
- navigate: w,
115
- reset: E,
116
- set: C,
117
- [Symbol.dispose]: A
118
- };
119
- };
120
- //#endregion
121
- export { s as createListNavigation };
122
-
1
+ import{FocusConfigError as e}from"./errors.js";import{matchKey as t}from"@vielzeug/keymap";var n={both:{first:[`Home`],last:[`End`],next:[`ArrowDown`,`ArrowRight`],prev:[`ArrowUp`,`ArrowLeft`]},horizontal:{first:[`Home`],last:[`End`],next:[`ArrowRight`],prev:[`ArrowLeft`]},vertical:{first:[`Home`],last:[`End`],next:[`ArrowDown`],prev:[`ArrowUp`]}},r={both:{first:[`Home`],last:[`End`],next:[`ArrowDown`,`ArrowLeft`],prev:[`ArrowUp`,`ArrowRight`]},horizontal:{first:[`Home`],last:[`End`],next:[`ArrowLeft`],prev:[`ArrowRight`]},vertical:n.vertical},i=500,findForward=(e,t,n)=>{for(let r=t;r<e.length;r++)if(n(e[r],r))return r;return-1},findBackward=(e,t,n)=>{for(let r=t;r>=0;r--)if(n(e[r],r))return r;return-1},resolveTypeaheadDelay=t=>{if(t===void 0)return i;if(!Number.isFinite(t)||t<=0)throw new e(`Typeahead delay must be a positive finite number`);return t},createListNavigation=i=>{let a=resolveTypeaheadDelay(i.typeahead?.delayMs),o=new Map;for(let t of[`next`,`prev`,`first`,`last`])for(let n of i.keys?.[t]??[]){let r=o.get(n);if(r&&r!==t)throw new e(`Key "${n}" is assigned to both ${r} and ${t}`);o.set(n,t)}let s=-1,c=``,l=0,isItemDisabled=(e,t)=>i.isItemDisabled?.(e,t)??!1,isUsableIndex=(e,t)=>t>=0&&t<e.length&&!isItemDisabled(e[t],t),normalizeIndex=e=>(isUsableIndex(e,s)||(s=-1),s),resetTypeahead=()=>{c=``,l=0},commitIndex=(e,t,n,r)=>isUsableIndex(e,t)?(s=t,Object.freeze({action:n,event:r,index:t,item:e[t]})):(s=-1,null),findEnabledIndex=(e,t,n)=>n===`forward`?findForward(e,t,(e,t)=>!isItemDisabled(e,t)):findBackward(e,t,(e,t)=>!isItemDisabled(e,t)),move=(e,t,n)=>{let r=normalizeIndex(e);if(!e.length)return s=-1,null;let a=r<0?t===`forward`?0:e.length-1:t===`forward`?r+1:r-1,o=findEnabledIndex(e,a,t),c=t===`forward`?`next`:`prev`;if(o>=0)return commitIndex(e,o,c,n);if(i.loop){let r=t===`forward`?0:e.length-1,i=findEnabledIndex(e,r,t);if(i>=0)return commitIndex(e,i,c,n)}return null},navigateWithItems=(e,t,n)=>(resetTypeahead(),normalizeIndex(e),e.length?t===`first`?commitIndex(e,findEnabledIndex(e,0,`forward`),t,n):t===`last`?commitIndex(e,findEnabledIndex(e,e.length-1,`backward`),t,n):move(e,t===`next`?`forward`:`backward`,n):(s=-1,null)),findTypeaheadMatch=(e,t,n)=>{let r=normalizeIndex(e),a=r<0?0:n?r:r+1;for(let n=0;n<e.length;n++){let r=(a+n)%e.length,o=e[r];if(!isItemDisabled(o,r)&&i.typeahead?.getLabel(o,r).toLocaleLowerCase().startsWith(t))return r}return-1},handleTypeahead=(e,t)=>{if(!i.typeahead||e.key.length!==1||e.ctrlKey||e.altKey||e.metaKey)return null;let n=performance.now(),r=e.key.toLocaleLowerCase();n-l>=a&&(c=``),l=n;let o=c+r;c=o.length>1&&[...o].every(e=>e===r)?r:o;let s=findTypeaheadMatch(t,c,c.length>1);return s<0&&c.length>1&&(c=r,s=findTypeaheadMatch(t,c,!1)),s<0?null:commitIndex(t,s,`typeahead`,e)},set=e=>{let t=i.getItems();if(normalizeIndex(t),resetTypeahead(),!Number.isInteger(e)||e<0||!t.length)return s=-1,s;let n=Math.min(e,t.length-1);return isUsableIndex(t,n)?(s=n,s):(s=-1,s)},navigate=e=>navigateWithItems(i.getItems(),e),getActiveItem=()=>{let e=i.getItems(),t=normalizeIndex(e);return t>=0?e[t]:void 0},reset=()=>{s=-1,resetTypeahead()},getIndex=()=>normalizeIndex(i.getItems()),resolve=(e,t)=>typeof e==`function`?e():e??t,resolveKeyAction=e=>{let a=i.keys,o=(resolve(i.direction,`ltr`)===`rtl`?r:n)[resolve(i.orientation,`vertical`)];for(let n of[`next`,`prev`,`first`,`last`])if((a?.[n]??o[n]).some(n=>t(e,n)))return n},handleKeydown=e=>{if(e.defaultPrevented||e.isComposing||resolve(i.disabled,!1))return null;let t=i.getItems();normalizeIndex(t);let n=resolveKeyAction(e);if(n){let r=navigateWithItems(t,n,e);return e.preventDefault(),Object.freeze({change:r,handled:!0})}let r=handleTypeahead(e,t);return r?(i.typeahead?.preventDefault&&e.preventDefault(),Object.freeze({change:r,handled:!0})):null};return{getActiveItem,getIndex,handleKeydown,navigate,reset,set}};export{createListNavigation};
123
2
  //# sourceMappingURL=list-navigation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"list-navigation.js","names":[],"sources":["../src/list-navigation.ts"],"sourcesContent":["export type MaybeGetter<T> = T | (() => T);\n\nexport type ListNavigationAction = 'first' | 'last' | 'next' | 'prev';\nexport type ListKeyAction = ListNavigationAction | 'typeahead';\n\nexport type ListNavigationChange<T> = {\n action: ListKeyAction;\n event?: KeyboardEvent;\n index: number;\n item: T;\n};\n\nexport type ListNavigationTypeaheadOptions<T> = {\n delayMs?: number;\n getLabel: (item: T, index: number) => string;\n};\n\nexport type ListNavigationOptions<T> = {\n direction?: MaybeGetter<'ltr' | 'rtl'>;\n disabled?: MaybeGetter<boolean | undefined>;\n getItems: () => readonly T[];\n isItemDisabled?: (item: T, index: number) => boolean;\n keys?: Partial<Record<ListNavigationAction, readonly string[]>>;\n loop?: boolean;\n onNavigate?: (change: ListNavigationChange<T>) => void;\n orientation?: MaybeGetter<'both' | 'horizontal' | 'vertical'>;\n signal?: AbortSignal;\n typeahead?: ListNavigationTypeaheadOptions<T>;\n};\n\nexport type ListNavigation<T> = {\n [Symbol.dispose](): void;\n readonly disposalSignal: AbortSignal;\n dispose(): void;\n readonly disposed: boolean;\n getActiveItem(): T | undefined;\n getIndex(): number;\n handleKeydown(event: KeyboardEvent): boolean;\n navigate(action: ListNavigationAction): number;\n reset(): void;\n set(index: number): number;\n};\n\nconst DEFAULT_KEYS: Record<'both' | 'horizontal' | 'vertical', Record<ListNavigationAction, readonly string[]>> = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowRight'], prev: ['ArrowUp', 'ArrowLeft'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowRight'], prev: ['ArrowLeft'] },\n vertical: { first: ['Home'], last: ['End'], next: ['ArrowDown'], prev: ['ArrowUp'] },\n};\n\nconst DEFAULT_KEYS_RTL: typeof DEFAULT_KEYS = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowLeft'], prev: ['ArrowUp', 'ArrowRight'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowLeft'], prev: ['ArrowRight'] },\n vertical: DEFAULT_KEYS.vertical,\n};\n\nconst DEFAULT_TYPEAHEAD_DELAY_MS = 500;\n\nconst read = <T>(value: MaybeGetter<T> | undefined, fallback: T): T =>\n typeof value === 'function' ? (value as () => T)() : (value ?? fallback);\n\nconst findForward = <T>(items: readonly T[], start: number, predicate: (item: T, index: number) => boolean): number => {\n for (let index = start; index < items.length; index++) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst findBackward = <T>(\n items: readonly T[],\n start: number,\n predicate: (item: T, index: number) => boolean,\n): number => {\n for (let index = start; index >= 0; index--) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst resolveTypeaheadDelay = (delay: number | undefined): number =>\n typeof delay === 'number' && Number.isFinite(delay) && delay > 0 ? delay : DEFAULT_TYPEAHEAD_DELAY_MS;\n\nexport const createListNavigation = <T>(options: ListNavigationOptions<T>): ListNavigation<T> => {\n const disposalController = new AbortController();\n let index = -1;\n let disposed = false;\n let typeaheadBuffer = '';\n let lastTypeaheadAt = 0;\n let removeExternalAbortListener: (() => void) | undefined;\n\n const isItemDisabled = (item: T, itemIndex: number): boolean => options.isItemDisabled?.(item, itemIndex) ?? false;\n\n const isUsableIndex = (items: readonly T[], itemIndex: number): boolean =>\n itemIndex >= 0 && itemIndex < items.length && !isItemDisabled(items[itemIndex], itemIndex);\n\n const normalizeIndex = (items: readonly T[]): number => {\n if (!isUsableIndex(items, index)) index = -1;\n\n return index;\n };\n\n const resetTypeahead = (): void => {\n typeaheadBuffer = '';\n lastTypeaheadAt = 0;\n };\n\n const commitIndex = (\n items: readonly T[],\n nextIndex: number,\n action: ListKeyAction,\n event?: KeyboardEvent,\n ): number => {\n if (!isUsableIndex(items, nextIndex)) {\n index = -1;\n\n return index;\n }\n\n index = nextIndex;\n options.onNavigate?.({ action, event, index: nextIndex, item: items[nextIndex] });\n\n return index;\n };\n\n const findEnabledIndex = (items: readonly T[], start: number, direction: 'forward' | 'backward'): number => {\n if (direction === 'forward')\n return findForward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n\n return findBackward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n };\n\n const move = (items: readonly T[], direction: 'forward' | 'backward', event?: KeyboardEvent): number => {\n const current = normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return index;\n }\n\n const start =\n current < 0\n ? direction === 'forward'\n ? 0\n : items.length - 1\n : direction === 'forward'\n ? current + 1\n : current - 1;\n\n const nextIndex = findEnabledIndex(items, start, direction);\n const action: ListNavigationAction = direction === 'forward' ? 'next' : 'prev';\n\n if (nextIndex >= 0) return commitIndex(items, nextIndex, action, event);\n\n if (options.loop) {\n const wrapStart = direction === 'forward' ? 0 : items.length - 1;\n const wrapped = findEnabledIndex(items, wrapStart, direction);\n\n if (wrapped >= 0) return commitIndex(items, wrapped, action, event);\n }\n\n return index;\n };\n\n const navigateWithItems = (items: readonly T[], action: ListNavigationAction, event?: KeyboardEvent): number => {\n resetTypeahead();\n normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return index;\n }\n\n if (action === 'first') {\n return commitIndex(items, findEnabledIndex(items, 0, 'forward'), action, event);\n }\n\n if (action === 'last') {\n return commitIndex(items, findEnabledIndex(items, items.length - 1, 'backward'), action, event);\n }\n\n return move(items, action === 'next' ? 'forward' : 'backward', event);\n };\n\n const findTypeaheadMatch = (items: readonly T[], search: string, includeCurrent: boolean): number => {\n const current = normalizeIndex(items);\n const start = current < 0 ? 0 : includeCurrent ? current : current + 1;\n\n for (let offset = 0; offset < items.length; offset++) {\n const itemIndex = (start + offset) % items.length;\n const item = items[itemIndex];\n\n if (isItemDisabled(item, itemIndex)) continue;\n\n if (options.typeahead?.getLabel(item, itemIndex).toLocaleLowerCase().startsWith(search)) {\n return itemIndex;\n }\n }\n\n return -1;\n };\n\n const handleTypeahead = (event: KeyboardEvent, items: readonly T[]): boolean => {\n if (!options.typeahead || event.key.length !== 1 || event.ctrlKey || event.altKey || event.metaKey) return false;\n\n const now = Date.now();\n const key = event.key.toLocaleLowerCase();\n const delay = resolveTypeaheadDelay(options.typeahead.delayMs);\n\n if (now - lastTypeaheadAt >= delay) typeaheadBuffer = '';\n\n lastTypeaheadAt = now;\n\n const candidate = typeaheadBuffer + key;\n const repeatedCharacter = candidate.length > 1 && [...candidate].every((character) => character === key);\n typeaheadBuffer = repeatedCharacter ? key : candidate;\n\n let nextIndex = findTypeaheadMatch(items, typeaheadBuffer, typeaheadBuffer.length > 1);\n\n if (nextIndex < 0 && typeaheadBuffer.length > 1) {\n typeaheadBuffer = key;\n nextIndex = findTypeaheadMatch(items, typeaheadBuffer, false);\n }\n\n if (nextIndex < 0) return false;\n\n commitIndex(items, nextIndex, 'typeahead', event);\n\n return true;\n };\n\n const set = (nextIndex: number): number => {\n if (disposed) return -1;\n\n const items = options.getItems();\n normalizeIndex(items);\n resetTypeahead();\n\n if (nextIndex < 0 || !items.length) {\n index = -1;\n\n return index;\n }\n\n const clamped = Math.min(nextIndex, items.length - 1);\n\n if (!isUsableIndex(items, clamped)) {\n index = -1;\n\n return index;\n }\n\n index = clamped;\n\n return index;\n };\n\n const navigate = (action: ListNavigationAction): number => {\n if (disposed) return -1;\n\n return navigateWithItems(options.getItems(), action);\n };\n\n const getActiveItem = (): T | undefined => {\n if (disposed) return undefined;\n\n const items = options.getItems();\n const current = normalizeIndex(items);\n\n return current >= 0 ? items[current] : undefined;\n };\n\n const reset = (): void => {\n if (disposed) return;\n\n index = -1;\n resetTypeahead();\n };\n\n const getIndex = (): number => {\n if (disposed) return -1;\n\n return normalizeIndex(options.getItems());\n };\n\n const resolveKeyAction = (eventKey: string): ListNavigationAction | undefined => {\n const keys = options.keys;\n const keyTable = read(options.direction, 'ltr') === 'rtl' ? DEFAULT_KEYS_RTL : DEFAULT_KEYS;\n const defaults = keyTable[read(options.orientation, 'vertical')];\n\n for (const action of ['next', 'prev', 'first', 'last'] as const) {\n if ((keys?.[action] ?? defaults[action]).includes(eventKey)) return action;\n }\n\n return undefined;\n };\n\n const handleKeydown = (event: KeyboardEvent): boolean => {\n if (disposed || read(options.disabled, false)) return false;\n\n const items = options.getItems();\n normalizeIndex(items);\n\n const action = resolveKeyAction(event.key);\n\n if (action) {\n event.preventDefault();\n navigateWithItems(items, action, event);\n\n return true;\n }\n\n return handleTypeahead(event, items);\n };\n\n const dispose = (): void => {\n if (disposed) return;\n\n disposed = true;\n index = -1;\n resetTypeahead();\n removeExternalAbortListener?.();\n removeExternalAbortListener = undefined;\n disposalController.abort();\n };\n\n if (options.signal?.aborted) {\n dispose();\n } else if (options.signal) {\n options.signal.addEventListener('abort', dispose, { once: true });\n removeExternalAbortListener = () => options.signal?.removeEventListener('abort', dispose);\n }\n\n return {\n get disposalSignal() {\n return disposalController.signal;\n },\n dispose,\n get disposed() {\n return disposed;\n },\n getActiveItem,\n getIndex,\n handleKeydown,\n navigate,\n reset,\n set,\n [Symbol.dispose]: dispose,\n };\n};\n"],"mappings":";AA2CA,IAAM,IAA4G;CAChH,MAAM;EAAE,OAAO,CAAC,MAAM;EAAG,MAAM,CAAC,KAAK;EAAG,MAAM,CAAC,aAAa,YAAY;EAAG,MAAM,CAAC,WAAW,WAAW;CAAE;CAC1G,YAAY;EAAE,OAAO,CAAC,MAAM;EAAG,MAAM,CAAC,KAAK;EAAG,MAAM,CAAC,YAAY;EAAG,MAAM,CAAC,WAAW;CAAE;CACxF,UAAU;EAAE,OAAO,CAAC,MAAM;EAAG,MAAM,CAAC,KAAK;EAAG,MAAM,CAAC,WAAW;EAAG,MAAM,CAAC,SAAS;CAAE;AACrF,GAEM,IAAwC;CAC5C,MAAM;EAAE,OAAO,CAAC,MAAM;EAAG,MAAM,CAAC,KAAK;EAAG,MAAM,CAAC,aAAa,WAAW;EAAG,MA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ACjB,GAEM,UACA,IAAiB,KAEd,EAAe,EAAQ,SAAS,CAAC,GAGpC,KAAoB,MAAuD;EAC/E,IAAM,IAAO,EAAQ,MAEf,KADW,EAAK,EAAQ,WAAW,KAAK,MAAM,QAAQ,IAAmB,EAAA,CACrD,EAAK,EAAQ,aAAa,UAAU;EAE9D,KAAK,IAAM,KAAU;GAAC;GAAQ;GAAQ;GAAS;EAAM,GACnD,KAAK,IAAO,MAAW,EAAS,GAAA,CAAS,SAAS,CAAQ,GAAG,OAAO;CAIxE,GAEM,KAAiB,MAAkC;EACvD,IAAI,KAAY,EAAK,EAAQ,UAAU,EAAK,GAAG,OAAO;EAEtD,IAAM,IAAQ,EAAQ,SAAS;EAC/B,EAAe,CAAK;EAEpB,IAAM,IAAS,EAAiB,EAAM,GAAG;EASzC,OAPI,KACF,EAAM,eAAe,GACrB,EAAkB,GAAO,GAAQ,CAAK,GAE/B,MAGF,EAAgB,GAAO,CAAK;CACrC,GAEM,UAAsB;EACtB,MAEJ,IAAW,IACX,IAAQ,IACR,EAAe,GACf,IAA8B,GAC9B,IAA8B,KAAA,GAC9B,EAAmB,MAAM;CAC3B;CASA,OAPI,EAAQ,QAAQ,UAClB,EAAQ,IACC,EAAQ,WACjB,EAAQ,OAAO,iBAAiB,SAAS,GAAS,EAAE,MAAM,GAAK,CAAC,GAChE,UAAoC,EAAQ,QAAQ,oBAAoB,SAAS,CAAO,IAGnF;EACL,IAAI,iBAAiB;GACnB,OAAO,EAAmB;EAC5B;EACA;EACA,IAAI,WAAW;GACb,OAAO;EACT;EACA;EACA;EACA;EACA;EACA;EACA;GACC,OAAO,UAAU;CACpB;AACF"}
1
+ {"version":3,"file":"list-navigation.js","names":[],"sources":["../src/list-navigation.ts"],"sourcesContent":["import { matchKey } from '@vielzeug/keymap';\n\nimport { FocusConfigError } from './errors.js';\n\nexport type ListNavigationAction = 'first' | 'last' | 'next' | 'prev';\nexport type ListKeyAction = ListNavigationAction | 'typeahead';\n\nexport type ListNavigationChange<T> = {\n readonly action: ListKeyAction;\n readonly event?: KeyboardEvent;\n readonly index: number;\n readonly item: T;\n};\n\nexport type ListKeyResult<T> = {\n readonly change: ListNavigationChange<T> | null;\n readonly handled: true;\n};\n\nexport type ListNavigationTypeaheadOptions<T> = {\n delayMs?: number;\n getLabel: (item: T, index: number) => string;\n preventDefault?: boolean;\n};\n\nexport type MaybeGetter<T> = T | (() => T);\n\nexport type ListNavigationOptions<T> = {\n direction?: MaybeGetter<'ltr' | 'rtl'>;\n disabled?: MaybeGetter<boolean>;\n getItems: () => readonly T[];\n isItemDisabled?: (item: T, index: number) => boolean;\n keys?: Partial<Record<ListNavigationAction, readonly string[]>>;\n loop?: boolean;\n orientation?: MaybeGetter<'both' | 'horizontal' | 'vertical'>;\n typeahead?: ListNavigationTypeaheadOptions<T>;\n};\n\nexport type ListNavigation<T> = {\n getActiveItem(): T | undefined;\n getIndex(): number;\n handleKeydown(event: KeyboardEvent): ListKeyResult<T> | null;\n navigate(action: ListNavigationAction): ListNavigationChange<T> | null;\n reset(): void;\n set(index: number): number;\n};\n\nconst DEFAULT_KEYS: Record<'both' | 'horizontal' | 'vertical', Record<ListNavigationAction, readonly string[]>> = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowRight'], prev: ['ArrowUp', 'ArrowLeft'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowRight'], prev: ['ArrowLeft'] },\n vertical: { first: ['Home'], last: ['End'], next: ['ArrowDown'], prev: ['ArrowUp'] },\n};\n\nconst DEFAULT_KEYS_RTL: typeof DEFAULT_KEYS = {\n both: { first: ['Home'], last: ['End'], next: ['ArrowDown', 'ArrowLeft'], prev: ['ArrowUp', 'ArrowRight'] },\n horizontal: { first: ['Home'], last: ['End'], next: ['ArrowLeft'], prev: ['ArrowRight'] },\n vertical: DEFAULT_KEYS.vertical,\n};\n\nconst DEFAULT_TYPEAHEAD_DELAY_MS = 500;\n\nconst findForward = <T>(items: readonly T[], start: number, predicate: (item: T, index: number) => boolean): number => {\n for (let index = start; index < items.length; index++) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst findBackward = <T>(\n items: readonly T[],\n start: number,\n predicate: (item: T, index: number) => boolean,\n): number => {\n for (let index = start; index >= 0; index--) {\n if (predicate(items[index], index)) return index;\n }\n\n return -1;\n};\n\nconst resolveTypeaheadDelay = (delay: number | undefined): number => {\n if (delay === undefined) return DEFAULT_TYPEAHEAD_DELAY_MS;\n if (!Number.isFinite(delay) || delay <= 0)\n throw new FocusConfigError('Typeahead delay must be a positive finite number');\n return delay;\n};\n\nexport const createListNavigation = <T>(options: ListNavigationOptions<T>): ListNavigation<T> => {\n const typeaheadDelay = resolveTypeaheadDelay(options.typeahead?.delayMs);\n const owners = new Map<string, ListNavigationAction>();\n\n for (const action of ['next', 'prev', 'first', 'last'] as const) {\n for (const key of options.keys?.[action] ?? []) {\n const owner = owners.get(key);\n if (owner && owner !== action)\n throw new FocusConfigError(`Key \"${key}\" is assigned to both ${owner} and ${action}`);\n owners.set(key, action);\n }\n }\n\n let index = -1;\n let typeaheadBuffer = '';\n let lastTypeaheadAt = 0;\n\n const isItemDisabled = (item: T, itemIndex: number): boolean => options.isItemDisabled?.(item, itemIndex) ?? false;\n\n const isUsableIndex = (items: readonly T[], itemIndex: number): boolean =>\n itemIndex >= 0 && itemIndex < items.length && !isItemDisabled(items[itemIndex], itemIndex);\n\n const normalizeIndex = (items: readonly T[]): number => {\n if (!isUsableIndex(items, index)) index = -1;\n\n return index;\n };\n\n const resetTypeahead = (): void => {\n typeaheadBuffer = '';\n lastTypeaheadAt = 0;\n };\n\n const commitIndex = (\n items: readonly T[],\n nextIndex: number,\n action: ListKeyAction,\n event?: KeyboardEvent,\n ): ListNavigationChange<T> | null => {\n if (!isUsableIndex(items, nextIndex)) {\n index = -1;\n\n return null;\n }\n\n index = nextIndex;\n\n return Object.freeze({ action, event, index: nextIndex, item: items[nextIndex] });\n };\n\n const findEnabledIndex = (items: readonly T[], start: number, direction: 'forward' | 'backward'): number => {\n if (direction === 'forward')\n return findForward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n\n return findBackward(items, start, (item, itemIndex) => !isItemDisabled(item, itemIndex));\n };\n\n const move = (\n items: readonly T[],\n direction: 'forward' | 'backward',\n event?: KeyboardEvent,\n ): ListNavigationChange<T> | null => {\n const current = normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return null;\n }\n\n const start =\n current < 0\n ? direction === 'forward'\n ? 0\n : items.length - 1\n : direction === 'forward'\n ? current + 1\n : current - 1;\n\n const nextIndex = findEnabledIndex(items, start, direction);\n const action: ListNavigationAction = direction === 'forward' ? 'next' : 'prev';\n\n if (nextIndex >= 0) return commitIndex(items, nextIndex, action, event);\n\n if (options.loop) {\n const wrapStart = direction === 'forward' ? 0 : items.length - 1;\n const wrapped = findEnabledIndex(items, wrapStart, direction);\n\n if (wrapped >= 0) return commitIndex(items, wrapped, action, event);\n }\n\n return null;\n };\n\n const navigateWithItems = (\n items: readonly T[],\n action: ListNavigationAction,\n event?: KeyboardEvent,\n ): ListNavigationChange<T> | null => {\n resetTypeahead();\n normalizeIndex(items);\n\n if (!items.length) {\n index = -1;\n\n return null;\n }\n\n if (action === 'first') {\n return commitIndex(items, findEnabledIndex(items, 0, 'forward'), action, event);\n }\n\n if (action === 'last') {\n return commitIndex(items, findEnabledIndex(items, items.length - 1, 'backward'), action, event);\n }\n\n return move(items, action === 'next' ? 'forward' : 'backward', event);\n };\n\n const findTypeaheadMatch = (items: readonly T[], search: string, includeCurrent: boolean): number => {\n const current = normalizeIndex(items);\n const start = current < 0 ? 0 : includeCurrent ? current : current + 1;\n\n for (let offset = 0; offset < items.length; offset++) {\n const itemIndex = (start + offset) % items.length;\n const item = items[itemIndex];\n\n if (isItemDisabled(item, itemIndex)) continue;\n\n if (options.typeahead?.getLabel(item, itemIndex).toLocaleLowerCase().startsWith(search)) {\n return itemIndex;\n }\n }\n\n return -1;\n };\n\n const handleTypeahead = (event: KeyboardEvent, items: readonly T[]): ListNavigationChange<T> | null => {\n if (!options.typeahead || event.key.length !== 1 || event.ctrlKey || event.altKey || event.metaKey) return null;\n\n const now = performance.now();\n const key = event.key.toLocaleLowerCase();\n\n if (now - lastTypeaheadAt >= typeaheadDelay) typeaheadBuffer = '';\n\n lastTypeaheadAt = now;\n\n const candidate = typeaheadBuffer + key;\n const repeatedCharacter = candidate.length > 1 && [...candidate].every((character) => character === key);\n typeaheadBuffer = repeatedCharacter ? key : candidate;\n\n let nextIndex = findTypeaheadMatch(items, typeaheadBuffer, typeaheadBuffer.length > 1);\n\n if (nextIndex < 0 && typeaheadBuffer.length > 1) {\n typeaheadBuffer = key;\n nextIndex = findTypeaheadMatch(items, typeaheadBuffer, false);\n }\n\n if (nextIndex < 0) return null;\n\n return commitIndex(items, nextIndex, 'typeahead', event);\n };\n\n const set = (nextIndex: number): number => {\n const items = options.getItems();\n normalizeIndex(items);\n resetTypeahead();\n\n if (!Number.isInteger(nextIndex) || nextIndex < 0 || !items.length) {\n index = -1;\n\n return index;\n }\n\n const clamped = Math.min(nextIndex, items.length - 1);\n\n if (!isUsableIndex(items, clamped)) {\n index = -1;\n\n return index;\n }\n\n index = clamped;\n\n return index;\n };\n\n const navigate = (action: ListNavigationAction): ListNavigationChange<T> | null => {\n return navigateWithItems(options.getItems(), action);\n };\n\n const getActiveItem = (): T | undefined => {\n const items = options.getItems();\n const current = normalizeIndex(items);\n\n return current >= 0 ? items[current] : undefined;\n };\n\n const reset = (): void => {\n index = -1;\n resetTypeahead();\n };\n\n const getIndex = (): number => {\n return normalizeIndex(options.getItems());\n };\n\n const resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n const resolveKeyAction = (event: KeyboardEvent): ListNavigationAction | undefined => {\n const keys = options.keys;\n const keyTable = resolve(options.direction, 'ltr') === 'rtl' ? DEFAULT_KEYS_RTL : DEFAULT_KEYS;\n const defaults = keyTable[resolve(options.orientation, 'vertical')];\n\n for (const action of ['next', 'prev', 'first', 'last'] as const) {\n if ((keys?.[action] ?? defaults[action]).some((pattern) => matchKey(event, pattern))) return action;\n }\n\n return undefined;\n };\n\n const handleKeydown = (event: KeyboardEvent): ListKeyResult<T> | null => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return null;\n\n const items = options.getItems();\n normalizeIndex(items);\n\n const action = resolveKeyAction(event);\n\n if (action) {\n const change = navigateWithItems(items, action, event);\n event.preventDefault();\n return Object.freeze({ change, handled: true });\n }\n\n const change = handleTypeahead(event, items);\n if (!change) return null;\n if (options.typeahead?.preventDefault) event.preventDefault();\n return Object.freeze({ change, handled: true });\n };\n\n return {\n getActiveItem,\n getIndex,\n handleKeydown,\n navigate,\n reset,\n set,\n };\n};\n"],"mappings":"2FA+CA,IAAM,EAA4G,CAChH,KAAM,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,YAAa,YAAY,EAAG,KAAM,CAAC,UAAW,WAAW,CAAE,EAC1G,WAAY,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,YAAY,EAAG,KAAM,CAAC,WAAW,CAAE,EACxF,SAAU,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,WAAW,EAAG,KAAM,CAAC,SAAS,CAAE,CACrF,EAEM,EAAwC,CAC5C,KAAM,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,YAAa,WAAW,EAAG,KAAM,CAAC,UAAW,YAAY,CAAE,EAC1G,WAAY,CAAE,MAAO,CAAC,MAAM,EAAG,KAAM,CAAC,KAAK,EAAG,KAAM,CAAC,WAAW,EAAG,KAAM,CAAC,YAAY,CAAE,EACxF,SAAU,EAAa,QACzB,EAEM,EAA6B,IAE7B,aAAkB,EAAqB,EAAe,IAA2D,CACrH,IA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EAEM,aACG,eAAe,EAAQ,SAAS,CAAC,EAGpC,SAAc,EAAmC,IACrD,OAAO,GAAU,WAAc,EAAkB,EAAK,GAAS,EAE3D,iBAAoB,GAA2D,CACnF,IAAM,EAAO,EAAQ,KAEf,GADW,QAAQ,EAAQ,UAAW,KAAK,IAAM,MAAQ,EAAmB,EAAA,CACxD,QAAQ,EAAQ,YAAa,UAAU,GAEjE,IAAK,IAAM,IAAU,CAAC,OAAQ,OAAQ,QAAS,MAAM,EACnD,IAAK,IAAO,IAAW,EAAS,GAAA,CAAS,KAAM,GAAY,EAAS,EAAO,CAAO,CAAC,EAAG,OAAO,CAIjG,EAEM,cAAiB,GAAkD,CACvE,GAAI,EAAM,kBAAoB,EAAM,aAAe,QAAQ,EAAQ,SAAU,EAAK,EAAG,OAAO,KAE5F,IAAM,EAAQ,EAAQ,SAAS,EAC/B,eAAe,CAAK,EAEpB,IAAM,EAAS,iBAAiB,CAAK,EAErC,GAAI,EAAQ,CACV,IAAM,EAAS,kBAAkB,EAAO,EAAQ,CAAK,EAErD,OADA,EAAM,eAAe,EACd,OAAO,OAAO,CAAE,SAAQ,QAAS,EAAK,CAAC,CAChD,CAEA,IAAM,EAAS,gBAAgB,EAAO,CAAK,EAG3C,OAFK,GACD,EAAQ,WAAW,gBAAgB,EAAM,eAAe,EACrD,OAAO,OAAO,CAAE,SAAQ,QAAS,EAAK,CAAC,GAF1B,IAGtB,EAEA,MAAO,CACL,cACA,SACA,cACA,SACA,MACA,GACF,CACF"}
@@ -1,2 +1,2 @@
1
- var e=e=>typeof e==`function`?e():e,t=e=>{let t=e.activeElement;for(;t instanceof HTMLElement&&t.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t},n=e=>e.isConnected,r=e=>e instanceof HTMLElement&&`disabled`in e&&!!e.disabled,i=e=>e.closest(`[inert]`)?!0:e instanceof HTMLElement&&e.inert,a=e=>n(e)&&!r(e)&&!i(e),o=(e,n)=>(e.focus({preventScroll:n}),t(e.ownerDocument)===e),s=(t,n={})=>{let r=e(t);if(r&&a(r)&&o(r,n.preventScroll))return!0;if(!n.fallback)return!1;let i=e(n.fallback);return!i||!a(i)?!1:o(i,n.preventScroll)},c=(e={})=>{let n=t(document),r=!e.signal?.aborted;r||(n=null);let i=()=>{r=!1,n=null};return e.signal?.aborted||e.signal?.addEventListener(`abort`,i,{once:!0}),()=>{if(!r)return!1;r=!1,e.signal?.removeEventListener(`abort`,i);let t=n;return n=null,t?s(t,{fallback:e.fallback,preventScroll:e.preventScroll}):e.fallback?s(e.fallback,{preventScroll:e.preventScroll}):!1}};exports.captureFocus=c,exports.restoreFocus=s;
1
+ var resolveTarget=e=>typeof e==`function`?e():e,getDeepActiveElement=e=>{let t=e.activeElement;for(;t instanceof HTMLElement&&t.shadowRoot?.activeElement;)t=t.shadowRoot.activeElement;return t},isConnected=e=>e.isConnected,isDisabled=e=>e instanceof HTMLElement&&`disabled`in e&&!!e.disabled,isInert=e=>e.closest(`[inert]`)?!0:e instanceof HTMLElement&&e.inert,canRestoreTo=e=>isConnected(e)&&!isDisabled(e)&&!isInert(e),focusAndVerify=(e,t)=>{try{return e.focus({preventScroll:t}),getDeepActiveElement(e.ownerDocument)===e}catch{return!1}},restoreFocus=(e,t={})=>{let n;try{n=resolveTarget(e)}catch{n=null}if(n&&canRestoreTo(n)&&focusAndVerify(n,t.preventScroll))return!0;if(!t.fallback)return!1;let r;try{r=resolveTarget(t.fallback)}catch{return!1}return!r||!canRestoreTo(r)?!1:focusAndVerify(r,t.preventScroll)},rescueFocus=(e,t={})=>{let n=getDeepActiveElement(document);return n&&n!==document.body?!1:restoreFocus(e,t)},captureFocus=(e={})=>{let t=getDeepActiveElement(document),n=!e.signal?.aborted;n||(t=null);let cancel=()=>{n=!1,t=null};return e.signal?.aborted||e.signal?.addEventListener(`abort`,cancel,{once:!0}),()=>{if(!n)return!1;n=!1,e.signal?.removeEventListener(`abort`,cancel);let r=t;return t=null,r?restoreFocus(r,{fallback:e.fallback,preventScroll:e.preventScroll}):e.fallback?restoreFocus(e.fallback,{preventScroll:e.preventScroll}):!1}};exports.captureFocus=captureFocus,exports.rescueFocus=rescueFocus,exports.restoreFocus=restoreFocus;
2
2
  //# sourceMappingURL=restore-focus.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"restore-focus.cjs","names":[],"sources":["../src/restore-focus.ts"],"sourcesContent":["export type FocusableElement = HTMLElement | SVGElement;\nexport type FocusTarget = FocusableElement | null | undefined | (() => FocusableElement | null | undefined);\n\nexport type RestoreFocusOptions = {\n fallback?: FocusTarget;\n preventScroll?: boolean;\n};\n\nexport type CaptureFocusOptions = RestoreFocusOptions & {\n signal?: AbortSignal;\n};\n\nexport type FocusRestorer = () => boolean;\n\nconst resolveTarget = (target: FocusTarget): FocusableElement | null | undefined => {\n return typeof target === 'function' ? target() : target;\n};\n\nconst getDeepActiveElement = (rootDocument: Document): Element | null => {\n let active: Element | null = rootDocument.activeElement;\n\n while (active instanceof HTMLElement && active.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n\n return active;\n};\n\nconst isConnected = (target: FocusableElement): boolean => {\n // `isConnected` pierces shadow boundaries (shadow-including root is the document);\n // `ownerDocument.contains` does NOT — it would reject elements inside shadow roots.\n return target.isConnected;\n};\n\nconst isDisabled = (target: FocusableElement): boolean => {\n return target instanceof HTMLElement && 'disabled' in target && Boolean((target as HTMLInputElement).disabled);\n};\n\nconst isInert = (target: FocusableElement): boolean => {\n if (target.closest('[inert]')) return true;\n\n return target instanceof HTMLElement && target.inert;\n};\n\nconst canRestoreTo = (target: FocusableElement): boolean => {\n return isConnected(target) && !isDisabled(target) && !isInert(target);\n};\n\nconst focusAndVerify = (target: FocusableElement, preventScroll: boolean | undefined): boolean => {\n target.focus({ preventScroll });\n\n return getDeepActiveElement(target.ownerDocument) === target;\n};\n\nexport const restoreFocus = (target: FocusTarget, options: RestoreFocusOptions = {}): boolean => {\n const next = resolveTarget(target);\n\n if (next && canRestoreTo(next) && focusAndVerify(next, options.preventScroll)) {\n return true;\n }\n\n if (!options.fallback) return false;\n\n const fallback = resolveTarget(options.fallback);\n\n if (!fallback || !canRestoreTo(fallback)) return false;\n\n return focusAndVerify(fallback, options.preventScroll);\n};\n\nexport const captureFocus = (options: CaptureFocusOptions = {}): FocusRestorer => {\n let captured = getDeepActiveElement(document) as FocusableElement | null;\n let available = !options.signal?.aborted;\n\n if (!available) captured = null;\n\n const cancel = (): void => {\n available = false;\n captured = null;\n };\n\n if (!options.signal?.aborted) {\n options.signal?.addEventListener('abort', cancel, { once: true });\n }\n\n return () => {\n if (!available) return false;\n\n available = false;\n options.signal?.removeEventListener('abort', cancel);\n\n const target = captured;\n captured = null;\n\n if (target) {\n return restoreFocus(target, {\n fallback: options.fallback,\n preventScroll: options.preventScroll,\n });\n }\n\n if (options.fallback) {\n return restoreFocus(options.fallback, {\n preventScroll: options.preventScroll,\n });\n }\n\n return false;\n };\n};\n"],"mappings":"AAcA,IAAM,EAAiB,GACd,OAAO,GAAW,WAAa,EAAO,EAAI,EAG7C,EAAwB,GAA2C,CACvE,IAAI,EAAyB,EAAa,cAE1C,KAAO,aAAkB,aAAe,EAAO,YAAY,eACzD,EAAS,EAAO,WAAW,cAG7B,OAAO,CACT,EAEM,EAAe,GAGZ,EAAO,YAGV,EAAc,GACX,aAAkB,aAAe,aAAc,GAAU,EAAS,EAA4B,SAGjG,EAAW,GACX,EAAO,QAAQ,SAAS,EAAU,GAE/B,aAAkB,aAAe,EAAO,MAG3C,EAAgB,GACb,EAAY,CAAM,GAAK,CAAC,EAAW,CAAM,GAAK,CAAC,EAAQ,CAAM,EAGhE,GAAkB,EAA0B,KAChD,EAAO,MAAM,CAAE,eAAc,CAAC,EAEvB,EAAqB,EAAO,aAAa,IAAM,GAG3C,GAAgB,EAAqB,EAA+B,CAAC,IAAe,CAC/F,IAAM,EAAO,EAAc,CAAM,EAEjC,GAAI,GAAQ,EAAa,CAAI,GAAK,EAAe,EAAM,EAAQ,aAAa,EAC1E,MAAO,GAGT,GAAI,CAAC,EAAQ,SAAU,MAAO,GAE9B,IAAM,EAAW,EAAc,EAAQ,QAAQ,EAI/C,MAFI,CAAC,GAAY,CAAC,EAAa,CAAQ,EAAU,GAE1C,EAAe,EAAU,EAAQ,aAAa,CACvD,EAEa,GAAgB,EAA+B,CAAC,IAAqB,CAChF,IAAI,EAAW,EAAqB,QAAQ,EACxC,EAAY,CAAC,EAAQ,QAAQ,QAE5B,IAAW,EAAW,MAE3B,IAAM,MAAqB,CACzB,EAAY,GACZ,EAAW,IACb,EAMA,OAJK,EAAQ,QAAQ,SACnB,EAAQ,QAAQ,iBAAiB,QAAS,EAAQ,CAAE,KAAM,EAAK,CAAC,MAGrD,CACX,GAAI,CAAC,EAAW,MAAO,GAEvB,EAAY,GACZ,EAAQ,QAAQ,oBAAoB,QAAS,CAAM,EAEnD,IAAM,EAAS,EAgBf,MAfA,GAAW,KAEP,EACK,EAAa,EAAQ,CAC1B,SAAU,EAAQ,SAClB,cAAe,EAAQ,aACzB,CAAC,EAGC,EAAQ,SACH,EAAa,EAAQ,SAAU,CACpC,cAAe,EAAQ,aACzB,CAAC,EAGI,EACT,CACF"}
1
+ {"version":3,"file":"restore-focus.cjs","names":[],"sources":["../src/restore-focus.ts"],"sourcesContent":["export type FocusableElement = HTMLElement | SVGElement;\nexport type FocusTarget = FocusableElement | null | undefined | (() => FocusableElement | null | undefined);\n\nexport type RestoreFocusOptions = {\n fallback?: FocusTarget;\n preventScroll?: boolean;\n};\n\nexport type CaptureFocusOptions = RestoreFocusOptions & {\n signal?: AbortSignal;\n};\n\nexport type FocusRestorer = () => boolean;\n\nconst resolveTarget = (target: FocusTarget): FocusableElement | null | undefined => {\n return typeof target === 'function' ? target() : target;\n};\n\nconst getDeepActiveElement = (rootDocument: Document): Element | null => {\n let active: Element | null = rootDocument.activeElement;\n\n while (active instanceof HTMLElement && active.shadowRoot?.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n\n return active;\n};\n\nconst isConnected = (target: FocusableElement): boolean => {\n // `isConnected` pierces shadow boundaries (shadow-including root is the document);\n // `ownerDocument.contains` does NOT — it would reject elements inside shadow roots.\n return target.isConnected;\n};\n\nconst isDisabled = (target: FocusableElement): boolean => {\n return target instanceof HTMLElement && 'disabled' in target && Boolean((target as HTMLInputElement).disabled);\n};\n\nconst isInert = (target: FocusableElement): boolean => {\n if (target.closest('[inert]')) return true;\n\n return target instanceof HTMLElement && target.inert;\n};\n\nconst canRestoreTo = (target: FocusableElement): boolean => {\n return isConnected(target) && !isDisabled(target) && !isInert(target);\n};\n\nconst focusAndVerify = (target: FocusableElement, preventScroll: boolean | undefined): boolean => {\n try {\n target.focus({ preventScroll });\n return getDeepActiveElement(target.ownerDocument) === target;\n } catch {\n return false;\n }\n};\n\nexport const restoreFocus = (target: FocusTarget, options: RestoreFocusOptions = {}): boolean => {\n let next: FocusableElement | null | undefined;\n try {\n next = resolveTarget(target);\n } catch {\n next = null;\n }\n\n if (next && canRestoreTo(next) && focusAndVerify(next, options.preventScroll)) {\n return true;\n }\n\n if (!options.fallback) return false;\n\n let fallback: FocusableElement | null | undefined;\n try {\n fallback = resolveTarget(options.fallback);\n } catch {\n return false;\n }\n\n if (!fallback || !canRestoreTo(fallback)) return false;\n\n return focusAndVerify(fallback, options.preventScroll);\n};\n\n/**\n * Hands focus to `target` when focus has been lost to the document body — the state left\n * behind when the focused element unmounts mid-swap (browsing a dialog, paging a list),\n * where keydown would never reach a handler and every shortcut dies. Returns `true` when\n * focus was rescued; `false` when focus is already on a real element or the target cannot\n * take focus (the `fallback` option of {@link RestoreFocusOptions} still applies).\n */\nexport const rescueFocus = (target: FocusTarget, options: RestoreFocusOptions = {}): boolean => {\n const active = getDeepActiveElement(document);\n\n if (active && active !== document.body) return false;\n\n return restoreFocus(target, options);\n};\n\nexport const captureFocus = (options: CaptureFocusOptions = {}): FocusRestorer => {\n let captured = getDeepActiveElement(document) as FocusableElement | null;\n let available = !options.signal?.aborted;\n\n if (!available) captured = null;\n\n const cancel = (): void => {\n available = false;\n captured = null;\n };\n\n if (!options.signal?.aborted) {\n options.signal?.addEventListener('abort', cancel, { once: true });\n }\n\n return () => {\n if (!available) return false;\n\n available = false;\n options.signal?.removeEventListener('abort', cancel);\n\n const target = captured;\n captured = null;\n\n if (target) {\n return restoreFocus(target, {\n fallback: options.fallback,\n preventScroll: options.preventScroll,\n });\n }\n\n if (options.fallback) {\n return restoreFocus(options.fallback, {\n preventScroll: options.preventScroll,\n });\n }\n\n return false;\n };\n};\n"],"mappings":"AAcA,IAAM,cAAiB,GACd,OAAO,GAAW,WAAa,EAAO,EAAI,EAG7C,qBAAwB,GAA2C,CACvE,IAAI,EAAyB,EAAa,cAE1C,KAAO,aAAkB,aAAe,EAAO,YAAY,eACzD,EAAS,EAAO,WAAW,cAG7B,OAAO,CACT,EAEM,YAAe,GAGZ,EAAO,YAGV,WAAc,GACX,aAAkB,aAAe,aAAc,GAAU,EAAS,EAA4B,SAGjG,QAAW,GACX,EAAO,QAAQ,SAAS,EAAU,GAE/B,aAAkB,aAAe,EAAO,MAG3C,aAAgB,GACb,YAAY,CAAM,GAAK,CAAC,WAAW,CAAM,GAAK,CAAC,QAAQ,CAAM,EAGhE,gBAAkB,EAA0B,IAAgD,CAChG,GAAI,CAEF,OADA,EAAO,MAAM,CAAE,eAAc,CAAC,EACvB,qBAAqB,EAAO,aAAa,IAAM,CACxD,MAAQ,CACN,MAAO,EACT,CACF,EAEa,cAAgB,EAAqB,EAA+B,CAAC,IAAe,CAC/F,IAAI,EACJ,GAAI,CACF,EAAO,cAAc,CAAM,CAC7B,MAAQ,CACN,EAAO,IACT,CAEA,GAAI,GAAQ,aAAa,CAAI,GAAK,eAAe,EAAM,EAAQ,aAAa,EAC1E,MAAO,GAGT,GAAI,CAAC,EAAQ,SAAU,MAAO,GAE9B,IAAI,EACJ,GAAI,CACF,EAAW,cAAc,EAAQ,QAAQ,CAC3C,MAAQ,CACN,MAAO,EACT,CAIA,MAFI,CAAC,GAAY,CAAC,aAAa,CAAQ,EAAU,GAE1C,eAAe,EAAU,EAAQ,aAAa,CACvD,EASa,aAAe,EAAqB,EAA+B,CAAC,IAAe,CAC9F,IAAM,EAAS,qBAAqB,QAAQ,EAI5C,OAFI,GAAU,IAAW,SAAS,KAAa,GAExC,aAAa,EAAQ,CAAO,CACrC,EAEa,cAAgB,EAA+B,CAAC,IAAqB,CAChF,IAAI,EAAW,qBAAqB,QAAQ,EACxC,EAAY,CAAC,EAAQ,QAAQ,QAE5B,IAAW,EAAW,MAE3B,IAAM,WAAqB,CACzB,EAAY,GACZ,EAAW,IACb,EAMA,OAJK,EAAQ,QAAQ,SACnB,EAAQ,QAAQ,iBAAiB,QAAS,OAAQ,CAAE,KAAM,EAAK,CAAC,MAGrD,CACX,GAAI,CAAC,EAAW,MAAO,GAEvB,EAAY,GACZ,EAAQ,QAAQ,oBAAoB,QAAS,MAAM,EAEnD,IAAM,EAAS,EAgBf,MAfA,GAAW,KAEP,EACK,aAAa,EAAQ,CAC1B,SAAU,EAAQ,SAClB,cAAe,EAAQ,aACzB,CAAC,EAGC,EAAQ,SACH,aAAa,EAAQ,SAAU,CACpC,cAAe,EAAQ,aACzB,CAAC,EAGI,EACT,CACF"}
@@ -9,5 +9,13 @@ export type CaptureFocusOptions = RestoreFocusOptions & {
9
9
  };
10
10
  export type FocusRestorer = () => boolean;
11
11
  export declare const restoreFocus: (target: FocusTarget, options?: RestoreFocusOptions) => boolean;
12
+ /**
13
+ * Hands focus to `target` when focus has been lost to the document body — the state left
14
+ * behind when the focused element unmounts mid-swap (browsing a dialog, paging a list),
15
+ * where keydown would never reach a handler and every shortcut dies. Returns `true` when
16
+ * focus was rescued; `false` when focus is already on a real element or the target cannot
17
+ * take focus (the `fallback` option of {@link RestoreFocusOptions} still applies).
18
+ */
19
+ export declare const rescueFocus: (target: FocusTarget, options?: RestoreFocusOptions) => boolean;
12
20
  export declare const captureFocus: (options?: CaptureFocusOptions) => FocusRestorer;
13
21
  //# sourceMappingURL=restore-focus.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"restore-focus.d.ts","sourceRoot":"","sources":["../src/restore-focus.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,UAAU,CAAC;AACxD,MAAM,MAAM,WAAW,GAAG,gBAAgB,GAAG,IAAI,GAAG,SAAS,GAAG,CAAC,MAAM,gBAAgB,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAE5G,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,mBAAmB,GAAG;IACtD,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC;AA0C1C,eAAO,MAAM,YAAY,GAAI,QAAQ,WAAW,EAAE,UAAS,mBAAwB,KAAG,OAcrF,CAAC;AAEF,eAAO,MAAM,YAAY,GAAI,UAAS,mBAAwB,KAAG,aAuChE,CAAC"}
1
+ {"version":3,"file":"restore-focus.d.ts","sourceRoot":"","sources":["../src/restore-focus.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,UAAU,CAAC;AACxD,MAAM,MAAM,WAAW,GAAG,gBAAgB,GAAG,IAAI,GAAG,SAAS,GAAG,CAAC,MAAM,gBAAgB,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAE5G,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,CAAC,EAAE,WAAW,CAAC;IACvB,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,mBAAmB,GAAG;IACtD,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC;AA6C1C,eAAO,MAAM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