@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,280 @@
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
+ }
@@ -0,0 +1,325 @@
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
+ }