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