@object-ui/react 0.5.0 → 2.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 (65) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +13 -0
  3. package/dist/LazyPluginLoader.d.ts +44 -0
  4. package/dist/LazyPluginLoader.js +92 -3
  5. package/dist/components/form/FieldFactory.js +44 -40
  6. package/dist/components/form/FormRenderer.js +45 -3
  7. package/dist/context/ActionContext.d.ts +76 -0
  8. package/dist/context/ActionContext.js +139 -0
  9. package/dist/context/ThemeContext.d.ts +94 -0
  10. package/dist/context/ThemeContext.js +215 -0
  11. package/dist/context/index.d.ts +2 -0
  12. package/dist/context/index.js +2 -0
  13. package/dist/hooks/index.d.ts +5 -0
  14. package/dist/hooks/index.js +5 -0
  15. package/dist/hooks/useActionRunner.d.ts +21 -7
  16. package/dist/hooks/useActionRunner.js +27 -7
  17. package/dist/hooks/useDiscovery.d.ts +78 -0
  18. package/dist/hooks/useDiscovery.js +96 -0
  19. package/dist/hooks/useDynamicApp.d.ts +70 -0
  20. package/dist/hooks/useDynamicApp.js +92 -0
  21. package/dist/hooks/useNavigationOverlay.d.ts +78 -0
  22. package/dist/hooks/useNavigationOverlay.js +112 -0
  23. package/dist/hooks/usePageVariables.d.ts +67 -0
  24. package/dist/hooks/usePageVariables.js +109 -0
  25. package/dist/hooks/useViewData.d.ts +73 -0
  26. package/dist/hooks/useViewData.js +135 -0
  27. package/dist/index.d.ts +1 -0
  28. package/dist/index.js +2 -0
  29. package/dist/utils/i18n.d.ts +10 -0
  30. package/dist/utils/i18n.js +12 -0
  31. package/package.json +6 -4
  32. package/src/LazyPluginLoader.tsx +129 -7
  33. package/src/__tests__/LazyPluginLoader.test.tsx +97 -1
  34. package/src/__tests__/ThemeProvider.test.tsx +451 -0
  35. package/src/__tests__/useNavigationOverlay.test.ts +416 -0
  36. package/src/__tests__/usePageVariables.test.tsx +334 -0
  37. package/src/__tests__/useViewData.test.tsx +422 -0
  38. package/src/components/form/FieldFactory.tsx +51 -46
  39. package/src/components/form/FormRenderer.test.tsx +145 -0
  40. package/src/components/form/FormRenderer.tsx +52 -3
  41. package/src/context/ActionContext.tsx +213 -0
  42. package/src/context/ThemeContext.tsx +325 -0
  43. package/src/context/__tests__/ActionContext.test.tsx +174 -0
  44. package/src/context/index.ts +2 -0
  45. package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
  46. package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
  47. package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
  48. package/src/hooks/__tests__/useExpression.test.ts +86 -0
  49. package/src/hooks/index.ts +5 -0
  50. package/src/hooks/useActionRunner.ts +49 -11
  51. package/src/hooks/useDiscovery.ts +141 -0
  52. package/src/hooks/useDynamicApp.ts +142 -0
  53. package/src/hooks/useNavigationOverlay.ts +180 -0
  54. package/src/hooks/usePageVariables.tsx +157 -0
  55. package/src/hooks/useViewData.ts +201 -0
  56. package/src/index.ts +21 -0
  57. package/src/utils/i18n.ts +10 -0
  58. package/tsconfig.json +1 -0
  59. package/tsconfig.tsbuildinfo +1 -1
  60. package/dist/__tests__/LazyPluginLoader.test.d.ts +0 -8
  61. package/dist/__tests__/LazyPluginLoader.test.js +0 -49
  62. package/dist/components/form/FormRenderer.test.d.ts +0 -8
  63. package/dist/components/form/FormRenderer.test.js +0 -534
  64. package/dist/index.test.d.ts +0 -8
  65. package/dist/index.test.js +0 -13
@@ -0,0 +1,213 @@
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 - Action Context
11
+ *
12
+ * Provides a shared ActionRunner instance and handlers to the component tree.
13
+ * Components can consume actions without creating their own runner instances.
14
+ */
15
+
16
+ import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
17
+ import {
18
+ ActionRunner,
19
+ type ActionContext as ActionCtx,
20
+ type ActionDef,
21
+ type ActionResult,
22
+ type ConfirmationHandler,
23
+ type ToastHandler,
24
+ type ModalHandler,
25
+ type NavigationHandler,
26
+ type ParamCollectionHandler,
27
+ } from '@object-ui/core';
28
+
29
+ export interface ActionProviderProps {
30
+ children: React.ReactNode;
31
+ /** Initial action context (record, user, data, etc.) */
32
+ context?: ActionCtx;
33
+ /** Custom confirmation handler (e.g., Shadcn AlertDialog) */
34
+ onConfirm?: ConfirmationHandler;
35
+ /** Custom toast handler (e.g., Sonner) */
36
+ onToast?: ToastHandler;
37
+ /** Custom modal handler — render modals in response to modal actions */
38
+ onModal?: ModalHandler;
39
+ /** Custom navigation handler — SPA-aware routing (e.g., React Router navigate) */
40
+ onNavigate?: NavigationHandler;
41
+ /** Custom param collection handler — show dialog to collect ActionParam values */
42
+ onParamCollection?: ParamCollectionHandler;
43
+ /** Pre-registered custom action handlers */
44
+ handlers?: Record<string, (action: ActionDef, ctx: ActionCtx) => Promise<ActionResult>>;
45
+ }
46
+
47
+ interface ActionContextValue {
48
+ /** Execute an action */
49
+ execute: (action: ActionDef) => Promise<ActionResult>;
50
+ /** Execute multiple actions in chain */
51
+ executeChain: (actions: ActionDef[], mode?: 'sequential' | 'parallel') => Promise<ActionResult>;
52
+ /** Whether an action is currently being executed */
53
+ loading: boolean;
54
+ /** Last error message */
55
+ error: string | null;
56
+ /** Last action result */
57
+ result: ActionResult | null;
58
+ /** The underlying ActionRunner instance */
59
+ runner: ActionRunner;
60
+ /** Update context data */
61
+ updateContext: (ctx: Partial<ActionCtx>) => void;
62
+ }
63
+
64
+ const ActionCtxReact = createContext<ActionContextValue | null>(null);
65
+
66
+ /**
67
+ * ActionProvider — Provides a shared ActionRunner to the tree.
68
+ *
69
+ * @example
70
+ * ```tsx
71
+ * <ActionProvider
72
+ * context={{ record: currentRecord, user }}
73
+ * onToast={(msg, opts) => toast[opts?.type ?? 'info'](msg)}
74
+ * onConfirm={async (msg) => showConfirmDialog(msg)}
75
+ * onNavigate={(url) => router.push(url)}
76
+ * >
77
+ * <SchemaRenderer schema={pageSchema} />
78
+ * </ActionProvider>
79
+ * ```
80
+ */
81
+ export const ActionProvider: React.FC<ActionProviderProps> = ({
82
+ children,
83
+ context = {},
84
+ onConfirm,
85
+ onToast,
86
+ onModal,
87
+ onNavigate,
88
+ onParamCollection,
89
+ handlers,
90
+ }) => {
91
+ const [loading, setLoading] = useState(false);
92
+ const [error, setError] = useState<string | null>(null);
93
+ const [result, setResult] = useState<ActionResult | null>(null);
94
+
95
+ const runner = useMemo(() => {
96
+ const r = new ActionRunner(context);
97
+ if (onConfirm) r.setConfirmHandler(onConfirm);
98
+ if (onToast) r.setToastHandler(onToast);
99
+ if (onModal) r.setModalHandler(onModal);
100
+ if (onNavigate) r.setNavigationHandler(onNavigate);
101
+ if (onParamCollection) r.setParamCollectionHandler(onParamCollection);
102
+ if (handlers) {
103
+ Object.entries(handlers).forEach(([name, handler]) => {
104
+ r.registerHandler(name, handler);
105
+ });
106
+ }
107
+ return r;
108
+ // eslint-disable-next-line react-hooks/exhaustive-deps
109
+ }, [JSON.stringify(context)]);
110
+
111
+ const execute = useCallback(
112
+ async (action: ActionDef): Promise<ActionResult> => {
113
+ setLoading(true);
114
+ setError(null);
115
+ setResult(null);
116
+
117
+ try {
118
+ const actionResult = await runner.execute(action);
119
+ setResult(actionResult);
120
+ if (!actionResult.success) {
121
+ setError(actionResult.error || 'Action failed');
122
+ }
123
+ return actionResult;
124
+ } catch (err) {
125
+ const errorMessage = (err as Error).message;
126
+ setError(errorMessage);
127
+ const failureResult: ActionResult = { success: false, error: errorMessage };
128
+ setResult(failureResult);
129
+ return failureResult;
130
+ } finally {
131
+ setLoading(false);
132
+ }
133
+ },
134
+ [runner],
135
+ );
136
+
137
+ const executeChain = useCallback(
138
+ async (actions: ActionDef[], mode?: 'sequential' | 'parallel'): Promise<ActionResult> => {
139
+ setLoading(true);
140
+ setError(null);
141
+ setResult(null);
142
+
143
+ try {
144
+ const actionResult = await runner.executeChain(actions, mode);
145
+ setResult(actionResult);
146
+ if (!actionResult.success) {
147
+ setError(actionResult.error || 'Chain failed');
148
+ }
149
+ return actionResult;
150
+ } catch (err) {
151
+ const errorMessage = (err as Error).message;
152
+ setError(errorMessage);
153
+ const failureResult: ActionResult = { success: false, error: errorMessage };
154
+ setResult(failureResult);
155
+ return failureResult;
156
+ } finally {
157
+ setLoading(false);
158
+ }
159
+ },
160
+ [runner],
161
+ );
162
+
163
+ const updateContext = useCallback(
164
+ (newContext: Partial<ActionCtx>) => {
165
+ runner.updateContext(newContext);
166
+ },
167
+ [runner],
168
+ );
169
+
170
+ const value = useMemo<ActionContextValue>(
171
+ () => ({ execute, executeChain, loading, error, result, runner, updateContext }),
172
+ [execute, executeChain, loading, error, result, runner, updateContext],
173
+ );
174
+
175
+ return (
176
+ <ActionCtxReact.Provider value={value}>{children}</ActionCtxReact.Provider>
177
+ );
178
+ };
179
+
180
+ ActionProvider.displayName = 'ActionProvider';
181
+
182
+ /**
183
+ * Hook to consume the ActionProvider context.
184
+ * Returns the shared ActionRunner execute function, loading state, and more.
185
+ *
186
+ * Falls back to a local ActionRunner if no ActionProvider is present.
187
+ */
188
+ export function useAction(): ActionContextValue {
189
+ const ctx = useContext(ActionCtxReact);
190
+ if (!ctx) {
191
+ // Graceful fallback: create a local runner
192
+ // This allows action components to work even without an ActionProvider
193
+ const runner = new ActionRunner();
194
+ return {
195
+ execute: (action: ActionDef) => runner.execute(action),
196
+ executeChain: (actions: ActionDef[], mode?: 'sequential' | 'parallel') =>
197
+ runner.executeChain(actions, mode),
198
+ loading: false,
199
+ error: null,
200
+ result: null,
201
+ runner,
202
+ updateContext: (ctx: Partial<ActionCtx>) => runner.updateContext(ctx),
203
+ };
204
+ }
205
+ return ctx;
206
+ }
207
+
208
+ /**
209
+ * Hook to check if an ActionProvider is available.
210
+ */
211
+ export function useHasActionProvider(): boolean {
212
+ return useContext(ActionCtxReact) !== null;
213
+ }
@@ -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
+ }
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Tests for ActionContext — ActionProvider, useAction, useHasActionProvider
3
+ */
4
+
5
+ import { describe, it, expect, vi } from 'vitest';
6
+ import { renderHook, waitFor, act } from '@testing-library/react';
7
+ import React from 'react';
8
+ import { ActionProvider, useAction, useHasActionProvider } from '../ActionContext';
9
+
10
+ describe('ActionContext', () => {
11
+ describe('useAction without ActionProvider', () => {
12
+ it('falls back to local ActionRunner with default state', () => {
13
+ const { result } = renderHook(() => useAction());
14
+
15
+ expect(result.current.loading).toBe(false);
16
+ expect(result.current.error).toBeNull();
17
+ expect(result.current.result).toBeNull();
18
+ expect(typeof result.current.execute).toBe('function');
19
+ expect(typeof result.current.executeChain).toBe('function');
20
+ expect(typeof result.current.updateContext).toBe('function');
21
+ expect(result.current.runner).toBeDefined();
22
+ });
23
+ });
24
+
25
+ describe('useHasActionProvider', () => {
26
+ it('returns false without provider', () => {
27
+ const { result } = renderHook(() => useHasActionProvider());
28
+
29
+ expect(result.current).toBe(false);
30
+ });
31
+
32
+ it('returns true with provider', () => {
33
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
34
+ React.createElement(ActionProvider, { context: {} }, children);
35
+
36
+ const { result } = renderHook(() => useHasActionProvider(), { wrapper });
37
+
38
+ expect(result.current).toBe(true);
39
+ });
40
+ });
41
+
42
+ describe('ActionProvider basic', () => {
43
+ it('children can access execute function', () => {
44
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
45
+ React.createElement(ActionProvider, { context: {} }, children);
46
+
47
+ const { result } = renderHook(() => useAction(), { wrapper });
48
+
49
+ expect(typeof result.current.execute).toBe('function');
50
+ expect(typeof result.current.executeChain).toBe('function');
51
+ expect(typeof result.current.updateContext).toBe('function');
52
+ expect(result.current.loading).toBe(false);
53
+ expect(result.current.error).toBeNull();
54
+ expect(result.current.result).toBeNull();
55
+ });
56
+ });
57
+
58
+ describe('ActionProvider execute', () => {
59
+ it('executes a toast action and returns result', async () => {
60
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
61
+ React.createElement(ActionProvider, { context: {} }, children);
62
+
63
+ const { result } = renderHook(() => useAction(), { wrapper });
64
+
65
+ let actionResult: any;
66
+ await act(async () => {
67
+ actionResult = await result.current.execute({
68
+ type: 'script',
69
+ execute: 'true',
70
+ toast: { showOnSuccess: true },
71
+ successMessage: 'Done!',
72
+ });
73
+ });
74
+
75
+ expect(actionResult.success).toBe(true);
76
+
77
+ await waitFor(() => {
78
+ expect(result.current.loading).toBe(false);
79
+ });
80
+
81
+ expect(result.current.result).toEqual(actionResult);
82
+ expect(result.current.error).toBeNull();
83
+ });
84
+ });
85
+
86
+ describe('ActionProvider execute error', () => {
87
+ it('executes an action that fails and sets error state', async () => {
88
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
89
+ React.createElement(ActionProvider, { context: {} }, children);
90
+
91
+ const { result } = renderHook(() => useAction(), { wrapper });
92
+
93
+ let actionResult: any;
94
+ await act(async () => {
95
+ actionResult = await result.current.execute({
96
+ onClick: vi.fn().mockRejectedValue(new Error('boom')),
97
+ });
98
+ });
99
+
100
+ await waitFor(() => {
101
+ expect(result.current.loading).toBe(false);
102
+ });
103
+
104
+ expect(actionResult.success).toBe(false);
105
+ expect(result.current.error).toBeTruthy();
106
+ expect(result.current.result?.success).toBe(false);
107
+ });
108
+ });
109
+
110
+ describe('ActionProvider executeChain', () => {
111
+ it('executes a chain of actions', async () => {
112
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
113
+ React.createElement(ActionProvider, { context: {} }, children);
114
+
115
+ const { result } = renderHook(() => useAction(), { wrapper });
116
+
117
+ let chainResult: any;
118
+ await act(async () => {
119
+ chainResult = await result.current.executeChain([
120
+ { type: 'script', execute: 'true' },
121
+ { type: 'script', execute: 'true' },
122
+ ]);
123
+ });
124
+
125
+ await waitFor(() => {
126
+ expect(result.current.loading).toBe(false);
127
+ });
128
+
129
+ expect(chainResult.success).toBe(true);
130
+ expect(result.current.result).toEqual(chainResult);
131
+ expect(result.current.error).toBeNull();
132
+ });
133
+ });
134
+
135
+ describe('ActionProvider updateContext', () => {
136
+ it('updateContext is callable', () => {
137
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
138
+ React.createElement(ActionProvider, { context: {} }, children);
139
+
140
+ const { result } = renderHook(() => useAction(), { wrapper });
141
+
142
+ expect(() => {
143
+ result.current.updateContext({ record: { id: 1 } });
144
+ }).not.toThrow();
145
+ });
146
+ });
147
+
148
+ describe('ActionProvider with handlers', () => {
149
+ it('invokes onToast handler when a toast action is executed', async () => {
150
+ const onToast = vi.fn();
151
+ const onNavigate = vi.fn();
152
+
153
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
154
+ React.createElement(
155
+ ActionProvider,
156
+ { context: {}, onToast, onNavigate },
157
+ children,
158
+ );
159
+
160
+ const { result } = renderHook(() => useAction(), { wrapper });
161
+
162
+ await act(async () => {
163
+ await result.current.execute({
164
+ type: 'script',
165
+ execute: 'true',
166
+ toast: { showOnSuccess: true },
167
+ successMessage: 'Saved!',
168
+ });
169
+ });
170
+
171
+ expect(onToast).toHaveBeenCalledWith('Saved!', expect.objectContaining({ type: 'success' }));
172
+ });
173
+ });
174
+ });