@object-ui/react 2.0.0 → 3.0.1

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 +28 -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,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,301 @@
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 { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Types aligned with @objectstack/spec v2.0.7 OfflineConfigSchema
13
+ // ---------------------------------------------------------------------------
14
+
15
+ /** Offline strategy determines how data is fetched when connectivity is limited. */
16
+ export type OfflineStrategy =
17
+ | 'cache_first'
18
+ | 'network_first'
19
+ | 'stale_while_revalidate'
20
+ | 'network_only'
21
+ | 'cache_only';
22
+
23
+ /** Conflict resolution strategy for sync operations. */
24
+ export type ConflictResolutionStrategy =
25
+ | 'manual'
26
+ | 'client_wins'
27
+ | 'server_wins'
28
+ | 'last_write_wins';
29
+
30
+ /** Persist storage backend. */
31
+ export type PersistStorageType = 'indexeddb' | 'localstorage' | 'sqlite';
32
+
33
+ /** Eviction policy for cache management. */
34
+ export type EvictionPolicyType = 'lru' | 'lfu' | 'fifo';
35
+
36
+ /** Sync state of the offline system. */
37
+ export type SyncState = 'idle' | 'syncing' | 'error' | 'offline';
38
+
39
+ /** A queued mutation waiting to be synced. */
40
+ export interface QueuedMutation {
41
+ id: string;
42
+ timestamp: number;
43
+ operation: 'create' | 'update' | 'delete';
44
+ resource: string;
45
+ data?: Record<string, unknown>;
46
+ }
47
+
48
+ /** Cache configuration aligned with OfflineCacheConfigSchema. */
49
+ export interface OfflineCacheConfig {
50
+ maxSize?: number;
51
+ ttl?: number;
52
+ persistStorage?: PersistStorageType;
53
+ evictionPolicy?: EvictionPolicyType;
54
+ }
55
+
56
+ /** Sync configuration aligned with SyncConfigSchema. */
57
+ export interface OfflineSyncConfig {
58
+ strategy?: OfflineStrategy;
59
+ conflictResolution?: ConflictResolutionStrategy;
60
+ retryInterval?: number;
61
+ maxRetries?: number;
62
+ batchSize?: number;
63
+ }
64
+
65
+ /** Top-level offline configuration aligned with OfflineConfigSchema. */
66
+ export interface OfflineConfig {
67
+ enabled?: boolean;
68
+ strategy?: OfflineStrategy;
69
+ cache?: OfflineCacheConfig;
70
+ sync?: OfflineSyncConfig;
71
+ offlineIndicator?: boolean;
72
+ offlineMessage?: string;
73
+ queueMaxSize?: number;
74
+ }
75
+
76
+ /** Result returned by the useOffline hook. */
77
+ export interface OfflineResult {
78
+ /** Whether the browser is currently online. */
79
+ isOnline: boolean;
80
+ /** Whether offline mode is enabled in config. */
81
+ enabled: boolean;
82
+ /** Current sync state. */
83
+ syncState: SyncState;
84
+ /** The active offline strategy. */
85
+ strategy: OfflineStrategy;
86
+ /** Number of pending mutations in the queue. */
87
+ pendingCount: number;
88
+ /** Queue a mutation for later sync. */
89
+ queueMutation: (mutation: Omit<QueuedMutation, 'id' | 'timestamp'>) => void;
90
+ /** Manually trigger a sync attempt. */
91
+ sync: () => Promise<void>;
92
+ /** Clear the mutation queue. */
93
+ clearQueue: () => void;
94
+ /** Whether to show the offline indicator UI. */
95
+ showIndicator: boolean;
96
+ /** The offline message to display. */
97
+ offlineMessage: string;
98
+ }
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // Online/offline external store (SSR-safe)
102
+ // ---------------------------------------------------------------------------
103
+
104
+ function subscribeOnline(callback: () => void) {
105
+ if (typeof window === 'undefined') return () => {};
106
+ window.addEventListener('online', callback);
107
+ window.addEventListener('offline', callback);
108
+ return () => {
109
+ window.removeEventListener('online', callback);
110
+ window.removeEventListener('offline', callback);
111
+ };
112
+ }
113
+
114
+ function getOnlineSnapshot(): boolean {
115
+ return typeof navigator !== 'undefined' ? navigator.onLine : true;
116
+ }
117
+
118
+ function getServerSnapshot(): boolean {
119
+ return true;
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Mutation queue storage helpers
124
+ // ---------------------------------------------------------------------------
125
+
126
+ const QUEUE_STORAGE_KEY = 'objectui-offline-queue';
127
+
128
+ function loadQueue(): QueuedMutation[] {
129
+ if (typeof localStorage === 'undefined') return [];
130
+ try {
131
+ const raw = localStorage.getItem(QUEUE_STORAGE_KEY);
132
+ return raw ? (JSON.parse(raw) as QueuedMutation[]) : [];
133
+ } catch {
134
+ return [];
135
+ }
136
+ }
137
+
138
+ function persistQueue(queue: QueuedMutation[]): void {
139
+ if (typeof localStorage === 'undefined') return;
140
+ try {
141
+ localStorage.setItem(QUEUE_STORAGE_KEY, JSON.stringify(queue));
142
+ } catch {
143
+ // localStorage full or unavailable — silently ignore
144
+ }
145
+ }
146
+
147
+ let idCounter = 0;
148
+ function generateId(): string {
149
+ idCounter += 1;
150
+ return `mut_${Date.now()}_${idCounter}`;
151
+ }
152
+
153
+ // ---------------------------------------------------------------------------
154
+ // useOffline hook
155
+ // ---------------------------------------------------------------------------
156
+
157
+ const DEFAULTS: Required<
158
+ Pick<OfflineConfig, 'enabled' | 'strategy' | 'offlineIndicator' | 'queueMaxSize'>
159
+ > & { offlineMessage: string } = {
160
+ enabled: true,
161
+ strategy: 'network_first',
162
+ offlineIndicator: true,
163
+ offlineMessage: 'You are currently offline. Changes will be synced when reconnected.',
164
+ queueMaxSize: 100,
165
+ };
166
+
167
+ /**
168
+ * Hook for offline mode detection and sync queue management.
169
+ * Implements OfflineConfigSchema, SyncConfigSchema, and ConflictResolutionSchema
170
+ * from @objectstack/spec v2.0.7.
171
+ *
172
+ * @example
173
+ * ```tsx
174
+ * function App() {
175
+ * const offline = useOffline({
176
+ * enabled: true,
177
+ * strategy: 'cache_first',
178
+ * sync: { conflictResolution: 'last_write_wins' },
179
+ * });
180
+ *
181
+ * if (!offline.isOnline && offline.showIndicator) {
182
+ * return <Banner>{offline.offlineMessage}</Banner>;
183
+ * }
184
+ *
185
+ * return <div>Pending mutations: {offline.pendingCount}</div>;
186
+ * }
187
+ * ```
188
+ */
189
+ export function useOffline(config: OfflineConfig = {}): OfflineResult {
190
+ const {
191
+ enabled = DEFAULTS.enabled,
192
+ strategy = DEFAULTS.strategy,
193
+ offlineIndicator = DEFAULTS.offlineIndicator,
194
+ offlineMessage = DEFAULTS.offlineMessage,
195
+ queueMaxSize = DEFAULTS.queueMaxSize,
196
+ sync: syncConfig,
197
+ } = config;
198
+
199
+ const isOnline = useSyncExternalStore(subscribeOnline, getOnlineSnapshot, getServerSnapshot);
200
+ const [queue, setQueue] = useState<QueuedMutation[]>(loadQueue);
201
+ const [syncState, setSyncState] = useState<SyncState>('idle');
202
+ const syncConfigRef = useRef(syncConfig);
203
+ syncConfigRef.current = syncConfig;
204
+
205
+ // Persist queue to localStorage whenever it changes
206
+ useEffect(() => {
207
+ persistQueue(queue);
208
+ }, [queue]);
209
+
210
+ // Update sync state based on online status
211
+ useEffect(() => {
212
+ if (!enabled) return;
213
+ if (!isOnline) {
214
+ setSyncState('offline');
215
+ } else if (syncState === 'offline') {
216
+ setSyncState('idle');
217
+ }
218
+ }, [isOnline, enabled, syncState]);
219
+
220
+ const queueMutation = useCallback(
221
+ (mutation: Omit<QueuedMutation, 'id' | 'timestamp'>) => {
222
+ if (!enabled) return;
223
+ setQueue((prev) => {
224
+ const newEntry: QueuedMutation = {
225
+ ...mutation,
226
+ id: generateId(),
227
+ timestamp: Date.now(),
228
+ };
229
+ const next = [...prev, newEntry];
230
+ // Enforce max queue size (FIFO eviction)
231
+ if (next.length > queueMaxSize) {
232
+ return next.slice(next.length - queueMaxSize);
233
+ }
234
+ return next;
235
+ });
236
+ },
237
+ [enabled, queueMaxSize],
238
+ );
239
+
240
+ const clearQueue = useCallback(() => {
241
+ setQueue([]);
242
+ }, []);
243
+
244
+ const sync = useCallback(async () => {
245
+ if (!enabled || queue.length === 0) return;
246
+ setSyncState('syncing');
247
+ try {
248
+ // In a real implementation, this would batch-send mutations to the server.
249
+ // For now, we simulate a successful sync by clearing the queue.
250
+ const batchSize = syncConfigRef.current?.batchSize ?? queue.length;
251
+ const batch = queue.slice(0, batchSize);
252
+
253
+ // Simulate network round-trip
254
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
255
+
256
+ // Remove synced mutations from queue
257
+ setQueue((prev) => prev.filter((m) => !batch.some((b) => b.id === m.id)));
258
+ setSyncState('idle');
259
+ } catch {
260
+ setSyncState('error');
261
+ }
262
+ }, [enabled, queue]);
263
+
264
+ // Auto-sync when coming back online (short stabilization delay)
265
+ useEffect(() => {
266
+ if (!enabled || !isOnline || queue.length === 0) return;
267
+ const timer = setTimeout(() => {
268
+ void sync();
269
+ }, 100);
270
+ return () => clearTimeout(timer);
271
+ // Only trigger on isOnline changes, not on every queue change
272
+ // eslint-disable-next-line react-hooks/exhaustive-deps
273
+ }, [isOnline, enabled]);
274
+
275
+ return useMemo<OfflineResult>(
276
+ () => ({
277
+ isOnline,
278
+ enabled,
279
+ syncState,
280
+ strategy,
281
+ pendingCount: queue.length,
282
+ queueMutation,
283
+ sync,
284
+ clearQueue,
285
+ showIndicator: offlineIndicator && !isOnline,
286
+ offlineMessage,
287
+ }),
288
+ [
289
+ isOnline,
290
+ enabled,
291
+ syncState,
292
+ strategy,
293
+ queue.length,
294
+ queueMutation,
295
+ sync,
296
+ clearQueue,
297
+ offlineIndicator,
298
+ offlineMessage,
299
+ ],
300
+ );
301
+ }