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