@vielzeug/focus 26.10.15 → 26.10.17

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.
@@ -1,2 +1,82 @@
1
- import{FocusConfigError as e}from"./errors.js";import{matchKey as t}from"@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(`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};
1
+ import { FocusConfigError as e } from "./errors.js";
2
+ import { matchKey as t } from "@vielzeug/keymap";
3
+ //#region src/grid-navigation.ts
4
+ var n = {
5
+ first: ["Home"],
6
+ last: ["End"],
7
+ next: ["ArrowRight"],
8
+ nextRow: ["ArrowDown"],
9
+ prev: ["ArrowLeft"],
10
+ prevRow: ["ArrowUp"]
11
+ }, r = {
12
+ ...n,
13
+ next: ["ArrowLeft"],
14
+ prev: ["ArrowRight"]
15
+ }, i = [
16
+ "first",
17
+ "last",
18
+ "next",
19
+ "nextRow",
20
+ "prev",
21
+ "prevRow"
22
+ ], resolve = (e, t) => typeof e == "function" ? e() : e ?? t, createGridNavigation = (a) => {
23
+ let o = /* @__PURE__ */ new Map();
24
+ for (let t of i) for (let n of a.keys?.[t] ?? []) {
25
+ let r = o.get(n);
26
+ if (r && r !== t) throw new e(`Key "${n}" is assigned to both ${r} and ${t}`);
27
+ o.set(n, t);
28
+ }
29
+ let s = -1, resolveColumns = () => {
30
+ let t = resolve(a.columns, 1);
31
+ if (!Number.isInteger(t) || t < 1) throw new e(`columns must resolve to a positive integer, got: ${t}`);
32
+ return t;
33
+ }, activeIndex = (e) => {
34
+ let t = a.getActiveIndex?.();
35
+ return t !== void 0 && (s = t >= 0 && t < e.length ? t : -1), s;
36
+ }, commitIndex = (e, t, n, r) => (s = t, Object.freeze({
37
+ action: n,
38
+ event: r,
39
+ index: t,
40
+ item: e[t]
41
+ })), navigateWithItems = (e, t, n) => {
42
+ if (!e.length) return s = -1, null;
43
+ if (t === "first") return commitIndex(e, 0, t, n);
44
+ if (t === "last") return commitIndex(e, e.length - 1, t, n);
45
+ 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;
46
+ if (a.loop) return commitIndex(e, (c % e.length + e.length) % e.length, t, n);
47
+ let l = Math.min(e.length - 1, Math.max(0, c));
48
+ return l === o ? null : commitIndex(e, l, t, n);
49
+ }, resolveKeyAction = (e) => {
50
+ let o = resolve(a.direction, "ltr") === "rtl" ? r : n;
51
+ for (let n of i) if ((a.keys?.[n] ?? o[n]).some((n) => t(e, n))) return n;
52
+ }, handleKeydown = (e) => {
53
+ if (e.defaultPrevented || e.isComposing || resolve(a.disabled, !1)) return null;
54
+ let t = resolveKeyAction(e);
55
+ if (!t) return null;
56
+ let n = navigateWithItems(a.getItems(), t, e);
57
+ return e.preventDefault(), Object.freeze({
58
+ change: n,
59
+ handled: !0
60
+ });
61
+ }, navigate = (e) => navigateWithItems(a.getItems(), e), set = (e) => {
62
+ let t = a.getItems();
63
+ s = !Number.isInteger(e) || e < 0 || !t.length ? -1 : Math.min(e, t.length - 1);
64
+ }, reset = () => {
65
+ s = -1;
66
+ }, getIndex = () => activeIndex(a.getItems()), getActiveItem = () => {
67
+ let e = a.getItems(), t = activeIndex(e);
68
+ return t >= 0 ? e[t] : void 0;
69
+ };
70
+ return {
71
+ getActiveItem,
72
+ getIndex,
73
+ handleKeydown,
74
+ navigate,
75
+ reset,
76
+ set
77
+ };
78
+ };
79
+ //#endregion
80
+ export { createGridNavigation };
81
+
2
82
  //# sourceMappingURL=grid-navigation.js.map
@@ -1 +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,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,GA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back","owners","action","key","options","owner","FocusConfigError","index","columns","derived","items","nextIndex","event","offset","current","base","clamped","keyTable","matchKey","pattern","change"],"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":";;;AAmDA,IAAMA,IAAgE;CACpE,OAAO,CAAC,MAAM;CACd,MAAM,CAAC,KAAK;CACZ,MAAM,CAAC,YAAY;CACnB,SAAS,CAAC,WAAW;CACrB,MAAM,CAAC,WAAW;C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AAWD,EAAM,SAAS,CAAC;CAC9C,GAEM,cAAoB;EACxB,IAAQ;CACV,GAEM,iBAAyB,YAAYN,EAAQ,SAAS,CAAC,GAEvD,sBAAqC;EACzC,IAAMM,IAAQN,EAAQ,SAAS,GACzBU,IAAU,YAAYJ,CAAK;EACjC,OAAOI,KAAW,IAAIJ,EAAMI,KAAW,KAAA;CACzC;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
package/dist/index.js CHANGED
@@ -1 +1,6 @@
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{createQuickLookGrid as i}from"./quick-look-grid.js";import{captureFocus as a,rescueFocus as o,restoreFocus as s}from"./restore-focus.js";export{e as FocusConfigError,t as FocusError,a as captureFocus,n as createGridNavigation,r as createListNavigation,i as createQuickLookGrid,o as rescueFocus,s as restoreFocus};
1
+ import { FocusConfigError as e, FocusError as t } from "./errors.js";
2
+ import { createGridNavigation as n } from "./grid-navigation.js";
3
+ import { createListNavigation as r } from "./list-navigation.js";
4
+ import { createQuickLookGrid as i } from "./quick-look-grid.js";
5
+ import { captureFocus as a, rescueFocus as o, restoreFocus as s } from "./restore-focus.js";
6
+ export { e as FocusConfigError, t as FocusError, a as captureFocus, n as createGridNavigation, r as createListNavigation, i as createQuickLookGrid, o as rescueFocus, s as restoreFocus };
@@ -1 +1 @@
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,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,IAAK,IAAI,EAAQ,EAAO,EAAQ,EAAM,OAAQ,IAC5C,GAAI,EAAU,EAAM,GAAQ,CAAK,EAAG,OAAO,EAG7C,MAAO,EACT,EAEM,cACJ,EACA,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,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,IAAA,EAAY,EAAA,SAAA,CAAS,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
+ {"version":3,"file":"list-navigation.cjs","names":["FocusConfigError","matchKey","require_errors","_vielzeug_keymap","DEFAULT_KEYS","DEFAULT_KEYS_RTL","DEFAULT_TYPEAHEAD_DELAY_MS","index","start","items","predicate","delay","typeaheadDelay","options","owners","action","key","owner","typeaheadBuffer","lastTypeaheadAt","item","itemIndex","nextIndex","direction","current","event","wrapStart","wrapped","includeCurrent","offset","search","now","candidate","character","clamped","value","fallback","keys","defaults","pattern","change"],"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":"A,kEA+CA,IAAMI,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,EAEMC,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,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EACrD,OAAO,OAAO,CAAE,SAAQ,QAAS,EAAK,CAAC,GAF1B,IAGtB,EAEA,MAAO,CACL,cACA,SACA,cACA,SACA,MACA,GACF,CACF,E"}
@@ -1,2 +1,139 @@
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};
1
+ import { FocusConfigError as e } from "./errors.js";
2
+ import { matchKey as t } from "@vielzeug/keymap";
3
+ //#region src/list-navigation.ts
4
+ var n = {
5
+ both: {
6
+ first: ["Home"],
7
+ last: ["End"],
8
+ next: ["ArrowDown", "ArrowRight"],
9
+ prev: ["ArrowUp", "ArrowLeft"]
10
+ },
11
+ horizontal: {
12
+ first: ["Home"],
13
+ last: ["End"],
14
+ next: ["ArrowRight"],
15
+ prev: ["ArrowLeft"]
16
+ },
17
+ vertical: {
18
+ first: ["Home"],
19
+ last: ["End"],
20
+ next: ["ArrowDown"],
21
+ prev: ["ArrowUp"]
22
+ }
23
+ }, r = {
24
+ both: {
25
+ first: ["Home"],
26
+ last: ["End"],
27
+ next: ["ArrowDown", "ArrowLeft"],
28
+ prev: ["ArrowUp", "ArrowRight"]
29
+ },
30
+ horizontal: {
31
+ first: ["Home"],
32
+ last: ["End"],
33
+ next: ["ArrowLeft"],
34
+ prev: ["ArrowRight"]
35
+ },
36
+ vertical: n.vertical
37
+ }, i = 500, findForward = (e, t, n) => {
38
+ for (let r = t; r < e.length; r++) if (n(e[r], r)) return r;
39
+ return -1;
40
+ }, findBackward = (e, t, n) => {
41
+ for (let r = t; r >= 0; r--) if (n(e[r], r)) return r;
42
+ return -1;
43
+ }, resolveTypeaheadDelay = (t) => {
44
+ if (t === void 0) return i;
45
+ if (!Number.isFinite(t) || t <= 0) throw new e("Typeahead delay must be a positive finite number");
46
+ return t;
47
+ }, createListNavigation = (i) => {
48
+ let a = resolveTypeaheadDelay(i.typeahead?.delayMs), o = /* @__PURE__ */ new Map();
49
+ for (let t of [
50
+ "next",
51
+ "prev",
52
+ "first",
53
+ "last"
54
+ ]) for (let n of i.keys?.[t] ?? []) {
55
+ let r = o.get(n);
56
+ if (r && r !== t) throw new e(`Key "${n}" is assigned to both ${r} and ${t}`);
57
+ o.set(n, t);
58
+ }
59
+ 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 = () => {
60
+ c = "", l = 0;
61
+ }, commitIndex = (e, t, n, r) => isUsableIndex(e, t) ? (s = t, Object.freeze({
62
+ action: n,
63
+ event: r,
64
+ index: t,
65
+ item: e[t]
66
+ })) : (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) => {
67
+ let r = normalizeIndex(e);
68
+ if (!e.length) return s = -1, null;
69
+ 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";
70
+ if (o >= 0) return commitIndex(e, o, c, n);
71
+ if (i.loop) {
72
+ let r = t === "forward" ? 0 : e.length - 1, i = findEnabledIndex(e, r, t);
73
+ if (i >= 0) return commitIndex(e, i, c, n);
74
+ }
75
+ return null;
76
+ }, 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) => {
77
+ let r = normalizeIndex(e), a = r < 0 ? 0 : n ? r : r + 1;
78
+ for (let n = 0; n < e.length; n++) {
79
+ let r = (a + n) % e.length, o = e[r];
80
+ if (!isItemDisabled(o, r) && i.typeahead?.getLabel(o, r).toLocaleLowerCase().startsWith(t)) return r;
81
+ }
82
+ return -1;
83
+ }, handleTypeahead = (e, t) => {
84
+ if (!i.typeahead || e.key.length !== 1 || e.ctrlKey || e.altKey || e.metaKey) return null;
85
+ let n = performance.now(), r = e.key.toLocaleLowerCase();
86
+ n - l >= a && (c = ""), l = n;
87
+ let o = c + r;
88
+ c = o.length > 1 && [...o].every((e) => e === r) ? r : o;
89
+ let s = findTypeaheadMatch(t, c, c.length > 1);
90
+ return s < 0 && c.length > 1 && (c = r, s = findTypeaheadMatch(t, c, !1)), s < 0 ? null : commitIndex(t, s, "typeahead", e);
91
+ }, set = (e) => {
92
+ let t = i.getItems();
93
+ if (normalizeIndex(t), resetTypeahead(), !Number.isInteger(e) || e < 0 || !t.length) return s = -1, s;
94
+ let n = Math.min(e, t.length - 1);
95
+ return isUsableIndex(t, n) ? (s = n, s) : (s = -1, s);
96
+ }, navigate = (e) => navigateWithItems(i.getItems(), e), getActiveItem = () => {
97
+ let e = i.getItems(), t = normalizeIndex(e);
98
+ return t >= 0 ? e[t] : void 0;
99
+ }, reset = () => {
100
+ s = -1, resetTypeahead();
101
+ }, getIndex = () => normalizeIndex(i.getItems()), resolve = (e, t) => typeof e == "function" ? e() : e ?? t, resolveKeyAction = (e) => {
102
+ let a = i.keys, o = (resolve(i.direction, "ltr") === "rtl" ? r : n)[resolve(i.orientation, "vertical")];
103
+ for (let n of [
104
+ "next",
105
+ "prev",
106
+ "first",
107
+ "last"
108
+ ]) if ((a?.[n] ?? o[n]).some((n) => t(e, n))) return n;
109
+ }, handleKeydown = (e) => {
110
+ if (e.defaultPrevented || e.isComposing || resolve(i.disabled, !1)) return null;
111
+ let t = i.getItems();
112
+ normalizeIndex(t);
113
+ let n = resolveKeyAction(e);
114
+ if (n) {
115
+ let r = navigateWithItems(t, n, e);
116
+ return e.preventDefault(), Object.freeze({
117
+ change: r,
118
+ handled: !0
119
+ });
120
+ }
121
+ let r = handleTypeahead(e, t);
122
+ return r ? (i.typeahead?.preventDefault && e.preventDefault(), Object.freeze({
123
+ change: r,
124
+ handled: !0
125
+ })) : null;
126
+ };
127
+ return {
128
+ getActiveItem,
129
+ getIndex,
130
+ handleKeydown,
131
+ navigate,
132
+ reset,
133
+ set
134
+ };
135
+ };
136
+ //#endregion
137
+ export { createListNavigation };
138
+
2
139
  //# sourceMappingURL=list-navigation.js.map
@@ -1 +1 @@
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,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K,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
+ {"version":3,"file":"list-navigation.js","names":["DEFAULT_KEYS","DEFAULT_KEYS_RTL","DEFAULT_TYPEAHEAD_DELAY_MS","index","start","items","predicate","delay","FocusConfigError","typeaheadDelay","options","owners","action","key","owner","typeaheadBuffer","lastTypeaheadAt","item","itemIndex","nextIndex","direction","current","event","wrapStart","wrapped","includeCurrent","offset","search","now","candidate","character","clamped","value","fallback","keys","defaults","matchKey","pattern","change"],"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 };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MAEfyB,KADW,QAAQzB,EAAQ,WAAW,KAAK,MAAM,QAAQT,IAAmBD,EAAA,CACxD,QAAQU,EAAQ,aAAa,UAAU;EAEjE,KAAK,IAAME,KAAU;GAAC;GAAQ;GAAQ;GAAS;EAAM,GACnD,KAAKsB,IAAOtB,MAAWuB,EAASvB,GAAA,CAAS,MAAM,MAAYwB,EAASd,GAAOe,CAAO,CAAC,GAAG,OAAOzB;CAIjG,GAEM,iBAAiB,MAAkD;EACvE,IAAIU,EAAM,oBAAoBA,EAAM,eAAe,QAAQZ,EAAQ,UAAU,EAAK,GAAG,OAAO;EAE5F,IAAML,IAAQK,EAAQ,SAAS;EAC/B,eAAeL,CAAK;EAEpB,IAAMO,IAAS,iBAAiBU,CAAK;EAErC,IAAIV,GAAQ;GACV,IAAM0B,IAAS,kBAAkBjC,GAAOO,GAAQU,CAAK;GAErD,OADAA,EAAM,eAAe,GACd,OAAO,OAAO;IAAE;IAAQ,SAAS;GAAK,CAAC;EAChD;EAEA,IAAMgB,IAAS,gBAAgBhB,GAAOjB,CAAK;EAG3C,OAFKiC,KACD5B,EAAQ,WAAW,kBAAgBY,EAAM,eAAe,GACrD,OAAO,OAAO;GAAE;GAAQ,SAAS;EAAK,CAAC,KAF1B;CAGtB;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"quick-look-grid.cjs","names":[],"sources":["../src/quick-look-grid.ts"],"sourcesContent":["import type { GridColumns } from './grid-navigation.js';\nimport { createGridNavigation } from './grid-navigation.js';\nimport type { MaybeGetter } from './list-navigation.js';\n\nexport type QuickLookGridOptions = {\n /**\n * Columns per row, resolved on every navigation. Defaults to the rendered row length at the\n * active item, which follows the grid's own responsive wrapping without a media query.\n */\n columns?: GridColumns;\n /** Suppresses every key: for grids the consumer has locked. */\n disabled?: MaybeGetter<boolean>;\n /** Reads the grid's items in display order, re-read on every key. */\n getItems: () => readonly HTMLElement[];\n /**\n * Reads the active index among the items when the event target is outside them, for grids\n * whose focus sits on a wrapper around the item. Defaults to the item that is (or contains)\n * `document.activeElement`.\n */\n getActiveIndex?: () => number;\n /** Key that opens the Quick Look. Default `' '` (Space), the platform preview key. */\n inspectKey?: string;\n /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */\n loop?: boolean;\n /**\n * Opens the Quick Look for one item. The keyboard path has already focused the item; the\n * consumer decides what \"detail\" means (a dialog, a zoom, a preview pane).\n */\n onInspect: (item: HTMLElement, index: number) => void;\n};\n\nexport type QuickLookGrid = {\n /**\n * Route the grid's `keydown` here. Arrow keys and Home/End move focus through the items;\n * `inspectKey` opens the Quick Look for the item under the event (or the active item),\n * cancelling the key so the focused control never activates. Modifier chords pass through.\n */\n handleKeydown(event: KeyboardEvent): void;\n};\n\nconst resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n/**\n * Keyboard browsing over a tile grid with a Quick Look key: the pair every card picker needs,\n * where arrows walk the tiles and Space previews the focused card instead of activating it.\n *\n * Built on `createGridNavigation`: horizontal arrows step one item, vertical arrows step one\n * row, Home/End jump to the ends, and focus follows the reported change. `inspectKey` (Space by\n * default) resolves the item under the event target, calls `preventDefault()` and\n * `stopPropagation()` so the focused button never sees the press, and reports it through\n * `onInspect`. Long-press is the touch counterpart of the same callback; pair this with a\n * pointer recognizer (for example `@vielzeug/gesture`'s long press) at the call site.\n */\nexport const createQuickLookGrid = (options: QuickLookGridOptions): QuickLookGrid => {\n const activeIndex = (): number => options.getItems().indexOf(document.activeElement as HTMLElement);\n\n /** The rendered row length at the active item: items sharing its top edge. */\n const measuredColumns = (): number => {\n const items = options.getItems();\n const active = items.indexOf(document.activeElement as HTMLElement);\n if (active < 0) return 1;\n const top = items[active]?.getBoundingClientRect().top ?? 0;\n return Math.max(1, items.filter((item) => Math.abs(item.getBoundingClientRect().top - top) < 1).length);\n };\n\n const navigation = createGridNavigation<HTMLElement>({\n columns: options.columns ?? measuredColumns,\n getActiveIndex: options.getActiveIndex ?? activeIndex,\n getItems: options.getItems,\n loop: options.loop,\n });\n\n /** The item the key belongs to: the one containing the event target, else the active item. */\n const resolveItem = (event: KeyboardEvent): { index: number; item: HTMLElement | undefined } => {\n const items = options.getItems();\n const target = event.target instanceof HTMLElement ? event.target : null;\n const byTarget = target === null ? -1 : items.findIndex((item) => item === target || item.contains(target));\n if (byTarget >= 0) return { index: byTarget, item: items[byTarget] };\n const index = (options.getActiveIndex ?? activeIndex)();\n return { index, item: index >= 0 ? items[index] : undefined };\n };\n\n const handleKeydown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return;\n if (event.ctrlKey || event.metaKey || event.altKey) return;\n\n if (event.key === (options.inspectKey ?? ' ')) {\n const { index, item } = resolveItem(event);\n if (!item) return;\n event.preventDefault();\n event.stopPropagation();\n options.onInspect(item, index);\n return;\n }\n\n const result = navigation.handleKeydown(event);\n if (result?.change) result.change.item.focus();\n };\n\n return { handleKeydown };\n};\n"],"mappings":"yCAwCA,IAAM,SAAc,EAAmC,IACrD,OAAO,GAAU,WAAc,EAAkB,EAAK,GAAS,EAapD,oBAAuB,GAAiD,CACnF,IAAM,gBAA4B,EAAQ,SAAS,CAAC,CAAC,QAAQ,SAAS,aAA4B,EAG5F,oBAAgC,CACpC,IAAM,EAAQ,EAAQ,SAAS,EACzB,EAAS,EAAM,QAAQ,SAAS,aAA4B,EAClE,GAAI,EAAS,EAAG,MAAO,GACvB,IAAM,EAAM,EAAM,EAAO,EAAE,sBAAsB,CAAC,CAAC,KAAO,EAC1D,OAAO,KAAK,IAAI,EAAG,EAAM,OAAQ,GAAS,KAAK,IAAI,EAAK,sBAAsB,CAAC,CAAC,IAAM,CAAG,EAAI,CAAC,CAAC,CAAC,MAAM,CACxG,EAEM,EAAa,EAAA,qBAAkC,CACnD,QAAS,EAAQ,SAAW,gBAC5B,eAAgB,EAAQ,gBAAkB,YAC1C,SAAU,EAAQ,SAClB,KAAM,EAAQ,IAChB,CAAC,EAGK,YAAe,GAA2E,CAC9F,IAAM,EAAQ,EAAQ,SAAS,EACzB,EAAS,EAAM,kBAAkB,YAAc,EAAM,OAAS,KAC9D,EAAW,IAAW,KAAO,GAAK,EAAM,UAAW,GAAS,IAAS,GAAU,EAAK,SAAS,CAAM,CAAC,EAC1G,GAAI,GAAY,EAAG,MAAO,CAAE,MAAO,EAAU,KAAM,EAAM,EAAU,EACnE,IAAM,GAAS,EAAQ,gBAAkB,YAAA,CAAa,EACtD,MAAO,CAAE,QAAO,KAAM,GAAS,EAAI,EAAM,GAAS,IAAA,EAAU,CAC9D,EAEM,cAAiB,GAA+B,CAEpD,GADI,EAAM,kBAAoB,EAAM,aAAe,QAAQ,EAAQ,SAAU,EAAK,GAC9E,EAAM,SAAW,EAAM,SAAW,EAAM,OAAQ,OAEpD,GAAI,EAAM,OAAS,EAAQ,YAAc,KAAM,CAC7C,GAAM,CAAE,QAAO,QAAS,YAAY,CAAK,EACzC,GAAI,CAAC,EAAM,OACX,EAAM,eAAe,EACrB,EAAM,gBAAgB,EACtB,EAAQ,UAAU,EAAM,CAAK,EAC7B,MACF,CAEA,IAAM,EAAS,EAAW,cAAc,CAAK,EACzC,GAAQ,QAAQ,EAAO,OAAO,KAAK,MAAM,CAC/C,EAEA,MAAO,CAAE,aAAc,CACzB"}
1
+ {"version":3,"file":"quick-look-grid.cjs","names":["createGridNavigation","require_grid_navigation","value","fallback","options","items","active","top","item","navigation","target","event","byTarget","index","result"],"sources":["../src/quick-look-grid.ts"],"sourcesContent":["import type { GridColumns } from './grid-navigation.js';\nimport { createGridNavigation } from './grid-navigation.js';\nimport type { MaybeGetter } from './list-navigation.js';\n\nexport type QuickLookGridOptions = {\n /**\n * Columns per row, resolved on every navigation. Defaults to the rendered row length at the\n * active item, which follows the grid's own responsive wrapping without a media query.\n */\n columns?: GridColumns;\n /** Suppresses every key: for grids the consumer has locked. */\n disabled?: MaybeGetter<boolean>;\n /** Reads the grid's items in display order, re-read on every key. */\n getItems: () => readonly HTMLElement[];\n /**\n * Reads the active index among the items when the event target is outside them, for grids\n * whose focus sits on a wrapper around the item. Defaults to the item that is (or contains)\n * `document.activeElement`.\n */\n getActiveIndex?: () => number;\n /** Key that opens the Quick Look. Default `' '` (Space), the platform preview key. */\n inspectKey?: string;\n /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */\n loop?: boolean;\n /**\n * Opens the Quick Look for one item. The keyboard path has already focused the item; the\n * consumer decides what \"detail\" means (a dialog, a zoom, a preview pane).\n */\n onInspect: (item: HTMLElement, index: number) => void;\n};\n\nexport type QuickLookGrid = {\n /**\n * Route the grid's `keydown` here. Arrow keys and Home/End move focus through the items;\n * `inspectKey` opens the Quick Look for the item under the event (or the active item),\n * cancelling the key so the focused control never activates. Modifier chords pass through.\n */\n handleKeydown(event: KeyboardEvent): void;\n};\n\nconst resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n/**\n * Keyboard browsing over a tile grid with a Quick Look key: the pair every card picker needs,\n * where arrows walk the tiles and Space previews the focused card instead of activating it.\n *\n * Built on `createGridNavigation`: horizontal arrows step one item, vertical arrows step one\n * row, Home/End jump to the ends, and focus follows the reported change. `inspectKey` (Space by\n * default) resolves the item under the event target, calls `preventDefault()` and\n * `stopPropagation()` so the focused button never sees the press, and reports it through\n * `onInspect`. Long-press is the touch counterpart of the same callback; pair this with a\n * pointer recognizer (for example `@vielzeug/gesture`'s long press) at the call site.\n */\nexport const createQuickLookGrid = (options: QuickLookGridOptions): QuickLookGrid => {\n const activeIndex = (): number => options.getItems().indexOf(document.activeElement as HTMLElement);\n\n /** The rendered row length at the active item: items sharing its top edge. */\n const measuredColumns = (): number => {\n const items = options.getItems();\n const active = items.indexOf(document.activeElement as HTMLElement);\n if (active < 0) return 1;\n const top = items[active]?.getBoundingClientRect().top ?? 0;\n return Math.max(1, items.filter((item) => Math.abs(item.getBoundingClientRect().top - top) < 1).length);\n };\n\n const navigation = createGridNavigation<HTMLElement>({\n columns: options.columns ?? measuredColumns,\n getActiveIndex: options.getActiveIndex ?? activeIndex,\n getItems: options.getItems,\n loop: options.loop,\n });\n\n /** The item the key belongs to: the one containing the event target, else the active item. */\n const resolveItem = (event: KeyboardEvent): { index: number; item: HTMLElement | undefined } => {\n const items = options.getItems();\n const target = event.target instanceof HTMLElement ? event.target : null;\n const byTarget = target === null ? -1 : items.findIndex((item) => item === target || item.contains(target));\n if (byTarget >= 0) return { index: byTarget, item: items[byTarget] };\n const index = (options.getActiveIndex ?? activeIndex)();\n return { index, item: index >= 0 ? items[index] : undefined };\n };\n\n const handleKeydown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return;\n if (event.ctrlKey || event.metaKey || event.altKey) return;\n\n if (event.key === (options.inspectKey ?? ' ')) {\n const { index, item } = resolveItem(event);\n if (!item) return;\n event.preventDefault();\n event.stopPropagation();\n options.onInspect(item, index);\n return;\n }\n\n const result = navigation.handleKeydown(event);\n if (result?.change) result.change.item.focus();\n };\n\n return { handleKeydown };\n};\n"],"mappings":"A,yCAwCA,IAAM,SAAc,EAAmC,IACrD,OAAOE,GAAU,WAAcA,EAAkB,EAAKA,GAASC,EAapD,oBAAuB,GAAiD,CACnF,IAAM,gBAA4BC,EAAQ,SAAS,CAAC,CAAC,QAAQ,SAAS,aAA4B,EAG5F,oBAAgC,CACpC,IAAMC,EAAQD,EAAQ,SAAS,EACzBE,EAASD,EAAM,QAAQ,SAAS,aAA4B,EAClE,GAAIC,EAAS,EAAG,MAAO,GACvB,IAAMC,EAAMF,EAAMC,EAAO,EAAE,sBAAsB,CAAC,CAAC,KAAO,EAC1D,OAAO,KAAK,IAAI,EAAGD,EAAM,OAAQ,GAAS,KAAK,IAAIG,EAAK,sBAAsB,CAAC,CAAC,IAAMD,CAAG,EAAI,CAAC,CAAC,CAAC,MAAM,CACxG,EAEME,EAAaT,EAAAA,qBAAkC,CACnD,QAASI,EAAQ,SAAW,gBAC5B,eAAgBA,EAAQ,gBAAkB,YAC1C,SAAUA,EAAQ,SAClB,KAAMA,EAAQ,IAChB,CAAC,EAGK,YAAe,GAA2E,CAC9F,IAAMC,EAAQD,EAAQ,SAAS,EACzBM,EAASC,EAAM,kBAAkB,YAAcA,EAAM,OAAS,KAC9DC,EAAWF,IAAW,KAAO,GAAKL,EAAM,UAAW,GAASG,IAASE,GAAUF,EAAK,SAASE,CAAM,CAAC,EAC1G,GAAIE,GAAY,EAAG,MAAO,CAAE,MAAOA,EAAU,KAAMP,EAAMO,EAAU,EACnE,IAAMC,GAAST,EAAQ,gBAAkB,YAAA,CAAa,EACtD,MAAO,CAAE,QAAO,KAAMS,GAAS,EAAIR,EAAMQ,GAAS,IAAA,EAAU,CAC9D,EAEM,cAAiB,GAA+B,CAEpD,GADIF,EAAM,kBAAoBA,EAAM,aAAe,QAAQP,EAAQ,SAAU,EAAK,GAC9EO,EAAM,SAAWA,EAAM,SAAWA,EAAM,OAAQ,OAEpD,GAAIA,EAAM,OAASP,EAAQ,YAAc,KAAM,CAC7C,GAAM,CAAE,QAAO,QAAS,YAAYO,CAAK,EACzC,GAAI,CAACH,EAAM,OACXG,EAAM,eAAe,EACrBA,EAAM,gBAAgB,EACtBP,EAAQ,UAAUI,EAAMK,CAAK,EAC7B,MACF,CAEA,IAAMC,EAASL,EAAW,cAAcE,CAAK,EACzCG,GAAQ,QAAQA,EAAO,OAAO,KAAK,MAAM,CAC/C,EAEA,MAAO,CAAE,aAAc,CACzB,E"}
@@ -1,2 +1,41 @@
1
- import{createGridNavigation as e}from"./grid-navigation.js";var resolve=(e,t)=>typeof e==`function`?e():e??t,createQuickLookGrid=t=>{let activeIndex=()=>t.getItems().indexOf(document.activeElement),measuredColumns=()=>{let e=t.getItems(),n=e.indexOf(document.activeElement);if(n<0)return 1;let r=e[n]?.getBoundingClientRect().top??0;return Math.max(1,e.filter(e=>Math.abs(e.getBoundingClientRect().top-r)<1).length)},n=e({columns:t.columns??measuredColumns,getActiveIndex:t.getActiveIndex??activeIndex,getItems:t.getItems,loop:t.loop}),resolveItem=e=>{let n=t.getItems(),r=e.target instanceof HTMLElement?e.target:null,i=r===null?-1:n.findIndex(e=>e===r||e.contains(r));if(i>=0)return{index:i,item:n[i]};let a=(t.getActiveIndex??activeIndex)();return{index:a,item:a>=0?n[a]:void 0}},handleKeydown=e=>{if(e.defaultPrevented||e.isComposing||resolve(t.disabled,!1)||e.ctrlKey||e.metaKey||e.altKey)return;if(e.key===(t.inspectKey??` `)){let{index:n,item:r}=resolveItem(e);if(!r)return;e.preventDefault(),e.stopPropagation(),t.onInspect(r,n);return}let r=n.handleKeydown(e);r?.change&&r.change.item.focus()};return{handleKeydown}};export{createQuickLookGrid};
1
+ import { createGridNavigation as e } from "./grid-navigation.js";
2
+ //#region src/quick-look-grid.ts
3
+ var resolve = (e, t) => typeof e == "function" ? e() : e ?? t, createQuickLookGrid = (t) => {
4
+ let activeIndex = () => t.getItems().indexOf(document.activeElement), measuredColumns = () => {
5
+ let e = t.getItems(), n = e.indexOf(document.activeElement);
6
+ if (n < 0) return 1;
7
+ let r = e[n]?.getBoundingClientRect().top ?? 0;
8
+ return Math.max(1, e.filter((e) => Math.abs(e.getBoundingClientRect().top - r) < 1).length);
9
+ }, n = e({
10
+ columns: t.columns ?? measuredColumns,
11
+ getActiveIndex: t.getActiveIndex ?? activeIndex,
12
+ getItems: t.getItems,
13
+ loop: t.loop
14
+ }), resolveItem = (e) => {
15
+ let n = t.getItems(), r = e.target instanceof HTMLElement ? e.target : null, i = r === null ? -1 : n.findIndex((e) => e === r || e.contains(r));
16
+ if (i >= 0) return {
17
+ index: i,
18
+ item: n[i]
19
+ };
20
+ let a = (t.getActiveIndex ?? activeIndex)();
21
+ return {
22
+ index: a,
23
+ item: a >= 0 ? n[a] : void 0
24
+ };
25
+ }, handleKeydown = (e) => {
26
+ if (e.defaultPrevented || e.isComposing || resolve(t.disabled, !1) || e.ctrlKey || e.metaKey || e.altKey) return;
27
+ if (e.key === (t.inspectKey ?? " ")) {
28
+ let { index: n, item: r } = resolveItem(e);
29
+ if (!r) return;
30
+ e.preventDefault(), e.stopPropagation(), t.onInspect(r, n);
31
+ return;
32
+ }
33
+ let r = n.handleKeydown(e);
34
+ r?.change && r.change.item.focus();
35
+ };
36
+ return { handleKeydown };
37
+ };
38
+ //#endregion
39
+ export { createQuickLookGrid };
40
+
2
41
  //# sourceMappingURL=quick-look-grid.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"quick-look-grid.js","names":[],"sources":["../src/quick-look-grid.ts"],"sourcesContent":["import type { GridColumns } from './grid-navigation.js';\nimport { createGridNavigation } from './grid-navigation.js';\nimport type { MaybeGetter } from './list-navigation.js';\n\nexport type QuickLookGridOptions = {\n /**\n * Columns per row, resolved on every navigation. Defaults to the rendered row length at the\n * active item, which follows the grid's own responsive wrapping without a media query.\n */\n columns?: GridColumns;\n /** Suppresses every key: for grids the consumer has locked. */\n disabled?: MaybeGetter<boolean>;\n /** Reads the grid's items in display order, re-read on every key. */\n getItems: () => readonly HTMLElement[];\n /**\n * Reads the active index among the items when the event target is outside them, for grids\n * whose focus sits on a wrapper around the item. Defaults to the item that is (or contains)\n * `document.activeElement`.\n */\n getActiveIndex?: () => number;\n /** Key that opens the Quick Look. Default `' '` (Space), the platform preview key. */\n inspectKey?: string;\n /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */\n loop?: boolean;\n /**\n * Opens the Quick Look for one item. The keyboard path has already focused the item; the\n * consumer decides what \"detail\" means (a dialog, a zoom, a preview pane).\n */\n onInspect: (item: HTMLElement, index: number) => void;\n};\n\nexport type QuickLookGrid = {\n /**\n * Route the grid's `keydown` here. Arrow keys and Home/End move focus through the items;\n * `inspectKey` opens the Quick Look for the item under the event (or the active item),\n * cancelling the key so the focused control never activates. Modifier chords pass through.\n */\n handleKeydown(event: KeyboardEvent): void;\n};\n\nconst resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n/**\n * Keyboard browsing over a tile grid with a Quick Look key: the pair every card picker needs,\n * where arrows walk the tiles and Space previews the focused card instead of activating it.\n *\n * Built on `createGridNavigation`: horizontal arrows step one item, vertical arrows step one\n * row, Home/End jump to the ends, and focus follows the reported change. `inspectKey` (Space by\n * default) resolves the item under the event target, calls `preventDefault()` and\n * `stopPropagation()` so the focused button never sees the press, and reports it through\n * `onInspect`. Long-press is the touch counterpart of the same callback; pair this with a\n * pointer recognizer (for example `@vielzeug/gesture`'s long press) at the call site.\n */\nexport const createQuickLookGrid = (options: QuickLookGridOptions): QuickLookGrid => {\n const activeIndex = (): number => options.getItems().indexOf(document.activeElement as HTMLElement);\n\n /** The rendered row length at the active item: items sharing its top edge. */\n const measuredColumns = (): number => {\n const items = options.getItems();\n const active = items.indexOf(document.activeElement as HTMLElement);\n if (active < 0) return 1;\n const top = items[active]?.getBoundingClientRect().top ?? 0;\n return Math.max(1, items.filter((item) => Math.abs(item.getBoundingClientRect().top - top) < 1).length);\n };\n\n const navigation = createGridNavigation<HTMLElement>({\n columns: options.columns ?? measuredColumns,\n getActiveIndex: options.getActiveIndex ?? activeIndex,\n getItems: options.getItems,\n loop: options.loop,\n });\n\n /** The item the key belongs to: the one containing the event target, else the active item. */\n const resolveItem = (event: KeyboardEvent): { index: number; item: HTMLElement | undefined } => {\n const items = options.getItems();\n const target = event.target instanceof HTMLElement ? event.target : null;\n const byTarget = target === null ? -1 : items.findIndex((item) => item === target || item.contains(target));\n if (byTarget >= 0) return { index: byTarget, item: items[byTarget] };\n const index = (options.getActiveIndex ?? activeIndex)();\n return { index, item: index >= 0 ? items[index] : undefined };\n };\n\n const handleKeydown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return;\n if (event.ctrlKey || event.metaKey || event.altKey) return;\n\n if (event.key === (options.inspectKey ?? ' ')) {\n const { index, item } = resolveItem(event);\n if (!item) return;\n event.preventDefault();\n event.stopPropagation();\n options.onInspect(item, index);\n return;\n }\n\n const result = navigation.handleKeydown(event);\n if (result?.change) result.change.item.focus();\n };\n\n return { handleKeydown };\n};\n"],"mappings":"4DAwCA,IAAM,SAAc,EAAmC,IACrD,OAAO,GAAU,WAAc,EAAkB,EAAK,GAAS,EAapD,oBAAuB,GAAiD,CACnF,IAAM,gBAA4B,EAAQ,SAAS,CAAC,CAAC,QAAQ,SAAS,aAA4B,EAG5F,oBAAgC,CACpC,IAAM,EAAQ,EAAQ,SAAS,EACzB,EAAS,EAAM,QAAQ,SAAS,aAA4B,EAClE,GAAI,EAAS,EAAG,MAAO,GACvB,IAAM,EAAM,EAAM,EAAO,EAAE,sBAAsB,CAAC,CAAC,KAAO,EAC1D,OAAO,KAAK,IAAI,EAAG,EAAM,OAAQ,GAAS,KAAK,IAAI,EAAK,sBAAsB,CAAC,CAAC,IAAM,CAAG,EAAI,CAAC,CAAC,CAAC,MAAM,CACxG,EAEM,EAAa,EAAkC,CACnD,QAAS,EAAQ,SAAW,gBAC5B,eAAgB,EAAQ,gBAAkB,YAC1C,SAAU,EAAQ,SAClB,KAAM,EAAQ,IAChB,CAAC,EAGK,YAAe,GAA2E,CAC9F,IAAM,EAAQ,EAAQ,SAAS,EACzB,EAAS,EAAM,kBAAkB,YAAc,EAAM,OAAS,KAC9D,EAAW,IAAW,KAAO,GAAK,EAAM,UAAW,GAAS,IAAS,GAAU,EAAK,SAAS,CAAM,CAAC,EAC1G,GAAI,GAAY,EAAG,MAAO,CAAE,MAAO,EAAU,KAAM,EAAM,EAAU,EACnE,IAAM,GAAS,EAAQ,gBAAkB,YAAA,CAAa,EACtD,MAAO,CAAE,QAAO,KAAM,GAAS,EAAI,EAAM,GAAS,IAAA,EAAU,CAC9D,EAEM,cAAiB,GAA+B,CAEpD,GADI,EAAM,kBAAoB,EAAM,aAAe,QAAQ,EAAQ,SAAU,EAAK,GAC9E,EAAM,SAAW,EAAM,SAAW,EAAM,OAAQ,OAEpD,GAAI,EAAM,OAAS,EAAQ,YAAc,KAAM,CAC7C,GAAM,CAAE,QAAO,QAAS,YAAY,CAAK,EACzC,GAAI,CAAC,EAAM,OACX,EAAM,eAAe,EACrB,EAAM,gBAAgB,EACtB,EAAQ,UAAU,EAAM,CAAK,EAC7B,MACF,CAEA,IAAM,EAAS,EAAW,cAAc,CAAK,EACzC,GAAQ,QAAQ,EAAO,OAAO,KAAK,MAAM,CAC/C,EAEA,MAAO,CAAE,aAAc,CACzB"}
1
+ {"version":3,"file":"quick-look-grid.js","names":["value","fallback","options","items","active","top","item","navigation","createGridNavigation","target","event","byTarget","index","result"],"sources":["../src/quick-look-grid.ts"],"sourcesContent":["import type { GridColumns } from './grid-navigation.js';\nimport { createGridNavigation } from './grid-navigation.js';\nimport type { MaybeGetter } from './list-navigation.js';\n\nexport type QuickLookGridOptions = {\n /**\n * Columns per row, resolved on every navigation. Defaults to the rendered row length at the\n * active item, which follows the grid's own responsive wrapping without a media query.\n */\n columns?: GridColumns;\n /** Suppresses every key: for grids the consumer has locked. */\n disabled?: MaybeGetter<boolean>;\n /** Reads the grid's items in display order, re-read on every key. */\n getItems: () => readonly HTMLElement[];\n /**\n * Reads the active index among the items when the event target is outside them, for grids\n * whose focus sits on a wrapper around the item. Defaults to the item that is (or contains)\n * `document.activeElement`.\n */\n getActiveIndex?: () => number;\n /** Key that opens the Quick Look. Default `' '` (Space), the platform preview key. */\n inspectKey?: string;\n /** Wrap moves around the grid's edges by flat index. Default clamps at the edges. */\n loop?: boolean;\n /**\n * Opens the Quick Look for one item. The keyboard path has already focused the item; the\n * consumer decides what \"detail\" means (a dialog, a zoom, a preview pane).\n */\n onInspect: (item: HTMLElement, index: number) => void;\n};\n\nexport type QuickLookGrid = {\n /**\n * Route the grid's `keydown` here. Arrow keys and Home/End move focus through the items;\n * `inspectKey` opens the Quick Look for the item under the event (or the active item),\n * cancelling the key so the focused control never activates. Modifier chords pass through.\n */\n handleKeydown(event: KeyboardEvent): void;\n};\n\nconst resolve = <V>(value: MaybeGetter<V> | undefined, fallback: V): V =>\n typeof value === 'function' ? (value as () => V)() : (value ?? fallback);\n\n/**\n * Keyboard browsing over a tile grid with a Quick Look key: the pair every card picker needs,\n * where arrows walk the tiles and Space previews the focused card instead of activating it.\n *\n * Built on `createGridNavigation`: horizontal arrows step one item, vertical arrows step one\n * row, Home/End jump to the ends, and focus follows the reported change. `inspectKey` (Space by\n * default) resolves the item under the event target, calls `preventDefault()` and\n * `stopPropagation()` so the focused button never sees the press, and reports it through\n * `onInspect`. Long-press is the touch counterpart of the same callback; pair this with a\n * pointer recognizer (for example `@vielzeug/gesture`'s long press) at the call site.\n */\nexport const createQuickLookGrid = (options: QuickLookGridOptions): QuickLookGrid => {\n const activeIndex = (): number => options.getItems().indexOf(document.activeElement as HTMLElement);\n\n /** The rendered row length at the active item: items sharing its top edge. */\n const measuredColumns = (): number => {\n const items = options.getItems();\n const active = items.indexOf(document.activeElement as HTMLElement);\n if (active < 0) return 1;\n const top = items[active]?.getBoundingClientRect().top ?? 0;\n return Math.max(1, items.filter((item) => Math.abs(item.getBoundingClientRect().top - top) < 1).length);\n };\n\n const navigation = createGridNavigation<HTMLElement>({\n columns: options.columns ?? measuredColumns,\n getActiveIndex: options.getActiveIndex ?? activeIndex,\n getItems: options.getItems,\n loop: options.loop,\n });\n\n /** The item the key belongs to: the one containing the event target, else the active item. */\n const resolveItem = (event: KeyboardEvent): { index: number; item: HTMLElement | undefined } => {\n const items = options.getItems();\n const target = event.target instanceof HTMLElement ? event.target : null;\n const byTarget = target === null ? -1 : items.findIndex((item) => item === target || item.contains(target));\n if (byTarget >= 0) return { index: byTarget, item: items[byTarget] };\n const index = (options.getActiveIndex ?? activeIndex)();\n return { index, item: index >= 0 ? items[index] : undefined };\n };\n\n const handleKeydown = (event: KeyboardEvent): void => {\n if (event.defaultPrevented || event.isComposing || resolve(options.disabled, false)) return;\n if (event.ctrlKey || event.metaKey || event.altKey) return;\n\n if (event.key === (options.inspectKey ?? ' ')) {\n const { index, item } = resolveItem(event);\n if (!item) return;\n event.preventDefault();\n event.stopPropagation();\n options.onInspect(item, index);\n return;\n }\n\n const result = navigation.handleKeydown(event);\n if (result?.change) result.change.item.focus();\n };\n\n return { handleKeydown };\n};\n"],"mappings":";;AAwCA,IAAM,WAAc,GAAmC,MACrD,OAAOA,KAAU,aAAcA,EAAkB,IAAKA,KAASC,GAapD,uBAAuB,MAAiD;CACnF,IAAM,oBAA4BC,EAAQ,SAAS,CAAC,CAAC,QAAQ,SAAS,aAA4B,GAG5F,wBAAgC;EACpC,IAAMC,IAAQD,EAAQ,SAAS,GACzBE,IAASD,EAAM,QAAQ,SAAS,aAA4B;EAClE,IAAIC,IAAS,GAAG,OAAO;EACvB,IAAMC,IAAMF,EAAMC,EAAO,EAAE,sBAAsB,CAAC,CAAC,OAAO;EAC1D,OAAO,KAAK,IAAI,GAAGD,EAAM,QAAQ,MAAS,KAAK,IAAIG,EAAK,sBAAsB,CAAC,CAAC,MAAMD,CAAG,IAAI,CAAC,CAAC,CAAC,MAAM;CACxG,GAEME,IAAaC,EAAkC;EACnD,SAASN,EAAQ,WAAW;EAC5B,gBAAgBA,EAAQ,kBAAkB;EAC1C,UAAUA,EAAQ;EAClB,MAAMA,EAAQ;CAChB,CAAC,GAGK,eAAe,MAA2E;EAC9F,IAAMC,IAAQD,EAAQ,SAAS,GACzBO,IAASC,EAAM,kBAAkB,cAAcA,EAAM,SAAS,MAC9DC,IAAWF,MAAW,OAAO,KAAKN,EAAM,WAAW,MAASG,MAASG,KAAUH,EAAK,SAASG,CAAM,CAAC;EAC1G,IAAIE,KAAY,GAAG,OAAO;GAAE,OAAOA;GAAU,MAAMR,EAAMQ;EAAU;EACnE,IAAMC,KAASV,EAAQ,kBAAkB,YAAA,CAAa;EACtD,OAAO;GAAE;GAAO,MAAMU,KAAS,IAAIT,EAAMS,KAAS,KAAA;EAAU;CAC9D,GAEM,iBAAiB,MAA+B;EAEpD,IADIF,EA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