@object-ui/react 3.3.0 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/README.md +21 -1
  3. package/dist/context/AppShellContext.d.ts +26 -0
  4. package/dist/context/AppShellContext.js +67 -0
  5. package/dist/context/index.d.ts +1 -7
  6. package/dist/context/index.js +1 -7
  7. package/package.json +32 -9
  8. package/.turbo/turbo-build.log +0 -4
  9. package/src/LazyPluginLoader.tsx +0 -174
  10. package/src/SchemaRenderer.tsx +0 -266
  11. package/src/__tests__/LazyPluginLoader.test.tsx +0 -176
  12. package/src/__tests__/SchemaRenderer.aria.test.tsx +0 -118
  13. package/src/__tests__/SchemaRenderer.debug.test.tsx +0 -69
  14. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +0 -114
  15. package/src/__tests__/SchemaRenderer.expressions.test.tsx +0 -131
  16. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +0 -132
  17. package/src/__tests__/ThemeProvider.test.tsx +0 -451
  18. package/src/__tests__/useNavigationOverlay.test.ts +0 -578
  19. package/src/__tests__/useOffline.test.ts +0 -198
  20. package/src/__tests__/usePageTransition.test.ts +0 -214
  21. package/src/__tests__/usePageVariables.test.tsx +0 -334
  22. package/src/__tests__/usePerformance.test.ts +0 -137
  23. package/src/__tests__/useViewData.test.tsx +0 -422
  24. package/src/__tests__/view-switching.test.tsx +0 -456
  25. package/src/components/form/FieldFactory.tsx +0 -516
  26. package/src/components/form/FormRenderer.test.tsx +0 -744
  27. package/src/components/form/FormRenderer.tsx +0 -258
  28. package/src/components/form/README.md +0 -352
  29. package/src/components/form/index.ts +0 -12
  30. package/src/context/ActionContext.tsx +0 -213
  31. package/src/context/DndContext.tsx +0 -260
  32. package/src/context/NotificationContext.tsx +0 -280
  33. package/src/context/SchemaRendererContext.tsx +0 -48
  34. package/src/context/ThemeContext.tsx +0 -325
  35. package/src/context/__tests__/ActionContext.test.tsx +0 -174
  36. package/src/context/__tests__/DndContext.test.tsx +0 -150
  37. package/src/context/__tests__/NotificationContext.test.tsx +0 -176
  38. package/src/context/__tests__/useDataScope.test.tsx +0 -91
  39. package/src/context/index.ts +0 -13
  40. package/src/hooks/__tests__/useActionEngine.test.ts +0 -170
  41. package/src/hooks/__tests__/useActionRunner.test.ts +0 -153
  42. package/src/hooks/__tests__/useAnimation.test.ts +0 -82
  43. package/src/hooks/__tests__/useColumnSummary.test.ts +0 -93
  44. package/src/hooks/__tests__/useCrudShortcuts.test.ts +0 -85
  45. package/src/hooks/__tests__/useDataRefresh.test.ts +0 -115
  46. package/src/hooks/__tests__/useDebugMode.test.ts +0 -83
  47. package/src/hooks/__tests__/useDensityMode.test.ts +0 -81
  48. package/src/hooks/__tests__/useDiscovery.test.tsx +0 -247
  49. package/src/hooks/__tests__/useDynamicApp.test.ts +0 -161
  50. package/src/hooks/__tests__/useETagCache.test.ts +0 -153
  51. package/src/hooks/__tests__/useExpression.test.ts +0 -86
  52. package/src/hooks/__tests__/useFocusTrap.test.ts +0 -294
  53. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +0 -144
  54. package/src/hooks/__tests__/usePageTransition.test.ts +0 -158
  55. package/src/hooks/__tests__/usePerformanceBudget.test.ts +0 -157
  56. package/src/hooks/__tests__/useReducedMotion.test.ts +0 -104
  57. package/src/hooks/__tests__/useSchemaPersistence.test.ts +0 -220
  58. package/src/hooks/__tests__/useViewSharing.test.ts +0 -121
  59. package/src/hooks/__tests__/useViewTransition.test.ts +0 -61
  60. package/src/hooks/index.ts +0 -36
  61. package/src/hooks/useActionEngine.ts +0 -84
  62. package/src/hooks/useActionRunner.ts +0 -119
  63. package/src/hooks/useAnimation.ts +0 -117
  64. package/src/hooks/useClientNotifications.ts +0 -251
  65. package/src/hooks/useColumnSummary.ts +0 -87
  66. package/src/hooks/useCrudShortcuts.ts +0 -126
  67. package/src/hooks/useDataRefresh.ts +0 -58
  68. package/src/hooks/useDebugMode.ts +0 -95
  69. package/src/hooks/useDensityMode.ts +0 -102
  70. package/src/hooks/useDiscovery.ts +0 -168
  71. package/src/hooks/useDynamicApp.ts +0 -142
  72. package/src/hooks/useETagCache.ts +0 -404
  73. package/src/hooks/useExpression.ts +0 -56
  74. package/src/hooks/useFocusManagement.ts +0 -248
  75. package/src/hooks/useFocusTrap.ts +0 -138
  76. package/src/hooks/useGlobalUndo.ts +0 -98
  77. package/src/hooks/useKeyboardShortcuts.ts +0 -119
  78. package/src/hooks/useNavigationOverlay.ts +0 -190
  79. package/src/hooks/useOffline.ts +0 -301
  80. package/src/hooks/usePageTransition.ts +0 -187
  81. package/src/hooks/usePageVariables.tsx +0 -157
  82. package/src/hooks/usePerformance.ts +0 -246
  83. package/src/hooks/usePerformanceBudget.ts +0 -313
  84. package/src/hooks/useReducedMotion.ts +0 -53
  85. package/src/hooks/useSchemaPersistence.ts +0 -222
  86. package/src/hooks/useViewData.ts +0 -201
  87. package/src/hooks/useViewSharing.ts +0 -140
  88. package/src/hooks/useViewTransition.ts +0 -144
  89. package/src/index.ts +0 -41
  90. package/src/spec-bridge/SpecBridge.ts +0 -64
  91. package/src/spec-bridge/__tests__/P1SpecBridge.test.ts +0 -855
  92. package/src/spec-bridge/__tests__/SpecBridge.test.ts +0 -550
  93. package/src/spec-bridge/bridges/dashboard.ts +0 -180
  94. package/src/spec-bridge/bridges/form-view.ts +0 -109
  95. package/src/spec-bridge/bridges/list-view.ts +0 -187
  96. package/src/spec-bridge/bridges/page.ts +0 -136
  97. package/src/spec-bridge/index.ts +0 -14
  98. package/src/spec-bridge/types.ts +0 -38
  99. package/src/utils/i18n.ts +0 -10
  100. package/tsconfig.json +0 -17
  101. package/tsconfig.tsbuildinfo +0 -1
  102. package/vitest.config.ts +0 -2
@@ -1,222 +0,0 @@
1
- /**
2
- * ObjectUI
3
- * Copyright (c) 2024-present ObjectStack Inc.
4
- *
5
- * This source code is licensed under the MIT license found in the
6
- * LICENSE file in the root directory of this source tree.
7
- */
8
-
9
- import { useState, useCallback, 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
- }
@@ -1,201 +0,0 @@
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
- }
@@ -1,140 +0,0 @@
1
- /**
2
- * ObjectUI
3
- * Copyright (c) 2024-present ObjectStack Inc.
4
- *
5
- * This source code is licensed under the MIT license found in the
6
- * LICENSE file in the root directory of this source tree.
7
- */
8
-
9
- import { useState, useCallback, useMemo } from 'react';
10
-
11
- /** 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
- }
@@ -1,144 +0,0 @@
1
- /**
2
- * ObjectUI
3
- * Copyright (c) 2024-present ObjectStack Inc.
4
- *
5
- * This source code is licensed under the MIT license found in the
6
- * LICENSE file in the root directory of this source tree.
7
- */
8
-
9
- import { useState, useCallback, useMemo } from 'react';
10
- 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
- }