@object-ui/react 3.1.5 → 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 (109) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +28 -3
  3. package/dist/SchemaRenderer.js +2 -2
  4. package/dist/components/form/FieldFactory.js +5 -2
  5. package/dist/context/AppShellContext.d.ts +26 -0
  6. package/dist/context/AppShellContext.js +67 -0
  7. package/dist/context/index.d.ts +1 -7
  8. package/dist/context/index.js +1 -7
  9. package/dist/hooks/index.d.ts +1 -0
  10. package/dist/hooks/index.js +1 -0
  11. package/dist/hooks/useDataRefresh.d.ts +36 -0
  12. package/dist/hooks/useDataRefresh.js +50 -0
  13. package/dist/hooks/useDiscovery.d.ts +12 -0
  14. package/dist/hooks/useDiscovery.js +6 -0
  15. package/dist/hooks/usePerformanceBudget.js +1 -1
  16. package/package.json +32 -9
  17. package/.turbo/turbo-build.log +0 -4
  18. package/src/LazyPluginLoader.tsx +0 -174
  19. package/src/SchemaRenderer.tsx +0 -266
  20. package/src/__tests__/LazyPluginLoader.test.tsx +0 -176
  21. package/src/__tests__/SchemaRenderer.aria.test.tsx +0 -118
  22. package/src/__tests__/SchemaRenderer.debug.test.tsx +0 -69
  23. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +0 -114
  24. package/src/__tests__/SchemaRenderer.expressions.test.tsx +0 -131
  25. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +0 -132
  26. package/src/__tests__/ThemeProvider.test.tsx +0 -451
  27. package/src/__tests__/useNavigationOverlay.test.ts +0 -578
  28. package/src/__tests__/useOffline.test.ts +0 -198
  29. package/src/__tests__/usePageTransition.test.ts +0 -214
  30. package/src/__tests__/usePageVariables.test.tsx +0 -334
  31. package/src/__tests__/usePerformance.test.ts +0 -137
  32. package/src/__tests__/useViewData.test.tsx +0 -422
  33. package/src/__tests__/view-switching.test.tsx +0 -456
  34. package/src/components/form/FieldFactory.tsx +0 -509
  35. package/src/components/form/FormRenderer.test.tsx +0 -744
  36. package/src/components/form/FormRenderer.tsx +0 -258
  37. package/src/components/form/README.md +0 -352
  38. package/src/components/form/index.ts +0 -12
  39. package/src/context/ActionContext.tsx +0 -213
  40. package/src/context/DndContext.tsx +0 -260
  41. package/src/context/NotificationContext.tsx +0 -280
  42. package/src/context/SchemaRendererContext.tsx +0 -48
  43. package/src/context/ThemeContext.tsx +0 -325
  44. package/src/context/__tests__/ActionContext.test.tsx +0 -174
  45. package/src/context/__tests__/DndContext.test.tsx +0 -150
  46. package/src/context/__tests__/NotificationContext.test.tsx +0 -176
  47. package/src/context/__tests__/useDataScope.test.tsx +0 -91
  48. package/src/context/index.ts +0 -13
  49. package/src/hooks/__tests__/useActionEngine.test.ts +0 -170
  50. package/src/hooks/__tests__/useActionRunner.test.ts +0 -153
  51. package/src/hooks/__tests__/useAnimation.test.ts +0 -82
  52. package/src/hooks/__tests__/useColumnSummary.test.ts +0 -93
  53. package/src/hooks/__tests__/useCrudShortcuts.test.ts +0 -85
  54. package/src/hooks/__tests__/useDebugMode.test.ts +0 -83
  55. package/src/hooks/__tests__/useDensityMode.test.ts +0 -81
  56. package/src/hooks/__tests__/useDiscovery.test.tsx +0 -149
  57. package/src/hooks/__tests__/useDynamicApp.test.ts +0 -161
  58. package/src/hooks/__tests__/useETagCache.test.ts +0 -153
  59. package/src/hooks/__tests__/useExpression.test.ts +0 -86
  60. package/src/hooks/__tests__/useFocusTrap.test.ts +0 -294
  61. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +0 -144
  62. package/src/hooks/__tests__/usePageTransition.test.ts +0 -158
  63. package/src/hooks/__tests__/usePerformanceBudget.test.ts +0 -157
  64. package/src/hooks/__tests__/useReducedMotion.test.ts +0 -104
  65. package/src/hooks/__tests__/useSchemaPersistence.test.ts +0 -220
  66. package/src/hooks/__tests__/useViewSharing.test.ts +0 -121
  67. package/src/hooks/__tests__/useViewTransition.test.ts +0 -61
  68. package/src/hooks/index.ts +0 -35
  69. package/src/hooks/useActionEngine.ts +0 -84
  70. package/src/hooks/useActionRunner.ts +0 -119
  71. package/src/hooks/useAnimation.ts +0 -117
  72. package/src/hooks/useClientNotifications.ts +0 -251
  73. package/src/hooks/useColumnSummary.ts +0 -87
  74. package/src/hooks/useCrudShortcuts.ts +0 -126
  75. package/src/hooks/useDebugMode.ts +0 -95
  76. package/src/hooks/useDensityMode.ts +0 -102
  77. package/src/hooks/useDiscovery.ts +0 -154
  78. package/src/hooks/useDynamicApp.ts +0 -142
  79. package/src/hooks/useETagCache.ts +0 -404
  80. package/src/hooks/useExpression.ts +0 -56
  81. package/src/hooks/useFocusManagement.ts +0 -248
  82. package/src/hooks/useFocusTrap.ts +0 -138
  83. package/src/hooks/useGlobalUndo.ts +0 -98
  84. package/src/hooks/useKeyboardShortcuts.ts +0 -119
  85. package/src/hooks/useNavigationOverlay.ts +0 -190
  86. package/src/hooks/useOffline.ts +0 -301
  87. package/src/hooks/usePageTransition.ts +0 -187
  88. package/src/hooks/usePageVariables.tsx +0 -157
  89. package/src/hooks/usePerformance.ts +0 -246
  90. package/src/hooks/usePerformanceBudget.ts +0 -313
  91. package/src/hooks/useReducedMotion.ts +0 -53
  92. package/src/hooks/useSchemaPersistence.ts +0 -222
  93. package/src/hooks/useViewData.ts +0 -201
  94. package/src/hooks/useViewSharing.ts +0 -140
  95. package/src/hooks/useViewTransition.ts +0 -144
  96. package/src/index.ts +0 -41
  97. package/src/spec-bridge/SpecBridge.ts +0 -64
  98. package/src/spec-bridge/__tests__/P1SpecBridge.test.ts +0 -855
  99. package/src/spec-bridge/__tests__/SpecBridge.test.ts +0 -550
  100. package/src/spec-bridge/bridges/dashboard.ts +0 -180
  101. package/src/spec-bridge/bridges/form-view.ts +0 -109
  102. package/src/spec-bridge/bridges/list-view.ts +0 -187
  103. package/src/spec-bridge/bridges/page.ts +0 -136
  104. package/src/spec-bridge/index.ts +0 -14
  105. package/src/spec-bridge/types.ts +0 -38
  106. package/src/utils/i18n.ts +0 -10
  107. package/tsconfig.json +0 -17
  108. package/tsconfig.tsbuildinfo +0 -1
  109. package/vitest.config.ts +0 -2
@@ -1,126 +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
- import { useMemo } from 'react';
10
- import {
11
- useKeyboardShortcuts,
12
- type KeyboardShortcutDefinition,
13
- } from './useKeyboardShortcuts';
14
-
15
- export interface CrudShortcutCallbacks {
16
- onCreate?: () => void;
17
- onEdit?: () => void;
18
- onDelete?: () => void;
19
- onSave?: () => void;
20
- onDuplicate?: () => void;
21
- onCancel?: () => void;
22
- onSearch?: () => void;
23
- }
24
-
25
- /**
26
- * Registers standard CRUD keyboard shortcuts using the useKeyboardShortcuts hook.
27
- *
28
- * Shortcuts:
29
- * - Ctrl/Cmd+N: Create new record
30
- * - Ctrl/Cmd+E: Edit selected record
31
- * - Delete / Backspace: Delete selected record(s)
32
- * - Ctrl/Cmd+S: Save current record
33
- * - Ctrl/Cmd+D: Duplicate selected record
34
- * - Escape: Cancel/close current operation
35
- * - Ctrl/Cmd+F: Focus search
36
- *
37
- * @example
38
- * ```tsx
39
- * useCrudShortcuts({
40
- * onCreate: () => openCreateDialog(),
41
- * onSave: () => saveRecord(),
42
- * onDelete: () => deleteSelected(),
43
- * onCancel: () => closeDialog(),
44
- * });
45
- * ```
46
- */
47
- export function useCrudShortcuts(
48
- callbacks: CrudShortcutCallbacks,
49
- enabled = true
50
- ): void {
51
- const shortcuts = useMemo<KeyboardShortcutDefinition[]>(() => {
52
- const defs: KeyboardShortcutDefinition[] = [];
53
-
54
- if (callbacks.onCreate) {
55
- defs.push({
56
- key: 'n',
57
- ctrlOrMeta: true,
58
- handler: () => callbacks.onCreate!(),
59
- description: 'New record',
60
- });
61
- }
62
-
63
- if (callbacks.onEdit) {
64
- defs.push({
65
- key: 'e',
66
- ctrlOrMeta: true,
67
- handler: () => callbacks.onEdit!(),
68
- description: 'Edit selected record',
69
- });
70
- }
71
-
72
- if (callbacks.onDelete) {
73
- defs.push(
74
- {
75
- key: 'Delete',
76
- handler: () => callbacks.onDelete!(),
77
- description: 'Delete selected record(s)',
78
- },
79
- {
80
- key: 'Backspace',
81
- handler: () => callbacks.onDelete!(),
82
- description: 'Delete selected record(s)',
83
- }
84
- );
85
- }
86
-
87
- if (callbacks.onSave) {
88
- defs.push({
89
- key: 's',
90
- ctrlOrMeta: true,
91
- handler: () => callbacks.onSave!(),
92
- description: 'Save current record',
93
- });
94
- }
95
-
96
- if (callbacks.onDuplicate) {
97
- defs.push({
98
- key: 'd',
99
- ctrlOrMeta: true,
100
- handler: () => callbacks.onDuplicate!(),
101
- description: 'Duplicate selected record',
102
- });
103
- }
104
-
105
- if (callbacks.onCancel) {
106
- defs.push({
107
- key: 'Escape',
108
- handler: () => callbacks.onCancel!(),
109
- description: 'Cancel/close current operation',
110
- });
111
- }
112
-
113
- if (callbacks.onSearch) {
114
- defs.push({
115
- key: 'f',
116
- ctrlOrMeta: true,
117
- handler: () => callbacks.onSearch!(),
118
- description: 'Focus search',
119
- });
120
- }
121
-
122
- return defs;
123
- }, [callbacks]);
124
-
125
- useKeyboardShortcuts(shortcuts, { enabled });
126
- }
@@ -1,95 +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
- import { useState, useEffect, useCallback, useMemo } from 'react';
10
- import { parseDebugFlags, type DebugFlags } from '@object-ui/core';
11
-
12
- /**
13
- * Result returned by {@link useDebugMode}.
14
- */
15
- export interface UseDebugModeResult {
16
- /** Whether debug mode is currently enabled */
17
- enabled: boolean;
18
- /** Fine-grained debug flags parsed from the URL */
19
- flags: DebugFlags;
20
- /** Toggle debug mode on/off */
21
- toggle: () => void;
22
- /** Explicitly set debug mode */
23
- setEnabled: (value: boolean) => void;
24
- }
25
-
26
- /**
27
- * Hook for managing debug mode.
28
- *
29
- * Automatically detects `?__debug` (and sub-flags like `?__debug_schema`)
30
- * from the URL. Supports manual toggle and Ctrl+Shift+D keyboard shortcut.
31
- *
32
- * SSR-safe — returns disabled state when `window` is unavailable.
33
- *
34
- * @example
35
- * ```tsx
36
- * function App() {
37
- * const debug = useDebugMode();
38
- * return (
39
- * <>
40
- * {debug.enabled && <DebugPanel flags={debug.flags} />}
41
- * <button onClick={debug.toggle}>Toggle Debug</button>
42
- * </>
43
- * );
44
- * }
45
- * ```
46
- */
47
- export function useDebugMode(): UseDebugModeResult {
48
- const urlFlags = useMemo(() => {
49
- try {
50
- return typeof window !== 'undefined'
51
- ? parseDebugFlags(window.location.search)
52
- : { enabled: false } as DebugFlags;
53
- } catch {
54
- return { enabled: false } as DebugFlags;
55
- }
56
- }, []);
57
-
58
- const [manualEnabled, setManualEnabled] = useState<boolean | null>(null);
59
-
60
- // Effective enabled: manual override wins, then URL flags
61
- const enabled = manualEnabled !== null ? manualEnabled : urlFlags.enabled;
62
-
63
- // Flags reflect URL-parsed flags plus effective enabled state
64
- const flags: DebugFlags = useMemo(
65
- () => ({ ...urlFlags, enabled }),
66
- [urlFlags, enabled],
67
- );
68
-
69
- const toggle = useCallback(() => {
70
- setManualEnabled((prev) => {
71
- if (prev === null) return !urlFlags.enabled;
72
- return !prev;
73
- });
74
- }, [urlFlags.enabled]);
75
-
76
- const setEnabled = useCallback((value: boolean) => {
77
- setManualEnabled(value);
78
- }, []);
79
-
80
- // Ctrl+Shift+D keyboard shortcut
81
- useEffect(() => {
82
- if (typeof window === 'undefined') return;
83
-
84
- const handler = (e: KeyboardEvent) => {
85
- if (e.ctrlKey && e.shiftKey && e.key === 'D') {
86
- e.preventDefault();
87
- toggle();
88
- }
89
- };
90
- document.addEventListener('keydown', handler);
91
- return () => document.removeEventListener('keydown', handler);
92
- }, [toggle]);
93
-
94
- return { enabled, flags, toggle, setEnabled };
95
- }
@@ -1,102 +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
- import { useState, useCallback, useMemo } from 'react';
10
-
11
- /** Density mode aligned with DensityMode from @objectstack/spec v2.0.7 */
12
- export type DensityModeValue = 'compact' | 'comfortable' | 'spacious';
13
-
14
- export interface DensityConfig {
15
- /** Row height in pixels for each density mode */
16
- rowHeights?: Record<DensityModeValue, number>;
17
- /** Padding classes for each density mode */
18
- paddingClasses?: Record<DensityModeValue, string>;
19
- /** Font size classes for each density mode */
20
- fontSizeClasses?: Record<DensityModeValue, string>;
21
- }
22
-
23
- export interface DensityResult {
24
- /** Current density mode */
25
- mode: DensityModeValue;
26
- /** Set the density mode */
27
- setMode: (mode: DensityModeValue) => void;
28
- /** Cycle through density modes */
29
- cycle: () => void;
30
- /** Row height for the current mode (in pixels) */
31
- rowHeight: number;
32
- /** Tailwind padding class for the current mode */
33
- paddingClass: string;
34
- /** Tailwind font-size class for the current mode */
35
- fontSizeClass: string;
36
- }
37
-
38
- const DEFAULT_ROW_HEIGHTS: Record<DensityModeValue, number> = {
39
- compact: 32,
40
- comfortable: 40,
41
- spacious: 52,
42
- };
43
-
44
- const DEFAULT_PADDING_CLASSES: Record<DensityModeValue, string> = {
45
- compact: 'py-1 px-2',
46
- comfortable: 'py-2 px-3',
47
- spacious: 'py-3 px-4',
48
- };
49
-
50
- const DEFAULT_FONT_SIZE_CLASSES: Record<DensityModeValue, string> = {
51
- compact: 'text-xs',
52
- comfortable: 'text-sm',
53
- spacious: 'text-base',
54
- };
55
-
56
- const DENSITY_ORDER: DensityModeValue[] = ['compact', 'comfortable', 'spacious'];
57
-
58
- /**
59
- * Hook for managing view density modes (compact/comfortable/spacious).
60
- * Implements DensityMode from @objectstack/spec v2.0.7.
61
- *
62
- * @example
63
- * ```tsx
64
- * const density = useDensityMode('comfortable');
65
- *
66
- * return (
67
- * <div className={density.paddingClass}>
68
- * <table style={{ rowHeight: density.rowHeight }}>...</table>
69
- * <button onClick={density.cycle}>Toggle Density</button>
70
- * </div>
71
- * );
72
- * ```
73
- */
74
- export function useDensityMode(
75
- initialMode: DensityModeValue = 'comfortable',
76
- config?: DensityConfig
77
- ): DensityResult {
78
- const [mode, setMode] = useState<DensityModeValue>(initialMode);
79
-
80
- const rowHeights = config?.rowHeights ?? DEFAULT_ROW_HEIGHTS;
81
- const paddingClasses = config?.paddingClasses ?? DEFAULT_PADDING_CLASSES;
82
- const fontSizeClasses = config?.fontSizeClasses ?? DEFAULT_FONT_SIZE_CLASSES;
83
-
84
- const cycle = useCallback(() => {
85
- setMode((current) => {
86
- const idx = DENSITY_ORDER.indexOf(current);
87
- return DENSITY_ORDER[(idx + 1) % DENSITY_ORDER.length];
88
- });
89
- }, []);
90
-
91
- return useMemo(
92
- () => ({
93
- mode,
94
- setMode,
95
- cycle,
96
- rowHeight: rowHeights[mode],
97
- paddingClass: paddingClasses[mode],
98
- fontSizeClass: fontSizeClasses[mode],
99
- }),
100
- [mode, cycle, rowHeights, paddingClasses, fontSizeClasses]
101
- );
102
- }
@@ -1,154 +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
- import { useState, useEffect, useContext } from 'react';
10
- import { SchemaRendererContext } from '../context/SchemaRendererContext';
11
-
12
- /**
13
- * Discovery service information structure.
14
- * Represents server capabilities and service status.
15
- */
16
- export interface DiscoveryInfo {
17
- /** Server name and version */
18
- name?: string;
19
- version?: string;
20
-
21
- /** Runtime mode (e.g., 'development', 'production', 'preview') */
22
- mode?: string;
23
-
24
- /** Preview mode configuration from the kernel (present when mode is 'preview') */
25
- previewMode?: {
26
- autoLogin?: boolean;
27
- simulatedRole?: 'admin' | 'user' | 'viewer';
28
- simulatedUserName?: string;
29
- readOnly?: boolean;
30
- expiresInSeconds?: number;
31
- bannerMessage?: string;
32
- };
33
-
34
- /** Service availability status */
35
- services?: {
36
- /** Authentication service status */
37
- auth?: {
38
- enabled: boolean;
39
- status?: 'available' | 'unavailable';
40
- message?: string;
41
- };
42
- /** Data access service status */
43
- data?: {
44
- enabled: boolean;
45
- status?: 'available' | 'unavailable';
46
- };
47
- /** Metadata service status */
48
- metadata?: {
49
- enabled: boolean;
50
- status?: 'available' | 'unavailable';
51
- };
52
- [key: string]: any;
53
- };
54
-
55
- /** API capabilities */
56
- capabilities?: string[];
57
-
58
- /** Additional discovery metadata */
59
- [key: string]: any;
60
- }
61
-
62
- /**
63
- * Hook to access discovery information from the ObjectStack server.
64
- *
65
- * This hook retrieves server capabilities and service status, which can be used
66
- * to conditionally enable/disable features based on server configuration.
67
- *
68
- * @example
69
- * ```tsx
70
- * function App() {
71
- * const { discovery, isLoading } = useDiscovery();
72
- *
73
- * if (isLoading) {
74
- * return <LoadingScreen />;
75
- * }
76
- *
77
- * // Check if auth is enabled on the server
78
- * const authEnabled = discovery?.services?.auth?.enabled ?? true;
79
- *
80
- * return (
81
- * <div>
82
- * {authEnabled ? <AuthProvider>...</AuthProvider> : <App />}
83
- * </div>
84
- * );
85
- * }
86
- * ```
87
- *
88
- * @returns Discovery information and loading state
89
- */
90
- export function useDiscovery() {
91
- const context = useContext(SchemaRendererContext);
92
- const dataSource = context?.dataSource;
93
- const [discovery, setDiscovery] = useState<DiscoveryInfo | null>(null);
94
- const [isLoading, setIsLoading] = useState(true);
95
- const [error, setError] = useState<Error | null>(null);
96
-
97
- useEffect(() => {
98
- let cancelled = false;
99
-
100
- async function fetchDiscovery() {
101
- if (!dataSource) {
102
- setIsLoading(false);
103
- return;
104
- }
105
-
106
- try {
107
- setIsLoading(true);
108
-
109
- // Check if dataSource has getDiscovery method
110
- if (typeof (dataSource as any).getDiscovery === 'function') {
111
- const discoveryData = await (dataSource as any).getDiscovery();
112
-
113
- if (!cancelled) {
114
- setDiscovery(discoveryData);
115
- setError(null);
116
- }
117
- } else {
118
- // DataSource doesn't support discovery
119
- if (!cancelled) {
120
- setDiscovery(null);
121
- setError(null);
122
- }
123
- }
124
- } catch (err) {
125
- if (!cancelled) {
126
- setError(err instanceof Error ? err : new Error('Failed to fetch discovery'));
127
- setDiscovery(null);
128
- }
129
- } finally {
130
- if (!cancelled) {
131
- setIsLoading(false);
132
- }
133
- }
134
- }
135
-
136
- fetchDiscovery();
137
-
138
- return () => {
139
- cancelled = true;
140
- };
141
- }, [dataSource]);
142
-
143
- return {
144
- discovery,
145
- isLoading,
146
- error,
147
- /**
148
- * Check if authentication is enabled on the server.
149
- * Defaults to true if discovery data is not available.
150
- */
151
- isAuthEnabled: discovery?.services?.auth?.enabled ?? true,
152
- };
153
- }
154
-
@@ -1,142 +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
- import { useState, useEffect, useCallback, useRef } from 'react';
10
-
11
- /**
12
- * Options for dynamic app configuration loading.
13
- */
14
- export interface DynamicAppOptions<TAppConfig = unknown> {
15
- /** Application identifier to load */
16
- appId: string;
17
- /**
18
- * Static (fallback) configuration used when the server does not
19
- * provide an app definition or is unreachable.
20
- */
21
- staticConfig?: TAppConfig;
22
- /**
23
- * Data source adapter with `getApp` and `invalidateCache` methods.
24
- * Typically an ObjectStackAdapter instance.
25
- */
26
- adapter?: {
27
- getApp: (appId: string) => Promise<unknown | null>;
28
- invalidateCache?: (key?: string) => void;
29
- getObjectSchema?: (objectName: string) => Promise<unknown>;
30
- };
31
- /** Whether to attempt loading from the server (default: true) */
32
- enabled?: boolean;
33
- }
34
-
35
- /**
36
- * Result returned by useDynamicApp.
37
- */
38
- export interface DynamicAppResult<TAppConfig = unknown> {
39
- /** The resolved app configuration (server or static fallback) */
40
- config: TAppConfig | null;
41
- /** Whether the configuration is currently loading */
42
- isLoading: boolean;
43
- /** Error from the most recent load attempt */
44
- error: Error | null;
45
- /** Whether the config was loaded from the server (vs static fallback) */
46
- isServerConfig: boolean;
47
- /** Re-fetch the app configuration from the server, invalidating cache */
48
- refresh: () => Promise<void>;
49
- }
50
-
51
- /**
52
- * React hook for dynamic app configuration loading.
53
- *
54
- * Fetches app configuration from the server via `adapter.getApp(appId)`,
55
- * falling back to `staticConfig` when the server is unavailable.
56
- * Supports cache-based hot-reload via the `refresh()` callback.
57
- *
58
- * @example
59
- * ```tsx
60
- * import { useDynamicApp } from '@object-ui/react';
61
- * import staticAppConfig from '../config/app.json';
62
- *
63
- * function App() {
64
- * const { config, isLoading, refresh } = useDynamicApp({
65
- * appId: 'crm',
66
- * staticConfig: staticAppConfig,
67
- * adapter: dataSource,
68
- * });
69
- *
70
- * if (isLoading) return <LoadingScreen />;
71
- * return <Console config={config} onRefresh={refresh} />;
72
- * }
73
- * ```
74
- */
75
- export function useDynamicApp<TAppConfig = unknown>(
76
- options: DynamicAppOptions<TAppConfig>,
77
- ): DynamicAppResult<TAppConfig> {
78
- const { appId, staticConfig, adapter, enabled = true } = options;
79
-
80
- const [config, setConfig] = useState<TAppConfig | null>(staticConfig ?? null);
81
- const [isLoading, setIsLoading] = useState(enabled && !!adapter);
82
- const [error, setError] = useState<Error | null>(null);
83
- const [isServerConfig, setIsServerConfig] = useState(false);
84
-
85
- // Ref to track unmount / stale requests
86
- const mountedRef = useRef(true);
87
- useEffect(() => {
88
- mountedRef.current = true;
89
- return () => { mountedRef.current = false; };
90
- }, []);
91
-
92
- const loadConfig = useCallback(async () => {
93
- if (!adapter || !enabled) {
94
- setConfig(staticConfig ?? null);
95
- setIsServerConfig(false);
96
- setIsLoading(false);
97
- return;
98
- }
99
-
100
- setIsLoading(true);
101
- setError(null);
102
-
103
- try {
104
- const serverConfig = await adapter.getApp(appId);
105
-
106
- if (!mountedRef.current) return;
107
-
108
- if (serverConfig) {
109
- setConfig(serverConfig as TAppConfig);
110
- setIsServerConfig(true);
111
- } else {
112
- // Server returned null — fall back to static config
113
- setConfig(staticConfig ?? null);
114
- setIsServerConfig(false);
115
- }
116
- } catch (err) {
117
- if (!mountedRef.current) return;
118
-
119
- setError(err instanceof Error ? err : new Error(String(err)));
120
- // Fall back to static config on error
121
- setConfig(staticConfig ?? null);
122
- setIsServerConfig(false);
123
- } finally {
124
- if (mountedRef.current) {
125
- setIsLoading(false);
126
- }
127
- }
128
- }, [adapter, appId, staticConfig, enabled]);
129
-
130
- // Load on mount and when appId changes
131
- useEffect(() => {
132
- loadConfig();
133
- }, [loadConfig]);
134
-
135
- const refresh = useCallback(async () => {
136
- // Invalidate cache before re-fetching
137
- adapter?.invalidateCache?.(`app:${appId}`);
138
- await loadConfig();
139
- }, [adapter, appId, loadConfig]);
140
-
141
- return { config, isLoading, error, isServerConfig, refresh };
142
- }