@donotdev/ui 0.2.1 → 0.2.3

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 (174) hide show
  1. package/dist/{GoToDialog-CICRYHHG.js → GoToDialog-KSBGOIWO.js} +1 -1
  2. package/dist/chunk-MS7ZIW5Z.js +1 -0
  3. package/dist/components/auth/AuthHeader.d.ts.map +1 -1
  4. package/dist/components/auth/AuthHeader.js +0 -2
  5. package/dist/components/auth/AuthMenu.d.ts.map +1 -1
  6. package/dist/components/auth/AuthMenu.js +6 -40
  7. package/dist/components/common/TechBento.d.ts +2 -6
  8. package/dist/components/common/TechBento.d.ts.map +1 -1
  9. package/dist/components/common/TechBento.js +14 -16
  10. package/dist/components/common/icon.d.ts.map +1 -1
  11. package/dist/components/common/icon.js +2 -1
  12. package/dist/components/common/lucideIconByName.d.ts +9 -0
  13. package/dist/components/common/lucideIconByName.d.ts.map +1 -0
  14. package/dist/components/common/lucideIconByName.js +32 -0
  15. package/dist/components/layout/GameFlow.d.ts.map +1 -1
  16. package/dist/components/layout/components/Breadcrumbs.d.ts.map +1 -1
  17. package/dist/components/layout/components/Breadcrumbs.js +14 -9
  18. package/dist/components/layout/components/header/CacheSettings.d.ts.map +1 -1
  19. package/dist/components/layout/components/header/CacheSettings.js +6 -4
  20. package/dist/components/layout/components/header/SettingsMenu.d.ts.map +1 -1
  21. package/dist/components/layout/components/header/SettingsMenu.js +2 -1
  22. package/dist/components/layout/components/header/ThemeToggle.d.ts.map +1 -1
  23. package/dist/components/layout/components/header/ThemeToggle.js +2 -1
  24. package/dist/crud/components/CrudCardLink.d.ts +6 -6
  25. package/dist/crud/components/CrudCardLink.d.ts.map +1 -1
  26. package/dist/crud/components/CrudCardLink.js +3 -9
  27. package/dist/crud/components/EntityCardList.d.ts.map +1 -1
  28. package/dist/crud/components/EntityCardList.js +3 -11
  29. package/dist/crud/components/EntityDisplayRenderer.d.ts +1 -1
  30. package/dist/crud/components/EntityDisplayRenderer.d.ts.map +1 -1
  31. package/dist/crud/components/EntityDisplayRenderer.js +17 -58
  32. package/dist/crud/components/EntityFormRenderer.d.ts.map +1 -1
  33. package/dist/crud/components/EntityFormRenderer.js +27 -5
  34. package/dist/crud/components/EntityList.d.ts +4 -4
  35. package/dist/crud/components/EntityList.d.ts.map +1 -1
  36. package/dist/crud/components/EntityList.js +136 -59
  37. package/dist/crud/components/Form.d.ts +1 -1
  38. package/dist/crud/components/Form.d.ts.map +1 -1
  39. package/dist/crud/components/Form.js +2 -2
  40. package/dist/crud/components/cellEditFor.d.ts +28 -0
  41. package/dist/crud/components/cellEditFor.d.ts.map +1 -0
  42. package/dist/crud/components/cellEditFor.js +54 -0
  43. package/dist/crud/components/entityParent.d.ts +40 -0
  44. package/dist/crud/components/entityParent.d.ts.map +1 -0
  45. package/dist/crud/components/entityParent.js +54 -0
  46. package/dist/crud/components/useRecordBreadcrumb.d.ts +11 -0
  47. package/dist/crud/components/useRecordBreadcrumb.d.ts.map +1 -0
  48. package/dist/crud/components/useRecordBreadcrumb.js +34 -0
  49. package/dist/crud/crudImports.d.ts +3 -0
  50. package/dist/crud/crudImports.d.ts.map +1 -1
  51. package/dist/crud/crudImports.js +3 -0
  52. package/dist/dndev-next.css +483 -145
  53. package/dist/dndev.css +483 -145
  54. package/dist/index.js +4 -4
  55. package/dist/internal/common/RouteErrorFallback.d.ts.map +1 -1
  56. package/dist/internal/common/RouteErrorFallback.js +2 -4
  57. package/dist/internal/devtools/components/ConfigTab.d.ts.map +1 -1
  58. package/dist/internal/devtools/components/ConfigTab.js +1 -1
  59. package/dist/internal/devtools/components/CookieTab.d.ts.map +1 -1
  60. package/dist/internal/devtools/components/CookieTab.js +1 -5
  61. package/dist/internal/devtools/components/DesignTab.d.ts.map +1 -1
  62. package/dist/internal/devtools/components/DesignTab.js +18 -7
  63. package/dist/internal/devtools/components/StoresTab.d.ts.map +1 -1
  64. package/dist/internal/devtools/components/StoresTab.js +17 -3
  65. package/dist/internal/devtools/types.d.ts +3 -3
  66. package/dist/internal/devtools/types.d.ts.map +1 -1
  67. package/dist/internal/devtools/utils/maskSensitive.d.ts +1 -1
  68. package/dist/internal/devtools/utils/maskSensitive.d.ts.map +1 -1
  69. package/dist/internal/layout/DnDevLayout.d.ts.map +1 -1
  70. package/dist/internal/layout/DnDevLayout.js +21 -21
  71. package/dist/internal/layout/components/AutoMetaTags.d.ts.map +1 -1
  72. package/dist/internal/layout/components/AutoMetaTags.js +45 -58
  73. package/dist/internal/layout/components/footer/FooterLegalLinks.js +2 -2
  74. package/dist/internal/layout/components/footer/useLegalLinks.d.ts +0 -2
  75. package/dist/internal/layout/components/footer/useLegalLinks.d.ts.map +1 -1
  76. package/dist/internal/layout/components/footer/useLegalLinks.js +0 -2
  77. package/dist/internal/layout/components/i18nSeoMeta.d.ts +54 -0
  78. package/dist/internal/layout/components/i18nSeoMeta.d.ts.map +1 -0
  79. package/dist/internal/layout/components/i18nSeoMeta.js +53 -0
  80. package/dist/internal/layout/components/index.d.ts +1 -1
  81. package/dist/internal/layout/components/index.js +1 -1
  82. package/dist/internal/layout/zones/DnDevMergedBar.js +3 -3
  83. package/dist/internal/providers/UIProviders.d.ts.map +1 -1
  84. package/dist/internal/providers/UIProviders.js +7 -2
  85. package/dist/providers/NextJsAppProviders.d.ts +5 -1
  86. package/dist/providers/NextJsAppProviders.d.ts.map +1 -1
  87. package/dist/providers/NextJsAppProviders.js +36 -6
  88. package/dist/providers/ViteAppProviders.d.ts.map +1 -1
  89. package/dist/providers/ViteAppProviders.js +42 -4
  90. package/dist/routing/404.js +4 -4
  91. package/dist/routing/AuthGuard.d.ts +0 -4
  92. package/dist/routing/AuthGuard.d.ts.map +1 -1
  93. package/dist/routing/AuthGuard.js +0 -4
  94. package/dist/routing/AuthGuardFallback.d.ts.map +1 -1
  95. package/dist/routing/AuthGuardFallback.js +1 -2
  96. package/dist/routing/AuthReturnTo.d.ts.map +1 -1
  97. package/dist/routing/AuthReturnTo.js +9 -2
  98. package/dist/routing/GoTo.d.ts +0 -6
  99. package/dist/routing/GoTo.d.ts.map +1 -1
  100. package/dist/routing/GoTo.js +5 -8
  101. package/dist/routing/Link.d.ts +4 -2
  102. package/dist/routing/Link.d.ts.map +1 -1
  103. package/dist/routing/Link.js +8 -5
  104. package/dist/routing/SignedInRedirect.d.ts +27 -0
  105. package/dist/routing/SignedInRedirect.d.ts.map +1 -0
  106. package/dist/routing/SignedInRedirect.js +47 -0
  107. package/dist/routing/hooks/hooks.next.d.ts +2 -0
  108. package/dist/routing/hooks/hooks.next.d.ts.map +1 -1
  109. package/dist/routing/hooks/hooks.next.js +1 -1
  110. package/dist/routing/hooks/hooks.vite.d.ts +2 -0
  111. package/dist/routing/hooks/hooks.vite.d.ts.map +1 -1
  112. package/dist/routing/hooks/hooks.vite.js +1 -1
  113. package/dist/routing/hooks/useLocation.next.d.ts +12 -0
  114. package/dist/routing/hooks/useLocation.next.d.ts.map +1 -1
  115. package/dist/routing/hooks/useLocation.next.js +17 -4
  116. package/dist/routing/hooks/useMatch.next.d.ts +6 -0
  117. package/dist/routing/hooks/useMatch.next.d.ts.map +1 -1
  118. package/dist/routing/hooks/useMatch.next.js +8 -2
  119. package/dist/routing/hooks/useNavigate.next.d.ts +6 -1
  120. package/dist/routing/hooks/useNavigate.next.d.ts.map +1 -1
  121. package/dist/routing/hooks/useNavigate.next.js +13 -4
  122. package/dist/routing/hooks/useNavigate.vite.d.ts +7 -1
  123. package/dist/routing/hooks/useNavigate.vite.d.ts.map +1 -1
  124. package/dist/routing/hooks/useNavigate.vite.js +20 -4
  125. package/dist/routing/hooks/useRedirectGuard.next.d.ts.map +1 -1
  126. package/dist/routing/hooks/useRedirectGuard.next.js +7 -1
  127. package/dist/routing/hooks/useRedirectGuard.vite.d.ts.map +1 -1
  128. package/dist/routing/hooks/useRedirectGuard.vite.js +7 -1
  129. package/dist/routing/hooks/useRoutePath.next.d.ts +23 -0
  130. package/dist/routing/hooks/useRoutePath.next.d.ts.map +1 -0
  131. package/dist/routing/hooks/useRoutePath.next.js +36 -0
  132. package/dist/routing/hooks/useRoutePath.vite.d.ts +13 -0
  133. package/dist/routing/hooks/useRoutePath.vite.d.ts.map +1 -0
  134. package/dist/routing/hooks/useRoutePath.vite.js +25 -0
  135. package/dist/routing/hooks/useUrlLanguage.next.d.ts +28 -0
  136. package/dist/routing/hooks/useUrlLanguage.next.d.ts.map +1 -0
  137. package/dist/routing/hooks/useUrlLanguage.next.js +50 -0
  138. package/dist/routing/hooks/useUrlLanguage.vite.d.ts +22 -0
  139. package/dist/routing/hooks/useUrlLanguage.vite.d.ts.map +1 -0
  140. package/dist/routing/hooks/useUrlLanguage.vite.js +41 -0
  141. package/dist/routing/index.d.ts +3 -1
  142. package/dist/routing/index.d.ts.map +1 -1
  143. package/dist/routing/index.js +2 -1
  144. package/dist/routing/useNavigation.js +4 -4
  145. package/dist/styles/index.css +483 -145
  146. package/dist/symbol-index.json +1 -1
  147. package/dist/utils/assetResolver.d.ts.map +1 -1
  148. package/dist/utils/assetResolver.js +1 -0
  149. package/dist/utils/index.d.ts +2 -0
  150. package/dist/utils/index.d.ts.map +1 -1
  151. package/dist/utils/index.js +3 -0
  152. package/dist/utils/useDeleteAccountSafe.d.ts +17 -0
  153. package/dist/utils/useDeleteAccountSafe.d.ts.map +1 -0
  154. package/dist/utils/useDeleteAccountSafe.js +52 -0
  155. package/dist/utils/useFormStoreSafe.d.ts.map +1 -1
  156. package/dist/utils/useFormStoreSafe.js +1 -0
  157. package/dist/utils/useSeo.d.ts +10 -2
  158. package/dist/utils/useSeo.d.ts.map +1 -1
  159. package/dist/utils/useSeo.js +44 -9
  160. package/dist/vite-routing/AppRoutes.d.ts.map +1 -1
  161. package/dist/vite-routing/AppRoutes.js +37 -4
  162. package/guidelines/COMPONENTS.md +2 -1
  163. package/guidelines/PAGES.md +7 -0
  164. package/guidelines/ROUTING.md +4 -0
  165. package/guidelines/SEO.md +64 -0
  166. package/package.json +9 -9
  167. package/dist/CookieConsent-5NH5DNTP.js +0 -1
  168. package/dist/CookieConsent-W7UE647Y.js +0 -1
  169. package/dist/GoToDialog-YGBON6FR.js +0 -1
  170. package/dist/chunk-DRFM6WXH.js +0 -1
  171. package/dist/chunk-MIPTBUWY.js +0 -1
  172. package/dist/internal/layout/components/NextJsAutoMetaTags.d.ts +0 -57
  173. package/dist/internal/layout/components/NextJsAutoMetaTags.d.ts.map +0 -1
  174. package/dist/internal/layout/components/NextJsAutoMetaTags.js +0 -182
@@ -10,16 +10,17 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
10
10
  * @since 0.0.1
11
11
  * @author AMBROISE PARK Consulting
12
12
  */
13
- import { useEffect, useState, useMemo } from 'react';
13
+ import { useMemo } from 'react';
14
14
  import { Stack, Spinner } from '@donotdev/components';
15
15
  import { useTranslation, isFieldVisible } from '@donotdev/core';
16
16
  import { useAuthSafe } from '../../utils/useAuthSafe';
17
- import { isCrudModuleAvailable, useCrud, DisplayFieldRenderer, } from '../crudImports';
17
+ import { isCrudModuleAvailable, useCrudDoc, DisplayFieldRenderer, } from '../crudImports';
18
+ import { useRecordBreadcrumb } from './useRecordBreadcrumb';
18
19
  /**
19
20
  * EntityDisplayRenderer - Automatically fetches and displays entity data
20
21
  *
21
22
  * Features:
22
- * - Automatic data fetching using useCrud
23
+ * - Reactive data fetching using useCrudDoc (stays in sync with edits)
23
24
  * - Loading state handling
24
25
  * - Error handling
25
26
  * - Automatic field rendering (respects visibility rules)
@@ -39,63 +40,18 @@ export function EntityDisplayRenderer({ entity, id, t, className = '', loadingMe
39
40
  // Auto-detect role from auth; prop overrides. Preview = design-time showcase, show all fields.
40
41
  const authRole = useAuthSafe('userRole');
41
42
  const viewerRole = viewerRoleProp ?? (isPreview ? 'super' : authRole);
42
- const { get, loading, data: storeData, error: storeError, isAvailable, } = useCrud(entity);
43
- const [isFetching, setIsFetching] = useState(false);
44
- const [fetchError, setFetchError] = useState(null);
45
- const [data, setData] = useState(null);
43
+ // Reactive read: re-renders on every cache write for this document (edits, deletes)
44
+ const { data: fetchedData, loading, error, notFound, } = useCrudDoc(entity, id, { enabled: !isPreview });
46
45
  // Entity + crud namespaces so formatValue can resolve crud:price.* etc.
47
46
  const { t: tDual } = useTranslation([entity.namespace, 'crud']);
48
47
  const { t: tCrud } = useTranslation('crud');
49
48
  const translate = t || tDual;
50
- // Fetch data when id is available and service is ready (skip in preview mode)
51
- useEffect(() => {
52
- if (isPreview)
53
- return;
54
- // Early return if no ID
55
- if (!id) {
56
- setData(null);
57
- setFetchError(null);
58
- setIsFetching(false);
59
- return;
60
- }
61
- // Early return if service not ready
62
- if (!isAvailable || !get) {
63
- return;
64
- }
65
- let cancelled = false;
66
- setIsFetching(true);
67
- setFetchError(null);
68
- // Call get function - it should trigger the fetch
69
- get(id)
70
- .then((fetchedData) => {
71
- if (cancelled)
72
- return;
73
- setIsFetching(false);
74
- if (fetchedData) {
75
- setData(fetchedData);
76
- setFetchError(null);
77
- }
78
- else {
79
- setData(null);
80
- setFetchError(new Error('Entity not found'));
81
- }
82
- })
83
- .catch((err) => {
84
- if (cancelled)
85
- return;
86
- setIsFetching(false);
87
- setFetchError(err instanceof Error ? err : new Error(String(err)));
88
- setData(null);
89
- });
90
- return () => {
91
- cancelled = true;
92
- };
93
- }, [id, get, isAvailable, isPreview]);
94
- // In preview mode: use preview data directly
95
- // Priority: preview > store data (reactive) > local fetch data
96
- const displayData = isPreview ? preview : storeData || data;
97
- const displayError = isPreview ? null : storeError || fetchError;
98
- const isLoading = isPreview ? false : loading || isFetching || !id;
49
+ // Preview: design-time showcase data, no read
50
+ const displayData = isPreview ? preview : fetchedData;
51
+ // Breadcrumb shows the record's name instead of its id
52
+ useRecordBreadcrumb(entity, isPreview ? null : displayData);
53
+ const displayError = isPreview ? null : error;
54
+ const isLoading = isPreview ? false : loading || !id;
99
55
  // Filter fields: respect visibility AND skip empty values
100
56
  // MUST be called before any early returns (Rules of Hooks)
101
57
  const visibleFields = useMemo(() => {
@@ -114,7 +70,7 @@ export function EntityDisplayRenderer({ entity, id, t, className = '', loadingMe
114
70
  if (fieldConfig.visibility === 'hidden') {
115
71
  return false;
116
72
  }
117
- // Get field value (displayData may be preview T or store row; entity is AnyEntity in props)
73
+ // Get field value (displayData may be preview T or cached row; entity is AnyEntity in props)
118
74
  const value = displayData[fieldName];
119
75
  // Hide if value is empty/null/undefined
120
76
  if (value === null || value === undefined) {
@@ -148,6 +104,9 @@ export function EntityDisplayRenderer({ entity, id, t, className = '', loadingMe
148
104
  }, className: className, children: _jsx(Spinner, { overlay: true, "aria-label": loadingMessage ||
149
105
  tCrud('form.loading', { defaultValue: 'Loading...' }) }) }));
150
106
  }
107
+ // CRUD unavailable (consent declined / feature absent): nothing will load
108
+ if (!displayData && !displayError && !notFound)
109
+ return null;
151
110
  // Error or not found state
152
111
  if (displayError || !displayData) {
153
112
  return (_jsx(Stack, { align: "center", justify: "center", style: {
@@ -155,7 +114,7 @@ export function EntityDisplayRenderer({ entity, id, t, className = '', loadingMe
155
114
  textAlign: 'center',
156
115
  }, className: className, children: _jsxs(Stack, { direction: "column", gap: "tight", children: [_jsx("h3", { style: { color: 'var(--muted-foreground)' }, children: notFoundMessage ||
157
116
  tCrud('errors.notFound', {
158
- defaultValue: `${entity.name} not found`,
117
+ entity: tDual('name', { defaultValue: entity.name }),
159
118
  }) }), displayError && (_jsx("p", { style: {
160
119
  color: 'var(--destructive)',
161
120
  fontSize: 'var(--font-size-sm)',
@@ -1 +1 @@
1
- {"version":3,"file":"EntityFormRenderer.d.ts","sourceRoot":"","sources":["../../../src/crud/components/EntityFormRenderer.tsx"],"names":[],"mappings":"AA0BA,OAAO,KAAK,EACV,uBAAuB,EACvB,YAAY,EAEb,MAAM,gBAAgB,CAAC;AAexB,YAAY,EAAE,uBAAuB,EAAE,CAAC;AA6BxC;;;;;;;;;;;;GAYG;AACH;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,EACtE,KAAK,EAAE,uBAAuB,CAAC,CAAC,CAAC,+BAIlC;AAseD,eAAe,kBAAkB,CAAC"}
1
+ {"version":3,"file":"EntityFormRenderer.d.ts","sourceRoot":"","sources":["../../../src/crud/components/EntityFormRenderer.tsx"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EACV,uBAAuB,EACvB,YAAY,EAEb,MAAM,gBAAgB,CAAC;AAiBxB,YAAY,EAAE,uBAAuB,EAAE,CAAC;AA6BxC;;;;;;;;;;;;GAYG;AACH;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,CAAC,SAAS,YAAY,GAAG,YAAY,EACtE,KAAK,EAAE,uBAAuB,CAAC,CAAC,CAAC,+BAIlC;AAggBD,eAAe,kBAAkB,CAAC"}
@@ -10,13 +10,15 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
10
10
  * @since 0.0.1
11
11
  * @author AMBROISE PARK Consulting
12
12
  */
13
- import { useEffect, useId, useMemo, useState } from 'react';
13
+ import { useEffect, useId, useMemo, useRef, useState, } from 'react';
14
14
  import { FormProvider, useWatch } from 'react-hook-form';
15
15
  import { Badge, Button, DropdownMenu, Grid, Stack, Spinner, } from '@donotdev/components';
16
16
  import { hasRoleAccess, useTranslation } from '@donotdev/core';
17
17
  import { useNavigate } from '../../routing';
18
18
  import { useAuthSafe } from '../../utils/useAuthSafe';
19
19
  import { isCrudModuleAvailable, DisplayFieldRenderer, FormFieldRenderer, UploadProvider, useEntityForm, useFormStore, useFieldConditions, } from '../crudImports';
20
+ import { referencePrefillFromQuery } from './entityParent';
21
+ import { useRecordBreadcrumb } from './useRecordBreadcrumb';
20
22
  /**
21
23
  * Read-only field inside a form.
22
24
  *
@@ -72,8 +74,9 @@ function EntityFormRendererCore({ entity, onSubmit, t, className = '', submitTex
72
74
  // Visibility badges (developer-facing) are for admins/super only
73
75
  const isAdminOrSuper = viewerRole === 'admin' || viewerRole === 'super';
74
76
  const showVisibilityBadges = !hideVisibilityInfo && isAdminOrSuper;
75
- // Preview dropdown (View As) is available for user/admin/super
76
- const canPreviewRole = viewerRole === 'user' || viewerRole === 'admin' || viewerRole === 'super';
77
+ // Preview dropdown (View As) is available for user/admin/super, hidden with the badges
78
+ const canPreviewRole = !hideVisibilityInfo &&
79
+ (viewerRole === 'user' || viewerRole === 'admin' || viewerRole === 'super');
77
80
  // Preview role state for View As toggle
78
81
  const [previewRole, setPreviewRole] = useState(viewerRole === 'admin' || viewerRole === 'super' || viewerRole === 'user'
79
82
  ? viewerRole
@@ -105,6 +108,10 @@ function EntityFormRendererCore({ entity, onSubmit, t, className = '', submitTex
105
108
  checked: previewRole === role,
106
109
  onClick: () => setPreviewRole(role),
107
110
  })), [previewRole, viewerRole]);
111
+ // Breadcrumb shows the edited record's name instead of its id
112
+ useRecordBreadcrumb(entity, operation === 'edit'
113
+ ? defaultValues
114
+ : undefined);
108
115
  // useEntityForm handles all orchestration
109
116
  const form = useEntityForm(entity, {
110
117
  formId,
@@ -114,8 +121,21 @@ function EntityFormRendererCore({ entity, onSubmit, t, className = '', submitTex
114
121
  t: translate,
115
122
  loading,
116
123
  });
117
- const { control, handleSubmit, formState: { errors }, fields: rawFields, formStatus, uploadProgress, isDirty, hasUserInteracted, resetForm, } = form;
124
+ const { control, setValue, handleSubmit, fields: rawFields, formStatus, uploadProgress, isDirty, hasUserInteracted, resetForm, } = form;
118
125
  const isDirtyForBlocking = isDirty && hasUserInteracted;
126
+ // Create: prefill reference fields named in the URL (`?brandId=…`, from a nested
127
+ // EntityList's add button). After mount, client-only (no Suspense / hydration
128
+ // impact on SSR pages); runs after draft restore, so the URL parent wins.
129
+ const prefilled = useRef(false);
130
+ useEffect(() => {
131
+ if (operation !== 'create' || prefilled.current)
132
+ return;
133
+ prefilled.current = true;
134
+ const prefill = referencePrefillFromQuery(entity, new URLSearchParams(window.location.search), viewerRole);
135
+ for (const [field, value] of Object.entries(prefill)) {
136
+ setValue(field, value);
137
+ }
138
+ }, [operation, entity, viewerRole, setValue]);
119
139
  // Filter fields based on previewRole when visibility info is shown
120
140
  const renderableFields = useMemo(() => {
121
141
  if (!canPreviewRole)
@@ -268,7 +288,9 @@ function EntityFormRendererCore({ entity, onSubmit, t, className = '', submitTex
268
288
  const badgeLabel = roleLabels[config.visibility] ??
269
289
  config.visibility;
270
290
  // Wrap field with visibility badge when enabled
271
- const fieldElement = !effectiveEditable ? (_jsx(FormDisplayField, { name: name, config: effectiveConfig, control: control, t: translate }, name)) : (_jsx(FormFieldRenderer, { name: name, config: effectiveConfig, control: control, errors: errors, t: translate }, name));
291
+ const fieldElement = !effectiveEditable ? (_jsx(FormDisplayField, { name: name, config: effectiveConfig,
292
+ // why: RHF Control<T> is invariant in T; FormDisplayField reads by string name, so it takes the erased Control<FieldValues>
293
+ control: control, t: translate }, name)) : (_jsx(FormFieldRenderer, { name: name, config: effectiveConfig, control: control, t: translate }, name));
272
294
  // If no badge needed, return field directly
273
295
  if (!showBadge)
274
296
  return fieldElement;
@@ -4,11 +4,11 @@ export type { EntityListProps };
4
4
  * Entity List Component - Table view for admin/internal operations
5
5
  *
6
6
  * Features:
7
- * - Filters section (collapsible) with actions and filter inputs
8
- * - Results section (collapsible) with DataTable
7
+ * - Filters section (collapsible): closed unless filters are active (e.g. from the URL)
8
+ * - Results section with the search / refresh / add toolbar and the DataTable
9
9
  * - Excel-like table display with formatted values
10
- * - Edit and Delete actions (admin only)
10
+ * - Open-link icon per row, bulk select, bulk delete of the checked rows
11
11
  * - Auto-routing when handlers not provided
12
12
  */
13
- export declare function EntityList({ entity, basePath, onClick, hideFilters, pagination, pageSize: pageSizeProp, queryOptions, exportable, preview, tone, }: EntityListProps): import("react").JSX.Element | null;
13
+ export declare function EntityList({ entity, basePath, onClick, hideFilters, pagination, pageSize: pageSizeProp, queryOptions, exportable, editable, parent, preview, tone, }: EntityListProps): import("react").JSX.Element | null;
14
14
  //# sourceMappingURL=EntityList.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"EntityList.d.ts","sourceRoot":"","sources":["../../../src/crud/components/EntityList.tsx"],"names":[],"mappings":"AA8BA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAetD,YAAY,EAAE,eAAe,EAAE,CAAC;AAEhC;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,EACzB,MAAM,EACN,QAAQ,EACR,OAAO,EACP,WAAmB,EACnB,UAAmB,EACnB,QAAQ,EAAE,YAAY,EACtB,YAAY,EACZ,UAAiB,EACjB,OAAO,EACP,IAAI,GACL,EAAE,eAAe,sCAqTjB"}
1
+ {"version":3,"file":"EntityList.d.ts","sourceRoot":"","sources":["../../../src/crud/components/EntityList.tsx"],"names":[],"mappings":"AA2CA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAmBtD,YAAY,EAAE,eAAe,EAAE,CAAC;AAEhC;;;;;;;;;GASG;AACH,wBAAgB,UAAU,CAAC,EACzB,MAAM,EACN,QAAQ,EACR,OAAO,EACP,WAAmB,EACnB,UAAmB,EACnB,QAAQ,EAAE,YAAY,EACtB,YAAY,EACZ,UAAiB,EACjB,QAAe,EACf,MAAM,EACN,OAAO,EACP,IAAI,GACL,EAAE,eAAe,sCA2YjB"}
@@ -9,31 +9,48 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
9
9
  * **Routing:** Convention basePath = `/${collection}`. View/Edit = basePath/:id, Create = basePath/new.
10
10
  * Override basePath for nested routes; use onClick(id) to open sheet instead of navigating.
11
11
  *
12
+ * **Rows:** open-link icon (opens the record) | checkbox (bulk select, select-all
13
+ * in the header) | fields. Checked rows can be deleted together (one `bulk({ deletes })`;
14
+ * rows not deleted stay checked).
15
+ *
16
+ * **Editing (default):** list fields are edited in their cells (DataTable `editable`),
17
+ * checked rows take one value at once; Save writes every change in one `bulk({ updates })`.
18
+ * Partial success: rows that fail stay pending (still marked) with an error count.
19
+ * `editable={false}`: read-only cells, a row click opens the record.
20
+ *
21
+ * **Nested list:** `parent={{ field, value }}` lists one parent's children; the add
22
+ * button opens the create form with the parent prefilled.
23
+ *
12
24
  * @version 0.1.0
13
25
  * @since 0.0.1
14
26
  * @author AMBROISE PARK Consulting
15
27
  */
16
- import { RefreshCw, Plus, Trash2, Edit, Search } from 'lucide-react';
28
+ import { RefreshCw, Plus, Trash2, Search, Save, Undo2 } from 'lucide-react';
17
29
  import { useCallback, useState } from 'react';
18
- import { DataTable, Button, Stack, ActionButton, Section, Input, } from '@donotdev/components';
30
+ import { DataTable, Button, Stack, ActionButton, Section, Input, Alert, Text, } from '@donotdev/components';
19
31
  import { useTranslation } from '@donotdev/core';
20
32
  import { Link, useNavigate } from '../../routing';
21
- import { isCrudModuleAvailable, translateFieldLabel, useCrud, useCrudList, useCrudPageSize, EntityFilters, formatValue, useReferenceResolver, } from '../crudImports';
33
+ import { useAuthSafe } from '../../utils/useAuthSafe';
34
+ import { cellEditFor } from './cellEditFor';
35
+ import { assertEntityParent, childCreatePath } from './entityParent';
36
+ import { isCrudModuleAvailable, translateFieldLabel, useCrud, useCrudFilters, useCrudList, useCrudPageSize, EntityFilters, formatValue, useReferenceResolver, } from '../crudImports';
22
37
  /**
23
38
  * Entity List Component - Table view for admin/internal operations
24
39
  *
25
40
  * Features:
26
- * - Filters section (collapsible) with actions and filter inputs
27
- * - Results section (collapsible) with DataTable
41
+ * - Filters section (collapsible): closed unless filters are active (e.g. from the URL)
42
+ * - Results section with the search / refresh / add toolbar and the DataTable
28
43
  * - Excel-like table display with formatted values
29
- * - Edit and Delete actions (admin only)
44
+ * - Open-link icon per row, bulk select, bulk delete of the checked rows
30
45
  * - Auto-routing when handlers not provided
31
46
  */
32
- export function EntityList({ entity, basePath, onClick, hideFilters = false, pagination = 'auto', pageSize: pageSizeProp, queryOptions, exportable = true, preview, tone, }) {
47
+ export function EntityList({ entity, basePath, onClick, hideFilters = false, pagination = 'auto', pageSize: pageSizeProp, queryOptions, exportable = true, editable = true, parent, preview, tone, }) {
33
48
  // Safe guard: isCrudModuleAvailable is a module-level constant (immutable after load).
34
49
  if (!isCrudModuleAvailable)
35
50
  return null;
36
51
  const isPreview = !!preview;
52
+ if (parent)
53
+ assertEntityParent(entity, parent);
37
54
  const navigate = useNavigate();
38
55
  const base = basePath ?? `/${entity.collection}`;
39
56
  // Pre-fetch referenced collections for display resolution
@@ -46,13 +63,27 @@ export function EntityList({ entity, basePath, onClick, hideFilters = false, pag
46
63
  ...(pageSizeProp != null && { defaultPageSize: pageSizeProp }),
47
64
  });
48
65
  const [searchQuery, setSearchQuery] = useState('');
66
+ // Filters panel starts closed so the table is above the fold; open when filters
67
+ // are already applied (URL or store), so they are never hidden.
68
+ const { filters } = useCrudFilters({ collection: entity.collection });
69
+ const hasActiveFilters = Object.keys(filters).length > 0;
49
70
  // useCrudList now handles client-side filter + search + sort via `processed`
50
71
  // effectiveMode tells us if auto-mode switched to server (for DataTable props)
51
72
  const { data: listData, items: rawData, processed: fetchedData, loading: fetchLoading, mutate: refreshList, effectiveMode, } = useCrudList(entity, {
52
73
  enabled: !isPreview,
53
74
  pagination,
54
75
  searchQuery,
55
- ...(queryOptions && { queryOptions }),
76
+ ...((queryOptions || parent) && {
77
+ queryOptions: parent
78
+ ? {
79
+ ...queryOptions,
80
+ where: [
81
+ ...(queryOptions?.where ?? []),
82
+ { field: parent.field, operator: '==', value: parent.value },
83
+ ],
84
+ }
85
+ : queryOptions,
86
+ }),
56
87
  ...((pagination === 'server' || pagination === 'auto') && {
57
88
  page: currentPage,
58
89
  pageSize: storedPageSize,
@@ -60,11 +91,48 @@ export function EntityList({ entity, basePath, onClick, hideFilters = false, pag
60
91
  });
61
92
  // In preview mode: use preview data, skip loading state
62
93
  const filteredData = isPreview
63
- ? preview
94
+ ? // why: public `preview` prop is untyped records (Record<string, unknown>); rows are trusted to match the entity
95
+ preview
64
96
  : fetchedData;
65
97
  const loading = isPreview ? false : fetchLoading;
66
- // useCrud -> handles actions (delete)
67
- const { delete: deleteItem } = useCrud(entity);
98
+ // useCrud -> bulk save of in-place edits, bulk delete of checked rows
99
+ const { bulk } = useCrud(entity);
100
+ // In-place editing: unsaved cell values, keyed by record id
101
+ const isEditing = editable && !isPreview;
102
+ const viewerRole = useAuthSafe('userRole');
103
+ const [pendingChanges, setPendingChanges] = useState({});
104
+ // Checked rows (bulk delete); DataTable drops rows that leave the data
105
+ const [selectedIds, setSelectedIds] = useState([]);
106
+ const presentIds = new Set(filteredData.map((row) => row.id));
107
+ const checkedIds = selectedIds.filter((id) => presentIds.has(id));
108
+ const [saving, setSaving] = useState(false);
109
+ // Rows the last bulk save / delete did not write (they stay pending / checked)
110
+ const [failedCount, setFailedCount] = useState(0);
111
+ const pendingCount = Object.values(pendingChanges).reduce((sum, row) => sum + Object.keys(row).length, 0);
112
+ // Partial success: saved rows leave the pending set, failed rows stay pending
113
+ // (still marked) so nothing typed is lost; the alert gives the count to retry.
114
+ const handleSave = async () => {
115
+ setSaving(true);
116
+ setFailedCount(0);
117
+ try {
118
+ const { failed } = await bulk({
119
+ updates: Object.entries(pendingChanges).map(([id, patch]) => ({
120
+ id,
121
+ patch: patch,
122
+ })),
123
+ });
124
+ const failedIds = new Set(failed.map((f) => f.id));
125
+ setPendingChanges(Object.fromEntries(Object.entries(pendingChanges).filter(([id]) => failedIds.has(id))));
126
+ setFailedCount(failedIds.size);
127
+ }
128
+ catch {
129
+ // Batch not attempted: every edit stays pending
130
+ setFailedCount(Object.keys(pendingChanges).length);
131
+ }
132
+ finally {
133
+ setSaving(false);
134
+ }
135
+ };
68
136
  const { t: tCrud } = useTranslation('crud');
69
137
  // Entity + crud namespaces so formatValue can resolve crud:price.* etc.
70
138
  const { t } = useTranslation([entity.namespace, 'crud']);
@@ -83,14 +151,20 @@ export function EntityList({ entity, basePath, onClick, hideFilters = false, pag
83
151
  navigate(`${base}/${id}`);
84
152
  }
85
153
  }, [base, navigate, onClick, isPreview]);
86
- // Delete handler - store handles optimistic removal automatically
87
- const handleDelete = async (itemId) => {
154
+ // Delete the checked rows in one bulk call (partial success): deleted rows leave
155
+ // the list, rows not deleted stay listed and checked; the alert gives the count.
156
+ const handleDeleteSelected = async () => {
88
157
  if (isPreview)
89
158
  return;
90
- await deleteItem(itemId);
159
+ setFailedCount(0);
160
+ const { failed } = await bulk({ deletes: checkedIds });
161
+ const failedIds = new Set(failed.map((f) => f.id));
162
+ setSelectedIds(checkedIds.filter((id) => failedIds.has(id)));
163
+ setFailedCount(failedIds.size);
91
164
  };
92
- // Generate columns from entity.listFields or entity.fields
93
- const fieldsToShow = entity.listFields || Object.keys(entity.fields);
165
+ // Generate columns from entity.listFields or entity.fields.
166
+ // A nested list hides its parent column: every row has the same parent.
167
+ const fieldsToShow = (entity.listFields || Object.keys(entity.fields)).filter((fieldName) => fieldName !== parent?.field);
94
168
  const dataColumns = fieldsToShow
95
169
  .map((fieldName) => {
96
170
  const fieldConfig = entity.fields[fieldName];
@@ -107,6 +181,9 @@ export function EntityList({ entity, basePath, onClick, hideFilters = false, pag
107
181
  sortable: !isPreview,
108
182
  filterable: !isPreview,
109
183
  align,
184
+ ...(isEditing && {
185
+ edit: cellEditFor(fieldConfig, viewerRole, referenceData, t),
186
+ }),
110
187
  render: (value, record) => formatValue(value, fieldConfig, t, {
111
188
  compact: true,
112
189
  referenceData,
@@ -115,36 +192,16 @@ export function EntityList({ entity, basePath, onClick, hideFilters = false, pag
115
192
  };
116
193
  })
117
194
  .filter(Boolean);
118
- // Actions column at the front (for mobile accessibility)
119
- const actionsColumn = {
120
- key: '_actions',
121
- title: tCrud('actions.label', { defaultValue: 'Actions' }),
122
- dataIndex: undefined,
123
- sortable: false,
124
- width: 120,
125
- align: 'center',
126
- render: (_, record) => (_jsxs(Stack, { direction: "row", gap: "tight", align: "center", justify: "center", children: [isPreview ? (_jsx(Button, { variant: "outline", icon: Edit, disabled: true, "aria-label": tCrud('edit', { defaultValue: 'Edit' }) })) : (_jsx(Button, { variant: "outline", icon: Edit, render: ({ children, ...renderProps }) => (_jsx(Link, { path: `${base}/${record.id}`, onClick: (e) => e.stopPropagation(), ...renderProps, children: children })), "aria-label": tCrud('edit', { defaultValue: 'Edit' }) })), _jsx(ActionButton, { action: async () => {
127
- await handleDelete(record.id);
128
- }, confirmText: tCrud('delete.confirm', {
129
- defaultValue: 'Are you sure you want to delete this item?',
130
- }), confirmTitle: tCrud('delete.title', {
131
- defaultValue: 'Delete Item',
132
- }), loadingText: tCrud('delete.loading', {
133
- defaultValue: 'Deleting...',
134
- }), variant: "destructive", icon: Trash2, disabled: isPreview, "aria-label": tCrud('delete', { defaultValue: 'Delete' }), children: tCrud('delete', { defaultValue: 'Delete' }) })] })),
135
- };
136
- const columns = [actionsColumn, ...dataColumns];
195
+ const columns = dataColumns;
137
196
  // Entity name for section title
138
197
  const entityName = t('name', { defaultValue: entity.name });
139
198
  // Result count
140
199
  const resultCount = filteredData.length;
141
200
  // Always show table structure - DataTable will show skeleton rows when loading
142
- return (_jsxs(_Fragment, { children: [_jsx(Section, { title: tCrud('filters.title', {
201
+ return (_jsxs(_Fragment, { children: [!hideFilters && (_jsx(Section, { title: tCrud('filters.title', {
143
202
  entity: entityName,
144
203
  defaultValue: `Browse ${entityName} - Filters`,
145
- }), collapsible: true, defaultOpen: true, tone: tone, children: _jsxs(Stack, { children: [_jsxs(Stack, { direction: "row", gap: "tight", align: "center", className: "dndev-w-full", style: { display: 'grid', gridTemplateColumns: '1fr auto auto' }, children: [_jsx(Input, { placeholder: tCrud('search.placeholder', {
146
- defaultValue: 'Search...',
147
- }), value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), icon: Search, className: "dndev-w-full", disabled: isPreview }), _jsx(Button, { icon: RefreshCw, variant: "outline", onClick: handleRefresh, disabled: isPreview || loading, display: "compact", "aria-label": tCrud('refresh', { defaultValue: 'Refresh' }) }), isPreview ? (_jsx(Button, { icon: Plus, display: "compact", disabled: true, children: tCrud('addNew', { defaultValue: 'Add New' }) })) : (_jsx(Button, { icon: Plus, display: "compact", render: ({ children, ...renderProps }) => (_jsx(Link, { path: `${base}/new`, ...renderProps, children: children })), children: tCrud('addNew', { defaultValue: 'Add New' }) }))] }), !hideFilters && (_jsx(EntityFilters, { entity: entity, data: rawData, fieldsToFilter: entity.listFields }))] }) }), _jsx(Section, { title: loading
204
+ }), collapsible: true, defaultOpen: hasActiveFilters, tone: tone, children: _jsx(EntityFilters, { entity: entity, data: rawData, fieldsToFilter: fieldsToShow }) })), _jsx(Section, { title: loading
148
205
  ? tCrud('results.title.fetching', {
149
206
  defaultValue: 'Fetching...',
150
207
  })
@@ -153,24 +210,44 @@ export function EntityList({ entity, basePath, onClick, hideFilters = false, pag
153
210
  defaultValue: resultCount === 1
154
211
  ? 'Found 1 occurrence'
155
212
  : `Found ${resultCount} occurrences`,
156
- }), collapsible: true, defaultOpen: true, tone: tone, children: _jsx(DataTable, { data: filteredData, columns: columns, sortable: !isPreview, searchable: false, pagination: true, loading: loading, onRowClick: isPreview ? undefined : (item) => handleView(item.id),
157
- // Pagination labels (translated)
158
- showingLabel: tCrud('pagination.showing', {
159
- defaultValue: 'Showing {{from}} to {{to}} of {{total}} entries',
160
- }), paginationPreviousLabel: tCrud('pagination.previous', {
161
- defaultValue: 'Previous',
162
- }), paginationNextLabel: tCrud('pagination.next', {
163
- defaultValue: 'Next',
164
- }), paginationItemsPerPagePlaceholder: tCrud('pagination.itemsPerPagePlaceholder', {
165
- defaultValue: 'Items per page',
166
- }),
167
- // Persisted page size — always controlled via CrudStore
168
- pageSize: storedPageSize, onPageSizeChange: setStoredPageSize, ...(!isPreview &&
169
- effectiveMode === 'server' && {
170
- currentPage,
171
- total: listData?.total,
172
- onPageChange: setCurrentPage,
173
- }),
174
- // Export functionality
175
- exportable: isPreview ? false : exportable, exportFilename: `${entity.collection}-export`, exportLabel: tCrud('export', { defaultValue: 'Export' }) }) })] }));
213
+ }), tone: tone, children: _jsxs(Stack, { children: [_jsxs(Stack, { direction: "row", gap: "tight", align: "center", className: "dndev-w-full", style: { display: 'grid', gridTemplateColumns: '1fr auto auto' }, children: [_jsx(Input, { placeholder: tCrud('actions.searchPlaceholder'), value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), icon: Search, className: "dndev-w-full", disabled: isPreview }), _jsx(Button, { icon: RefreshCw, variant: "outline", onClick: handleRefresh, disabled: isPreview || loading, display: "compact", "aria-label": tCrud('actions.refresh') }), isPreview ? (_jsx(Button, { icon: Plus, display: "compact", disabled: true, children: tCrud('addNew', { defaultValue: 'Add New' }) })) : (_jsx(Button, { icon: Plus, display: "compact", render: ({ children, ...renderProps }) => (_jsx(Link, { path: parent ? childCreatePath(base, parent) : `${base}/new`, ...renderProps, children: children })), children: tCrud('addNew', { defaultValue: 'Add New' }) }))] }), isEditing && pendingCount > 0 && (_jsxs(Stack, { direction: "row", gap: "tight", align: "center", wrap: "wrap", children: [_jsx(Text, { level: "body", children: tCrud('bulkEdit.pending', { count: pendingCount }) }), _jsx(Button, { icon: Save, display: "compact", onClick: handleSave, disabled: saving, children: saving ? tCrud('form.saving') : tCrud('actions.save') }), _jsx(Button, { icon: Undo2, variant: "outline", display: "compact", onClick: () => {
214
+ setPendingChanges({});
215
+ setFailedCount(0);
216
+ }, disabled: saving, children: tCrud('bulkEdit.discard') })] })), failedCount > 0 && (_jsx(Alert, { variant: "error", title: tCrud('bulkEdit.failed', { count: failedCount }) })), !isPreview && checkedIds.length > 0 && (_jsx(Stack, { direction: "row", gap: "tight", align: "center", wrap: "wrap", children: _jsx(ActionButton, { action: handleDeleteSelected, confirmTitle: tCrud('delete.titleSelected', {
217
+ count: checkedIds.length,
218
+ }), confirmText: tCrud('delete.confirmSelected', {
219
+ count: checkedIds.length,
220
+ }), confirmLabel: tCrud('actions.delete'), cancelLabel: tCrud('actions.cancel'), variant: "outline", icon: Trash2, display: "compact", children: tCrud('bulkEdit.deleteSelected', { count: checkedIds.length }) }) })), _jsx(DataTable, { data: filteredData, columns: columns, sortable: !isPreview, searchable: false, pagination: true, loading: loading, onRowClick: isPreview ? undefined : (item) => handleView(item.id), selectable: !isPreview, getRowId: (row) => row.id, onSelect: (rows) => setSelectedIds(rows.map((row) => row.id)), openLabel: tCrud('actions.open'), ...(!isPreview &&
221
+ (onClick
222
+ ? { onRowOpen: (row) => onClick(row.id) }
223
+ : { getRowHref: (row) => `${base}/${row.id}` })), ...(isEditing && {
224
+ editable: true,
225
+ pendingChanges,
226
+ onPendingChange: setPendingChanges,
227
+ editLabels: {
228
+ selected: tCrud('bulkEdit.selected'),
229
+ field: tCrud('bulkEdit.field'),
230
+ value: tCrud('bulkEdit.value'),
231
+ apply: tCrud('bulkEdit.apply'),
232
+ },
233
+ }),
234
+ // Pagination labels (translated)
235
+ showingLabel: tCrud('pagination.showing', {
236
+ defaultValue: 'Showing {{from}} to {{to}} of {{total}} entries',
237
+ }), paginationPreviousLabel: tCrud('pagination.previous', {
238
+ defaultValue: 'Previous',
239
+ }), paginationNextLabel: tCrud('pagination.next', {
240
+ defaultValue: 'Next',
241
+ }), paginationItemsPerPagePlaceholder: tCrud('pagination.itemsPerPagePlaceholder', {
242
+ defaultValue: 'Items per page',
243
+ }),
244
+ // Persisted page size — always controlled via CrudStore
245
+ pageSize: storedPageSize, onPageSizeChange: setStoredPageSize, ...(!isPreview &&
246
+ effectiveMode === 'server' && {
247
+ currentPage,
248
+ total: listData?.total,
249
+ onPageChange: setCurrentPage,
250
+ }),
251
+ // Export functionality
252
+ exportable: isPreview ? false : exportable, exportFilename: `${entity.collection}-export`, exportLabel: tCrud('export', { defaultValue: 'Export' }) })] }) })] }));
176
253
  }
@@ -40,7 +40,7 @@ declare const FormField: <TFieldValues extends FieldValues = FieldValues, TName
40
40
  * @since 0.0.1
41
41
  * @author AMBROISE PARK Consulting
42
42
  */
43
- declare const FormItem: ({ className, ...props }: HTMLAttributes<HTMLDivElement>) => import("react").JSX.Element;
43
+ declare const FormItem: ({ className, children, ...props }: HTMLAttributes<HTMLDivElement>) => import("react").JSX.Element;
44
44
  /**
45
45
  * Hook for accessing form field context
46
46
  *
@@ -1 +1 @@
1
- {"version":3,"file":"Form.d.ts","sourceRoot":"","sources":["../../../src/crud/components/Form.tsx"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,cAAc,EACpB,MAAM,OAAO,CAAC;AACf,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAa,MAAM,sBAAsB,CAAC;AAE9D;;;;;;GAMG;AACH,QAAA,MAAM,IAAI,yaAAe,CAAC;AAqB1B;;;;;;;;;;GAUG;AACH,QAAA,MAAM,SAAS,GACb,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,KAAK,SAAS,SAAS,CAAC,YAAY,CAAC,GAAG,SAAS,CAAC,YAAY,CAAC,EAC/D,cAEC,eAAe,CAAC,YAAY,EAAE,KAAK,CAAC,gCAMtC,CAAC;AAYF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,QAAQ,GAAI,yBAAyB,cAAc,CAAC,cAAc,CAAC,gCAOxE,CAAC;AAEF;;;;;;;;;GASG;AACH,QAAA,MAAM,YAAY;;;;;;;;;;;QA4BjB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,SAAS,GAAI,yBAAyB,cAAc,CAAC,OAAO,KAAK,CAAC,uCAWvE,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,WAAW,GAAI,cAAc,cAAc,CAAC,OAAO,IAAI,CAAC,uCAgB7D,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,eAAe,GAAI,yBAGtB,cAAc,CAAC,oBAAoB,CAAC,uCAetC,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,WAAW,GAAI,mCAIlB,cAAc,CAAC,oBAAoB,CAAC,uCAsBtC,CAAC;AAEF;;;;;;GAMG;AACH,OAAO,EACL,IAAI,EACJ,QAAQ,EACR,SAAS,EACT,WAAW,EACX,eAAe,EACf,WAAW,EACX,SAAS,EACT,YAAY,GACb,CAAC"}
1
+ {"version":3,"file":"Form.d.ts","sourceRoot":"","sources":["../../../src/crud/components/Form.tsx"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AAEH,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,cAAc,EACpB,MAAM,OAAO,CAAC;AACf,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,SAAS,EACd,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,KAAK,EAAE,IAAI,EAAa,MAAM,sBAAsB,CAAC;AAE9D;;;;;;GAMG;AACH,QAAA,MAAM,IAAI,yaAAe,CAAC;AAqB1B;;;;;;;;;;GAUG;AACH,QAAA,MAAM,SAAS,GACb,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,KAAK,SAAS,SAAS,CAAC,YAAY,CAAC,GAAG,SAAS,CAAC,YAAY,CAAC,EAC/D,cAEC,eAAe,CAAC,YAAY,EAAE,KAAK,CAAC,gCAMtC,CAAC;AAYF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,QAAQ,GAAI,mCAIf,cAAc,CAAC,cAAc,CAAC,gCAShC,CAAC;AAEF;;;;;;;;;GASG;AACH,QAAA,MAAM,YAAY;;;;;;;;;;;QA4BjB,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,SAAS,GAAI,yBAAyB,cAAc,CAAC,OAAO,KAAK,CAAC,uCAWvE,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,WAAW,GAAI,cAAc,cAAc,CAAC,OAAO,IAAI,CAAC,uCAgB7D,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,eAAe,GAAI,yBAGtB,cAAc,CAAC,oBAAoB,CAAC,uCAetC,CAAC;AAEF;;;;;;;;;;GAUG;AACH,QAAA,MAAM,WAAW,GAAI,mCAIlB,cAAc,CAAC,oBAAoB,CAAC,uCAsBtC,CAAC;AAEF;;;;;;GAMG;AACH,OAAO,EACL,IAAI,EACJ,QAAQ,EACR,SAAS,EACT,WAAW,EACX,eAAe,EACf,WAAW,EACX,SAAS,EACT,YAAY,GACb,CAAC"}
@@ -62,9 +62,9 @@ const FormItemContext = createContext({});
62
62
  * @since 0.0.1
63
63
  * @author AMBROISE PARK Consulting
64
64
  */
65
- const FormItem = ({ className, ...props }) => {
65
+ const FormItem = ({ className, children, ...props }) => {
66
66
  const id = useId();
67
- return (_jsx(FormItemContext.Provider, { value: { id }, children: _jsx(Stack, { className: className, ...props }) }));
67
+ return (_jsx(FormItemContext.Provider, { value: { id }, children: _jsx(Stack, { className: className, ...props, children: children }) }));
68
68
  };
69
69
  /**
70
70
  * Hook for accessing form field context
@@ -0,0 +1,28 @@
1
+ /**
2
+ * @fileoverview Cell editor of an entity field
3
+ * @description Maps an entity field to the DataTable cell editor used by an
4
+ * `editable` EntityList.
5
+ *
6
+ * @version 0.1.0
7
+ * @since 0.2.3
8
+ * @author AMBROISE PARK Consulting
9
+ */
10
+ import type { TableCellEdit } from '@donotdev/components';
11
+ import type { EntityField } from '@donotdev/core';
12
+ type Translate = (key: string, options?: Record<string, unknown>) => string;
13
+ /**
14
+ * Cell editor of a list field, or `undefined` when the field is not edited in
15
+ * the table (type without a cell editor, or not editable by the viewer).
16
+ * References list the referenced records by their resolved label
17
+ * (`useReferenceResolver`); a reference whose collection is not resolved yet
18
+ * stays read-only.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * cellEditFor({ name: 'price', type: 'number', visibility: 'user' }, 'admin', {}, t);
23
+ * // { type: 'number' }
24
+ * ```
25
+ */
26
+ export declare function cellEditFor(field: EntityField, viewerRole: string, referenceData: Record<string, Record<string, string>>, t: Translate): TableCellEdit | undefined;
27
+ export {};
28
+ //# sourceMappingURL=cellEditFor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cellEditFor.d.ts","sourceRoot":"","sources":["../../../src/crud/components/cellEditFor.ts"],"names":[],"mappings":"AAEA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AASlD,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAK,MAAM,CAAC;AAE5E;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CACzB,KAAK,EAAE,WAAW,EAClB,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EACrD,CAAC,EAAE,SAAS,GACX,aAAa,GAAG,SAAS,CA8B3B"}
@@ -0,0 +1,54 @@
1
+ // packages/ui/src/crud/components/cellEditFor.ts
2
+ import { isFieldEditable, translateLabel } from '../crudImports';
3
+ /** Field types edited as free text in an editable list. */
4
+ const TEXT_TYPES = new Set(['text', 'email', 'url', 'tel', 'textarea']);
5
+ /** Field types edited as a dropdown of their `validation.options`. */
6
+ const OPTION_TYPES = new Set(['select', 'radio']);
7
+ /**
8
+ * Cell editor of a list field, or `undefined` when the field is not edited in
9
+ * the table (type without a cell editor, or not editable by the viewer).
10
+ * References list the referenced records by their resolved label
11
+ * (`useReferenceResolver`); a reference whose collection is not resolved yet
12
+ * stays read-only.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * cellEditFor({ name: 'price', type: 'number', visibility: 'user' }, 'admin', {}, t);
17
+ * // { type: 'number' }
18
+ * ```
19
+ */
20
+ export function cellEditFor(field, viewerRole, referenceData, t) {
21
+ if (!isFieldEditable(field.editable, viewerRole, 'edit'))
22
+ return undefined;
23
+ const type = field.type || 'text';
24
+ if (TEXT_TYPES.has(type))
25
+ return { type: 'text' };
26
+ if (type === 'number')
27
+ return { type: 'number' };
28
+ if (OPTION_TYPES.has(type)) {
29
+ const raw = field.validation?.options;
30
+ const options = typeof raw === 'function' ? raw() : raw;
31
+ if (!Array.isArray(options))
32
+ return undefined;
33
+ return {
34
+ type: 'select',
35
+ options: options.map((o) => ({
36
+ value: String(o.value),
37
+ label: translateLabel(o.label, t),
38
+ })),
39
+ };
40
+ }
41
+ if (type === 'reference') {
42
+ const collection = field.validation?.reference;
43
+ const labels = typeof collection === 'string' ? referenceData[collection] : undefined;
44
+ if (!labels)
45
+ return undefined;
46
+ return {
47
+ type: 'select',
48
+ options: Object.entries(labels)
49
+ .map(([value, label]) => ({ value, label }))
50
+ .sort((a, b) => a.label.localeCompare(b.label)),
51
+ };
52
+ }
53
+ return undefined;
54
+ }