@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,213 @@
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 - Action Context
11
+ *
12
+ * Provides a shared ActionRunner instance and handlers to the component tree.
13
+ * Components can consume actions without creating their own runner instances.
14
+ */
15
+
16
+ import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
17
+ import {
18
+ ActionRunner,
19
+ type ActionContext as ActionCtx,
20
+ type ActionDef,
21
+ type ActionResult,
22
+ type ConfirmationHandler,
23
+ type ToastHandler,
24
+ type ModalHandler,
25
+ type NavigationHandler,
26
+ type ParamCollectionHandler,
27
+ } from '@object-ui/core';
28
+
29
+ export interface ActionProviderProps {
30
+ children: React.ReactNode;
31
+ /** Initial action context (record, user, data, etc.) */
32
+ context?: ActionCtx;
33
+ /** Custom confirmation handler (e.g., Shadcn AlertDialog) */
34
+ onConfirm?: ConfirmationHandler;
35
+ /** Custom toast handler (e.g., Sonner) */
36
+ onToast?: ToastHandler;
37
+ /** Custom modal handler — render modals in response to modal actions */
38
+ onModal?: ModalHandler;
39
+ /** Custom navigation handler — SPA-aware routing (e.g., React Router navigate) */
40
+ onNavigate?: NavigationHandler;
41
+ /** Custom param collection handler — show dialog to collect ActionParam values */
42
+ onParamCollection?: ParamCollectionHandler;
43
+ /** Pre-registered custom action handlers */
44
+ handlers?: Record<string, (action: ActionDef, ctx: ActionCtx) => Promise<ActionResult>>;
45
+ }
46
+
47
+ interface ActionContextValue {
48
+ /** Execute an action */
49
+ execute: (action: ActionDef) => Promise<ActionResult>;
50
+ /** Execute multiple actions in chain */
51
+ executeChain: (actions: ActionDef[], mode?: 'sequential' | 'parallel') => Promise<ActionResult>;
52
+ /** Whether an action is currently being executed */
53
+ loading: boolean;
54
+ /** Last error message */
55
+ error: string | null;
56
+ /** Last action result */
57
+ result: ActionResult | null;
58
+ /** The underlying ActionRunner instance */
59
+ runner: ActionRunner;
60
+ /** Update context data */
61
+ updateContext: (ctx: Partial<ActionCtx>) => void;
62
+ }
63
+
64
+ const ActionCtxReact = createContext<ActionContextValue | null>(null);
65
+
66
+ /**
67
+ * ActionProvider — Provides a shared ActionRunner to the tree.
68
+ *
69
+ * @example
70
+ * ```tsx
71
+ * <ActionProvider
72
+ * context={{ record: currentRecord, user }}
73
+ * onToast={(msg, opts) => toast[opts?.type ?? 'info'](msg)}
74
+ * onConfirm={async (msg) => showConfirmDialog(msg)}
75
+ * onNavigate={(url) => router.push(url)}
76
+ * >
77
+ * <SchemaRenderer schema={pageSchema} />
78
+ * </ActionProvider>
79
+ * ```
80
+ */
81
+ export const ActionProvider: React.FC<ActionProviderProps> = ({
82
+ children,
83
+ context = {},
84
+ onConfirm,
85
+ onToast,
86
+ onModal,
87
+ onNavigate,
88
+ onParamCollection,
89
+ handlers,
90
+ }) => {
91
+ const [loading, setLoading] = useState(false);
92
+ const [error, setError] = useState<string | null>(null);
93
+ const [result, setResult] = useState<ActionResult | null>(null);
94
+
95
+ const runner = useMemo(() => {
96
+ const r = new ActionRunner(context);
97
+ if (onConfirm) r.setConfirmHandler(onConfirm);
98
+ if (onToast) r.setToastHandler(onToast);
99
+ if (onModal) r.setModalHandler(onModal);
100
+ if (onNavigate) r.setNavigationHandler(onNavigate);
101
+ if (onParamCollection) r.setParamCollectionHandler(onParamCollection);
102
+ if (handlers) {
103
+ Object.entries(handlers).forEach(([name, handler]) => {
104
+ r.registerHandler(name, handler);
105
+ });
106
+ }
107
+ return r;
108
+ // eslint-disable-next-line react-hooks/exhaustive-deps
109
+ }, [JSON.stringify(context)]);
110
+
111
+ const execute = useCallback(
112
+ async (action: ActionDef): Promise<ActionResult> => {
113
+ setLoading(true);
114
+ setError(null);
115
+ setResult(null);
116
+
117
+ try {
118
+ const actionResult = await runner.execute(action);
119
+ setResult(actionResult);
120
+ if (!actionResult.success) {
121
+ setError(actionResult.error || 'Action failed');
122
+ }
123
+ return actionResult;
124
+ } catch (err) {
125
+ const errorMessage = (err as Error).message;
126
+ setError(errorMessage);
127
+ const failureResult: ActionResult = { success: false, error: errorMessage };
128
+ setResult(failureResult);
129
+ return failureResult;
130
+ } finally {
131
+ setLoading(false);
132
+ }
133
+ },
134
+ [runner],
135
+ );
136
+
137
+ const executeChain = useCallback(
138
+ async (actions: ActionDef[], mode?: 'sequential' | 'parallel'): Promise<ActionResult> => {
139
+ setLoading(true);
140
+ setError(null);
141
+ setResult(null);
142
+
143
+ try {
144
+ const actionResult = await runner.executeChain(actions, mode);
145
+ setResult(actionResult);
146
+ if (!actionResult.success) {
147
+ setError(actionResult.error || 'Chain failed');
148
+ }
149
+ return actionResult;
150
+ } catch (err) {
151
+ const errorMessage = (err as Error).message;
152
+ setError(errorMessage);
153
+ const failureResult: ActionResult = { success: false, error: errorMessage };
154
+ setResult(failureResult);
155
+ return failureResult;
156
+ } finally {
157
+ setLoading(false);
158
+ }
159
+ },
160
+ [runner],
161
+ );
162
+
163
+ const updateContext = useCallback(
164
+ (newContext: Partial<ActionCtx>) => {
165
+ runner.updateContext(newContext);
166
+ },
167
+ [runner],
168
+ );
169
+
170
+ const value = useMemo<ActionContextValue>(
171
+ () => ({ execute, executeChain, loading, error, result, runner, updateContext }),
172
+ [execute, executeChain, loading, error, result, runner, updateContext],
173
+ );
174
+
175
+ return (
176
+ <ActionCtxReact.Provider value={value}>{children}</ActionCtxReact.Provider>
177
+ );
178
+ };
179
+
180
+ ActionProvider.displayName = 'ActionProvider';
181
+
182
+ /**
183
+ * Hook to consume the ActionProvider context.
184
+ * Returns the shared ActionRunner execute function, loading state, and more.
185
+ *
186
+ * Falls back to a local ActionRunner if no ActionProvider is present.
187
+ */
188
+ export function useAction(): ActionContextValue {
189
+ const ctx = useContext(ActionCtxReact);
190
+ if (!ctx) {
191
+ // Graceful fallback: create a local runner
192
+ // This allows action components to work even without an ActionProvider
193
+ const runner = new ActionRunner();
194
+ return {
195
+ execute: (action: ActionDef) => runner.execute(action),
196
+ executeChain: (actions: ActionDef[], mode?: 'sequential' | 'parallel') =>
197
+ runner.executeChain(actions, mode),
198
+ loading: false,
199
+ error: null,
200
+ result: null,
201
+ runner,
202
+ updateContext: (ctx: Partial<ActionCtx>) => runner.updateContext(ctx),
203
+ };
204
+ }
205
+ return ctx;
206
+ }
207
+
208
+ /**
209
+ * Hook to check if an ActionProvider is available.
210
+ */
211
+ export function useHasActionProvider(): boolean {
212
+ return useContext(ActionCtxReact) !== null;
213
+ }
@@ -0,0 +1,260 @@
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 - Drag and Drop Context
11
+ *
12
+ * Provides a unified DnD configuration system to the component tree.
13
+ * Implements DndConfigSchema, DragItemSchema, DropZoneSchema,
14
+ * DragConstraintSchema, and DropEffectSchema from @objectstack/spec v2.0.7.
15
+ */
16
+
17
+ import React, { createContext, useCallback, useContext, useMemo, useState } from 'react';
18
+
19
+ /** Drop effect types aligned with DropEffectSchema */
20
+ export type DropEffectType = 'move' | 'copy' | 'link' | 'none';
21
+
22
+ /** Drag constraint axis aligned with DragConstraintSchema */
23
+ export type DragAxis = 'x' | 'y' | 'both';
24
+
25
+ /** Drag item metadata */
26
+ export interface DragItemData {
27
+ /** Unique identifier for the dragged item */
28
+ id: string;
29
+ /** Type of the dragged item (for drop zone filtering) */
30
+ type: string;
31
+ /** Arbitrary data associated with the drag */
32
+ data?: Record<string, unknown>;
33
+ /** Source container/zone identifier */
34
+ sourceId?: string;
35
+ }
36
+
37
+ /** Drop zone configuration */
38
+ export interface DropZoneConfig {
39
+ /** Unique identifier for the drop zone */
40
+ id: string;
41
+ /** Accepted drag item types */
42
+ acceptTypes: string[];
43
+ /** Drop effect to apply */
44
+ effect?: DropEffectType;
45
+ /** Whether the zone is currently disabled */
46
+ disabled?: boolean;
47
+ /** Maximum number of items this zone can hold */
48
+ maxItems?: number;
49
+ }
50
+
51
+ /** Drag constraints configuration */
52
+ export interface DragConstraintConfig {
53
+ /** Constrain movement to an axis */
54
+ axis?: DragAxis;
55
+ /** Minimum distance before drag starts (in pixels) */
56
+ activationDistance?: number;
57
+ /** Whether to show a drag handle */
58
+ showHandle?: boolean;
59
+ /** Container bounds (CSS selector) */
60
+ containerId?: string;
61
+ }
62
+
63
+ /** Overall DnD configuration aligned with DndConfigSchema */
64
+ export interface DndSystemConfig {
65
+ /** Whether DnD is enabled */
66
+ enabled?: boolean;
67
+ /** Default drag constraints */
68
+ defaultConstraints?: DragConstraintConfig;
69
+ /** Whether to show drag overlay/preview */
70
+ showPreview?: boolean;
71
+ /** Auto-scroll when dragging near edges */
72
+ autoScroll?: boolean;
73
+ }
74
+
75
+ /** Drag event information */
76
+ export interface DragEvent {
77
+ /** The dragged item */
78
+ item: DragItemData;
79
+ /** Target drop zone (null if not over a zone) */
80
+ targetZoneId: string | null;
81
+ /** The applied drop effect */
82
+ effect: DropEffectType;
83
+ }
84
+
85
+ export interface DndProviderProps {
86
+ children: React.ReactNode;
87
+ /** System-wide DnD configuration */
88
+ config?: DndSystemConfig;
89
+ /** Called when a drag starts */
90
+ onDragStart?: (event: DragEvent) => void;
91
+ /** Called when an item is dropped */
92
+ onDrop?: (event: DragEvent) => void;
93
+ /** Called when a drag is cancelled */
94
+ onDragCancel?: (event: DragEvent) => void;
95
+ }
96
+
97
+ interface DndContextValue {
98
+ /** System-wide DnD configuration */
99
+ config: DndSystemConfig;
100
+ /** Whether DnD is enabled */
101
+ enabled: boolean;
102
+ /** Currently dragging item (null if not dragging) */
103
+ activeItem: DragItemData | null;
104
+ /** Registered drop zones */
105
+ dropZones: Map<string, DropZoneConfig>;
106
+ /** Start a drag operation */
107
+ startDrag: (item: DragItemData) => void;
108
+ /** End the current drag operation */
109
+ endDrag: (targetZoneId?: string) => void;
110
+ /** Cancel the current drag */
111
+ cancelDrag: () => void;
112
+ /** Register a drop zone */
113
+ registerDropZone: (zone: DropZoneConfig) => void;
114
+ /** Unregister a drop zone */
115
+ unregisterDropZone: (zoneId: string) => void;
116
+ /** Check if a drop zone accepts a drag item type */
117
+ canDrop: (zoneId: string, itemType: string) => boolean;
118
+ }
119
+
120
+ const DndCtx = createContext<DndContextValue | null>(null);
121
+
122
+ /**
123
+ * DndProvider — Provides a unified DnD system aligned with @objectstack/spec v2.0.7.
124
+ *
125
+ * This is a coordination layer; actual drag mechanics are delegated to
126
+ * libraries like @dnd-kit/core or react-grid-layout in individual plugins.
127
+ *
128
+ * @example
129
+ * ```tsx
130
+ * <DndProvider
131
+ * config={{ enabled: true, showPreview: true, autoScroll: true }}
132
+ * onDrop={(event) => handleDrop(event.item, event.targetZoneId)}
133
+ * >
134
+ * <KanbanBoard />
135
+ * </DndProvider>
136
+ * ```
137
+ */
138
+ export const DndProvider: React.FC<DndProviderProps> = ({
139
+ children,
140
+ config: userConfig = {},
141
+ onDragStart,
142
+ onDrop,
143
+ onDragCancel,
144
+ }) => {
145
+ const config = useMemo<DndSystemConfig>(
146
+ () => ({
147
+ enabled: true,
148
+ showPreview: true,
149
+ autoScroll: true,
150
+ ...userConfig,
151
+ }),
152
+ // eslint-disable-next-line react-hooks/exhaustive-deps
153
+ [JSON.stringify(userConfig)],
154
+ );
155
+
156
+ const [activeItem, setActiveItem] = useState<DragItemData | null>(null);
157
+ const [dropZones] = useState<Map<string, DropZoneConfig>>(() => new Map());
158
+
159
+ const startDrag = useCallback(
160
+ (item: DragItemData) => {
161
+ if (!config.enabled) return;
162
+ setActiveItem(item);
163
+ onDragStart?.({ item, targetZoneId: null, effect: 'move' });
164
+ },
165
+ [config.enabled, onDragStart],
166
+ );
167
+
168
+ const endDrag = useCallback(
169
+ (targetZoneId?: string) => {
170
+ if (!activeItem) return;
171
+ const zone = targetZoneId ? dropZones.get(targetZoneId) : undefined;
172
+ const effect: DropEffectType = zone?.effect ?? 'move';
173
+ onDrop?.({ item: activeItem, targetZoneId: targetZoneId ?? null, effect });
174
+ setActiveItem(null);
175
+ },
176
+ [activeItem, dropZones, onDrop],
177
+ );
178
+
179
+ const cancelDrag = useCallback(() => {
180
+ if (!activeItem) return;
181
+ onDragCancel?.({ item: activeItem, targetZoneId: null, effect: 'none' });
182
+ setActiveItem(null);
183
+ }, [activeItem, onDragCancel]);
184
+
185
+ const registerDropZone = useCallback(
186
+ (zone: DropZoneConfig) => {
187
+ dropZones.set(zone.id, zone);
188
+ },
189
+ [dropZones],
190
+ );
191
+
192
+ const unregisterDropZone = useCallback(
193
+ (zoneId: string) => {
194
+ dropZones.delete(zoneId);
195
+ },
196
+ [dropZones],
197
+ );
198
+
199
+ const canDrop = useCallback(
200
+ (zoneId: string, itemType: string): boolean => {
201
+ const zone = dropZones.get(zoneId);
202
+ if (!zone || zone.disabled) return false;
203
+ return zone.acceptTypes.includes(itemType);
204
+ },
205
+ [dropZones],
206
+ );
207
+
208
+ const value = useMemo<DndContextValue>(
209
+ () => ({
210
+ config,
211
+ enabled: config.enabled ?? true,
212
+ activeItem,
213
+ dropZones,
214
+ startDrag,
215
+ endDrag,
216
+ cancelDrag,
217
+ registerDropZone,
218
+ unregisterDropZone,
219
+ canDrop,
220
+ }),
221
+ [
222
+ config,
223
+ activeItem,
224
+ dropZones,
225
+ startDrag,
226
+ endDrag,
227
+ cancelDrag,
228
+ registerDropZone,
229
+ unregisterDropZone,
230
+ canDrop,
231
+ ],
232
+ );
233
+
234
+ return <DndCtx.Provider value={value}>{children}</DndCtx.Provider>;
235
+ };
236
+
237
+ DndProvider.displayName = 'DndProvider';
238
+
239
+ /**
240
+ * Hook to consume the DnD context.
241
+ *
242
+ * @throws Error if used outside a DndProvider
243
+ */
244
+ export function useDnd(): DndContextValue {
245
+ const ctx = useContext(DndCtx);
246
+ if (!ctx) {
247
+ throw new Error(
248
+ 'useDnd must be used within a <DndProvider>. ' +
249
+ 'Wrap your app with <DndProvider> to use the drag and drop system.',
250
+ );
251
+ }
252
+ return ctx;
253
+ }
254
+
255
+ /**
256
+ * Hook to check if a DndProvider is available.
257
+ */
258
+ export function useHasDndProvider(): boolean {
259
+ return useContext(DndCtx) !== null;
260
+ }