@puzzle-ui/hooks 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sjoerd van Den Berg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs ADDED
@@ -0,0 +1,5 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_use_keyboard_keys = require("./use-keyboard-keys.cjs");
3
+ const require_use_roving_focus = require("./use-roving-focus.cjs");
4
+ exports.useKeyboardKeys = require_use_keyboard_keys.useKeyboardKeys;
5
+ exports.useRovingFocus = require_use_roving_focus.useRovingFocus;
@@ -0,0 +1,3 @@
1
+ import { UseKeyboardKeysEvent, UseKeyboardKeysOptions, useKeyboardKeys } from "./use-keyboard-keys.cjs";
2
+ import { RovingFocusItem, RovingFocusOrientation, UseRovingFocusOptions, UseRovingFocusReturn, useRovingFocus } from "./use-roving-focus.cjs";
3
+ export { type RovingFocusItem, type RovingFocusOrientation, type UseKeyboardKeysEvent, type UseKeyboardKeysOptions, type UseRovingFocusOptions, type UseRovingFocusReturn, useKeyboardKeys, useRovingFocus };
@@ -0,0 +1,3 @@
1
+ import { UseKeyboardKeysEvent, UseKeyboardKeysOptions, useKeyboardKeys } from "./use-keyboard-keys.js";
2
+ import { RovingFocusItem, RovingFocusOrientation, UseRovingFocusOptions, UseRovingFocusReturn, useRovingFocus } from "./use-roving-focus.js";
3
+ export { type RovingFocusItem, type RovingFocusOrientation, type UseKeyboardKeysEvent, type UseKeyboardKeysOptions, type UseRovingFocusOptions, type UseRovingFocusReturn, useKeyboardKeys, useRovingFocus };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import { useKeyboardKeys } from "./use-keyboard-keys.js";
2
+ import { useRovingFocus } from "./use-roving-focus.js";
3
+ export { useKeyboardKeys, useRovingFocus };
@@ -0,0 +1,89 @@
1
+ let react = require("react");
2
+ // src/use-keyboard-keys.ts
3
+ function normalizeKey(key) {
4
+ const normalized = key.toLowerCase();
5
+ if (normalized === "space" || normalized === "spacebar") return " ";
6
+ return normalized;
7
+ }
8
+ function useKeyboardKeys({ keys, onKeyDown, onKeyUp, preventDefault = false, stopPropagation = false, enabled = true }) {
9
+ const pressedKeys = (0, react.useRef)(/* @__PURE__ */ new Set());
10
+ const callbacksRef = (0, react.useRef)({
11
+ onKeyDown,
12
+ onKeyUp
13
+ });
14
+ (0, react.useEffect)(() => {
15
+ callbacksRef.current = {
16
+ onKeyDown,
17
+ onKeyUp
18
+ };
19
+ }, [onKeyDown, onKeyUp]);
20
+ const keysSignature = JSON.stringify([...new Set(keys.map(normalizeKey))].sort());
21
+ const hasCallback = Boolean(onKeyDown || onKeyUp);
22
+ (0, react.useEffect)(() => {
23
+ if (!enabled || !hasCallback) {
24
+ pressedKeys.current.clear();
25
+ return;
26
+ }
27
+ const subscribedKeys = new Set(JSON.parse(keysSignature));
28
+ if (subscribedKeys.size === 0) {
29
+ pressedKeys.current.clear();
30
+ return;
31
+ }
32
+ const getModifierState = (modifier, nativeState, normalizedKey, type) => {
33
+ if (normalizedKey === modifier) return type === "keydown";
34
+ return nativeState || pressedKeys.current.has(modifier);
35
+ };
36
+ const handleKeyboardEvent = (event, type) => {
37
+ const normalizedKey = normalizeKey(event.key);
38
+ if (type === "keydown") pressedKeys.current.add(normalizedKey);
39
+ else pressedKeys.current.delete(normalizedKey);
40
+ if (!subscribedKeys.has(normalizedKey)) return;
41
+ const callback = type === "keydown" ? callbacksRef.current.onKeyDown : callbacksRef.current.onKeyUp;
42
+ if (!callback) return;
43
+ if (preventDefault && event.cancelable) event.preventDefault();
44
+ if (stopPropagation) event.stopPropagation();
45
+ callback({
46
+ key: event.key,
47
+ type,
48
+ shiftKey: getModifierState("shift", event.shiftKey, normalizedKey, type),
49
+ ctrlKey: getModifierState("control", event.ctrlKey, normalizedKey, type),
50
+ metaKey: getModifierState("meta", event.metaKey, normalizedKey, type),
51
+ altKey: getModifierState("alt", event.altKey, normalizedKey, type),
52
+ repeat: event.repeat,
53
+ nativeEvent: event
54
+ });
55
+ };
56
+ const handleKeyDown = (event) => {
57
+ handleKeyboardEvent(event, "keydown");
58
+ };
59
+ const handleKeyUp = (event) => {
60
+ handleKeyboardEvent(event, "keyup");
61
+ };
62
+ const clearPressedKeys = () => {
63
+ pressedKeys.current.clear();
64
+ };
65
+ const handleVisibilityChange = () => {
66
+ if (document.visibilityState === "hidden") clearPressedKeys();
67
+ };
68
+ window.addEventListener("keydown", handleKeyDown, true);
69
+ window.addEventListener("keyup", handleKeyUp, true);
70
+ window.addEventListener("blur", clearPressedKeys);
71
+ document.addEventListener("visibilitychange", handleVisibilityChange);
72
+ return () => {
73
+ window.removeEventListener("keydown", handleKeyDown, true);
74
+ window.removeEventListener("keyup", handleKeyUp, true);
75
+ window.removeEventListener("blur", clearPressedKeys);
76
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
77
+ clearPressedKeys();
78
+ };
79
+ }, [
80
+ enabled,
81
+ hasCallback,
82
+ keysSignature,
83
+ preventDefault,
84
+ stopPropagation
85
+ ]);
86
+ }
87
+ exports.useKeyboardKeys = useKeyboardKeys;
88
+
89
+ //# sourceMappingURL=use-keyboard-keys.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-keyboard-keys.cjs","names":["useRef"],"sources":["../src/use-keyboard-keys.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\n\nexport type KeyboardEventType = \"keydown\" | \"keyup\";\n\nexport interface UseKeyboardKeysEvent {\n key: string;\n type: KeyboardEventType;\n shiftKey: boolean;\n ctrlKey: boolean;\n metaKey: boolean;\n altKey: boolean;\n repeat: boolean;\n nativeEvent: KeyboardEvent;\n}\n\nexport interface UseKeyboardKeysOptions {\n keys: readonly string[];\n onKeyDown?: (event: UseKeyboardKeysEvent) => void;\n onKeyUp?: (event: UseKeyboardKeysEvent) => void;\n preventDefault?: boolean;\n stopPropagation?: boolean;\n enabled?: boolean;\n}\n\nfunction normalizeKey(key: string): string {\n const normalized = key.toLowerCase();\n\n if (normalized === \"space\" || normalized === \"spacebar\") {\n return \" \";\n }\n\n return normalized;\n}\n\ntype ModifierKey = \"shift\" | \"control\" | \"meta\" | \"alt\";\n\nexport function useKeyboardKeys({\n keys,\n onKeyDown,\n onKeyUp,\n preventDefault = false,\n stopPropagation = false,\n enabled = true,\n}: UseKeyboardKeysOptions): void {\n const pressedKeys = useRef(new Set<string>());\n const callbacksRef = useRef({ onKeyDown, onKeyUp });\n\n useEffect(() => {\n callbacksRef.current = { onKeyDown, onKeyUp };\n }, [onKeyDown, onKeyUp]);\n\n const keysSignature = JSON.stringify(\n [...new Set(keys.map(normalizeKey))].sort(),\n );\n\n const hasCallback = Boolean(onKeyDown || onKeyUp);\n\n useEffect(() => {\n if (!enabled || !hasCallback) {\n pressedKeys.current.clear();\n return;\n }\n\n const subscribedKeys = new Set<string>(\n JSON.parse(keysSignature) as string[],\n );\n\n if (subscribedKeys.size === 0) {\n pressedKeys.current.clear();\n return;\n }\n\n const getModifierState = (\n modifier: ModifierKey,\n nativeState: boolean,\n normalizedKey: string,\n type: KeyboardEventType,\n ): boolean => {\n if (normalizedKey === modifier) {\n return type === \"keydown\";\n }\n\n return nativeState || pressedKeys.current.has(modifier);\n };\n\n const handleKeyboardEvent = (\n event: KeyboardEvent,\n type: KeyboardEventType,\n ) => {\n const normalizedKey = normalizeKey(event.key);\n\n if (type === \"keydown\") {\n pressedKeys.current.add(normalizedKey);\n } else {\n pressedKeys.current.delete(normalizedKey);\n }\n\n if (!subscribedKeys.has(normalizedKey)) {\n return;\n }\n\n const callback =\n type === \"keydown\"\n ? callbacksRef.current.onKeyDown\n : callbacksRef.current.onKeyUp;\n\n if (!callback) {\n return;\n }\n\n if (preventDefault && event.cancelable) {\n event.preventDefault();\n }\n\n if (stopPropagation) {\n event.stopPropagation();\n }\n\n callback({\n key: event.key,\n type,\n shiftKey: getModifierState(\n \"shift\",\n event.shiftKey,\n normalizedKey,\n type,\n ),\n ctrlKey: getModifierState(\n \"control\",\n event.ctrlKey,\n normalizedKey,\n type,\n ),\n metaKey: getModifierState(\"meta\", event.metaKey, normalizedKey, type),\n altKey: getModifierState(\"alt\", event.altKey, normalizedKey, type),\n repeat: event.repeat,\n nativeEvent: event,\n });\n };\n\n const handleKeyDown = (event: KeyboardEvent) => {\n handleKeyboardEvent(event, \"keydown\");\n };\n\n const handleKeyUp = (event: KeyboardEvent) => {\n handleKeyboardEvent(event, \"keyup\");\n };\n\n const clearPressedKeys = () => {\n pressedKeys.current.clear();\n };\n\n const handleVisibilityChange = () => {\n if (document.visibilityState === \"hidden\") {\n clearPressedKeys();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown, true);\n window.addEventListener(\"keyup\", handleKeyUp, true);\n window.addEventListener(\"blur\", clearPressedKeys);\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n window.removeEventListener(\"keydown\", handleKeyDown, true);\n window.removeEventListener(\"keyup\", handleKeyUp, true);\n window.removeEventListener(\"blur\", clearPressedKeys);\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n\n clearPressedKeys();\n };\n }, [enabled, hasCallback, keysSignature, preventDefault, stopPropagation]);\n}\n"],"mappings":";;AAwBA,SAAS,aAAa,KAAqB;CACzC,MAAM,aAAa,IAAI,YAAY;CAEnC,IAAI,eAAe,WAAW,eAAe,YAC3C,OAAO;CAGT,OAAO;AACT;AAIA,SAAgB,gBAAgB,EAC9B,MACA,WACA,SACA,iBAAiB,OACjB,kBAAkB,OAClB,UAAU,QACqB;CAC/B,MAAM,eAAA,GAAcA,MAAAA,OAAAA,iBAAO,IAAI,IAAY,CAAC;CAC5C,MAAM,gBAAA,GAAeA,MAAAA,OAAAA,CAAO;EAAE;EAAW;CAAQ,CAAC;CAElD,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,aAAa,UAAU;GAAE;GAAW;EAAQ;CAC9C,GAAG,CAAC,WAAW,OAAO,CAAC;CAEvB,MAAM,gBAAgB,KAAK,UACzB,CAAC,GAAG,IAAI,IAAI,KAAK,IAAI,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAC5C;CAEA,MAAM,cAAc,QAAQ,aAAa,OAAO;CAEhD,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,IAAI,CAAC,WAAW,CAAC,aAAa;GAC5B,YAAY,QAAQ,MAAM;GAC1B;EACF;EAEA,MAAM,iBAAiB,IAAI,IACzB,KAAK,MAAM,aAAa,CAC1B;EAEA,IAAI,eAAe,SAAS,GAAG;GAC7B,YAAY,QAAQ,MAAM;GAC1B;EACF;EAEA,MAAM,oBACJ,UACA,aACA,eACA,SACY;GACZ,IAAI,kBAAkB,UACpB,OAAO,SAAS;GAGlB,OAAO,eAAe,YAAY,QAAQ,IAAI,QAAQ;EACxD;EAEA,MAAM,uBACJ,OACA,S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C3E"}
@@ -0,0 +1,20 @@
1
+ export type KeyboardEventType = "keydown" | "keyup";
2
+ export interface UseKeyboardKeysEvent {
3
+ key: string;
4
+ type: KeyboardEventType;
5
+ shiftKey: boolean;
6
+ ctrlKey: boolean;
7
+ metaKey: boolean;
8
+ altKey: boolean;
9
+ repeat: boolean;
10
+ nativeEvent: KeyboardEvent;
11
+ }
12
+ export interface UseKeyboardKeysOptions {
13
+ keys: readonly string[];
14
+ onKeyDown?: (event: UseKeyboardKeysEvent) => void;
15
+ onKeyUp?: (event: UseKeyboardKeysEvent) => void;
16
+ preventDefault?: boolean;
17
+ stopPropagation?: boolean;
18
+ enabled?: boolean;
19
+ }
20
+ export declare function useKeyboardKeys({ keys, onKeyDown, onKeyUp, preventDefault, stopPropagation, enabled }: UseKeyboardKeysOptions): void;
@@ -0,0 +1,20 @@
1
+ export type KeyboardEventType = "keydown" | "keyup";
2
+ export interface UseKeyboardKeysEvent {
3
+ key: string;
4
+ type: KeyboardEventType;
5
+ shiftKey: boolean;
6
+ ctrlKey: boolean;
7
+ metaKey: boolean;
8
+ altKey: boolean;
9
+ repeat: boolean;
10
+ nativeEvent: KeyboardEvent;
11
+ }
12
+ export interface UseKeyboardKeysOptions {
13
+ keys: readonly string[];
14
+ onKeyDown?: (event: UseKeyboardKeysEvent) => void;
15
+ onKeyUp?: (event: UseKeyboardKeysEvent) => void;
16
+ preventDefault?: boolean;
17
+ stopPropagation?: boolean;
18
+ enabled?: boolean;
19
+ }
20
+ export declare function useKeyboardKeys({ keys, onKeyDown, onKeyUp, preventDefault, stopPropagation, enabled }: UseKeyboardKeysOptions): void;
@@ -0,0 +1,89 @@
1
+ import { useEffect, useRef } from "react";
2
+ // src/use-keyboard-keys.ts
3
+ function normalizeKey(key) {
4
+ const normalized = key.toLowerCase();
5
+ if (normalized === "space" || normalized === "spacebar") return " ";
6
+ return normalized;
7
+ }
8
+ function useKeyboardKeys({ keys, onKeyDown, onKeyUp, preventDefault = false, stopPropagation = false, enabled = true }) {
9
+ const pressedKeys = useRef(/* @__PURE__ */ new Set());
10
+ const callbacksRef = useRef({
11
+ onKeyDown,
12
+ onKeyUp
13
+ });
14
+ useEffect(() => {
15
+ callbacksRef.current = {
16
+ onKeyDown,
17
+ onKeyUp
18
+ };
19
+ }, [onKeyDown, onKeyUp]);
20
+ const keysSignature = JSON.stringify([...new Set(keys.map(normalizeKey))].sort());
21
+ const hasCallback = Boolean(onKeyDown || onKeyUp);
22
+ useEffect(() => {
23
+ if (!enabled || !hasCallback) {
24
+ pressedKeys.current.clear();
25
+ return;
26
+ }
27
+ const subscribedKeys = new Set(JSON.parse(keysSignature));
28
+ if (subscribedKeys.size === 0) {
29
+ pressedKeys.current.clear();
30
+ return;
31
+ }
32
+ const getModifierState = (modifier, nativeState, normalizedKey, type) => {
33
+ if (normalizedKey === modifier) return type === "keydown";
34
+ return nativeState || pressedKeys.current.has(modifier);
35
+ };
36
+ const handleKeyboardEvent = (event, type) => {
37
+ const normalizedKey = normalizeKey(event.key);
38
+ if (type === "keydown") pressedKeys.current.add(normalizedKey);
39
+ else pressedKeys.current.delete(normalizedKey);
40
+ if (!subscribedKeys.has(normalizedKey)) return;
41
+ const callback = type === "keydown" ? callbacksRef.current.onKeyDown : callbacksRef.current.onKeyUp;
42
+ if (!callback) return;
43
+ if (preventDefault && event.cancelable) event.preventDefault();
44
+ if (stopPropagation) event.stopPropagation();
45
+ callback({
46
+ key: event.key,
47
+ type,
48
+ shiftKey: getModifierState("shift", event.shiftKey, normalizedKey, type),
49
+ ctrlKey: getModifierState("control", event.ctrlKey, normalizedKey, type),
50
+ metaKey: getModifierState("meta", event.metaKey, normalizedKey, type),
51
+ altKey: getModifierState("alt", event.altKey, normalizedKey, type),
52
+ repeat: event.repeat,
53
+ nativeEvent: event
54
+ });
55
+ };
56
+ const handleKeyDown = (event) => {
57
+ handleKeyboardEvent(event, "keydown");
58
+ };
59
+ const handleKeyUp = (event) => {
60
+ handleKeyboardEvent(event, "keyup");
61
+ };
62
+ const clearPressedKeys = () => {
63
+ pressedKeys.current.clear();
64
+ };
65
+ const handleVisibilityChange = () => {
66
+ if (document.visibilityState === "hidden") clearPressedKeys();
67
+ };
68
+ window.addEventListener("keydown", handleKeyDown, true);
69
+ window.addEventListener("keyup", handleKeyUp, true);
70
+ window.addEventListener("blur", clearPressedKeys);
71
+ document.addEventListener("visibilitychange", handleVisibilityChange);
72
+ return () => {
73
+ window.removeEventListener("keydown", handleKeyDown, true);
74
+ window.removeEventListener("keyup", handleKeyUp, true);
75
+ window.removeEventListener("blur", clearPressedKeys);
76
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
77
+ clearPressedKeys();
78
+ };
79
+ }, [
80
+ enabled,
81
+ hasCallback,
82
+ keysSignature,
83
+ preventDefault,
84
+ stopPropagation
85
+ ]);
86
+ }
87
+ export { useKeyboardKeys };
88
+
89
+ //# sourceMappingURL=use-keyboard-keys.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-keyboard-keys.js","names":[],"sources":["../src/use-keyboard-keys.ts"],"sourcesContent":["import { useEffect, useRef } from \"react\";\n\nexport type KeyboardEventType = \"keydown\" | \"keyup\";\n\nexport interface UseKeyboardKeysEvent {\n key: string;\n type: KeyboardEventType;\n shiftKey: boolean;\n ctrlKey: boolean;\n metaKey: boolean;\n altKey: boolean;\n repeat: boolean;\n nativeEvent: KeyboardEvent;\n}\n\nexport interface UseKeyboardKeysOptions {\n keys: readonly string[];\n onKeyDown?: (event: UseKeyboardKeysEvent) => void;\n onKeyUp?: (event: UseKeyboardKeysEvent) => void;\n preventDefault?: boolean;\n stopPropagation?: boolean;\n enabled?: boolean;\n}\n\nfunction normalizeKey(key: string): string {\n const normalized = key.toLowerCase();\n\n if (normalized === \"space\" || normalized === \"spacebar\") {\n return \" \";\n }\n\n return normalized;\n}\n\ntype ModifierKey = \"shift\" | \"control\" | \"meta\" | \"alt\";\n\nexport function useKeyboardKeys({\n keys,\n onKeyDown,\n onKeyUp,\n preventDefault = false,\n stopPropagation = false,\n enabled = true,\n}: UseKeyboardKeysOptions): void {\n const pressedKeys = useRef(new Set<string>());\n const callbacksRef = useRef({ onKeyDown, onKeyUp });\n\n useEffect(() => {\n callbacksRef.current = { onKeyDown, onKeyUp };\n }, [onKeyDown, onKeyUp]);\n\n const keysSignature = JSON.stringify(\n [...new Set(keys.map(normalizeKey))].sort(),\n );\n\n const hasCallback = Boolean(onKeyDown || onKeyUp);\n\n useEffect(() => {\n if (!enabled || !hasCallback) {\n pressedKeys.current.clear();\n return;\n }\n\n const subscribedKeys = new Set<string>(\n JSON.parse(keysSignature) as string[],\n );\n\n if (subscribedKeys.size === 0) {\n pressedKeys.current.clear();\n return;\n }\n\n const getModifierState = (\n modifier: ModifierKey,\n nativeState: boolean,\n normalizedKey: string,\n type: KeyboardEventType,\n ): boolean => {\n if (normalizedKey === modifier) {\n return type === \"keydown\";\n }\n\n return nativeState || pressedKeys.current.has(modifier);\n };\n\n const handleKeyboardEvent = (\n event: KeyboardEvent,\n type: KeyboardEventType,\n ) => {\n const normalizedKey = normalizeKey(event.key);\n\n if (type === \"keydown\") {\n pressedKeys.current.add(normalizedKey);\n } else {\n pressedKeys.current.delete(normalizedKey);\n }\n\n if (!subscribedKeys.has(normalizedKey)) {\n return;\n }\n\n const callback =\n type === \"keydown\"\n ? callbacksRef.current.onKeyDown\n : callbacksRef.current.onKeyUp;\n\n if (!callback) {\n return;\n }\n\n if (preventDefault && event.cancelable) {\n event.preventDefault();\n }\n\n if (stopPropagation) {\n event.stopPropagation();\n }\n\n callback({\n key: event.key,\n type,\n shiftKey: getModifierState(\n \"shift\",\n event.shiftKey,\n normalizedKey,\n type,\n ),\n ctrlKey: getModifierState(\n \"control\",\n event.ctrlKey,\n normalizedKey,\n type,\n ),\n metaKey: getModifierState(\"meta\", event.metaKey, normalizedKey, type),\n altKey: getModifierState(\"alt\", event.altKey, normalizedKey, type),\n repeat: event.repeat,\n nativeEvent: event,\n });\n };\n\n const handleKeyDown = (event: KeyboardEvent) => {\n handleKeyboardEvent(event, \"keydown\");\n };\n\n const handleKeyUp = (event: KeyboardEvent) => {\n handleKeyboardEvent(event, \"keyup\");\n };\n\n const clearPressedKeys = () => {\n pressedKeys.current.clear();\n };\n\n const handleVisibilityChange = () => {\n if (document.visibilityState === \"hidden\") {\n clearPressedKeys();\n }\n };\n\n window.addEventListener(\"keydown\", handleKeyDown, true);\n window.addEventListener(\"keyup\", handleKeyUp, true);\n window.addEventListener(\"blur\", clearPressedKeys);\n document.addEventListener(\"visibilitychange\", handleVisibilityChange);\n\n return () => {\n window.removeEventListener(\"keydown\", handleKeyDown, true);\n window.removeEventListener(\"keyup\", handleKeyUp, true);\n window.removeEventListener(\"blur\", clearPressedKeys);\n document.removeEventListener(\"visibilitychange\", handleVisibilityChange);\n\n clearPressedKeys();\n };\n }, [enabled, hasCallback, keysSignature, preventDefault, stopPropagation]);\n}\n"],"mappings":";;AAwBA,SAAS,aAAa,KAAqB;CACzC,MAAM,aAAa,IAAI,YAAY;CAEnC,IAAI,eAAe,WAAW,eAAe,YAC3C,OAAO;CAGT,OAAO;AACT;AAIA,SAAgB,gBAAgB,EAC9B,MACA,WACA,SACA,iBAAiB,OACjB,kBAAkB,OAClB,UAAU,QACqB;CAC/B,MAAM,cAAc,uBAAO,IAAI,IAAY,CAAC;CAC5C,MAAM,eAAe,OAAO;EAAE;EAAW;CAAQ,CAAC;CAElD,gBAAgB;EACd,aAAa,UAAU;GAAE;GAAW;EAAQ;CAC9C,GAAG,CAAC,WAAW,OAAO,CAAC;CAEvB,MAAM,gBAAgB,KAAK,UACzB,CAAC,GAAG,IAAI,IAAI,KAAK,IAAI,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAC5C;CAEA,MAAM,cAAc,QAAQ,aAAa,OAAO;CAEhD,gBAAgB;EACd,IAAI,CAAC,WAAW,CAAC,aAAa;GAC5B,YAAY,QAAQ,MAAM;GAC1B;EACF;EAEA,MAAM,iBAAiB,IAAI,IACzB,KAAK,MAAM,a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,aAAa;GACX,OAAO,oBAAoB,WAAW,eAAe,IAAI;GACzD,OAAO,oBAAoB,SAAS,aAAa,IAAI;GACrD,OAAO,oBAAoB,QAAQ,gBAAgB;GACnD,SAAS,oBAAoB,oBAAoB,sBAAsB;GAEvE,iBAAiB;EACnB;CACF,GAAG;EAAC;EAAS;EAAa;EAAe;EAAgB;CAAe,CAAC;AAC3E"}
@@ -0,0 +1,93 @@
1
+ "use client";
2
+ let react = require("react");
3
+ // src/use-roving-focus.ts
4
+ const useRovingFocus = ({ items, orientation = "horizontal", dir = "ltr", loop = true, initialActiveId }) => {
5
+ const itemRefs = (0, react.useRef)(/* @__PURE__ */ new Map());
6
+ const callbackRefs = (0, react.useRef)(/* @__PURE__ */ new Map());
7
+ const itemsRef = (0, react.useRef)(items);
8
+ itemsRef.current = items;
9
+ const [activeId, setActiveId] = (0, react.useState)(() => {
10
+ return items.find((item) => item.id === initialActiveId && !item.disabled)?.id ?? items.find((item) => !item.disabled)?.id;
11
+ });
12
+ const resolvedActiveId = items.find((item) => item.id === activeId && !item.disabled)?.id ?? items.find((item) => !item.disabled)?.id;
13
+ (0, react.useEffect)(() => {
14
+ if (activeId !== resolvedActiveId) setActiveId(resolvedActiveId);
15
+ }, [activeId, resolvedActiveId]);
16
+ const getItemRef = (0, react.useCallback)((id) => {
17
+ const existingCallback = callbackRefs.current.get(id);
18
+ if (existingCallback) return existingCallback;
19
+ const callback = (node) => {
20
+ if (node) {
21
+ itemRefs.current.set(id, node);
22
+ return;
23
+ }
24
+ itemRefs.current.delete(id);
25
+ if (callbackRefs.current.get(id) === callback) callbackRefs.current.delete(id);
26
+ };
27
+ callbackRefs.current.set(id, callback);
28
+ return callback;
29
+ }, []);
30
+ const focusItem = (0, react.useCallback)((id) => {
31
+ const item = itemsRef.current.find((candidate) => candidate.id === id && !candidate.disabled);
32
+ const element = itemRefs.current.get(id);
33
+ if (!item || !element) return;
34
+ setActiveId(id);
35
+ element.focus();
36
+ }, []);
37
+ return {
38
+ activeId: resolvedActiveId,
39
+ getItemRef,
40
+ getItemTabIndex: (0, react.useCallback)((id, disabled = false) => {
41
+ if (disabled || resolvedActiveId === void 0) return -1;
42
+ return id === resolvedActiveId ? 0 : -1;
43
+ }, [resolvedActiveId]),
44
+ focusItem,
45
+ onItemFocus: (0, react.useCallback)((id) => {
46
+ if (itemsRef.current.find((candidate) => candidate.id === id && !candidate.disabled)) setActiveId(id);
47
+ }, []),
48
+ onItemKeyDown: (0, react.useCallback)((event, id) => {
49
+ if (event.defaultPrevented) return;
50
+ const enabledItems = itemsRef.current.filter((item) => !item.disabled);
51
+ if (enabledItems.length === 0) return;
52
+ const currentIndex = enabledItems.findIndex((item) => item.id === id);
53
+ if (currentIndex === -1) return;
54
+ let nextIndex;
55
+ let direction;
56
+ switch (event.key) {
57
+ case "Home":
58
+ nextIndex = 0;
59
+ break;
60
+ case "End":
61
+ nextIndex = enabledItems.length - 1;
62
+ break;
63
+ case "ArrowRight":
64
+ if (orientation === "horizontal" || orientation === "both") direction = dir === "rtl" ? -1 : 1;
65
+ break;
66
+ case "ArrowLeft":
67
+ if (orientation === "horizontal" || orientation === "both") direction = dir === "rtl" ? 1 : -1;
68
+ break;
69
+ case "ArrowDown":
70
+ if (orientation === "vertical" || orientation === "both") direction = 1;
71
+ break;
72
+ case "ArrowUp": if (orientation === "vertical" || orientation === "both") direction = -1;
73
+ }
74
+ if (direction !== void 0) {
75
+ const candidateIndex = currentIndex + direction;
76
+ nextIndex = loop ? (candidateIndex + enabledItems.length) % enabledItems.length : Math.min(Math.max(candidateIndex, 0), enabledItems.length - 1);
77
+ }
78
+ if (nextIndex === void 0) return;
79
+ const nextItem = enabledItems[nextIndex];
80
+ if (!nextItem) return;
81
+ event.preventDefault();
82
+ focusItem(nextItem.id);
83
+ }, [
84
+ dir,
85
+ focusItem,
86
+ loop,
87
+ orientation
88
+ ])
89
+ };
90
+ };
91
+ exports.useRovingFocus = useRovingFocus;
92
+
93
+ //# sourceMappingURL=use-roving-focus.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-roving-focus.cjs","names":["useRef","useState","useCallback"],"sources":["../src/use-roving-focus.ts"],"sourcesContent":["\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n type KeyboardEvent,\n type RefCallback,\n} from \"react\";\n\nexport type RovingFocusOrientation = \"horizontal\" | \"vertical\" | \"both\";\n\nexport type RovingFocusItem = {\n id: string;\n disabled?: boolean;\n};\n\nexport type UseRovingFocusOptions = {\n items: readonly RovingFocusItem[];\n orientation?: RovingFocusOrientation;\n dir?: \"ltr\" | \"rtl\";\n loop?: boolean;\n initialActiveId?: string;\n};\n\nexport type UseRovingFocusReturn<T extends HTMLElement> = {\n activeId: string | undefined;\n getItemRef: (id: string) => RefCallback<T>;\n getItemTabIndex: (id: string, disabled?: boolean) => 0 | -1;\n focusItem: (id: string) => void;\n onItemFocus: (id: string) => void;\n onItemKeyDown: (event: KeyboardEvent<T>, id: string) => void;\n};\n\nconst useRovingFocus = <T extends HTMLElement>({\n items,\n orientation = \"horizontal\",\n dir = \"ltr\",\n loop = true,\n initialActiveId,\n}: UseRovingFocusOptions): UseRovingFocusReturn<T> => {\n const itemRefs = useRef(new Map<string, T>());\n const callbackRefs = useRef(new Map<string, RefCallback<T>>());\n const itemsRef = useRef(items);\n\n itemsRef.current = items;\n\n const [activeId, setActiveId] = useState<string | undefined>(() => {\n const initialItem = items.find(\n (item) => item.id === initialActiveId && !item.disabled,\n );\n\n return initialItem?.id ?? items.find((item) => !item.disabled)?.id;\n });\n\n const resolvedActiveId =\n items.find((item) => item.id === activeId && !item.disabled)?.id ??\n items.find((item) => !item.disabled)?.id;\n\n useEffect(() => {\n if (activeId !== resolvedActiveId) {\n setActiveId(resolvedActiveId);\n }\n }, [activeId, resolvedActiveId]);\n\n const getItemRef = useCallback((id: string): RefCallback<T> => {\n const existingCallback = callbackRefs.current.get(id);\n\n if (existingCallback) {\n return existingCallback;\n }\n\n const callback: RefCallback<T> = (node) => {\n if (node) {\n itemRefs.current.set(id, node);\n return;\n }\n\n itemRefs.current.delete(id);\n\n if (callbackRefs.current.get(id) === callback) {\n callbackRefs.current.delete(id);\n }\n };\n\n callbackRefs.current.set(id, callback);\n\n return callback;\n }, []);\n\n const focusItem = useCallback((id: string) => {\n const item = itemsRef.current.find(\n (candidate) => candidate.id === id && !candidate.disabled,\n );\n const element = itemRefs.current.get(id);\n\n if (!item || !element) {\n return;\n }\n\n setActiveId(id);\n element.focus();\n }, []);\n\n const getItemTabIndex = useCallback(\n (id: string, disabled = false): 0 | -1 => {\n if (disabled || resolvedActiveId === undefined) {\n return -1;\n }\n\n return id === resolvedActiveId ? 0 : -1;\n },\n [resolvedActiveId],\n );\n\n const onItemFocus = useCallback((id: string) => {\n const item = itemsRef.current.find(\n (candidate) => candidate.id === id && !candidate.disabled,\n );\n\n if (item) {\n setActiveId(id);\n }\n }, []);\n\n const onItemKeyDown = useCallback(\n (event: KeyboardEvent<T>, id: string) => {\n if (event.defaultPrevented) {\n return;\n }\n\n const enabledItems = itemsRef.current.filter((item) => !item.disabled);\n\n if (enabledItems.length === 0) {\n return;\n }\n\n const currentIndex = enabledItems.findIndex((item) => item.id === id);\n\n if (currentIndex === -1) {\n return;\n }\n\n let nextIndex: number | undefined;\n let direction: number | undefined;\n\n switch (event.key) {\n case \"Home\":\n nextIndex = 0;\n break;\n\n case \"End\":\n nextIndex = enabledItems.length - 1;\n break;\n\n case \"ArrowRight\":\n if (orientation === \"horizontal\" || orientation === \"both\") {\n direction = dir === \"rtl\" ? -1 : 1;\n }\n break;\n\n case \"ArrowLeft\":\n if (orientation === \"horizontal\" || orientation === \"both\") {\n direction = dir === \"rtl\" ? 1 : -1;\n }\n break;\n\n case \"ArrowDown\":\n if (orientation === \"vertical\" || orientation === \"both\") {\n direction = 1;\n }\n break;\n\n case \"ArrowUp\":\n if (orientation === \"vertical\" || orientation === \"both\") {\n direction = -1;\n }\n break;\n }\n\n if (direction !== undefined) {\n const candidateIndex = currentIndex + direction;\n\n nextIndex = loop\n ? (candidateIndex + enabledItems.length) % enabledItems.length\n : Math.min(Math.max(candidateIndex, 0), enabledItems.length - 1);\n }\n\n if (nextIndex === undefined) {\n return;\n }\n\n const nextItem = enabledItems[nextIndex];\n\n if (!nextItem) {\n return;\n }\n\n event.preventDefault();\n focusItem(nextItem.id);\n },\n [dir, focusItem, loop, orientation],\n );\n\n return {\n activeId: resolvedActiveId,\n getItemRef,\n getItemTabIndex,\n focusItem,\n onItemFocus,\n onItemKeyDown,\n };\n};\n\nexport { useRovingFocus };\n"],"mappings":";;;AAmCA,MAAM,kBAAyC,EAC7C,OACA,cAAc,cACd,MAAM,OACN,OAAO,MACP,sBACoD;CACpD,MAAM,YAAA,GAAWA,MAAAA,OAAAA,iBAAO,IAAI,IAAe,CAAC;CAC5C,MAAM,gBAAA,GAAeA,MAAAA,OAAAA,iBAAO,IAAI,IAA4B,CAAC;CAC7D,MAAM,YAAA,GAAWA,MAAAA,OAAAA,CAAO,KAAK;CAE7B,SAAS,UAAU;CAEnB,MAAM,CAAC,UAAU,gBAAA,GAAeC,MAAAA,SAAAA,OAAmC;EAKjE,OAJoB,MAAM,MACvB,SAAS,KAAK,OAAO,mBAAmB,CAAC,KAAK,QAGhC,CAAC,EAAE,MAAM,MAAM,MAAM,SAAS,CAAC,KAAK,QAAQ,CAAC,EAAE;CAClE,CAAC;CAED,MAAM,mBACJ,MAAM,MAAM,SAAS,KAAK,OAAO,YAAY,CAAC,KAAK,QAAQ,CAAC,EAAE,MAC9D,MAAM,MAAM,SAAS,CAAC,KAAK,QAAQ,CAAC,EAAE;CAExC,CAAA,GAAA,MAAA,UAAA,OAAgB;EACd,IAAI,aAAa,kBACf,YAAY,gBAAgB;CAEhC,GAAG,CAAC,UAAU,gBAAgB,CAAC;CAE/B,MAAM,cAAA,GAAaC,MAAAA,YAAAA,EAAa,OAA+B;EAC7D,MAAM,mBAAmB,aAAa,QAAQ,IAAI,EAAE;EAEpD,IAAI,kBACF,O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d;IACE,KAAK;KACH,YAAY;KACZ;IAEF,KAAK;KACH,YAAY,aAAa,SAAS;KAClC;IAEF,KAAK;KACH,IAAI,gBAAgB,gBAAgB,gBAAgB,QAClD,YAAY,QAAQ,QAAQ,KAAK;KAEnC;IAEF,KAAK;KACH,IAAI,gBAAgB,gBAAgB,gBAAgB,QAClD,YAAY,QAAQ,QAAQ,IAAI;KAElC;IAEF,KAAK;KACH,IAAI,gBAAgB,cAAc,gBAAgB,QAChD,YAAY;KAEd;IAEF,KAAK,WACH,IAAI,gBAAgB,cAAc,gBAAgB,QAChD,YAAY;GAGlB;GAEA,IAAI,cAAc,KAAA,GAAW;IAC3B,MAAM,iBAAiB,eAAe;IAEtC,YAAY,QACP,iBAAiB,aAAa,UAAU,aAAa,SACtD,KAAK,IAAI,KAAK,IAAI,gBAAgB,CAAC,GAAG,aAAa,SAAS,CAAC;GACnE;GAEA,IAAI,cAAc,KAAA,GAChB;GAGF,MAAM,WAAW,aAAa;GAE9B,IAAI,CAAC,UACH;GAGF,MAAM,eAAe;GACrB,UAAU,SAAS,EAAE;EACvB,GACA;GAAC;GAAK;GAAW;GAAM;EAAW,CAStB;CACd;AACF"}
@@ -0,0 +1,23 @@
1
+ import { KeyboardEvent, RefCallback } from "react";
2
+ export type RovingFocusOrientation = "horizontal" | "vertical" | "both";
3
+ export type RovingFocusItem = {
4
+ id: string;
5
+ disabled?: boolean;
6
+ };
7
+ export type UseRovingFocusOptions = {
8
+ items: readonly RovingFocusItem[];
9
+ orientation?: RovingFocusOrientation;
10
+ dir?: "ltr" | "rtl";
11
+ loop?: boolean;
12
+ initialActiveId?: string;
13
+ };
14
+ export type UseRovingFocusReturn<T extends HTMLElement> = {
15
+ activeId: string | undefined;
16
+ getItemRef: (id: string) => RefCallback<T>;
17
+ getItemTabIndex: (id: string, disabled?: boolean) => 0 | -1;
18
+ focusItem: (id: string) => void;
19
+ onItemFocus: (id: string) => void;
20
+ onItemKeyDown: (event: KeyboardEvent<T>, id: string) => void;
21
+ };
22
+ declare const useRovingFocus: <T extends HTMLElement>({ items, orientation, dir, loop, initialActiveId }: UseRovingFocusOptions) => UseRovingFocusReturn<T>;
23
+ export { useRovingFocus };
@@ -0,0 +1,23 @@
1
+ import { KeyboardEvent, RefCallback } from "react";
2
+ export type RovingFocusOrientation = "horizontal" | "vertical" | "both";
3
+ export type RovingFocusItem = {
4
+ id: string;
5
+ disabled?: boolean;
6
+ };
7
+ export type UseRovingFocusOptions = {
8
+ items: readonly RovingFocusItem[];
9
+ orientation?: RovingFocusOrientation;
10
+ dir?: "ltr" | "rtl";
11
+ loop?: boolean;
12
+ initialActiveId?: string;
13
+ };
14
+ export type UseRovingFocusReturn<T extends HTMLElement> = {
15
+ activeId: string | undefined;
16
+ getItemRef: (id: string) => RefCallback<T>;
17
+ getItemTabIndex: (id: string, disabled?: boolean) => 0 | -1;
18
+ focusItem: (id: string) => void;
19
+ onItemFocus: (id: string) => void;
20
+ onItemKeyDown: (event: KeyboardEvent<T>, id: string) => void;
21
+ };
22
+ declare const useRovingFocus: <T extends HTMLElement>({ items, orientation, dir, loop, initialActiveId }: UseRovingFocusOptions) => UseRovingFocusReturn<T>;
23
+ export { useRovingFocus };
@@ -0,0 +1,93 @@
1
+ "use client";
2
+ import { useCallback, useEffect, useRef, useState } from "react";
3
+ // src/use-roving-focus.ts
4
+ const useRovingFocus = ({ items, orientation = "horizontal", dir = "ltr", loop = true, initialActiveId }) => {
5
+ const itemRefs = useRef(/* @__PURE__ */ new Map());
6
+ const callbackRefs = useRef(/* @__PURE__ */ new Map());
7
+ const itemsRef = useRef(items);
8
+ itemsRef.current = items;
9
+ const [activeId, setActiveId] = useState(() => {
10
+ return items.find((item) => item.id === initialActiveId && !item.disabled)?.id ?? items.find((item) => !item.disabled)?.id;
11
+ });
12
+ const resolvedActiveId = items.find((item) => item.id === activeId && !item.disabled)?.id ?? items.find((item) => !item.disabled)?.id;
13
+ useEffect(() => {
14
+ if (activeId !== resolvedActiveId) setActiveId(resolvedActiveId);
15
+ }, [activeId, resolvedActiveId]);
16
+ const getItemRef = useCallback((id) => {
17
+ const existingCallback = callbackRefs.current.get(id);
18
+ if (existingCallback) return existingCallback;
19
+ const callback = (node) => {
20
+ if (node) {
21
+ itemRefs.current.set(id, node);
22
+ return;
23
+ }
24
+ itemRefs.current.delete(id);
25
+ if (callbackRefs.current.get(id) === callback) callbackRefs.current.delete(id);
26
+ };
27
+ callbackRefs.current.set(id, callback);
28
+ return callback;
29
+ }, []);
30
+ const focusItem = useCallback((id) => {
31
+ const item = itemsRef.current.find((candidate) => candidate.id === id && !candidate.disabled);
32
+ const element = itemRefs.current.get(id);
33
+ if (!item || !element) return;
34
+ setActiveId(id);
35
+ element.focus();
36
+ }, []);
37
+ return {
38
+ activeId: resolvedActiveId,
39
+ getItemRef,
40
+ getItemTabIndex: useCallback((id, disabled = false) => {
41
+ if (disabled || resolvedActiveId === void 0) return -1;
42
+ return id === resolvedActiveId ? 0 : -1;
43
+ }, [resolvedActiveId]),
44
+ focusItem,
45
+ onItemFocus: useCallback((id) => {
46
+ if (itemsRef.current.find((candidate) => candidate.id === id && !candidate.disabled)) setActiveId(id);
47
+ }, []),
48
+ onItemKeyDown: useCallback((event, id) => {
49
+ if (event.defaultPrevented) return;
50
+ const enabledItems = itemsRef.current.filter((item) => !item.disabled);
51
+ if (enabledItems.length === 0) return;
52
+ const currentIndex = enabledItems.findIndex((item) => item.id === id);
53
+ if (currentIndex === -1) return;
54
+ let nextIndex;
55
+ let direction;
56
+ switch (event.key) {
57
+ case "Home":
58
+ nextIndex = 0;
59
+ break;
60
+ case "End":
61
+ nextIndex = enabledItems.length - 1;
62
+ break;
63
+ case "ArrowRight":
64
+ if (orientation === "horizontal" || orientation === "both") direction = dir === "rtl" ? -1 : 1;
65
+ break;
66
+ case "ArrowLeft":
67
+ if (orientation === "horizontal" || orientation === "both") direction = dir === "rtl" ? 1 : -1;
68
+ break;
69
+ case "ArrowDown":
70
+ if (orientation === "vertical" || orientation === "both") direction = 1;
71
+ break;
72
+ case "ArrowUp": if (orientation === "vertical" || orientation === "both") direction = -1;
73
+ }
74
+ if (direction !== void 0) {
75
+ const candidateIndex = currentIndex + direction;
76
+ nextIndex = loop ? (candidateIndex + enabledItems.length) % enabledItems.length : Math.min(Math.max(candidateIndex, 0), enabledItems.length - 1);
77
+ }
78
+ if (nextIndex === void 0) return;
79
+ const nextItem = enabledItems[nextIndex];
80
+ if (!nextItem) return;
81
+ event.preventDefault();
82
+ focusItem(nextItem.id);
83
+ }, [
84
+ dir,
85
+ focusItem,
86
+ loop,
87
+ orientation
88
+ ])
89
+ };
90
+ };
91
+ export { useRovingFocus };
92
+
93
+ //# sourceMappingURL=use-roving-focus.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-roving-focus.js","names":[],"sources":["../src/use-roving-focus.ts"],"sourcesContent":["\"use client\";\n\nimport {\n useCallback,\n useEffect,\n useRef,\n useState,\n type KeyboardEvent,\n type RefCallback,\n} from \"react\";\n\nexport type RovingFocusOrientation = \"horizontal\" | \"vertical\" | \"both\";\n\nexport type RovingFocusItem = {\n id: string;\n disabled?: boolean;\n};\n\nexport type UseRovingFocusOptions = {\n items: readonly RovingFocusItem[];\n orientation?: RovingFocusOrientation;\n dir?: \"ltr\" | \"rtl\";\n loop?: boolean;\n initialActiveId?: string;\n};\n\nexport type UseRovingFocusReturn<T extends HTMLElement> = {\n activeId: string | undefined;\n getItemRef: (id: string) => RefCallback<T>;\n getItemTabIndex: (id: string, disabled?: boolean) => 0 | -1;\n focusItem: (id: string) => void;\n onItemFocus: (id: string) => void;\n onItemKeyDown: (event: KeyboardEvent<T>, id: string) => void;\n};\n\nconst useRovingFocus = <T extends HTMLElement>({\n items,\n orientation = \"horizontal\",\n dir = \"ltr\",\n loop = true,\n initialActiveId,\n}: UseRovingFocusOptions): UseRovingFocusReturn<T> => {\n const itemRefs = useRef(new Map<string, T>());\n const callbackRefs = useRef(new Map<string, RefCallback<T>>());\n const itemsRef = useRef(items);\n\n itemsRef.current = items;\n\n const [activeId, setActiveId] = useState<string | undefined>(() => {\n const initialItem = items.find(\n (item) => item.id === initialActiveId && !item.disabled,\n );\n\n return initialItem?.id ?? items.find((item) => !item.disabled)?.id;\n });\n\n const resolvedActiveId =\n items.find((item) => item.id === activeId && !item.disabled)?.id ??\n items.find((item) => !item.disabled)?.id;\n\n useEffect(() => {\n if (activeId !== resolvedActiveId) {\n setActiveId(resolvedActiveId);\n }\n }, [activeId, resolvedActiveId]);\n\n const getItemRef = useCallback((id: string): RefCallback<T> => {\n const existingCallback = callbackRefs.current.get(id);\n\n if (existingCallback) {\n return existingCallback;\n }\n\n const callback: RefCallback<T> = (node) => {\n if (node) {\n itemRefs.current.set(id, node);\n return;\n }\n\n itemRefs.current.delete(id);\n\n if (callbackRefs.current.get(id) === callback) {\n callbackRefs.current.delete(id);\n }\n };\n\n callbackRefs.current.set(id, callback);\n\n return callback;\n }, []);\n\n const focusItem = useCallback((id: string) => {\n const item = itemsRef.current.find(\n (candidate) => candidate.id === id && !candidate.disabled,\n );\n const element = itemRefs.current.get(id);\n\n if (!item || !element) {\n return;\n }\n\n setActiveId(id);\n element.focus();\n }, []);\n\n const getItemTabIndex = useCallback(\n (id: string, disabled = false): 0 | -1 => {\n if (disabled || resolvedActiveId === undefined) {\n return -1;\n }\n\n return id === resolvedActiveId ? 0 : -1;\n },\n [resolvedActiveId],\n );\n\n const onItemFocus = useCallback((id: string) => {\n const item = itemsRef.current.find(\n (candidate) => candidate.id === id && !candidate.disabled,\n );\n\n if (item) {\n setActiveId(id);\n }\n }, []);\n\n const onItemKeyDown = useCallback(\n (event: KeyboardEvent<T>, id: string) => {\n if (event.defaultPrevented) {\n return;\n }\n\n const enabledItems = itemsRef.current.filter((item) => !item.disabled);\n\n if (enabledItems.length === 0) {\n return;\n }\n\n const currentIndex = enabledItems.findIndex((item) => item.id === id);\n\n if (currentIndex === -1) {\n return;\n }\n\n let nextIndex: number | undefined;\n let direction: number | undefined;\n\n switch (event.key) {\n case \"Home\":\n nextIndex = 0;\n break;\n\n case \"End\":\n nextIndex = enabledItems.length - 1;\n break;\n\n case \"ArrowRight\":\n if (orientation === \"horizontal\" || orientation === \"both\") {\n direction = dir === \"rtl\" ? -1 : 1;\n }\n break;\n\n case \"ArrowLeft\":\n if (orientation === \"horizontal\" || orientation === \"both\") {\n direction = dir === \"rtl\" ? 1 : -1;\n }\n break;\n\n case \"ArrowDown\":\n if (orientation === \"vertical\" || orientation === \"both\") {\n direction = 1;\n }\n break;\n\n case \"ArrowUp\":\n if (orientation === \"vertical\" || orientation === \"both\") {\n direction = -1;\n }\n break;\n }\n\n if (direction !== undefined) {\n const candidateIndex = currentIndex + direction;\n\n nextIndex = loop\n ? (candidateIndex + enabledItems.length) % enabledItems.length\n : Math.min(Math.max(candidateIndex, 0), enabledItems.length - 1);\n }\n\n if (nextIndex === undefined) {\n return;\n }\n\n const nextItem = enabledItems[nextIndex];\n\n if (!nextItem) {\n return;\n }\n\n event.preventDefault();\n focusItem(nextItem.id);\n },\n [dir, focusItem, loop, orientation],\n );\n\n return {\n activeId: resolvedActiveId,\n getItemRef,\n getItemTabIndex,\n focusItem,\n onItemFocus,\n onItemKeyDown,\n };\n};\n\nexport { useRovingFocus };\n"],"mappings":";;;AAmCA,MAAM,kBAAyC,EAC7C,OACA,cAAc,cACd,MAAM,OACN,OAAO,MACP,sBACoD;CACpD,MAAM,WAAW,uBAAO,IAAI,IAAe,CAAC;CAC5C,MAAM,eAAe,uBAAO,IAAI,IAA4B,CAAC;CAC7D,MAAM,WAAW,OAAO,KAAK;CAE7B,SAAS,UAAU;CAEnB,MAAM,CAAC,UAAU,eAAe,eAAmC;EAKjE,OAJoB,MAAM,MACvB,SAAS,KAAK,OAAO,mBAAmB,CAAC,KAAK,QAGhC,CAAC,EAAE,MAAM,MAAM,MAAM,SAAS,CAAC,KAAK,QAAQ,CAAC,EAAE;CAClE,CAAC;CAED,MAAM,mBACJ,MAAM,MAAM,SAAS,KAAK,OAAO,Y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,QAAQ,SAAS,CAAC,KAAK,QAAQ;GAErE,IAAI,aAAa,WAAW,GAC1B;GAGF,MAAM,eAAe,aAAa,WAAW,SAAS,KAAK,OAAO,EAAE;GAEpE,IAAI,iBAAiB,IACnB;GAGF,IAAI;GACJ,IAAI;GAEJ,QAAQ,MAAM,KAAd;IACE,KAAK;KACH,YAAY;KACZ;IAEF,KAAK;KACH,YAAY,aAAa,SAAS;KAClC;IAEF,KAAK;KACH,IAAI,gBAAgB,gBAAgB,gBAAgB,QAClD,YAAY,QAAQ,QAAQ,KAAK;KAEnC;IAEF,KAAK;KACH,IAAI,gBAAgB,gBAAgB,gBAAgB,QAClD,YAAY,QAAQ,QAAQ,IAAI;KAElC;IAEF,KAAK;KACH,IAAI,gBAAgB,cAAc,gBAAgB,QAChD,YAAY;KAEd;IAEF,KAAK,WACH,IAAI,gBAAgB,cAAc,gBAAgB,QAChD,YAAY;GAGlB;GAEA,IAAI,cAAc,KAAA,GAAW;IAC3B,MAAM,iBAAiB,eAAe;IAEtC,YAAY,QACP,iBAAiB,aAAa,UAAU,aAAa,SACtD,KAAK,IAAI,KAAK,IAAI,gBAAgB,CAAC,GAAG,aAAa,SAAS,CAAC;GACnE;GAEA,IAAI,cAAc,KAAA,GAChB;GAGF,MAAM,WAAW,aAAa;GAE9B,IAAI,CAAC,UACH;GAGF,MAAM,eAAe;GACrB,UAAU,SAAS,EAAE;EACvB,GACA;GAAC;GAAK;GAAW;GAAM;EAAW,CAStB;CACd;AACF"}
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@puzzle-ui/hooks",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Reusable React hooks for Puzzle",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public",
8
+ "registry": "https://registry.npmjs.org/"
9
+ },
10
+ "type": "module",
11
+ "sideEffects": false,
12
+ "main": "./dist/index.cjs",
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "import": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "require": {
22
+ "types": "./dist/index.d.cts",
23
+ "default": "./dist/index.cjs"
24
+ }
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsdown",
32
+ "clean": "rm -rf dist",
33
+ "prepack": "tsdown"
34
+ },
35
+ "dependencies": {
36
+ "@puzzle-ui/core": "^0.1.0"
37
+ },
38
+ "peerDependencies": {
39
+ "react": "^19.0.0"
40
+ },
41
+ "devDependencies": {
42
+ "@types/react": "^19.0.0",
43
+ "react": "^19.0.0",
44
+ "tsdown": "^0.23.1",
45
+ "typescript": "^6.0.3"
46
+ }
47
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.