@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
@@ -9,6 +9,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
9
9
  import React from 'react';
10
10
  import { useForm, FormProvider } from 'react-hook-form';
11
11
  import { FieldFactory } from './FieldFactory';
12
+ import { ExpressionEvaluator } from '@object-ui/core';
13
+ import { resolveI18nLabel } from '../../utils/i18n';
12
14
  /**
13
15
  * FormRenderer component that renders forms based on FormViewSchema
14
16
  * from @objectstack/spec
@@ -58,6 +60,33 @@ const COL_SPAN = {
58
60
  3: 'col-span-3',
59
61
  4: 'col-span-4',
60
62
  };
63
+ /**
64
+ * Evaluate whether a field should be visible based on visibleOn expression
65
+ * and dependsOn parent field value.
66
+ */
67
+ function evaluateFieldVisibility(fieldConfig, formValues) {
68
+ // If explicitly hidden, skip
69
+ if (fieldConfig.hidden) {
70
+ return false;
71
+ }
72
+ // Evaluate visibleOn expression
73
+ if (fieldConfig.visibleOn) {
74
+ try {
75
+ const evaluator = new ExpressionEvaluator({ data: formValues, form: formValues });
76
+ return evaluator.evaluateCondition(fieldConfig.visibleOn);
77
+ }
78
+ catch {
79
+ // On error, default to visible
80
+ return true;
81
+ }
82
+ }
83
+ // Evaluate dependsOn: field is hidden if parent field has no value
84
+ if (fieldConfig.dependsOn) {
85
+ const parentValue = formValues[fieldConfig.dependsOn];
86
+ return parentValue !== undefined && parentValue !== null && parentValue !== '';
87
+ }
88
+ return true;
89
+ }
61
90
  /**
62
91
  * Renders a form section with grid layout
63
92
  */
@@ -65,17 +94,30 @@ const FormSectionRenderer = ({ section, methods, disabled = false, }) => {
65
94
  const [isCollapsed, setIsCollapsed] = React.useState(section.collapsed || false);
66
95
  // Determine grid columns based on section.columns
67
96
  const gridCols = GRID_COLS[section.columns || 1];
97
+ // Collect whether there are any conditional fields
98
+ const hasConditionalFields = React.useMemo(() => {
99
+ return section.fields.some((field) => {
100
+ if (typeof field === 'string')
101
+ return false;
102
+ return !!field.dependsOn || !!field.visibleOn;
103
+ });
104
+ }, [section.fields]);
105
+ // Watch form values for conditional field evaluation
106
+ // Only watch when there are fields with dependsOn or visibleOn to avoid
107
+ // unnecessary re-renders in forms without conditional fields.
108
+ const allFormValues = methods.watch();
109
+ const formValues = hasConditionalFields ? allFormValues : undefined;
68
110
  const handleToggleCollapse = () => {
69
111
  if (section.collapsible) {
70
112
  setIsCollapsed(!isCollapsed);
71
113
  }
72
114
  };
73
- return (_jsxs("div", { className: "border rounded-lg p-4", children: [section.label && (_jsxs("div", { className: `flex items-center justify-between mb-4 ${section.collapsible ? 'cursor-pointer' : ''}`, onClick: handleToggleCollapse, children: [_jsx("h3", { className: "text-lg font-semibold", children: section.label }), section.collapsible && (_jsx("span", { className: "text-sm text-gray-500", children: isCollapsed ? '▶' : '▼' }))] })), !isCollapsed && (_jsx("div", { className: `grid ${gridCols} gap-4`, children: section.fields.map((field, index) => {
115
+ return (_jsxs("div", { className: "border rounded-lg p-4", children: [section.label && (_jsxs("div", { className: `flex items-center justify-between mb-4 ${section.collapsible ? 'cursor-pointer' : ''}`, onClick: handleToggleCollapse, children: [_jsx("h3", { className: "text-lg font-semibold", children: resolveI18nLabel(section.label) }), section.collapsible && (_jsx("span", { className: "text-sm text-gray-500", children: isCollapsed ? '▶' : '▼' }))] })), !isCollapsed && (_jsx("div", { className: `grid ${gridCols} gap-4`, children: section.fields.map((field, index) => {
74
116
  // Handle both string fields (legacy) and FormFieldSchema objects
75
117
  const fieldName = typeof field === 'string' ? field : field.field;
76
118
  const fieldConfig = typeof field === 'string' ? { field: fieldName } : field;
77
- // Skip hidden fields
78
- if (fieldConfig.hidden) {
119
+ // Evaluate visibility: static hidden, visibleOn expression, dependsOn parent
120
+ if (!evaluateFieldVisibility(fieldConfig, formValues || {})) {
79
121
  return null;
80
122
  }
81
123
  // Calculate colSpan for grid
@@ -0,0 +1,76 @@
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 - Action Context
10
+ *
11
+ * Provides a shared ActionRunner instance and handlers to the component tree.
12
+ * Components can consume actions without creating their own runner instances.
13
+ */
14
+ import React from 'react';
15
+ import { ActionRunner, type ActionContext as ActionCtx, type ActionDef, type ActionResult, type ConfirmationHandler, type ToastHandler, type ModalHandler, type NavigationHandler, type ParamCollectionHandler } from '@object-ui/core';
16
+ export interface ActionProviderProps {
17
+ children: React.ReactNode;
18
+ /** Initial action context (record, user, data, etc.) */
19
+ context?: ActionCtx;
20
+ /** Custom confirmation handler (e.g., Shadcn AlertDialog) */
21
+ onConfirm?: ConfirmationHandler;
22
+ /** Custom toast handler (e.g., Sonner) */
23
+ onToast?: ToastHandler;
24
+ /** Custom modal handler — render modals in response to modal actions */
25
+ onModal?: ModalHandler;
26
+ /** Custom navigation handler — SPA-aware routing (e.g., React Router navigate) */
27
+ onNavigate?: NavigationHandler;
28
+ /** Custom param collection handler — show dialog to collect ActionParam values */
29
+ onParamCollection?: ParamCollectionHandler;
30
+ /** Pre-registered custom action handlers */
31
+ handlers?: Record<string, (action: ActionDef, ctx: ActionCtx) => Promise<ActionResult>>;
32
+ }
33
+ interface ActionContextValue {
34
+ /** Execute an action */
35
+ execute: (action: ActionDef) => Promise<ActionResult>;
36
+ /** Execute multiple actions in chain */
37
+ executeChain: (actions: ActionDef[], mode?: 'sequential' | 'parallel') => Promise<ActionResult>;
38
+ /** Whether an action is currently being executed */
39
+ loading: boolean;
40
+ /** Last error message */
41
+ error: string | null;
42
+ /** Last action result */
43
+ result: ActionResult | null;
44
+ /** The underlying ActionRunner instance */
45
+ runner: ActionRunner;
46
+ /** Update context data */
47
+ updateContext: (ctx: Partial<ActionCtx>) => void;
48
+ }
49
+ /**
50
+ * ActionProvider — Provides a shared ActionRunner to the tree.
51
+ *
52
+ * @example
53
+ * ```tsx
54
+ * <ActionProvider
55
+ * context={{ record: currentRecord, user }}
56
+ * onToast={(msg, opts) => toast[opts?.type ?? 'info'](msg)}
57
+ * onConfirm={async (msg) => showConfirmDialog(msg)}
58
+ * onNavigate={(url) => router.push(url)}
59
+ * >
60
+ * <SchemaRenderer schema={pageSchema} />
61
+ * </ActionProvider>
62
+ * ```
63
+ */
64
+ export declare const ActionProvider: React.FC<ActionProviderProps>;
65
+ /**
66
+ * Hook to consume the ActionProvider context.
67
+ * Returns the shared ActionRunner execute function, loading state, and more.
68
+ *
69
+ * Falls back to a local ActionRunner if no ActionProvider is present.
70
+ */
71
+ export declare function useAction(): ActionContextValue;
72
+ /**
73
+ * Hook to check if an ActionProvider is available.
74
+ */
75
+ export declare function useHasActionProvider(): boolean;
76
+ export {};
@@ -0,0 +1,139 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * ObjectUI
4
+ * Copyright (c) 2024-present ObjectStack Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
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
+ import { createContext, useCallback, useContext, useMemo, useState } from 'react';
16
+ import { ActionRunner, } from '@object-ui/core';
17
+ const ActionCtxReact = createContext(null);
18
+ /**
19
+ * ActionProvider — Provides a shared ActionRunner to the tree.
20
+ *
21
+ * @example
22
+ * ```tsx
23
+ * <ActionProvider
24
+ * context={{ record: currentRecord, user }}
25
+ * onToast={(msg, opts) => toast[opts?.type ?? 'info'](msg)}
26
+ * onConfirm={async (msg) => showConfirmDialog(msg)}
27
+ * onNavigate={(url) => router.push(url)}
28
+ * >
29
+ * <SchemaRenderer schema={pageSchema} />
30
+ * </ActionProvider>
31
+ * ```
32
+ */
33
+ export const ActionProvider = ({ children, context = {}, onConfirm, onToast, onModal, onNavigate, onParamCollection, handlers, }) => {
34
+ const [loading, setLoading] = useState(false);
35
+ const [error, setError] = useState(null);
36
+ const [result, setResult] = useState(null);
37
+ const runner = useMemo(() => {
38
+ const r = new ActionRunner(context);
39
+ if (onConfirm)
40
+ r.setConfirmHandler(onConfirm);
41
+ if (onToast)
42
+ r.setToastHandler(onToast);
43
+ if (onModal)
44
+ r.setModalHandler(onModal);
45
+ if (onNavigate)
46
+ r.setNavigationHandler(onNavigate);
47
+ if (onParamCollection)
48
+ r.setParamCollectionHandler(onParamCollection);
49
+ if (handlers) {
50
+ Object.entries(handlers).forEach(([name, handler]) => {
51
+ r.registerHandler(name, handler);
52
+ });
53
+ }
54
+ return r;
55
+ // eslint-disable-next-line react-hooks/exhaustive-deps
56
+ }, [JSON.stringify(context)]);
57
+ const execute = useCallback(async (action) => {
58
+ setLoading(true);
59
+ setError(null);
60
+ setResult(null);
61
+ try {
62
+ const actionResult = await runner.execute(action);
63
+ setResult(actionResult);
64
+ if (!actionResult.success) {
65
+ setError(actionResult.error || 'Action failed');
66
+ }
67
+ return actionResult;
68
+ }
69
+ catch (err) {
70
+ const errorMessage = err.message;
71
+ setError(errorMessage);
72
+ const failureResult = { success: false, error: errorMessage };
73
+ setResult(failureResult);
74
+ return failureResult;
75
+ }
76
+ finally {
77
+ setLoading(false);
78
+ }
79
+ }, [runner]);
80
+ const executeChain = useCallback(async (actions, mode) => {
81
+ setLoading(true);
82
+ setError(null);
83
+ setResult(null);
84
+ try {
85
+ const actionResult = await runner.executeChain(actions, mode);
86
+ setResult(actionResult);
87
+ if (!actionResult.success) {
88
+ setError(actionResult.error || 'Chain failed');
89
+ }
90
+ return actionResult;
91
+ }
92
+ catch (err) {
93
+ const errorMessage = err.message;
94
+ setError(errorMessage);
95
+ const failureResult = { success: false, error: errorMessage };
96
+ setResult(failureResult);
97
+ return failureResult;
98
+ }
99
+ finally {
100
+ setLoading(false);
101
+ }
102
+ }, [runner]);
103
+ const updateContext = useCallback((newContext) => {
104
+ runner.updateContext(newContext);
105
+ }, [runner]);
106
+ const value = useMemo(() => ({ execute, executeChain, loading, error, result, runner, updateContext }), [execute, executeChain, loading, error, result, runner, updateContext]);
107
+ return (_jsx(ActionCtxReact.Provider, { value: value, children: children }));
108
+ };
109
+ ActionProvider.displayName = 'ActionProvider';
110
+ /**
111
+ * Hook to consume the ActionProvider context.
112
+ * Returns the shared ActionRunner execute function, loading state, and more.
113
+ *
114
+ * Falls back to a local ActionRunner if no ActionProvider is present.
115
+ */
116
+ export function useAction() {
117
+ const ctx = useContext(ActionCtxReact);
118
+ if (!ctx) {
119
+ // Graceful fallback: create a local runner
120
+ // This allows action components to work even without an ActionProvider
121
+ const runner = new ActionRunner();
122
+ return {
123
+ execute: (action) => runner.execute(action),
124
+ executeChain: (actions, mode) => runner.executeChain(actions, mode),
125
+ loading: false,
126
+ error: null,
127
+ result: null,
128
+ runner,
129
+ updateContext: (ctx) => runner.updateContext(ctx),
130
+ };
131
+ }
132
+ return ctx;
133
+ }
134
+ /**
135
+ * Hook to check if an ActionProvider is available.
136
+ */
137
+ export function useHasActionProvider() {
138
+ return useContext(ActionCtxReact) !== null;
139
+ }
@@ -0,0 +1,135 @@
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 - Drag and Drop Context
10
+ *
11
+ * Provides a unified DnD configuration system to the component tree.
12
+ * Implements DndConfigSchema, DragItemSchema, DropZoneSchema,
13
+ * DragConstraintSchema, and DropEffectSchema from @objectstack/spec v2.0.7.
14
+ */
15
+ import React from 'react';
16
+ /** Drop effect types aligned with DropEffectSchema */
17
+ export type DropEffectType = 'move' | 'copy' | 'link' | 'none';
18
+ /** Drag constraint axis aligned with DragConstraintSchema */
19
+ export type DragAxis = 'x' | 'y' | 'both';
20
+ /** Drag item metadata */
21
+ export interface DragItemData {
22
+ /** Unique identifier for the dragged item */
23
+ id: string;
24
+ /** Type of the dragged item (for drop zone filtering) */
25
+ type: string;
26
+ /** Arbitrary data associated with the drag */
27
+ data?: Record<string, unknown>;
28
+ /** Source container/zone identifier */
29
+ sourceId?: string;
30
+ }
31
+ /** Drop zone configuration */
32
+ export interface DropZoneConfig {
33
+ /** Unique identifier for the drop zone */
34
+ id: string;
35
+ /** Accepted drag item types */
36
+ acceptTypes: string[];
37
+ /** Drop effect to apply */
38
+ effect?: DropEffectType;
39
+ /** Whether the zone is currently disabled */
40
+ disabled?: boolean;
41
+ /** Maximum number of items this zone can hold */
42
+ maxItems?: number;
43
+ }
44
+ /** Drag constraints configuration */
45
+ export interface DragConstraintConfig {
46
+ /** Constrain movement to an axis */
47
+ axis?: DragAxis;
48
+ /** Minimum distance before drag starts (in pixels) */
49
+ activationDistance?: number;
50
+ /** Whether to show a drag handle */
51
+ showHandle?: boolean;
52
+ /** Container bounds (CSS selector) */
53
+ containerId?: string;
54
+ }
55
+ /** Overall DnD configuration aligned with DndConfigSchema */
56
+ export interface DndSystemConfig {
57
+ /** Whether DnD is enabled */
58
+ enabled?: boolean;
59
+ /** Default drag constraints */
60
+ defaultConstraints?: DragConstraintConfig;
61
+ /** Whether to show drag overlay/preview */
62
+ showPreview?: boolean;
63
+ /** Auto-scroll when dragging near edges */
64
+ autoScroll?: boolean;
65
+ }
66
+ /** Drag event information */
67
+ export interface DragEvent {
68
+ /** The dragged item */
69
+ item: DragItemData;
70
+ /** Target drop zone (null if not over a zone) */
71
+ targetZoneId: string | null;
72
+ /** The applied drop effect */
73
+ effect: DropEffectType;
74
+ }
75
+ export interface DndProviderProps {
76
+ children: React.ReactNode;
77
+ /** System-wide DnD configuration */
78
+ config?: DndSystemConfig;
79
+ /** Called when a drag starts */
80
+ onDragStart?: (event: DragEvent) => void;
81
+ /** Called when an item is dropped */
82
+ onDrop?: (event: DragEvent) => void;
83
+ /** Called when a drag is cancelled */
84
+ onDragCancel?: (event: DragEvent) => void;
85
+ }
86
+ interface DndContextValue {
87
+ /** System-wide DnD configuration */
88
+ config: DndSystemConfig;
89
+ /** Whether DnD is enabled */
90
+ enabled: boolean;
91
+ /** Currently dragging item (null if not dragging) */
92
+ activeItem: DragItemData | null;
93
+ /** Registered drop zones */
94
+ dropZones: Map<string, DropZoneConfig>;
95
+ /** Start a drag operation */
96
+ startDrag: (item: DragItemData) => void;
97
+ /** End the current drag operation */
98
+ endDrag: (targetZoneId?: string) => void;
99
+ /** Cancel the current drag */
100
+ cancelDrag: () => void;
101
+ /** Register a drop zone */
102
+ registerDropZone: (zone: DropZoneConfig) => void;
103
+ /** Unregister a drop zone */
104
+ unregisterDropZone: (zoneId: string) => void;
105
+ /** Check if a drop zone accepts a drag item type */
106
+ canDrop: (zoneId: string, itemType: string) => boolean;
107
+ }
108
+ /**
109
+ * DndProvider — Provides a unified DnD system aligned with @objectstack/spec v2.0.7.
110
+ *
111
+ * This is a coordination layer; actual drag mechanics are delegated to
112
+ * libraries like @dnd-kit/core or react-grid-layout in individual plugins.
113
+ *
114
+ * @example
115
+ * ```tsx
116
+ * <DndProvider
117
+ * config={{ enabled: true, showPreview: true, autoScroll: true }}
118
+ * onDrop={(event) => handleDrop(event.item, event.targetZoneId)}
119
+ * >
120
+ * <KanbanBoard />
121
+ * </DndProvider>
122
+ * ```
123
+ */
124
+ export declare const DndProvider: React.FC<DndProviderProps>;
125
+ /**
126
+ * Hook to consume the DnD context.
127
+ *
128
+ * @throws Error if used outside a DndProvider
129
+ */
130
+ export declare function useDnd(): DndContextValue;
131
+ /**
132
+ * Hook to check if a DndProvider is available.
133
+ */
134
+ export declare function useHasDndProvider(): boolean;
135
+ export {};
@@ -0,0 +1,120 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * ObjectUI
4
+ * Copyright (c) 2024-present ObjectStack Inc.
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
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
+ import { createContext, useCallback, useContext, useMemo, useState } from 'react';
17
+ const DndCtx = createContext(null);
18
+ /**
19
+ * DndProvider — Provides a unified DnD system aligned with @objectstack/spec v2.0.7.
20
+ *
21
+ * This is a coordination layer; actual drag mechanics are delegated to
22
+ * libraries like @dnd-kit/core or react-grid-layout in individual plugins.
23
+ *
24
+ * @example
25
+ * ```tsx
26
+ * <DndProvider
27
+ * config={{ enabled: true, showPreview: true, autoScroll: true }}
28
+ * onDrop={(event) => handleDrop(event.item, event.targetZoneId)}
29
+ * >
30
+ * <KanbanBoard />
31
+ * </DndProvider>
32
+ * ```
33
+ */
34
+ export const DndProvider = ({ children, config: userConfig = {}, onDragStart, onDrop, onDragCancel, }) => {
35
+ const config = useMemo(() => ({
36
+ enabled: true,
37
+ showPreview: true,
38
+ autoScroll: true,
39
+ ...userConfig,
40
+ }),
41
+ // eslint-disable-next-line react-hooks/exhaustive-deps
42
+ [JSON.stringify(userConfig)]);
43
+ const [activeItem, setActiveItem] = useState(null);
44
+ const [dropZones] = useState(() => new Map());
45
+ const startDrag = useCallback((item) => {
46
+ if (!config.enabled)
47
+ return;
48
+ setActiveItem(item);
49
+ onDragStart?.({ item, targetZoneId: null, effect: 'move' });
50
+ }, [config.enabled, onDragStart]);
51
+ const endDrag = useCallback((targetZoneId) => {
52
+ if (!activeItem)
53
+ return;
54
+ const zone = targetZoneId ? dropZones.get(targetZoneId) : undefined;
55
+ const effect = zone?.effect ?? 'move';
56
+ onDrop?.({ item: activeItem, targetZoneId: targetZoneId ?? null, effect });
57
+ setActiveItem(null);
58
+ }, [activeItem, dropZones, onDrop]);
59
+ const cancelDrag = useCallback(() => {
60
+ if (!activeItem)
61
+ return;
62
+ onDragCancel?.({ item: activeItem, targetZoneId: null, effect: 'none' });
63
+ setActiveItem(null);
64
+ }, [activeItem, onDragCancel]);
65
+ const registerDropZone = useCallback((zone) => {
66
+ dropZones.set(zone.id, zone);
67
+ }, [dropZones]);
68
+ const unregisterDropZone = useCallback((zoneId) => {
69
+ dropZones.delete(zoneId);
70
+ }, [dropZones]);
71
+ const canDrop = useCallback((zoneId, itemType) => {
72
+ const zone = dropZones.get(zoneId);
73
+ if (!zone || zone.disabled)
74
+ return false;
75
+ return zone.acceptTypes.includes(itemType);
76
+ }, [dropZones]);
77
+ const value = useMemo(() => ({
78
+ config,
79
+ enabled: config.enabled ?? true,
80
+ activeItem,
81
+ dropZones,
82
+ startDrag,
83
+ endDrag,
84
+ cancelDrag,
85
+ registerDropZone,
86
+ unregisterDropZone,
87
+ canDrop,
88
+ }), [
89
+ config,
90
+ activeItem,
91
+ dropZones,
92
+ startDrag,
93
+ endDrag,
94
+ cancelDrag,
95
+ registerDropZone,
96
+ unregisterDropZone,
97
+ canDrop,
98
+ ]);
99
+ return _jsx(DndCtx.Provider, { value: value, children: children });
100
+ };
101
+ DndProvider.displayName = 'DndProvider';
102
+ /**
103
+ * Hook to consume the DnD context.
104
+ *
105
+ * @throws Error if used outside a DndProvider
106
+ */
107
+ export function useDnd() {
108
+ const ctx = useContext(DndCtx);
109
+ if (!ctx) {
110
+ throw new Error('useDnd must be used within a <DndProvider>. ' +
111
+ 'Wrap your app with <DndProvider> to use the drag and drop system.');
112
+ }
113
+ return ctx;
114
+ }
115
+ /**
116
+ * Hook to check if a DndProvider is available.
117
+ */
118
+ export function useHasDndProvider() {
119
+ return useContext(DndCtx) !== null;
120
+ }
@@ -0,0 +1,113 @@
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 - Notification Context
10
+ *
11
+ * Provides a spec-driven notification system to the component tree.
12
+ * Implements NotificationSchema, NotificationConfigSchema, and
13
+ * NotificationActionSchema from @objectstack/spec v2.0.7.
14
+ */
15
+ import React from 'react';
16
+ /** Notification severity levels aligned with NotificationSeveritySchema */
17
+ export type NotificationSeverityLevel = 'info' | 'success' | 'warning' | 'error';
18
+ /** Notification display type aligned with NotificationTypeSchema */
19
+ export type NotificationDisplayType = 'toast' | 'banner' | 'snackbar' | 'modal';
20
+ /** Notification position aligned with NotificationPositionSchema */
21
+ export type NotificationPositionValue = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
22
+ /** Action button on a notification */
23
+ export interface NotificationActionButton {
24
+ label: string;
25
+ onClick: () => void;
26
+ variant?: 'default' | 'destructive' | 'outline';
27
+ }
28
+ /** A single notification item */
29
+ export interface NotificationItem {
30
+ id: string;
31
+ title: string;
32
+ message?: string;
33
+ severity: NotificationSeverityLevel;
34
+ displayType?: NotificationDisplayType;
35
+ actions?: NotificationActionButton[];
36
+ /** Duration in ms (0 = persistent). Default: 5000 */
37
+ duration?: number;
38
+ /** Whether the notification has been read */
39
+ read?: boolean;
40
+ /** Timestamp */
41
+ createdAt: Date;
42
+ /** Optional icon name (lucide icon) */
43
+ icon?: string;
44
+ }
45
+ /** Configuration for the notification system */
46
+ export interface NotificationSystemConfig {
47
+ /** Default position for toast notifications */
48
+ position?: NotificationPositionValue;
49
+ /** Default duration in ms */
50
+ defaultDuration?: number;
51
+ /** Maximum number of visible notifications */
52
+ maxVisible?: number;
53
+ /** Whether to stack notifications */
54
+ stacking?: boolean;
55
+ }
56
+ export interface NotificationProviderProps {
57
+ children: React.ReactNode;
58
+ /** System configuration */
59
+ config?: NotificationSystemConfig;
60
+ /** External toast handler (e.g., Sonner) for rendering toasts */
61
+ onToast?: (notification: NotificationItem) => void;
62
+ }
63
+ interface NotificationContextValue {
64
+ /** All notifications (including history) */
65
+ notifications: NotificationItem[];
66
+ /** Unread notification count */
67
+ unreadCount: number;
68
+ /** Add a notification */
69
+ notify: (notification: Omit<NotificationItem, 'id' | 'createdAt' | 'read'>) => string;
70
+ /** Convenience: show info notification */
71
+ info: (title: string, message?: string) => string;
72
+ /** Convenience: show success notification */
73
+ success: (title: string, message?: string) => string;
74
+ /** Convenience: show warning notification */
75
+ warning: (title: string, message?: string) => string;
76
+ /** Convenience: show error notification */
77
+ error: (title: string, message?: string) => string;
78
+ /** Mark a notification as read */
79
+ markAsRead: (id: string) => void;
80
+ /** Mark all notifications as read */
81
+ markAllAsRead: () => void;
82
+ /** Dismiss a notification */
83
+ dismiss: (id: string) => void;
84
+ /** Clear all notifications */
85
+ clearAll: () => void;
86
+ /** System configuration */
87
+ config: NotificationSystemConfig;
88
+ }
89
+ /**
90
+ * NotificationProvider — Provides a spec-driven notification system.
91
+ *
92
+ * @example
93
+ * ```tsx
94
+ * <NotificationProvider
95
+ * config={{ position: 'top-right', defaultDuration: 5000, maxVisible: 5 }}
96
+ * onToast={(n) => toast[n.severity](n.title, { description: n.message })}
97
+ * >
98
+ * <App />
99
+ * </NotificationProvider>
100
+ * ```
101
+ */
102
+ export declare const NotificationProvider: React.FC<NotificationProviderProps>;
103
+ /**
104
+ * Hook to consume the NotificationProvider context.
105
+ *
106
+ * @throws Error if used outside a NotificationProvider
107
+ */
108
+ export declare function useNotifications(): NotificationContextValue;
109
+ /**
110
+ * Hook to check if a NotificationProvider is available.
111
+ */
112
+ export declare function useHasNotificationProvider(): boolean;
113
+ export {};