@object-ui/react 0.3.1 → 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.
- package/.turbo/turbo-build.log +4 -0
- package/CHANGELOG.md +13 -0
- package/dist/LazyPluginLoader.d.ts +82 -0
- package/dist/LazyPluginLoader.js +124 -0
- package/dist/SchemaRenderer.js +44 -12
- package/dist/components/form/FieldFactory.js +44 -40
- package/dist/components/form/FormRenderer.js +45 -3
- package/dist/context/ActionContext.d.ts +76 -0
- package/dist/context/ActionContext.js +139 -0
- package/dist/context/SchemaRendererContext.d.ts +2 -1
- package/dist/context/SchemaRendererContext.js +4 -2
- package/dist/context/ThemeContext.d.ts +94 -0
- package/dist/context/ThemeContext.js +215 -0
- package/dist/context/index.d.ts +2 -0
- package/dist/context/index.js +2 -0
- package/dist/hooks/index.d.ts +5 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/useActionRunner.d.ts +21 -7
- package/dist/hooks/useActionRunner.js +27 -7
- package/dist/hooks/useDiscovery.d.ts +78 -0
- package/dist/hooks/useDiscovery.js +96 -0
- package/dist/hooks/useDynamicApp.d.ts +70 -0
- package/dist/hooks/useDynamicApp.js +92 -0
- package/dist/hooks/useNavigationOverlay.d.ts +78 -0
- package/dist/hooks/useNavigationOverlay.js +112 -0
- package/dist/hooks/usePageVariables.d.ts +67 -0
- package/dist/hooks/usePageVariables.js +109 -0
- package/dist/hooks/useViewData.d.ts +73 -0
- package/dist/hooks/useViewData.js +135 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +3 -0
- package/dist/utils/i18n.d.ts +10 -0
- package/dist/utils/i18n.js +12 -0
- package/package.json +16 -6
- package/src/LazyPluginLoader.tsx +174 -0
- package/src/SchemaRenderer.tsx +64 -12
- package/src/__tests__/LazyPluginLoader.test.tsx +176 -0
- package/src/__tests__/ThemeProvider.test.tsx +451 -0
- package/src/__tests__/useNavigationOverlay.test.ts +416 -0
- package/src/__tests__/usePageVariables.test.tsx +334 -0
- package/src/__tests__/useViewData.test.tsx +422 -0
- package/src/components/form/FieldFactory.tsx +51 -46
- package/src/components/form/FormRenderer.test.tsx +145 -0
- package/src/components/form/FormRenderer.tsx +52 -3
- package/src/context/ActionContext.tsx +213 -0
- package/src/context/SchemaRendererContext.tsx +5 -2
- package/src/context/ThemeContext.tsx +325 -0
- package/src/context/__tests__/ActionContext.test.tsx +174 -0
- package/src/context/index.ts +2 -0
- package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
- package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
- package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
- package/src/hooks/__tests__/useExpression.test.ts +86 -0
- package/src/hooks/index.ts +5 -0
- package/src/hooks/useActionRunner.ts +49 -11
- package/src/hooks/useDiscovery.ts +141 -0
- package/src/hooks/useDynamicApp.ts +142 -0
- package/src/hooks/useNavigationOverlay.ts +180 -0
- package/src/hooks/usePageVariables.tsx +157 -0
- package/src/hooks/useViewData.ts +201 -0
- package/src/index.ts +22 -0
- package/src/utils/i18n.ts +10 -0
- package/tsconfig.json +1 -0
- package/tsconfig.tsbuildinfo +1 -1
- package/vitest.config.ts +2 -0
- package/dist/components/form/FormRenderer.test.d.ts +0 -8
- package/dist/components/form/FormRenderer.test.js +0 -534
- package/dist/index.test.d.ts +0 -8
- package/dist/index.test.js +0 -13
|
@@ -0,0 +1,109 @@
|
|
|
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
|
+
import { createContext, useContext, useState, useCallback, useMemo } from 'react';
|
|
10
|
+
const PageVariablesContext = createContext(null);
|
|
11
|
+
/**
|
|
12
|
+
* Initialize page variables from their definitions.
|
|
13
|
+
* Sets each variable to its defaultValue or type-appropriate default.
|
|
14
|
+
*/
|
|
15
|
+
function initializeVariables(definitions) {
|
|
16
|
+
if (!definitions || definitions.length === 0)
|
|
17
|
+
return {};
|
|
18
|
+
const initial = {};
|
|
19
|
+
for (const def of definitions) {
|
|
20
|
+
if (def.defaultValue !== undefined) {
|
|
21
|
+
initial[def.name] = def.defaultValue;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
// Type-appropriate defaults
|
|
25
|
+
switch (def.type) {
|
|
26
|
+
case 'number':
|
|
27
|
+
initial[def.name] = 0;
|
|
28
|
+
break;
|
|
29
|
+
case 'boolean':
|
|
30
|
+
initial[def.name] = false;
|
|
31
|
+
break;
|
|
32
|
+
case 'object':
|
|
33
|
+
initial[def.name] = {};
|
|
34
|
+
break;
|
|
35
|
+
case 'array':
|
|
36
|
+
initial[def.name] = [];
|
|
37
|
+
break;
|
|
38
|
+
case 'string':
|
|
39
|
+
default:
|
|
40
|
+
initial[def.name] = '';
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return initial;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* PageVariablesProvider — Provides page-level state variables to the component tree.
|
|
49
|
+
*
|
|
50
|
+
* Initializes variables from their definitions and provides read/write access
|
|
51
|
+
* to all child components via the usePageVariables hook.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```tsx
|
|
55
|
+
* <PageVariablesProvider definitions={[
|
|
56
|
+
* { name: 'selectedId', type: 'string', defaultValue: '' },
|
|
57
|
+
* { name: 'count', type: 'number', defaultValue: 0 },
|
|
58
|
+
* ]}>
|
|
59
|
+
* <MyComponents />
|
|
60
|
+
* </PageVariablesProvider>
|
|
61
|
+
* ```
|
|
62
|
+
*/
|
|
63
|
+
export const PageVariablesProvider = ({ definitions, children, }) => {
|
|
64
|
+
const [variables, setVariablesState] = useState(() => initializeVariables(definitions));
|
|
65
|
+
const setVariable = useCallback((name, value) => {
|
|
66
|
+
setVariablesState((prev) => ({ ...prev, [name]: value }));
|
|
67
|
+
}, []);
|
|
68
|
+
const setVariables = useCallback((updates) => {
|
|
69
|
+
setVariablesState((prev) => ({ ...prev, ...updates }));
|
|
70
|
+
}, []);
|
|
71
|
+
const resetVariables = useCallback(() => {
|
|
72
|
+
setVariablesState(initializeVariables(definitions));
|
|
73
|
+
}, [definitions]);
|
|
74
|
+
const value = useMemo(() => ({ variables, setVariable, setVariables, resetVariables }), [variables, setVariable, setVariables, resetVariables]);
|
|
75
|
+
return (_jsx(PageVariablesContext.Provider, { value: value, children: children }));
|
|
76
|
+
};
|
|
77
|
+
PageVariablesProvider.displayName = 'PageVariablesProvider';
|
|
78
|
+
/**
|
|
79
|
+
* Hook to access page-level variables.
|
|
80
|
+
*
|
|
81
|
+
* Returns the current variable values and setter functions.
|
|
82
|
+
* Returns a no-op fallback if used outside a PageVariablesProvider.
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* ```tsx
|
|
86
|
+
* const { variables, setVariable } = usePageVariables();
|
|
87
|
+
* const userId = variables.selectedId;
|
|
88
|
+
* setVariable('selectedId', '123');
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
export function usePageVariables() {
|
|
92
|
+
const ctx = useContext(PageVariablesContext);
|
|
93
|
+
if (!ctx) {
|
|
94
|
+
// Graceful fallback — allows components to work outside a Page
|
|
95
|
+
return {
|
|
96
|
+
variables: {},
|
|
97
|
+
setVariable: () => { },
|
|
98
|
+
setVariables: () => { },
|
|
99
|
+
resetVariables: () => { },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
return ctx;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Hook to check if a PageVariablesProvider is available.
|
|
106
|
+
*/
|
|
107
|
+
export function useHasPageVariables() {
|
|
108
|
+
return useContext(PageVariablesContext) !== null;
|
|
109
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ObjectUI — useViewData
|
|
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
|
+
* A React hook that resolves a ViewData configuration into a DataSource
|
|
9
|
+
* and provides reactive data fetching with loading/error states.
|
|
10
|
+
*/
|
|
11
|
+
import type { DataSource, ViewData, QueryParams } from '@object-ui/types';
|
|
12
|
+
import { type ResolveDataSourceOptions } from '@object-ui/core';
|
|
13
|
+
export interface UseViewDataOptions<T = any> {
|
|
14
|
+
/** The ViewData configuration from the schema */
|
|
15
|
+
viewData?: ViewData | null;
|
|
16
|
+
/** Resource name (object name, used for DataSource.find calls) */
|
|
17
|
+
resource?: string;
|
|
18
|
+
/** Initial query parameters */
|
|
19
|
+
params?: QueryParams;
|
|
20
|
+
/** Explicit data source override (bypasses context) */
|
|
21
|
+
dataSource?: DataSource<T> | null;
|
|
22
|
+
/** Options for adapter construction */
|
|
23
|
+
adapterOptions?: ResolveDataSourceOptions;
|
|
24
|
+
/** If true, skip the initial fetch (useful for forms in create mode) */
|
|
25
|
+
skip?: boolean;
|
|
26
|
+
}
|
|
27
|
+
export interface UseViewDataResult<T = any> {
|
|
28
|
+
/** Resolved data array */
|
|
29
|
+
data: T[];
|
|
30
|
+
/** Total number of records (from server or array length) */
|
|
31
|
+
totalCount: number;
|
|
32
|
+
/** Whether data is being fetched */
|
|
33
|
+
loading: boolean;
|
|
34
|
+
/** Error from the last fetch attempt */
|
|
35
|
+
error: Error | null;
|
|
36
|
+
/** The resolved DataSource instance (can be used for create/update/delete) */
|
|
37
|
+
dataSource: DataSource<T> | null;
|
|
38
|
+
/** Re-fetch data with current or new params */
|
|
39
|
+
refresh: (newParams?: QueryParams) => Promise<void>;
|
|
40
|
+
/** Fetch a single record by ID */
|
|
41
|
+
fetchOne: (id: string | number) => Promise<T | null>;
|
|
42
|
+
/** Whether more records are available */
|
|
43
|
+
hasMore: boolean;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* useViewData — resolves ViewData into a DataSource and provides reactive data.
|
|
47
|
+
*
|
|
48
|
+
* This hook centralizes the data resolution pattern that was previously
|
|
49
|
+
* duplicated across plugins (ObjectGrid, ObjectView, etc.). It:
|
|
50
|
+
*
|
|
51
|
+
* 1. Resolves the ViewData config to the right DataSource adapter
|
|
52
|
+
* - `provider: 'object'` → context DataSource (ObjectStackAdapter)
|
|
53
|
+
* - `provider: 'api'` → ApiDataSource (raw HTTP)
|
|
54
|
+
* - `provider: 'value'` → ValueDataSource (in-memory)
|
|
55
|
+
* 2. Fetches data automatically on mount
|
|
56
|
+
* 3. Provides loading/error states and refresh capability
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```tsx
|
|
60
|
+
* function MyGrid({ schema }) {
|
|
61
|
+
* const { data, loading, error, refresh, dataSource } = useViewData({
|
|
62
|
+
* viewData: schema.data,
|
|
63
|
+
* resource: schema.objectName,
|
|
64
|
+
* params: { $top: 50 },
|
|
65
|
+
* });
|
|
66
|
+
*
|
|
67
|
+
* if (loading) return <Spinner />;
|
|
68
|
+
* if (error) return <ErrorMessage error={error} />;
|
|
69
|
+
* return <Table data={data} />;
|
|
70
|
+
* }
|
|
71
|
+
* ```
|
|
72
|
+
*/
|
|
73
|
+
export declare function useViewData<T = any>(options: UseViewDataOptions<T>): UseViewDataResult<T>;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ObjectUI — useViewData
|
|
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
|
+
* A React hook that resolves a ViewData configuration into a DataSource
|
|
9
|
+
* and provides reactive data fetching with loading/error states.
|
|
10
|
+
*/
|
|
11
|
+
import { useState, useEffect, useCallback, useMemo, useContext } from 'react';
|
|
12
|
+
import { resolveDataSource } from '@object-ui/core';
|
|
13
|
+
import { SchemaRendererContext } from '../context/SchemaRendererContext';
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// Hook
|
|
16
|
+
// ---------------------------------------------------------------------------
|
|
17
|
+
/**
|
|
18
|
+
* useViewData — resolves ViewData into a DataSource and provides reactive data.
|
|
19
|
+
*
|
|
20
|
+
* This hook centralizes the data resolution pattern that was previously
|
|
21
|
+
* duplicated across plugins (ObjectGrid, ObjectView, etc.). It:
|
|
22
|
+
*
|
|
23
|
+
* 1. Resolves the ViewData config to the right DataSource adapter
|
|
24
|
+
* - `provider: 'object'` → context DataSource (ObjectStackAdapter)
|
|
25
|
+
* - `provider: 'api'` → ApiDataSource (raw HTTP)
|
|
26
|
+
* - `provider: 'value'` → ValueDataSource (in-memory)
|
|
27
|
+
* 2. Fetches data automatically on mount
|
|
28
|
+
* 3. Provides loading/error states and refresh capability
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```tsx
|
|
32
|
+
* function MyGrid({ schema }) {
|
|
33
|
+
* const { data, loading, error, refresh, dataSource } = useViewData({
|
|
34
|
+
* viewData: schema.data,
|
|
35
|
+
* resource: schema.objectName,
|
|
36
|
+
* params: { $top: 50 },
|
|
37
|
+
* });
|
|
38
|
+
*
|
|
39
|
+
* if (loading) return <Spinner />;
|
|
40
|
+
* if (error) return <ErrorMessage error={error} />;
|
|
41
|
+
* return <Table data={data} />;
|
|
42
|
+
* }
|
|
43
|
+
* ```
|
|
44
|
+
*/
|
|
45
|
+
export function useViewData(options) {
|
|
46
|
+
const { viewData, resource = '', params, dataSource: explicitDataSource, adapterOptions, skip = false, } = options;
|
|
47
|
+
// Get context DataSource
|
|
48
|
+
const context = useContext(SchemaRendererContext);
|
|
49
|
+
const contextDataSource = context?.dataSource ?? null;
|
|
50
|
+
// Resolve the DataSource — memoize to prevent re-creation on every render.
|
|
51
|
+
// We key on the viewData provider + config identity.
|
|
52
|
+
const resolvedDataSource = useMemo(() => {
|
|
53
|
+
if (explicitDataSource)
|
|
54
|
+
return explicitDataSource;
|
|
55
|
+
return resolveDataSource(viewData, contextDataSource, adapterOptions);
|
|
56
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
57
|
+
}, [
|
|
58
|
+
explicitDataSource,
|
|
59
|
+
viewData?.provider,
|
|
60
|
+
// For 'api' provider, key on read/write URLs
|
|
61
|
+
viewData?.provider === 'api' ? viewData.read?.url : undefined,
|
|
62
|
+
viewData?.provider === 'api' ? viewData.write?.url : undefined,
|
|
63
|
+
// For 'value' provider, key on items reference (or length as proxy)
|
|
64
|
+
viewData?.provider === 'value' ? viewData.items?.length : undefined,
|
|
65
|
+
contextDataSource,
|
|
66
|
+
]);
|
|
67
|
+
// State
|
|
68
|
+
const [data, setData] = useState([]);
|
|
69
|
+
const [totalCount, setTotalCount] = useState(0);
|
|
70
|
+
const [loading, setLoading] = useState(!skip);
|
|
71
|
+
const [error, setError] = useState(null);
|
|
72
|
+
const [hasMore, setHasMore] = useState(false);
|
|
73
|
+
// Stable params reference
|
|
74
|
+
const paramsKey = useMemo(() => JSON.stringify(params ?? {}), [params]);
|
|
75
|
+
// Fetch function
|
|
76
|
+
const fetchData = useCallback(async (fetchParams) => {
|
|
77
|
+
if (!resolvedDataSource || !resource) {
|
|
78
|
+
setLoading(false);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
setLoading(true);
|
|
82
|
+
setError(null);
|
|
83
|
+
try {
|
|
84
|
+
const mergedParams = fetchParams ?? (params ? { ...params } : undefined);
|
|
85
|
+
const result = await resolvedDataSource.find(resource, mergedParams);
|
|
86
|
+
setData(result.data ?? []);
|
|
87
|
+
setTotalCount(result.total ?? result.data?.length ?? 0);
|
|
88
|
+
setHasMore(result.hasMore ?? false);
|
|
89
|
+
}
|
|
90
|
+
catch (err) {
|
|
91
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
92
|
+
setData([]);
|
|
93
|
+
setTotalCount(0);
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
setLoading(false);
|
|
97
|
+
}
|
|
98
|
+
}, [resolvedDataSource, resource, params]);
|
|
99
|
+
// Auto-fetch on mount / when deps change
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
if (skip) {
|
|
102
|
+
setLoading(false);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
// For value provider, data is synchronous — still go through fetchData
|
|
106
|
+
// for consistency, but it resolves immediately.
|
|
107
|
+
fetchData();
|
|
108
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
109
|
+
}, [resolvedDataSource, resource, paramsKey, skip]);
|
|
110
|
+
// Refresh function (can accept new params)
|
|
111
|
+
const refresh = useCallback(async (newParams) => {
|
|
112
|
+
await fetchData(newParams);
|
|
113
|
+
}, [fetchData]);
|
|
114
|
+
// Fetch one record
|
|
115
|
+
const fetchOne = useCallback(async (id) => {
|
|
116
|
+
if (!resolvedDataSource)
|
|
117
|
+
return null;
|
|
118
|
+
try {
|
|
119
|
+
return await resolvedDataSource.findOne(resource, id);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}, [resolvedDataSource, resource]);
|
|
125
|
+
return {
|
|
126
|
+
data,
|
|
127
|
+
totalCount,
|
|
128
|
+
loading,
|
|
129
|
+
error,
|
|
130
|
+
dataSource: resolvedDataSource,
|
|
131
|
+
refresh,
|
|
132
|
+
fetchOne,
|
|
133
|
+
hasMore,
|
|
134
|
+
};
|
|
135
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,3 +9,5 @@ export * from './SchemaRenderer';
|
|
|
9
9
|
export * from './hooks';
|
|
10
10
|
export * from './context';
|
|
11
11
|
export * from './components/form';
|
|
12
|
+
export * from './LazyPluginLoader';
|
|
13
|
+
export { I18nProvider, useObjectTranslation, useI18nContext, createI18n, getDirection, getAvailableLanguages, formatDate, formatDateTime, formatRelativeTime, formatCurrency, formatNumber, type I18nConfig, type I18nProviderProps, type TranslationKeys, type DateFormatOptions, type CurrencyFormatOptions, type NumberFormatOptions, } from '@object-ui/i18n';
|
package/dist/index.js
CHANGED
|
@@ -9,3 +9,6 @@ export * from './SchemaRenderer';
|
|
|
9
9
|
export * from './hooks'; // will be empty for now
|
|
10
10
|
export * from './context'; // will be empty for now
|
|
11
11
|
export * from './components/form';
|
|
12
|
+
export * from './LazyPluginLoader';
|
|
13
|
+
// Built-in i18n support
|
|
14
|
+
export { I18nProvider, useObjectTranslation, useI18nContext, createI18n, getDirection, getAvailableLanguages, formatDate, formatDateTime, formatRelativeTime, formatCurrency, formatNumber, } from '@object-ui/i18n';
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolves an I18nLabel to a plain string.
|
|
3
|
+
* I18nLabel can be either a string or an object { key, defaultValue?, params? }.
|
|
4
|
+
* When it's an object, we return the defaultValue or the key as fallback.
|
|
5
|
+
*/
|
|
6
|
+
export declare function resolveI18nLabel(label: string | {
|
|
7
|
+
key: string;
|
|
8
|
+
defaultValue?: string;
|
|
9
|
+
params?: Record<string, any>;
|
|
10
|
+
} | undefined): string | undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolves an I18nLabel to a plain string.
|
|
3
|
+
* I18nLabel can be either a string or an object { key, defaultValue?, params? }.
|
|
4
|
+
* When it's an object, we return the defaultValue or the key as fallback.
|
|
5
|
+
*/
|
|
6
|
+
export function resolveI18nLabel(label) {
|
|
7
|
+
if (label === undefined || label === null)
|
|
8
|
+
return undefined;
|
|
9
|
+
if (typeof label === 'string')
|
|
10
|
+
return label;
|
|
11
|
+
return label.defaultValue || label.key;
|
|
12
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@object-ui/react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"type": "module",
|
|
4
5
|
"license": "MIT",
|
|
5
6
|
"description": "React bindings and SchemaRenderer component for Object UI",
|
|
6
7
|
"homepage": "https://www.objectui.org",
|
|
@@ -12,19 +13,28 @@
|
|
|
12
13
|
"bugs": {
|
|
13
14
|
"url": "https://github.com/objectstack-ai/objectui/issues"
|
|
14
15
|
},
|
|
15
|
-
"main": "dist/index.js",
|
|
16
|
-
"
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
17
25
|
"dependencies": {
|
|
18
|
-
"@objectstack/spec": "^0.
|
|
26
|
+
"@objectstack/spec": "^2.0.7",
|
|
19
27
|
"react-hook-form": "^7.71.1",
|
|
20
|
-
"@object-ui/core": "0.
|
|
28
|
+
"@object-ui/core": "2.0.0",
|
|
29
|
+
"@object-ui/i18n": "2.0.0",
|
|
30
|
+
"@object-ui/types": "2.0.0"
|
|
21
31
|
},
|
|
22
32
|
"peerDependencies": {
|
|
23
33
|
"react": "^18.0.0 || ^19.0.0",
|
|
24
34
|
"react-dom": "^18.0.0 || ^19.0.0"
|
|
25
35
|
},
|
|
26
36
|
"devDependencies": {
|
|
27
|
-
"@types/react": "^19.2.
|
|
37
|
+
"@types/react": "^19.2.13",
|
|
28
38
|
"@types/react-dom": "^19.2.3",
|
|
29
39
|
"typescript": "^5.9.3"
|
|
30
40
|
},
|
|
@@ -0,0 +1,174 @@
|
|
|
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 React, { lazy, Suspense, Component } from 'react';
|
|
10
|
+
|
|
11
|
+
export interface LazyPluginOptions {
|
|
12
|
+
/**
|
|
13
|
+
* Fallback component to show while loading
|
|
14
|
+
*/
|
|
15
|
+
fallback?: React.ReactNode;
|
|
16
|
+
/**
|
|
17
|
+
* Number of retry attempts on load failure (default: 2)
|
|
18
|
+
*/
|
|
19
|
+
retries?: number;
|
|
20
|
+
/**
|
|
21
|
+
* Delay in ms between retries (default: 1000)
|
|
22
|
+
*/
|
|
23
|
+
retryDelay?: number;
|
|
24
|
+
/**
|
|
25
|
+
* Custom error fallback component
|
|
26
|
+
*/
|
|
27
|
+
errorFallback?: React.ComponentType<{ error: Error; retry: () => void }>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Error boundary for lazy-loaded plugins
|
|
32
|
+
*/
|
|
33
|
+
interface ErrorBoundaryState {
|
|
34
|
+
hasError: boolean;
|
|
35
|
+
error: Error | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
class PluginErrorBoundary extends Component<
|
|
39
|
+
{ fallback?: React.ComponentType<{ error: Error; retry: () => void }>; children: React.ReactNode },
|
|
40
|
+
ErrorBoundaryState
|
|
41
|
+
> {
|
|
42
|
+
state: ErrorBoundaryState = { hasError: false, error: null };
|
|
43
|
+
|
|
44
|
+
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
|
|
45
|
+
return { hasError: true, error };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
handleRetry = () => {
|
|
49
|
+
this.setState({ hasError: false, error: null });
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
render() {
|
|
53
|
+
if (this.state.hasError && this.state.error) {
|
|
54
|
+
const FallbackComponent = this.props.fallback;
|
|
55
|
+
if (FallbackComponent) {
|
|
56
|
+
return <FallbackComponent error={this.state.error} retry={this.handleRetry} />;
|
|
57
|
+
}
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
return this.props.children;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Create a lazy-loaded import function with retry support
|
|
66
|
+
*/
|
|
67
|
+
function createRetryImport<P extends object>(
|
|
68
|
+
importFn: () => Promise<{ default: React.ComponentType<P> }>,
|
|
69
|
+
retries: number,
|
|
70
|
+
retryDelay: number,
|
|
71
|
+
): () => Promise<{ default: React.ComponentType<P> }> {
|
|
72
|
+
return () => {
|
|
73
|
+
let attempt = 0;
|
|
74
|
+
const tryImport = (): Promise<{ default: React.ComponentType<P> }> =>
|
|
75
|
+
importFn().catch((err) => {
|
|
76
|
+
attempt++;
|
|
77
|
+
if (attempt <= retries) {
|
|
78
|
+
return new Promise((resolve) =>
|
|
79
|
+
setTimeout(() => resolve(tryImport()), retryDelay),
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
throw err;
|
|
83
|
+
});
|
|
84
|
+
return tryImport();
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Create a lazy-loaded plugin component with Suspense wrapper
|
|
90
|
+
*
|
|
91
|
+
* @param importFn - Dynamic import function that returns a module with default export
|
|
92
|
+
* @param options - Configuration options for the lazy plugin
|
|
93
|
+
* @returns A component that lazy loads the plugin
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```tsx
|
|
97
|
+
* // Basic usage
|
|
98
|
+
* const ObjectGrid = createLazyPlugin(
|
|
99
|
+
* () => import('@object-ui/plugin-grid')
|
|
100
|
+
* );
|
|
101
|
+
*
|
|
102
|
+
* // With custom fallback
|
|
103
|
+
* const ObjectGrid = createLazyPlugin(
|
|
104
|
+
* () => import('@object-ui/plugin-grid'),
|
|
105
|
+
* { fallback: <div>Loading grid...</div> }
|
|
106
|
+
* );
|
|
107
|
+
*
|
|
108
|
+
* // With retry and error handling
|
|
109
|
+
* const ObjectGrid = createLazyPlugin(
|
|
110
|
+
* () => import('@object-ui/plugin-grid'),
|
|
111
|
+
* {
|
|
112
|
+
* retries: 3,
|
|
113
|
+
* errorFallback: ({ error, retry }) => (
|
|
114
|
+
* <div>
|
|
115
|
+
* <p>Failed to load: {error.message}</p>
|
|
116
|
+
* <button onClick={retry}>Retry</button>
|
|
117
|
+
* </div>
|
|
118
|
+
* ),
|
|
119
|
+
* }
|
|
120
|
+
* );
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
export function createLazyPlugin<P extends object = any>(
|
|
124
|
+
importFn: () => Promise<{ default: React.ComponentType<P> }>,
|
|
125
|
+
options?: LazyPluginOptions
|
|
126
|
+
): React.ComponentType<P> {
|
|
127
|
+
const { retries = 2, retryDelay = 1000, errorFallback } = options || {};
|
|
128
|
+
|
|
129
|
+
const retryImport = retries > 0
|
|
130
|
+
? createRetryImport(importFn, retries, retryDelay)
|
|
131
|
+
: importFn;
|
|
132
|
+
|
|
133
|
+
const LazyComponent = lazy(retryImport);
|
|
134
|
+
|
|
135
|
+
const PluginWrapper: React.FC<P> = (props) => {
|
|
136
|
+
const content = (
|
|
137
|
+
<Suspense fallback={options?.fallback || null}>
|
|
138
|
+
<LazyComponent {...props} />
|
|
139
|
+
</Suspense>
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
if (errorFallback) {
|
|
143
|
+
return (
|
|
144
|
+
<PluginErrorBoundary fallback={errorFallback}>
|
|
145
|
+
{content}
|
|
146
|
+
</PluginErrorBoundary>
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return content;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
return PluginWrapper;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Preload a plugin module without rendering it.
|
|
158
|
+
* Useful for preloading plugins that will be needed soon.
|
|
159
|
+
*
|
|
160
|
+
* @param importFn - Dynamic import function
|
|
161
|
+
* @returns Promise that resolves when the module is loaded
|
|
162
|
+
*
|
|
163
|
+
* @example
|
|
164
|
+
* ```tsx
|
|
165
|
+
* // Preload on hover
|
|
166
|
+
* const loadGrid = () => import('@object-ui/plugin-grid');
|
|
167
|
+
* <button onMouseEnter={() => preloadPlugin(loadGrid)}>Show Grid</button>
|
|
168
|
+
* ```
|
|
169
|
+
*/
|
|
170
|
+
export function preloadPlugin<T = unknown>(
|
|
171
|
+
importFn: () => Promise<T>,
|
|
172
|
+
): Promise<T> {
|
|
173
|
+
return importFn();
|
|
174
|
+
}
|
package/src/SchemaRenderer.tsx
CHANGED
|
@@ -6,33 +6,85 @@
|
|
|
6
6
|
* LICENSE file in the root directory of this source tree.
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
|
-
import React, { forwardRef } from 'react';
|
|
10
|
-
import { SchemaNode, ComponentRegistry } from '@object-ui/core';
|
|
9
|
+
import React, { forwardRef, useContext, useMemo } from 'react';
|
|
10
|
+
import { SchemaNode, ComponentRegistry, ExpressionEvaluator } from '@object-ui/core';
|
|
11
|
+
import { SchemaRendererContext } from './context/SchemaRendererContext';
|
|
11
12
|
|
|
12
13
|
export const SchemaRenderer = forwardRef<any, { schema: SchemaNode } & Record<string, any>>(({ schema, ...props }, _ref) => {
|
|
13
|
-
|
|
14
|
+
const context = useContext(SchemaRendererContext);
|
|
15
|
+
const dataSource = context?.dataSource || {};
|
|
16
|
+
|
|
17
|
+
// Evaluate schema expressions against the data source
|
|
18
|
+
const evaluatedSchema = useMemo(() => {
|
|
19
|
+
if (!schema || typeof schema === 'string') return schema;
|
|
20
|
+
|
|
21
|
+
const evaluator = new ExpressionEvaluator({ data: dataSource });
|
|
22
|
+
// Shallow copy
|
|
23
|
+
const newSchema = { ...schema };
|
|
24
|
+
|
|
25
|
+
// COMPAT: Hoist 'properties' up to schema level
|
|
26
|
+
// This allows support for strict configs that wrap all props in 'properties'
|
|
27
|
+
if (newSchema.properties) {
|
|
28
|
+
Object.assign(newSchema, newSchema.properties);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Evaluate 'content' (common in Text, Button)
|
|
32
|
+
if (typeof newSchema.content === 'string') {
|
|
33
|
+
newSchema.content = evaluator.evaluate(newSchema.content);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Evaluate 'props'
|
|
37
|
+
if (newSchema.props) {
|
|
38
|
+
const newProps = { ...newSchema.props };
|
|
39
|
+
for (const [key, val] of Object.entries(newProps)) {
|
|
40
|
+
newProps[key] = evaluator.evaluate(val as any);
|
|
41
|
+
}
|
|
42
|
+
newSchema.props = newProps;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return newSchema;
|
|
46
|
+
}, [schema, dataSource]);
|
|
47
|
+
|
|
48
|
+
if (!evaluatedSchema) return null;
|
|
14
49
|
// If schema is just a string, render it as text
|
|
15
|
-
if (typeof
|
|
50
|
+
if (typeof evaluatedSchema === 'string') return <>{evaluatedSchema}</>;
|
|
16
51
|
|
|
17
|
-
const Component = ComponentRegistry.get(
|
|
52
|
+
const Component = ComponentRegistry.get(evaluatedSchema.type);
|
|
18
53
|
|
|
19
54
|
if (!Component) {
|
|
20
55
|
return (
|
|
21
56
|
<div className="p-4 border border-red-500 rounded text-red-500 bg-red-50 my-2">
|
|
22
|
-
Unknown component type: <strong>{
|
|
23
|
-
<pre className="text-xs mt-2 overflow-auto">{JSON.stringify(
|
|
57
|
+
Unknown component type: <strong>{evaluatedSchema.type}</strong>
|
|
58
|
+
<pre className="text-xs mt-2 overflow-auto">{JSON.stringify(evaluatedSchema, null, 2)}</pre>
|
|
24
59
|
</div>
|
|
25
60
|
);
|
|
26
61
|
}
|
|
27
62
|
|
|
28
63
|
// Note: We don't forward the ref to the Component because components in the registry
|
|
29
64
|
// may not support refs. The SchemaRenderer itself can still receive refs for its own use.
|
|
65
|
+
|
|
66
|
+
// Extract schema metadata properties that should NOT be passed as React props
|
|
67
|
+
const {
|
|
68
|
+
type: _type,
|
|
69
|
+
children: _children,
|
|
70
|
+
body: _body,
|
|
71
|
+
schema: _schema,
|
|
72
|
+
visible: _visible,
|
|
73
|
+
visibleOn: _visibleOn,
|
|
74
|
+
hidden: _hidden,
|
|
75
|
+
hiddenOn: _hiddenOn,
|
|
76
|
+
disabled: _disabled,
|
|
77
|
+
disabledOn: _disabledOn,
|
|
78
|
+
...componentProps
|
|
79
|
+
} = evaluatedSchema;
|
|
80
|
+
|
|
30
81
|
return React.createElement(Component, {
|
|
31
|
-
schema,
|
|
32
|
-
...
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
'data-obj-
|
|
82
|
+
schema: evaluatedSchema,
|
|
83
|
+
...componentProps, // Spread non-metadata schema properties as props
|
|
84
|
+
...(evaluatedSchema.props || {}), // Override with explicit props if provided
|
|
85
|
+
className: evaluatedSchema.className,
|
|
86
|
+
'data-obj-id': evaluatedSchema.id,
|
|
87
|
+
'data-obj-type': evaluatedSchema.type,
|
|
36
88
|
...props
|
|
37
89
|
});
|
|
38
90
|
});
|