@object-ui/react 3.1.4 → 3.3.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 +1 -1
- package/CHANGELOG.md +25 -0
- package/README.md +7 -2
- package/dist/SchemaRenderer.js +2 -2
- package/dist/components/form/FieldFactory.js +5 -2
- package/dist/hooks/index.d.ts +1 -0
- package/dist/hooks/index.js +1 -0
- package/dist/hooks/useDataRefresh.d.ts +36 -0
- package/dist/hooks/useDataRefresh.js +50 -0
- package/dist/hooks/useDiscovery.d.ts +12 -0
- package/dist/hooks/useDiscovery.js +6 -0
- package/dist/hooks/usePerformanceBudget.js +1 -1
- package/package.json +7 -7
- package/src/SchemaRenderer.tsx +2 -2
- package/src/components/form/FieldFactory.tsx +9 -2
- package/src/hooks/__tests__/useDataRefresh.test.ts +115 -0
- package/src/hooks/__tests__/useDiscovery.test.tsx +98 -0
- package/src/hooks/index.ts +1 -0
- package/src/hooks/useDataRefresh.ts +58 -0
- package/src/hooks/useDiscovery.ts +14 -0
- package/src/hooks/usePerformanceBudget.ts +1 -1
- package/tsconfig.tsbuildinfo +1 -1
package/.turbo/turbo-build.log
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,30 @@
|
|
|
1
1
|
# @object-ui/react
|
|
2
2
|
|
|
3
|
+
## 3.3.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- @object-ui/types@3.3.0
|
|
8
|
+
- @object-ui/core@3.3.0
|
|
9
|
+
- @object-ui/i18n@3.3.0
|
|
10
|
+
|
|
11
|
+
## 3.2.0
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- @object-ui/types@3.2.0
|
|
16
|
+
- @object-ui/core@3.2.0
|
|
17
|
+
- @object-ui/i18n@3.2.0
|
|
18
|
+
|
|
19
|
+
## 3.1.5
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- Updated dependencies [cfe0596]
|
|
24
|
+
- @object-ui/i18n@3.1.5
|
|
25
|
+
- @object-ui/types@3.1.5
|
|
26
|
+
- @object-ui/core@3.1.5
|
|
27
|
+
|
|
3
28
|
## 3.1.4
|
|
4
29
|
|
|
5
30
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -120,13 +120,18 @@ Access server discovery information including preview mode detection:
|
|
|
120
120
|
import { useDiscovery } from '@object-ui/react'
|
|
121
121
|
|
|
122
122
|
function MyComponent() {
|
|
123
|
-
const { discovery, isLoading, isAuthEnabled } = useDiscovery()
|
|
123
|
+
const { discovery, isLoading, isAuthEnabled, isAiEnabled } = useDiscovery()
|
|
124
124
|
|
|
125
125
|
// Check if the server is in preview mode
|
|
126
126
|
if (discovery?.mode === 'preview') {
|
|
127
127
|
console.log('Preview mode active:', discovery.previewMode)
|
|
128
128
|
}
|
|
129
129
|
|
|
130
|
+
// Check if AI service is available
|
|
131
|
+
if (isAiEnabled) {
|
|
132
|
+
console.log('AI service route:', discovery?.services?.ai?.route)
|
|
133
|
+
}
|
|
134
|
+
|
|
130
135
|
return <div>Server: {discovery?.name}</div>
|
|
131
136
|
}
|
|
132
137
|
```
|
|
@@ -139,7 +144,7 @@ function MyComponent() {
|
|
|
139
144
|
| `version` | `string` | Server version |
|
|
140
145
|
| `mode` | `string` | Runtime mode (e.g. `'development'`, `'production'`, `'preview'`) |
|
|
141
146
|
| `previewMode` | `object` | Preview mode configuration (present when mode is `'preview'`) |
|
|
142
|
-
| `services` | `object` | Service availability status (auth, data, metadata) |
|
|
147
|
+
| `services` | `object` | Service availability status (auth, data, metadata, ai) |
|
|
143
148
|
| `capabilities` | `string[]` | API capabilities |
|
|
144
149
|
|
|
145
150
|
The `previewMode` object contains:
|
package/dist/SchemaRenderer.js
CHANGED
|
@@ -56,7 +56,7 @@ export class SchemaErrorBoundary extends Component {
|
|
|
56
56
|
render() {
|
|
57
57
|
if (this.state.hasError && this.state.error) {
|
|
58
58
|
const error = this.state.error;
|
|
59
|
-
const isDev = process
|
|
59
|
+
const isDev = globalThis.process?.env?.NODE_ENV !== 'production';
|
|
60
60
|
const objuiError = isObjectUIError(error) ? error : null;
|
|
61
61
|
return (_jsxs("div", { className: "p-4 border border-orange-400 rounded bg-orange-50 text-orange-700 my-2", role: "alert", children: [_jsxs("p", { className: "font-medium", children: ["Component", this.props.componentType ? ` "${this.props.componentType}"` : '', " failed to render"] }), _jsx("p", { className: "text-sm mt-1", children: error.message }), isDev && objuiError?.code && (_jsxs("p", { className: "text-xs mt-1 text-orange-500", children: ["Error code: ", objuiError.code, objuiError.details?.suggestion ? (_jsxs("span", { className: "block mt-0.5", children: ["\uD83D\uDCA1 ", String(objuiError.details.suggestion)] })) : null] })), _jsx("button", { onClick: this.handleRetry, className: "mt-2 text-sm underline hover:no-underline", children: "Retry" })] }));
|
|
62
62
|
}
|
|
@@ -137,7 +137,7 @@ export const SchemaRenderer = forwardRef(({ schema, ...props }, _ref) => {
|
|
|
137
137
|
if (!Component) {
|
|
138
138
|
debugLog('schema', 'Component not found in registry', { type: evaluatedSchema.type });
|
|
139
139
|
const errorInfo = ERROR_CODES['OBJUI-001'];
|
|
140
|
-
return (_jsxs("div", { className: "p-4 border border-red-500 rounded text-red-500 bg-red-50 my-2", role: "alert", children: [_jsxs("p", { className: "font-medium", children: ["Unknown component type: ", _jsx("strong", { children: evaluatedSchema.type })] }), process
|
|
140
|
+
return (_jsxs("div", { className: "p-4 border border-red-500 rounded text-red-500 bg-red-50 my-2", role: "alert", children: [_jsxs("p", { className: "font-medium", children: ["Unknown component type: ", _jsx("strong", { children: evaluatedSchema.type })] }), globalThis.process?.env?.NODE_ENV !== 'production' && (_jsxs("p", { className: "text-xs mt-1", children: ["\uD83D\uDCA1 ", errorInfo.suggestion, " (OBJUI-001)"] })), _jsx("pre", { className: "text-xs mt-2 overflow-auto", children: JSON.stringify(evaluatedSchema, null, 2) })] }));
|
|
141
141
|
}
|
|
142
142
|
// Note: We don't forward the ref to the Component because components in the registry
|
|
143
143
|
// may not support refs. The SchemaRenderer itself can still receive refs for its own use.
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
2
|
import { resolveI18nLabel } from '../../utils/i18n';
|
|
3
|
+
import { createSafeTranslation } from '@object-ui/i18n';
|
|
4
|
+
const useSafeTranslation = createSafeTranslation({ 'common.selectOption': 'Select an option' }, 'common.selectOption');
|
|
3
5
|
/**
|
|
4
6
|
* FieldFactory component that renders different input types based on
|
|
5
7
|
* the widget property or field type
|
|
6
8
|
*/
|
|
7
9
|
export const FieldFactory = ({ field, methods, disabled = false, }) => {
|
|
8
10
|
const { register, formState: { errors } } = methods;
|
|
11
|
+
const { t } = useSafeTranslation();
|
|
9
12
|
// Cast to extended field for properties not in base schema
|
|
10
13
|
const extendedField = field;
|
|
11
14
|
// Determine the widget type
|
|
@@ -61,7 +64,7 @@ export const FieldFactory = ({ field, methods, disabled = false, }) => {
|
|
|
61
64
|
return renderField(_jsxs("select", { id: fieldName, disabled: disabled, multiple: extendedField.multiple, className: "w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed", ...register(fieldName, {
|
|
62
65
|
required: field.required ? `${fieldLabel || fieldName} is required` : false,
|
|
63
66
|
setValueAs: handleMultipleSelectValue,
|
|
64
|
-
}), children: [!extendedField.multiple && _jsx("option", { value: "", children: fieldPlaceholder || '
|
|
67
|
+
}), children: [!extendedField.multiple && _jsx("option", { value: "", children: fieldPlaceholder || t('common.selectOption') }), extendedField.options?.map((option) => (_jsx("option", { value: option.value, disabled: option.disabled, children: option.label }, option.value)))] }));
|
|
65
68
|
case 'date':
|
|
66
69
|
return renderField(_jsx("input", { id: fieldName, type: "date", placeholder: fieldPlaceholder, disabled: disabled, className: "w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed", ...register(fieldName, {
|
|
67
70
|
required: field.required ? `${fieldLabel || fieldName} is required` : false,
|
|
@@ -118,7 +121,7 @@ export const FieldFactory = ({ field, methods, disabled = false, }) => {
|
|
|
118
121
|
return renderField(_jsxs("select", { id: fieldName, disabled: disabled, multiple: extendedField.multiple, className: "w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed", ...register(fieldName, {
|
|
119
122
|
required: field.required ? `${fieldLabel || fieldName} is required` : false,
|
|
120
123
|
setValueAs: handleMultipleSelectValue,
|
|
121
|
-
}), children: [!extendedField.multiple && _jsx("option", { value: "", children: fieldPlaceholder || '
|
|
124
|
+
}), children: [!extendedField.multiple && _jsx("option", { value: "", children: fieldPlaceholder || t('common.selectOption') }), extendedField.options?.map((option) => (_jsx("option", { value: option.value, disabled: option.disabled, children: option.label }, option.value)))] }));
|
|
122
125
|
case 'user':
|
|
123
126
|
case 'owner':
|
|
124
127
|
return renderField(_jsxs("select", { id: fieldName, disabled: disabled, multiple: extendedField.multiple, className: "w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:bg-gray-100 disabled:cursor-not-allowed", ...register(fieldName, {
|
package/dist/hooks/index.d.ts
CHANGED
package/dist/hooks/index.js
CHANGED
|
@@ -0,0 +1,36 @@
|
|
|
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
|
+
import type { DataSource } from '@object-ui/types';
|
|
9
|
+
/**
|
|
10
|
+
* Reusable hook that encapsulates the data-refresh pattern:
|
|
11
|
+
* 1. A numeric `refreshKey` that triggers React effect re-runs when incremented.
|
|
12
|
+
* 2. An imperative `refresh()` function to trigger a re-fetch on demand.
|
|
13
|
+
* 3. Auto-subscription to `DataSource.onMutation()` — if the DataSource
|
|
14
|
+
* implements the optional mutation event bus, the hook auto-refreshes
|
|
15
|
+
* whenever a mutation occurs on the matching `objectName`.
|
|
16
|
+
*
|
|
17
|
+
* @param dataSource - The DataSource instance (may be undefined during initial render)
|
|
18
|
+
* @param objectName - The resource/object name to watch for mutations
|
|
19
|
+
* @returns `{ refreshKey, refresh }` — include `refreshKey` in your effect deps
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```tsx
|
|
23
|
+
* const { refreshKey, refresh } = useDataRefresh(dataSource, schema.objectName);
|
|
24
|
+
*
|
|
25
|
+
* useEffect(() => {
|
|
26
|
+
* dataSource.find(objectName, params).then(setData);
|
|
27
|
+
* }, [objectName, refreshKey]);
|
|
28
|
+
*
|
|
29
|
+
* // Or trigger manually:
|
|
30
|
+
* <button onClick={refresh}>Refresh</button>
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function useDataRefresh(dataSource: DataSource | undefined, objectName: string | undefined): {
|
|
34
|
+
refreshKey: number;
|
|
35
|
+
refresh: () => void;
|
|
36
|
+
};
|
|
@@ -0,0 +1,50 @@
|
|
|
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
|
+
import { useState, useCallback, useEffect } from 'react';
|
|
9
|
+
/**
|
|
10
|
+
* Reusable hook that encapsulates the data-refresh pattern:
|
|
11
|
+
* 1. A numeric `refreshKey` that triggers React effect re-runs when incremented.
|
|
12
|
+
* 2. An imperative `refresh()` function to trigger a re-fetch on demand.
|
|
13
|
+
* 3. Auto-subscription to `DataSource.onMutation()` — if the DataSource
|
|
14
|
+
* implements the optional mutation event bus, the hook auto-refreshes
|
|
15
|
+
* whenever a mutation occurs on the matching `objectName`.
|
|
16
|
+
*
|
|
17
|
+
* @param dataSource - The DataSource instance (may be undefined during initial render)
|
|
18
|
+
* @param objectName - The resource/object name to watch for mutations
|
|
19
|
+
* @returns `{ refreshKey, refresh }` — include `refreshKey` in your effect deps
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```tsx
|
|
23
|
+
* const { refreshKey, refresh } = useDataRefresh(dataSource, schema.objectName);
|
|
24
|
+
*
|
|
25
|
+
* useEffect(() => {
|
|
26
|
+
* dataSource.find(objectName, params).then(setData);
|
|
27
|
+
* }, [objectName, refreshKey]);
|
|
28
|
+
*
|
|
29
|
+
* // Or trigger manually:
|
|
30
|
+
* <button onClick={refresh}>Refresh</button>
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export function useDataRefresh(dataSource, objectName) {
|
|
34
|
+
const [refreshKey, setRefreshKey] = useState(0);
|
|
35
|
+
const refresh = useCallback(() => {
|
|
36
|
+
setRefreshKey(k => k + 1);
|
|
37
|
+
}, []);
|
|
38
|
+
// Auto-subscribe to DataSource mutation events
|
|
39
|
+
useEffect(() => {
|
|
40
|
+
if (!dataSource?.onMutation || !objectName)
|
|
41
|
+
return;
|
|
42
|
+
const unsub = dataSource.onMutation((event) => {
|
|
43
|
+
if (event.resource === objectName) {
|
|
44
|
+
setRefreshKey(k => k + 1);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
return unsub;
|
|
48
|
+
}, [dataSource, objectName]);
|
|
49
|
+
return { refreshKey, refresh };
|
|
50
|
+
}
|
|
@@ -42,6 +42,13 @@ export interface DiscoveryInfo {
|
|
|
42
42
|
enabled: boolean;
|
|
43
43
|
status?: 'available' | 'unavailable';
|
|
44
44
|
};
|
|
45
|
+
/** AI service configuration */
|
|
46
|
+
ai?: {
|
|
47
|
+
enabled: boolean;
|
|
48
|
+
status?: 'available' | 'unavailable';
|
|
49
|
+
/** AI service endpoint route (e.g. '/api/v1/ai') */
|
|
50
|
+
route?: string;
|
|
51
|
+
};
|
|
45
52
|
[key: string]: any;
|
|
46
53
|
};
|
|
47
54
|
/** API capabilities */
|
|
@@ -86,4 +93,9 @@ export declare function useDiscovery(): {
|
|
|
86
93
|
* Defaults to true if discovery data is not available.
|
|
87
94
|
*/
|
|
88
95
|
isAuthEnabled: boolean;
|
|
96
|
+
/**
|
|
97
|
+
* Check if AI service is enabled and available on the server.
|
|
98
|
+
* Defaults to false if discovery data is not available.
|
|
99
|
+
*/
|
|
100
|
+
isAiEnabled: boolean;
|
|
89
101
|
};
|
|
@@ -92,5 +92,11 @@ export function useDiscovery() {
|
|
|
92
92
|
* Defaults to true if discovery data is not available.
|
|
93
93
|
*/
|
|
94
94
|
isAuthEnabled: discovery?.services?.auth?.enabled ?? true,
|
|
95
|
+
/**
|
|
96
|
+
* Check if AI service is enabled and available on the server.
|
|
97
|
+
* Defaults to false if discovery data is not available.
|
|
98
|
+
*/
|
|
99
|
+
isAiEnabled: discovery?.services?.ai?.enabled === true &&
|
|
100
|
+
discovery?.services?.ai?.status === 'available',
|
|
95
101
|
};
|
|
96
102
|
}
|
|
@@ -122,7 +122,7 @@ export function usePerformanceBudget(userBudget = {}) {
|
|
|
122
122
|
timestamp: Date.now(),
|
|
123
123
|
};
|
|
124
124
|
setViolations((prev) => [...prev, violation]);
|
|
125
|
-
if (budget.warnOnViolation && process
|
|
125
|
+
if (budget.warnOnViolation && globalThis.process?.env?.NODE_ENV !== 'production') {
|
|
126
126
|
console.warn(`[ObjectUI] Performance budget violated: ${metric} = ${violation.actual} (budget: ${budgetValue})`);
|
|
127
127
|
}
|
|
128
128
|
onViolationRef.current?.(violation);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@object-ui/react",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"description": "React bindings and SchemaRenderer component for Object UI",
|
|
@@ -24,11 +24,11 @@
|
|
|
24
24
|
}
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@objectstack/spec": "^
|
|
28
|
-
"react-hook-form": "^7.72.
|
|
29
|
-
"@object-ui/core": "3.
|
|
30
|
-
"@object-ui/i18n": "3.
|
|
31
|
-
"@object-ui/types": "3.
|
|
27
|
+
"@objectstack/spec": "^4.0.3",
|
|
28
|
+
"react-hook-form": "^7.72.1",
|
|
29
|
+
"@object-ui/core": "3.3.0",
|
|
30
|
+
"@object-ui/i18n": "3.3.0",
|
|
31
|
+
"@object-ui/types": "3.3.0"
|
|
32
32
|
},
|
|
33
33
|
"peerDependencies": {
|
|
34
34
|
"react": "^18.0.0 || ^19.0.0",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"@types/react": "19.2.14",
|
|
39
39
|
"@types/react-dom": "19.2.3",
|
|
40
|
-
"typescript": "^
|
|
40
|
+
"typescript": "^6.0.2"
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "tsc",
|
package/src/SchemaRenderer.tsx
CHANGED
|
@@ -72,7 +72,7 @@ export class SchemaErrorBoundary extends Component<
|
|
|
72
72
|
render() {
|
|
73
73
|
if (this.state.hasError && this.state.error) {
|
|
74
74
|
const error = this.state.error;
|
|
75
|
-
const isDev = process
|
|
75
|
+
const isDev = (globalThis as any).process?.env?.NODE_ENV !== 'production';
|
|
76
76
|
const objuiError = isObjectUIError(error) ? error as ObjectUIError : null;
|
|
77
77
|
|
|
78
78
|
return (
|
|
@@ -189,7 +189,7 @@ export const SchemaRenderer = forwardRef<any, { schema: SchemaNode } & Record<st
|
|
|
189
189
|
return (
|
|
190
190
|
<div className="p-4 border border-red-500 rounded text-red-500 bg-red-50 my-2" role="alert">
|
|
191
191
|
<p className="font-medium">Unknown component type: <strong>{evaluatedSchema.type}</strong></p>
|
|
192
|
-
{process
|
|
192
|
+
{(globalThis as any).process?.env?.NODE_ENV !== 'production' && (
|
|
193
193
|
<p className="text-xs mt-1">💡 {errorInfo.suggestion} (OBJUI-001)</p>
|
|
194
194
|
)}
|
|
195
195
|
<pre className="text-xs mt-2 overflow-auto">{JSON.stringify(evaluatedSchema, null, 2)}</pre>
|
|
@@ -10,6 +10,12 @@ import React from 'react';
|
|
|
10
10
|
import { UseFormReturn } from 'react-hook-form';
|
|
11
11
|
import type { FormField } from '@objectstack/spec/ui';
|
|
12
12
|
import { resolveI18nLabel } from '../../utils/i18n';
|
|
13
|
+
import { createSafeTranslation } from '@object-ui/i18n';
|
|
14
|
+
|
|
15
|
+
const useSafeTranslation = createSafeTranslation(
|
|
16
|
+
{ 'common.selectOption': 'Select an option' },
|
|
17
|
+
'common.selectOption',
|
|
18
|
+
);
|
|
13
19
|
|
|
14
20
|
/**
|
|
15
21
|
* Extended form field with additional properties for complex widgets
|
|
@@ -51,6 +57,7 @@ export const FieldFactory: React.FC<FieldFactoryProps> = ({
|
|
|
51
57
|
disabled = false,
|
|
52
58
|
}) => {
|
|
53
59
|
const { register, formState: { errors } } = methods;
|
|
60
|
+
const { t } = useSafeTranslation();
|
|
54
61
|
|
|
55
62
|
// Cast to extended field for properties not in base schema
|
|
56
63
|
const extendedField = field as ExtendedFormField;
|
|
@@ -193,7 +200,7 @@ export const FieldFactory: React.FC<FieldFactoryProps> = ({
|
|
|
193
200
|
setValueAs: handleMultipleSelectValue,
|
|
194
201
|
})}
|
|
195
202
|
>
|
|
196
|
-
{!extendedField.multiple && <option value="">{fieldPlaceholder || '
|
|
203
|
+
{!extendedField.multiple && <option value="">{fieldPlaceholder || t('common.selectOption')}</option>}
|
|
197
204
|
{extendedField.options?.map((option) => (
|
|
198
205
|
<option key={option.value} value={option.value} disabled={option.disabled}>
|
|
199
206
|
{option.label}
|
|
@@ -400,7 +407,7 @@ export const FieldFactory: React.FC<FieldFactoryProps> = ({
|
|
|
400
407
|
setValueAs: handleMultipleSelectValue,
|
|
401
408
|
})}
|
|
402
409
|
>
|
|
403
|
-
{!extendedField.multiple && <option value="">{fieldPlaceholder || '
|
|
410
|
+
{!extendedField.multiple && <option value="">{fieldPlaceholder || t('common.selectOption')}</option>}
|
|
404
411
|
{extendedField.options?.map((option) => (
|
|
405
412
|
<option key={option.value} value={option.value} disabled={option.disabled}>
|
|
406
413
|
{option.label}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ObjectUI — useDataRefresh Tests
|
|
3
|
+
* Copyright (c) 2024-present ObjectStack Inc.
|
|
4
|
+
*
|
|
5
|
+
* Tests for the reusable data-refresh hook (P1/P2).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
9
|
+
import { renderHook, act } from '@testing-library/react';
|
|
10
|
+
import { useDataRefresh } from '../useDataRefresh';
|
|
11
|
+
|
|
12
|
+
describe('useDataRefresh', () => {
|
|
13
|
+
it('should return refreshKey=0 and a refresh function', () => {
|
|
14
|
+
const { result } = renderHook(() => useDataRefresh(undefined, undefined));
|
|
15
|
+
|
|
16
|
+
expect(result.current.refreshKey).toBe(0);
|
|
17
|
+
expect(typeof result.current.refresh).toBe('function');
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
it('should increment refreshKey when refresh() is called', () => {
|
|
21
|
+
const { result } = renderHook(() => useDataRefresh(undefined, 'contacts'));
|
|
22
|
+
|
|
23
|
+
act(() => {
|
|
24
|
+
result.current.refresh();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
expect(result.current.refreshKey).toBe(1);
|
|
28
|
+
|
|
29
|
+
act(() => {
|
|
30
|
+
result.current.refresh();
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
expect(result.current.refreshKey).toBe(2);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it('should auto-subscribe to DataSource.onMutation() when available', () => {
|
|
37
|
+
let listener: ((event: any) => void) | null = null;
|
|
38
|
+
const unsub = vi.fn();
|
|
39
|
+
const ds: any = {
|
|
40
|
+
onMutation: vi.fn((cb: any) => {
|
|
41
|
+
listener = cb;
|
|
42
|
+
return unsub;
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const { result } = renderHook(() => useDataRefresh(ds, 'contacts'));
|
|
47
|
+
|
|
48
|
+
expect(ds.onMutation).toHaveBeenCalledOnce();
|
|
49
|
+
|
|
50
|
+
// Simulate a mutation on the same resource
|
|
51
|
+
act(() => {
|
|
52
|
+
listener?.({ type: 'create', resource: 'contacts' });
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
expect(result.current.refreshKey).toBe(1);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('should NOT increment refreshKey for mutations on a different resource', () => {
|
|
59
|
+
let listener: ((event: any) => void) | null = null;
|
|
60
|
+
const ds: any = {
|
|
61
|
+
onMutation: vi.fn((cb: any) => {
|
|
62
|
+
listener = cb;
|
|
63
|
+
return vi.fn();
|
|
64
|
+
}),
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const { result } = renderHook(() => useDataRefresh(ds, 'contacts'));
|
|
68
|
+
|
|
69
|
+
act(() => {
|
|
70
|
+
listener?.({ type: 'create', resource: 'accounts' });
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
expect(result.current.refreshKey).toBe(0);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('should unsubscribe on unmount', () => {
|
|
77
|
+
const unsub = vi.fn();
|
|
78
|
+
const ds: any = {
|
|
79
|
+
onMutation: vi.fn(() => unsub),
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const { unmount } = renderHook(() => useDataRefresh(ds, 'contacts'));
|
|
83
|
+
|
|
84
|
+
expect(unsub).not.toHaveBeenCalled();
|
|
85
|
+
|
|
86
|
+
unmount();
|
|
87
|
+
|
|
88
|
+
expect(unsub).toHaveBeenCalledOnce();
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('should work without onMutation (backward compatible)', () => {
|
|
92
|
+
const ds: any = {
|
|
93
|
+
find: vi.fn(),
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const { result } = renderHook(() => useDataRefresh(ds, 'contacts'));
|
|
97
|
+
|
|
98
|
+
expect(result.current.refreshKey).toBe(0);
|
|
99
|
+
// Should not throw
|
|
100
|
+
act(() => {
|
|
101
|
+
result.current.refresh();
|
|
102
|
+
});
|
|
103
|
+
expect(result.current.refreshKey).toBe(1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('should skip subscription when objectName is undefined', () => {
|
|
107
|
+
const ds: any = {
|
|
108
|
+
onMutation: vi.fn(() => vi.fn()),
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
renderHook(() => useDataRefresh(ds, undefined));
|
|
112
|
+
|
|
113
|
+
expect(ds.onMutation).not.toHaveBeenCalled();
|
|
114
|
+
});
|
|
115
|
+
});
|
|
@@ -122,6 +122,104 @@ describe('useDiscovery', () => {
|
|
|
122
122
|
expect(result.current.isAuthEnabled).toBe(false);
|
|
123
123
|
});
|
|
124
124
|
|
|
125
|
+
it('isAiEnabled defaults to false when no discovery', async () => {
|
|
126
|
+
const { result } = renderHook(() => useDiscovery());
|
|
127
|
+
|
|
128
|
+
await waitFor(() => {
|
|
129
|
+
expect(result.current.isLoading).toBe(false);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
expect(result.current.isAiEnabled).toBe(false);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('isAiEnabled is true when ai service is enabled and available', async () => {
|
|
136
|
+
const discoveryData = {
|
|
137
|
+
services: {
|
|
138
|
+
ai: { enabled: true, status: 'available' as const, route: '/api/v1/ai' },
|
|
139
|
+
},
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const dataSource = {
|
|
143
|
+
getDiscovery: vi.fn().mockResolvedValue(discoveryData),
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
const { result } = renderHook(() => useDiscovery(), {
|
|
147
|
+
wrapper: createWrapper(dataSource),
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
await waitFor(() => {
|
|
151
|
+
expect(result.current.isLoading).toBe(false);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
expect(result.current.isAiEnabled).toBe(true);
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
it('isAiEnabled is false when ai service is enabled but unavailable', async () => {
|
|
158
|
+
const discoveryData = {
|
|
159
|
+
services: {
|
|
160
|
+
ai: { enabled: true, status: 'unavailable' as const },
|
|
161
|
+
},
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
const dataSource = {
|
|
165
|
+
getDiscovery: vi.fn().mockResolvedValue(discoveryData),
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const { result } = renderHook(() => useDiscovery(), {
|
|
169
|
+
wrapper: createWrapper(dataSource),
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
await waitFor(() => {
|
|
173
|
+
expect(result.current.isLoading).toBe(false);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
expect(result.current.isAiEnabled).toBe(false);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
it('isAiEnabled is false when ai service is disabled', async () => {
|
|
180
|
+
const discoveryData = {
|
|
181
|
+
services: {
|
|
182
|
+
ai: { enabled: false, status: 'available' as const },
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const dataSource = {
|
|
187
|
+
getDiscovery: vi.fn().mockResolvedValue(discoveryData),
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const { result } = renderHook(() => useDiscovery(), {
|
|
191
|
+
wrapper: createWrapper(dataSource),
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
await waitFor(() => {
|
|
195
|
+
expect(result.current.isLoading).toBe(false);
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
expect(result.current.isAiEnabled).toBe(false);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
it('isAiEnabled is false when ai service has no status', async () => {
|
|
202
|
+
const discoveryData = {
|
|
203
|
+
services: {
|
|
204
|
+
ai: { enabled: true },
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
const dataSource = {
|
|
209
|
+
getDiscovery: vi.fn().mockResolvedValue(discoveryData),
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const { result } = renderHook(() => useDiscovery(), {
|
|
213
|
+
wrapper: createWrapper(dataSource),
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
await waitFor(() => {
|
|
217
|
+
expect(result.current.isLoading).toBe(false);
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
expect(result.current.isAiEnabled).toBe(false);
|
|
221
|
+
});
|
|
222
|
+
|
|
125
223
|
it('cleans up on unmount (cancelled flag)', async () => {
|
|
126
224
|
let resolveDiscovery: (value: any) => void;
|
|
127
225
|
const discoveryPromise = new Promise((resolve) => {
|
package/src/hooks/index.ts
CHANGED
|
@@ -0,0 +1,58 @@
|
|
|
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, useEffect } from 'react';
|
|
10
|
+
import type { DataSource } from '@object-ui/types';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Reusable hook that encapsulates the data-refresh pattern:
|
|
14
|
+
* 1. A numeric `refreshKey` that triggers React effect re-runs when incremented.
|
|
15
|
+
* 2. An imperative `refresh()` function to trigger a re-fetch on demand.
|
|
16
|
+
* 3. Auto-subscription to `DataSource.onMutation()` — if the DataSource
|
|
17
|
+
* implements the optional mutation event bus, the hook auto-refreshes
|
|
18
|
+
* whenever a mutation occurs on the matching `objectName`.
|
|
19
|
+
*
|
|
20
|
+
* @param dataSource - The DataSource instance (may be undefined during initial render)
|
|
21
|
+
* @param objectName - The resource/object name to watch for mutations
|
|
22
|
+
* @returns `{ refreshKey, refresh }` — include `refreshKey` in your effect deps
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* const { refreshKey, refresh } = useDataRefresh(dataSource, schema.objectName);
|
|
27
|
+
*
|
|
28
|
+
* useEffect(() => {
|
|
29
|
+
* dataSource.find(objectName, params).then(setData);
|
|
30
|
+
* }, [objectName, refreshKey]);
|
|
31
|
+
*
|
|
32
|
+
* // Or trigger manually:
|
|
33
|
+
* <button onClick={refresh}>Refresh</button>
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export function useDataRefresh(
|
|
37
|
+
dataSource: DataSource | undefined,
|
|
38
|
+
objectName: string | undefined,
|
|
39
|
+
): { refreshKey: number; refresh: () => void } {
|
|
40
|
+
const [refreshKey, setRefreshKey] = useState(0);
|
|
41
|
+
|
|
42
|
+
const refresh = useCallback(() => {
|
|
43
|
+
setRefreshKey(k => k + 1);
|
|
44
|
+
}, []);
|
|
45
|
+
|
|
46
|
+
// Auto-subscribe to DataSource mutation events
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
if (!dataSource?.onMutation || !objectName) return;
|
|
49
|
+
const unsub = dataSource.onMutation((event) => {
|
|
50
|
+
if (event.resource === objectName) {
|
|
51
|
+
setRefreshKey(k => k + 1);
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
return unsub;
|
|
55
|
+
}, [dataSource, objectName]);
|
|
56
|
+
|
|
57
|
+
return { refreshKey, refresh };
|
|
58
|
+
}
|