@object-ui/react 3.1.5 → 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 (109) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +28 -3
  3. package/dist/SchemaRenderer.js +2 -2
  4. package/dist/components/form/FieldFactory.js +5 -2
  5. package/dist/context/AppShellContext.d.ts +26 -0
  6. package/dist/context/AppShellContext.js +67 -0
  7. package/dist/context/index.d.ts +1 -7
  8. package/dist/context/index.js +1 -7
  9. package/dist/hooks/index.d.ts +1 -0
  10. package/dist/hooks/index.js +1 -0
  11. package/dist/hooks/useDataRefresh.d.ts +36 -0
  12. package/dist/hooks/useDataRefresh.js +50 -0
  13. package/dist/hooks/useDiscovery.d.ts +12 -0
  14. package/dist/hooks/useDiscovery.js +6 -0
  15. package/dist/hooks/usePerformanceBudget.js +1 -1
  16. package/package.json +32 -9
  17. package/.turbo/turbo-build.log +0 -4
  18. package/src/LazyPluginLoader.tsx +0 -174
  19. package/src/SchemaRenderer.tsx +0 -266
  20. package/src/__tests__/LazyPluginLoader.test.tsx +0 -176
  21. package/src/__tests__/SchemaRenderer.aria.test.tsx +0 -118
  22. package/src/__tests__/SchemaRenderer.debug.test.tsx +0 -69
  23. package/src/__tests__/SchemaRenderer.errorBoundary.test.tsx +0 -114
  24. package/src/__tests__/SchemaRenderer.expressions.test.tsx +0 -131
  25. package/src/__tests__/SchemaRendererProvider.smoke.test.tsx +0 -132
  26. package/src/__tests__/ThemeProvider.test.tsx +0 -451
  27. package/src/__tests__/useNavigationOverlay.test.ts +0 -578
  28. package/src/__tests__/useOffline.test.ts +0 -198
  29. package/src/__tests__/usePageTransition.test.ts +0 -214
  30. package/src/__tests__/usePageVariables.test.tsx +0 -334
  31. package/src/__tests__/usePerformance.test.ts +0 -137
  32. package/src/__tests__/useViewData.test.tsx +0 -422
  33. package/src/__tests__/view-switching.test.tsx +0 -456
  34. package/src/components/form/FieldFactory.tsx +0 -509
  35. package/src/components/form/FormRenderer.test.tsx +0 -744
  36. package/src/components/form/FormRenderer.tsx +0 -258
  37. package/src/components/form/README.md +0 -352
  38. package/src/components/form/index.ts +0 -12
  39. package/src/context/ActionContext.tsx +0 -213
  40. package/src/context/DndContext.tsx +0 -260
  41. package/src/context/NotificationContext.tsx +0 -280
  42. package/src/context/SchemaRendererContext.tsx +0 -48
  43. package/src/context/ThemeContext.tsx +0 -325
  44. package/src/context/__tests__/ActionContext.test.tsx +0 -174
  45. package/src/context/__tests__/DndContext.test.tsx +0 -150
  46. package/src/context/__tests__/NotificationContext.test.tsx +0 -176
  47. package/src/context/__tests__/useDataScope.test.tsx +0 -91
  48. package/src/context/index.ts +0 -13
  49. package/src/hooks/__tests__/useActionEngine.test.ts +0 -170
  50. package/src/hooks/__tests__/useActionRunner.test.ts +0 -153
  51. package/src/hooks/__tests__/useAnimation.test.ts +0 -82
  52. package/src/hooks/__tests__/useColumnSummary.test.ts +0 -93
  53. package/src/hooks/__tests__/useCrudShortcuts.test.ts +0 -85
  54. package/src/hooks/__tests__/useDebugMode.test.ts +0 -83
  55. package/src/hooks/__tests__/useDensityMode.test.ts +0 -81
  56. package/src/hooks/__tests__/useDiscovery.test.tsx +0 -149
  57. package/src/hooks/__tests__/useDynamicApp.test.ts +0 -161
  58. package/src/hooks/__tests__/useETagCache.test.ts +0 -153
  59. package/src/hooks/__tests__/useExpression.test.ts +0 -86
  60. package/src/hooks/__tests__/useFocusTrap.test.ts +0 -294
  61. package/src/hooks/__tests__/useKeyboardShortcuts.test.ts +0 -144
  62. package/src/hooks/__tests__/usePageTransition.test.ts +0 -158
  63. package/src/hooks/__tests__/usePerformanceBudget.test.ts +0 -157
  64. package/src/hooks/__tests__/useReducedMotion.test.ts +0 -104
  65. package/src/hooks/__tests__/useSchemaPersistence.test.ts +0 -220
  66. package/src/hooks/__tests__/useViewSharing.test.ts +0 -121
  67. package/src/hooks/__tests__/useViewTransition.test.ts +0 -61
  68. package/src/hooks/index.ts +0 -35
  69. package/src/hooks/useActionEngine.ts +0 -84
  70. package/src/hooks/useActionRunner.ts +0 -119
  71. package/src/hooks/useAnimation.ts +0 -117
  72. package/src/hooks/useClientNotifications.ts +0 -251
  73. package/src/hooks/useColumnSummary.ts +0 -87
  74. package/src/hooks/useCrudShortcuts.ts +0 -126
  75. package/src/hooks/useDebugMode.ts +0 -95
  76. package/src/hooks/useDensityMode.ts +0 -102
  77. package/src/hooks/useDiscovery.ts +0 -154
  78. package/src/hooks/useDynamicApp.ts +0 -142
  79. package/src/hooks/useETagCache.ts +0 -404
  80. package/src/hooks/useExpression.ts +0 -56
  81. package/src/hooks/useFocusManagement.ts +0 -248
  82. package/src/hooks/useFocusTrap.ts +0 -138
  83. package/src/hooks/useGlobalUndo.ts +0 -98
  84. package/src/hooks/useKeyboardShortcuts.ts +0 -119
  85. package/src/hooks/useNavigationOverlay.ts +0 -190
  86. package/src/hooks/useOffline.ts +0 -301
  87. package/src/hooks/usePageTransition.ts +0 -187
  88. package/src/hooks/usePageVariables.tsx +0 -157
  89. package/src/hooks/usePerformance.ts +0 -246
  90. package/src/hooks/usePerformanceBudget.ts +0 -313
  91. package/src/hooks/useReducedMotion.ts +0 -53
  92. package/src/hooks/useSchemaPersistence.ts +0 -222
  93. package/src/hooks/useViewData.ts +0 -201
  94. package/src/hooks/useViewSharing.ts +0 -140
  95. package/src/hooks/useViewTransition.ts +0 -144
  96. package/src/index.ts +0 -41
  97. package/src/spec-bridge/SpecBridge.ts +0 -64
  98. package/src/spec-bridge/__tests__/P1SpecBridge.test.ts +0 -855
  99. package/src/spec-bridge/__tests__/SpecBridge.test.ts +0 -550
  100. package/src/spec-bridge/bridges/dashboard.ts +0 -180
  101. package/src/spec-bridge/bridges/form-view.ts +0 -109
  102. package/src/spec-bridge/bridges/list-view.ts +0 -187
  103. package/src/spec-bridge/bridges/page.ts +0 -136
  104. package/src/spec-bridge/index.ts +0 -14
  105. package/src/spec-bridge/types.ts +0 -38
  106. package/src/utils/i18n.ts +0 -10
  107. package/tsconfig.json +0 -17
  108. package/tsconfig.tsbuildinfo +0 -1
  109. package/vitest.config.ts +0 -2
@@ -1,84 +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
- /**
10
- * useActionEngine — React hook wrapping ActionEngine for location-based action management.
11
- *
12
- * Provides declarative access to the ActionEngine's location filtering, bulk operations,
13
- * keyboard shortcut handling, and execution pipeline from React components.
14
- *
15
- * @example
16
- * ```tsx
17
- * const { getActionsForLocation, executeAction } = useActionEngine({
18
- * actions: schema.actions,
19
- * context: { record, user },
20
- * });
21
- *
22
- * const toolbarActions = getActionsForLocation('list_toolbar');
23
- * ```
24
- */
25
-
26
- import { useCallback, useMemo } from 'react';
27
- import {
28
- ActionEngine,
29
- type ActionLocation,
30
- type ActionDef,
31
- type ActionContext,
32
- type ActionResult,
33
- } from '@object-ui/core';
34
-
35
- export interface UseActionEngineOptions {
36
- /** Action definitions to register */
37
- actions?: ActionDef[];
38
- /** Action context (record, user, etc.) */
39
- context?: ActionContext;
40
- }
41
-
42
- export interface UseActionEngineReturn {
43
- /** Get actions available at a specific location, sorted by priority */
44
- getActionsForLocation: (location: ActionLocation) => ActionDef[];
45
- /** Get actions that support bulk operations */
46
- getBulkActions: () => ActionDef[];
47
- /** Execute an action by name */
48
- executeAction: (name: string, contextOverride?: Partial<ActionContext>) => Promise<ActionResult>;
49
- /** Handle a keyboard shortcut */
50
- handleShortcut: (keys: string) => Promise<ActionResult | null>;
51
- /** The underlying ActionEngine instance */
52
- engine: ActionEngine;
53
- }
54
-
55
- export function useActionEngine(options: UseActionEngineOptions = {}): UseActionEngineReturn {
56
- const { actions = [], context = {} } = options;
57
-
58
- const engine = useMemo(() => {
59
- const e = new ActionEngine(context);
60
- e.registerActions(actions);
61
- return e;
62
- // eslint-disable-next-line react-hooks/exhaustive-deps
63
- }, [JSON.stringify(actions), JSON.stringify(context)]);
64
-
65
- const getActionsForLocation = useCallback(
66
- (location: ActionLocation) => engine.getActionsForLocation(location),
67
- [engine],
68
- );
69
-
70
- const getBulkActions = useCallback(() => engine.getBulkActions(), [engine]);
71
-
72
- const executeAction = useCallback(
73
- (name: string, contextOverride?: Partial<ActionContext>) =>
74
- engine.executeAction(name, contextOverride),
75
- [engine],
76
- );
77
-
78
- const handleShortcut = useCallback(
79
- (keys: string) => engine.handleShortcut(keys),
80
- [engine],
81
- );
82
-
83
- return { getActionsForLocation, getBulkActions, executeAction, handleShortcut, engine };
84
- }
@@ -1,119 +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 {
11
- ActionRunner,
12
- type ActionContext,
13
- type ActionDef,
14
- type ActionResult,
15
- type ConfirmationHandler,
16
- type ToastHandler,
17
- type ModalHandler,
18
- type NavigationHandler,
19
- } from '@object-ui/core';
20
-
21
- export interface UseActionRunnerOptions {
22
- context?: ActionContext;
23
- /** Custom confirmation handler — wire to Shadcn AlertDialog or similar */
24
- onConfirm?: ConfirmationHandler;
25
- /** Custom toast handler — wire to Sonner or similar */
26
- onToast?: ToastHandler;
27
- /** Custom modal handler — render modals in response to modal actions */
28
- onModal?: ModalHandler;
29
- /** Custom navigation handler — SPA-aware routing */
30
- onNavigate?: NavigationHandler;
31
- }
32
-
33
- /**
34
- * Hook for executing actions with loading state, typed with ActionDef.
35
- *
36
- * @example
37
- * ```tsx
38
- * const { execute, loading, error, result } = useActionRunner({
39
- * context: { data: formData },
40
- * onToast: (msg, opts) => toast[opts?.type || 'info'](msg),
41
- * });
42
- *
43
- * const handleClick = () => {
44
- * execute({
45
- * type: 'api',
46
- * api: '/api/save',
47
- * successMessage: 'Saved successfully!',
48
- * });
49
- * };
50
- * ```
51
- */
52
- export function useActionRunner(
53
- optionsOrContext: UseActionRunnerOptions | ActionContext = {},
54
- ) {
55
- // Backwards compat: if no 'context' key, treat entire object as context
56
- const options: UseActionRunnerOptions = 'context' in optionsOrContext
57
- ? optionsOrContext as UseActionRunnerOptions
58
- : { context: optionsOrContext as ActionContext };
59
-
60
- const { context = {}, onConfirm, onToast, onModal, onNavigate } = options;
61
-
62
- const [loading, setLoading] = useState(false);
63
- const [error, setError] = useState<string | null>(null);
64
- const [result, setResult] = useState<ActionResult | null>(null);
65
-
66
- const runner = useMemo(() => {
67
- const r = new ActionRunner(context);
68
- if (onConfirm) r.setConfirmHandler(onConfirm);
69
- if (onToast) r.setToastHandler(onToast);
70
- if (onModal) r.setModalHandler(onModal);
71
- if (onNavigate) r.setNavigationHandler(onNavigate);
72
- return r;
73
- // eslint-disable-next-line react-hooks/exhaustive-deps
74
- }, [JSON.stringify(context)]);
75
-
76
- const execute = useCallback(
77
- async (action: ActionDef): Promise<ActionResult> => {
78
- setLoading(true);
79
- setError(null);
80
- setResult(null);
81
-
82
- try {
83
- const actionResult = await runner.execute(action);
84
- setResult(actionResult);
85
-
86
- if (!actionResult.success) {
87
- setError(actionResult.error || 'Action failed');
88
- }
89
-
90
- return actionResult;
91
- } catch (err) {
92
- const errorMessage = (err as Error).message;
93
- setError(errorMessage);
94
- const failureResult = { success: false, error: errorMessage };
95
- setResult(failureResult);
96
- return failureResult;
97
- } finally {
98
- setLoading(false);
99
- }
100
- },
101
- [runner]
102
- );
103
-
104
- const updateContext = useCallback(
105
- (newContext: Partial<ActionContext>) => {
106
- runner.updateContext(newContext);
107
- },
108
- [runner]
109
- );
110
-
111
- return {
112
- execute,
113
- loading,
114
- error,
115
- result,
116
- updateContext,
117
- runner
118
- };
119
- }
@@ -1,117 +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 { useMemo } from 'react';
10
-
11
- /** Animation trigger type */
12
- export type AnimationTriggerType = 'enter' | 'exit' | 'hover' | 'focus' | 'click';
13
-
14
- /** Easing presets aligned with EasingFunctionSchema */
15
- export type EasingPreset =
16
- | 'linear'
17
- | 'ease'
18
- | 'ease-in'
19
- | 'ease-out'
20
- | 'ease-in-out'
21
- | 'spring';
22
-
23
- /** Transition preset aligned with TransitionPresetSchema */
24
- export type TransitionPresetType =
25
- | 'fade'
26
- | 'slide-up'
27
- | 'slide-down'
28
- | 'slide-left'
29
- | 'slide-right'
30
- | 'scale'
31
- | 'scale-fade'
32
- | 'none';
33
-
34
- export interface AnimationConfig {
35
- /** The animation/transition preset */
36
- preset?: TransitionPresetType;
37
- /** Duration in milliseconds */
38
- duration?: number;
39
- /** Delay in milliseconds */
40
- delay?: number;
41
- /** Easing function */
42
- easing?: EasingPreset;
43
- /** Whether animation is enabled */
44
- enabled?: boolean;
45
- }
46
-
47
- /** Resolved CSS classes and styles for animation */
48
- export interface AnimationResult {
49
- /** Tailwind CSS classes for the animation */
50
- className: string;
51
- /** Inline style for custom durations/delays (only when needed) */
52
- style: React.CSSProperties;
53
- }
54
-
55
- const EASING_MAP: Record<EasingPreset, string> = {
56
- linear: 'linear',
57
- ease: 'ease',
58
- 'ease-in': 'ease-in',
59
- 'ease-out': 'ease-out',
60
- 'ease-in-out': 'ease-in-out',
61
- spring: 'cubic-bezier(0.34, 1.56, 0.64, 1)',
62
- };
63
-
64
- const PRESET_CLASSES: Record<TransitionPresetType, string> = {
65
- fade: 'animate-in fade-in',
66
- 'slide-up': 'animate-in slide-in-from-bottom-2',
67
- 'slide-down': 'animate-in slide-in-from-top-2',
68
- 'slide-left': 'animate-in slide-in-from-right-2',
69
- 'slide-right': 'animate-in slide-in-from-left-2',
70
- scale: 'animate-in zoom-in-95',
71
- 'scale-fade': 'animate-in fade-in zoom-in-95',
72
- none: '',
73
- };
74
-
75
- /**
76
- * Hook for applying spec-driven animations to components.
77
- * Implements ComponentAnimationSchema and TransitionPresetSchema
78
- * from @objectstack/spec v2.0.7.
79
- *
80
- * @example
81
- * ```tsx
82
- * function Card() {
83
- * const animation = useAnimation({ preset: 'fade', duration: 200, easing: 'ease-out' });
84
- * return <div className={animation.className} style={animation.style}>...</div>;
85
- * }
86
- * ```
87
- */
88
- export function useAnimation(config: AnimationConfig = {}): AnimationResult {
89
- const {
90
- preset = 'none',
91
- duration,
92
- delay,
93
- easing = 'ease-out',
94
- enabled = true,
95
- } = config;
96
-
97
- return useMemo(() => {
98
- if (!enabled || preset === 'none') {
99
- return { className: '', style: {} };
100
- }
101
-
102
- const className = PRESET_CLASSES[preset] || '';
103
- const style: React.CSSProperties = {};
104
-
105
- if (duration !== undefined) {
106
- style.animationDuration = `${duration}ms`;
107
- }
108
- if (delay !== undefined) {
109
- style.animationDelay = `${delay}ms`;
110
- }
111
- if (easing) {
112
- style.animationTimingFunction = EASING_MAP[easing] || easing;
113
- }
114
-
115
- return { className, style };
116
- }, [preset, duration, delay, easing, enabled]);
117
- }
@@ -1,251 +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
- /**
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
- }
@@ -1,87 +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 { 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
- }