@object-ui/react 3.3.0 → 3.3.2

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 (103) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +21 -1
  3. package/dist/SchemaRenderer.js +19 -2
  4. package/dist/context/AppShellContext.d.ts +26 -0
  5. package/dist/context/AppShellContext.js +67 -0
  6. package/dist/context/index.d.ts +1 -7
  7. package/dist/context/index.js +1 -7
  8. package/package.json +32 -9
  9. package/.turbo/turbo-build.log +0 -4
  10. package/src/LazyPluginLoader.tsx +0 -174
  11. package/src/SchemaRenderer.tsx +0 -266
  12. package/src/__tests__/LazyPluginLoader.test.tsx +0 -176
  13. package/src/__tests__/SchemaRenderer.aria.test.tsx +0 -118
  14. package/src/__tests__/SchemaRenderer.debug.test.tsx +0 -69
  15. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +0 -114
  16. package/src/__tests__/SchemaRenderer.expressions.test.tsx +0 -131
  17. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +0 -132
  18. package/src/__tests__/ThemeProvider.test.tsx +0 -451
  19. package/src/__tests__/useNavigationOverlay.test.ts +0 -578
  20. package/src/__tests__/useOffline.test.ts +0 -198
  21. package/src/__tests__/usePageTransition.test.ts +0 -214
  22. package/src/__tests__/usePageVariables.test.tsx +0 -334
  23. package/src/__tests__/usePerformance.test.ts +0 -137
  24. package/src/__tests__/useViewData.test.tsx +0 -422
  25. package/src/__tests__/view-switching.test.tsx +0 -456
  26. package/src/components/form/FieldFactory.tsx +0 -516
  27. package/src/components/form/FormRenderer.test.tsx +0 -744
  28. package/src/components/form/FormRenderer.tsx +0 -258
  29. package/src/components/form/README.md +0 -352
  30. package/src/components/form/index.ts +0 -12
  31. package/src/context/ActionContext.tsx +0 -213
  32. package/src/context/DndContext.tsx +0 -260
  33. package/src/context/NotificationContext.tsx +0 -280
  34. package/src/context/SchemaRendererContext.tsx +0 -48
  35. package/src/context/ThemeContext.tsx +0 -325
  36. package/src/context/__tests__/ActionContext.test.tsx +0 -174
  37. package/src/context/__tests__/DndContext.test.tsx +0 -150
  38. package/src/context/__tests__/NotificationContext.test.tsx +0 -176
  39. package/src/context/__tests__/useDataScope.test.tsx +0 -91
  40. package/src/context/index.ts +0 -13
  41. package/src/hooks/__tests__/useActionEngine.test.ts +0 -170
  42. package/src/hooks/__tests__/useActionRunner.test.ts +0 -153
  43. package/src/hooks/__tests__/useAnimation.test.ts +0 -82
  44. package/src/hooks/__tests__/useColumnSummary.test.ts +0 -93
  45. package/src/hooks/__tests__/useCrudShortcuts.test.ts +0 -85
  46. package/src/hooks/__tests__/useDataRefresh.test.ts +0 -115
  47. package/src/hooks/__tests__/useDebugMode.test.ts +0 -83
  48. package/src/hooks/__tests__/useDensityMode.test.ts +0 -81
  49. package/src/hooks/__tests__/useDiscovery.test.tsx +0 -247
  50. package/src/hooks/__tests__/useDynamicApp.test.ts +0 -161
  51. package/src/hooks/__tests__/useETagCache.test.ts +0 -153
  52. package/src/hooks/__tests__/useExpression.test.ts +0 -86
  53. package/src/hooks/__tests__/useFocusTrap.test.ts +0 -294
  54. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +0 -144
  55. package/src/hooks/__tests__/usePageTransition.test.ts +0 -158
  56. package/src/hooks/__tests__/usePerformanceBudget.test.ts +0 -157
  57. package/src/hooks/__tests__/useReducedMotion.test.ts +0 -104
  58. package/src/hooks/__tests__/useSchemaPersistence.test.ts +0 -220
  59. package/src/hooks/__tests__/useViewSharing.test.ts +0 -121
  60. package/src/hooks/__tests__/useViewTransition.test.ts +0 -61
  61. package/src/hooks/index.ts +0 -36
  62. package/src/hooks/useActionEngine.ts +0 -84
  63. package/src/hooks/useActionRunner.ts +0 -119
  64. package/src/hooks/useAnimation.ts +0 -117
  65. package/src/hooks/useClientNotifications.ts +0 -251
  66. package/src/hooks/useColumnSummary.ts +0 -87
  67. package/src/hooks/useCrudShortcuts.ts +0 -126
  68. package/src/hooks/useDataRefresh.ts +0 -58
  69. package/src/hooks/useDebugMode.ts +0 -95
  70. package/src/hooks/useDensityMode.ts +0 -102
  71. package/src/hooks/useDiscovery.ts +0 -168
  72. package/src/hooks/useDynamicApp.ts +0 -142
  73. package/src/hooks/useETagCache.ts +0 -404
  74. package/src/hooks/useExpression.ts +0 -56
  75. package/src/hooks/useFocusManagement.ts +0 -248
  76. package/src/hooks/useFocusTrap.ts +0 -138
  77. package/src/hooks/useGlobalUndo.ts +0 -98
  78. package/src/hooks/useKeyboardShortcuts.ts +0 -119
  79. package/src/hooks/useNavigationOverlay.ts +0 -190
  80. package/src/hooks/useOffline.ts +0 -301
  81. package/src/hooks/usePageTransition.ts +0 -187
  82. package/src/hooks/usePageVariables.tsx +0 -157
  83. package/src/hooks/usePerformance.ts +0 -246
  84. package/src/hooks/usePerformanceBudget.ts +0 -313
  85. package/src/hooks/useReducedMotion.ts +0 -53
  86. package/src/hooks/useSchemaPersistence.ts +0 -222
  87. package/src/hooks/useViewData.ts +0 -201
  88. package/src/hooks/useViewSharing.ts +0 -140
  89. package/src/hooks/useViewTransition.ts +0 -144
  90. package/src/index.ts +0 -41
  91. package/src/spec-bridge/SpecBridge.ts +0 -64
  92. package/src/spec-bridge/__tests__/P1SpecBridge.test.ts +0 -855
  93. package/src/spec-bridge/__tests__/SpecBridge.test.ts +0 -550
  94. package/src/spec-bridge/bridges/dashboard.ts +0 -180
  95. package/src/spec-bridge/bridges/form-view.ts +0 -109
  96. package/src/spec-bridge/bridges/list-view.ts +0 -187
  97. package/src/spec-bridge/bridges/page.ts +0 -136
  98. package/src/spec-bridge/index.ts +0 -14
  99. package/src/spec-bridge/types.ts +0 -38
  100. package/src/utils/i18n.ts +0 -10
  101. package/tsconfig.json +0 -17
  102. package/tsconfig.tsbuildinfo +0 -1
  103. package/vitest.config.ts +0 -2
@@ -1,301 +0,0 @@
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
- }
@@ -1,187 +0,0 @@
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 { useMemo } from 'react';
10
- import { useReducedMotion } from './useReducedMotion';
11
-
12
- // ---------------------------------------------------------------------------
13
- // Types aligned with @objectstack/spec v2.0.7 PageTransitionSchema
14
- // ---------------------------------------------------------------------------
15
-
16
- /** Page transition type. */
17
- export type PageTransitionType =
18
- | 'none'
19
- | 'fade'
20
- | 'slide_up'
21
- | 'slide_down'
22
- | 'slide_left'
23
- | 'slide_right'
24
- | 'scale'
25
- | 'rotate'
26
- | 'flip';
27
-
28
- /** Easing function for page transitions. */
29
- export type PageTransitionEasing =
30
- | 'linear'
31
- | 'ease'
32
- | 'ease_in'
33
- | 'ease_out'
34
- | 'ease_in_out'
35
- | 'spring';
36
-
37
- /** Page transition configuration aligned with PageTransitionSchema. */
38
- export interface PageTransitionConfig {
39
- /** Transition type. */
40
- type?: PageTransitionType;
41
- /** Duration in milliseconds. */
42
- duration?: number;
43
- /** Easing function. */
44
- easing?: PageTransitionEasing;
45
- /** Whether entering and exiting pages cross-fade. */
46
- crossFade?: boolean;
47
- }
48
-
49
- /** Resolved CSS classes and styles for a page transition. */
50
- export interface PageTransitionResult {
51
- /** Tailwind CSS classes for the enter transition. */
52
- enterClassName: string;
53
- /** Tailwind CSS classes for the exit transition. */
54
- exitClassName: string;
55
- /** Inline styles for the enter transition. */
56
- enterStyle: React.CSSProperties;
57
- /** Inline styles for the exit transition. */
58
- exitStyle: React.CSSProperties;
59
- /** Whether the transition is active (not 'none' and motion not reduced). */
60
- isActive: boolean;
61
- /** The resolved transition type. */
62
- type: PageTransitionType;
63
- /** The resolved duration in ms. */
64
- duration: number;
65
- }
66
-
67
- // ---------------------------------------------------------------------------
68
- // Constants
69
- // ---------------------------------------------------------------------------
70
-
71
- const EASING_CSS: Record<PageTransitionEasing, string> = {
72
- linear: 'linear',
73
- ease: 'ease',
74
- ease_in: 'ease-in',
75
- ease_out: 'ease-out',
76
- ease_in_out: 'ease-in-out',
77
- spring: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
78
- };
79
-
80
- const ENTER_CLASSES: Record<PageTransitionType, string> = {
81
- none: '',
82
- fade: 'animate-in fade-in',
83
- slide_up: 'animate-in slide-in-from-bottom-4',
84
- slide_down: 'animate-in slide-in-from-top-4',
85
- slide_left: 'animate-in slide-in-from-right-4',
86
- slide_right: 'animate-in slide-in-from-left-4',
87
- scale: 'animate-in zoom-in-95',
88
- rotate: 'animate-in spin-in-90',
89
- flip: 'animate-in fade-in zoom-in-95',
90
- };
91
-
92
- const EXIT_CLASSES: Record<PageTransitionType, string> = {
93
- none: '',
94
- fade: 'animate-out fade-out',
95
- slide_up: 'animate-out slide-out-to-top-4',
96
- slide_down: 'animate-out slide-out-to-bottom-4',
97
- slide_left: 'animate-out slide-out-to-left-4',
98
- slide_right: 'animate-out slide-out-to-right-4',
99
- scale: 'animate-out zoom-out-95',
100
- rotate: 'animate-out spin-out-90',
101
- flip: 'animate-out fade-out zoom-out-95',
102
- };
103
-
104
- const DEFAULT_DURATION = 300;
105
- const DEFAULT_EASING: PageTransitionEasing = 'ease_in_out';
106
-
107
- // ---------------------------------------------------------------------------
108
- // usePageTransition hook
109
- // ---------------------------------------------------------------------------
110
-
111
- /**
112
- * Hook for page-level transition animations aligned with
113
- * PageTransitionSchema from @objectstack/spec v2.0.7.
114
- *
115
- * Generates Tailwind CSS animate-in / animate-out classes and inline styles
116
- * for enter/exit page transitions. Respects `prefers-reduced-motion`.
117
- *
118
- * @example
119
- * ```tsx
120
- * function PageWrapper({ children }: { children: React.ReactNode }) {
121
- * const transition = usePageTransition({ type: 'fade', duration: 200 });
122
- *
123
- * return (
124
- * <div className={transition.enterClassName} style={transition.enterStyle}>
125
- * {children}
126
- * </div>
127
- * );
128
- * }
129
- * ```
130
- */
131
- export function usePageTransition(config: PageTransitionConfig = {}): PageTransitionResult {
132
- const {
133
- type = 'none',
134
- duration = DEFAULT_DURATION,
135
- easing = DEFAULT_EASING,
136
- crossFade = false,
137
- } = config;
138
-
139
- const reducedMotion = useReducedMotion();
140
-
141
- return useMemo(() => {
142
- const isActive = type !== 'none' && !reducedMotion;
143
-
144
- if (!isActive) {
145
- return {
146
- enterClassName: '',
147
- exitClassName: '',
148
- enterStyle: {},
149
- exitStyle: {},
150
- isActive: false,
151
- type,
152
- duration,
153
- };
154
- }
155
-
156
- const enterClassName = ENTER_CLASSES[type] || '';
157
- const exitClassName = EXIT_CLASSES[type] || '';
158
-
159
- const baseStyle: React.CSSProperties = {
160
- animationDuration: `${duration}ms`,
161
- animationTimingFunction: EASING_CSS[easing] || EASING_CSS.ease_in_out,
162
- animationFillMode: 'both',
163
- };
164
-
165
- const enterStyle: React.CSSProperties = { ...baseStyle };
166
- const exitStyle: React.CSSProperties = { ...baseStyle };
167
-
168
- // When crossFade is enabled, both the entering and exiting pages
169
- // should overlap and transition opacity simultaneously.
170
- if (crossFade) {
171
- enterStyle.position = 'absolute';
172
- enterStyle.inset = '0';
173
- exitStyle.position = 'absolute';
174
- exitStyle.inset = '0';
175
- }
176
-
177
- return {
178
- enterClassName,
179
- exitClassName,
180
- enterStyle,
181
- exitStyle,
182
- isActive: true,
183
- type,
184
- duration,
185
- };
186
- }, [type, duration, easing, crossFade, reducedMotion]);
187
- }
@@ -1,157 +0,0 @@
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 React, { createContext, useContext, useState, useCallback, useMemo } from 'react';
10
- import type { PageVariable } from '@object-ui/types';
11
-
12
- /**
13
- * Page variables context value.
14
- * Provides access to page-level state variables.
15
- */
16
- export interface PageVariablesContextValue {
17
- /** Current variable values */
18
- variables: Record<string, any>;
19
- /** Set a single variable value */
20
- setVariable: (name: string, value: any) => void;
21
- /** Set multiple variable values at once */
22
- setVariables: (updates: Record<string, any>) => void;
23
- /** Reset all variables to their default values */
24
- resetVariables: () => void;
25
- }
26
-
27
- const PageVariablesContext = createContext<PageVariablesContextValue | null>(null);
28
-
29
- /**
30
- * Initialize page variables from their definitions.
31
- * Sets each variable to its defaultValue or type-appropriate default.
32
- */
33
- function initializeVariables(definitions?: PageVariable[]): Record<string, any> {
34
- if (!definitions || definitions.length === 0) return {};
35
-
36
- const initial: Record<string, any> = {};
37
- for (const def of definitions) {
38
- if (def.defaultValue !== undefined) {
39
- initial[def.name] = def.defaultValue;
40
- } else {
41
- // Type-appropriate defaults
42
- switch (def.type) {
43
- case 'number':
44
- initial[def.name] = 0;
45
- break;
46
- case 'boolean':
47
- initial[def.name] = false;
48
- break;
49
- case 'object':
50
- initial[def.name] = {};
51
- break;
52
- case 'array':
53
- initial[def.name] = [];
54
- break;
55
- case 'string':
56
- default:
57
- initial[def.name] = '';
58
- break;
59
- }
60
- }
61
- }
62
- return initial;
63
- }
64
-
65
- /**
66
- * Props for PageVariablesProvider
67
- */
68
- export interface PageVariablesProviderProps {
69
- /** Variable definitions from PageSchema.variables */
70
- definitions?: PageVariable[];
71
- /** Child components */
72
- children: React.ReactNode;
73
- }
74
-
75
- /**
76
- * PageVariablesProvider — Provides page-level state variables to the component tree.
77
- *
78
- * Initializes variables from their definitions and provides read/write access
79
- * to all child components via the usePageVariables hook.
80
- *
81
- * @example
82
- * ```tsx
83
- * <PageVariablesProvider definitions={[
84
- * { name: 'selectedId', type: 'string', defaultValue: '' },
85
- * { name: 'count', type: 'number', defaultValue: 0 },
86
- * ]}>
87
- * <MyComponents />
88
- * </PageVariablesProvider>
89
- * ```
90
- */
91
- export const PageVariablesProvider: React.FC<PageVariablesProviderProps> = ({
92
- definitions,
93
- children,
94
- }) => {
95
- const [variables, setVariablesState] = useState<Record<string, any>>(() =>
96
- initializeVariables(definitions)
97
- );
98
-
99
- const setVariable = useCallback((name: string, value: any) => {
100
- setVariablesState((prev) => ({ ...prev, [name]: value }));
101
- }, []);
102
-
103
- const setVariables = useCallback((updates: Record<string, any>) => {
104
- setVariablesState((prev) => ({ ...prev, ...updates }));
105
- }, []);
106
-
107
- const resetVariables = useCallback(() => {
108
- setVariablesState(initializeVariables(definitions));
109
- }, [definitions]);
110
-
111
- const value = useMemo<PageVariablesContextValue>(
112
- () => ({ variables, setVariable, setVariables, resetVariables }),
113
- [variables, setVariable, setVariables, resetVariables]
114
- );
115
-
116
- return (
117
- <PageVariablesContext.Provider value={value}>
118
- {children}
119
- </PageVariablesContext.Provider>
120
- );
121
- };
122
-
123
- PageVariablesProvider.displayName = 'PageVariablesProvider';
124
-
125
- /**
126
- * Hook to access page-level variables.
127
- *
128
- * Returns the current variable values and setter functions.
129
- * Returns a no-op fallback if used outside a PageVariablesProvider.
130
- *
131
- * @example
132
- * ```tsx
133
- * const { variables, setVariable } = usePageVariables();
134
- * const userId = variables.selectedId;
135
- * setVariable('selectedId', '123');
136
- * ```
137
- */
138
- export function usePageVariables(): PageVariablesContextValue {
139
- const ctx = useContext(PageVariablesContext);
140
- if (!ctx) {
141
- // Graceful fallback — allows components to work outside a Page
142
- return {
143
- variables: {},
144
- setVariable: () => {},
145
- setVariables: () => {},
146
- resetVariables: () => {},
147
- };
148
- }
149
- return ctx;
150
- }
151
-
152
- /**
153
- * Hook to check if a PageVariablesProvider is available.
154
- */
155
- export function useHasPageVariables(): boolean {
156
- return useContext(PageVariablesContext) !== null;
157
- }