@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,139 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * ObjectUI
4
+ * Copyright (c) 2024-present ObjectStack Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
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
+ import { createContext, useCallback, useContext, useMemo, useState } from 'react';
16
+ import { ActionRunner, } from '@object-ui/core';
17
+ const ActionCtxReact = createContext(null);
18
+ /**
19
+ * ActionProvider — Provides a shared ActionRunner to the tree.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * <ActionProvider
24
+ * context={{ record: currentRecord, user }}
25
+ * onToast={(msg, opts) => toast[opts?.type ?? 'info'](msg)}
26
+ * onConfirm={async (msg) => showConfirmDialog(msg)}
27
+ * onNavigate={(url) => router.push(url)}
28
+ * >
29
+ * <SchemaRenderer schema={pageSchema} />
30
+ * </ActionProvider>
31
+ * ```
32
+ */
33
+ export const ActionProvider = ({ children, context = {}, onConfirm, onToast, onModal, onNavigate, onParamCollection, handlers, }) => {
34
+ const [loading, setLoading] = useState(false);
35
+ const [error, setError] = useState(null);
36
+ const [result, setResult] = useState(null);
37
+ const runner = useMemo(() => {
38
+ const r = new ActionRunner(context);
39
+ if (onConfirm)
40
+ r.setConfirmHandler(onConfirm);
41
+ if (onToast)
42
+ r.setToastHandler(onToast);
43
+ if (onModal)
44
+ r.setModalHandler(onModal);
45
+ if (onNavigate)
46
+ r.setNavigationHandler(onNavigate);
47
+ if (onParamCollection)
48
+ r.setParamCollectionHandler(onParamCollection);
49
+ if (handlers) {
50
+ Object.entries(handlers).forEach(([name, handler]) => {
51
+ r.registerHandler(name, handler);
52
+ });
53
+ }
54
+ return r;
55
+ // eslint-disable-next-line react-hooks/exhaustive-deps
56
+ }, [JSON.stringify(context)]);
57
+ const execute = useCallback(async (action) => {
58
+ setLoading(true);
59
+ setError(null);
60
+ setResult(null);
61
+ try {
62
+ const actionResult = await runner.execute(action);
63
+ setResult(actionResult);
64
+ if (!actionResult.success) {
65
+ setError(actionResult.error || 'Action failed');
66
+ }
67
+ return actionResult;
68
+ }
69
+ catch (err) {
70
+ const errorMessage = err.message;
71
+ setError(errorMessage);
72
+ const failureResult = { success: false, error: errorMessage };
73
+ setResult(failureResult);
74
+ return failureResult;
75
+ }
76
+ finally {
77
+ setLoading(false);
78
+ }
79
+ }, [runner]);
80
+ const executeChain = useCallback(async (actions, mode) => {
81
+ setLoading(true);
82
+ setError(null);
83
+ setResult(null);
84
+ try {
85
+ const actionResult = await runner.executeChain(actions, mode);
86
+ setResult(actionResult);
87
+ if (!actionResult.success) {
88
+ setError(actionResult.error || 'Chain failed');
89
+ }
90
+ return actionResult;
91
+ }
92
+ catch (err) {
93
+ const errorMessage = err.message;
94
+ setError(errorMessage);
95
+ const failureResult = { success: false, error: errorMessage };
96
+ setResult(failureResult);
97
+ return failureResult;
98
+ }
99
+ finally {
100
+ setLoading(false);
101
+ }
102
+ }, [runner]);
103
+ const updateContext = useCallback((newContext) => {
104
+ runner.updateContext(newContext);
105
+ }, [runner]);
106
+ const value = useMemo(() => ({ execute, executeChain, loading, error, result, runner, updateContext }), [execute, executeChain, loading, error, result, runner, updateContext]);
107
+ return (_jsx(ActionCtxReact.Provider, { value: value, children: children }));
108
+ };
109
+ ActionProvider.displayName = 'ActionProvider';
110
+ /**
111
+ * Hook to consume the ActionProvider context.
112
+ * Returns the shared ActionRunner execute function, loading state, and more.
113
+ *
114
+ * Falls back to a local ActionRunner if no ActionProvider is present.
115
+ */
116
+ export function useAction() {
117
+ const ctx = useContext(ActionCtxReact);
118
+ if (!ctx) {
119
+ // Graceful fallback: create a local runner
120
+ // This allows action components to work even without an ActionProvider
121
+ const runner = new ActionRunner();
122
+ return {
123
+ execute: (action) => runner.execute(action),
124
+ executeChain: (actions, mode) => runner.executeChain(actions, mode),
125
+ loading: false,
126
+ error: null,
127
+ result: null,
128
+ runner,
129
+ updateContext: (ctx) => runner.updateContext(ctx),
130
+ };
131
+ }
132
+ return ctx;
133
+ }
134
+ /**
135
+ * Hook to check if an ActionProvider is available.
136
+ */
137
+ export function useHasActionProvider() {
138
+ return useContext(ActionCtxReact) !== null;
139
+ }
@@ -0,0 +1,94 @@
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
+ * @object-ui/react - ThemeContext
10
+ *
11
+ * React context + provider for the Theme System.
12
+ * Converts a spec-aligned Theme JSON into CSS custom properties
13
+ * and manages mode switching, theme registration, and persistence.
14
+ *
15
+ * @module context/ThemeContext
16
+ * @packageDocumentation
17
+ */
18
+ import React from 'react';
19
+ import type { Theme, ThemeMode } from '@object-ui/types';
20
+ /**
21
+ * The public API surface of the theme system, available via useTheme().
22
+ */
23
+ export interface ThemeContextValue {
24
+ /** The fully resolved active theme (after inheritance) */
25
+ theme: Theme | null;
26
+ /** The effective mode: 'light' or 'dark' (resolved from 'auto') */
27
+ resolvedMode: 'light' | 'dark';
28
+ /** The raw mode setting (may be 'auto') */
29
+ mode: ThemeMode;
30
+ /** Name of the active theme */
31
+ activeTheme: string | null;
32
+ /** List of available themes */
33
+ themes: Theme[];
34
+ /** Switch to a different theme by name */
35
+ setTheme: (name: string) => void;
36
+ /** Switch mode (light / dark / auto) */
37
+ setMode: (mode: ThemeMode) => void;
38
+ /** The generated CSS custom property map */
39
+ cssVars: Record<string, string>;
40
+ }
41
+ /**
42
+ * Props for the ThemeProvider component.
43
+ */
44
+ export interface ThemeProviderProps {
45
+ /** Available theme definitions */
46
+ themes?: Theme[];
47
+ /** Initial active theme name (default: first theme) */
48
+ defaultTheme?: string;
49
+ /** Initial mode (default: 'auto') */
50
+ defaultMode?: ThemeMode;
51
+ /** Persist theme/mode to localStorage */
52
+ persist?: boolean;
53
+ /** localStorage key prefix */
54
+ storageKey?: string;
55
+ /** Target element for CSS variable injection (default: document.documentElement) */
56
+ target?: HTMLElement | null;
57
+ /** Children */
58
+ children: React.ReactNode;
59
+ }
60
+ /**
61
+ * ThemeProvider
62
+ *
63
+ * Wraps a subtree with theme context. It:
64
+ * 1. Maintains theme + mode state
65
+ * 2. Resolves theme inheritance (extends)
66
+ * 3. Converts the active theme → CSS custom properties
67
+ * 4. Injects those CSS variables into the DOM
68
+ * 5. Applies 'dark' / 'light' class to the target element
69
+ * 6. Optionally persists user preference to localStorage
70
+ *
71
+ * @example
72
+ * ```tsx
73
+ * <ThemeProvider themes={[myTheme]} defaultTheme="my-theme" defaultMode="auto">
74
+ * <App />
75
+ * </ThemeProvider>
76
+ * ```
77
+ */
78
+ export declare function ThemeProvider({ themes: themesInput, defaultTheme, defaultMode, persist, storageKey, target, children, }: ThemeProviderProps): import("react/jsx-runtime").JSX.Element;
79
+ /**
80
+ * useTheme — access the current theme context.
81
+ *
82
+ * @example
83
+ * ```tsx
84
+ * const { theme, resolvedMode, setMode, setTheme } = useTheme();
85
+ * ```
86
+ *
87
+ * @throws Error if used outside a ThemeProvider
88
+ */
89
+ export declare function useTheme(): ThemeContextValue;
90
+ /**
91
+ * useOptionalTheme — like useTheme() but returns null outside a provider.
92
+ * Useful for components that should work with or without a theme.
93
+ */
94
+ export declare function useOptionalTheme(): ThemeContextValue | null;
@@ -0,0 +1,215 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * ObjectUI
4
+ * Copyright (c) 2024-present ObjectStack Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
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
+ import { createContext, useContext, useState, useEffect, useMemo, useCallback, } from 'react';
20
+ import { generateThemeVars, resolveThemeInheritance, resolveMode, } from '@object-ui/core';
21
+ // ============================================================================
22
+ // Context
23
+ // ============================================================================
24
+ const ThemeContext = createContext(null);
25
+ /**
26
+ * Default storage keys
27
+ */
28
+ const DEFAULT_STORAGE_KEY = 'objectui-theme';
29
+ // ============================================================================
30
+ // Provider
31
+ // ============================================================================
32
+ /**
33
+ * ThemeProvider
34
+ *
35
+ * Wraps a subtree with theme context. It:
36
+ * 1. Maintains theme + mode state
37
+ * 2. Resolves theme inheritance (extends)
38
+ * 3. Converts the active theme → CSS custom properties
39
+ * 4. Injects those CSS variables into the DOM
40
+ * 5. Applies 'dark' / 'light' class to the target element
41
+ * 6. Optionally persists user preference to localStorage
42
+ *
43
+ * @example
44
+ * ```tsx
45
+ * <ThemeProvider themes={[myTheme]} defaultTheme="my-theme" defaultMode="auto">
46
+ * <App />
47
+ * </ThemeProvider>
48
+ * ```
49
+ */
50
+ export function ThemeProvider({ themes: themesInput = [], defaultTheme, defaultMode = 'auto', persist = false, storageKey = DEFAULT_STORAGE_KEY, target, children, }) {
51
+ // ---- Build theme registry ----
52
+ const registry = useMemo(() => {
53
+ const map = new Map();
54
+ for (const t of themesInput) {
55
+ map.set(t.name, t);
56
+ }
57
+ return map;
58
+ }, [themesInput]);
59
+ // ---- Load persisted state ----
60
+ const loadPersistedTheme = useCallback(() => {
61
+ if (!persist)
62
+ return undefined;
63
+ try {
64
+ if (typeof window !== 'undefined') {
65
+ return localStorage.getItem(`${storageKey}-name`) ?? undefined;
66
+ }
67
+ }
68
+ catch { /* ignore */ }
69
+ return undefined;
70
+ }, [persist, storageKey]);
71
+ const loadPersistedMode = useCallback(() => {
72
+ if (!persist)
73
+ return undefined;
74
+ try {
75
+ if (typeof window !== 'undefined') {
76
+ const stored = localStorage.getItem(`${storageKey}-mode`);
77
+ if (stored === 'light' || stored === 'dark' || stored === 'auto') {
78
+ return stored;
79
+ }
80
+ }
81
+ }
82
+ catch { /* ignore */ }
83
+ return undefined;
84
+ }, [persist, storageKey]);
85
+ // ---- State ----
86
+ const [activeThemeName, setActiveThemeName] = useState(() => loadPersistedTheme() ?? defaultTheme ?? themesInput[0]?.name ?? null);
87
+ const [mode, setModeState] = useState(() => loadPersistedMode() ?? defaultMode);
88
+ // ---- Resolve theme ----
89
+ const resolvedTheme = useMemo(() => {
90
+ if (!activeThemeName)
91
+ return null;
92
+ const base = registry.get(activeThemeName);
93
+ if (!base)
94
+ return null;
95
+ return resolveThemeInheritance(base, registry);
96
+ }, [activeThemeName, registry]);
97
+ // ---- Resolve mode ----
98
+ const [systemDark, setSystemDark] = useState(() => {
99
+ if (typeof window !== 'undefined' && window.matchMedia) {
100
+ return window.matchMedia('(prefers-color-scheme: dark)').matches;
101
+ }
102
+ return false;
103
+ });
104
+ // Listen to system preference changes
105
+ useEffect(() => {
106
+ if (typeof window === 'undefined' || !window.matchMedia)
107
+ return;
108
+ const mq = window.matchMedia('(prefers-color-scheme: dark)');
109
+ const handler = (e) => setSystemDark(e.matches);
110
+ mq.addEventListener('change', handler);
111
+ return () => mq.removeEventListener('change', handler);
112
+ }, []);
113
+ const resolvedMode = useMemo(() => resolveMode(mode, systemDark), [mode, systemDark]);
114
+ // ---- Generate CSS variables ----
115
+ const cssVars = useMemo(() => {
116
+ if (!resolvedTheme)
117
+ return {};
118
+ return generateThemeVars(resolvedTheme);
119
+ }, [resolvedTheme]);
120
+ // ---- Inject CSS variables into the DOM ----
121
+ useEffect(() => {
122
+ const el = target ?? (typeof document !== 'undefined' ? document.documentElement : null);
123
+ if (!el)
124
+ return;
125
+ // Apply CSS variables
126
+ const previousValues = {};
127
+ for (const [prop, value] of Object.entries(cssVars)) {
128
+ previousValues[prop] = el.style.getPropertyValue(prop);
129
+ el.style.setProperty(prop, value);
130
+ }
131
+ // Apply mode class
132
+ el.classList.remove('light', 'dark');
133
+ el.classList.add(resolvedMode);
134
+ // Apply logo / favicon
135
+ if (resolvedTheme?.logo?.favicon && typeof document !== 'undefined') {
136
+ const link = document.querySelector('link[rel="icon"]')
137
+ ?? document.querySelector('#favicon');
138
+ if (link) {
139
+ link.href = resolvedTheme.logo.favicon;
140
+ }
141
+ }
142
+ return () => {
143
+ // Cleanup: remove injected vars
144
+ for (const prop of Object.keys(cssVars)) {
145
+ if (previousValues[prop]) {
146
+ el.style.setProperty(prop, previousValues[prop]);
147
+ }
148
+ else {
149
+ el.style.removeProperty(prop);
150
+ }
151
+ }
152
+ el.classList.remove(resolvedMode);
153
+ };
154
+ }, [cssVars, resolvedMode, resolvedTheme, target]);
155
+ // ---- Persistence ----
156
+ useEffect(() => {
157
+ if (!persist)
158
+ return;
159
+ try {
160
+ if (activeThemeName) {
161
+ localStorage.setItem(`${storageKey}-name`, activeThemeName);
162
+ }
163
+ localStorage.setItem(`${storageKey}-mode`, mode);
164
+ }
165
+ catch { /* ignore */ }
166
+ }, [persist, storageKey, activeThemeName, mode]);
167
+ // ---- Actions ----
168
+ const setTheme = useCallback((name) => {
169
+ if (registry.has(name)) {
170
+ setActiveThemeName(name);
171
+ }
172
+ }, [registry]);
173
+ const setMode = useCallback((newMode) => {
174
+ setModeState(newMode);
175
+ }, []);
176
+ // ---- Context value ----
177
+ const value = useMemo(() => ({
178
+ theme: resolvedTheme,
179
+ resolvedMode,
180
+ mode,
181
+ activeTheme: activeThemeName,
182
+ themes: themesInput,
183
+ setTheme,
184
+ setMode,
185
+ cssVars,
186
+ }), [resolvedTheme, resolvedMode, mode, activeThemeName, themesInput, setTheme, setMode, cssVars]);
187
+ return (_jsx(ThemeContext.Provider, { value: value, children: children }));
188
+ }
189
+ // ============================================================================
190
+ // Hook
191
+ // ============================================================================
192
+ /**
193
+ * useTheme — access the current theme context.
194
+ *
195
+ * @example
196
+ * ```tsx
197
+ * const { theme, resolvedMode, setMode, setTheme } = useTheme();
198
+ * ```
199
+ *
200
+ * @throws Error if used outside a ThemeProvider
201
+ */
202
+ export function useTheme() {
203
+ const ctx = useContext(ThemeContext);
204
+ if (!ctx) {
205
+ throw new Error('useTheme must be used within a <ThemeProvider>');
206
+ }
207
+ return ctx;
208
+ }
209
+ /**
210
+ * useOptionalTheme — like useTheme() but returns null outside a provider.
211
+ * Useful for components that should work with or without a theme.
212
+ */
213
+ export function useOptionalTheme() {
214
+ return useContext(ThemeContext);
215
+ }
@@ -6,3 +6,5 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  export * from './SchemaRendererContext';
9
+ export * from './ActionContext';
10
+ export * from './ThemeContext';
@@ -6,3 +6,5 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  export * from './SchemaRendererContext';
9
+ export * from './ActionContext';
10
+ export * from './ThemeContext';
@@ -7,3 +7,8 @@
7
7
  */
8
8
  export * from './useExpression';
9
9
  export * from './useActionRunner';
10
+ export * from './useNavigationOverlay';
11
+ export * from './usePageVariables';
12
+ export * from './useViewData';
13
+ export * from './useDynamicApp';
14
+ export * from './useDiscovery';
@@ -7,3 +7,8 @@
7
7
  */
8
8
  export * from './useExpression';
9
9
  export * from './useActionRunner';
10
+ export * from './useNavigationOverlay';
11
+ export * from './usePageVariables';
12
+ export * from './useViewData';
13
+ export * from './useDynamicApp';
14
+ export * from './useDiscovery';
@@ -5,25 +5,39 @@
5
5
  * This source code is licensed under the MIT license found in the
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
- import { ActionRunner, type ActionContext, type ActionResult } from '@object-ui/core';
8
+ import { ActionRunner, type ActionContext, type ActionDef, type ActionResult, type ConfirmationHandler, type ToastHandler, type ModalHandler, type NavigationHandler } from '@object-ui/core';
9
+ export interface UseActionRunnerOptions {
10
+ context?: ActionContext;
11
+ /** Custom confirmation handler — wire to Shadcn AlertDialog or similar */
12
+ onConfirm?: ConfirmationHandler;
13
+ /** Custom toast handler — wire to Sonner or similar */
14
+ onToast?: ToastHandler;
15
+ /** Custom modal handler — render modals in response to modal actions */
16
+ onModal?: ModalHandler;
17
+ /** Custom navigation handler — SPA-aware routing */
18
+ onNavigate?: NavigationHandler;
19
+ }
9
20
  /**
10
- * Hook for executing actions with loading state
21
+ * Hook for executing actions with loading state, typed with ActionDef.
11
22
  *
12
23
  * @example
13
24
  * ```tsx
14
- * const { execute, loading, error, result } = useActionRunner({ data: formData });
25
+ * const { execute, loading, error, result } = useActionRunner({
26
+ * context: { data: formData },
27
+ * onToast: (msg, opts) => toast[opts?.type || 'info'](msg),
28
+ * });
15
29
  *
16
30
  * const handleClick = () => {
17
31
  * execute({
18
- * type: 'action',
32
+ * type: 'api',
19
33
  * api: '/api/save',
20
- * successMessage: 'Saved successfully!'
34
+ * successMessage: 'Saved successfully!',
21
35
  * });
22
36
  * };
23
37
  * ```
24
38
  */
25
- export declare function useActionRunner(context?: ActionContext): {
26
- execute: (action: any) => Promise<ActionResult>;
39
+ export declare function useActionRunner(optionsOrContext?: UseActionRunnerOptions | ActionContext): {
40
+ execute: (action: ActionDef) => Promise<ActionResult>;
27
41
  loading: boolean;
28
42
  error: string | null;
29
43
  result: ActionResult | null;
@@ -6,28 +6,48 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  import { useState, useCallback, useMemo } from 'react';
9
- import { ActionRunner } from '@object-ui/core';
9
+ import { ActionRunner, } from '@object-ui/core';
10
10
  /**
11
- * Hook for executing actions with loading state
11
+ * Hook for executing actions with loading state, typed with ActionDef.
12
12
  *
13
13
  * @example
14
14
  * ```tsx
15
- * const { execute, loading, error, result } = useActionRunner({ data: formData });
15
+ * const { execute, loading, error, result } = useActionRunner({
16
+ * context: { data: formData },
17
+ * onToast: (msg, opts) => toast[opts?.type || 'info'](msg),
18
+ * });
16
19
  *
17
20
  * const handleClick = () => {
18
21
  * execute({
19
- * type: 'action',
22
+ * type: 'api',
20
23
  * api: '/api/save',
21
- * successMessage: 'Saved successfully!'
24
+ * successMessage: 'Saved successfully!',
22
25
  * });
23
26
  * };
24
27
  * ```
25
28
  */
26
- export function useActionRunner(context = {}) {
29
+ export function useActionRunner(optionsOrContext = {}) {
30
+ // Backwards compat: if no 'context' key, treat entire object as context
31
+ const options = 'context' in optionsOrContext
32
+ ? optionsOrContext
33
+ : { context: optionsOrContext };
34
+ const { context = {}, onConfirm, onToast, onModal, onNavigate } = options;
27
35
  const [loading, setLoading] = useState(false);
28
36
  const [error, setError] = useState(null);
29
37
  const [result, setResult] = useState(null);
30
- const runner = useMemo(() => new ActionRunner(context), [JSON.stringify(context)]);
38
+ const runner = useMemo(() => {
39
+ const r = new ActionRunner(context);
40
+ if (onConfirm)
41
+ r.setConfirmHandler(onConfirm);
42
+ if (onToast)
43
+ r.setToastHandler(onToast);
44
+ if (onModal)
45
+ r.setModalHandler(onModal);
46
+ if (onNavigate)
47
+ r.setNavigationHandler(onNavigate);
48
+ return r;
49
+ // eslint-disable-next-line react-hooks/exhaustive-deps
50
+ }, [JSON.stringify(context)]);
31
51
  const execute = useCallback(async (action) => {
32
52
  setLoading(true);
33
53
  setError(null);
@@ -0,0 +1,78 @@
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
+ * Discovery service information structure.
10
+ * Represents server capabilities and service status.
11
+ */
12
+ export interface DiscoveryInfo {
13
+ /** Server name and version */
14
+ name?: string;
15
+ version?: string;
16
+ /** Service availability status */
17
+ services?: {
18
+ /** Authentication service status */
19
+ auth?: {
20
+ enabled: boolean;
21
+ status?: 'available' | 'unavailable';
22
+ message?: string;
23
+ };
24
+ /** Data access service status */
25
+ data?: {
26
+ enabled: boolean;
27
+ status?: 'available' | 'unavailable';
28
+ };
29
+ /** Metadata service status */
30
+ metadata?: {
31
+ enabled: boolean;
32
+ status?: 'available' | 'unavailable';
33
+ };
34
+ [key: string]: any;
35
+ };
36
+ /** API capabilities */
37
+ capabilities?: string[];
38
+ /** Additional discovery metadata */
39
+ [key: string]: any;
40
+ }
41
+ /**
42
+ * Hook to access discovery information from the ObjectStack server.
43
+ *
44
+ * This hook retrieves server capabilities and service status, which can be used
45
+ * to conditionally enable/disable features based on server configuration.
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * function App() {
50
+ * const { discovery, isLoading } = useDiscovery();
51
+ *
52
+ * if (isLoading) {
53
+ * return <LoadingScreen />;
54
+ * }
55
+ *
56
+ * // Check if auth is enabled on the server
57
+ * const authEnabled = discovery?.services?.auth?.enabled ?? true;
58
+ *
59
+ * return (
60
+ * <div>
61
+ * {authEnabled ? <AuthProvider>...</AuthProvider> : <App />}
62
+ * </div>
63
+ * );
64
+ * }
65
+ * ```
66
+ *
67
+ * @returns Discovery information and loading state
68
+ */
69
+ export declare function useDiscovery(): {
70
+ discovery: DiscoveryInfo | null;
71
+ isLoading: boolean;
72
+ error: Error | null;
73
+ /**
74
+ * Check if authentication is enabled on the server.
75
+ * Defaults to true if discovery data is not available.
76
+ */
77
+ isAuthEnabled: boolean;
78
+ };