@object-ui/react 3.3.0 → 3.3.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 (102) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +21 -1
  3. package/dist/context/AppShellContext.d.ts +26 -0
  4. package/dist/context/AppShellContext.js +67 -0
  5. package/dist/context/index.d.ts +1 -7
  6. package/dist/context/index.js +1 -7
  7. package/package.json +32 -9
  8. package/.turbo/turbo-build.log +0 -4
  9. package/src/LazyPluginLoader.tsx +0 -174
  10. package/src/SchemaRenderer.tsx +0 -266
  11. package/src/__tests__/LazyPluginLoader.test.tsx +0 -176
  12. package/src/__tests__/SchemaRenderer.aria.test.tsx +0 -118
  13. package/src/__tests__/SchemaRenderer.debug.test.tsx +0 -69
  14. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +0 -114
  15. package/src/__tests__/SchemaRenderer.expressions.test.tsx +0 -131
  16. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +0 -132
  17. package/src/__tests__/ThemeProvider.test.tsx +0 -451
  18. package/src/__tests__/useNavigationOverlay.test.ts +0 -578
  19. package/src/__tests__/useOffline.test.ts +0 -198
  20. package/src/__tests__/usePageTransition.test.ts +0 -214
  21. package/src/__tests__/usePageVariables.test.tsx +0 -334
  22. package/src/__tests__/usePerformance.test.ts +0 -137
  23. package/src/__tests__/useViewData.test.tsx +0 -422
  24. package/src/__tests__/view-switching.test.tsx +0 -456
  25. package/src/components/form/FieldFactory.tsx +0 -516
  26. package/src/components/form/FormRenderer.test.tsx +0 -744
  27. package/src/components/form/FormRenderer.tsx +0 -258
  28. package/src/components/form/README.md +0 -352
  29. package/src/components/form/index.ts +0 -12
  30. package/src/context/ActionContext.tsx +0 -213
  31. package/src/context/DndContext.tsx +0 -260
  32. package/src/context/NotificationContext.tsx +0 -280
  33. package/src/context/SchemaRendererContext.tsx +0 -48
  34. package/src/context/ThemeContext.tsx +0 -325
  35. package/src/context/__tests__/ActionContext.test.tsx +0 -174
  36. package/src/context/__tests__/DndContext.test.tsx +0 -150
  37. package/src/context/__tests__/NotificationContext.test.tsx +0 -176
  38. package/src/context/__tests__/useDataScope.test.tsx +0 -91
  39. package/src/context/index.ts +0 -13
  40. package/src/hooks/__tests__/useActionEngine.test.ts +0 -170
  41. package/src/hooks/__tests__/useActionRunner.test.ts +0 -153
  42. package/src/hooks/__tests__/useAnimation.test.ts +0 -82
  43. package/src/hooks/__tests__/useColumnSummary.test.ts +0 -93
  44. package/src/hooks/__tests__/useCrudShortcuts.test.ts +0 -85
  45. package/src/hooks/__tests__/useDataRefresh.test.ts +0 -115
  46. package/src/hooks/__tests__/useDebugMode.test.ts +0 -83
  47. package/src/hooks/__tests__/useDensityMode.test.ts +0 -81
  48. package/src/hooks/__tests__/useDiscovery.test.tsx +0 -247
  49. package/src/hooks/__tests__/useDynamicApp.test.ts +0 -161
  50. package/src/hooks/__tests__/useETagCache.test.ts +0 -153
  51. package/src/hooks/__tests__/useExpression.test.ts +0 -86
  52. package/src/hooks/__tests__/useFocusTrap.test.ts +0 -294
  53. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +0 -144
  54. package/src/hooks/__tests__/usePageTransition.test.ts +0 -158
  55. package/src/hooks/__tests__/usePerformanceBudget.test.ts +0 -157
  56. package/src/hooks/__tests__/useReducedMotion.test.ts +0 -104
  57. package/src/hooks/__tests__/useSchemaPersistence.test.ts +0 -220
  58. package/src/hooks/__tests__/useViewSharing.test.ts +0 -121
  59. package/src/hooks/__tests__/useViewTransition.test.ts +0 -61
  60. package/src/hooks/index.ts +0 -36
  61. package/src/hooks/useActionEngine.ts +0 -84
  62. package/src/hooks/useActionRunner.ts +0 -119
  63. package/src/hooks/useAnimation.ts +0 -117
  64. package/src/hooks/useClientNotifications.ts +0 -251
  65. package/src/hooks/useColumnSummary.ts +0 -87
  66. package/src/hooks/useCrudShortcuts.ts +0 -126
  67. package/src/hooks/useDataRefresh.ts +0 -58
  68. package/src/hooks/useDebugMode.ts +0 -95
  69. package/src/hooks/useDensityMode.ts +0 -102
  70. package/src/hooks/useDiscovery.ts +0 -168
  71. package/src/hooks/useDynamicApp.ts +0 -142
  72. package/src/hooks/useETagCache.ts +0 -404
  73. package/src/hooks/useExpression.ts +0 -56
  74. package/src/hooks/useFocusManagement.ts +0 -248
  75. package/src/hooks/useFocusTrap.ts +0 -138
  76. package/src/hooks/useGlobalUndo.ts +0 -98
  77. package/src/hooks/useKeyboardShortcuts.ts +0 -119
  78. package/src/hooks/useNavigationOverlay.ts +0 -190
  79. package/src/hooks/useOffline.ts +0 -301
  80. package/src/hooks/usePageTransition.ts +0 -187
  81. package/src/hooks/usePageVariables.tsx +0 -157
  82. package/src/hooks/usePerformance.ts +0 -246
  83. package/src/hooks/usePerformanceBudget.ts +0 -313
  84. package/src/hooks/useReducedMotion.ts +0 -53
  85. package/src/hooks/useSchemaPersistence.ts +0 -222
  86. package/src/hooks/useViewData.ts +0 -201
  87. package/src/hooks/useViewSharing.ts +0 -140
  88. package/src/hooks/useViewTransition.ts +0 -144
  89. package/src/index.ts +0 -41
  90. package/src/spec-bridge/SpecBridge.ts +0 -64
  91. package/src/spec-bridge/__tests__/P1SpecBridge.test.ts +0 -855
  92. package/src/spec-bridge/__tests__/SpecBridge.test.ts +0 -550
  93. package/src/spec-bridge/bridges/dashboard.ts +0 -180
  94. package/src/spec-bridge/bridges/form-view.ts +0 -109
  95. package/src/spec-bridge/bridges/list-view.ts +0 -187
  96. package/src/spec-bridge/bridges/page.ts +0 -136
  97. package/src/spec-bridge/index.ts +0 -14
  98. package/src/spec-bridge/types.ts +0 -38
  99. package/src/utils/i18n.ts +0 -10
  100. package/tsconfig.json +0 -17
  101. package/tsconfig.tsbuildinfo +0 -1
  102. package/vitest.config.ts +0 -2
@@ -1,246 +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 } from 'react';
10
-
11
- // ---------------------------------------------------------------------------
12
- // Types aligned with @objectstack/spec v2.0.7 PerformanceConfigSchema
13
- // ---------------------------------------------------------------------------
14
-
15
- /** Cache strategy for data fetching. */
16
- export type CacheStrategyType =
17
- | 'none'
18
- | 'cache-first'
19
- | 'network-first'
20
- | 'stale-while-revalidate';
21
-
22
- /** Virtual scroll configuration. */
23
- export interface VirtualScrollConfig {
24
- enabled?: boolean;
25
- itemHeight?: number;
26
- overscan?: number;
27
- }
28
-
29
- /** Performance configuration aligned with PerformanceConfigSchema. */
30
- export interface PerformanceConfig {
31
- /** Whether to lazy-load components/data. */
32
- lazyLoad?: boolean;
33
- /** Virtual scroll settings for large lists. */
34
- virtualScroll?: VirtualScrollConfig;
35
- /** Cache strategy for data fetching. */
36
- cacheStrategy?: CacheStrategyType;
37
- /** Whether to prefetch linked resources. */
38
- prefetch?: boolean;
39
- /** Default page size for paginated views. */
40
- pageSize?: number;
41
- /** Debounce interval in milliseconds for user input. */
42
- debounceMs?: number;
43
- }
44
-
45
- /** Web Vitals metrics snapshot. */
46
- export interface PerformanceMetrics {
47
- /** Largest Contentful Paint (ms). */
48
- lcp: number | null;
49
- /** First Contentful Paint (ms). */
50
- fcp: number | null;
51
- /** Time to Interactive (ms). */
52
- tti: number | null;
53
- /** Total render count since mount. */
54
- renderCount: number;
55
- /** Last render duration (ms). */
56
- lastRenderDuration: number | null;
57
- }
58
-
59
- /** Result returned by the usePerformance hook. */
60
- export interface PerformanceResult {
61
- /** The resolved performance configuration (with defaults). */
62
- config: Required<Omit<PerformanceConfig, 'virtualScroll'>> & {
63
- virtualScroll: Required<VirtualScrollConfig>;
64
- };
65
- /** Current performance metrics. */
66
- metrics: PerformanceMetrics;
67
- /** Mark a rendering start (returns stop function). */
68
- markRenderStart: () => () => void;
69
- /** Create a debounced version of a callback. */
70
- debounce: <T extends (...args: unknown[]) => void>(fn: T) => T;
71
- }
72
-
73
- // ---------------------------------------------------------------------------
74
- // Defaults
75
- // ---------------------------------------------------------------------------
76
-
77
- const DEFAULTS = {
78
- lazyLoad: true,
79
- cacheStrategy: 'stale-while-revalidate' as CacheStrategyType,
80
- prefetch: false,
81
- pageSize: 50,
82
- debounceMs: 300,
83
- virtualScroll: {
84
- enabled: false,
85
- itemHeight: 40,
86
- overscan: 5,
87
- },
88
- } as const;
89
-
90
- // ---------------------------------------------------------------------------
91
- // Helpers
92
- // ---------------------------------------------------------------------------
93
-
94
- function getFCP(): number | null {
95
- if (typeof performance === 'undefined' || !performance.getEntriesByType) return null;
96
- try {
97
- const entries = performance.getEntriesByType('paint');
98
- const entry = entries.find((e) => e.name === 'first-contentful-paint');
99
- return entry ? Math.round(entry.startTime) : null;
100
- } catch {
101
- return null;
102
- }
103
- }
104
-
105
- function getLCP(): number | null {
106
- if (typeof performance === 'undefined' || !performance.getEntriesByType) return null;
107
- try {
108
- const entries = performance.getEntriesByType('largest-contentful-paint');
109
- const entry = entries.length > 0 ? entries[entries.length - 1] : undefined;
110
- return entry ? Math.round(entry.startTime) : null;
111
- } catch {
112
- return null;
113
- }
114
- }
115
-
116
- // ---------------------------------------------------------------------------
117
- // usePerformance hook
118
- // ---------------------------------------------------------------------------
119
-
120
- /**
121
- * Hook for performance monitoring and configuration aligned with
122
- * PerformanceConfigSchema from @objectstack/spec v2.0.7.
123
- *
124
- * Provides resolved config values, Web Vitals metrics, and utility functions
125
- * (debounce, render marking) for performance-aware components.
126
- *
127
- * @example
128
- * ```tsx
129
- * function DataGrid({ data }: { data: unknown[] }) {
130
- * const perf = usePerformance({
131
- * lazyLoad: true,
132
- * virtualScroll: { enabled: true, itemHeight: 40 },
133
- * debounceMs: 200,
134
- * });
135
- *
136
- * const handleSearch = perf.debounce((query: string) => {
137
- * // debounced search
138
- * });
139
- *
140
- * return (
141
- * <div>
142
- * {perf.config.virtualScroll.enabled
143
- * ? <VirtualList itemHeight={perf.config.virtualScroll.itemHeight} />
144
- * : <NormalList />}
145
- * </div>
146
- * );
147
- * }
148
- * ```
149
- */
150
- export function usePerformance(userConfig: PerformanceConfig = {}): PerformanceResult {
151
- const config = useMemo(
152
- () => ({
153
- lazyLoad: userConfig.lazyLoad ?? DEFAULTS.lazyLoad,
154
- cacheStrategy: userConfig.cacheStrategy ?? DEFAULTS.cacheStrategy,
155
- prefetch: userConfig.prefetch ?? DEFAULTS.prefetch,
156
- pageSize: userConfig.pageSize ?? DEFAULTS.pageSize,
157
- debounceMs: userConfig.debounceMs ?? DEFAULTS.debounceMs,
158
- virtualScroll: {
159
- enabled: userConfig.virtualScroll?.enabled ?? DEFAULTS.virtualScroll.enabled,
160
- itemHeight: userConfig.virtualScroll?.itemHeight ?? DEFAULTS.virtualScroll.itemHeight,
161
- overscan: userConfig.virtualScroll?.overscan ?? DEFAULTS.virtualScroll.overscan,
162
- },
163
- }),
164
- [
165
- userConfig.lazyLoad,
166
- userConfig.cacheStrategy,
167
- userConfig.prefetch,
168
- userConfig.pageSize,
169
- userConfig.debounceMs,
170
- userConfig.virtualScroll?.enabled,
171
- userConfig.virtualScroll?.itemHeight,
172
- userConfig.virtualScroll?.overscan,
173
- ],
174
- );
175
-
176
- const [metrics, setMetrics] = useState<PerformanceMetrics>({
177
- lcp: null,
178
- fcp: null,
179
- tti: null,
180
- renderCount: 0,
181
- lastRenderDuration: null,
182
- });
183
-
184
- // Collect paint metrics on mount
185
- useEffect(() => {
186
- // Defer metric collection to allow paint entries to populate
187
- const timer = setTimeout(() => {
188
- setMetrics((prev) => ({
189
- ...prev,
190
- fcp: getFCP(),
191
- lcp: getLCP(),
192
- }));
193
- }, 0);
194
- return () => clearTimeout(timer);
195
- }, []);
196
-
197
- const markRenderStart = useCallback((): (() => void) => {
198
- const start = typeof performance !== 'undefined' ? performance.now() : Date.now();
199
- return () => {
200
- const end = typeof performance !== 'undefined' ? performance.now() : Date.now();
201
- const duration = Math.round((end - start) * 100) / 100;
202
- setMetrics((prev) => ({ ...prev, lastRenderDuration: duration, renderCount: prev.renderCount + 1 }));
203
- };
204
- }, []);
205
-
206
- const debounceMs = config.debounceMs;
207
- const timersRef = useRef<Set<ReturnType<typeof setTimeout>>>(new Set());
208
-
209
- const debounce = useCallback(
210
- <T extends (...args: unknown[]) => void>(fn: T): T => {
211
- let timer: ReturnType<typeof setTimeout> | null = null;
212
- const debounced = (...args: unknown[]) => {
213
- if (timer) {
214
- clearTimeout(timer);
215
- timersRef.current.delete(timer);
216
- }
217
- timer = setTimeout(() => {
218
- fn(...args);
219
- if (timer) timersRef.current.delete(timer);
220
- }, debounceMs);
221
- timersRef.current.add(timer);
222
- };
223
- return debounced as unknown as T;
224
- },
225
- [debounceMs],
226
- );
227
-
228
- // Cleanup all debounce timers
229
- useEffect(() => {
230
- const timers = timersRef.current;
231
- return () => {
232
- timers.forEach((t) => clearTimeout(t));
233
- timers.clear();
234
- };
235
- }, []);
236
-
237
- return useMemo(
238
- () => ({
239
- config,
240
- metrics,
241
- markRenderStart,
242
- debounce,
243
- }),
244
- [config, metrics, markRenderStart, debounce],
245
- );
246
- }
@@ -1,313 +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 } 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 && (globalThis as any).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
- }
@@ -1,53 +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 { 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
- }