@object-ui/react 0.5.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/dist/LazyPluginLoader.d.ts +44 -0
  4. package/dist/LazyPluginLoader.js +92 -3
  5. package/dist/SchemaRenderer.d.ts +20 -1
  6. package/dist/SchemaRenderer.js +76 -13
  7. package/dist/components/form/FieldFactory.js +44 -40
  8. package/dist/components/form/FormRenderer.js +45 -3
  9. package/dist/context/ActionContext.d.ts +76 -0
  10. package/dist/context/ActionContext.js +139 -0
  11. package/dist/context/DndContext.d.ts +135 -0
  12. package/dist/context/DndContext.js +120 -0
  13. package/dist/context/NotificationContext.d.ts +113 -0
  14. package/dist/context/NotificationContext.js +130 -0
  15. package/dist/context/ThemeContext.d.ts +94 -0
  16. package/dist/context/ThemeContext.js +215 -0
  17. package/dist/context/index.d.ts +4 -0
  18. package/dist/context/index.js +4 -0
  19. package/dist/hooks/index.d.ts +22 -0
  20. package/dist/hooks/index.js +22 -0
  21. package/dist/hooks/useActionRunner.d.ts +21 -7
  22. package/dist/hooks/useActionRunner.js +27 -7
  23. package/dist/hooks/useAnimation.d.ts +46 -0
  24. package/dist/hooks/useAnimation.js +59 -0
  25. package/dist/hooks/useClientNotifications.d.ts +53 -0
  26. package/dist/hooks/useClientNotifications.js +190 -0
  27. package/dist/hooks/useColumnSummary.d.ts +38 -0
  28. package/dist/hooks/useColumnSummary.js +54 -0
  29. package/dist/hooks/useCrudShortcuts.d.ts +39 -0
  30. package/dist/hooks/useCrudShortcuts.js +96 -0
  31. package/dist/hooks/useDensityMode.d.ts +48 -0
  32. package/dist/hooks/useDensityMode.js +60 -0
  33. package/dist/hooks/useDiscovery.d.ts +78 -0
  34. package/dist/hooks/useDiscovery.js +96 -0
  35. package/dist/hooks/useDynamicApp.d.ts +70 -0
  36. package/dist/hooks/useDynamicApp.js +92 -0
  37. package/dist/hooks/useETagCache.d.ts +75 -0
  38. package/dist/hooks/useETagCache.js +306 -0
  39. package/dist/hooks/useFocusManagement.d.ts +89 -0
  40. package/dist/hooks/useFocusManagement.js +188 -0
  41. package/dist/hooks/useFocusTrap.d.ts +41 -0
  42. package/dist/hooks/useFocusTrap.js +103 -0
  43. package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
  44. package/dist/hooks/useKeyboardShortcuts.js +86 -0
  45. package/dist/hooks/useNavigationOverlay.d.ts +78 -0
  46. package/dist/hooks/useNavigationOverlay.js +112 -0
  47. package/dist/hooks/useOffline.d.ts +96 -0
  48. package/dist/hooks/useOffline.js +185 -0
  49. package/dist/hooks/usePageTransition.d.ts +60 -0
  50. package/dist/hooks/usePageTransition.js +111 -0
  51. package/dist/hooks/usePageVariables.d.ts +67 -0
  52. package/dist/hooks/usePageVariables.js +109 -0
  53. package/dist/hooks/usePerformance.d.ts +87 -0
  54. package/dist/hooks/usePerformance.js +165 -0
  55. package/dist/hooks/usePerformanceBudget.d.ts +78 -0
  56. package/dist/hooks/usePerformanceBudget.js +209 -0
  57. package/dist/hooks/useReducedMotion.d.ts +28 -0
  58. package/dist/hooks/useReducedMotion.js +48 -0
  59. package/dist/hooks/useSchemaPersistence.d.ts +87 -0
  60. package/dist/hooks/useSchemaPersistence.js +173 -0
  61. package/dist/hooks/useViewData.d.ts +73 -0
  62. package/dist/hooks/useViewData.js +135 -0
  63. package/dist/hooks/useViewSharing.d.ts +57 -0
  64. package/dist/hooks/useViewSharing.js +74 -0
  65. package/dist/hooks/useViewTransition.d.ts +54 -0
  66. package/dist/hooks/useViewTransition.js +83 -0
  67. package/dist/index.d.ts +1 -0
  68. package/dist/index.js +2 -0
  69. package/dist/utils/i18n.d.ts +10 -0
  70. package/dist/utils/i18n.js +12 -0
  71. package/package.json +7 -5
  72. package/src/LazyPluginLoader.tsx +129 -7
  73. package/src/SchemaRenderer.tsx +122 -13
  74. package/src/__tests__/LazyPluginLoader.test.tsx +97 -1
  75. package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
  76. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
  77. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
  78. package/src/__tests__/ThemeProvider.test.tsx +451 -0
  79. package/src/__tests__/useNavigationOverlay.test.ts +416 -0
  80. package/src/__tests__/useOffline.test.ts +198 -0
  81. package/src/__tests__/usePageTransition.test.ts +214 -0
  82. package/src/__tests__/usePageVariables.test.tsx +334 -0
  83. package/src/__tests__/usePerformance.test.ts +137 -0
  84. package/src/__tests__/useViewData.test.tsx +422 -0
  85. package/src/__tests__/view-switching.test.tsx +456 -0
  86. package/src/components/form/FieldFactory.tsx +51 -46
  87. package/src/components/form/FormRenderer.test.tsx +145 -0
  88. package/src/components/form/FormRenderer.tsx +52 -3
  89. package/src/context/ActionContext.tsx +213 -0
  90. package/src/context/DndContext.tsx +260 -0
  91. package/src/context/NotificationContext.tsx +280 -0
  92. package/src/context/ThemeContext.tsx +325 -0
  93. package/src/context/__tests__/ActionContext.test.tsx +174 -0
  94. package/src/context/__tests__/DndContext.test.tsx +150 -0
  95. package/src/context/__tests__/NotificationContext.test.tsx +176 -0
  96. package/src/context/index.ts +4 -0
  97. package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
  98. package/src/hooks/__tests__/useAnimation.test.ts +82 -0
  99. package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
  100. package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
  101. package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
  102. package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
  103. package/src/hooks/__tests__/useETagCache.test.ts +153 -0
  104. package/src/hooks/__tests__/useExpression.test.ts +86 -0
  105. package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
  106. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
  107. package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
  108. package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
  109. package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
  110. package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
  111. package/src/hooks/index.ts +22 -1
  112. package/src/hooks/useActionRunner.ts +49 -11
  113. package/src/hooks/useAnimation.ts +117 -0
  114. package/src/hooks/useClientNotifications.ts +251 -0
  115. package/src/hooks/useColumnSummary.ts +87 -0
  116. package/src/hooks/useCrudShortcuts.ts +126 -0
  117. package/src/hooks/useDensityMode.ts +102 -0
  118. package/src/hooks/useDiscovery.ts +141 -0
  119. package/src/hooks/useDynamicApp.ts +142 -0
  120. package/src/hooks/useETagCache.ts +404 -0
  121. package/src/hooks/useFocusManagement.ts +248 -0
  122. package/src/hooks/useFocusTrap.ts +138 -0
  123. package/src/hooks/useKeyboardShortcuts.ts +119 -0
  124. package/src/hooks/useNavigationOverlay.ts +180 -0
  125. package/src/hooks/useOffline.ts +301 -0
  126. package/src/hooks/usePageTransition.ts +187 -0
  127. package/src/hooks/usePageVariables.tsx +157 -0
  128. package/src/hooks/usePerformance.ts +246 -0
  129. package/src/hooks/usePerformanceBudget.ts +313 -0
  130. package/src/hooks/useReducedMotion.ts +53 -0
  131. package/src/hooks/useSchemaPersistence.ts +222 -0
  132. package/src/hooks/useViewData.ts +201 -0
  133. package/src/hooks/useViewSharing.ts +140 -0
  134. package/src/hooks/useViewTransition.ts +144 -0
  135. package/src/index.ts +21 -0
  136. package/src/utils/i18n.ts +10 -0
  137. package/tsconfig.json +1 -0
  138. package/tsconfig.tsbuildinfo +1 -1
  139. package/dist/__tests__/LazyPluginLoader.test.d.ts +0 -8
  140. package/dist/__tests__/LazyPluginLoader.test.js +0 -49
  141. package/dist/components/form/FormRenderer.test.d.ts +0 -8
  142. package/dist/components/form/FormRenderer.test.js +0 -534
  143. package/dist/index.test.d.ts +0 -8
  144. package/dist/index.test.js +0 -13
@@ -0,0 +1,246 @@
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
+ }
@@ -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
+ }