@object-ui/react 0.5.0 → 3.0.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.
Files changed (144) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/dist/LazyPluginLoader.d.ts +44 -0
  4. package/dist/LazyPluginLoader.js +92 -3
  5. package/dist/SchemaRenderer.d.ts +20 -1
  6. package/dist/SchemaRenderer.js +76 -13
  7. package/dist/components/form/FieldFactory.js +44 -40
  8. package/dist/components/form/FormRenderer.js +45 -3
  9. package/dist/context/ActionContext.d.ts +76 -0
  10. package/dist/context/ActionContext.js +139 -0
  11. package/dist/context/DndContext.d.ts +135 -0
  12. package/dist/context/DndContext.js +120 -0
  13. package/dist/context/NotificationContext.d.ts +113 -0
  14. package/dist/context/NotificationContext.js +130 -0
  15. package/dist/context/ThemeContext.d.ts +94 -0
  16. package/dist/context/ThemeContext.js +215 -0
  17. package/dist/context/index.d.ts +4 -0
  18. package/dist/context/index.js +4 -0
  19. package/dist/hooks/index.d.ts +22 -0
  20. package/dist/hooks/index.js +22 -0
  21. package/dist/hooks/useActionRunner.d.ts +21 -7
  22. package/dist/hooks/useActionRunner.js +27 -7
  23. package/dist/hooks/useAnimation.d.ts +46 -0
  24. package/dist/hooks/useAnimation.js +59 -0
  25. package/dist/hooks/useClientNotifications.d.ts +53 -0
  26. package/dist/hooks/useClientNotifications.js +190 -0
  27. package/dist/hooks/useColumnSummary.d.ts +38 -0
  28. package/dist/hooks/useColumnSummary.js +54 -0
  29. package/dist/hooks/useCrudShortcuts.d.ts +39 -0
  30. package/dist/hooks/useCrudShortcuts.js +96 -0
  31. package/dist/hooks/useDensityMode.d.ts +48 -0
  32. package/dist/hooks/useDensityMode.js +60 -0
  33. package/dist/hooks/useDiscovery.d.ts +78 -0
  34. package/dist/hooks/useDiscovery.js +96 -0
  35. package/dist/hooks/useDynamicApp.d.ts +70 -0
  36. package/dist/hooks/useDynamicApp.js +92 -0
  37. package/dist/hooks/useETagCache.d.ts +75 -0
  38. package/dist/hooks/useETagCache.js +306 -0
  39. package/dist/hooks/useFocusManagement.d.ts +89 -0
  40. package/dist/hooks/useFocusManagement.js +188 -0
  41. package/dist/hooks/useFocusTrap.d.ts +41 -0
  42. package/dist/hooks/useFocusTrap.js +103 -0
  43. package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
  44. package/dist/hooks/useKeyboardShortcuts.js +86 -0
  45. package/dist/hooks/useNavigationOverlay.d.ts +78 -0
  46. package/dist/hooks/useNavigationOverlay.js +112 -0
  47. package/dist/hooks/useOffline.d.ts +96 -0
  48. package/dist/hooks/useOffline.js +185 -0
  49. package/dist/hooks/usePageTransition.d.ts +60 -0
  50. package/dist/hooks/usePageTransition.js +111 -0
  51. package/dist/hooks/usePageVariables.d.ts +67 -0
  52. package/dist/hooks/usePageVariables.js +109 -0
  53. package/dist/hooks/usePerformance.d.ts +87 -0
  54. package/dist/hooks/usePerformance.js +165 -0
  55. package/dist/hooks/usePerformanceBudget.d.ts +78 -0
  56. package/dist/hooks/usePerformanceBudget.js +209 -0
  57. package/dist/hooks/useReducedMotion.d.ts +28 -0
  58. package/dist/hooks/useReducedMotion.js +48 -0
  59. package/dist/hooks/useSchemaPersistence.d.ts +87 -0
  60. package/dist/hooks/useSchemaPersistence.js +173 -0
  61. package/dist/hooks/useViewData.d.ts +73 -0
  62. package/dist/hooks/useViewData.js +135 -0
  63. package/dist/hooks/useViewSharing.d.ts +57 -0
  64. package/dist/hooks/useViewSharing.js +74 -0
  65. package/dist/hooks/useViewTransition.d.ts +54 -0
  66. package/dist/hooks/useViewTransition.js +83 -0
  67. package/dist/index.d.ts +1 -0
  68. package/dist/index.js +2 -0
  69. package/dist/utils/i18n.d.ts +10 -0
  70. package/dist/utils/i18n.js +12 -0
  71. package/package.json +7 -5
  72. package/src/LazyPluginLoader.tsx +129 -7
  73. package/src/SchemaRenderer.tsx +122 -13
  74. package/src/__tests__/LazyPluginLoader.test.tsx +97 -1
  75. package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
  76. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
  77. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
  78. package/src/__tests__/ThemeProvider.test.tsx +451 -0
  79. package/src/__tests__/useNavigationOverlay.test.ts +416 -0
  80. package/src/__tests__/useOffline.test.ts +198 -0
  81. package/src/__tests__/usePageTransition.test.ts +214 -0
  82. package/src/__tests__/usePageVariables.test.tsx +334 -0
  83. package/src/__tests__/usePerformance.test.ts +137 -0
  84. package/src/__tests__/useViewData.test.tsx +422 -0
  85. package/src/__tests__/view-switching.test.tsx +456 -0
  86. package/src/components/form/FieldFactory.tsx +51 -46
  87. package/src/components/form/FormRenderer.test.tsx +145 -0
  88. package/src/components/form/FormRenderer.tsx +52 -3
  89. package/src/context/ActionContext.tsx +213 -0
  90. package/src/context/DndContext.tsx +260 -0
  91. package/src/context/NotificationContext.tsx +280 -0
  92. package/src/context/ThemeContext.tsx +325 -0
  93. package/src/context/__tests__/ActionContext.test.tsx +174 -0
  94. package/src/context/__tests__/DndContext.test.tsx +150 -0
  95. package/src/context/__tests__/NotificationContext.test.tsx +176 -0
  96. package/src/context/index.ts +4 -0
  97. package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
  98. package/src/hooks/__tests__/useAnimation.test.ts +82 -0
  99. package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
  100. package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
  101. package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
  102. package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
  103. package/src/hooks/__tests__/useETagCache.test.ts +153 -0
  104. package/src/hooks/__tests__/useExpression.test.ts +86 -0
  105. package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
  106. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
  107. package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
  108. package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
  109. package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
  110. package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
  111. package/src/hooks/index.ts +22 -1
  112. package/src/hooks/useActionRunner.ts +49 -11
  113. package/src/hooks/useAnimation.ts +117 -0
  114. package/src/hooks/useClientNotifications.ts +251 -0
  115. package/src/hooks/useColumnSummary.ts +87 -0
  116. package/src/hooks/useCrudShortcuts.ts +126 -0
  117. package/src/hooks/useDensityMode.ts +102 -0
  118. package/src/hooks/useDiscovery.ts +141 -0
  119. package/src/hooks/useDynamicApp.ts +142 -0
  120. package/src/hooks/useETagCache.ts +404 -0
  121. package/src/hooks/useFocusManagement.ts +248 -0
  122. package/src/hooks/useFocusTrap.ts +138 -0
  123. package/src/hooks/useKeyboardShortcuts.ts +119 -0
  124. package/src/hooks/useNavigationOverlay.ts +180 -0
  125. package/src/hooks/useOffline.ts +301 -0
  126. package/src/hooks/usePageTransition.ts +187 -0
  127. package/src/hooks/usePageVariables.tsx +157 -0
  128. package/src/hooks/usePerformance.ts +246 -0
  129. package/src/hooks/usePerformanceBudget.ts +313 -0
  130. package/src/hooks/useReducedMotion.ts +53 -0
  131. package/src/hooks/useSchemaPersistence.ts +222 -0
  132. package/src/hooks/useViewData.ts +201 -0
  133. package/src/hooks/useViewSharing.ts +140 -0
  134. package/src/hooks/useViewTransition.ts +144 -0
  135. package/src/index.ts +21 -0
  136. package/src/utils/i18n.ts +10 -0
  137. package/tsconfig.json +1 -0
  138. package/tsconfig.tsbuildinfo +1 -1
  139. package/dist/__tests__/LazyPluginLoader.test.d.ts +0 -8
  140. package/dist/__tests__/LazyPluginLoader.test.js +0 -49
  141. package/dist/components/form/FormRenderer.test.d.ts +0 -8
  142. package/dist/components/form/FormRenderer.test.js +0 -534
  143. package/dist/index.test.d.ts +0 -8
  144. package/dist/index.test.js +0 -13
@@ -0,0 +1,248 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { useEffect, useRef, useCallback, useState } from 'react';
10
+
11
+ // ─── useFocusReturn ────────────────────────────────────────────────────────────
12
+
13
+ export interface FocusReturnOptions {
14
+ /** Whether focus restoration is enabled. @default true */
15
+ enabled?: boolean;
16
+ /** Whether to focus the previously active element on unmount. @default true */
17
+ restoreOnUnmount?: boolean;
18
+ }
19
+
20
+ /**
21
+ * Hook that captures the currently focused element on mount and restores
22
+ * focus to it when the component unmounts. Useful for modals, drawers,
23
+ * and overlays that temporarily steal focus.
24
+ *
25
+ * @example
26
+ * ```tsx
27
+ * function Drawer({ onClose }: { onClose: () => void }) {
28
+ * const { returnFocus } = useFocusReturn();
29
+ *
30
+ * const handleClose = () => {
31
+ * returnFocus();
32
+ * onClose();
33
+ * };
34
+ *
35
+ * return <aside>...</aside>;
36
+ * }
37
+ * ```
38
+ */
39
+ export function useFocusReturn(options: FocusReturnOptions = {}): {
40
+ /** Manually restore focus to the previously focused element. */
41
+ returnFocus: () => void;
42
+ } {
43
+ const { enabled = true, restoreOnUnmount = true } = options;
44
+ const previousFocusRef = useRef<HTMLElement | null>(null);
45
+
46
+ // Capture focused element on mount
47
+ useEffect(() => {
48
+ if (!enabled) return;
49
+ previousFocusRef.current = document.activeElement as HTMLElement | null;
50
+ }, [enabled]);
51
+
52
+ const returnFocus = useCallback(() => {
53
+ if (!enabled) return;
54
+ const el = previousFocusRef.current;
55
+ if (el && typeof el.focus === 'function' && document.body.contains(el)) {
56
+ el.focus();
57
+ }
58
+ }, [enabled]);
59
+
60
+ // Restore on unmount
61
+ useEffect(() => {
62
+ if (!enabled || !restoreOnUnmount) return;
63
+ return () => {
64
+ const el = previousFocusRef.current;
65
+ if (el && typeof el.focus === 'function' && document.body.contains(el)) {
66
+ el.focus();
67
+ }
68
+ };
69
+ // Only run cleanup on unmount — intentionally stable deps
70
+ // eslint-disable-next-line react-hooks/exhaustive-deps
71
+ }, []);
72
+
73
+ return { returnFocus };
74
+ }
75
+
76
+ // ─── useRovingFocus ────────────────────────────────────────────────────────────
77
+
78
+ export type RovingOrientation = 'horizontal' | 'vertical' | 'both';
79
+
80
+ export interface RovingFocusOptions {
81
+ /** Whether roving focus is enabled. @default true */
82
+ enabled?: boolean;
83
+ /** Navigation orientation. @default 'vertical' */
84
+ orientation?: RovingOrientation;
85
+ /** Whether focus wraps from last to first item and vice-versa. @default true */
86
+ loop?: boolean;
87
+ /** Callback fired when the focused index changes. */
88
+ onFocusChange?: (index: number) => void;
89
+ }
90
+
91
+ export interface RovingFocusReturn<T extends HTMLElement> {
92
+ /** Ref to attach to the container element. */
93
+ containerRef: React.RefObject<T | null>;
94
+ /** The index of the currently focused item (-1 if none). */
95
+ focusedIndex: number;
96
+ /** Programmatically focus a specific item by index. */
97
+ setFocusedIndex: (index: number) => void;
98
+ }
99
+
100
+ /**
101
+ * Hook that implements roving tabindex / arrow-key navigation for a list of
102
+ * focusable items inside a container (sidebar items, tab lists, menu items).
103
+ *
104
+ * Only the currently active item participates in the tab order (tabindex 0);
105
+ * all other items are removed from the tab order (tabindex -1). Arrow keys
106
+ * move focus between items.
107
+ *
108
+ * @example
109
+ * ```tsx
110
+ * function SidebarNav({ items }: { items: string[] }) {
111
+ * const { containerRef, focusedIndex } = useRovingFocus<HTMLUListElement>({
112
+ * orientation: 'vertical',
113
+ * loop: true,
114
+ * });
115
+ *
116
+ * return (
117
+ * <ul ref={containerRef} role="tablist">
118
+ * {items.map((item, i) => (
119
+ * <li
120
+ * key={item}
121
+ * role="tab"
122
+ * tabIndex={i === focusedIndex ? 0 : -1}
123
+ * data-roving-item
124
+ * >
125
+ * {item}
126
+ * </li>
127
+ * ))}
128
+ * </ul>
129
+ * );
130
+ * }
131
+ * ```
132
+ */
133
+ export function useRovingFocus<T extends HTMLElement = HTMLDivElement>(
134
+ options: RovingFocusOptions = {}
135
+ ): RovingFocusReturn<T> {
136
+ const {
137
+ enabled = true,
138
+ orientation = 'vertical',
139
+ loop = true,
140
+ onFocusChange,
141
+ } = options;
142
+
143
+ const containerRef = useRef<T | null>(null);
144
+ const [focusedIndex, setFocusedIndexState] = useState(-1);
145
+ const onFocusChangeRef = useRef(onFocusChange);
146
+ useEffect(() => {
147
+ onFocusChangeRef.current = onFocusChange;
148
+ }, [onFocusChange]);
149
+
150
+ const getItems = useCallback((): HTMLElement[] => {
151
+ if (!containerRef.current) return [];
152
+ return Array.from(
153
+ containerRef.current.querySelectorAll<HTMLElement>('[data-roving-item]')
154
+ ).filter((el) => {
155
+ // Exclude hidden or disabled elements
156
+ if (el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true') {
157
+ return false;
158
+ }
159
+ return el.offsetParent !== null; // visible check
160
+ });
161
+ }, []);
162
+
163
+ const setFocusedIndex = useCallback(
164
+ (index: number) => {
165
+ const items = getItems();
166
+ if (items.length === 0) return;
167
+
168
+ const clamped = Math.max(0, Math.min(index, items.length - 1));
169
+ setFocusedIndexState(clamped);
170
+ items[clamped]?.focus();
171
+ onFocusChangeRef.current?.(clamped);
172
+ },
173
+ [getItems]
174
+ );
175
+
176
+ useEffect(() => {
177
+ if (!enabled || !containerRef.current) return;
178
+
179
+ const handleKeyDown = (event: KeyboardEvent) => {
180
+ const items = getItems();
181
+ if (items.length === 0) return;
182
+
183
+ const currentIndex = items.findIndex((el) => el === document.activeElement);
184
+ if (currentIndex === -1) return;
185
+
186
+ const prevKeys =
187
+ orientation === 'horizontal' ? ['ArrowLeft'] :
188
+ orientation === 'vertical' ? ['ArrowUp'] :
189
+ ['ArrowUp', 'ArrowLeft'];
190
+
191
+ const nextKeys =
192
+ orientation === 'horizontal' ? ['ArrowRight'] :
193
+ orientation === 'vertical' ? ['ArrowDown'] :
194
+ ['ArrowDown', 'ArrowRight'];
195
+
196
+ let nextIndex: number | null = null;
197
+
198
+ if (prevKeys.includes(event.key)) {
199
+ event.preventDefault();
200
+ if (currentIndex > 0) {
201
+ nextIndex = currentIndex - 1;
202
+ } else if (loop) {
203
+ nextIndex = items.length - 1;
204
+ }
205
+ } else if (nextKeys.includes(event.key)) {
206
+ event.preventDefault();
207
+ if (currentIndex < items.length - 1) {
208
+ nextIndex = currentIndex + 1;
209
+ } else if (loop) {
210
+ nextIndex = 0;
211
+ }
212
+ } else if (event.key === 'Home') {
213
+ event.preventDefault();
214
+ nextIndex = 0;
215
+ } else if (event.key === 'End') {
216
+ event.preventDefault();
217
+ nextIndex = items.length - 1;
218
+ }
219
+
220
+ if (nextIndex !== null) {
221
+ setFocusedIndexState(nextIndex);
222
+ items[nextIndex].focus();
223
+ onFocusChangeRef.current?.(nextIndex);
224
+ }
225
+ };
226
+
227
+ // When an item receives focus (e.g. via click), sync the index
228
+ const handleFocusIn = (event: FocusEvent) => {
229
+ const items = getItems();
230
+ const index = items.findIndex((el) => el === event.target);
231
+ if (index !== -1) {
232
+ setFocusedIndexState(index);
233
+ onFocusChangeRef.current?.(index);
234
+ }
235
+ };
236
+
237
+ const container = containerRef.current;
238
+ container.addEventListener('keydown', handleKeyDown);
239
+ container.addEventListener('focusin', handleFocusIn);
240
+
241
+ return () => {
242
+ container.removeEventListener('keydown', handleKeyDown);
243
+ container.removeEventListener('focusin', handleFocusIn);
244
+ };
245
+ }, [enabled, orientation, loop, getItems]);
246
+
247
+ return { containerRef, focusedIndex, setFocusedIndex };
248
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { useEffect, useRef, useCallback } from 'react';
10
+
11
+ export interface FocusTrapOptions {
12
+ /** Whether the focus trap is currently active */
13
+ enabled?: boolean;
14
+ /** Whether to auto-focus the first focusable element on mount */
15
+ autoFocus?: boolean;
16
+ /** Whether to restore focus to the previously focused element on unmount */
17
+ restoreFocus?: boolean;
18
+ /** Whether to release the trap on Escape key */
19
+ escapeDeactivates?: boolean;
20
+ /** Callback when Escape is pressed (if escapeDeactivates is true) */
21
+ onEscape?: () => void;
22
+ /** Initial element to focus (CSS selector) */
23
+ initialFocus?: string;
24
+ }
25
+
26
+ const FOCUSABLE_SELECTOR = [
27
+ 'a[href]',
28
+ 'button:not([disabled])',
29
+ 'input:not([disabled])',
30
+ 'select:not([disabled])',
31
+ 'textarea:not([disabled])',
32
+ '[tabindex]:not([tabindex="-1"])',
33
+ ].join(', ');
34
+
35
+ /**
36
+ * Hook that traps focus within a container element.
37
+ * Implements FocusTrapConfigSchema from @objectstack/spec v2.0.7.
38
+ *
39
+ * @example
40
+ * ```tsx
41
+ * function Modal({ onClose }: { onClose: () => void }) {
42
+ * const trapRef = useFocusTrap({
43
+ * enabled: true,
44
+ * autoFocus: true,
45
+ * restoreFocus: true,
46
+ * escapeDeactivates: true,
47
+ * onEscape: onClose,
48
+ * });
49
+ *
50
+ * return <div ref={trapRef}>...</div>;
51
+ * }
52
+ * ```
53
+ */
54
+ export function useFocusTrap<T extends HTMLElement = HTMLDivElement>(
55
+ options: FocusTrapOptions = {}
56
+ ): React.RefObject<T | null> {
57
+ const {
58
+ enabled = true,
59
+ autoFocus = true,
60
+ restoreFocus = true,
61
+ escapeDeactivates = false,
62
+ onEscape,
63
+ initialFocus,
64
+ } = options;
65
+
66
+ const containerRef = useRef<T | null>(null);
67
+ const previousFocusRef = useRef<HTMLElement | null>(null);
68
+
69
+ const getFocusableElements = useCallback(() => {
70
+ if (!containerRef.current) return [];
71
+ return Array.from(
72
+ containerRef.current.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)
73
+ ).filter((el) => !el.hasAttribute('disabled') && el.tabIndex >= 0);
74
+ }, []);
75
+
76
+ useEffect(() => {
77
+ if (!enabled || !containerRef.current) return;
78
+
79
+ // Save previously focused element
80
+ previousFocusRef.current = document.activeElement as HTMLElement;
81
+
82
+ // Auto-focus
83
+ if (autoFocus) {
84
+ const focusableElements = getFocusableElements();
85
+ if (initialFocus) {
86
+ const target = containerRef.current.querySelector<HTMLElement>(initialFocus);
87
+ if (target) {
88
+ target.focus();
89
+ } else if (focusableElements.length > 0) {
90
+ focusableElements[0].focus();
91
+ }
92
+ } else if (focusableElements.length > 0) {
93
+ focusableElements[0].focus();
94
+ }
95
+ }
96
+
97
+ const handleKeyDown = (event: KeyboardEvent) => {
98
+ if (!containerRef.current) return;
99
+
100
+ if (event.key === 'Escape' && escapeDeactivates) {
101
+ onEscape?.();
102
+ return;
103
+ }
104
+
105
+ if (event.key !== 'Tab') return;
106
+
107
+ const focusableElements = getFocusableElements();
108
+ if (focusableElements.length === 0) return;
109
+
110
+ const firstElement = focusableElements[0];
111
+ const lastElement = focusableElements[focusableElements.length - 1];
112
+
113
+ if (event.shiftKey) {
114
+ if (document.activeElement === firstElement) {
115
+ event.preventDefault();
116
+ lastElement.focus();
117
+ }
118
+ } else {
119
+ if (document.activeElement === lastElement) {
120
+ event.preventDefault();
121
+ firstElement.focus();
122
+ }
123
+ }
124
+ };
125
+
126
+ const container = containerRef.current;
127
+ container.addEventListener('keydown', handleKeyDown);
128
+
129
+ return () => {
130
+ container.removeEventListener('keydown', handleKeyDown);
131
+ if (restoreFocus && previousFocusRef.current) {
132
+ previousFocusRef.current.focus();
133
+ }
134
+ };
135
+ }, [enabled, autoFocus, restoreFocus, escapeDeactivates, onEscape, initialFocus, getFocusableElements]);
136
+
137
+ return containerRef;
138
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ import { useEffect, useRef, useCallback } from 'react';
10
+
11
+ export interface KeyboardShortcutDefinition {
12
+ /** The key to listen for (e.g., 'k', 'Enter', 'Escape') */
13
+ key: string;
14
+ /** Whether Ctrl/Cmd is required */
15
+ ctrlOrMeta?: boolean;
16
+ /** Whether Shift is required */
17
+ shift?: boolean;
18
+ /** Whether Alt is required */
19
+ alt?: boolean;
20
+ /** Handler to call when the shortcut is triggered */
21
+ handler: (event: KeyboardEvent) => void;
22
+ /** Human-readable description for the help dialog */
23
+ description?: string;
24
+ /** Whether to prevent default browser behavior */
25
+ preventDefault?: boolean;
26
+ /** Whether the shortcut is currently enabled */
27
+ enabled?: boolean;
28
+ }
29
+
30
+ /**
31
+ * Hook for registering keyboard shortcuts.
32
+ * Implements KeyboardShortcutSchema from @objectstack/spec v2.0.7.
33
+ *
34
+ * @example
35
+ * ```tsx
36
+ * useKeyboardShortcuts([
37
+ * { key: 'k', ctrlOrMeta: true, handler: () => openSearch(), description: 'Open search' },
38
+ * { key: 'n', ctrlOrMeta: true, handler: () => createNew(), description: 'Create new record' },
39
+ * { key: 'Escape', handler: () => closeModal(), description: 'Close dialog' },
40
+ * ]);
41
+ * ```
42
+ */
43
+ export function useKeyboardShortcuts(
44
+ shortcuts: KeyboardShortcutDefinition[],
45
+ options: { enabled?: boolean } = {}
46
+ ): void {
47
+ const { enabled = true } = options;
48
+ const shortcutsRef = useRef(shortcuts);
49
+ useEffect(() => {
50
+ shortcutsRef.current = shortcuts;
51
+ }, [shortcuts]);
52
+
53
+ const handleKeyDown = useCallback(
54
+ (event: KeyboardEvent) => {
55
+ // Don't trigger shortcuts when typing in form elements
56
+ const target = event.target as HTMLElement;
57
+ const isFormElement =
58
+ target.tagName === 'INPUT' ||
59
+ target.tagName === 'TEXTAREA' ||
60
+ target.tagName === 'SELECT' ||
61
+ target.isContentEditable;
62
+
63
+ for (const shortcut of shortcutsRef.current) {
64
+ if (shortcut.enabled === false) continue;
65
+
66
+ const keyMatch =
67
+ event.key.toLowerCase() === shortcut.key.toLowerCase();
68
+ const ctrlMatch = shortcut.ctrlOrMeta
69
+ ? event.ctrlKey || event.metaKey
70
+ : !event.ctrlKey && !event.metaKey;
71
+ const shiftMatch = shortcut.shift ? event.shiftKey : !event.shiftKey;
72
+ const altMatch = shortcut.alt ? event.altKey : !event.altKey;
73
+
74
+ if (keyMatch && ctrlMatch && shiftMatch && altMatch) {
75
+ // Allow shortcuts with modifiers even in form elements
76
+ if (isFormElement && !shortcut.ctrlOrMeta && !shortcut.alt) continue;
77
+
78
+ if (shortcut.preventDefault !== false) {
79
+ event.preventDefault();
80
+ }
81
+ shortcut.handler(event);
82
+ return;
83
+ }
84
+ }
85
+ },
86
+ []
87
+ );
88
+
89
+ useEffect(() => {
90
+ if (!enabled) return;
91
+
92
+ document.addEventListener('keydown', handleKeyDown);
93
+ return () => {
94
+ document.removeEventListener('keydown', handleKeyDown);
95
+ };
96
+ }, [enabled, handleKeyDown]);
97
+ }
98
+
99
+ /**
100
+ * Returns a list of all registered shortcut descriptions.
101
+ * Useful for building a help dialog (? key).
102
+ */
103
+ export function getShortcutDescriptions(
104
+ shortcuts: KeyboardShortcutDefinition[]
105
+ ): Array<{ keys: string; description: string }> {
106
+ return shortcuts
107
+ .filter((s) => s.description && s.enabled !== false)
108
+ .map((s) => {
109
+ const parts: string[] = [];
110
+ if (s.ctrlOrMeta) parts.push('⌘/Ctrl');
111
+ if (s.shift) parts.push('Shift');
112
+ if (s.alt) parts.push('Alt');
113
+ parts.push(s.key.length === 1 ? s.key.toUpperCase() : s.key);
114
+ return {
115
+ keys: parts.join(' + '),
116
+ description: s.description!,
117
+ };
118
+ });
119
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * ObjectUI
3
+ * Copyright (c) 2024-present ObjectStack Inc.
4
+ *
5
+ * This source code is licensed under the MIT license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ /**
10
+ * useNavigationOverlay
11
+ *
12
+ * A reusable hook for handling NavigationConfig-driven row/item click behavior.
13
+ * Manages overlay state (drawer/modal/split/popover) and generates click handlers
14
+ * that respect the ViewNavigationConfig specification.
15
+ *
16
+ * Used by plugin-grid, plugin-list, plugin-detail and any component that needs
17
+ * NavigationConfig support.
18
+ */
19
+
20
+ import { useState, useCallback, useMemo } from 'react';
21
+
22
+ /**
23
+ * Inline ViewNavigationConfig to avoid importing from @object-ui/types
24
+ * (which may not be a direct dependency of @object-ui/react).
25
+ * Mirrors the canonical definition in @object-ui/types/objectql.ts.
26
+ */
27
+ export interface NavigationConfig {
28
+ mode: 'page' | 'drawer' | 'modal' | 'split' | 'popover' | 'new_window' | 'none';
29
+ view?: string;
30
+ preventNavigation?: boolean;
31
+ openNewTab?: boolean;
32
+ width?: string | number;
33
+ }
34
+
35
+ export type NavigationMode = NavigationConfig['mode'];
36
+
37
+ export interface UseNavigationOverlayOptions {
38
+ /** The navigation configuration from the schema */
39
+ navigation?: NavigationConfig;
40
+ /** Object name — used to build default URLs for page/new_window modes */
41
+ objectName?: string;
42
+ /** External onNavigate callback (e.g., from ActionProvider or parent) */
43
+ onNavigate?: (recordId: string | number, action?: string) => void;
44
+ /** External onRowClick callback — if set, takes full priority */
45
+ onRowClick?: (record: Record<string, unknown>) => void;
46
+ }
47
+
48
+ export interface NavigationOverlayState {
49
+ /** Whether the overlay (drawer/modal/split/popover) is open */
50
+ isOpen: boolean;
51
+ /** The record that triggered the navigation */
52
+ selectedRecord: Record<string, unknown> | null;
53
+ /** The resolved navigation mode */
54
+ mode: NavigationMode;
55
+ /** Close the overlay */
56
+ close: () => void;
57
+ /** Open the overlay with a specific record */
58
+ open: (record: Record<string, unknown>) => void;
59
+ /** Set the open state (for controlled Sheet/Dialog `onOpenChange`) */
60
+ setIsOpen: (open: boolean) => void;
61
+ /** The click handler to attach to rows/items */
62
+ handleClick: (record: Record<string, unknown>) => void;
63
+ /** The width from NavigationConfig (for drawer/modal/split sizing) */
64
+ width: string | number | undefined;
65
+ /** Whether navigation is an overlay mode (drawer/modal/split/popover) */
66
+ isOverlay: boolean;
67
+ }
68
+
69
+ /**
70
+ * Hook for NavigationConfig-driven navigation overlay.
71
+ *
72
+ * @example
73
+ * ```tsx
74
+ * const { handleClick, isOpen, selectedRecord, mode, close, width } =
75
+ * useNavigationOverlay({
76
+ * navigation: schema.navigation,
77
+ * objectName: schema.objectName,
78
+ * onNavigate: schema.onNavigate,
79
+ * onRowClick: props.onRowClick,
80
+ * });
81
+ *
82
+ * return (
83
+ * <>
84
+ * <DataTable onRowClick={handleClick} ... />
85
+ * {isOpen && mode === 'drawer' && (
86
+ * <Sheet open onOpenChange={() => close()}>
87
+ * <SheetContent style={{ maxWidth: width }}>
88
+ * <RecordDetail record={selectedRecord} />
89
+ * </SheetContent>
90
+ * </Sheet>
91
+ * )}
92
+ * </>
93
+ * );
94
+ * ```
95
+ */
96
+ export function useNavigationOverlay(
97
+ options: UseNavigationOverlayOptions
98
+ ): NavigationOverlayState {
99
+ const { navigation, objectName, onNavigate, onRowClick } = options;
100
+ const [isOpen, setIsOpen] = useState(false);
101
+ const [selectedRecord, setSelectedRecord] = useState<Record<string, unknown> | null>(null);
102
+
103
+ const mode: NavigationMode = navigation?.mode ?? 'page';
104
+ const width = navigation?.width;
105
+ const isOverlay = mode === 'drawer' || mode === 'modal' || mode === 'split' || mode === 'popover';
106
+
107
+ const close = useCallback(() => {
108
+ setIsOpen(false);
109
+ setSelectedRecord(null);
110
+ }, []);
111
+
112
+ const open = useCallback((record: Record<string, unknown>) => {
113
+ setSelectedRecord(record);
114
+ setIsOpen(true);
115
+ }, []);
116
+
117
+ const handleClick = useCallback(
118
+ (record: Record<string, unknown>) => {
119
+ // External onRowClick takes full priority
120
+ if (onRowClick) {
121
+ onRowClick(record);
122
+ return;
123
+ }
124
+
125
+ // No navigation config — default to page navigation
126
+ if (!navigation) {
127
+ const recordId = record._id || record.id;
128
+ if (onNavigate && recordId != null) {
129
+ onNavigate(recordId as string | number, 'view');
130
+ }
131
+ return;
132
+ }
133
+
134
+ // 'none' or preventNavigation — do nothing
135
+ if (mode === 'none' || navigation.preventNavigation) {
136
+ return;
137
+ }
138
+
139
+ // new_window / openNewTab — open in new browser tab
140
+ if (mode === 'new_window' || navigation.openNewTab) {
141
+ const recordId = record._id || record.id;
142
+ const url = objectName ? `/${objectName}/${recordId}` : `/${recordId}`;
143
+ window.open(url, '_blank');
144
+ return;
145
+ }
146
+
147
+ // page — delegate to onNavigate callback
148
+ if (mode === 'page') {
149
+ const recordId = record._id || record.id;
150
+ if (onNavigate && recordId != null) {
151
+ onNavigate(recordId as string | number, 'view');
152
+ }
153
+ return;
154
+ }
155
+
156
+ // Overlay modes: drawer, modal, split, popover
157
+ if (isOverlay) {
158
+ setSelectedRecord(record);
159
+ setIsOpen(true);
160
+ return;
161
+ }
162
+ },
163
+ [onRowClick, navigation, mode, objectName, onNavigate, isOverlay]
164
+ );
165
+
166
+ return useMemo(
167
+ () => ({
168
+ isOpen,
169
+ selectedRecord,
170
+ mode,
171
+ close,
172
+ open,
173
+ setIsOpen,
174
+ handleClick,
175
+ width,
176
+ isOverlay,
177
+ }),
178
+ [isOpen, selectedRecord, mode, close, open, handleClick, width, isOverlay]
179
+ );
180
+ }