@object-ui/react 2.0.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 (89) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/dist/SchemaRenderer.d.ts +20 -1
  4. package/dist/SchemaRenderer.js +76 -13
  5. package/dist/context/DndContext.d.ts +135 -0
  6. package/dist/context/DndContext.js +120 -0
  7. package/dist/context/NotificationContext.d.ts +113 -0
  8. package/dist/context/NotificationContext.js +130 -0
  9. package/dist/context/index.d.ts +2 -0
  10. package/dist/context/index.js +2 -0
  11. package/dist/hooks/index.d.ts +17 -0
  12. package/dist/hooks/index.js +17 -0
  13. package/dist/hooks/useAnimation.d.ts +46 -0
  14. package/dist/hooks/useAnimation.js +59 -0
  15. package/dist/hooks/useClientNotifications.d.ts +53 -0
  16. package/dist/hooks/useClientNotifications.js +190 -0
  17. package/dist/hooks/useColumnSummary.d.ts +38 -0
  18. package/dist/hooks/useColumnSummary.js +54 -0
  19. package/dist/hooks/useCrudShortcuts.d.ts +39 -0
  20. package/dist/hooks/useCrudShortcuts.js +96 -0
  21. package/dist/hooks/useDensityMode.d.ts +48 -0
  22. package/dist/hooks/useDensityMode.js +60 -0
  23. package/dist/hooks/useETagCache.d.ts +75 -0
  24. package/dist/hooks/useETagCache.js +306 -0
  25. package/dist/hooks/useFocusManagement.d.ts +89 -0
  26. package/dist/hooks/useFocusManagement.js +188 -0
  27. package/dist/hooks/useFocusTrap.d.ts +41 -0
  28. package/dist/hooks/useFocusTrap.js +103 -0
  29. package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
  30. package/dist/hooks/useKeyboardShortcuts.js +86 -0
  31. package/dist/hooks/useOffline.d.ts +96 -0
  32. package/dist/hooks/useOffline.js +185 -0
  33. package/dist/hooks/usePageTransition.d.ts +60 -0
  34. package/dist/hooks/usePageTransition.js +111 -0
  35. package/dist/hooks/usePerformance.d.ts +87 -0
  36. package/dist/hooks/usePerformance.js +165 -0
  37. package/dist/hooks/usePerformanceBudget.d.ts +78 -0
  38. package/dist/hooks/usePerformanceBudget.js +209 -0
  39. package/dist/hooks/useReducedMotion.d.ts +28 -0
  40. package/dist/hooks/useReducedMotion.js +48 -0
  41. package/dist/hooks/useSchemaPersistence.d.ts +87 -0
  42. package/dist/hooks/useSchemaPersistence.js +173 -0
  43. package/dist/hooks/useViewSharing.d.ts +57 -0
  44. package/dist/hooks/useViewSharing.js +74 -0
  45. package/dist/hooks/useViewTransition.d.ts +54 -0
  46. package/dist/hooks/useViewTransition.js +83 -0
  47. package/package.json +7 -7
  48. package/src/SchemaRenderer.tsx +122 -13
  49. package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
  50. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
  51. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
  52. package/src/__tests__/useOffline.test.ts +198 -0
  53. package/src/__tests__/usePageTransition.test.ts +214 -0
  54. package/src/__tests__/usePerformance.test.ts +137 -0
  55. package/src/__tests__/view-switching.test.tsx +456 -0
  56. package/src/context/DndContext.tsx +260 -0
  57. package/src/context/NotificationContext.tsx +280 -0
  58. package/src/context/__tests__/DndContext.test.tsx +150 -0
  59. package/src/context/__tests__/NotificationContext.test.tsx +176 -0
  60. package/src/context/index.ts +2 -0
  61. package/src/hooks/__tests__/useAnimation.test.ts +82 -0
  62. package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
  63. package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
  64. package/src/hooks/__tests__/useETagCache.test.ts +153 -0
  65. package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
  66. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
  67. package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
  68. package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
  69. package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
  70. package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
  71. package/src/hooks/index.ts +17 -1
  72. package/src/hooks/useAnimation.ts +117 -0
  73. package/src/hooks/useClientNotifications.ts +251 -0
  74. package/src/hooks/useColumnSummary.ts +87 -0
  75. package/src/hooks/useCrudShortcuts.ts +126 -0
  76. package/src/hooks/useDensityMode.ts +102 -0
  77. package/src/hooks/useETagCache.ts +404 -0
  78. package/src/hooks/useFocusManagement.ts +248 -0
  79. package/src/hooks/useFocusTrap.ts +138 -0
  80. package/src/hooks/useKeyboardShortcuts.ts +119 -0
  81. package/src/hooks/useOffline.ts +301 -0
  82. package/src/hooks/usePageTransition.ts +187 -0
  83. package/src/hooks/usePerformance.ts +246 -0
  84. package/src/hooks/usePerformanceBudget.ts +313 -0
  85. package/src/hooks/useReducedMotion.ts +53 -0
  86. package/src/hooks/useSchemaPersistence.ts +222 -0
  87. package/src/hooks/useViewSharing.ts +140 -0
  88. package/src/hooks/useViewTransition.ts +144 -0
  89. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,188 @@
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
+ import { useEffect, useRef, useCallback, useState } from 'react';
9
+ /**
10
+ * Hook that captures the currently focused element on mount and restores
11
+ * focus to it when the component unmounts. Useful for modals, drawers,
12
+ * and overlays that temporarily steal focus.
13
+ *
14
+ * @example
15
+ * ```tsx
16
+ * function Drawer({ onClose }: { onClose: () => void }) {
17
+ * const { returnFocus } = useFocusReturn();
18
+ *
19
+ * const handleClose = () => {
20
+ * returnFocus();
21
+ * onClose();
22
+ * };
23
+ *
24
+ * return <aside>...</aside>;
25
+ * }
26
+ * ```
27
+ */
28
+ export function useFocusReturn(options = {}) {
29
+ const { enabled = true, restoreOnUnmount = true } = options;
30
+ const previousFocusRef = useRef(null);
31
+ // Capture focused element on mount
32
+ useEffect(() => {
33
+ if (!enabled)
34
+ return;
35
+ previousFocusRef.current = document.activeElement;
36
+ }, [enabled]);
37
+ const returnFocus = useCallback(() => {
38
+ if (!enabled)
39
+ return;
40
+ const el = previousFocusRef.current;
41
+ if (el && typeof el.focus === 'function' && document.body.contains(el)) {
42
+ el.focus();
43
+ }
44
+ }, [enabled]);
45
+ // Restore on unmount
46
+ useEffect(() => {
47
+ if (!enabled || !restoreOnUnmount)
48
+ return;
49
+ return () => {
50
+ const el = previousFocusRef.current;
51
+ if (el && typeof el.focus === 'function' && document.body.contains(el)) {
52
+ el.focus();
53
+ }
54
+ };
55
+ // Only run cleanup on unmount — intentionally stable deps
56
+ // eslint-disable-next-line react-hooks/exhaustive-deps
57
+ }, []);
58
+ return { returnFocus };
59
+ }
60
+ /**
61
+ * Hook that implements roving tabindex / arrow-key navigation for a list of
62
+ * focusable items inside a container (sidebar items, tab lists, menu items).
63
+ *
64
+ * Only the currently active item participates in the tab order (tabindex 0);
65
+ * all other items are removed from the tab order (tabindex -1). Arrow keys
66
+ * move focus between items.
67
+ *
68
+ * @example
69
+ * ```tsx
70
+ * function SidebarNav({ items }: { items: string[] }) {
71
+ * const { containerRef, focusedIndex } = useRovingFocus<HTMLUListElement>({
72
+ * orientation: 'vertical',
73
+ * loop: true,
74
+ * });
75
+ *
76
+ * return (
77
+ * <ul ref={containerRef} role="tablist">
78
+ * {items.map((item, i) => (
79
+ * <li
80
+ * key={item}
81
+ * role="tab"
82
+ * tabIndex={i === focusedIndex ? 0 : -1}
83
+ * data-roving-item
84
+ * >
85
+ * {item}
86
+ * </li>
87
+ * ))}
88
+ * </ul>
89
+ * );
90
+ * }
91
+ * ```
92
+ */
93
+ export function useRovingFocus(options = {}) {
94
+ const { enabled = true, orientation = 'vertical', loop = true, onFocusChange, } = options;
95
+ const containerRef = useRef(null);
96
+ const [focusedIndex, setFocusedIndexState] = useState(-1);
97
+ const onFocusChangeRef = useRef(onFocusChange);
98
+ useEffect(() => {
99
+ onFocusChangeRef.current = onFocusChange;
100
+ }, [onFocusChange]);
101
+ const getItems = useCallback(() => {
102
+ if (!containerRef.current)
103
+ return [];
104
+ return Array.from(containerRef.current.querySelectorAll('[data-roving-item]')).filter((el) => {
105
+ // Exclude hidden or disabled elements
106
+ if (el.hasAttribute('disabled') || el.getAttribute('aria-disabled') === 'true') {
107
+ return false;
108
+ }
109
+ return el.offsetParent !== null; // visible check
110
+ });
111
+ }, []);
112
+ const setFocusedIndex = useCallback((index) => {
113
+ const items = getItems();
114
+ if (items.length === 0)
115
+ return;
116
+ const clamped = Math.max(0, Math.min(index, items.length - 1));
117
+ setFocusedIndexState(clamped);
118
+ items[clamped]?.focus();
119
+ onFocusChangeRef.current?.(clamped);
120
+ }, [getItems]);
121
+ useEffect(() => {
122
+ if (!enabled || !containerRef.current)
123
+ return;
124
+ const handleKeyDown = (event) => {
125
+ const items = getItems();
126
+ if (items.length === 0)
127
+ return;
128
+ const currentIndex = items.findIndex((el) => el === document.activeElement);
129
+ if (currentIndex === -1)
130
+ return;
131
+ const prevKeys = orientation === 'horizontal' ? ['ArrowLeft'] :
132
+ orientation === 'vertical' ? ['ArrowUp'] :
133
+ ['ArrowUp', 'ArrowLeft'];
134
+ const nextKeys = orientation === 'horizontal' ? ['ArrowRight'] :
135
+ orientation === 'vertical' ? ['ArrowDown'] :
136
+ ['ArrowDown', 'ArrowRight'];
137
+ let nextIndex = null;
138
+ if (prevKeys.includes(event.key)) {
139
+ event.preventDefault();
140
+ if (currentIndex > 0) {
141
+ nextIndex = currentIndex - 1;
142
+ }
143
+ else if (loop) {
144
+ nextIndex = items.length - 1;
145
+ }
146
+ }
147
+ else if (nextKeys.includes(event.key)) {
148
+ event.preventDefault();
149
+ if (currentIndex < items.length - 1) {
150
+ nextIndex = currentIndex + 1;
151
+ }
152
+ else if (loop) {
153
+ nextIndex = 0;
154
+ }
155
+ }
156
+ else if (event.key === 'Home') {
157
+ event.preventDefault();
158
+ nextIndex = 0;
159
+ }
160
+ else if (event.key === 'End') {
161
+ event.preventDefault();
162
+ nextIndex = items.length - 1;
163
+ }
164
+ if (nextIndex !== null) {
165
+ setFocusedIndexState(nextIndex);
166
+ items[nextIndex].focus();
167
+ onFocusChangeRef.current?.(nextIndex);
168
+ }
169
+ };
170
+ // When an item receives focus (e.g. via click), sync the index
171
+ const handleFocusIn = (event) => {
172
+ const items = getItems();
173
+ const index = items.findIndex((el) => el === event.target);
174
+ if (index !== -1) {
175
+ setFocusedIndexState(index);
176
+ onFocusChangeRef.current?.(index);
177
+ }
178
+ };
179
+ const container = containerRef.current;
180
+ container.addEventListener('keydown', handleKeyDown);
181
+ container.addEventListener('focusin', handleFocusIn);
182
+ return () => {
183
+ container.removeEventListener('keydown', handleKeyDown);
184
+ container.removeEventListener('focusin', handleFocusIn);
185
+ };
186
+ }, [enabled, orientation, loop, getItems]);
187
+ return { containerRef, focusedIndex, setFocusedIndex };
188
+ }
@@ -0,0 +1,41 @@
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
+ export interface FocusTrapOptions {
9
+ /** Whether the focus trap is currently active */
10
+ enabled?: boolean;
11
+ /** Whether to auto-focus the first focusable element on mount */
12
+ autoFocus?: boolean;
13
+ /** Whether to restore focus to the previously focused element on unmount */
14
+ restoreFocus?: boolean;
15
+ /** Whether to release the trap on Escape key */
16
+ escapeDeactivates?: boolean;
17
+ /** Callback when Escape is pressed (if escapeDeactivates is true) */
18
+ onEscape?: () => void;
19
+ /** Initial element to focus (CSS selector) */
20
+ initialFocus?: string;
21
+ }
22
+ /**
23
+ * Hook that traps focus within a container element.
24
+ * Implements FocusTrapConfigSchema from @objectstack/spec v2.0.7.
25
+ *
26
+ * @example
27
+ * ```tsx
28
+ * function Modal({ onClose }: { onClose: () => void }) {
29
+ * const trapRef = useFocusTrap({
30
+ * enabled: true,
31
+ * autoFocus: true,
32
+ * restoreFocus: true,
33
+ * escapeDeactivates: true,
34
+ * onEscape: onClose,
35
+ * });
36
+ *
37
+ * return <div ref={trapRef}>...</div>;
38
+ * }
39
+ * ```
40
+ */
41
+ export declare function useFocusTrap<T extends HTMLElement = HTMLDivElement>(options?: FocusTrapOptions): React.RefObject<T | null>;
@@ -0,0 +1,103 @@
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
+ import { useEffect, useRef, useCallback } from 'react';
9
+ const FOCUSABLE_SELECTOR = [
10
+ 'a[href]',
11
+ 'button:not([disabled])',
12
+ 'input:not([disabled])',
13
+ 'select:not([disabled])',
14
+ 'textarea:not([disabled])',
15
+ '[tabindex]:not([tabindex="-1"])',
16
+ ].join(', ');
17
+ /**
18
+ * Hook that traps focus within a container element.
19
+ * Implements FocusTrapConfigSchema from @objectstack/spec v2.0.7.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * function Modal({ onClose }: { onClose: () => void }) {
24
+ * const trapRef = useFocusTrap({
25
+ * enabled: true,
26
+ * autoFocus: true,
27
+ * restoreFocus: true,
28
+ * escapeDeactivates: true,
29
+ * onEscape: onClose,
30
+ * });
31
+ *
32
+ * return <div ref={trapRef}>...</div>;
33
+ * }
34
+ * ```
35
+ */
36
+ export function useFocusTrap(options = {}) {
37
+ const { enabled = true, autoFocus = true, restoreFocus = true, escapeDeactivates = false, onEscape, initialFocus, } = options;
38
+ const containerRef = useRef(null);
39
+ const previousFocusRef = useRef(null);
40
+ const getFocusableElements = useCallback(() => {
41
+ if (!containerRef.current)
42
+ return [];
43
+ return Array.from(containerRef.current.querySelectorAll(FOCUSABLE_SELECTOR)).filter((el) => !el.hasAttribute('disabled') && el.tabIndex >= 0);
44
+ }, []);
45
+ useEffect(() => {
46
+ if (!enabled || !containerRef.current)
47
+ return;
48
+ // Save previously focused element
49
+ previousFocusRef.current = document.activeElement;
50
+ // Auto-focus
51
+ if (autoFocus) {
52
+ const focusableElements = getFocusableElements();
53
+ if (initialFocus) {
54
+ const target = containerRef.current.querySelector(initialFocus);
55
+ if (target) {
56
+ target.focus();
57
+ }
58
+ else if (focusableElements.length > 0) {
59
+ focusableElements[0].focus();
60
+ }
61
+ }
62
+ else if (focusableElements.length > 0) {
63
+ focusableElements[0].focus();
64
+ }
65
+ }
66
+ const handleKeyDown = (event) => {
67
+ if (!containerRef.current)
68
+ return;
69
+ if (event.key === 'Escape' && escapeDeactivates) {
70
+ onEscape?.();
71
+ return;
72
+ }
73
+ if (event.key !== 'Tab')
74
+ return;
75
+ const focusableElements = getFocusableElements();
76
+ if (focusableElements.length === 0)
77
+ return;
78
+ const firstElement = focusableElements[0];
79
+ const lastElement = focusableElements[focusableElements.length - 1];
80
+ if (event.shiftKey) {
81
+ if (document.activeElement === firstElement) {
82
+ event.preventDefault();
83
+ lastElement.focus();
84
+ }
85
+ }
86
+ else {
87
+ if (document.activeElement === lastElement) {
88
+ event.preventDefault();
89
+ firstElement.focus();
90
+ }
91
+ }
92
+ };
93
+ const container = containerRef.current;
94
+ container.addEventListener('keydown', handleKeyDown);
95
+ return () => {
96
+ container.removeEventListener('keydown', handleKeyDown);
97
+ if (restoreFocus && previousFocusRef.current) {
98
+ previousFocusRef.current.focus();
99
+ }
100
+ };
101
+ }, [enabled, autoFocus, restoreFocus, escapeDeactivates, onEscape, initialFocus, getFocusableElements]);
102
+ return containerRef;
103
+ }
@@ -0,0 +1,49 @@
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
+ export interface KeyboardShortcutDefinition {
9
+ /** The key to listen for (e.g., 'k', 'Enter', 'Escape') */
10
+ key: string;
11
+ /** Whether Ctrl/Cmd is required */
12
+ ctrlOrMeta?: boolean;
13
+ /** Whether Shift is required */
14
+ shift?: boolean;
15
+ /** Whether Alt is required */
16
+ alt?: boolean;
17
+ /** Handler to call when the shortcut is triggered */
18
+ handler: (event: KeyboardEvent) => void;
19
+ /** Human-readable description for the help dialog */
20
+ description?: string;
21
+ /** Whether to prevent default browser behavior */
22
+ preventDefault?: boolean;
23
+ /** Whether the shortcut is currently enabled */
24
+ enabled?: boolean;
25
+ }
26
+ /**
27
+ * Hook for registering keyboard shortcuts.
28
+ * Implements KeyboardShortcutSchema from @objectstack/spec v2.0.7.
29
+ *
30
+ * @example
31
+ * ```tsx
32
+ * useKeyboardShortcuts([
33
+ * { key: 'k', ctrlOrMeta: true, handler: () => openSearch(), description: 'Open search' },
34
+ * { key: 'n', ctrlOrMeta: true, handler: () => createNew(), description: 'Create new record' },
35
+ * { key: 'Escape', handler: () => closeModal(), description: 'Close dialog' },
36
+ * ]);
37
+ * ```
38
+ */
39
+ export declare function useKeyboardShortcuts(shortcuts: KeyboardShortcutDefinition[], options?: {
40
+ enabled?: boolean;
41
+ }): void;
42
+ /**
43
+ * Returns a list of all registered shortcut descriptions.
44
+ * Useful for building a help dialog (? key).
45
+ */
46
+ export declare function getShortcutDescriptions(shortcuts: KeyboardShortcutDefinition[]): Array<{
47
+ keys: string;
48
+ description: string;
49
+ }>;
@@ -0,0 +1,86 @@
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
+ import { useEffect, useRef, useCallback } from 'react';
9
+ /**
10
+ * Hook for registering keyboard shortcuts.
11
+ * Implements KeyboardShortcutSchema from @objectstack/spec v2.0.7.
12
+ *
13
+ * @example
14
+ * ```tsx
15
+ * useKeyboardShortcuts([
16
+ * { key: 'k', ctrlOrMeta: true, handler: () => openSearch(), description: 'Open search' },
17
+ * { key: 'n', ctrlOrMeta: true, handler: () => createNew(), description: 'Create new record' },
18
+ * { key: 'Escape', handler: () => closeModal(), description: 'Close dialog' },
19
+ * ]);
20
+ * ```
21
+ */
22
+ export function useKeyboardShortcuts(shortcuts, options = {}) {
23
+ const { enabled = true } = options;
24
+ const shortcutsRef = useRef(shortcuts);
25
+ useEffect(() => {
26
+ shortcutsRef.current = shortcuts;
27
+ }, [shortcuts]);
28
+ const handleKeyDown = useCallback((event) => {
29
+ // Don't trigger shortcuts when typing in form elements
30
+ const target = event.target;
31
+ const isFormElement = target.tagName === 'INPUT' ||
32
+ target.tagName === 'TEXTAREA' ||
33
+ target.tagName === 'SELECT' ||
34
+ target.isContentEditable;
35
+ for (const shortcut of shortcutsRef.current) {
36
+ if (shortcut.enabled === false)
37
+ continue;
38
+ const keyMatch = event.key.toLowerCase() === shortcut.key.toLowerCase();
39
+ const ctrlMatch = shortcut.ctrlOrMeta
40
+ ? event.ctrlKey || event.metaKey
41
+ : !event.ctrlKey && !event.metaKey;
42
+ const shiftMatch = shortcut.shift ? event.shiftKey : !event.shiftKey;
43
+ const altMatch = shortcut.alt ? event.altKey : !event.altKey;
44
+ if (keyMatch && ctrlMatch && shiftMatch && altMatch) {
45
+ // Allow shortcuts with modifiers even in form elements
46
+ if (isFormElement && !shortcut.ctrlOrMeta && !shortcut.alt)
47
+ continue;
48
+ if (shortcut.preventDefault !== false) {
49
+ event.preventDefault();
50
+ }
51
+ shortcut.handler(event);
52
+ return;
53
+ }
54
+ }
55
+ }, []);
56
+ useEffect(() => {
57
+ if (!enabled)
58
+ return;
59
+ document.addEventListener('keydown', handleKeyDown);
60
+ return () => {
61
+ document.removeEventListener('keydown', handleKeyDown);
62
+ };
63
+ }, [enabled, handleKeyDown]);
64
+ }
65
+ /**
66
+ * Returns a list of all registered shortcut descriptions.
67
+ * Useful for building a help dialog (? key).
68
+ */
69
+ export function getShortcutDescriptions(shortcuts) {
70
+ return shortcuts
71
+ .filter((s) => s.description && s.enabled !== false)
72
+ .map((s) => {
73
+ const parts = [];
74
+ if (s.ctrlOrMeta)
75
+ parts.push('⌘/Ctrl');
76
+ if (s.shift)
77
+ parts.push('Shift');
78
+ if (s.alt)
79
+ parts.push('Alt');
80
+ parts.push(s.key.length === 1 ? s.key.toUpperCase() : s.key);
81
+ return {
82
+ keys: parts.join(' + '),
83
+ description: s.description,
84
+ };
85
+ });
86
+ }
@@ -0,0 +1,96 @@
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
+ /** Offline strategy determines how data is fetched when connectivity is limited. */
9
+ export type OfflineStrategy = 'cache_first' | 'network_first' | 'stale_while_revalidate' | 'network_only' | 'cache_only';
10
+ /** Conflict resolution strategy for sync operations. */
11
+ export type ConflictResolutionStrategy = 'manual' | 'client_wins' | 'server_wins' | 'last_write_wins';
12
+ /** Persist storage backend. */
13
+ export type PersistStorageType = 'indexeddb' | 'localstorage' | 'sqlite';
14
+ /** Eviction policy for cache management. */
15
+ export type EvictionPolicyType = 'lru' | 'lfu' | 'fifo';
16
+ /** Sync state of the offline system. */
17
+ export type SyncState = 'idle' | 'syncing' | 'error' | 'offline';
18
+ /** A queued mutation waiting to be synced. */
19
+ export interface QueuedMutation {
20
+ id: string;
21
+ timestamp: number;
22
+ operation: 'create' | 'update' | 'delete';
23
+ resource: string;
24
+ data?: Record<string, unknown>;
25
+ }
26
+ /** Cache configuration aligned with OfflineCacheConfigSchema. */
27
+ export interface OfflineCacheConfig {
28
+ maxSize?: number;
29
+ ttl?: number;
30
+ persistStorage?: PersistStorageType;
31
+ evictionPolicy?: EvictionPolicyType;
32
+ }
33
+ /** Sync configuration aligned with SyncConfigSchema. */
34
+ export interface OfflineSyncConfig {
35
+ strategy?: OfflineStrategy;
36
+ conflictResolution?: ConflictResolutionStrategy;
37
+ retryInterval?: number;
38
+ maxRetries?: number;
39
+ batchSize?: number;
40
+ }
41
+ /** Top-level offline configuration aligned with OfflineConfigSchema. */
42
+ export interface OfflineConfig {
43
+ enabled?: boolean;
44
+ strategy?: OfflineStrategy;
45
+ cache?: OfflineCacheConfig;
46
+ sync?: OfflineSyncConfig;
47
+ offlineIndicator?: boolean;
48
+ offlineMessage?: string;
49
+ queueMaxSize?: number;
50
+ }
51
+ /** Result returned by the useOffline hook. */
52
+ export interface OfflineResult {
53
+ /** Whether the browser is currently online. */
54
+ isOnline: boolean;
55
+ /** Whether offline mode is enabled in config. */
56
+ enabled: boolean;
57
+ /** Current sync state. */
58
+ syncState: SyncState;
59
+ /** The active offline strategy. */
60
+ strategy: OfflineStrategy;
61
+ /** Number of pending mutations in the queue. */
62
+ pendingCount: number;
63
+ /** Queue a mutation for later sync. */
64
+ queueMutation: (mutation: Omit<QueuedMutation, 'id' | 'timestamp'>) => void;
65
+ /** Manually trigger a sync attempt. */
66
+ sync: () => Promise<void>;
67
+ /** Clear the mutation queue. */
68
+ clearQueue: () => void;
69
+ /** Whether to show the offline indicator UI. */
70
+ showIndicator: boolean;
71
+ /** The offline message to display. */
72
+ offlineMessage: string;
73
+ }
74
+ /**
75
+ * Hook for offline mode detection and sync queue management.
76
+ * Implements OfflineConfigSchema, SyncConfigSchema, and ConflictResolutionSchema
77
+ * from @objectstack/spec v2.0.7.
78
+ *
79
+ * @example
80
+ * ```tsx
81
+ * function App() {
82
+ * const offline = useOffline({
83
+ * enabled: true,
84
+ * strategy: 'cache_first',
85
+ * sync: { conflictResolution: 'last_write_wins' },
86
+ * });
87
+ *
88
+ * if (!offline.isOnline && offline.showIndicator) {
89
+ * return <Banner>{offline.offlineMessage}</Banner>;
90
+ * }
91
+ *
92
+ * return <div>Pending mutations: {offline.pendingCount}</div>;
93
+ * }
94
+ * ```
95
+ */
96
+ export declare function useOffline(config?: OfflineConfig): OfflineResult;