@aventoapp/framework 0.2.0 → 0.2.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 (157) hide show
  1. package/README.md +260 -0
  2. package/dist/index.js.map +1 -1
  3. package/dist/native/index.js.map +1 -1
  4. package/dist/offline/index.js.map +1 -1
  5. package/dist/server/index.js.map +1 -1
  6. package/dist/server/workflow/index.js.map +1 -1
  7. package/dist/shared/index.js.map +1 -1
  8. package/dist/web/index.js.map +1 -1
  9. package/package.json +84 -79
  10. package/schemas/Workflow.json +14 -14
  11. package/schemas/WorkflowHistory.json +22 -22
  12. package/schemas/WorkflowInstance.json +16 -16
  13. package/schemas/WorkflowState.json +18 -18
  14. package/schemas/WorkflowTransition.json +27 -27
  15. package/src/index.js +8 -8
  16. package/src/native/components/NativeAuthProvider.jsx +249 -249
  17. package/src/native/components/NativeDetail.jsx +270 -270
  18. package/src/native/components/NativeForm.jsx +543 -543
  19. package/src/native/components/NativeGrid.jsx +90 -90
  20. package/src/native/components/NativeJsonGrid.jsx +213 -213
  21. package/src/native/components/NativeJsonView.jsx +454 -454
  22. package/src/native/components/NativeJsonViewContext.js +17 -17
  23. package/src/native/components/NativeShell.jsx +68 -68
  24. package/src/native/components/NativeViewComponent.jsx +351 -351
  25. package/src/native/extensions/NativeExtensionRegistry.js +81 -81
  26. package/src/native/hooks/useNativeStore.js +72 -72
  27. package/src/native/index.js +15 -15
  28. package/src/native/layouts/NativeStackLayout.jsx +30 -30
  29. package/src/native/layouts/NativeTabLayout.jsx +96 -96
  30. package/src/native/storage.js +13 -13
  31. package/src/native/stores/NativeBaseStore.js +348 -348
  32. package/src/native/stores/NativeStoreContext.jsx +53 -53
  33. package/src/offline/index.js +1 -1
  34. package/src/server/ai/capabilities-routes.js +106 -106
  35. package/src/server/ai/index.js +1 -1
  36. package/src/server/cache/MemoryCache.js +153 -153
  37. package/src/server/cache/index.js +2 -2
  38. package/src/server/cache/middleware.js +12 -12
  39. package/src/server/db/index.js +14 -14
  40. package/src/server/db/mongo.js +137 -137
  41. package/src/server/db/postgres.js +144 -144
  42. package/src/server/index.js +42 -42
  43. package/src/server/middleware/auth.js +682 -682
  44. package/src/server/middleware/can-flags.js +132 -132
  45. package/src/server/middleware/entityRoles.js +105 -105
  46. package/src/server/middleware/index.js +58 -58
  47. package/src/server/middleware/permissions.js +240 -240
  48. package/src/server/middleware/tenant.js +203 -203
  49. package/src/server/realtime/EventBus.js +45 -45
  50. package/src/server/realtime/WebSocketServer.js +105 -105
  51. package/src/server/realtime/index.js +3 -3
  52. package/src/server/realtime/middleware.js +18 -18
  53. package/src/server/services/email-templates.js +157 -157
  54. package/src/server/services/email.js +78 -78
  55. package/src/server/services/index.js +15 -15
  56. package/src/server/services/storage.js +119 -119
  57. package/src/server/utils/index.js +16 -16
  58. package/src/server/utils/paginate.js +65 -65
  59. package/src/server/utils/query-builder.js +293 -293
  60. package/src/server/utils/route-loader.js +61 -61
  61. package/src/server/workflow/WorkflowEngine.js +494 -494
  62. package/src/server/workflow/index.js +2 -2
  63. package/src/server/workflow/workflow-routes.js +174 -174
  64. package/src/shared/index.js +10 -10
  65. package/src/shared/utils/field-accessor.js +108 -108
  66. package/src/shared/utils/index.js +7 -7
  67. package/src/shared/utils/validation-utils.js +83 -83
  68. package/src/web/components/AppRouter/AppRouter.jsx +130 -130
  69. package/src/web/components/AppRouter/index.js +1 -1
  70. package/src/web/components/AppShell/AppShell.jsx +101 -101
  71. package/src/web/components/AppShell/DefaultUserMenu.jsx +54 -54
  72. package/src/web/components/AppShell/ShellConfig.js +53 -53
  73. package/src/web/components/AppShell/index.js +3 -3
  74. package/src/web/components/AuthProvider.jsx +426 -426
  75. package/src/web/components/CardList/CardList.jsx +272 -272
  76. package/src/web/components/CardList/index.js +2 -2
  77. package/src/web/components/DetailView/DetailView.jsx +281 -281
  78. package/src/web/components/DetailView/index.js +2 -2
  79. package/src/web/components/Form/Form.jsx +300 -300
  80. package/src/web/components/Form/FormField.jsx +226 -226
  81. package/src/web/components/Form/index.js +3 -3
  82. package/src/web/components/Grid/Grid.jsx +304 -304
  83. package/src/web/components/Grid/index.js +2 -2
  84. package/src/web/components/IconRegistry/IconRegistry.jsx +127 -127
  85. package/src/web/components/IconRegistry/index.js +1 -1
  86. package/src/web/components/JsonView/JsonView.jsx +647 -647
  87. package/src/web/components/JsonView/ViewComponent.jsx +1045 -1045
  88. package/src/web/components/JsonView/ViewToolbar.jsx +141 -141
  89. package/src/web/components/JsonView/index.js +14 -14
  90. package/src/web/components/JsonView/layouts/SingleLayout.jsx +41 -41
  91. package/src/web/components/JsonView/layouts/SplitLayout.jsx +122 -122
  92. package/src/web/components/JsonView/layouts/TabLayout.jsx +112 -112
  93. package/src/web/components/JsonView/layouts/index.js +8 -8
  94. package/src/web/components/Layout.jsx +265 -265
  95. package/src/web/components/MobileLayout/MobileLayout.jsx +385 -385
  96. package/src/web/components/MobileLayout/index.js +1 -1
  97. package/src/web/components/Navigation/Navigation.jsx +248 -248
  98. package/src/web/components/Navigation/index.js +1 -1
  99. package/src/web/components/NotificationProvider.jsx +55 -55
  100. package/src/web/components/Pagination/InfiniteScroll.jsx +82 -82
  101. package/src/web/components/Pagination/Pagination.jsx +73 -73
  102. package/src/web/components/Pagination/index.js +8 -8
  103. package/src/web/components/SimpleList/SimpleList.jsx +177 -177
  104. package/src/web/components/SimpleList/index.js +2 -2
  105. package/src/web/components/TenantProvider.jsx +121 -121
  106. package/src/web/components/WorkflowActions/WorkflowActions.jsx +71 -71
  107. package/src/web/components/WorkflowActions/index.js +1 -1
  108. package/src/web/components/WorkflowField/WorkflowField.jsx +176 -176
  109. package/src/web/components/WorkflowField/index.js +2 -2
  110. package/src/web/components/WorkflowField/workflowColors.js +32 -32
  111. package/src/web/components/auth/DevTenantSelector.jsx +90 -90
  112. package/src/web/components/auth/ForgotPasswordForm.jsx +94 -94
  113. package/src/web/components/auth/RegisterForm.jsx +168 -168
  114. package/src/web/components/auth/ResetPasswordForm.jsx +121 -121
  115. package/src/web/components/auth/VerifyEmailView.jsx +85 -85
  116. package/src/web/components/auth/index.js +5 -5
  117. package/src/web/components/index.js +39 -39
  118. package/src/web/components/layouts/CardListLayout.jsx +68 -68
  119. package/src/web/components/layouts/FullscreenLayout.jsx +30 -30
  120. package/src/web/components/layouts/MobileStackLayout.jsx +28 -28
  121. package/src/web/components/layouts/WizardLayout.jsx +86 -86
  122. package/src/web/components/layouts/index.js +4 -4
  123. package/src/web/components/mobile/Badge.jsx +105 -105
  124. package/src/web/components/mobile/BadgeThemeEditor.jsx +104 -104
  125. package/src/web/components/mobile/EmptyState.jsx +30 -30
  126. package/src/web/components/mobile/QuickActionButton.jsx +77 -77
  127. package/src/web/components/mobile/ServerAutocomplete.jsx +123 -123
  128. package/src/web/components/mobile/StarRating.jsx +42 -42
  129. package/src/web/components/mobile/StatCard.jsx +65 -65
  130. package/src/web/components/mobile/index.js +7 -7
  131. package/src/web/extensions/ExtensionRegistry.js +79 -79
  132. package/src/web/extensions/index.js +7 -7
  133. package/src/web/hooks/index.js +15 -15
  134. package/src/web/hooks/useApi.js +76 -76
  135. package/src/web/hooks/useAuth.js +37 -37
  136. package/src/web/hooks/useDebouncedSave.js +158 -158
  137. package/src/web/hooks/useIsMobile.js +14 -14
  138. package/src/web/hooks/useOfflineQueue.js +99 -99
  139. package/src/web/hooks/useSelectionModel.js +143 -143
  140. package/src/web/hooks/useServerAutocomplete.js +146 -146
  141. package/src/web/hooks/useStore.js +107 -107
  142. package/src/web/hooks/useSubscription.js +130 -130
  143. package/src/web/hooks/useTenant.js +39 -39
  144. package/src/web/hooks/useTenantResolver.js +65 -65
  145. package/src/web/hooks/useUndoRedo.js +77 -77
  146. package/src/web/hooks/useViews.js +113 -113
  147. package/src/web/hooks/useWorkflow.js +190 -190
  148. package/src/web/index.js +117 -117
  149. package/src/web/stores/BaseStore.js +439 -439
  150. package/src/web/stores/StoreContext.jsx +93 -93
  151. package/src/web/stores/index.js +3 -3
  152. package/src/web/theme/index.js +3 -3
  153. package/src/web/theme/mui-theme.js +228 -228
  154. package/src/web/utils/formatTimeAgo.js +22 -22
  155. package/src/web/utils/index.js +1 -1
  156. package/src/web/views/ViewRegistry.js +235 -235
  157. package/src/web/views/index.js +2 -2
@@ -1,1045 +1,1045 @@
1
- /**
2
- * ViewComponent
3
- *
4
- * Renders Grid/Form/Detail based on component type configuration.
5
- * Handles listenTo bindings, showWhen visibility, and event dispatching.
6
- */
7
- import React, { useMemo, useCallback } from 'react';
8
- import { useNavigate } from 'react-router-dom';
9
- import { Box, Typography, Paper, Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material';
10
- import { useJsonView } from './JsonView.jsx';
11
- import { Grid } from '../Grid/index.js';
12
- import { Form } from '../Form/index.js';
13
- import { DetailView } from '../DetailView/index.js';
14
- import { SimpleList } from '../SimpleList/index.js';
15
- import { CardList } from '../CardList/index.js';
16
- import { InfiniteScroll } from '../Pagination/index.js';
17
- import { SplitLayout, TabLayout, SingleLayout } from './layouts/index.js';
18
- import { WorkflowActions } from '../WorkflowActions/index.js';
19
- import { useWorkflow } from '../../hooks/useWorkflow.js';
20
- import { useAuth } from '../../hooks/useAuth.js';
21
- import { useTenant } from '../../hooks/useTenant.js';
22
-
23
- /**
24
- * Hook to get API headers with auth and tenant info
25
- */
26
- function useApiHeaders() {
27
- const { token } = useAuth();
28
- const { tenant } = useTenant();
29
-
30
- return useMemo(() => {
31
- const headers = { 'Content-Type': 'application/json' };
32
- if (token) headers.Authorization = `Bearer ${token}`;
33
- if (tenant?.id) headers['X-Tenant-ID'] = tenant.id;
34
- return headers;
35
- }, [token, tenant?.id]);
36
- }
37
-
38
- /**
39
- * Resolve listenTo binding to actual data
40
- *
41
- * @param {Object} listenTo - Binding configuration { "componentId.property": "targetProp" }
42
- * @param {Object} viewState - Current view state
43
- * @returns {Object} Resolved data object
44
- */
45
- function resolveListenTo(listenTo, viewState) {
46
- if (!listenTo) return {};
47
-
48
- const resolved = {};
49
-
50
- Object.entries(listenTo).forEach(([binding, targetProp]) => {
51
- const [componentId, property] = binding.split('.');
52
-
53
- let value = null;
54
- switch (property) {
55
- case 'selection':
56
- value = viewState.selections[componentId];
57
- break;
58
- case 'editItem':
59
- value = viewState.editItems[componentId];
60
- break;
61
- default:
62
- value = viewState.componentStates[componentId]?.[property];
63
- }
64
-
65
- resolved[targetProp] = value;
66
- });
67
-
68
- return resolved;
69
- }
70
-
71
- /**
72
- * Evaluate showWhen condition
73
- *
74
- * @param {string} showWhen - Condition string like "componentId.selection"
75
- * @param {Object} viewState - Current view state
76
- * @returns {boolean} Whether component should be visible
77
- */
78
- function evaluateShowWhen(showWhen, viewState) {
79
- if (!showWhen) return true;
80
-
81
- const [componentId, property] = showWhen.split('.');
82
-
83
- switch (property) {
84
- case 'selection':
85
- return !!viewState.selections[componentId];
86
- case 'editItem':
87
- return !!viewState.editItems[componentId];
88
- default:
89
- return !!viewState.componentStates[componentId]?.[property];
90
- }
91
- }
92
-
93
- /**
94
- * CardListComponent - Renders a CardList with JSON view bindings.
95
- * Shares the same action/selection logic as GridComponent.
96
- */
97
- function CardListComponent({ componentConfig, boundData }) {
98
- const {
99
- items,
100
- loading,
101
- storeActions,
102
- setSelection,
103
- setEditItem,
104
- openDialog,
105
- viewState,
106
- executeCustomAction,
107
- } = useJsonView();
108
-
109
- const { id, config, onAction } = componentConfig;
110
- const navigate = useNavigate();
111
-
112
- const handleRowClick = useCallback((rowId, row) => {
113
- setSelection(id, row);
114
- storeActions.select?.(row);
115
-
116
- // Navigate if configured
117
- const navTemplate = componentConfig.onRowClick?.navigate;
118
- if (navTemplate) {
119
- const path = navTemplate.replace(':id', rowId);
120
- navigate(path);
121
- }
122
- }, [id, setSelection, storeActions, componentConfig.onRowClick, navigate]);
123
-
124
- const handleAction = useCallback((actionId, row) => {
125
- const actionConfig = onAction?.[actionId];
126
-
127
- switch (actionId) {
128
- case 'edit':
129
- setEditItem(id, row);
130
- if (actionConfig?.open) openDialog(actionConfig.open, row);
131
- break;
132
- case 'delete':
133
- if (actionConfig?.confirm) {
134
- openDialog(`${id}_deleteConfirm`, row);
135
- } else if (actionConfig?.action === 'delete') {
136
- storeActions.delete?.(row.id);
137
- }
138
- break;
139
- case 'view':
140
- setSelection(id, row);
141
- break;
142
- default:
143
- if (actionConfig?.handler || actionConfig?.serverAction) {
144
- executeCustomAction(actionConfig, row);
145
- } else if (actionConfig?.open) {
146
- openDialog(actionConfig.open, row);
147
- }
148
- }
149
- }, [id, onAction, setEditItem, openDialog, storeActions, setSelection, executeCustomAction]);
150
-
151
- const selectedId = viewState.selections[id]?.id;
152
-
153
- return (
154
- <Box sx={{ p: 1.5 }}>
155
- <CardList
156
- config={config}
157
- data={items}
158
- loading={loading}
159
- selectedId={selectedId}
160
- onRowClick={handleRowClick}
161
- onAction={handleAction}
162
- />
163
- </Box>
164
- );
165
- }
166
-
167
- /**
168
- * GridComponent - Renders a Grid with JSON view bindings
169
- */
170
- function GridComponent({ componentConfig, boundData }) {
171
- const {
172
- items,
173
- loading,
174
- storeActions,
175
- setSelection,
176
- setEditItem,
177
- openDialog,
178
- viewState,
179
- pagination,
180
- paginationConfig,
181
- onLoadMore,
182
- executeCustomAction,
183
- config: viewConfig
184
- } = useJsonView();
185
-
186
- const { id, config, onAction } = componentConfig;
187
- const isInfiniteScroll = paginationConfig?.mode === 'infinite';
188
-
189
- // Handle row click
190
- const handleRowClick = useCallback((rowId, row) => {
191
- setSelection(id, row);
192
- // Also update store selection if available
193
- storeActions.select?.(row);
194
- }, [id, setSelection, storeActions]);
195
-
196
- // Handle grid actions (edit, delete, view)
197
- const handleAction = useCallback((actionId, row) => {
198
- const actionConfig = onAction?.[actionId];
199
-
200
- switch (actionId) {
201
- case 'edit':
202
- setEditItem(id, row);
203
- if (actionConfig?.open) {
204
- openDialog(actionConfig.open, row);
205
- }
206
- break;
207
-
208
- case 'delete':
209
- if (actionConfig?.confirm) {
210
- // Open confirmation dialog
211
- openDialog(`${id}_deleteConfirm`, row);
212
- } else if (actionConfig?.action === 'delete') {
213
- storeActions.delete?.(row.id);
214
- }
215
- break;
216
-
217
- case 'view':
218
- setSelection(id, row);
219
- break;
220
-
221
- default:
222
- // Check for custom handler or server action
223
- if (actionConfig?.handler || actionConfig?.serverAction) {
224
- executeCustomAction(actionConfig, row);
225
- } else if (actionConfig?.open) {
226
- openDialog(actionConfig.open, row);
227
- }
228
- }
229
- }, [id, onAction, setEditItem, openDialog, storeActions, setSelection, executeCustomAction]);
230
-
231
- // Get selected row ID
232
- const selectedId = viewState.selections[id]?.id;
233
-
234
- // Merge config to hide internal pagination when controlled externally
235
- const gridConfig = useMemo(() => {
236
- if (paginationConfig?.mode === 'pages' || paginationConfig?.mode === 'infinite') {
237
- return {
238
- ...config,
239
- pagination: { ...config?.pagination, enabled: false }
240
- };
241
- }
242
- return config;
243
- }, [config, paginationConfig?.mode]);
244
-
245
- // Handle workflow transition in grid: refresh the list
246
- const sliceId = viewConfig?.dataSource?.sliceId;
247
- const handleWorkflowTransition = useCallback(() => {
248
- storeActions.list?.(sliceId ? { sliceId } : undefined);
249
- }, [storeActions, sliceId]);
250
-
251
- const gridElement = (
252
- <Grid
253
- config={gridConfig}
254
- data={items}
255
- loading={loading}
256
- selectedId={selectedId}
257
- onRowClick={handleRowClick}
258
- onAction={handleAction}
259
- onWorkflowTransition={handleWorkflowTransition}
260
- />
261
- );
262
-
263
- // Wrap with InfiniteScroll for infinite mode
264
- if (isInfiniteScroll) {
265
- // containerHeight is required for infinite scroll to work properly
266
- // Default to 400px if not specified
267
- const containerHeight = paginationConfig?.containerHeight || 400;
268
-
269
- return (
270
- <InfiniteScroll
271
- hasMore={pagination?.hasNext || false}
272
- loading={loading}
273
- onLoadMore={onLoadMore}
274
- threshold={paginationConfig?.threshold || 200}
275
- height={containerHeight}
276
- >
277
- {gridElement}
278
- </InfiniteScroll>
279
- );
280
- }
281
-
282
- return gridElement;
283
- }
284
-
285
- /**
286
- * FormComponent - Renders a Form with JSON view bindings
287
- *
288
- * Supports two modes:
289
- * 1. Standard mode: Uses store actions for CRUD operations
290
- * 2. Sub-resource mode: When formData contains _parentId and _bindTo,
291
- * uses sub-resource API endpoints for hasMany relations
292
- */
293
- function FormComponent({ componentConfig, boundData, asDialog }) {
294
- const {
295
- storeActions,
296
- clearEditItem,
297
- closeDialog,
298
- dialogs,
299
- setRelatedItems,
300
- relatedItems,
301
- config: viewConfig
302
- } = useJsonView();
303
-
304
- const { id, config, listenTo, onSubmit, saveMode } = componentConfig;
305
-
306
- // Get API headers with auth/tenant
307
- const apiHeaders = useApiHeaders();
308
-
309
- // Get sliceId from view config for refreshing with joined data
310
- const sliceId = viewConfig?.dataSource?.sliceId;
311
- const parentEntityLower = viewConfig?.dataSource?.entityName?.toLowerCase();
312
-
313
- // Get data from boundData or dialog
314
- const dialogState = dialogs[id];
315
- const formData = boundData?.data || dialogState?.data || null;
316
- const isOpen = asDialog ? (dialogState?.open || false) : true;
317
-
318
- // Check if this is a sub-resource form (for hasMany relations)
319
- const isSubResource = formData?._parentId && formData?._bindTo;
320
- const parentId = formData?._parentId;
321
- const bindTo = formData?._bindTo;
322
- const isNew = formData?._isNew;
323
-
324
- // Handle form submit
325
- const handleSubmit = useCallback(async (data, editId) => {
326
- try {
327
- // Sub-resource mode: use sub-resource API
328
- if (isSubResource && saveMode !== 'saveWithParent') {
329
- const apiBase = `/api/${parentEntityLower}s/${parentId}/${bindTo}`;
330
-
331
- // Remove internal fields from data
332
- const cleanData = { ...data };
333
- delete cleanData._parentId;
334
- delete cleanData._bindTo;
335
- delete cleanData._isNew;
336
-
337
- if (editId && !isNew) {
338
- // Update existing child
339
- const response = await fetch(`${apiBase}/${editId}`, {
340
- method: 'PUT',
341
- headers: apiHeaders,
342
- body: JSON.stringify(cleanData)
343
- });
344
- if (!response.ok) {
345
- throw new Error('Failed to update');
346
- }
347
- } else {
348
- // Create new child
349
- const response = await fetch(apiBase, {
350
- method: 'POST',
351
- headers: apiHeaders,
352
- body: JSON.stringify(cleanData)
353
- });
354
- if (!response.ok) {
355
- throw new Error('Failed to create');
356
- }
357
- }
358
-
359
- // Trigger a refresh of the SimpleList
360
- window.dispatchEvent(new CustomEvent('simpleListRefresh', { detail: { bindTo, parentId } }));
361
- } else {
362
- // Standard mode: use store actions
363
- if (editId) {
364
- await storeActions.update?.(editId, data);
365
- } else {
366
- await storeActions.create?.(data);
367
- }
368
-
369
- // Refresh list after successful save (include sliceId for joined data)
370
- storeActions.list?.(sliceId ? { sliceId } : undefined);
371
- }
372
-
373
- // Close form/dialog if configured
374
- if (onSubmit?.closeOnSuccess !== false) {
375
- clearEditItem(id);
376
- closeDialog(id);
377
- }
378
- } catch (err) {
379
- // Error handling is done by Form component
380
- throw err;
381
- }
382
- }, [id, storeActions, clearEditItem, closeDialog, onSubmit, sliceId, isSubResource, saveMode, parentEntityLower, parentId, bindTo, isNew, apiHeaders]);
383
-
384
- // Handle close
385
- const handleClose = useCallback(() => {
386
- clearEditItem(id);
387
- closeDialog(id);
388
- }, [id, clearEditItem, closeDialog]);
389
-
390
- // If used as dialog component, the Form component handles dialog rendering
391
- const formConfig = {
392
- ...config,
393
- layout: asDialog ? { mode: 'dialog', ...(config?.layout || {}) } : config?.layout
394
- };
395
-
396
- // Clean the form data to not show internal fields
397
- const cleanFormData = formData ? {
398
- ...formData,
399
- // Keep id for editing but remove internal tracking fields from display
400
- } : null;
401
- // If it's a new sub-resource item, don't pass the _isNew flag as id
402
- if (cleanFormData && cleanFormData._isNew) {
403
- delete cleanFormData.id;
404
- }
405
-
406
- return (
407
- <Form
408
- config={formConfig}
409
- data={cleanFormData}
410
- open={isOpen}
411
- onClose={handleClose}
412
- onSubmit={handleSubmit}
413
- />
414
- );
415
- }
416
-
417
- /**
418
- * DetailComponent - Renders a DetailView with JSON view bindings
419
- */
420
- function DetailComponent({ componentConfig, boundData }) {
421
- const {
422
- storeActions,
423
- setEditItem,
424
- openDialog,
425
- config: viewConfig
426
- } = useJsonView();
427
-
428
- const { id, config, onAction, placeholder } = componentConfig;
429
-
430
- // Get data from boundData
431
- const detailData = boundData?.data || null;
432
-
433
- // Handle detail actions
434
- const handleAction = useCallback((actionId, data) => {
435
- const actionConfig = onAction?.[actionId];
436
-
437
- switch (actionId) {
438
- case 'edit':
439
- setEditItem(id, data);
440
- if (actionConfig?.open) {
441
- openDialog(actionConfig.open, data);
442
- }
443
- break;
444
-
445
- case 'delete':
446
- if (actionConfig?.confirm) {
447
- openDialog(`${id}_deleteConfirm`, data);
448
- } else {
449
- storeActions.delete?.(data.id);
450
- }
451
- break;
452
-
453
- default:
454
- if (actionConfig?.open) {
455
- openDialog(actionConfig.open, data);
456
- }
457
- }
458
- }, [id, onAction, setEditItem, openDialog, storeActions]);
459
-
460
- // Show placeholder if no data
461
- if (!detailData && placeholder) {
462
- return (
463
- <Box
464
- sx={{
465
- display: 'flex',
466
- alignItems: 'center',
467
- justifyContent: 'center',
468
- height: '100%',
469
- minHeight: 200,
470
- color: 'text.secondary'
471
- }}
472
- >
473
- <Typography>{placeholder.message || 'No item selected'}</Typography>
474
- </Box>
475
- );
476
- }
477
-
478
- // Handle workflow transition in detail: refresh the list
479
- const sliceId = viewConfig?.dataSource?.sliceId;
480
- const handleWorkflowTransition = useCallback(() => {
481
- storeActions.list?.(sliceId ? { sliceId } : undefined);
482
- }, [storeActions, sliceId]);
483
-
484
- // Use panel mode for inline detail views
485
- const detailConfig = {
486
- ...config,
487
- layout: { mode: 'panel', ...(config?.layout || {}) }
488
- };
489
-
490
- return (
491
- <DetailView
492
- config={detailConfig}
493
- data={detailData}
494
- open={true}
495
- onAction={handleAction}
496
- onWorkflowTransition={handleWorkflowTransition}
497
- />
498
- );
499
- }
500
-
501
- /**
502
- * SimpleListComponent - Renders a SimpleList with JSON view bindings
503
- *
504
- * Handles hasMany relationships by fetching related items via sub-resource API.
505
- * Supports bindTo property to determine which parent field to use.
506
- */
507
- function SimpleListComponent({ componentConfig, boundData }) {
508
- const {
509
- viewState,
510
- relatedItems,
511
- relatedLoading,
512
- setRelatedItems,
513
- setRelatedLoading,
514
- setEditItem,
515
- openDialog,
516
- config: viewConfig
517
- } = useJsonView();
518
-
519
- const { id, config, bindTo, onAction } = componentConfig;
520
-
521
- // Get API headers with auth/tenant
522
- const apiHeaders = useApiHeaders();
523
-
524
- // Get parent entity info from view config
525
- const parentEntityName = viewConfig?.dataSource?.entityName;
526
- const parentEntityLower = parentEntityName?.toLowerCase();
527
-
528
- // Get parent selection (bound data typically comes from a parent grid's selection)
529
- const parentData = boundData?.data;
530
- const parentId = parentData?.id;
531
-
532
- // Get current related items state
533
- const relatedState = relatedItems[id] || { items: [], parentId: null };
534
- const loading = relatedLoading[id] || false;
535
-
536
- // Fetch related items when parent changes
537
- React.useEffect(() => {
538
- if (!parentId || !bindTo) {
539
- // Clear items if no parent selected
540
- if (relatedState.items.length > 0 || relatedState.parentId) {
541
- setRelatedItems(id, [], null, null);
542
- }
543
- return;
544
- }
545
-
546
- // Skip if already loaded for this parent
547
- if (relatedState.parentId === parentId) {
548
- return;
549
- }
550
-
551
- // Build sub-resource URL: /api/{parentEntity}s/{parentId}/{bindTo}
552
- const apiUrl = `/api/${parentEntityLower}s/${parentId}/${bindTo}`;
553
-
554
- const fetchRelatedItems = async () => {
555
- setRelatedLoading(id, true);
556
- try {
557
- const response = await fetch(apiUrl, { headers: apiHeaders });
558
- if (!response.ok) {
559
- throw new Error(`Failed to fetch ${bindTo}`);
560
- }
561
- const result = await response.json();
562
- // API returns { data: [], pagination: {} }
563
- const items = result.data || result;
564
- setRelatedItems(id, items, parentId, result.pagination);
565
- } catch (err) {
566
- console.error(`[SimpleList] Error fetching ${bindTo}:`, err);
567
- setRelatedItems(id, [], parentId, null);
568
- }
569
- };
570
-
571
- fetchRelatedItems();
572
- }, [parentId, bindTo, id, parentEntityLower, relatedState.parentId, setRelatedItems, setRelatedLoading, apiHeaders]);
573
-
574
- // Refresh function for after mutations
575
- const refreshItems = React.useCallback(async () => {
576
- if (!parentId || !bindTo) return;
577
-
578
- const apiUrl = `/api/${parentEntityLower}s/${parentId}/${bindTo}`;
579
- setRelatedLoading(id, true);
580
- try {
581
- const response = await fetch(apiUrl, { headers: apiHeaders });
582
- const result = await response.json();
583
- const items = result.data || result;
584
- setRelatedItems(id, items, parentId, result.pagination);
585
- } catch (err) {
586
- console.error(`[SimpleList] Error refreshing ${bindTo}:`, err);
587
- }
588
- }, [parentId, bindTo, id, parentEntityLower, setRelatedItems, setRelatedLoading, apiHeaders]);
589
-
590
- // Listen for refresh events (triggered after form submissions)
591
- React.useEffect(() => {
592
- const handleRefresh = (event) => {
593
- const { bindTo: eventBindTo, parentId: eventParentId, componentId } = event.detail || {};
594
- // Refresh if this event is for us
595
- if ((eventBindTo === bindTo && eventParentId === parentId) || componentId === id) {
596
- refreshItems();
597
- }
598
- };
599
-
600
- window.addEventListener('simpleListRefresh', handleRefresh);
601
- return () => window.removeEventListener('simpleListRefresh', handleRefresh);
602
- }, [bindTo, parentId, id, refreshItems]);
603
-
604
- // Handle item click
605
- const handleItemClick = React.useCallback((item) => {
606
- // Could be used to show detail or trigger selection
607
- }, []);
608
-
609
- // Handle actions (edit, delete)
610
- const handleAction = React.useCallback(async (actionId, item) => {
611
- const actionConfig = onAction?.[actionId];
612
-
613
- switch (actionId) {
614
- case 'edit':
615
- setEditItem(id, item);
616
- if (actionConfig?.open) {
617
- openDialog(actionConfig.open, { ...item, _parentId: parentId, _bindTo: bindTo });
618
- }
619
- break;
620
-
621
- case 'delete':
622
- if (actionConfig?.confirm) {
623
- openDialog(`${id}_deleteConfirm`, { ...item, _parentId: parentId, _bindTo: bindTo });
624
- } else {
625
- // Direct delete via sub-resource API
626
- const deleteUrl = `/api/${parentEntityLower}s/${parentId}/${bindTo}/${item.id}`;
627
- try {
628
- const response = await fetch(deleteUrl, { method: 'DELETE', headers: apiHeaders });
629
- if (response.ok) {
630
- refreshItems();
631
- }
632
- } catch (err) {
633
- console.error(`[SimpleList] Delete error:`, err);
634
- }
635
- }
636
- break;
637
-
638
- default:
639
- if (actionConfig?.open) {
640
- openDialog(actionConfig.open, { ...item, _parentId: parentId, _bindTo: bindTo });
641
- }
642
- }
643
- }, [id, onAction, setEditItem, openDialog, parentId, bindTo, parentEntityLower, refreshItems, apiHeaders]);
644
-
645
- // Handle add button
646
- const handleAdd = React.useCallback(() => {
647
- const actionConfig = onAction?.add;
648
- // Open form dialog with parent context
649
- if (actionConfig?.open) {
650
- openDialog(actionConfig.open, { _parentId: parentId, _bindTo: bindTo, _isNew: true });
651
- } else {
652
- // Default: try to open a form with the component's entity name
653
- const formId = config?.entityName?.toLowerCase() + 'Form';
654
- openDialog(formId, { _parentId: parentId, _bindTo: bindTo, _isNew: true });
655
- }
656
- }, [onAction, openDialog, parentId, bindTo, config?.entityName]);
657
-
658
- // Show placeholder if no parent selected
659
- if (!parentId) {
660
- return (
661
- <Box
662
- sx={{
663
- display: 'flex',
664
- alignItems: 'center',
665
- justifyContent: 'center',
666
- height: '100%',
667
- minHeight: 100,
668
- color: 'text.secondary',
669
- bgcolor: 'grey.50',
670
- borderRadius: 1
671
- }}
672
- >
673
- <Typography variant="body2">
674
- {componentConfig.placeholder?.message || `Select a ${parentEntityName?.toLowerCase() || 'record'} to view ${config?.entityNamePlural?.toLowerCase() || 'items'}`}
675
- </Typography>
676
- </Box>
677
- );
678
- }
679
-
680
- return (
681
- <SimpleList
682
- config={config}
683
- data={relatedState.items}
684
- loading={loading}
685
- onItemClick={handleItemClick}
686
- onAction={handleAction}
687
- onAdd={handleAdd}
688
- />
689
- );
690
- }
691
-
692
- /**
693
- * SimpleListDeleteDialog - Confirmation dialog for SimpleList delete actions
694
- */
695
- function SimpleListDeleteDialog({ componentId, componentConfig }) {
696
- const { dialogs, closeDialog, config: viewConfig } = useJsonView();
697
- const apiHeaders = useApiHeaders();
698
-
699
- const dialogId = `${componentId}_deleteConfirm`;
700
- const dialogState = dialogs[dialogId];
701
- const isOpen = dialogState?.open || false;
702
- const itemToDelete = dialogState?.data;
703
-
704
- const parentEntityLower = viewConfig?.dataSource?.entityName?.toLowerCase();
705
- const entityName = componentConfig?.config?.entityName || 'item';
706
-
707
- const handleConfirm = React.useCallback(async () => {
708
- if (!itemToDelete?.id || !itemToDelete?._parentId || !itemToDelete?._bindTo) {
709
- closeDialog(dialogId);
710
- return;
711
- }
712
-
713
- const deleteUrl = `/api/${parentEntityLower}s/${itemToDelete._parentId}/${itemToDelete._bindTo}/${itemToDelete.id}`;
714
- try {
715
- const response = await fetch(deleteUrl, { method: 'DELETE', headers: apiHeaders });
716
- if (response.ok) {
717
- // The SimpleListComponent will refresh on next render when dialog closes
718
- // We need to trigger a refresh - this is handled by the component's useEffect
719
- window.dispatchEvent(new CustomEvent('simpleListRefresh', { detail: { componentId } }));
720
- }
721
- } catch (err) {
722
- console.error(`[SimpleList] Delete error:`, err);
723
- }
724
- closeDialog(dialogId);
725
- }, [itemToDelete, parentEntityLower, closeDialog, dialogId, componentId, apiHeaders]);
726
-
727
- const handleCancel = React.useCallback(() => {
728
- closeDialog(dialogId);
729
- }, [closeDialog, dialogId]);
730
-
731
- return (
732
- <Dialog open={isOpen} onClose={handleCancel}>
733
- <DialogTitle>Confirm Delete</DialogTitle>
734
- <DialogContent>
735
- <Typography>
736
- Are you sure you want to delete this {entityName.toLowerCase()}?
737
- </Typography>
738
- </DialogContent>
739
- <DialogActions>
740
- <Button onClick={handleCancel}>Cancel</Button>
741
- <Button onClick={handleConfirm} color="error" variant="contained">
742
- Delete
743
- </Button>
744
- </DialogActions>
745
- </Dialog>
746
- );
747
- }
748
-
749
- /**
750
- * WorkflowComponent - Renders WorkflowActions with JSON view bindings
751
- */
752
- function WorkflowComponent({ componentConfig, boundData }) {
753
- const { storeActions, config: viewConfig } = useJsonView();
754
-
755
- const workflowInstanceField = componentConfig.config?.workflowInstanceField || 'workflow_instance_id';
756
- const instanceId = boundData?.data?.[workflowInstanceField];
757
-
758
- const sliceId = viewConfig?.dataSource?.sliceId;
759
-
760
- const { transitions, workflowState, loading, error, executeTransition } = useWorkflow(instanceId);
761
-
762
- const handleTransition = useCallback(async (ruleId) => {
763
- try {
764
- await executeTransition(ruleId);
765
- // Refresh the grid after successful transition
766
- storeActions.list?.(sliceId ? { sliceId } : undefined);
767
- } catch (err) {
768
- // Error is already set in useWorkflow state
769
- }
770
- }, [executeTransition, storeActions, sliceId]);
771
-
772
- return (
773
- <WorkflowActions
774
- workflowState={workflowState}
775
- transitions={transitions}
776
- loading={loading}
777
- error={error}
778
- onTransition={handleTransition}
779
- />
780
- );
781
- }
782
-
783
- /**
784
- * DeleteConfirmDialog - Confirmation dialog for delete actions
785
- */
786
- function DeleteConfirmDialog({ componentId, entityName = 'item' }) {
787
- const { dialogs, closeDialog, storeActions, config: viewConfig } = useJsonView();
788
-
789
- const dialogId = `${componentId}_deleteConfirm`;
790
- const dialogState = dialogs[dialogId];
791
- const isOpen = dialogState?.open || false;
792
- const itemToDelete = dialogState?.data;
793
- const sliceId = viewConfig?.dataSource?.sliceId;
794
-
795
- const handleConfirm = useCallback(async () => {
796
- if (itemToDelete?.id) {
797
- await storeActions.delete?.(itemToDelete.id);
798
- storeActions.list?.(sliceId ? { sliceId } : undefined);
799
- }
800
- closeDialog(dialogId);
801
- }, [itemToDelete, storeActions, closeDialog, dialogId, sliceId]);
802
-
803
- const handleCancel = useCallback(() => {
804
- closeDialog(dialogId);
805
- }, [closeDialog, dialogId]);
806
-
807
- return (
808
- <Dialog open={isOpen} onClose={handleCancel}>
809
- <DialogTitle>Confirm Delete</DialogTitle>
810
- <DialogContent>
811
- <Typography>
812
- Are you sure you want to delete this {entityName}?
813
- {itemToDelete?.title && ` "${itemToDelete.title}"`}
814
- </Typography>
815
- </DialogContent>
816
- <DialogActions>
817
- <Button onClick={handleCancel}>Cancel</Button>
818
- <Button onClick={handleConfirm} color="error" variant="contained">
819
- Delete
820
- </Button>
821
- </DialogActions>
822
- </Dialog>
823
- );
824
- }
825
-
826
- /**
827
- * ViewComponent
828
- *
829
- * Renders the appropriate component based on type configuration.
830
- *
831
- * @param {Object} componentConfig - Component configuration
832
- * @param {string} componentConfig.id - Component ID
833
- * @param {string} componentConfig.type - Component type: grid | form | detail | custom
834
- * @param {Object} componentConfig.config - Type-specific configuration
835
- * @param {Object} componentConfig.listenTo - Reactive bindings
836
- * @param {string} componentConfig.showWhen - Visibility condition
837
- * @param {Object} componentConfig.placeholder - Placeholder when hidden/empty
838
- * @param {Object} componentConfig.onAction - Action handlers
839
- * @param {string} componentConfig.component - For custom type: name of extension component
840
- */
841
- export function ViewComponent({ componentConfig }) {
842
- const { viewState, config: viewConfig, extensionComponents, dialogs, closeDialog } = useJsonView();
843
-
844
- const { id, type, listenTo, showWhen, minBreakpoint, maxBreakpoint } = componentConfig;
845
-
846
- // Resolve bindings
847
- const boundData = useMemo(
848
- () => resolveListenTo(listenTo, viewState),
849
- [listenTo, viewState]
850
- );
851
-
852
- // Evaluate visibility
853
- const isVisible = useMemo(
854
- () => evaluateShowWhen(showWhen, viewState),
855
- [showWhen, viewState]
856
- );
857
-
858
- // Get entity name for delete dialog
859
- const entityName = componentConfig.config?.entityName ||
860
- viewConfig?.dataSource?.entityName ||
861
- 'item';
862
-
863
- // Render based on type
864
- let content;
865
- switch (type) {
866
- case 'grid':
867
- content = <GridComponent componentConfig={componentConfig} boundData={boundData} />;
868
- break;
869
-
870
- case 'cardList':
871
- content = <CardListComponent componentConfig={componentConfig} boundData={boundData} />;
872
- break;
873
-
874
- case 'form':
875
- // Forms are typically rendered as dialogs
876
- content = <FormComponent componentConfig={componentConfig} boundData={boundData} asDialog />;
877
- break;
878
-
879
- case 'detail':
880
- if (!isVisible) {
881
- // Show placeholder when not visible
882
- if (componentConfig.placeholder) {
883
- content = (
884
- <Box
885
- sx={{
886
- display: 'flex',
887
- alignItems: 'center',
888
- justifyContent: 'center',
889
- height: '100%',
890
- minHeight: 200,
891
- color: 'text.secondary',
892
- bgcolor: 'grey.50',
893
- borderRadius: 1
894
- }}
895
- >
896
- <Typography>{componentConfig.placeholder.message}</Typography>
897
- </Box>
898
- );
899
- } else {
900
- content = null;
901
- }
902
- } else {
903
- content = <DetailComponent componentConfig={componentConfig} boundData={boundData} />;
904
- }
905
- break;
906
-
907
- case 'workflow':
908
- if (!isVisible) {
909
- if (componentConfig.placeholder) {
910
- content = (
911
- <Box
912
- sx={{
913
- display: 'flex',
914
- alignItems: 'center',
915
- justifyContent: 'center',
916
- height: '100%',
917
- minHeight: 200,
918
- color: 'text.secondary',
919
- bgcolor: 'grey.50',
920
- borderRadius: 1
921
- }}
922
- >
923
- <Typography>{componentConfig.placeholder.message}</Typography>
924
- </Box>
925
- );
926
- } else {
927
- content = null;
928
- }
929
- } else {
930
- content = <WorkflowComponent componentConfig={componentConfig} boundData={boundData} />;
931
- }
932
- break;
933
-
934
- case 'simpleList':
935
- content = <SimpleListComponent componentConfig={componentConfig} boundData={boundData} />;
936
- break;
937
-
938
- case 'view':
939
- // Nested view - render with appropriate layout
940
- if (!isVisible) {
941
- if (componentConfig.placeholder) {
942
- content = (
943
- <Box
944
- sx={{
945
- display: 'flex',
946
- alignItems: 'center',
947
- justifyContent: 'center',
948
- height: '100%',
949
- minHeight: 200,
950
- color: 'text.secondary',
951
- bgcolor: 'grey.50',
952
- borderRadius: 1
953
- }}
954
- >
955
- <Typography>{componentConfig.placeholder.message}</Typography>
956
- </Box>
957
- );
958
- } else {
959
- content = null;
960
- }
961
- } else {
962
- const NestedLayout = componentConfig.layout === 'tabs' ? TabLayout
963
- : componentConfig.layout === 'split' ? SplitLayout
964
- : SingleLayout;
965
- content = (
966
- <NestedLayout
967
- config={componentConfig.layoutConfig}
968
- components={componentConfig.components || []}
969
- />
970
- );
971
- }
972
- break;
973
-
974
- case 'custom':
975
- // Render custom component from extension
976
- const CustomComponent = extensionComponents?.[componentConfig.component];
977
- if (CustomComponent) {
978
- // Check if this is a dialog-based component
979
- const dialogState = dialogs[id];
980
- const isDialogOpen = dialogState?.open || false;
981
- const dialogData = dialogState?.data || boundData?.data;
982
-
983
- content = (
984
- <CustomComponent
985
- id={id}
986
- config={componentConfig.config}
987
- data={dialogData}
988
- boundData={boundData}
989
- open={isDialogOpen}
990
- onClose={() => closeDialog(id)}
991
- />
992
- );
993
- } else {
994
- content = (
995
- <Box sx={{ p: 2 }}>
996
- <Typography color="error">
997
- Custom component not found: {componentConfig.component}
998
- </Typography>
999
- </Box>
1000
- );
1001
- }
1002
- break;
1003
-
1004
- default:
1005
- content = (
1006
- <Box sx={{ p: 2 }}>
1007
- <Typography color="error">Unknown component type: {type}</Typography>
1008
- </Box>
1009
- );
1010
- }
1011
-
1012
- // Build responsive display sx if breakpoint visibility is configured.
1013
- // minBreakpoint: show only at this breakpoint and above (e.g. 'md' → hide on xs/sm)
1014
- // maxBreakpoint: show only at this breakpoint and below (e.g. 'sm' → hide on md+)
1015
- let displaySx;
1016
- if (minBreakpoint) {
1017
- displaySx = { display: { xs: 'none', [minBreakpoint]: 'block' } };
1018
- } else if (maxBreakpoint) {
1019
- const nextBp = { xs: 'sm', sm: 'md', md: 'lg', lg: 'xl' }[maxBreakpoint];
1020
- displaySx = nextBp
1021
- ? { display: { xs: 'block', [nextBp]: 'none' } }
1022
- : { display: 'block' };
1023
- }
1024
-
1025
- // Wrap in a Box with responsive display if needed, otherwise render directly
1026
- const wrapped = displaySx ? (
1027
- <Box sx={displaySx}>
1028
- {content}
1029
- </Box>
1030
- ) : content;
1031
-
1032
- return (
1033
- <>
1034
- {wrapped}
1035
- {/* Delete confirmation dialog for this component */}
1036
- <DeleteConfirmDialog componentId={id} entityName={entityName} />
1037
- {/* Delete confirmation dialog for SimpleList */}
1038
- {type === 'simpleList' && (
1039
- <SimpleListDeleteDialog componentId={id} componentConfig={componentConfig} />
1040
- )}
1041
- </>
1042
- );
1043
- }
1044
-
1045
- export default ViewComponent;
1
+ /**
2
+ * ViewComponent
3
+ *
4
+ * Renders Grid/Form/Detail based on component type configuration.
5
+ * Handles listenTo bindings, showWhen visibility, and event dispatching.
6
+ */
7
+ import React, { useMemo, useCallback } from 'react';
8
+ import { useNavigate } from 'react-router-dom';
9
+ import { Box, Typography, Paper, Dialog, DialogTitle, DialogContent, DialogActions, Button } from '@mui/material';
10
+ import { useJsonView } from './JsonView.jsx';
11
+ import { Grid } from '../Grid/index.js';
12
+ import { Form } from '../Form/index.js';
13
+ import { DetailView } from '../DetailView/index.js';
14
+ import { SimpleList } from '../SimpleList/index.js';
15
+ import { CardList } from '../CardList/index.js';
16
+ import { InfiniteScroll } from '../Pagination/index.js';
17
+ import { SplitLayout, TabLayout, SingleLayout } from './layouts/index.js';
18
+ import { WorkflowActions } from '../WorkflowActions/index.js';
19
+ import { useWorkflow } from '../../hooks/useWorkflow.js';
20
+ import { useAuth } from '../../hooks/useAuth.js';
21
+ import { useTenant } from '../../hooks/useTenant.js';
22
+
23
+ /**
24
+ * Hook to get API headers with auth and tenant info
25
+ */
26
+ function useApiHeaders() {
27
+ const { token } = useAuth();
28
+ const { tenant } = useTenant();
29
+
30
+ return useMemo(() => {
31
+ const headers = { 'Content-Type': 'application/json' };
32
+ if (token) headers.Authorization = `Bearer ${token}`;
33
+ if (tenant?.id) headers['X-Tenant-ID'] = tenant.id;
34
+ return headers;
35
+ }, [token, tenant?.id]);
36
+ }
37
+
38
+ /**
39
+ * Resolve listenTo binding to actual data
40
+ *
41
+ * @param {Object} listenTo - Binding configuration { "componentId.property": "targetProp" }
42
+ * @param {Object} viewState - Current view state
43
+ * @returns {Object} Resolved data object
44
+ */
45
+ function resolveListenTo(listenTo, viewState) {
46
+ if (!listenTo) return {};
47
+
48
+ const resolved = {};
49
+
50
+ Object.entries(listenTo).forEach(([binding, targetProp]) => {
51
+ const [componentId, property] = binding.split('.');
52
+
53
+ let value = null;
54
+ switch (property) {
55
+ case 'selection':
56
+ value = viewState.selections[componentId];
57
+ break;
58
+ case 'editItem':
59
+ value = viewState.editItems[componentId];
60
+ break;
61
+ default:
62
+ value = viewState.componentStates[componentId]?.[property];
63
+ }
64
+
65
+ resolved[targetProp] = value;
66
+ });
67
+
68
+ return resolved;
69
+ }
70
+
71
+ /**
72
+ * Evaluate showWhen condition
73
+ *
74
+ * @param {string} showWhen - Condition string like "componentId.selection"
75
+ * @param {Object} viewState - Current view state
76
+ * @returns {boolean} Whether component should be visible
77
+ */
78
+ function evaluateShowWhen(showWhen, viewState) {
79
+ if (!showWhen) return true;
80
+
81
+ const [componentId, property] = showWhen.split('.');
82
+
83
+ switch (property) {
84
+ case 'selection':
85
+ return !!viewState.selections[componentId];
86
+ case 'editItem':
87
+ return !!viewState.editItems[componentId];
88
+ default:
89
+ return !!viewState.componentStates[componentId]?.[property];
90
+ }
91
+ }
92
+
93
+ /**
94
+ * CardListComponent - Renders a CardList with JSON view bindings.
95
+ * Shares the same action/selection logic as GridComponent.
96
+ */
97
+ function CardListComponent({ componentConfig, boundData }) {
98
+ const {
99
+ items,
100
+ loading,
101
+ storeActions,
102
+ setSelection,
103
+ setEditItem,
104
+ openDialog,
105
+ viewState,
106
+ executeCustomAction,
107
+ } = useJsonView();
108
+
109
+ const { id, config, onAction } = componentConfig;
110
+ const navigate = useNavigate();
111
+
112
+ const handleRowClick = useCallback((rowId, row) => {
113
+ setSelection(id, row);
114
+ storeActions.select?.(row);
115
+
116
+ // Navigate if configured
117
+ const navTemplate = componentConfig.onRowClick?.navigate;
118
+ if (navTemplate) {
119
+ const path = navTemplate.replace(':id', rowId);
120
+ navigate(path);
121
+ }
122
+ }, [id, setSelection, storeActions, componentConfig.onRowClick, navigate]);
123
+
124
+ const handleAction = useCallback((actionId, row) => {
125
+ const actionConfig = onAction?.[actionId];
126
+
127
+ switch (actionId) {
128
+ case 'edit':
129
+ setEditItem(id, row);
130
+ if (actionConfig?.open) openDialog(actionConfig.open, row);
131
+ break;
132
+ case 'delete':
133
+ if (actionConfig?.confirm) {
134
+ openDialog(`${id}_deleteConfirm`, row);
135
+ } else if (actionConfig?.action === 'delete') {
136
+ storeActions.delete?.(row.id);
137
+ }
138
+ break;
139
+ case 'view':
140
+ setSelection(id, row);
141
+ break;
142
+ default:
143
+ if (actionConfig?.handler || actionConfig?.serverAction) {
144
+ executeCustomAction(actionConfig, row);
145
+ } else if (actionConfig?.open) {
146
+ openDialog(actionConfig.open, row);
147
+ }
148
+ }
149
+ }, [id, onAction, setEditItem, openDialog, storeActions, setSelection, executeCustomAction]);
150
+
151
+ const selectedId = viewState.selections[id]?.id;
152
+
153
+ return (
154
+ <Box sx={{ p: 1.5 }}>
155
+ <CardList
156
+ config={config}
157
+ data={items}
158
+ loading={loading}
159
+ selectedId={selectedId}
160
+ onRowClick={handleRowClick}
161
+ onAction={handleAction}
162
+ />
163
+ </Box>
164
+ );
165
+ }
166
+
167
+ /**
168
+ * GridComponent - Renders a Grid with JSON view bindings
169
+ */
170
+ function GridComponent({ componentConfig, boundData }) {
171
+ const {
172
+ items,
173
+ loading,
174
+ storeActions,
175
+ setSelection,
176
+ setEditItem,
177
+ openDialog,
178
+ viewState,
179
+ pagination,
180
+ paginationConfig,
181
+ onLoadMore,
182
+ executeCustomAction,
183
+ config: viewConfig
184
+ } = useJsonView();
185
+
186
+ const { id, config, onAction } = componentConfig;
187
+ const isInfiniteScroll = paginationConfig?.mode === 'infinite';
188
+
189
+ // Handle row click
190
+ const handleRowClick = useCallback((rowId, row) => {
191
+ setSelection(id, row);
192
+ // Also update store selection if available
193
+ storeActions.select?.(row);
194
+ }, [id, setSelection, storeActions]);
195
+
196
+ // Handle grid actions (edit, delete, view)
197
+ const handleAction = useCallback((actionId, row) => {
198
+ const actionConfig = onAction?.[actionId];
199
+
200
+ switch (actionId) {
201
+ case 'edit':
202
+ setEditItem(id, row);
203
+ if (actionConfig?.open) {
204
+ openDialog(actionConfig.open, row);
205
+ }
206
+ break;
207
+
208
+ case 'delete':
209
+ if (actionConfig?.confirm) {
210
+ // Open confirmation dialog
211
+ openDialog(`${id}_deleteConfirm`, row);
212
+ } else if (actionConfig?.action === 'delete') {
213
+ storeActions.delete?.(row.id);
214
+ }
215
+ break;
216
+
217
+ case 'view':
218
+ setSelection(id, row);
219
+ break;
220
+
221
+ default:
222
+ // Check for custom handler or server action
223
+ if (actionConfig?.handler || actionConfig?.serverAction) {
224
+ executeCustomAction(actionConfig, row);
225
+ } else if (actionConfig?.open) {
226
+ openDialog(actionConfig.open, row);
227
+ }
228
+ }
229
+ }, [id, onAction, setEditItem, openDialog, storeActions, setSelection, executeCustomAction]);
230
+
231
+ // Get selected row ID
232
+ const selectedId = viewState.selections[id]?.id;
233
+
234
+ // Merge config to hide internal pagination when controlled externally
235
+ const gridConfig = useMemo(() => {
236
+ if (paginationConfig?.mode === 'pages' || paginationConfig?.mode === 'infinite') {
237
+ return {
238
+ ...config,
239
+ pagination: { ...config?.pagination, enabled: false }
240
+ };
241
+ }
242
+ return config;
243
+ }, [config, paginationConfig?.mode]);
244
+
245
+ // Handle workflow transition in grid: refresh the list
246
+ const sliceId = viewConfig?.dataSource?.sliceId;
247
+ const handleWorkflowTransition = useCallback(() => {
248
+ storeActions.list?.(sliceId ? { sliceId } : undefined);
249
+ }, [storeActions, sliceId]);
250
+
251
+ const gridElement = (
252
+ <Grid
253
+ config={gridConfig}
254
+ data={items}
255
+ loading={loading}
256
+ selectedId={selectedId}
257
+ onRowClick={handleRowClick}
258
+ onAction={handleAction}
259
+ onWorkflowTransition={handleWorkflowTransition}
260
+ />
261
+ );
262
+
263
+ // Wrap with InfiniteScroll for infinite mode
264
+ if (isInfiniteScroll) {
265
+ // containerHeight is required for infinite scroll to work properly
266
+ // Default to 400px if not specified
267
+ const containerHeight = paginationConfig?.containerHeight || 400;
268
+
269
+ return (
270
+ <InfiniteScroll
271
+ hasMore={pagination?.hasNext || false}
272
+ loading={loading}
273
+ onLoadMore={onLoadMore}
274
+ threshold={paginationConfig?.threshold || 200}
275
+ height={containerHeight}
276
+ >
277
+ {gridElement}
278
+ </InfiniteScroll>
279
+ );
280
+ }
281
+
282
+ return gridElement;
283
+ }
284
+
285
+ /**
286
+ * FormComponent - Renders a Form with JSON view bindings
287
+ *
288
+ * Supports two modes:
289
+ * 1. Standard mode: Uses store actions for CRUD operations
290
+ * 2. Sub-resource mode: When formData contains _parentId and _bindTo,
291
+ * uses sub-resource API endpoints for hasMany relations
292
+ */
293
+ function FormComponent({ componentConfig, boundData, asDialog }) {
294
+ const {
295
+ storeActions,
296
+ clearEditItem,
297
+ closeDialog,
298
+ dialogs,
299
+ setRelatedItems,
300
+ relatedItems,
301
+ config: viewConfig
302
+ } = useJsonView();
303
+
304
+ const { id, config, listenTo, onSubmit, saveMode } = componentConfig;
305
+
306
+ // Get API headers with auth/tenant
307
+ const apiHeaders = useApiHeaders();
308
+
309
+ // Get sliceId from view config for refreshing with joined data
310
+ const sliceId = viewConfig?.dataSource?.sliceId;
311
+ const parentEntityLower = viewConfig?.dataSource?.entityName?.toLowerCase();
312
+
313
+ // Get data from boundData or dialog
314
+ const dialogState = dialogs[id];
315
+ const formData = boundData?.data || dialogState?.data || null;
316
+ const isOpen = asDialog ? (dialogState?.open || false) : true;
317
+
318
+ // Check if this is a sub-resource form (for hasMany relations)
319
+ const isSubResource = formData?._parentId && formData?._bindTo;
320
+ const parentId = formData?._parentId;
321
+ const bindTo = formData?._bindTo;
322
+ const isNew = formData?._isNew;
323
+
324
+ // Handle form submit
325
+ const handleSubmit = useCallback(async (data, editId) => {
326
+ try {
327
+ // Sub-resource mode: use sub-resource API
328
+ if (isSubResource && saveMode !== 'saveWithParent') {
329
+ const apiBase = `/api/${parentEntityLower}s/${parentId}/${bindTo}`;
330
+
331
+ // Remove internal fields from data
332
+ const cleanData = { ...data };
333
+ delete cleanData._parentId;
334
+ delete cleanData._bindTo;
335
+ delete cleanData._isNew;
336
+
337
+ if (editId && !isNew) {
338
+ // Update existing child
339
+ const response = await fetch(`${apiBase}/${editId}`, {
340
+ method: 'PUT',
341
+ headers: apiHeaders,
342
+ body: JSON.stringify(cleanData)
343
+ });
344
+ if (!response.ok) {
345
+ throw new Error('Failed to update');
346
+ }
347
+ } else {
348
+ // Create new child
349
+ const response = await fetch(apiBase, {
350
+ method: 'POST',
351
+ headers: apiHeaders,
352
+ body: JSON.stringify(cleanData)
353
+ });
354
+ if (!response.ok) {
355
+ throw new Error('Failed to create');
356
+ }
357
+ }
358
+
359
+ // Trigger a refresh of the SimpleList
360
+ window.dispatchEvent(new CustomEvent('simpleListRefresh', { detail: { bindTo, parentId } }));
361
+ } else {
362
+ // Standard mode: use store actions
363
+ if (editId) {
364
+ await storeActions.update?.(editId, data);
365
+ } else {
366
+ await storeActions.create?.(data);
367
+ }
368
+
369
+ // Refresh list after successful save (include sliceId for joined data)
370
+ storeActions.list?.(sliceId ? { sliceId } : undefined);
371
+ }
372
+
373
+ // Close form/dialog if configured
374
+ if (onSubmit?.closeOnSuccess !== false) {
375
+ clearEditItem(id);
376
+ closeDialog(id);
377
+ }
378
+ } catch (err) {
379
+ // Error handling is done by Form component
380
+ throw err;
381
+ }
382
+ }, [id, storeActions, clearEditItem, closeDialog, onSubmit, sliceId, isSubResource, saveMode, parentEntityLower, parentId, bindTo, isNew, apiHeaders]);
383
+
384
+ // Handle close
385
+ const handleClose = useCallback(() => {
386
+ clearEditItem(id);
387
+ closeDialog(id);
388
+ }, [id, clearEditItem, closeDialog]);
389
+
390
+ // If used as dialog component, the Form component handles dialog rendering
391
+ const formConfig = {
392
+ ...config,
393
+ layout: asDialog ? { mode: 'dialog', ...(config?.layout || {}) } : config?.layout
394
+ };
395
+
396
+ // Clean the form data to not show internal fields
397
+ const cleanFormData = formData ? {
398
+ ...formData,
399
+ // Keep id for editing but remove internal tracking fields from display
400
+ } : null;
401
+ // If it's a new sub-resource item, don't pass the _isNew flag as id
402
+ if (cleanFormData && cleanFormData._isNew) {
403
+ delete cleanFormData.id;
404
+ }
405
+
406
+ return (
407
+ <Form
408
+ config={formConfig}
409
+ data={cleanFormData}
410
+ open={isOpen}
411
+ onClose={handleClose}
412
+ onSubmit={handleSubmit}
413
+ />
414
+ );
415
+ }
416
+
417
+ /**
418
+ * DetailComponent - Renders a DetailView with JSON view bindings
419
+ */
420
+ function DetailComponent({ componentConfig, boundData }) {
421
+ const {
422
+ storeActions,
423
+ setEditItem,
424
+ openDialog,
425
+ config: viewConfig
426
+ } = useJsonView();
427
+
428
+ const { id, config, onAction, placeholder } = componentConfig;
429
+
430
+ // Get data from boundData
431
+ const detailData = boundData?.data || null;
432
+
433
+ // Handle detail actions
434
+ const handleAction = useCallback((actionId, data) => {
435
+ const actionConfig = onAction?.[actionId];
436
+
437
+ switch (actionId) {
438
+ case 'edit':
439
+ setEditItem(id, data);
440
+ if (actionConfig?.open) {
441
+ openDialog(actionConfig.open, data);
442
+ }
443
+ break;
444
+
445
+ case 'delete':
446
+ if (actionConfig?.confirm) {
447
+ openDialog(`${id}_deleteConfirm`, data);
448
+ } else {
449
+ storeActions.delete?.(data.id);
450
+ }
451
+ break;
452
+
453
+ default:
454
+ if (actionConfig?.open) {
455
+ openDialog(actionConfig.open, data);
456
+ }
457
+ }
458
+ }, [id, onAction, setEditItem, openDialog, storeActions]);
459
+
460
+ // Show placeholder if no data
461
+ if (!detailData && placeholder) {
462
+ return (
463
+ <Box
464
+ sx={{
465
+ display: 'flex',
466
+ alignItems: 'center',
467
+ justifyContent: 'center',
468
+ height: '100%',
469
+ minHeight: 200,
470
+ color: 'text.secondary'
471
+ }}
472
+ >
473
+ <Typography>{placeholder.message || 'No item selected'}</Typography>
474
+ </Box>
475
+ );
476
+ }
477
+
478
+ // Handle workflow transition in detail: refresh the list
479
+ const sliceId = viewConfig?.dataSource?.sliceId;
480
+ const handleWorkflowTransition = useCallback(() => {
481
+ storeActions.list?.(sliceId ? { sliceId } : undefined);
482
+ }, [storeActions, sliceId]);
483
+
484
+ // Use panel mode for inline detail views
485
+ const detailConfig = {
486
+ ...config,
487
+ layout: { mode: 'panel', ...(config?.layout || {}) }
488
+ };
489
+
490
+ return (
491
+ <DetailView
492
+ config={detailConfig}
493
+ data={detailData}
494
+ open={true}
495
+ onAction={handleAction}
496
+ onWorkflowTransition={handleWorkflowTransition}
497
+ />
498
+ );
499
+ }
500
+
501
+ /**
502
+ * SimpleListComponent - Renders a SimpleList with JSON view bindings
503
+ *
504
+ * Handles hasMany relationships by fetching related items via sub-resource API.
505
+ * Supports bindTo property to determine which parent field to use.
506
+ */
507
+ function SimpleListComponent({ componentConfig, boundData }) {
508
+ const {
509
+ viewState,
510
+ relatedItems,
511
+ relatedLoading,
512
+ setRelatedItems,
513
+ setRelatedLoading,
514
+ setEditItem,
515
+ openDialog,
516
+ config: viewConfig
517
+ } = useJsonView();
518
+
519
+ const { id, config, bindTo, onAction } = componentConfig;
520
+
521
+ // Get API headers with auth/tenant
522
+ const apiHeaders = useApiHeaders();
523
+
524
+ // Get parent entity info from view config
525
+ const parentEntityName = viewConfig?.dataSource?.entityName;
526
+ const parentEntityLower = parentEntityName?.toLowerCase();
527
+
528
+ // Get parent selection (bound data typically comes from a parent grid's selection)
529
+ const parentData = boundData?.data;
530
+ const parentId = parentData?.id;
531
+
532
+ // Get current related items state
533
+ const relatedState = relatedItems[id] || { items: [], parentId: null };
534
+ const loading = relatedLoading[id] || false;
535
+
536
+ // Fetch related items when parent changes
537
+ React.useEffect(() => {
538
+ if (!parentId || !bindTo) {
539
+ // Clear items if no parent selected
540
+ if (relatedState.items.length > 0 || relatedState.parentId) {
541
+ setRelatedItems(id, [], null, null);
542
+ }
543
+ return;
544
+ }
545
+
546
+ // Skip if already loaded for this parent
547
+ if (relatedState.parentId === parentId) {
548
+ return;
549
+ }
550
+
551
+ // Build sub-resource URL: /api/{parentEntity}s/{parentId}/{bindTo}
552
+ const apiUrl = `/api/${parentEntityLower}s/${parentId}/${bindTo}`;
553
+
554
+ const fetchRelatedItems = async () => {
555
+ setRelatedLoading(id, true);
556
+ try {
557
+ const response = await fetch(apiUrl, { headers: apiHeaders });
558
+ if (!response.ok) {
559
+ throw new Error(`Failed to fetch ${bindTo}`);
560
+ }
561
+ const result = await response.json();
562
+ // API returns { data: [], pagination: {} }
563
+ const items = result.data || result;
564
+ setRelatedItems(id, items, parentId, result.pagination);
565
+ } catch (err) {
566
+ console.error(`[SimpleList] Error fetching ${bindTo}:`, err);
567
+ setRelatedItems(id, [], parentId, null);
568
+ }
569
+ };
570
+
571
+ fetchRelatedItems();
572
+ }, [parentId, bindTo, id, parentEntityLower, relatedState.parentId, setRelatedItems, setRelatedLoading, apiHeaders]);
573
+
574
+ // Refresh function for after mutations
575
+ const refreshItems = React.useCallback(async () => {
576
+ if (!parentId || !bindTo) return;
577
+
578
+ const apiUrl = `/api/${parentEntityLower}s/${parentId}/${bindTo}`;
579
+ setRelatedLoading(id, true);
580
+ try {
581
+ const response = await fetch(apiUrl, { headers: apiHeaders });
582
+ const result = await response.json();
583
+ const items = result.data || result;
584
+ setRelatedItems(id, items, parentId, result.pagination);
585
+ } catch (err) {
586
+ console.error(`[SimpleList] Error refreshing ${bindTo}:`, err);
587
+ }
588
+ }, [parentId, bindTo, id, parentEntityLower, setRelatedItems, setRelatedLoading, apiHeaders]);
589
+
590
+ // Listen for refresh events (triggered after form submissions)
591
+ React.useEffect(() => {
592
+ const handleRefresh = (event) => {
593
+ const { bindTo: eventBindTo, parentId: eventParentId, componentId } = event.detail || {};
594
+ // Refresh if this event is for us
595
+ if ((eventBindTo === bindTo && eventParentId === parentId) || componentId === id) {
596
+ refreshItems();
597
+ }
598
+ };
599
+
600
+ window.addEventListener('simpleListRefresh', handleRefresh);
601
+ return () => window.removeEventListener('simpleListRefresh', handleRefresh);
602
+ }, [bindTo, parentId, id, refreshItems]);
603
+
604
+ // Handle item click
605
+ const handleItemClick = React.useCallback((item) => {
606
+ // Could be used to show detail or trigger selection
607
+ }, []);
608
+
609
+ // Handle actions (edit, delete)
610
+ const handleAction = React.useCallback(async (actionId, item) => {
611
+ const actionConfig = onAction?.[actionId];
612
+
613
+ switch (actionId) {
614
+ case 'edit':
615
+ setEditItem(id, item);
616
+ if (actionConfig?.open) {
617
+ openDialog(actionConfig.open, { ...item, _parentId: parentId, _bindTo: bindTo });
618
+ }
619
+ break;
620
+
621
+ case 'delete':
622
+ if (actionConfig?.confirm) {
623
+ openDialog(`${id}_deleteConfirm`, { ...item, _parentId: parentId, _bindTo: bindTo });
624
+ } else {
625
+ // Direct delete via sub-resource API
626
+ const deleteUrl = `/api/${parentEntityLower}s/${parentId}/${bindTo}/${item.id}`;
627
+ try {
628
+ const response = await fetch(deleteUrl, { method: 'DELETE', headers: apiHeaders });
629
+ if (response.ok) {
630
+ refreshItems();
631
+ }
632
+ } catch (err) {
633
+ console.error(`[SimpleList] Delete error:`, err);
634
+ }
635
+ }
636
+ break;
637
+
638
+ default:
639
+ if (actionConfig?.open) {
640
+ openDialog(actionConfig.open, { ...item, _parentId: parentId, _bindTo: bindTo });
641
+ }
642
+ }
643
+ }, [id, onAction, setEditItem, openDialog, parentId, bindTo, parentEntityLower, refreshItems, apiHeaders]);
644
+
645
+ // Handle add button
646
+ const handleAdd = React.useCallback(() => {
647
+ const actionConfig = onAction?.add;
648
+ // Open form dialog with parent context
649
+ if (actionConfig?.open) {
650
+ openDialog(actionConfig.open, { _parentId: parentId, _bindTo: bindTo, _isNew: true });
651
+ } else {
652
+ // Default: try to open a form with the component's entity name
653
+ const formId = config?.entityName?.toLowerCase() + 'Form';
654
+ openDialog(formId, { _parentId: parentId, _bindTo: bindTo, _isNew: true });
655
+ }
656
+ }, [onAction, openDialog, parentId, bindTo, config?.entityName]);
657
+
658
+ // Show placeholder if no parent selected
659
+ if (!parentId) {
660
+ return (
661
+ <Box
662
+ sx={{
663
+ display: 'flex',
664
+ alignItems: 'center',
665
+ justifyContent: 'center',
666
+ height: '100%',
667
+ minHeight: 100,
668
+ color: 'text.secondary',
669
+ bgcolor: 'grey.50',
670
+ borderRadius: 1
671
+ }}
672
+ >
673
+ <Typography variant="body2">
674
+ {componentConfig.placeholder?.message || `Select a ${parentEntityName?.toLowerCase() || 'record'} to view ${config?.entityNamePlural?.toLowerCase() || 'items'}`}
675
+ </Typography>
676
+ </Box>
677
+ );
678
+ }
679
+
680
+ return (
681
+ <SimpleList
682
+ config={config}
683
+ data={relatedState.items}
684
+ loading={loading}
685
+ onItemClick={handleItemClick}
686
+ onAction={handleAction}
687
+ onAdd={handleAdd}
688
+ />
689
+ );
690
+ }
691
+
692
+ /**
693
+ * SimpleListDeleteDialog - Confirmation dialog for SimpleList delete actions
694
+ */
695
+ function SimpleListDeleteDialog({ componentId, componentConfig }) {
696
+ const { dialogs, closeDialog, config: viewConfig } = useJsonView();
697
+ const apiHeaders = useApiHeaders();
698
+
699
+ const dialogId = `${componentId}_deleteConfirm`;
700
+ const dialogState = dialogs[dialogId];
701
+ const isOpen = dialogState?.open || false;
702
+ const itemToDelete = dialogState?.data;
703
+
704
+ const parentEntityLower = viewConfig?.dataSource?.entityName?.toLowerCase();
705
+ const entityName = componentConfig?.config?.entityName || 'item';
706
+
707
+ const handleConfirm = React.useCallback(async () => {
708
+ if (!itemToDelete?.id || !itemToDelete?._parentId || !itemToDelete?._bindTo) {
709
+ closeDialog(dialogId);
710
+ return;
711
+ }
712
+
713
+ const deleteUrl = `/api/${parentEntityLower}s/${itemToDelete._parentId}/${itemToDelete._bindTo}/${itemToDelete.id}`;
714
+ try {
715
+ const response = await fetch(deleteUrl, { method: 'DELETE', headers: apiHeaders });
716
+ if (response.ok) {
717
+ // The SimpleListComponent will refresh on next render when dialog closes
718
+ // We need to trigger a refresh - this is handled by the component's useEffect
719
+ window.dispatchEvent(new CustomEvent('simpleListRefresh', { detail: { componentId } }));
720
+ }
721
+ } catch (err) {
722
+ console.error(`[SimpleList] Delete error:`, err);
723
+ }
724
+ closeDialog(dialogId);
725
+ }, [itemToDelete, parentEntityLower, closeDialog, dialogId, componentId, apiHeaders]);
726
+
727
+ const handleCancel = React.useCallback(() => {
728
+ closeDialog(dialogId);
729
+ }, [closeDialog, dialogId]);
730
+
731
+ return (
732
+ <Dialog open={isOpen} onClose={handleCancel}>
733
+ <DialogTitle>Confirm Delete</DialogTitle>
734
+ <DialogContent>
735
+ <Typography>
736
+ Are you sure you want to delete this {entityName.toLowerCase()}?
737
+ </Typography>
738
+ </DialogContent>
739
+ <DialogActions>
740
+ <Button onClick={handleCancel}>Cancel</Button>
741
+ <Button onClick={handleConfirm} color="error" variant="contained">
742
+ Delete
743
+ </Button>
744
+ </DialogActions>
745
+ </Dialog>
746
+ );
747
+ }
748
+
749
+ /**
750
+ * WorkflowComponent - Renders WorkflowActions with JSON view bindings
751
+ */
752
+ function WorkflowComponent({ componentConfig, boundData }) {
753
+ const { storeActions, config: viewConfig } = useJsonView();
754
+
755
+ const workflowInstanceField = componentConfig.config?.workflowInstanceField || 'workflow_instance_id';
756
+ const instanceId = boundData?.data?.[workflowInstanceField];
757
+
758
+ const sliceId = viewConfig?.dataSource?.sliceId;
759
+
760
+ const { transitions, workflowState, loading, error, executeTransition } = useWorkflow(instanceId);
761
+
762
+ const handleTransition = useCallback(async (ruleId) => {
763
+ try {
764
+ await executeTransition(ruleId);
765
+ // Refresh the grid after successful transition
766
+ storeActions.list?.(sliceId ? { sliceId } : undefined);
767
+ } catch (err) {
768
+ // Error is already set in useWorkflow state
769
+ }
770
+ }, [executeTransition, storeActions, sliceId]);
771
+
772
+ return (
773
+ <WorkflowActions
774
+ workflowState={workflowState}
775
+ transitions={transitions}
776
+ loading={loading}
777
+ error={error}
778
+ onTransition={handleTransition}
779
+ />
780
+ );
781
+ }
782
+
783
+ /**
784
+ * DeleteConfirmDialog - Confirmation dialog for delete actions
785
+ */
786
+ function DeleteConfirmDialog({ componentId, entityName = 'item' }) {
787
+ const { dialogs, closeDialog, storeActions, config: viewConfig } = useJsonView();
788
+
789
+ const dialogId = `${componentId}_deleteConfirm`;
790
+ const dialogState = dialogs[dialogId];
791
+ const isOpen = dialogState?.open || false;
792
+ const itemToDelete = dialogState?.data;
793
+ const sliceId = viewConfig?.dataSource?.sliceId;
794
+
795
+ const handleConfirm = useCallback(async () => {
796
+ if (itemToDelete?.id) {
797
+ await storeActions.delete?.(itemToDelete.id);
798
+ storeActions.list?.(sliceId ? { sliceId } : undefined);
799
+ }
800
+ closeDialog(dialogId);
801
+ }, [itemToDelete, storeActions, closeDialog, dialogId, sliceId]);
802
+
803
+ const handleCancel = useCallback(() => {
804
+ closeDialog(dialogId);
805
+ }, [closeDialog, dialogId]);
806
+
807
+ return (
808
+ <Dialog open={isOpen} onClose={handleCancel}>
809
+ <DialogTitle>Confirm Delete</DialogTitle>
810
+ <DialogContent>
811
+ <Typography>
812
+ Are you sure you want to delete this {entityName}?
813
+ {itemToDelete?.title && ` "${itemToDelete.title}"`}
814
+ </Typography>
815
+ </DialogContent>
816
+ <DialogActions>
817
+ <Button onClick={handleCancel}>Cancel</Button>
818
+ <Button onClick={handleConfirm} color="error" variant="contained">
819
+ Delete
820
+ </Button>
821
+ </DialogActions>
822
+ </Dialog>
823
+ );
824
+ }
825
+
826
+ /**
827
+ * ViewComponent
828
+ *
829
+ * Renders the appropriate component based on type configuration.
830
+ *
831
+ * @param {Object} componentConfig - Component configuration
832
+ * @param {string} componentConfig.id - Component ID
833
+ * @param {string} componentConfig.type - Component type: grid | form | detail | custom
834
+ * @param {Object} componentConfig.config - Type-specific configuration
835
+ * @param {Object} componentConfig.listenTo - Reactive bindings
836
+ * @param {string} componentConfig.showWhen - Visibility condition
837
+ * @param {Object} componentConfig.placeholder - Placeholder when hidden/empty
838
+ * @param {Object} componentConfig.onAction - Action handlers
839
+ * @param {string} componentConfig.component - For custom type: name of extension component
840
+ */
841
+ export function ViewComponent({ componentConfig }) {
842
+ const { viewState, config: viewConfig, extensionComponents, dialogs, closeDialog } = useJsonView();
843
+
844
+ const { id, type, listenTo, showWhen, minBreakpoint, maxBreakpoint } = componentConfig;
845
+
846
+ // Resolve bindings
847
+ const boundData = useMemo(
848
+ () => resolveListenTo(listenTo, viewState),
849
+ [listenTo, viewState]
850
+ );
851
+
852
+ // Evaluate visibility
853
+ const isVisible = useMemo(
854
+ () => evaluateShowWhen(showWhen, viewState),
855
+ [showWhen, viewState]
856
+ );
857
+
858
+ // Get entity name for delete dialog
859
+ const entityName = componentConfig.config?.entityName ||
860
+ viewConfig?.dataSource?.entityName ||
861
+ 'item';
862
+
863
+ // Render based on type
864
+ let content;
865
+ switch (type) {
866
+ case 'grid':
867
+ content = <GridComponent componentConfig={componentConfig} boundData={boundData} />;
868
+ break;
869
+
870
+ case 'cardList':
871
+ content = <CardListComponent componentConfig={componentConfig} boundData={boundData} />;
872
+ break;
873
+
874
+ case 'form':
875
+ // Forms are typically rendered as dialogs
876
+ content = <FormComponent componentConfig={componentConfig} boundData={boundData} asDialog />;
877
+ break;
878
+
879
+ case 'detail':
880
+ if (!isVisible) {
881
+ // Show placeholder when not visible
882
+ if (componentConfig.placeholder) {
883
+ content = (
884
+ <Box
885
+ sx={{
886
+ display: 'flex',
887
+ alignItems: 'center',
888
+ justifyContent: 'center',
889
+ height: '100%',
890
+ minHeight: 200,
891
+ color: 'text.secondary',
892
+ bgcolor: 'grey.50',
893
+ borderRadius: 1
894
+ }}
895
+ >
896
+ <Typography>{componentConfig.placeholder.message}</Typography>
897
+ </Box>
898
+ );
899
+ } else {
900
+ content = null;
901
+ }
902
+ } else {
903
+ content = <DetailComponent componentConfig={componentConfig} boundData={boundData} />;
904
+ }
905
+ break;
906
+
907
+ case 'workflow':
908
+ if (!isVisible) {
909
+ if (componentConfig.placeholder) {
910
+ content = (
911
+ <Box
912
+ sx={{
913
+ display: 'flex',
914
+ alignItems: 'center',
915
+ justifyContent: 'center',
916
+ height: '100%',
917
+ minHeight: 200,
918
+ color: 'text.secondary',
919
+ bgcolor: 'grey.50',
920
+ borderRadius: 1
921
+ }}
922
+ >
923
+ <Typography>{componentConfig.placeholder.message}</Typography>
924
+ </Box>
925
+ );
926
+ } else {
927
+ content = null;
928
+ }
929
+ } else {
930
+ content = <WorkflowComponent componentConfig={componentConfig} boundData={boundData} />;
931
+ }
932
+ break;
933
+
934
+ case 'simpleList':
935
+ content = <SimpleListComponent componentConfig={componentConfig} boundData={boundData} />;
936
+ break;
937
+
938
+ case 'view':
939
+ // Nested view - render with appropriate layout
940
+ if (!isVisible) {
941
+ if (componentConfig.placeholder) {
942
+ content = (
943
+ <Box
944
+ sx={{
945
+ display: 'flex',
946
+ alignItems: 'center',
947
+ justifyContent: 'center',
948
+ height: '100%',
949
+ minHeight: 200,
950
+ color: 'text.secondary',
951
+ bgcolor: 'grey.50',
952
+ borderRadius: 1
953
+ }}
954
+ >
955
+ <Typography>{componentConfig.placeholder.message}</Typography>
956
+ </Box>
957
+ );
958
+ } else {
959
+ content = null;
960
+ }
961
+ } else {
962
+ const NestedLayout = componentConfig.layout === 'tabs' ? TabLayout
963
+ : componentConfig.layout === 'split' ? SplitLayout
964
+ : SingleLayout;
965
+ content = (
966
+ <NestedLayout
967
+ config={componentConfig.layoutConfig}
968
+ components={componentConfig.components || []}
969
+ />
970
+ );
971
+ }
972
+ break;
973
+
974
+ case 'custom':
975
+ // Render custom component from extension
976
+ const CustomComponent = extensionComponents?.[componentConfig.component];
977
+ if (CustomComponent) {
978
+ // Check if this is a dialog-based component
979
+ const dialogState = dialogs[id];
980
+ const isDialogOpen = dialogState?.open || false;
981
+ const dialogData = dialogState?.data || boundData?.data;
982
+
983
+ content = (
984
+ <CustomComponent
985
+ id={id}
986
+ config={componentConfig.config}
987
+ data={dialogData}
988
+ boundData={boundData}
989
+ open={isDialogOpen}
990
+ onClose={() => closeDialog(id)}
991
+ />
992
+ );
993
+ } else {
994
+ content = (
995
+ <Box sx={{ p: 2 }}>
996
+ <Typography color="error">
997
+ Custom component not found: {componentConfig.component}
998
+ </Typography>
999
+ </Box>
1000
+ );
1001
+ }
1002
+ break;
1003
+
1004
+ default:
1005
+ content = (
1006
+ <Box sx={{ p: 2 }}>
1007
+ <Typography color="error">Unknown component type: {type}</Typography>
1008
+ </Box>
1009
+ );
1010
+ }
1011
+
1012
+ // Build responsive display sx if breakpoint visibility is configured.
1013
+ // minBreakpoint: show only at this breakpoint and above (e.g. 'md' → hide on xs/sm)
1014
+ // maxBreakpoint: show only at this breakpoint and below (e.g. 'sm' → hide on md+)
1015
+ let displaySx;
1016
+ if (minBreakpoint) {
1017
+ displaySx = { display: { xs: 'none', [minBreakpoint]: 'block' } };
1018
+ } else if (maxBreakpoint) {
1019
+ const nextBp = { xs: 'sm', sm: 'md', md: 'lg', lg: 'xl' }[maxBreakpoint];
1020
+ displaySx = nextBp
1021
+ ? { display: { xs: 'block', [nextBp]: 'none' } }
1022
+ : { display: 'block' };
1023
+ }
1024
+
1025
+ // Wrap in a Box with responsive display if needed, otherwise render directly
1026
+ const wrapped = displaySx ? (
1027
+ <Box sx={displaySx}>
1028
+ {content}
1029
+ </Box>
1030
+ ) : content;
1031
+
1032
+ return (
1033
+ <>
1034
+ {wrapped}
1035
+ {/* Delete confirmation dialog for this component */}
1036
+ <DeleteConfirmDialog componentId={id} entityName={entityName} />
1037
+ {/* Delete confirmation dialog for SimpleList */}
1038
+ {type === 'simpleList' && (
1039
+ <SimpleListDeleteDialog componentId={id} componentConfig={componentConfig} />
1040
+ )}
1041
+ </>
1042
+ );
1043
+ }
1044
+
1045
+ export default ViewComponent;