@object-ui/react 2.0.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 (89) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/dist/SchemaRenderer.d.ts +20 -1
  4. package/dist/SchemaRenderer.js +76 -13
  5. package/dist/context/DndContext.d.ts +135 -0
  6. package/dist/context/DndContext.js +120 -0
  7. package/dist/context/NotificationContext.d.ts +113 -0
  8. package/dist/context/NotificationContext.js +130 -0
  9. package/dist/context/index.d.ts +2 -0
  10. package/dist/context/index.js +2 -0
  11. package/dist/hooks/index.d.ts +17 -0
  12. package/dist/hooks/index.js +17 -0
  13. package/dist/hooks/useAnimation.d.ts +46 -0
  14. package/dist/hooks/useAnimation.js +59 -0
  15. package/dist/hooks/useClientNotifications.d.ts +53 -0
  16. package/dist/hooks/useClientNotifications.js +190 -0
  17. package/dist/hooks/useColumnSummary.d.ts +38 -0
  18. package/dist/hooks/useColumnSummary.js +54 -0
  19. package/dist/hooks/useCrudShortcuts.d.ts +39 -0
  20. package/dist/hooks/useCrudShortcuts.js +96 -0
  21. package/dist/hooks/useDensityMode.d.ts +48 -0
  22. package/dist/hooks/useDensityMode.js +60 -0
  23. package/dist/hooks/useETagCache.d.ts +75 -0
  24. package/dist/hooks/useETagCache.js +306 -0
  25. package/dist/hooks/useFocusManagement.d.ts +89 -0
  26. package/dist/hooks/useFocusManagement.js +188 -0
  27. package/dist/hooks/useFocusTrap.d.ts +41 -0
  28. package/dist/hooks/useFocusTrap.js +103 -0
  29. package/dist/hooks/useKeyboardShortcuts.d.ts +49 -0
  30. package/dist/hooks/useKeyboardShortcuts.js +86 -0
  31. package/dist/hooks/useOffline.d.ts +96 -0
  32. package/dist/hooks/useOffline.js +185 -0
  33. package/dist/hooks/usePageTransition.d.ts +60 -0
  34. package/dist/hooks/usePageTransition.js +111 -0
  35. package/dist/hooks/usePerformance.d.ts +87 -0
  36. package/dist/hooks/usePerformance.js +165 -0
  37. package/dist/hooks/usePerformanceBudget.d.ts +78 -0
  38. package/dist/hooks/usePerformanceBudget.js +209 -0
  39. package/dist/hooks/useReducedMotion.d.ts +28 -0
  40. package/dist/hooks/useReducedMotion.js +48 -0
  41. package/dist/hooks/useSchemaPersistence.d.ts +87 -0
  42. package/dist/hooks/useSchemaPersistence.js +173 -0
  43. package/dist/hooks/useViewSharing.d.ts +57 -0
  44. package/dist/hooks/useViewSharing.js +74 -0
  45. package/dist/hooks/useViewTransition.d.ts +54 -0
  46. package/dist/hooks/useViewTransition.js +83 -0
  47. package/package.json +7 -7
  48. package/src/SchemaRenderer.tsx +122 -13
  49. package/src/__tests__/SchemaRenderer.aria.test.tsx +118 -0
  50. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +114 -0
  51. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +132 -0
  52. package/src/__tests__/useOffline.test.ts +198 -0
  53. package/src/__tests__/usePageTransition.test.ts +214 -0
  54. package/src/__tests__/usePerformance.test.ts +137 -0
  55. package/src/__tests__/view-switching.test.tsx +456 -0
  56. package/src/context/DndContext.tsx +260 -0
  57. package/src/context/NotificationContext.tsx +280 -0
  58. package/src/context/__tests__/DndContext.test.tsx +150 -0
  59. package/src/context/__tests__/NotificationContext.test.tsx +176 -0
  60. package/src/context/index.ts +2 -0
  61. package/src/hooks/__tests__/useAnimation.test.ts +82 -0
  62. package/src/hooks/__tests__/useColumnSummary.test.ts +93 -0
  63. package/src/hooks/__tests__/useDensityMode.test.ts +81 -0
  64. package/src/hooks/__tests__/useETagCache.test.ts +153 -0
  65. package/src/hooks/__tests__/useFocusTrap.test.ts +47 -0
  66. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +144 -0
  67. package/src/hooks/__tests__/usePerformanceBudget.test.ts +157 -0
  68. package/src/hooks/__tests__/useSchemaPersistence.test.ts +220 -0
  69. package/src/hooks/__tests__/useViewSharing.test.ts +121 -0
  70. package/src/hooks/__tests__/useViewTransition.test.ts +61 -0
  71. package/src/hooks/index.ts +17 -1
  72. package/src/hooks/useAnimation.ts +117 -0
  73. package/src/hooks/useClientNotifications.ts +251 -0
  74. package/src/hooks/useColumnSummary.ts +87 -0
  75. package/src/hooks/useCrudShortcuts.ts +126 -0
  76. package/src/hooks/useDensityMode.ts +102 -0
  77. package/src/hooks/useETagCache.ts +404 -0
  78. package/src/hooks/useFocusManagement.ts +248 -0
  79. package/src/hooks/useFocusTrap.ts +138 -0
  80. package/src/hooks/useKeyboardShortcuts.ts +119 -0
  81. package/src/hooks/useOffline.ts +301 -0
  82. package/src/hooks/usePageTransition.ts +187 -0
  83. package/src/hooks/usePerformance.ts +246 -0
  84. package/src/hooks/usePerformanceBudget.ts +313 -0
  85. package/src/hooks/useReducedMotion.ts +53 -0
  86. package/src/hooks/useSchemaPersistence.ts +222 -0
  87. package/src/hooks/useViewSharing.ts +140 -0
  88. package/src/hooks/useViewTransition.ts +144 -0
  89. package/tsconfig.tsbuildinfo +1 -1
@@ -0,0 +1,251 @@
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
+ /**
10
+ * @object-ui/react - useClientNotifications
11
+ *
12
+ * Bridge hook between the @objectstack/client notifications API
13
+ * and the local NotificationContext state. Fetches server-side
14
+ * notifications and surfaces them through the existing provider.
15
+ */
16
+
17
+ import { useCallback, useContext, useEffect, useRef, useState } from 'react';
18
+ import { SchemaRendererContext } from '../context/SchemaRendererContext';
19
+ import { useNotifications } from '../context/NotificationContext';
20
+ import type { NotificationSeverityLevel } from '../context/NotificationContext';
21
+
22
+ /* ------------------------------------------------------------------ */
23
+ /* Public types */
24
+ /* ------------------------------------------------------------------ */
25
+
26
+ export interface UseClientNotificationsOptions {
27
+ /** ObjectStack client instance (optional, from context if available) */
28
+ client?: any;
29
+ /** Whether to auto-fetch notifications on mount */
30
+ autoFetch?: boolean;
31
+ /** Polling interval in ms (0 to disable) */
32
+ pollInterval?: number;
33
+ }
34
+
35
+ export interface UseClientNotificationsResult {
36
+ /** Fetch notifications from server */
37
+ fetchNotifications: () => Promise<void>;
38
+ /** Register device for push notifications */
39
+ registerDevice: (token: string, platform: string) => Promise<void>;
40
+ /** Get notification preferences */
41
+ getPreferences: () => Promise<any>;
42
+ /** Update notification preferences */
43
+ updatePreferences: (prefs: any) => Promise<void>;
44
+ /** Mark a notification as read on the server */
45
+ markAsRead: (id: string) => Promise<void>;
46
+ /** Loading state */
47
+ loading: boolean;
48
+ /** Error state */
49
+ error: Error | null;
50
+ }
51
+
52
+ /* ------------------------------------------------------------------ */
53
+ /* Helpers */
54
+ /* ------------------------------------------------------------------ */
55
+
56
+ /** Normalise severity coming from the server into a valid local level. */
57
+ function toSeverity(value: unknown): NotificationSeverityLevel {
58
+ const valid: NotificationSeverityLevel[] = ['info', 'success', 'warning', 'error'];
59
+ if (typeof value === 'string' && valid.includes(value as NotificationSeverityLevel)) {
60
+ return value as NotificationSeverityLevel;
61
+ }
62
+ return 'info';
63
+ }
64
+
65
+ /**
66
+ * Resolve the ObjectStack client from explicit option or SchemaRendererContext.
67
+ *
68
+ * The dataSource stored in context is typically an ObjectStackAdapter which
69
+ * exposes `getClient()`. When the caller passes a client directly we use
70
+ * that instead.
71
+ */
72
+ function useResolvedClient(explicit?: any): any {
73
+ const rendererCtx = useContext(SchemaRendererContext);
74
+ if (explicit) return explicit;
75
+
76
+ const dataSource = rendererCtx?.dataSource;
77
+ if (dataSource && typeof dataSource.getClient === 'function') {
78
+ return dataSource.getClient();
79
+ }
80
+ return null;
81
+ }
82
+
83
+ /* ------------------------------------------------------------------ */
84
+ /* Hook */
85
+ /* ------------------------------------------------------------------ */
86
+
87
+ /**
88
+ * Bridge between the `@objectstack/client` notifications API and the
89
+ * local {@link NotificationContext}.
90
+ *
91
+ * The hook resolves the ObjectStack client either from the explicit
92
+ * `client` option or from the `SchemaRendererContext` dataSource, then
93
+ * delegates to `client.notifications.*` methods. Fetched notifications
94
+ * are fed into the local provider via `useNotifications().notify()`.
95
+ *
96
+ * @example
97
+ * ```tsx
98
+ * function NotificationBell() {
99
+ * const { fetchNotifications, loading } = useClientNotifications({
100
+ * autoFetch: true,
101
+ * pollInterval: 30_000,
102
+ * });
103
+ *
104
+ * return <Button onClick={fetchNotifications} disabled={loading}>🔔</Button>;
105
+ * }
106
+ * ```
107
+ */
108
+ export function useClientNotifications(
109
+ options: UseClientNotificationsOptions = {},
110
+ ): UseClientNotificationsResult {
111
+ const { client: explicitClient, autoFetch = false, pollInterval = 0 } = options;
112
+
113
+ const client = useResolvedClient(explicitClient);
114
+ const { notify, markAsRead: localMarkAsRead } = useNotifications();
115
+
116
+ const [loading, setLoading] = useState(false);
117
+ const [error, setError] = useState<Error | null>(null);
118
+
119
+ // Track IDs that have already been pushed into the local context so we
120
+ // don't add duplicates on subsequent fetches / polls.
121
+ const seenIdsRef = useRef<Set<string>>(new Set());
122
+
123
+ /* ---- fetchNotifications ---- */
124
+
125
+ const fetchNotifications = useCallback(async () => {
126
+ if (!client?.notifications) return;
127
+
128
+ setLoading(true);
129
+ setError(null);
130
+
131
+ try {
132
+ const result = await client.notifications.list({});
133
+ const items: any[] = Array.isArray(result) ? result : result?.data ?? result?.items ?? [];
134
+
135
+ for (const item of items) {
136
+ const id = String(item.id ?? '');
137
+ if (!id || seenIdsRef.current.has(id)) continue;
138
+
139
+ seenIdsRef.current.add(id);
140
+ notify({
141
+ title: item.title ?? 'Notification',
142
+ message: item.message ?? item.body,
143
+ severity: toSeverity(item.severity ?? item.level),
144
+ duration: 0, // server-driven notifications are persistent
145
+ });
146
+ }
147
+ } catch (err) {
148
+ setError(err instanceof Error ? err : new Error('Failed to fetch notifications'));
149
+ } finally {
150
+ setLoading(false);
151
+ }
152
+ }, [client, notify]);
153
+
154
+ /* ---- registerDevice ---- */
155
+
156
+ const registerDevice = useCallback(
157
+ async (token: string, platform: string) => {
158
+ if (!client?.notifications) return;
159
+ setError(null);
160
+ try {
161
+ await client.notifications.registerDevice(token, platform);
162
+ } catch (err) {
163
+ const wrapped = err instanceof Error ? err : new Error('Failed to register device');
164
+ setError(wrapped);
165
+ throw wrapped;
166
+ }
167
+ },
168
+ [client],
169
+ );
170
+
171
+ /* ---- getPreferences ---- */
172
+
173
+ const getPreferences = useCallback(async () => {
174
+ if (!client?.notifications) return null;
175
+ setError(null);
176
+ try {
177
+ return await client.notifications.getPreferences();
178
+ } catch (err) {
179
+ const wrapped = err instanceof Error ? err : new Error('Failed to get preferences');
180
+ setError(wrapped);
181
+ throw wrapped;
182
+ }
183
+ }, [client]);
184
+
185
+ /* ---- updatePreferences ---- */
186
+
187
+ const updatePreferences = useCallback(
188
+ async (prefs: any) => {
189
+ if (!client?.notifications) return;
190
+ setError(null);
191
+ try {
192
+ await client.notifications.updatePreferences(prefs);
193
+ } catch (err) {
194
+ const wrapped = err instanceof Error ? err : new Error('Failed to update preferences');
195
+ setError(wrapped);
196
+ throw wrapped;
197
+ }
198
+ },
199
+ [client],
200
+ );
201
+
202
+ /* ---- markAsRead (server + local) ---- */
203
+
204
+ const markAsRead = useCallback(
205
+ async (id: string) => {
206
+ // Optimistically mark locally first
207
+ localMarkAsRead(id);
208
+
209
+ if (!client?.notifications) return;
210
+ setError(null);
211
+ try {
212
+ await client.notifications.markAsRead(id);
213
+ } catch (err) {
214
+ const wrapped = err instanceof Error ? err : new Error('Failed to mark as read');
215
+ setError(wrapped);
216
+ throw wrapped;
217
+ }
218
+ },
219
+ [client, localMarkAsRead],
220
+ );
221
+
222
+ /* ---- auto-fetch on mount ---- */
223
+
224
+ useEffect(() => {
225
+ if (autoFetch && client?.notifications) {
226
+ fetchNotifications();
227
+ }
228
+ }, [autoFetch, client, fetchNotifications]);
229
+
230
+ /* ---- polling ---- */
231
+
232
+ useEffect(() => {
233
+ if (!pollInterval || pollInterval <= 0 || !client?.notifications) return;
234
+
235
+ const id = setInterval(() => {
236
+ fetchNotifications();
237
+ }, pollInterval);
238
+
239
+ return () => clearInterval(id);
240
+ }, [pollInterval, client, fetchNotifications]);
241
+
242
+ return {
243
+ fetchNotifications,
244
+ registerDevice,
245
+ getPreferences,
246
+ updatePreferences,
247
+ markAsRead,
248
+ loading,
249
+ error,
250
+ };
251
+ }
@@ -0,0 +1,87 @@
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 { useMemo } from 'react';
10
+
11
+ /** Summary function types aligned with ColumnSummarySchema */
12
+ export type SummaryFunction = 'sum' | 'avg' | 'count' | 'min' | 'max' | 'distinct';
13
+
14
+ export interface ColumnSummaryConfig {
15
+ /** The field/column to aggregate */
16
+ field: string;
17
+ /** The aggregation function */
18
+ function: SummaryFunction;
19
+ /** Optional label for the summary */
20
+ label?: string;
21
+ /** Number format options */
22
+ format?: Intl.NumberFormatOptions;
23
+ }
24
+
25
+ export interface ColumnSummaryResult {
26
+ /** The computed value */
27
+ value: number;
28
+ /** Formatted display string */
29
+ formatted: string;
30
+ /** The label */
31
+ label: string;
32
+ }
33
+
34
+ /**
35
+ * Hook for computing column-level summaries (SUM, AVG, COUNT, MIN, MAX, DISTINCT).
36
+ * Implements ColumnSummarySchema from @objectstack/spec v2.0.7.
37
+ *
38
+ * @example
39
+ * ```tsx
40
+ * const summary = useColumnSummary(data, { field: 'amount', function: 'sum', label: 'Total' });
41
+ * // summary.formatted => "$12,345.67"
42
+ * ```
43
+ */
44
+ export function useColumnSummary(
45
+ data: Record<string, unknown>[],
46
+ config: ColumnSummaryConfig,
47
+ locale?: string
48
+ ): ColumnSummaryResult {
49
+ return useMemo(() => {
50
+ const values = data
51
+ .map((row) => {
52
+ const val = row[config.field];
53
+ return typeof val === 'number' ? val : Number(val);
54
+ })
55
+ .filter((v) => !isNaN(v));
56
+
57
+ let value: number;
58
+
59
+ switch (config.function) {
60
+ case 'sum':
61
+ value = values.reduce((acc, v) => acc + v, 0);
62
+ break;
63
+ case 'avg':
64
+ value = values.length > 0 ? values.reduce((acc, v) => acc + v, 0) / values.length : 0;
65
+ break;
66
+ case 'count':
67
+ value = data.length;
68
+ break;
69
+ case 'min':
70
+ value = values.length > 0 ? Math.min(...values) : 0;
71
+ break;
72
+ case 'max':
73
+ value = values.length > 0 ? Math.max(...values) : 0;
74
+ break;
75
+ case 'distinct':
76
+ value = new Set(data.map((row) => row[config.field])).size;
77
+ break;
78
+ default:
79
+ value = 0;
80
+ }
81
+
82
+ const formatted = new Intl.NumberFormat(locale, config.format).format(value);
83
+ const label = config.label ?? config.function.toUpperCase();
84
+
85
+ return { value, formatted, label };
86
+ }, [data, config.field, config.function, config.label, config.format, locale]);
87
+ }
@@ -0,0 +1,126 @@
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 { useMemo } from 'react';
10
+ import {
11
+ useKeyboardShortcuts,
12
+ type KeyboardShortcutDefinition,
13
+ } from './useKeyboardShortcuts';
14
+
15
+ export interface CrudShortcutCallbacks {
16
+ onCreate?: () => void;
17
+ onEdit?: () => void;
18
+ onDelete?: () => void;
19
+ onSave?: () => void;
20
+ onDuplicate?: () => void;
21
+ onCancel?: () => void;
22
+ onSearch?: () => void;
23
+ }
24
+
25
+ /**
26
+ * Registers standard CRUD keyboard shortcuts using the useKeyboardShortcuts hook.
27
+ *
28
+ * Shortcuts:
29
+ * - Ctrl/Cmd+N: Create new record
30
+ * - Ctrl/Cmd+E: Edit selected record
31
+ * - Delete / Backspace: Delete selected record(s)
32
+ * - Ctrl/Cmd+S: Save current record
33
+ * - Ctrl/Cmd+D: Duplicate selected record
34
+ * - Escape: Cancel/close current operation
35
+ * - Ctrl/Cmd+F: Focus search
36
+ *
37
+ * @example
38
+ * ```tsx
39
+ * useCrudShortcuts({
40
+ * onCreate: () => openCreateDialog(),
41
+ * onSave: () => saveRecord(),
42
+ * onDelete: () => deleteSelected(),
43
+ * onCancel: () => closeDialog(),
44
+ * });
45
+ * ```
46
+ */
47
+ export function useCrudShortcuts(
48
+ callbacks: CrudShortcutCallbacks,
49
+ enabled = true
50
+ ): void {
51
+ const shortcuts = useMemo<KeyboardShortcutDefinition[]>(() => {
52
+ const defs: KeyboardShortcutDefinition[] = [];
53
+
54
+ if (callbacks.onCreate) {
55
+ defs.push({
56
+ key: 'n',
57
+ ctrlOrMeta: true,
58
+ handler: () => callbacks.onCreate!(),
59
+ description: 'New record',
60
+ });
61
+ }
62
+
63
+ if (callbacks.onEdit) {
64
+ defs.push({
65
+ key: 'e',
66
+ ctrlOrMeta: true,
67
+ handler: () => callbacks.onEdit!(),
68
+ description: 'Edit selected record',
69
+ });
70
+ }
71
+
72
+ if (callbacks.onDelete) {
73
+ defs.push(
74
+ {
75
+ key: 'Delete',
76
+ handler: () => callbacks.onDelete!(),
77
+ description: 'Delete selected record(s)',
78
+ },
79
+ {
80
+ key: 'Backspace',
81
+ handler: () => callbacks.onDelete!(),
82
+ description: 'Delete selected record(s)',
83
+ }
84
+ );
85
+ }
86
+
87
+ if (callbacks.onSave) {
88
+ defs.push({
89
+ key: 's',
90
+ ctrlOrMeta: true,
91
+ handler: () => callbacks.onSave!(),
92
+ description: 'Save current record',
93
+ });
94
+ }
95
+
96
+ if (callbacks.onDuplicate) {
97
+ defs.push({
98
+ key: 'd',
99
+ ctrlOrMeta: true,
100
+ handler: () => callbacks.onDuplicate!(),
101
+ description: 'Duplicate selected record',
102
+ });
103
+ }
104
+
105
+ if (callbacks.onCancel) {
106
+ defs.push({
107
+ key: 'Escape',
108
+ handler: () => callbacks.onCancel!(),
109
+ description: 'Cancel/close current operation',
110
+ });
111
+ }
112
+
113
+ if (callbacks.onSearch) {
114
+ defs.push({
115
+ key: 'f',
116
+ ctrlOrMeta: true,
117
+ handler: () => callbacks.onSearch!(),
118
+ description: 'Focus search',
119
+ });
120
+ }
121
+
122
+ return defs;
123
+ }, [callbacks]);
124
+
125
+ useKeyboardShortcuts(shortcuts, { enabled });
126
+ }
@@ -0,0 +1,102 @@
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
+ /** Density mode aligned with DensityMode from @objectstack/spec v2.0.7 */
12
+ export type DensityModeValue = 'compact' | 'comfortable' | 'spacious';
13
+
14
+ export interface DensityConfig {
15
+ /** Row height in pixels for each density mode */
16
+ rowHeights?: Record<DensityModeValue, number>;
17
+ /** Padding classes for each density mode */
18
+ paddingClasses?: Record<DensityModeValue, string>;
19
+ /** Font size classes for each density mode */
20
+ fontSizeClasses?: Record<DensityModeValue, string>;
21
+ }
22
+
23
+ export interface DensityResult {
24
+ /** Current density mode */
25
+ mode: DensityModeValue;
26
+ /** Set the density mode */
27
+ setMode: (mode: DensityModeValue) => void;
28
+ /** Cycle through density modes */
29
+ cycle: () => void;
30
+ /** Row height for the current mode (in pixels) */
31
+ rowHeight: number;
32
+ /** Tailwind padding class for the current mode */
33
+ paddingClass: string;
34
+ /** Tailwind font-size class for the current mode */
35
+ fontSizeClass: string;
36
+ }
37
+
38
+ const DEFAULT_ROW_HEIGHTS: Record<DensityModeValue, number> = {
39
+ compact: 32,
40
+ comfortable: 40,
41
+ spacious: 52,
42
+ };
43
+
44
+ const DEFAULT_PADDING_CLASSES: Record<DensityModeValue, string> = {
45
+ compact: 'py-1 px-2',
46
+ comfortable: 'py-2 px-3',
47
+ spacious: 'py-3 px-4',
48
+ };
49
+
50
+ const DEFAULT_FONT_SIZE_CLASSES: Record<DensityModeValue, string> = {
51
+ compact: 'text-xs',
52
+ comfortable: 'text-sm',
53
+ spacious: 'text-base',
54
+ };
55
+
56
+ const DENSITY_ORDER: DensityModeValue[] = ['compact', 'comfortable', 'spacious'];
57
+
58
+ /**
59
+ * Hook for managing view density modes (compact/comfortable/spacious).
60
+ * Implements DensityMode from @objectstack/spec v2.0.7.
61
+ *
62
+ * @example
63
+ * ```tsx
64
+ * const density = useDensityMode('comfortable');
65
+ *
66
+ * return (
67
+ * <div className={density.paddingClass}>
68
+ * <table style={{ rowHeight: density.rowHeight }}>...</table>
69
+ * <button onClick={density.cycle}>Toggle Density</button>
70
+ * </div>
71
+ * );
72
+ * ```
73
+ */
74
+ export function useDensityMode(
75
+ initialMode: DensityModeValue = 'comfortable',
76
+ config?: DensityConfig
77
+ ): DensityResult {
78
+ const [mode, setMode] = useState<DensityModeValue>(initialMode);
79
+
80
+ const rowHeights = config?.rowHeights ?? DEFAULT_ROW_HEIGHTS;
81
+ const paddingClasses = config?.paddingClasses ?? DEFAULT_PADDING_CLASSES;
82
+ const fontSizeClasses = config?.fontSizeClasses ?? DEFAULT_FONT_SIZE_CLASSES;
83
+
84
+ const cycle = useCallback(() => {
85
+ setMode((current) => {
86
+ const idx = DENSITY_ORDER.indexOf(current);
87
+ return DENSITY_ORDER[(idx + 1) % DENSITY_ORDER.length];
88
+ });
89
+ }, []);
90
+
91
+ return useMemo(
92
+ () => ({
93
+ mode,
94
+ setMode,
95
+ cycle,
96
+ rowHeight: rowHeights[mode],
97
+ paddingClass: paddingClasses[mode],
98
+ fontSizeClass: fontSizeClasses[mode],
99
+ }),
100
+ [mode, cycle, rowHeights, paddingClasses, fontSizeClasses]
101
+ );
102
+ }