@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,280 +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
- /**
10
- * @object-ui/react - Notification Context
11
- *
12
- * Provides a spec-driven notification system to the component tree.
13
- * Implements NotificationSchema, NotificationConfigSchema, and
14
- * NotificationActionSchema from @objectstack/spec v2.0.7.
15
- */
16
-
17
- import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
18
-
19
- /** Notification severity levels aligned with NotificationSeveritySchema */
20
- export type NotificationSeverityLevel = 'info' | 'success' | 'warning' | 'error';
21
-
22
- /** Notification display type aligned with NotificationTypeSchema */
23
- export type NotificationDisplayType = 'toast' | 'banner' | 'snackbar' | 'modal';
24
-
25
- /** Notification position aligned with NotificationPositionSchema */
26
- export type NotificationPositionValue =
27
- | 'top-left'
28
- | 'top-center'
29
- | 'top-right'
30
- | 'bottom-left'
31
- | 'bottom-center'
32
- | 'bottom-right';
33
-
34
- /** Action button on a notification */
35
- export interface NotificationActionButton {
36
- label: string;
37
- onClick: () => void;
38
- variant?: 'default' | 'destructive' | 'outline';
39
- }
40
-
41
- /** A single notification item */
42
- export interface NotificationItem {
43
- id: string;
44
- title: string;
45
- message?: string;
46
- severity: NotificationSeverityLevel;
47
- displayType?: NotificationDisplayType;
48
- actions?: NotificationActionButton[];
49
- /** Duration in ms (0 = persistent). Default: 5000 */
50
- duration?: number;
51
- /** Whether the notification has been read */
52
- read?: boolean;
53
- /** Timestamp */
54
- createdAt: Date;
55
- /** Optional icon name (lucide icon) */
56
- icon?: string;
57
- }
58
-
59
- /** Configuration for the notification system */
60
- export interface NotificationSystemConfig {
61
- /** Default position for toast notifications */
62
- position?: NotificationPositionValue;
63
- /** Default duration in ms */
64
- defaultDuration?: number;
65
- /** Maximum number of visible notifications */
66
- maxVisible?: number;
67
- /** Whether to stack notifications */
68
- stacking?: boolean;
69
- }
70
-
71
- export interface NotificationProviderProps {
72
- children: React.ReactNode;
73
- /** System configuration */
74
- config?: NotificationSystemConfig;
75
- /** External toast handler (e.g., Sonner) for rendering toasts */
76
- onToast?: (notification: NotificationItem) => void;
77
- }
78
-
79
- interface NotificationContextValue {
80
- /** All notifications (including history) */
81
- notifications: NotificationItem[];
82
- /** Unread notification count */
83
- unreadCount: number;
84
- /** Add a notification */
85
- notify: (notification: Omit<NotificationItem, 'id' | 'createdAt' | 'read'>) => string;
86
- /** Convenience: show info notification */
87
- info: (title: string, message?: string) => string;
88
- /** Convenience: show success notification */
89
- success: (title: string, message?: string) => string;
90
- /** Convenience: show warning notification */
91
- warning: (title: string, message?: string) => string;
92
- /** Convenience: show error notification */
93
- error: (title: string, message?: string) => string;
94
- /** Mark a notification as read */
95
- markAsRead: (id: string) => void;
96
- /** Mark all notifications as read */
97
- markAllAsRead: () => void;
98
- /** Dismiss a notification */
99
- dismiss: (id: string) => void;
100
- /** Clear all notifications */
101
- clearAll: () => void;
102
- /** System configuration */
103
- config: NotificationSystemConfig;
104
- }
105
-
106
- let notificationCounter = 0;
107
-
108
- const NotificationCtx = createContext<NotificationContextValue | null>(null);
109
-
110
- /**
111
- * NotificationProvider — Provides a spec-driven notification system.
112
- *
113
- * @example
114
- * ```tsx
115
- * <NotificationProvider
116
- * config={{ position: 'top-right', defaultDuration: 5000, maxVisible: 5 }}
117
- * onToast={(n) => toast[n.severity](n.title, { description: n.message })}
118
- * >
119
- * <App />
120
- * </NotificationProvider>
121
- * ```
122
- */
123
- export const NotificationProvider: React.FC<NotificationProviderProps> = ({
124
- children,
125
- config: userConfig = {},
126
- onToast,
127
- }) => {
128
- const config = useMemo<NotificationSystemConfig>(
129
- () => ({
130
- position: 'top-right',
131
- defaultDuration: 5000,
132
- maxVisible: 5,
133
- stacking: true,
134
- ...userConfig,
135
- }),
136
- // eslint-disable-next-line react-hooks/exhaustive-deps
137
- [JSON.stringify(userConfig)],
138
- );
139
-
140
- const [notifications, setNotifications] = useState<NotificationItem[]>([]);
141
-
142
- const notify = useCallback(
143
- (input: Omit<NotificationItem, 'id' | 'createdAt' | 'read'>): string => {
144
- const id = `notification-${++notificationCounter}`;
145
- const notification: NotificationItem = {
146
- ...input,
147
- id,
148
- createdAt: new Date(),
149
- read: false,
150
- };
151
-
152
- setNotifications((prev) => [notification, ...prev]);
153
-
154
- // Delegate to external toast handler if provided
155
- if (onToast) {
156
- onToast(notification);
157
- }
158
-
159
- // Auto-dismiss non-persistent notifications
160
- const duration = input.duration ?? config.defaultDuration ?? 5000;
161
- if (duration > 0) {
162
- setTimeout(() => {
163
- setNotifications((prev) => prev.filter((n) => n.id !== id));
164
- }, duration);
165
- }
166
-
167
- return id;
168
- },
169
- [config.defaultDuration, onToast],
170
- );
171
-
172
- const info = useCallback(
173
- (title: string, message?: string) =>
174
- notify({ title, message, severity: 'info' }),
175
- [notify],
176
- );
177
-
178
- const success = useCallback(
179
- (title: string, message?: string) =>
180
- notify({ title, message, severity: 'success' }),
181
- [notify],
182
- );
183
-
184
- const warning = useCallback(
185
- (title: string, message?: string) =>
186
- notify({ title, message, severity: 'warning' }),
187
- [notify],
188
- );
189
-
190
- const error = useCallback(
191
- (title: string, message?: string) =>
192
- notify({ title, message, severity: 'error' }),
193
- [notify],
194
- );
195
-
196
- const markAsRead = useCallback((id: string) => {
197
- setNotifications((prev) =>
198
- prev.map((n) => (n.id === id ? { ...n, read: true } : n)),
199
- );
200
- }, []);
201
-
202
- const markAllAsRead = useCallback(() => {
203
- setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
204
- }, []);
205
-
206
- const dismiss = useCallback((id: string) => {
207
- setNotifications((prev) => prev.filter((n) => n.id !== id));
208
- }, []);
209
-
210
- const clearAll = useCallback(() => {
211
- setNotifications([]);
212
- }, []);
213
-
214
- const unreadCount = useMemo(
215
- () => notifications.filter((n) => !n.read).length,
216
- [notifications],
217
- );
218
-
219
- const value = useMemo<NotificationContextValue>(
220
- () => ({
221
- notifications,
222
- unreadCount,
223
- notify,
224
- info,
225
- success,
226
- warning,
227
- error,
228
- markAsRead,
229
- markAllAsRead,
230
- dismiss,
231
- clearAll,
232
- config,
233
- }),
234
- [
235
- notifications,
236
- unreadCount,
237
- notify,
238
- info,
239
- success,
240
- warning,
241
- error,
242
- markAsRead,
243
- markAllAsRead,
244
- dismiss,
245
- clearAll,
246
- config,
247
- ],
248
- );
249
-
250
- return (
251
- <NotificationCtx.Provider value={value}>
252
- {children}
253
- </NotificationCtx.Provider>
254
- );
255
- };
256
-
257
- NotificationProvider.displayName = 'NotificationProvider';
258
-
259
- /**
260
- * Hook to consume the NotificationProvider context.
261
- *
262
- * @throws Error if used outside a NotificationProvider
263
- */
264
- export function useNotifications(): NotificationContextValue {
265
- const ctx = useContext(NotificationCtx);
266
- if (!ctx) {
267
- throw new Error(
268
- 'useNotifications must be used within a <NotificationProvider>. ' +
269
- 'Wrap your app with <NotificationProvider> to use the notification system.',
270
- );
271
- }
272
- return ctx;
273
- }
274
-
275
- /**
276
- * Hook to check if a NotificationProvider is available.
277
- */
278
- export function useHasNotificationProvider(): boolean {
279
- return useContext(NotificationCtx) !== null;
280
- }
@@ -1,48 +0,0 @@
1
- import React, { createContext, useContext, useMemo } from 'react';
2
- import type { DebugFlags } from '@object-ui/core';
3
-
4
- interface SchemaRendererContextType {
5
- dataSource: any;
6
- debug?: boolean;
7
- debugFlags?: DebugFlags;
8
- }
9
-
10
- const SchemaRendererContext = createContext<SchemaRendererContextType | null>(null);
11
-
12
- export { SchemaRendererContext };
13
-
14
- export const SchemaRendererProvider = ({
15
- children,
16
- dataSource,
17
- debug,
18
- debugFlags,
19
- }: {
20
- children: React.ReactNode;
21
- dataSource: any;
22
- debug?: boolean;
23
- debugFlags?: DebugFlags;
24
- }) => {
25
- const value = useMemo(() => ({ dataSource, debug, debugFlags }), [dataSource, debug, debugFlags]);
26
- return (
27
- <SchemaRendererContext.Provider value={value}>
28
- {children}
29
- </SchemaRendererContext.Provider>
30
- );
31
- };
32
-
33
- export const useSchemaContext = () => {
34
- const context = useContext(SchemaRendererContext);
35
- if (!context) {
36
- throw new Error('useSchemaContext must be used within a SchemaRendererProvider');
37
- }
38
- return context;
39
- };
40
-
41
- export const useDataScope = (path?: string) => {
42
- const context = useContext(SchemaRendererContext);
43
- const dataSource = context?.dataSource;
44
- if (!path) return undefined;
45
- if (!dataSource) return undefined;
46
- // Simple path resolution for now. In real app might be more complex
47
- return path.split('.').reduce((acc, part) => acc && acc[part], dataSource);
48
- }
@@ -1,325 +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
- /**
10
- * @object-ui/react - ThemeContext
11
- *
12
- * React context + provider for the Theme System.
13
- * Converts a spec-aligned Theme JSON into CSS custom properties
14
- * and manages mode switching, theme registration, and persistence.
15
- *
16
- * @module context/ThemeContext
17
- * @packageDocumentation
18
- */
19
-
20
- import React, {
21
- createContext,
22
- useContext,
23
- useState,
24
- useEffect,
25
- useMemo,
26
- useCallback,
27
- } from 'react';
28
- import type { Theme, ThemeMode } from '@object-ui/types';
29
- import {
30
- generateThemeVars,
31
- mergeThemes,
32
- resolveThemeInheritance,
33
- resolveMode,
34
- } from '@object-ui/core';
35
-
36
- // ============================================================================
37
- // Types
38
- // ============================================================================
39
-
40
- /**
41
- * The public API surface of the theme system, available via useTheme().
42
- */
43
- export interface ThemeContextValue {
44
- /** The fully resolved active theme (after inheritance) */
45
- theme: Theme | null;
46
-
47
- /** The effective mode: 'light' or 'dark' (resolved from 'auto') */
48
- resolvedMode: 'light' | 'dark';
49
-
50
- /** The raw mode setting (may be 'auto') */
51
- mode: ThemeMode;
52
-
53
- /** Name of the active theme */
54
- activeTheme: string | null;
55
-
56
- /** List of available themes */
57
- themes: Theme[];
58
-
59
- /** Switch to a different theme by name */
60
- setTheme: (name: string) => void;
61
-
62
- /** Switch mode (light / dark / auto) */
63
- setMode: (mode: ThemeMode) => void;
64
-
65
- /** The generated CSS custom property map */
66
- cssVars: Record<string, string>;
67
- }
68
-
69
- /**
70
- * Props for the ThemeProvider component.
71
- */
72
- export interface ThemeProviderProps {
73
- /** Available theme definitions */
74
- themes?: Theme[];
75
-
76
- /** Initial active theme name (default: first theme) */
77
- defaultTheme?: string;
78
-
79
- /** Initial mode (default: 'auto') */
80
- defaultMode?: ThemeMode;
81
-
82
- /** Persist theme/mode to localStorage */
83
- persist?: boolean;
84
-
85
- /** localStorage key prefix */
86
- storageKey?: string;
87
-
88
- /** Target element for CSS variable injection (default: document.documentElement) */
89
- target?: HTMLElement | null;
90
-
91
- /** Children */
92
- children: React.ReactNode;
93
- }
94
-
95
- // ============================================================================
96
- // Context
97
- // ============================================================================
98
-
99
- const ThemeContext = createContext<ThemeContextValue | null>(null);
100
-
101
- /**
102
- * Default storage keys
103
- */
104
- const DEFAULT_STORAGE_KEY = 'objectui-theme';
105
-
106
- // ============================================================================
107
- // Provider
108
- // ============================================================================
109
-
110
- /**
111
- * ThemeProvider
112
- *
113
- * Wraps a subtree with theme context. It:
114
- * 1. Maintains theme + mode state
115
- * 2. Resolves theme inheritance (extends)
116
- * 3. Converts the active theme → CSS custom properties
117
- * 4. Injects those CSS variables into the DOM
118
- * 5. Applies 'dark' / 'light' class to the target element
119
- * 6. Optionally persists user preference to localStorage
120
- *
121
- * @example
122
- * ```tsx
123
- * <ThemeProvider themes={[myTheme]} defaultTheme="my-theme" defaultMode="auto">
124
- * <App />
125
- * </ThemeProvider>
126
- * ```
127
- */
128
- export function ThemeProvider({
129
- themes: themesInput = [],
130
- defaultTheme,
131
- defaultMode = 'auto',
132
- persist = false,
133
- storageKey = DEFAULT_STORAGE_KEY,
134
- target,
135
- children,
136
- }: ThemeProviderProps) {
137
- // ---- Build theme registry ----
138
- const registry = useMemo(() => {
139
- const map = new Map<string, Theme>();
140
- for (const t of themesInput) {
141
- map.set(t.name, t);
142
- }
143
- return map;
144
- }, [themesInput]);
145
-
146
- // ---- Load persisted state ----
147
- const loadPersistedTheme = useCallback((): string | undefined => {
148
- if (!persist) return undefined;
149
- try {
150
- if (typeof window !== 'undefined') {
151
- return localStorage.getItem(`${storageKey}-name`) ?? undefined;
152
- }
153
- } catch { /* ignore */ }
154
- return undefined;
155
- }, [persist, storageKey]);
156
-
157
- const loadPersistedMode = useCallback((): ThemeMode | undefined => {
158
- if (!persist) return undefined;
159
- try {
160
- if (typeof window !== 'undefined') {
161
- const stored = localStorage.getItem(`${storageKey}-mode`);
162
- if (stored === 'light' || stored === 'dark' || stored === 'auto') {
163
- return stored;
164
- }
165
- }
166
- } catch { /* ignore */ }
167
- return undefined;
168
- }, [persist, storageKey]);
169
-
170
- // ---- State ----
171
- const [activeThemeName, setActiveThemeName] = useState<string | null>(
172
- () => loadPersistedTheme() ?? defaultTheme ?? themesInput[0]?.name ?? null,
173
- );
174
-
175
- const [mode, setModeState] = useState<ThemeMode>(
176
- () => loadPersistedMode() ?? defaultMode,
177
- );
178
-
179
- // ---- Resolve theme ----
180
- const resolvedTheme = useMemo(() => {
181
- if (!activeThemeName) return null;
182
- const base = registry.get(activeThemeName);
183
- if (!base) return null;
184
- return resolveThemeInheritance(base, registry);
185
- }, [activeThemeName, registry]);
186
-
187
- // ---- Resolve mode ----
188
- const [systemDark, setSystemDark] = useState<boolean>(() => {
189
- if (typeof window !== 'undefined' && window.matchMedia) {
190
- return window.matchMedia('(prefers-color-scheme: dark)').matches;
191
- }
192
- return false;
193
- });
194
-
195
- // Listen to system preference changes
196
- useEffect(() => {
197
- if (typeof window === 'undefined' || !window.matchMedia) return;
198
- const mq = window.matchMedia('(prefers-color-scheme: dark)');
199
- const handler = (e: MediaQueryListEvent) => setSystemDark(e.matches);
200
- mq.addEventListener('change', handler);
201
- return () => mq.removeEventListener('change', handler);
202
- }, []);
203
-
204
- const resolvedMode = useMemo(
205
- () => resolveMode(mode, systemDark),
206
- [mode, systemDark],
207
- );
208
-
209
- // ---- Generate CSS variables ----
210
- const cssVars = useMemo(() => {
211
- if (!resolvedTheme) return {};
212
- return generateThemeVars(resolvedTheme);
213
- }, [resolvedTheme]);
214
-
215
- // ---- Inject CSS variables into the DOM ----
216
- useEffect(() => {
217
- const el = target ?? (typeof document !== 'undefined' ? document.documentElement : null);
218
- if (!el) return;
219
-
220
- // Apply CSS variables
221
- const previousValues: Record<string, string> = {};
222
- for (const [prop, value] of Object.entries(cssVars)) {
223
- previousValues[prop] = el.style.getPropertyValue(prop);
224
- el.style.setProperty(prop, value);
225
- }
226
-
227
- // Apply mode class
228
- el.classList.remove('light', 'dark');
229
- el.classList.add(resolvedMode);
230
-
231
- // Apply logo / favicon
232
- if (resolvedTheme?.logo?.favicon && typeof document !== 'undefined') {
233
- const link = document.querySelector<HTMLLinkElement>('link[rel="icon"]')
234
- ?? document.querySelector<HTMLLinkElement>('#favicon');
235
- if (link) {
236
- link.href = resolvedTheme.logo.favicon;
237
- }
238
- }
239
-
240
- return () => {
241
- // Cleanup: remove injected vars
242
- for (const prop of Object.keys(cssVars)) {
243
- if (previousValues[prop]) {
244
- el.style.setProperty(prop, previousValues[prop]);
245
- } else {
246
- el.style.removeProperty(prop);
247
- }
248
- }
249
- el.classList.remove(resolvedMode);
250
- };
251
- }, [cssVars, resolvedMode, resolvedTheme, target]);
252
-
253
- // ---- Persistence ----
254
- useEffect(() => {
255
- if (!persist) return;
256
- try {
257
- if (activeThemeName) {
258
- localStorage.setItem(`${storageKey}-name`, activeThemeName);
259
- }
260
- localStorage.setItem(`${storageKey}-mode`, mode);
261
- } catch { /* ignore */ }
262
- }, [persist, storageKey, activeThemeName, mode]);
263
-
264
- // ---- Actions ----
265
- const setTheme = useCallback((name: string) => {
266
- if (registry.has(name)) {
267
- setActiveThemeName(name);
268
- }
269
- }, [registry]);
270
-
271
- const setMode = useCallback((newMode: ThemeMode) => {
272
- setModeState(newMode);
273
- }, []);
274
-
275
- // ---- Context value ----
276
- const value = useMemo<ThemeContextValue>(
277
- () => ({
278
- theme: resolvedTheme,
279
- resolvedMode,
280
- mode,
281
- activeTheme: activeThemeName,
282
- themes: themesInput,
283
- setTheme,
284
- setMode,
285
- cssVars,
286
- }),
287
- [resolvedTheme, resolvedMode, mode, activeThemeName, themesInput, setTheme, setMode, cssVars],
288
- );
289
-
290
- return (
291
- <ThemeContext.Provider value={value}>
292
- {children}
293
- </ThemeContext.Provider>
294
- );
295
- }
296
-
297
- // ============================================================================
298
- // Hook
299
- // ============================================================================
300
-
301
- /**
302
- * useTheme — access the current theme context.
303
- *
304
- * @example
305
- * ```tsx
306
- * const { theme, resolvedMode, setMode, setTheme } = useTheme();
307
- * ```
308
- *
309
- * @throws Error if used outside a ThemeProvider
310
- */
311
- export function useTheme(): ThemeContextValue {
312
- const ctx = useContext(ThemeContext);
313
- if (!ctx) {
314
- throw new Error('useTheme must be used within a <ThemeProvider>');
315
- }
316
- return ctx;
317
- }
318
-
319
- /**
320
- * useOptionalTheme — like useTheme() but returns null outside a provider.
321
- * Useful for components that should work with or without a theme.
322
- */
323
- export function useOptionalTheme(): ThemeContextValue | null {
324
- return useContext(ThemeContext);
325
- }