@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.
- package/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +19 -0
- package/dist/SchemaRenderer.d.ts +20 -1
- package/dist/SchemaRenderer.js +76 -13
- package/dist/context/DndContext.d.ts +135 -0
- package/dist/context/DndContext.js +120 -0
- package/dist/context/NotificationContext.d.ts +113 -0
- package/dist/context/NotificationContext.js +130 -0
- package/dist/context/index.d.ts +2 -0
- package/dist/context/index.js +2 -0
- package/dist/hooks/index.d.ts +17 -0
- package/dist/hooks/index.js +17 -0
- package/dist/hooks/useAnimation.d.ts +46 -0
- package/dist/hooks/useAnimation.js +59 -0
- package/dist/hooks/useClientNotifications.d.ts +53 -0
- package/dist/hooks/useClientNotifications.js +190 -0
- package/dist/hooks/useColumnSummary.d.ts +38 -0
- package/dist/hooks/useColumnSummary.js +54 -0
- package/dist/hooks/useCrudShortcuts.d.ts +39 -0
- package/dist/hooks/useCrudShortcuts.js +96 -0
- package/dist/hooks/useDensityMode.d.ts +48 -0
- package/dist/hooks/useDensityMode.js +60 -0
- package/dist/hooks/useETagCache.d.ts +75 -0
- package/dist/hooks/useETagCache.js +306 -0
- package/dist/hooks/useFocusManagement.d.ts +89 -0
- package/dist/hooks/useFocusManagement.js +188 -0
- package/dist/hooks/useFocusTrap.d.ts +41 -0
- package/dist/hooks/useFocusTrap.js +103 -0
- package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
- package/dist/hooks/useKeyboardShortcuts.js +86 -0
- package/dist/hooks/useOffline.d.ts +96 -0
- package/dist/hooks/useOffline.js +185 -0
- package/dist/hooks/usePageTransition.d.ts +60 -0
- package/dist/hooks/usePageTransition.js +111 -0
- package/dist/hooks/usePerformance.d.ts +87 -0
- package/dist/hooks/usePerformance.js +165 -0
- package/dist/hooks/usePerformanceBudget.d.ts +78 -0
- package/dist/hooks/usePerformanceBudget.js +209 -0
- package/dist/hooks/useReducedMotion.d.ts +28 -0
- package/dist/hooks/useReducedMotion.js +48 -0
- package/dist/hooks/useSchemaPersistence.d.ts +87 -0
- package/dist/hooks/useSchemaPersistence.js +173 -0
- package/dist/hooks/useViewSharing.d.ts +57 -0
- package/dist/hooks/useViewSharing.js +74 -0
- package/dist/hooks/useViewTransition.d.ts +54 -0
- package/dist/hooks/useViewTransition.js +83 -0
- package/package.json +7 -7
- package/src/SchemaRenderer.tsx +122 -13
- package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
- package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
- package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
- package/src/__tests__/useOffline.test.ts +198 -0
- package/src/__tests__/usePageTransition.test.ts +214 -0
- package/src/__tests__/usePerformance.test.ts +137 -0
- package/src/__tests__/view-switching.test.tsx +456 -0
- package/src/context/DndContext.tsx +260 -0
- package/src/context/NotificationContext.tsx +280 -0
- package/src/context/__tests__/DndContext.test.tsx +150 -0
- package/src/context/__tests__/NotificationContext.test.tsx +176 -0
- package/src/context/index.ts +2 -0
- package/src/hooks/__tests__/useAnimation.test.ts +82 -0
- package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
- package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
- package/src/hooks/__tests__/useETagCache.test.ts +153 -0
- package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
- package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
- package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
- package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
- package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
- package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
- package/src/hooks/index.ts +17 -1
- package/src/hooks/useAnimation.ts +117 -0
- package/src/hooks/useClientNotifications.ts +251 -0
- package/src/hooks/useColumnSummary.ts +87 -0
- package/src/hooks/useCrudShortcuts.ts +126 -0
- package/src/hooks/useDensityMode.ts +102 -0
- package/src/hooks/useETagCache.ts +404 -0
- package/src/hooks/useFocusManagement.ts +248 -0
- package/src/hooks/useFocusTrap.ts +138 -0
- package/src/hooks/useKeyboardShortcuts.ts +119 -0
- package/src/hooks/useOffline.ts +301 -0
- package/src/hooks/usePageTransition.ts +187 -0
- package/src/hooks/usePerformance.ts +246 -0
- package/src/hooks/usePerformanceBudget.ts +313 -0
- package/src/hooks/useReducedMotion.ts +53 -0
- package/src/hooks/useSchemaPersistence.ts +222 -0
- package/src/hooks/useViewSharing.ts +140 -0
- package/src/hooks/useViewTransition.ts +144 -0
- package/tsconfig.tsbuildinfo +1 -1
|
@@ -0,0 +1,313 @@
|
|
|
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 } from 'react';
|
|
10
|
+
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Types for performance budget enforcement
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
/** Metric names that can be tracked against a budget. */
|
|
16
|
+
export type BudgetMetric = 'lcp' | 'fcp' | 'renderTime' | 'memory';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Performance budget configuration.
|
|
20
|
+
* Defines thresholds for LCP, bundle size, render time, etc.
|
|
21
|
+
*/
|
|
22
|
+
export interface PerformanceBudget {
|
|
23
|
+
/** Max Largest Contentful Paint in ms (default: 600) */
|
|
24
|
+
maxLCP?: number;
|
|
25
|
+
/** Max First Contentful Paint in ms (default: 300) */
|
|
26
|
+
maxFCP?: number;
|
|
27
|
+
/** Max component render time in ms (default: 16) */
|
|
28
|
+
maxRenderTime?: number;
|
|
29
|
+
/** Max bundle size in KB (gzipped) - informational only */
|
|
30
|
+
maxBundleSizeKB?: number;
|
|
31
|
+
/** Max memory usage in MB */
|
|
32
|
+
maxMemoryMB?: number;
|
|
33
|
+
/** Whether to log warnings to console in dev mode (default: true) */
|
|
34
|
+
warnOnViolation?: boolean;
|
|
35
|
+
/** Callback when a budget is violated */
|
|
36
|
+
onViolation?: (violation: BudgetViolation) => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface BudgetViolation {
|
|
40
|
+
metric: BudgetMetric;
|
|
41
|
+
budget: number;
|
|
42
|
+
actual: number;
|
|
43
|
+
timestamp: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface PerformanceBudgetResult {
|
|
47
|
+
/** Current violations */
|
|
48
|
+
violations: BudgetViolation[];
|
|
49
|
+
/** Whether all budgets are within limits */
|
|
50
|
+
isWithinBudget: boolean;
|
|
51
|
+
/** Check if a specific metric is within budget */
|
|
52
|
+
checkMetric: (metric: BudgetMetric, value: number) => boolean;
|
|
53
|
+
/** Track a render and check against budget */
|
|
54
|
+
trackRender: (durationMs: number) => boolean;
|
|
55
|
+
/** Clear all recorded violations */
|
|
56
|
+
clearViolations: () => void;
|
|
57
|
+
/** Current performance snapshot */
|
|
58
|
+
snapshot: {
|
|
59
|
+
lcp: number | null;
|
|
60
|
+
fcp: number | null;
|
|
61
|
+
memoryMB: number | null;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// ---------------------------------------------------------------------------
|
|
66
|
+
// Defaults
|
|
67
|
+
// ---------------------------------------------------------------------------
|
|
68
|
+
|
|
69
|
+
const DEFAULTS = {
|
|
70
|
+
maxLCP: 600,
|
|
71
|
+
maxFCP: 300,
|
|
72
|
+
maxRenderTime: 16,
|
|
73
|
+
maxMemoryMB: 128,
|
|
74
|
+
warnOnViolation: true,
|
|
75
|
+
} as const;
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------------------
|
|
78
|
+
// Helpers (same getFCP/getLCP pattern as usePerformance.ts)
|
|
79
|
+
// ---------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
function getFCP(): number | null {
|
|
82
|
+
if (typeof performance === 'undefined' || !performance.getEntriesByType) return null;
|
|
83
|
+
try {
|
|
84
|
+
const entries = performance.getEntriesByType('paint');
|
|
85
|
+
const entry = entries.find((e) => e.name === 'first-contentful-paint');
|
|
86
|
+
return entry ? Math.round(entry.startTime) : null;
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function getLCP(): number | null {
|
|
93
|
+
if (typeof performance === 'undefined' || !performance.getEntriesByType) return null;
|
|
94
|
+
try {
|
|
95
|
+
const entries = performance.getEntriesByType('largest-contentful-paint');
|
|
96
|
+
const entry = entries.length > 0 ? entries[entries.length - 1] : undefined;
|
|
97
|
+
return entry ? Math.round(entry.startTime) : null;
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Chrome-only memory API (guarded). */
|
|
104
|
+
function getMemoryMB(): number | null {
|
|
105
|
+
try {
|
|
106
|
+
const mem = (performance as unknown as { memory?: { usedJSHeapSize?: number } }).memory;
|
|
107
|
+
if (mem?.usedJSHeapSize != null) {
|
|
108
|
+
return Math.round((mem.usedJSHeapSize / (1024 * 1024)) * 100) / 100;
|
|
109
|
+
}
|
|
110
|
+
} catch {
|
|
111
|
+
/* not available */
|
|
112
|
+
}
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function buildViolationKey(metric: BudgetMetric): string {
|
|
117
|
+
return metric;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// usePerformanceBudget hook
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Hook for performance budget enforcement aligned with ROADMAP Q3 3.3.
|
|
126
|
+
*
|
|
127
|
+
* Monitors Web Vitals (LCP, FCP), memory usage, and component render times
|
|
128
|
+
* against configurable thresholds. Violations are recorded, deduplicated,
|
|
129
|
+
* and optionally logged to the console in development mode.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```tsx
|
|
133
|
+
* function App() {
|
|
134
|
+
* const budget = usePerformanceBudget({
|
|
135
|
+
* maxLCP: 500,
|
|
136
|
+
* maxRenderTime: 16,
|
|
137
|
+
* onViolation: (v) => analytics.track('perf_violation', v),
|
|
138
|
+
* });
|
|
139
|
+
*
|
|
140
|
+
* if (!budget.isWithinBudget) {
|
|
141
|
+
* console.warn('Performance budget exceeded:', budget.violations);
|
|
142
|
+
* }
|
|
143
|
+
*
|
|
144
|
+
* return <Dashboard />;
|
|
145
|
+
* }
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
export function usePerformanceBudget(
|
|
149
|
+
userBudget: PerformanceBudget = {},
|
|
150
|
+
): PerformanceBudgetResult {
|
|
151
|
+
const budget = useMemo(
|
|
152
|
+
() => ({
|
|
153
|
+
maxLCP: userBudget.maxLCP ?? DEFAULTS.maxLCP,
|
|
154
|
+
maxFCP: userBudget.maxFCP ?? DEFAULTS.maxFCP,
|
|
155
|
+
maxRenderTime: userBudget.maxRenderTime ?? DEFAULTS.maxRenderTime,
|
|
156
|
+
maxMemoryMB: userBudget.maxMemoryMB ?? DEFAULTS.maxMemoryMB,
|
|
157
|
+
warnOnViolation: userBudget.warnOnViolation ?? DEFAULTS.warnOnViolation,
|
|
158
|
+
}),
|
|
159
|
+
[
|
|
160
|
+
userBudget.maxLCP,
|
|
161
|
+
userBudget.maxFCP,
|
|
162
|
+
userBudget.maxRenderTime,
|
|
163
|
+
userBudget.maxMemoryMB,
|
|
164
|
+
userBudget.warnOnViolation,
|
|
165
|
+
],
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
const onViolationRef = useRef(userBudget.onViolation);
|
|
169
|
+
useEffect(() => {
|
|
170
|
+
onViolationRef.current = userBudget.onViolation;
|
|
171
|
+
}, [userBudget.onViolation]);
|
|
172
|
+
|
|
173
|
+
const [violations, setViolations] = useState<BudgetViolation[]>([]);
|
|
174
|
+
const seenRef = useRef<Set<string>>(new Set());
|
|
175
|
+
|
|
176
|
+
const [snapshot, setSnapshot] = useState<{
|
|
177
|
+
lcp: number | null;
|
|
178
|
+
fcp: number | null;
|
|
179
|
+
memoryMB: number | null;
|
|
180
|
+
}>({ lcp: null, fcp: null, memoryMB: null });
|
|
181
|
+
|
|
182
|
+
// -------------------------------------------------------------------
|
|
183
|
+
// Violation recording with deduplication
|
|
184
|
+
// -------------------------------------------------------------------
|
|
185
|
+
|
|
186
|
+
const recordViolation = useCallback(
|
|
187
|
+
(metric: BudgetMetric, budgetValue: number, actual: number) => {
|
|
188
|
+
const key = buildViolationKey(metric);
|
|
189
|
+
if (seenRef.current.has(key)) return;
|
|
190
|
+
seenRef.current.add(key);
|
|
191
|
+
|
|
192
|
+
const violation: BudgetViolation = {
|
|
193
|
+
metric,
|
|
194
|
+
budget: budgetValue,
|
|
195
|
+
actual: Math.round(actual * 100) / 100,
|
|
196
|
+
timestamp: Date.now(),
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
setViolations((prev) => [...prev, violation]);
|
|
200
|
+
|
|
201
|
+
if (budget.warnOnViolation && process.env.NODE_ENV !== 'production') {
|
|
202
|
+
console.warn(
|
|
203
|
+
`[ObjectUI] Performance budget violated: ${metric} = ${violation.actual} (budget: ${budgetValue})`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
onViolationRef.current?.(violation);
|
|
208
|
+
},
|
|
209
|
+
[budget.warnOnViolation],
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
// -------------------------------------------------------------------
|
|
213
|
+
// Collect Web Vitals & memory on mount
|
|
214
|
+
// -------------------------------------------------------------------
|
|
215
|
+
|
|
216
|
+
useEffect(() => {
|
|
217
|
+
const timer = setTimeout(() => {
|
|
218
|
+
const fcp = getFCP();
|
|
219
|
+
const lcp = getLCP();
|
|
220
|
+
const memoryMB = getMemoryMB();
|
|
221
|
+
|
|
222
|
+
setSnapshot({ lcp, fcp, memoryMB });
|
|
223
|
+
|
|
224
|
+
if (fcp != null && fcp > budget.maxFCP) {
|
|
225
|
+
recordViolation('fcp', budget.maxFCP, fcp);
|
|
226
|
+
}
|
|
227
|
+
if (lcp != null && lcp > budget.maxLCP) {
|
|
228
|
+
recordViolation('lcp', budget.maxLCP, lcp);
|
|
229
|
+
}
|
|
230
|
+
if (memoryMB != null && memoryMB > budget.maxMemoryMB) {
|
|
231
|
+
recordViolation('memory', budget.maxMemoryMB, memoryMB);
|
|
232
|
+
}
|
|
233
|
+
}, 0);
|
|
234
|
+
|
|
235
|
+
return () => clearTimeout(timer);
|
|
236
|
+
}, [budget.maxFCP, budget.maxLCP, budget.maxMemoryMB, recordViolation]);
|
|
237
|
+
|
|
238
|
+
// -------------------------------------------------------------------
|
|
239
|
+
// Periodic memory monitoring
|
|
240
|
+
// -------------------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
useEffect(() => {
|
|
243
|
+
// Only run when memory API is available
|
|
244
|
+
if (getMemoryMB() == null) return;
|
|
245
|
+
|
|
246
|
+
const interval = setInterval(() => {
|
|
247
|
+
const memoryMB = getMemoryMB();
|
|
248
|
+
if (memoryMB != null) {
|
|
249
|
+
setSnapshot((prev) => ({ ...prev, memoryMB }));
|
|
250
|
+
if (memoryMB > budget.maxMemoryMB) {
|
|
251
|
+
recordViolation('memory', budget.maxMemoryMB, memoryMB);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}, 10_000);
|
|
255
|
+
|
|
256
|
+
return () => clearInterval(interval);
|
|
257
|
+
}, [budget.maxMemoryMB, recordViolation]);
|
|
258
|
+
|
|
259
|
+
// -------------------------------------------------------------------
|
|
260
|
+
// Public API
|
|
261
|
+
// -------------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
const checkMetric = useCallback(
|
|
264
|
+
(metric: BudgetMetric, value: number): boolean => {
|
|
265
|
+
let threshold: number;
|
|
266
|
+
switch (metric) {
|
|
267
|
+
case 'lcp':
|
|
268
|
+
threshold = budget.maxLCP;
|
|
269
|
+
break;
|
|
270
|
+
case 'fcp':
|
|
271
|
+
threshold = budget.maxFCP;
|
|
272
|
+
break;
|
|
273
|
+
case 'renderTime':
|
|
274
|
+
threshold = budget.maxRenderTime;
|
|
275
|
+
break;
|
|
276
|
+
case 'memory':
|
|
277
|
+
threshold = budget.maxMemoryMB;
|
|
278
|
+
break;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const withinBudget = value <= threshold;
|
|
282
|
+
if (!withinBudget) {
|
|
283
|
+
recordViolation(metric, threshold, value);
|
|
284
|
+
}
|
|
285
|
+
return withinBudget;
|
|
286
|
+
},
|
|
287
|
+
[budget.maxLCP, budget.maxFCP, budget.maxRenderTime, budget.maxMemoryMB, recordViolation],
|
|
288
|
+
);
|
|
289
|
+
|
|
290
|
+
const trackRender = useCallback(
|
|
291
|
+
(durationMs: number): boolean => {
|
|
292
|
+
return checkMetric('renderTime', durationMs);
|
|
293
|
+
},
|
|
294
|
+
[checkMetric],
|
|
295
|
+
);
|
|
296
|
+
|
|
297
|
+
const clearViolations = useCallback(() => {
|
|
298
|
+
setViolations([]);
|
|
299
|
+
seenRef.current.clear();
|
|
300
|
+
}, []);
|
|
301
|
+
|
|
302
|
+
return useMemo(
|
|
303
|
+
() => ({
|
|
304
|
+
violations,
|
|
305
|
+
isWithinBudget: violations.length === 0,
|
|
306
|
+
checkMetric,
|
|
307
|
+
trackRender,
|
|
308
|
+
clearViolations,
|
|
309
|
+
snapshot,
|
|
310
|
+
}),
|
|
311
|
+
[violations, checkMetric, trackRender, clearViolations, snapshot],
|
|
312
|
+
);
|
|
313
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
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 { useState, useEffect } from 'react';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Hook that detects the user's motion preference.
|
|
13
|
+
* Implements MotionConfigSchema from @objectstack/spec v2.0.7.
|
|
14
|
+
*
|
|
15
|
+
* Respects the `prefers-reduced-motion` media query to provide
|
|
16
|
+
* accessible animation experiences.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```tsx
|
|
20
|
+
* function AnimatedCard() {
|
|
21
|
+
* const prefersReducedMotion = useReducedMotion();
|
|
22
|
+
*
|
|
23
|
+
* return (
|
|
24
|
+
* <div className={prefersReducedMotion ? '' : 'animate-fade-in'}>
|
|
25
|
+
* Content
|
|
26
|
+
* </div>
|
|
27
|
+
* );
|
|
28
|
+
* }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
export function useReducedMotion(): boolean {
|
|
32
|
+
const [prefersReducedMotion, setPrefersReducedMotion] = useState(() => {
|
|
33
|
+
if (typeof window === 'undefined') return false;
|
|
34
|
+
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
useEffect(() => {
|
|
38
|
+
if (typeof window === 'undefined') return;
|
|
39
|
+
|
|
40
|
+
const mediaQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
|
|
41
|
+
|
|
42
|
+
const handleChange = (event: MediaQueryListEvent) => {
|
|
43
|
+
setPrefersReducedMotion(event.matches);
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
mediaQuery.addEventListener('change', handleChange);
|
|
47
|
+
return () => {
|
|
48
|
+
mediaQuery.removeEventListener('change', handleChange);
|
|
49
|
+
};
|
|
50
|
+
}, []);
|
|
51
|
+
|
|
52
|
+
return prefersReducedMotion;
|
|
53
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
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 { useState, useCallback, useRef, useMemo } from 'react';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Persistence adapter interface for schema save/load operations.
|
|
13
|
+
* Implement this to connect to any backend (REST API, GraphQL, localStorage, etc.).
|
|
14
|
+
*/
|
|
15
|
+
export interface SchemaPersistenceAdapter {
|
|
16
|
+
/** Save a schema to the backend. Returns the saved schema ID. */
|
|
17
|
+
save: (id: string, schema: Record<string, unknown>) => Promise<string>;
|
|
18
|
+
/** Load a schema from the backend by ID. */
|
|
19
|
+
load: (id: string) => Promise<Record<string, unknown> | null>;
|
|
20
|
+
/** List all available schemas. */
|
|
21
|
+
list?: () => Promise<Array<{ id: string; name?: string; updatedAt?: string }>>;
|
|
22
|
+
/** Delete a schema from the backend. */
|
|
23
|
+
delete?: (id: string) => Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SchemaPersistenceState {
|
|
27
|
+
/** Whether a save/load operation is in progress */
|
|
28
|
+
loading: boolean;
|
|
29
|
+
/** The last error from a save/load operation */
|
|
30
|
+
error: Error | null;
|
|
31
|
+
/** Whether the current schema has unsaved changes */
|
|
32
|
+
isDirty: boolean;
|
|
33
|
+
/** The last saved timestamp */
|
|
34
|
+
lastSavedAt: Date | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface SchemaPersistenceResult extends SchemaPersistenceState {
|
|
38
|
+
/** Save the current schema */
|
|
39
|
+
save: (id: string, schema: Record<string, unknown>) => Promise<string | null>;
|
|
40
|
+
/** Load a schema by ID */
|
|
41
|
+
load: (id: string) => Promise<Record<string, unknown> | null>;
|
|
42
|
+
/** List available schemas */
|
|
43
|
+
list: () => Promise<Array<{ id: string; name?: string; updatedAt?: string }>>;
|
|
44
|
+
/** Delete a schema */
|
|
45
|
+
remove: (id: string) => Promise<boolean>;
|
|
46
|
+
/** Mark the current schema as dirty (has unsaved changes) */
|
|
47
|
+
markDirty: () => void;
|
|
48
|
+
/** Clear the error state */
|
|
49
|
+
clearError: () => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Default localStorage adapter for schema persistence.
|
|
54
|
+
* Useful for development and demos.
|
|
55
|
+
*/
|
|
56
|
+
export function createLocalStorageAdapter(prefix = 'objectui-schema'): SchemaPersistenceAdapter {
|
|
57
|
+
return {
|
|
58
|
+
async save(id: string, schema: Record<string, unknown>): Promise<string> {
|
|
59
|
+
const key = `${prefix}:${id}`;
|
|
60
|
+
const entry = { schema, updatedAt: new Date().toISOString() };
|
|
61
|
+
localStorage.setItem(key, JSON.stringify(entry));
|
|
62
|
+
// Update the index
|
|
63
|
+
const indexKey = `${prefix}:__index__`;
|
|
64
|
+
const index: string[] = JSON.parse(localStorage.getItem(indexKey) || '[]');
|
|
65
|
+
if (!index.includes(id)) {
|
|
66
|
+
index.push(id);
|
|
67
|
+
localStorage.setItem(indexKey, JSON.stringify(index));
|
|
68
|
+
}
|
|
69
|
+
return id;
|
|
70
|
+
},
|
|
71
|
+
async load(id: string): Promise<Record<string, unknown> | null> {
|
|
72
|
+
const key = `${prefix}:${id}`;
|
|
73
|
+
const raw = localStorage.getItem(key);
|
|
74
|
+
if (!raw) return null;
|
|
75
|
+
const entry = JSON.parse(raw);
|
|
76
|
+
return entry.schema ?? null;
|
|
77
|
+
},
|
|
78
|
+
async list(): Promise<Array<{ id: string; name?: string; updatedAt?: string }>> {
|
|
79
|
+
const indexKey = `${prefix}:__index__`;
|
|
80
|
+
const index: string[] = JSON.parse(localStorage.getItem(indexKey) || '[]');
|
|
81
|
+
return index.map((id) => {
|
|
82
|
+
const raw = localStorage.getItem(`${prefix}:${id}`);
|
|
83
|
+
const entry = raw ? JSON.parse(raw) : {};
|
|
84
|
+
return { id, name: id, updatedAt: entry.updatedAt };
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
async delete(id: string): Promise<void> {
|
|
88
|
+
const key = `${prefix}:${id}`;
|
|
89
|
+
localStorage.removeItem(key);
|
|
90
|
+
const indexKey = `${prefix}:__index__`;
|
|
91
|
+
const index: string[] = JSON.parse(localStorage.getItem(indexKey) || '[]');
|
|
92
|
+
localStorage.setItem(indexKey, JSON.stringify(index.filter((i) => i !== id)));
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Hook for persisting designer schemas (save/load/list/delete).
|
|
99
|
+
* Implements schema persistence for @object-ui/plugin-designer.
|
|
100
|
+
*
|
|
101
|
+
* Accepts a pluggable adapter for connecting to any backend.
|
|
102
|
+
* Falls back to a localStorage adapter for development use.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```tsx
|
|
106
|
+
* // With default localStorage adapter
|
|
107
|
+
* const persistence = useSchemaPersistence();
|
|
108
|
+
*
|
|
109
|
+
* // Save current design
|
|
110
|
+
* await persistence.save('my-page', pageSchema);
|
|
111
|
+
*
|
|
112
|
+
* // Load a design
|
|
113
|
+
* const schema = await persistence.load('my-page');
|
|
114
|
+
*
|
|
115
|
+
* // With custom API adapter
|
|
116
|
+
* const apiAdapter: SchemaPersistenceAdapter = {
|
|
117
|
+
* save: (id, schema) => fetch(`/api/schemas/${id}`, { method: 'PUT', body: JSON.stringify(schema) }).then(r => r.json()),
|
|
118
|
+
* load: (id) => fetch(`/api/schemas/${id}`).then(r => r.json()),
|
|
119
|
+
* list: () => fetch('/api/schemas').then(r => r.json()),
|
|
120
|
+
* delete: (id) => fetch(`/api/schemas/${id}`, { method: 'DELETE' }).then(() => {}),
|
|
121
|
+
* };
|
|
122
|
+
* const persistence = useSchemaPersistence(apiAdapter);
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
export function useSchemaPersistence(
|
|
126
|
+
adapter?: SchemaPersistenceAdapter,
|
|
127
|
+
): SchemaPersistenceResult {
|
|
128
|
+
const defaultAdapter = useRef(createLocalStorageAdapter());
|
|
129
|
+
const adapterRef = useRef(adapter ?? defaultAdapter.current);
|
|
130
|
+
// Keep the ref up to date if the adapter prop changes
|
|
131
|
+
adapterRef.current = adapter ?? defaultAdapter.current;
|
|
132
|
+
const [loading, setLoading] = useState(false);
|
|
133
|
+
const [error, setError] = useState<Error | null>(null);
|
|
134
|
+
const [isDirty, setIsDirty] = useState(false);
|
|
135
|
+
const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null);
|
|
136
|
+
|
|
137
|
+
const save = useCallback(
|
|
138
|
+
async (id: string, schema: Record<string, unknown>): Promise<string | null> => {
|
|
139
|
+
setLoading(true);
|
|
140
|
+
setError(null);
|
|
141
|
+
try {
|
|
142
|
+
const result = await adapterRef.current.save(id, schema);
|
|
143
|
+
setIsDirty(false);
|
|
144
|
+
setLastSavedAt(new Date());
|
|
145
|
+
return result;
|
|
146
|
+
} catch (err) {
|
|
147
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
148
|
+
return null;
|
|
149
|
+
} finally {
|
|
150
|
+
setLoading(false);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
[],
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
const load = useCallback(async (id: string): Promise<Record<string, unknown> | null> => {
|
|
157
|
+
setLoading(true);
|
|
158
|
+
setError(null);
|
|
159
|
+
try {
|
|
160
|
+
const result = await adapterRef.current.load(id);
|
|
161
|
+
setIsDirty(false);
|
|
162
|
+
return result;
|
|
163
|
+
} catch (err) {
|
|
164
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
165
|
+
return null;
|
|
166
|
+
} finally {
|
|
167
|
+
setLoading(false);
|
|
168
|
+
}
|
|
169
|
+
}, []);
|
|
170
|
+
|
|
171
|
+
const list = useCallback(async (): Promise<Array<{ id: string; name?: string; updatedAt?: string }>> => {
|
|
172
|
+
setLoading(true);
|
|
173
|
+
setError(null);
|
|
174
|
+
try {
|
|
175
|
+
if (adapterRef.current.list) {
|
|
176
|
+
return await adapterRef.current.list();
|
|
177
|
+
}
|
|
178
|
+
return [];
|
|
179
|
+
} catch (err) {
|
|
180
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
181
|
+
return [];
|
|
182
|
+
} finally {
|
|
183
|
+
setLoading(false);
|
|
184
|
+
}
|
|
185
|
+
}, []);
|
|
186
|
+
|
|
187
|
+
const remove = useCallback(async (id: string): Promise<boolean> => {
|
|
188
|
+
setLoading(true);
|
|
189
|
+
setError(null);
|
|
190
|
+
try {
|
|
191
|
+
if (adapterRef.current.delete) {
|
|
192
|
+
await adapterRef.current.delete(id);
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
} catch (err) {
|
|
197
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
198
|
+
return false;
|
|
199
|
+
} finally {
|
|
200
|
+
setLoading(false);
|
|
201
|
+
}
|
|
202
|
+
}, []);
|
|
203
|
+
|
|
204
|
+
const markDirty = useCallback(() => setIsDirty(true), []);
|
|
205
|
+
const clearError = useCallback(() => setError(null), []);
|
|
206
|
+
|
|
207
|
+
return useMemo(
|
|
208
|
+
() => ({
|
|
209
|
+
loading,
|
|
210
|
+
error,
|
|
211
|
+
isDirty,
|
|
212
|
+
lastSavedAt,
|
|
213
|
+
save,
|
|
214
|
+
load,
|
|
215
|
+
list,
|
|
216
|
+
remove,
|
|
217
|
+
markDirty,
|
|
218
|
+
clearError,
|
|
219
|
+
}),
|
|
220
|
+
[loading, error, isDirty, lastSavedAt, save, load, list, remove, markDirty, clearError],
|
|
221
|
+
);
|
|
222
|
+
}
|