@object-ui/react 0.5.0 → 3.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 +1 -1
- package/CHANGELOG.md +32 -0
- package/dist/LazyPluginLoader.d.ts +44 -0
- package/dist/LazyPluginLoader.js +92 -3
- package/dist/SchemaRenderer.d.ts +20 -1
- package/dist/SchemaRenderer.js +76 -13
- 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/DndContext.d.ts +135 -0
- package/dist/context/DndContext.js +120 -0
- package/dist/context/NotificationContext.d.ts +113 -0
- package/dist/context/NotificationContext.js +130 -0
- package/dist/context/ThemeContext.d.ts +94 -0
- package/dist/context/ThemeContext.js +215 -0
- package/dist/context/index.d.ts +4 -0
- package/dist/context/index.js +4 -0
- package/dist/hooks/index.d.ts +22 -0
- package/dist/hooks/index.js +22 -0
- package/dist/hooks/useActionRunner.d.ts +21 -7
- package/dist/hooks/useActionRunner.js +27 -7
- package/dist/hooks/useAnimation.d.ts +46 -0
- package/dist/hooks/useAnimation.js +59 -0
- package/dist/hooks/useClientNotifications.d.ts +53 -0
- package/dist/hooks/useClientNotifications.js +190 -0
- package/dist/hooks/useColumnSummary.d.ts +38 -0
- package/dist/hooks/useColumnSummary.js +54 -0
- package/dist/hooks/useCrudShortcuts.d.ts +39 -0
- package/dist/hooks/useCrudShortcuts.js +96 -0
- package/dist/hooks/useDensityMode.d.ts +48 -0
- package/dist/hooks/useDensityMode.js +60 -0
- 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/useETagCache.d.ts +75 -0
- package/dist/hooks/useETagCache.js +306 -0
- package/dist/hooks/useFocusManagement.d.ts +89 -0
- package/dist/hooks/useFocusManagement.js +188 -0
- package/dist/hooks/useFocusTrap.d.ts +41 -0
- package/dist/hooks/useFocusTrap.js +103 -0
- package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
- package/dist/hooks/useKeyboardShortcuts.js +86 -0
- package/dist/hooks/useNavigationOverlay.d.ts +78 -0
- package/dist/hooks/useNavigationOverlay.js +112 -0
- package/dist/hooks/useOffline.d.ts +96 -0
- package/dist/hooks/useOffline.js +185 -0
- package/dist/hooks/usePageTransition.d.ts +60 -0
- package/dist/hooks/usePageTransition.js +111 -0
- package/dist/hooks/usePageVariables.d.ts +67 -0
- package/dist/hooks/usePageVariables.js +109 -0
- package/dist/hooks/usePerformance.d.ts +87 -0
- package/dist/hooks/usePerformance.js +165 -0
- package/dist/hooks/usePerformanceBudget.d.ts +78 -0
- package/dist/hooks/usePerformanceBudget.js +209 -0
- package/dist/hooks/useReducedMotion.d.ts +28 -0
- package/dist/hooks/useReducedMotion.js +48 -0
- package/dist/hooks/useSchemaPersistence.d.ts +87 -0
- package/dist/hooks/useSchemaPersistence.js +173 -0
- package/dist/hooks/useViewData.d.ts +73 -0
- package/dist/hooks/useViewData.js +135 -0
- package/dist/hooks/useViewSharing.d.ts +57 -0
- package/dist/hooks/useViewSharing.js +74 -0
- package/dist/hooks/useViewTransition.d.ts +54 -0
- package/dist/hooks/useViewTransition.js +83 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/utils/i18n.d.ts +10 -0
- package/dist/utils/i18n.js +12 -0
- package/package.json +7 -5
- package/src/LazyPluginLoader.tsx +129 -7
- package/src/SchemaRenderer.tsx +122 -13
- package/src/__tests__/LazyPluginLoader.test.tsx +97 -1
- package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
- package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
- package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
- package/src/__tests__/ThemeProvider.test.tsx +451 -0
- package/src/__tests__/useNavigationOverlay.test.ts +416 -0
- package/src/__tests__/useOffline.test.ts +198 -0
- package/src/__tests__/usePageTransition.test.ts +214 -0
- package/src/__tests__/usePageVariables.test.tsx +334 -0
- package/src/__tests__/usePerformance.test.ts +137 -0
- package/src/__tests__/useViewData.test.tsx +422 -0
- package/src/__tests__/view-switching.test.tsx +456 -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/DndContext.tsx +260 -0
- package/src/context/NotificationContext.tsx +280 -0
- package/src/context/ThemeContext.tsx +325 -0
- package/src/context/__tests__/ActionContext.test.tsx +174 -0
- package/src/context/__tests__/DndContext.test.tsx +150 -0
- package/src/context/__tests__/NotificationContext.test.tsx +176 -0
- package/src/context/index.ts +4 -0
- package/src/hooks/__tests__/useActionRunner.test.ts +153 -0
- package/src/hooks/__tests__/useAnimation.test.ts +82 -0
- package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
- package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
- package/src/hooks/__tests__/useDiscovery.test.tsx +149 -0
- package/src/hooks/__tests__/useDynamicApp.test.ts +161 -0
- package/src/hooks/__tests__/useETagCache.test.ts +153 -0
- package/src/hooks/__tests__/useExpression.test.ts +86 -0
- package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
- package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
- package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
- package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
- package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
- package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
- package/src/hooks/index.ts +22 -1
- package/src/hooks/useActionRunner.ts +49 -11
- package/src/hooks/useAnimation.ts +117 -0
- package/src/hooks/useClientNotifications.ts +251 -0
- package/src/hooks/useColumnSummary.ts +87 -0
- package/src/hooks/useCrudShortcuts.ts +126 -0
- package/src/hooks/useDensityMode.ts +102 -0
- package/src/hooks/useDiscovery.ts +141 -0
- package/src/hooks/useDynamicApp.ts +142 -0
- package/src/hooks/useETagCache.ts +404 -0
- package/src/hooks/useFocusManagement.ts +248 -0
- package/src/hooks/useFocusTrap.ts +138 -0
- package/src/hooks/useKeyboardShortcuts.ts +119 -0
- package/src/hooks/useNavigationOverlay.ts +180 -0
- package/src/hooks/useOffline.ts +301 -0
- package/src/hooks/usePageTransition.ts +187 -0
- package/src/hooks/usePageVariables.tsx +157 -0
- package/src/hooks/usePerformance.ts +246 -0
- package/src/hooks/usePerformanceBudget.ts +313 -0
- package/src/hooks/useReducedMotion.ts +53 -0
- package/src/hooks/useSchemaPersistence.ts +222 -0
- package/src/hooks/useViewData.ts +201 -0
- package/src/hooks/useViewSharing.ts +140 -0
- package/src/hooks/useViewTransition.ts +144 -0
- package/src/index.ts +21 -0
- package/src/utils/i18n.ts +10 -0
- package/tsconfig.json +1 -0
- package/tsconfig.tsbuildinfo +1 -1
- package/dist/__tests__/LazyPluginLoader.test.d.ts +0 -8
- package/dist/__tests__/LazyPluginLoader.test.js +0 -49
- 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,222 @@
|
|
|
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, useRef, useMemo } from 'react';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Persistence adapter interface for schema save/load operations.
|
|
13
|
+
* Implement this to connect to any backend (REST API, GraphQL, localStorage, etc.).
|
|
14
|
+
*/
|
|
15
|
+
export interface SchemaPersistenceAdapter {
|
|
16
|
+
/** Save a schema to the backend. Returns the saved schema ID. */
|
|
17
|
+
save: (id: string, schema: Record<string, unknown>) => Promise<string>;
|
|
18
|
+
/** Load a schema from the backend by ID. */
|
|
19
|
+
load: (id: string) => Promise<Record<string, unknown> | null>;
|
|
20
|
+
/** List all available schemas. */
|
|
21
|
+
list?: () => Promise<Array<{ id: string; name?: string; updatedAt?: string }>>;
|
|
22
|
+
/** Delete a schema from the backend. */
|
|
23
|
+
delete?: (id: string) => Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface SchemaPersistenceState {
|
|
27
|
+
/** Whether a save/load operation is in progress */
|
|
28
|
+
loading: boolean;
|
|
29
|
+
/** The last error from a save/load operation */
|
|
30
|
+
error: Error | null;
|
|
31
|
+
/** Whether the current schema has unsaved changes */
|
|
32
|
+
isDirty: boolean;
|
|
33
|
+
/** The last saved timestamp */
|
|
34
|
+
lastSavedAt: Date | null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface SchemaPersistenceResult extends SchemaPersistenceState {
|
|
38
|
+
/** Save the current schema */
|
|
39
|
+
save: (id: string, schema: Record<string, unknown>) => Promise<string | null>;
|
|
40
|
+
/** Load a schema by ID */
|
|
41
|
+
load: (id: string) => Promise<Record<string, unknown> | null>;
|
|
42
|
+
/** List available schemas */
|
|
43
|
+
list: () => Promise<Array<{ id: string; name?: string; updatedAt?: string }>>;
|
|
44
|
+
/** Delete a schema */
|
|
45
|
+
remove: (id: string) => Promise<boolean>;
|
|
46
|
+
/** Mark the current schema as dirty (has unsaved changes) */
|
|
47
|
+
markDirty: () => void;
|
|
48
|
+
/** Clear the error state */
|
|
49
|
+
clearError: () => void;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Default localStorage adapter for schema persistence.
|
|
54
|
+
* Useful for development and demos.
|
|
55
|
+
*/
|
|
56
|
+
export function createLocalStorageAdapter(prefix = 'objectui-schema'): SchemaPersistenceAdapter {
|
|
57
|
+
return {
|
|
58
|
+
async save(id: string, schema: Record<string, unknown>): Promise<string> {
|
|
59
|
+
const key = `${prefix}:${id}`;
|
|
60
|
+
const entry = { schema, updatedAt: new Date().toISOString() };
|
|
61
|
+
localStorage.setItem(key, JSON.stringify(entry));
|
|
62
|
+
// Update the index
|
|
63
|
+
const indexKey = `${prefix}:__index__`;
|
|
64
|
+
const index: string[] = JSON.parse(localStorage.getItem(indexKey) || '[]');
|
|
65
|
+
if (!index.includes(id)) {
|
|
66
|
+
index.push(id);
|
|
67
|
+
localStorage.setItem(indexKey, JSON.stringify(index));
|
|
68
|
+
}
|
|
69
|
+
return id;
|
|
70
|
+
},
|
|
71
|
+
async load(id: string): Promise<Record<string, unknown> | null> {
|
|
72
|
+
const key = `${prefix}:${id}`;
|
|
73
|
+
const raw = localStorage.getItem(key);
|
|
74
|
+
if (!raw) return null;
|
|
75
|
+
const entry = JSON.parse(raw);
|
|
76
|
+
return entry.schema ?? null;
|
|
77
|
+
},
|
|
78
|
+
async list(): Promise<Array<{ id: string; name?: string; updatedAt?: string }>> {
|
|
79
|
+
const indexKey = `${prefix}:__index__`;
|
|
80
|
+
const index: string[] = JSON.parse(localStorage.getItem(indexKey) || '[]');
|
|
81
|
+
return index.map((id) => {
|
|
82
|
+
const raw = localStorage.getItem(`${prefix}:${id}`);
|
|
83
|
+
const entry = raw ? JSON.parse(raw) : {};
|
|
84
|
+
return { id, name: id, updatedAt: entry.updatedAt };
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
async delete(id: string): Promise<void> {
|
|
88
|
+
const key = `${prefix}:${id}`;
|
|
89
|
+
localStorage.removeItem(key);
|
|
90
|
+
const indexKey = `${prefix}:__index__`;
|
|
91
|
+
const index: string[] = JSON.parse(localStorage.getItem(indexKey) || '[]');
|
|
92
|
+
localStorage.setItem(indexKey, JSON.stringify(index.filter((i) => i !== id)));
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Hook for persisting designer schemas (save/load/list/delete).
|
|
99
|
+
* Implements schema persistence for @object-ui/plugin-designer.
|
|
100
|
+
*
|
|
101
|
+
* Accepts a pluggable adapter for connecting to any backend.
|
|
102
|
+
* Falls back to a localStorage adapter for development use.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* ```tsx
|
|
106
|
+
* // With default localStorage adapter
|
|
107
|
+
* const persistence = useSchemaPersistence();
|
|
108
|
+
*
|
|
109
|
+
* // Save current design
|
|
110
|
+
* await persistence.save('my-page', pageSchema);
|
|
111
|
+
*
|
|
112
|
+
* // Load a design
|
|
113
|
+
* const schema = await persistence.load('my-page');
|
|
114
|
+
*
|
|
115
|
+
* // With custom API adapter
|
|
116
|
+
* const apiAdapter: SchemaPersistenceAdapter = {
|
|
117
|
+
* save: (id, schema) => fetch(`/api/schemas/${id}`, { method: 'PUT', body: JSON.stringify(schema) }).then(r => r.json()),
|
|
118
|
+
* load: (id) => fetch(`/api/schemas/${id}`).then(r => r.json()),
|
|
119
|
+
* list: () => fetch('/api/schemas').then(r => r.json()),
|
|
120
|
+
* delete: (id) => fetch(`/api/schemas/${id}`, { method: 'DELETE' }).then(() => {}),
|
|
121
|
+
* };
|
|
122
|
+
* const persistence = useSchemaPersistence(apiAdapter);
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
export function useSchemaPersistence(
|
|
126
|
+
adapter?: SchemaPersistenceAdapter,
|
|
127
|
+
): SchemaPersistenceResult {
|
|
128
|
+
const defaultAdapter = useRef(createLocalStorageAdapter());
|
|
129
|
+
const adapterRef = useRef(adapter ?? defaultAdapter.current);
|
|
130
|
+
// Keep the ref up to date if the adapter prop changes
|
|
131
|
+
adapterRef.current = adapter ?? defaultAdapter.current;
|
|
132
|
+
const [loading, setLoading] = useState(false);
|
|
133
|
+
const [error, setError] = useState<Error | null>(null);
|
|
134
|
+
const [isDirty, setIsDirty] = useState(false);
|
|
135
|
+
const [lastSavedAt, setLastSavedAt] = useState<Date | null>(null);
|
|
136
|
+
|
|
137
|
+
const save = useCallback(
|
|
138
|
+
async (id: string, schema: Record<string, unknown>): Promise<string | null> => {
|
|
139
|
+
setLoading(true);
|
|
140
|
+
setError(null);
|
|
141
|
+
try {
|
|
142
|
+
const result = await adapterRef.current.save(id, schema);
|
|
143
|
+
setIsDirty(false);
|
|
144
|
+
setLastSavedAt(new Date());
|
|
145
|
+
return result;
|
|
146
|
+
} catch (err) {
|
|
147
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
148
|
+
return null;
|
|
149
|
+
} finally {
|
|
150
|
+
setLoading(false);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
[],
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
const load = useCallback(async (id: string): Promise<Record<string, unknown> | null> => {
|
|
157
|
+
setLoading(true);
|
|
158
|
+
setError(null);
|
|
159
|
+
try {
|
|
160
|
+
const result = await adapterRef.current.load(id);
|
|
161
|
+
setIsDirty(false);
|
|
162
|
+
return result;
|
|
163
|
+
} catch (err) {
|
|
164
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
165
|
+
return null;
|
|
166
|
+
} finally {
|
|
167
|
+
setLoading(false);
|
|
168
|
+
}
|
|
169
|
+
}, []);
|
|
170
|
+
|
|
171
|
+
const list = useCallback(async (): Promise<Array<{ id: string; name?: string; updatedAt?: string }>> => {
|
|
172
|
+
setLoading(true);
|
|
173
|
+
setError(null);
|
|
174
|
+
try {
|
|
175
|
+
if (adapterRef.current.list) {
|
|
176
|
+
return await adapterRef.current.list();
|
|
177
|
+
}
|
|
178
|
+
return [];
|
|
179
|
+
} catch (err) {
|
|
180
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
181
|
+
return [];
|
|
182
|
+
} finally {
|
|
183
|
+
setLoading(false);
|
|
184
|
+
}
|
|
185
|
+
}, []);
|
|
186
|
+
|
|
187
|
+
const remove = useCallback(async (id: string): Promise<boolean> => {
|
|
188
|
+
setLoading(true);
|
|
189
|
+
setError(null);
|
|
190
|
+
try {
|
|
191
|
+
if (adapterRef.current.delete) {
|
|
192
|
+
await adapterRef.current.delete(id);
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
195
|
+
return false;
|
|
196
|
+
} catch (err) {
|
|
197
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
198
|
+
return false;
|
|
199
|
+
} finally {
|
|
200
|
+
setLoading(false);
|
|
201
|
+
}
|
|
202
|
+
}, []);
|
|
203
|
+
|
|
204
|
+
const markDirty = useCallback(() => setIsDirty(true), []);
|
|
205
|
+
const clearError = useCallback(() => setError(null), []);
|
|
206
|
+
|
|
207
|
+
return useMemo(
|
|
208
|
+
() => ({
|
|
209
|
+
loading,
|
|
210
|
+
error,
|
|
211
|
+
isDirty,
|
|
212
|
+
lastSavedAt,
|
|
213
|
+
save,
|
|
214
|
+
load,
|
|
215
|
+
list,
|
|
216
|
+
remove,
|
|
217
|
+
markDirty,
|
|
218
|
+
clearError,
|
|
219
|
+
}),
|
|
220
|
+
[loading, error, isDirty, lastSavedAt, save, load, list, remove, markDirty, clearError],
|
|
221
|
+
);
|
|
222
|
+
}
|
|
@@ -0,0 +1,201 @@
|
|
|
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
|
+
|
|
12
|
+
import { useState, useEffect, useCallback, useMemo, useContext } from 'react';
|
|
13
|
+
import type { DataSource, ViewData, QueryParams, QueryResult } from '@object-ui/types';
|
|
14
|
+
import { resolveDataSource, type ResolveDataSourceOptions } from '@object-ui/core';
|
|
15
|
+
import { SchemaRendererContext } from '../context/SchemaRendererContext';
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------------------
|
|
18
|
+
// Types
|
|
19
|
+
// ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
export interface UseViewDataOptions<T = any> {
|
|
22
|
+
/** The ViewData configuration from the schema */
|
|
23
|
+
viewData?: ViewData | null;
|
|
24
|
+
/** Resource name (object name, used for DataSource.find calls) */
|
|
25
|
+
resource?: string;
|
|
26
|
+
/** Initial query parameters */
|
|
27
|
+
params?: QueryParams;
|
|
28
|
+
/** Explicit data source override (bypasses context) */
|
|
29
|
+
dataSource?: DataSource<T> | null;
|
|
30
|
+
/** Options for adapter construction */
|
|
31
|
+
adapterOptions?: ResolveDataSourceOptions;
|
|
32
|
+
/** If true, skip the initial fetch (useful for forms in create mode) */
|
|
33
|
+
skip?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface UseViewDataResult<T = any> {
|
|
37
|
+
/** Resolved data array */
|
|
38
|
+
data: T[];
|
|
39
|
+
/** Total number of records (from server or array length) */
|
|
40
|
+
totalCount: number;
|
|
41
|
+
/** Whether data is being fetched */
|
|
42
|
+
loading: boolean;
|
|
43
|
+
/** Error from the last fetch attempt */
|
|
44
|
+
error: Error | null;
|
|
45
|
+
/** The resolved DataSource instance (can be used for create/update/delete) */
|
|
46
|
+
dataSource: DataSource<T> | null;
|
|
47
|
+
/** Re-fetch data with current or new params */
|
|
48
|
+
refresh: (newParams?: QueryParams) => Promise<void>;
|
|
49
|
+
/** Fetch a single record by ID */
|
|
50
|
+
fetchOne: (id: string | number) => Promise<T | null>;
|
|
51
|
+
/** Whether more records are available */
|
|
52
|
+
hasMore: boolean;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ---------------------------------------------------------------------------
|
|
56
|
+
// Hook
|
|
57
|
+
// ---------------------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* useViewData — resolves ViewData into a DataSource and provides reactive data.
|
|
61
|
+
*
|
|
62
|
+
* This hook centralizes the data resolution pattern that was previously
|
|
63
|
+
* duplicated across plugins (ObjectGrid, ObjectView, etc.). It:
|
|
64
|
+
*
|
|
65
|
+
* 1. Resolves the ViewData config to the right DataSource adapter
|
|
66
|
+
* - `provider: 'object'` → context DataSource (ObjectStackAdapter)
|
|
67
|
+
* - `provider: 'api'` → ApiDataSource (raw HTTP)
|
|
68
|
+
* - `provider: 'value'` → ValueDataSource (in-memory)
|
|
69
|
+
* 2. Fetches data automatically on mount
|
|
70
|
+
* 3. Provides loading/error states and refresh capability
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```tsx
|
|
74
|
+
* function MyGrid({ schema }) {
|
|
75
|
+
* const { data, loading, error, refresh, dataSource } = useViewData({
|
|
76
|
+
* viewData: schema.data,
|
|
77
|
+
* resource: schema.objectName,
|
|
78
|
+
* params: { $top: 50 },
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* if (loading) return <Spinner />;
|
|
82
|
+
* if (error) return <ErrorMessage error={error} />;
|
|
83
|
+
* return <Table data={data} />;
|
|
84
|
+
* }
|
|
85
|
+
* ```
|
|
86
|
+
*/
|
|
87
|
+
export function useViewData<T = any>(options: UseViewDataOptions<T>): UseViewDataResult<T> {
|
|
88
|
+
const {
|
|
89
|
+
viewData,
|
|
90
|
+
resource = '',
|
|
91
|
+
params,
|
|
92
|
+
dataSource: explicitDataSource,
|
|
93
|
+
adapterOptions,
|
|
94
|
+
skip = false,
|
|
95
|
+
} = options;
|
|
96
|
+
|
|
97
|
+
// Get context DataSource
|
|
98
|
+
const context = useContext(SchemaRendererContext);
|
|
99
|
+
const contextDataSource = context?.dataSource ?? null;
|
|
100
|
+
|
|
101
|
+
// Resolve the DataSource — memoize to prevent re-creation on every render.
|
|
102
|
+
// We key on the viewData provider + config identity.
|
|
103
|
+
const resolvedDataSource = useMemo(() => {
|
|
104
|
+
if (explicitDataSource) return explicitDataSource;
|
|
105
|
+
return resolveDataSource<T>(viewData, contextDataSource, adapterOptions);
|
|
106
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
107
|
+
}, [
|
|
108
|
+
explicitDataSource,
|
|
109
|
+
viewData?.provider,
|
|
110
|
+
// For 'api' provider, key on read/write URLs
|
|
111
|
+
viewData?.provider === 'api' ? (viewData as any).read?.url : undefined,
|
|
112
|
+
viewData?.provider === 'api' ? (viewData as any).write?.url : undefined,
|
|
113
|
+
// For 'value' provider, key on items reference (or length as proxy)
|
|
114
|
+
viewData?.provider === 'value' ? (viewData as any).items?.length : undefined,
|
|
115
|
+
contextDataSource,
|
|
116
|
+
]);
|
|
117
|
+
|
|
118
|
+
// State
|
|
119
|
+
const [data, setData] = useState<T[]>([]);
|
|
120
|
+
const [totalCount, setTotalCount] = useState(0);
|
|
121
|
+
const [loading, setLoading] = useState(!skip);
|
|
122
|
+
const [error, setError] = useState<Error | null>(null);
|
|
123
|
+
const [hasMore, setHasMore] = useState(false);
|
|
124
|
+
|
|
125
|
+
// Stable params reference
|
|
126
|
+
const paramsKey = useMemo(() => JSON.stringify(params ?? {}), [params]);
|
|
127
|
+
|
|
128
|
+
// Fetch function
|
|
129
|
+
const fetchData = useCallback(
|
|
130
|
+
async (fetchParams?: QueryParams) => {
|
|
131
|
+
if (!resolvedDataSource || !resource) {
|
|
132
|
+
setLoading(false);
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
setLoading(true);
|
|
137
|
+
setError(null);
|
|
138
|
+
|
|
139
|
+
try {
|
|
140
|
+
const mergedParams = fetchParams ?? (params ? { ...params } : undefined);
|
|
141
|
+
const result: QueryResult<T> = await resolvedDataSource.find(resource, mergedParams);
|
|
142
|
+
setData(result.data ?? []);
|
|
143
|
+
setTotalCount(result.total ?? result.data?.length ?? 0);
|
|
144
|
+
setHasMore(result.hasMore ?? false);
|
|
145
|
+
} catch (err) {
|
|
146
|
+
setError(err instanceof Error ? err : new Error(String(err)));
|
|
147
|
+
setData([]);
|
|
148
|
+
setTotalCount(0);
|
|
149
|
+
} finally {
|
|
150
|
+
setLoading(false);
|
|
151
|
+
}
|
|
152
|
+
},
|
|
153
|
+
[resolvedDataSource, resource, params],
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
// Auto-fetch on mount / when deps change
|
|
157
|
+
useEffect(() => {
|
|
158
|
+
if (skip) {
|
|
159
|
+
setLoading(false);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// For value provider, data is synchronous — still go through fetchData
|
|
164
|
+
// for consistency, but it resolves immediately.
|
|
165
|
+
fetchData();
|
|
166
|
+
|
|
167
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
168
|
+
}, [resolvedDataSource, resource, paramsKey, skip]);
|
|
169
|
+
|
|
170
|
+
// Refresh function (can accept new params)
|
|
171
|
+
const refresh = useCallback(
|
|
172
|
+
async (newParams?: QueryParams) => {
|
|
173
|
+
await fetchData(newParams);
|
|
174
|
+
},
|
|
175
|
+
[fetchData],
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
// Fetch one record
|
|
179
|
+
const fetchOne = useCallback(
|
|
180
|
+
async (id: string | number): Promise<T | null> => {
|
|
181
|
+
if (!resolvedDataSource) return null;
|
|
182
|
+
try {
|
|
183
|
+
return await resolvedDataSource.findOne(resource, id);
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
[resolvedDataSource, resource],
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
data,
|
|
193
|
+
totalCount,
|
|
194
|
+
loading,
|
|
195
|
+
error,
|
|
196
|
+
dataSource: resolvedDataSource,
|
|
197
|
+
refresh,
|
|
198
|
+
fetchOne,
|
|
199
|
+
hasMore,
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -0,0 +1,140 @@
|
|
|
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
|
+
/** View sharing visibility aligned with ViewSharingSchema */
|
|
12
|
+
export type ViewVisibility = 'private' | 'team' | 'organization' | 'public';
|
|
13
|
+
|
|
14
|
+
/** A saved view configuration */
|
|
15
|
+
export interface SavedView {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
/** The view configuration (filters, sort, columns, etc.) */
|
|
19
|
+
config: Record<string, unknown>;
|
|
20
|
+
/** Who can see this view */
|
|
21
|
+
visibility: ViewVisibility;
|
|
22
|
+
/** Who created this view */
|
|
23
|
+
createdBy?: string;
|
|
24
|
+
/** Whether this is the default view */
|
|
25
|
+
isDefault?: boolean;
|
|
26
|
+
/** When the view was last modified */
|
|
27
|
+
updatedAt: Date;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface ViewSharingResult {
|
|
31
|
+
/** All available views */
|
|
32
|
+
views: SavedView[];
|
|
33
|
+
/** Currently active view */
|
|
34
|
+
activeView: SavedView | null;
|
|
35
|
+
/** Save a new view or update existing */
|
|
36
|
+
saveView: (view: Omit<SavedView, 'id' | 'updatedAt'>) => string;
|
|
37
|
+
/** Set the active view */
|
|
38
|
+
setActiveView: (viewId: string) => void;
|
|
39
|
+
/** Delete a view */
|
|
40
|
+
deleteView: (viewId: string) => void;
|
|
41
|
+
/** Duplicate a view */
|
|
42
|
+
duplicateView: (viewId: string, newName: string) => string;
|
|
43
|
+
/** Update view visibility */
|
|
44
|
+
setVisibility: (viewId: string, visibility: ViewVisibility) => void;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let viewCounter = 0;
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Hook for managing shared/personal view configurations.
|
|
51
|
+
* Implements ViewSharingSchema from @objectstack/spec v2.0.7.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```tsx
|
|
55
|
+
* const viewSharing = useViewSharing(initialViews);
|
|
56
|
+
*
|
|
57
|
+
* // Save current filters/sort as a named view
|
|
58
|
+
* viewSharing.saveView({
|
|
59
|
+
* name: 'My Open Tasks',
|
|
60
|
+
* config: { filters: currentFilters, sort: currentSort },
|
|
61
|
+
* visibility: 'private',
|
|
62
|
+
* });
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
export function useViewSharing(initialViews: SavedView[] = []): ViewSharingResult {
|
|
66
|
+
const [views, setViews] = useState<SavedView[]>(initialViews);
|
|
67
|
+
const [activeViewId, setActiveViewId] = useState<string | null>(
|
|
68
|
+
initialViews.find((v) => v.isDefault)?.id ?? initialViews[0]?.id ?? null
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
const activeView = useMemo(
|
|
72
|
+
() => views.find((v) => v.id === activeViewId) ?? null,
|
|
73
|
+
[views, activeViewId]
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
const saveView = useCallback(
|
|
77
|
+
(input: Omit<SavedView, 'id' | 'updatedAt'>): string => {
|
|
78
|
+
const id = `view-${++viewCounter}`;
|
|
79
|
+
const view: SavedView = {
|
|
80
|
+
...input,
|
|
81
|
+
id,
|
|
82
|
+
updatedAt: new Date(),
|
|
83
|
+
};
|
|
84
|
+
setViews((prev) => [...prev, view]);
|
|
85
|
+
return id;
|
|
86
|
+
},
|
|
87
|
+
[]
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const setActiveView = useCallback((viewId: string) => {
|
|
91
|
+
setActiveViewId(viewId);
|
|
92
|
+
}, []);
|
|
93
|
+
|
|
94
|
+
const deleteView = useCallback((viewId: string) => {
|
|
95
|
+
setViews((prev) => prev.filter((v) => v.id !== viewId));
|
|
96
|
+
setActiveViewId((current) => (current === viewId ? null : current));
|
|
97
|
+
}, []);
|
|
98
|
+
|
|
99
|
+
const duplicateView = useCallback(
|
|
100
|
+
(viewId: string, newName: string): string => {
|
|
101
|
+
const original = views.find((v) => v.id === viewId);
|
|
102
|
+
if (!original) return '';
|
|
103
|
+
const id = `view-${++viewCounter}`;
|
|
104
|
+
const duplicate: SavedView = {
|
|
105
|
+
...original,
|
|
106
|
+
id,
|
|
107
|
+
name: newName,
|
|
108
|
+
isDefault: false,
|
|
109
|
+
updatedAt: new Date(),
|
|
110
|
+
};
|
|
111
|
+
setViews((prev) => [...prev, duplicate]);
|
|
112
|
+
return id;
|
|
113
|
+
},
|
|
114
|
+
[views]
|
|
115
|
+
);
|
|
116
|
+
|
|
117
|
+
const setVisibility = useCallback(
|
|
118
|
+
(viewId: string, visibility: ViewVisibility) => {
|
|
119
|
+
setViews((prev) =>
|
|
120
|
+
prev.map((v) =>
|
|
121
|
+
v.id === viewId ? { ...v, visibility, updatedAt: new Date() } : v
|
|
122
|
+
)
|
|
123
|
+
);
|
|
124
|
+
},
|
|
125
|
+
[]
|
|
126
|
+
);
|
|
127
|
+
|
|
128
|
+
return useMemo(
|
|
129
|
+
() => ({
|
|
130
|
+
views,
|
|
131
|
+
activeView,
|
|
132
|
+
saveView,
|
|
133
|
+
setActiveView,
|
|
134
|
+
deleteView,
|
|
135
|
+
duplicateView,
|
|
136
|
+
setVisibility,
|
|
137
|
+
}),
|
|
138
|
+
[views, activeView, saveView, setActiveView, deleteView, duplicateView, setVisibility]
|
|
139
|
+
);
|
|
140
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
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
|
+
import { useReducedMotion } from './useReducedMotion';
|
|
11
|
+
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
// Types
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
|
|
16
|
+
export interface ViewTransitionConfig {
|
|
17
|
+
/** Enable view transitions (default: true) */
|
|
18
|
+
enabled?: boolean;
|
|
19
|
+
/** Fallback animation class when View Transitions API is unsupported */
|
|
20
|
+
fallbackClass?: string;
|
|
21
|
+
/** Transition duration in ms (default: 300) */
|
|
22
|
+
duration?: number;
|
|
23
|
+
/** Called before transition starts */
|
|
24
|
+
onTransitionStart?: () => void;
|
|
25
|
+
/** Called after transition completes */
|
|
26
|
+
onTransitionEnd?: () => void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ViewTransitionResult {
|
|
30
|
+
/** Whether the View Transitions API is supported */
|
|
31
|
+
isSupported: boolean;
|
|
32
|
+
/** Whether a transition is currently in progress */
|
|
33
|
+
isTransitioning: boolean;
|
|
34
|
+
/** Execute a callback with a view transition */
|
|
35
|
+
startTransition: (callback: () => void | Promise<void>) => Promise<void>;
|
|
36
|
+
/** CSS class to apply during transitions */
|
|
37
|
+
transitionClass: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ---------------------------------------------------------------------------
|
|
41
|
+
// Helpers
|
|
42
|
+
// ---------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
const DEFAULT_DURATION = 300;
|
|
45
|
+
const DEFAULT_FALLBACK_CLASS = 'oui-view-transition-fallback';
|
|
46
|
+
|
|
47
|
+
/** Minimal type for the native ViewTransition object returned by the API. */
|
|
48
|
+
interface ViewTransition {
|
|
49
|
+
finished: Promise<void>;
|
|
50
|
+
ready: Promise<void>;
|
|
51
|
+
updateCallbackDone: Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function supportsViewTransitions(): boolean {
|
|
55
|
+
return (
|
|
56
|
+
typeof document !== 'undefined' &&
|
|
57
|
+
'startViewTransition' in document
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
// useViewTransition hook
|
|
63
|
+
// ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Hook for integrating with the browser View Transitions API.
|
|
67
|
+
*
|
|
68
|
+
* Uses the native `document.startViewTransition()` when available and
|
|
69
|
+
* falls back to a temporary CSS class for animation when unsupported.
|
|
70
|
+
* Respects `prefers-reduced-motion`.
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* ```tsx
|
|
74
|
+
* function ViewSwitcher({ onViewChange }: { onViewChange: (v: string) => void }) {
|
|
75
|
+
* const { startTransition, transitionClass, isTransitioning } = useViewTransition();
|
|
76
|
+
*
|
|
77
|
+
* const handleChange = (view: string) => {
|
|
78
|
+
* startTransition(() => onViewChange(view));
|
|
79
|
+
* };
|
|
80
|
+
*
|
|
81
|
+
* return (
|
|
82
|
+
* <div className={transitionClass}>
|
|
83
|
+
* ...
|
|
84
|
+
* </div>
|
|
85
|
+
* );
|
|
86
|
+
* }
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export function useViewTransition(
|
|
90
|
+
config: ViewTransitionConfig = {},
|
|
91
|
+
): ViewTransitionResult {
|
|
92
|
+
const {
|
|
93
|
+
enabled = true,
|
|
94
|
+
fallbackClass = DEFAULT_FALLBACK_CLASS,
|
|
95
|
+
duration = DEFAULT_DURATION,
|
|
96
|
+
onTransitionStart,
|
|
97
|
+
onTransitionEnd,
|
|
98
|
+
} = config;
|
|
99
|
+
|
|
100
|
+
const reducedMotion = useReducedMotion();
|
|
101
|
+
const [isTransitioning, setIsTransitioning] = useState(false);
|
|
102
|
+
|
|
103
|
+
const isSupported = useMemo(() => supportsViewTransitions(), []);
|
|
104
|
+
|
|
105
|
+
const startTransition = useCallback(
|
|
106
|
+
async (callback: () => void | Promise<void>): Promise<void> => {
|
|
107
|
+
// Skip transition when disabled or user prefers reduced motion
|
|
108
|
+
if (!enabled || reducedMotion) {
|
|
109
|
+
await callback();
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
onTransitionStart?.();
|
|
114
|
+
setIsTransitioning(true);
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
if (isSupported) {
|
|
118
|
+
// Use native View Transitions API
|
|
119
|
+
const transition = (document as Document & {
|
|
120
|
+
startViewTransition: (cb: () => void | Promise<void>) => ViewTransition;
|
|
121
|
+
}).startViewTransition(callback);
|
|
122
|
+
await transition.finished;
|
|
123
|
+
} else {
|
|
124
|
+
// Fallback: apply class, run callback, remove class after duration
|
|
125
|
+
await callback();
|
|
126
|
+
await new Promise<void>((resolve) => setTimeout(resolve, duration));
|
|
127
|
+
}
|
|
128
|
+
} finally {
|
|
129
|
+
setIsTransitioning(false);
|
|
130
|
+
onTransitionEnd?.();
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
[enabled, reducedMotion, isSupported, duration, onTransitionStart, onTransitionEnd],
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
const transitionClass = isTransitioning && !isSupported ? fallbackClass : '';
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
isSupported,
|
|
140
|
+
isTransitioning,
|
|
141
|
+
startTransition,
|
|
142
|
+
transitionClass,
|
|
143
|
+
};
|
|
144
|
+
}
|