@donotdev/ui 0.3.1 → 0.3.2
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.
- package/dist/components/auth/AuthHeader.js +1 -93
- package/dist/components/auth/AuthMenu.d.ts.map +1 -1
- package/dist/components/auth/AuthMenu.js +3 -286
- package/dist/components/auth/index.js +1 -9
- package/dist/components/common/FeatureCard.d.ts.map +1 -1
- package/dist/components/common/FeatureCard.js +1 -86
- package/dist/components/common/FeatureDisabled.js +1 -67
- package/dist/components/common/IconPlaceholder.d.ts +24 -0
- package/dist/components/common/IconPlaceholder.d.ts.map +1 -0
- package/dist/components/common/IconPlaceholder.js +1 -0
- package/dist/components/common/LazyLucideIcon.d.ts +39 -0
- package/dist/components/common/LazyLucideIcon.d.ts.map +1 -0
- package/dist/components/common/LazyLucideIcon.js +1 -0
- package/dist/components/common/ProgressBar.js +1 -84
- package/dist/components/common/RedirectOverlay.js +1 -243
- package/dist/components/common/Skeleton.js +1 -144
- package/dist/components/common/TechBento.d.ts.map +1 -1
- package/dist/components/common/TechBento.js +1 -53
- package/dist/components/common/icon.d.ts +1 -1
- package/dist/components/common/icon.d.ts.map +1 -1
- package/dist/components/common/icon.js +1 -84
- package/dist/components/common/iconByName.d.ts +33 -0
- package/dist/components/common/iconByName.d.ts.map +1 -0
- package/dist/components/common/iconByName.js +1 -0
- package/dist/components/common/index.js +1 -16
- package/dist/components/cookie-consent/ConsentBanner.d.ts +3 -1
- package/dist/components/cookie-consent/ConsentBanner.d.ts.map +1 -1
- package/dist/components/cookie-consent/ConsentBanner.js +1 -31
- package/dist/components/cookie-consent/CookieConsent.d.ts.map +1 -1
- package/dist/components/cookie-consent/CookieConsent.js +1 -183
- package/dist/components/cookie-consent/index.js +1 -11
- package/dist/components/cookie-consent/useCookieNoticeRequired.d.ts +7 -0
- package/dist/components/cookie-consent/useCookieNoticeRequired.d.ts.map +1 -0
- package/dist/components/cookie-consent/useCookieNoticeRequired.js +1 -0
- package/dist/components/index.js +1 -13
- package/dist/components/layout/GameContainer.d.ts.map +1 -1
- package/dist/components/layout/GameContainer.js +1 -72
- package/dist/components/layout/GameFlow.d.ts.map +1 -1
- package/dist/components/layout/GameFlow.js +1 -93
- package/dist/components/layout/PageConfig.d.ts.map +1 -1
- package/dist/components/layout/PageConfig.js +1 -47
- package/dist/components/layout/PageContainer.d.ts.map +1 -1
- package/dist/components/layout/PageContainer.js +1 -38
- package/dist/components/layout/components/Breadcrumbs.d.ts +2 -1
- package/dist/components/layout/components/Breadcrumbs.d.ts.map +1 -1
- package/dist/components/layout/components/Breadcrumbs.js +1 -89
- package/dist/components/layout/components/DropdownNavigation.d.ts.map +1 -1
- package/dist/components/layout/components/DropdownNavigation.js +1 -30
- package/dist/components/layout/components/FloatingLanguageSwitcher.d.ts.map +1 -1
- package/dist/components/layout/components/FloatingLanguageSwitcher.js +1 -26
- package/dist/components/layout/components/Notifications.js +1 -182
- package/dist/components/layout/components/header/AppBranding.d.ts.map +1 -1
- package/dist/components/layout/components/header/AppBranding.js +1 -54
- package/dist/components/layout/components/header/AppIcon.d.ts.map +1 -1
- package/dist/components/layout/components/header/AppIcon.js +1 -59
- package/dist/components/layout/components/header/AppTitle.d.ts.map +1 -1
- package/dist/components/layout/components/header/AppTitle.js +1 -40
- package/dist/components/layout/components/header/CacheSettings.js +1 -225
- package/dist/components/layout/components/header/GameTitle.d.ts.map +1 -1
- package/dist/components/layout/components/header/GameTitle.js +1 -66
- package/dist/components/layout/components/header/HeaderMenu.js +1 -75
- package/dist/components/layout/components/header/HeaderNavigation.d.ts.map +1 -1
- package/dist/components/layout/components/header/HeaderNavigation.js +1 -66
- package/dist/components/layout/components/header/SettingsMenu.d.ts.map +1 -1
- package/dist/components/layout/components/header/SettingsMenu.js +1 -85
- package/dist/components/layout/components/header/ThemeToggle.d.ts.map +1 -1
- package/dist/components/layout/components/header/ThemeToggle.js +1 -93
- package/dist/components/layout/components/index.js +1 -25
- package/dist/components/layout/index.js +1 -14
- package/dist/crud/components/ChildRowsPicker.js +1 -68
- package/dist/crud/components/CrudCardLink.js +1 -14
- package/dist/crud/components/EntityCardList.js +1 -184
- package/dist/crud/components/EntityDisplayRenderer.js +1 -130
- package/dist/crud/components/EntityFormRenderer.js +1 -433
- package/dist/crud/components/EntityList.js +1 -521
- package/dist/crud/components/EntityRecommendations.js +1 -87
- package/dist/crud/components/EntityWorkflow.js +1 -55
- package/dist/crud/components/Form.d.ts.map +1 -1
- package/dist/crud/components/Form.js +1 -198
- package/dist/crud/components/cellEditFor.js +1 -74
- package/dist/crud/components/entityParent.js +1 -76
- package/dist/crud/components/index.js +1 -16
- package/dist/crud/components/useRecordBreadcrumb.d.ts.map +1 -1
- package/dist/crud/components/useRecordBreadcrumb.js +1 -43
- package/dist/crud/crudImports.js +1 -51
- package/dist/crud/index.js +1 -11
- package/dist/data/techLogos.js +1 -99
- package/dist/dndev-next.css +25 -4
- package/dist/dndev.css +25 -4
- package/dist/index.js +1 -5
- package/dist/internal/common/DnDevErrorBoundary.js +1 -55
- package/dist/internal/common/ErrorFallback.js +3 -214
- package/dist/internal/common/GlobalErrorFallback.js +1 -45
- package/dist/internal/common/RouteErrorFallback.js +3 -140
- package/dist/internal/devtools/DebugTools.js +1 -131
- package/dist/internal/devtools/components/AuthDebugButton.js +1 -72
- package/dist/internal/devtools/components/ConfigTab.js +1 -61
- package/dist/internal/devtools/components/CookieTab.js +1 -156
- package/dist/internal/devtools/components/DebugDialog.js +1 -48
- package/dist/internal/devtools/components/DesignTab.js +1 -469
- package/dist/internal/devtools/components/LayoutReset.js +1 -214
- package/dist/internal/devtools/components/MaskedValue.js +1 -39
- package/dist/internal/devtools/components/StoresTab.js +1 -90
- package/dist/internal/devtools/components/index.js +1 -16
- package/dist/internal/devtools/index.js +1 -13
- package/dist/internal/devtools/types.js +0 -2
- package/dist/internal/devtools/utils/envVarDiscovery.js +1 -106
- package/dist/internal/devtools/utils/index.js +1 -12
- package/dist/internal/devtools/utils/maskSensitive.js +1 -59
- package/dist/internal/devtools/utils/virtualModuleInspector.js +1 -309
- package/dist/internal/initializers/BaseStoresInitializer.js +1 -367
- package/dist/internal/initializers/NextJsStoresInitializer.js +1 -78
- package/dist/internal/initializers/ViteStoresInitializer.js +1 -20
- package/dist/internal/initializers/index.js +1 -11
- package/dist/internal/layout/DnDevLayout.js +1 -321
- package/dist/internal/layout/components/AutoMetaTags.d.ts +2 -0
- package/dist/internal/layout/components/AutoMetaTags.d.ts.map +1 -1
- package/dist/internal/layout/components/AutoMetaTags.js +1 -338
- package/dist/internal/layout/components/FaviconHead.js +1 -60
- package/dist/internal/layout/components/FontPreloadLinks.js +1 -31
- package/dist/internal/layout/components/HeadTags.js +1 -20
- package/dist/internal/layout/components/PWAUpdateNotification.js +1 -131
- package/dist/internal/layout/components/footer/FooterBranding.d.ts.map +1 -1
- package/dist/internal/layout/components/footer/FooterBranding.js +1 -35
- package/dist/internal/layout/components/footer/FooterCopyright.d.ts.map +1 -1
- package/dist/internal/layout/components/footer/FooterCopyright.js +1 -37
- package/dist/internal/layout/components/footer/FooterLegalLinks.d.ts.map +1 -1
- package/dist/internal/layout/components/footer/FooterLegalLinks.js +1 -44
- package/dist/internal/layout/components/footer/useLegalLinks.d.ts +4 -2
- package/dist/internal/layout/components/footer/useLegalLinks.d.ts.map +1 -1
- package/dist/internal/layout/components/footer/useLegalLinks.js +1 -21
- package/dist/internal/layout/components/i18nSeoMeta.js +1 -53
- package/dist/internal/layout/components/index.js +1 -13
- package/dist/internal/layout/config/defaults.js +1 -47
- package/dist/internal/layout/config/index.js +1 -11
- package/dist/internal/layout/config/presets/admin.js +1 -35
- package/dist/internal/layout/config/presets/blog.js +1 -31
- package/dist/internal/layout/config/presets/docs.js +1 -51
- package/dist/internal/layout/config/presets/game.js +1 -53
- package/dist/internal/layout/config/presets/index.js +1 -24
- package/dist/internal/layout/config/presets/landing.js +1 -42
- package/dist/internal/layout/config/presets/moolti.js +1 -52
- package/dist/internal/layout/config/presets/plain.js +1 -25
- package/dist/internal/layout/renderers/index.js +0 -10
- package/dist/internal/layout/zones/DnDevFooter.d.ts.map +1 -1
- package/dist/internal/layout/zones/DnDevFooter.js +1 -67
- package/dist/internal/layout/zones/DnDevHeader.js +1 -41
- package/dist/internal/layout/zones/DnDevMergedBar.d.ts.map +1 -1
- package/dist/internal/layout/zones/DnDevMergedBar.js +1 -52
- package/dist/internal/layout/zones/DnDevSidebar.d.ts.map +1 -1
- package/dist/internal/layout/zones/DnDevSidebar.js +1 -181
- package/dist/internal/layout/zones/index.js +1 -14
- package/dist/internal/providers/NavigationProvider.d.ts.map +1 -1
- package/dist/internal/providers/NavigationProvider.js +1 -71
- package/dist/internal/providers/SentryInitializer.d.ts.map +1 -1
- package/dist/internal/providers/SentryInitializer.js +1 -36
- package/dist/internal/providers/UIProviders.js +1 -79
- package/dist/internal/providers/index.js +1 -12
- package/dist/next.js +1 -11
- package/dist/providers/NextJsAppProviders.d.ts.map +1 -1
- package/dist/providers/NextJsAppProviders.js +1 -107
- package/dist/providers/ViteAppProviders.d.ts.map +1 -1
- package/dist/providers/ViteAppProviders.js +1 -117
- package/dist/providers/index.js +1 -11
- package/dist/routing/404.js +1 -108
- package/dist/routing/AuthGuard.js +1 -178
- package/dist/routing/AuthGuardFallback.d.ts.map +1 -1
- package/dist/routing/AuthGuardFallback.js +1 -67
- package/dist/routing/AuthReturnTo.js +1 -68
- package/dist/routing/DnDevNavigationMenu.d.ts.map +1 -1
- package/dist/routing/DnDevNavigationMenu.js +1 -138
- package/dist/routing/GoTo.d.ts.map +1 -1
- package/dist/routing/GoTo.js +1 -38
- package/dist/routing/GoToDialog.d.ts.map +1 -1
- package/dist/routing/GoToDialog.js +1 -97
- package/dist/routing/GoToInput.d.ts.map +1 -1
- package/dist/routing/GoToInput.js +1 -49
- package/dist/routing/GoToWrapper.d.ts.map +1 -1
- package/dist/routing/GoToWrapper.js +1 -59
- package/dist/routing/Link.d.ts +10 -2
- package/dist/routing/Link.d.ts.map +1 -1
- package/dist/routing/Link.js +1 -109
- package/dist/routing/NavigationItem.d.ts.map +1 -1
- package/dist/routing/NavigationItem.js +1 -44
- package/dist/routing/NotFoundDocument.d.ts +33 -0
- package/dist/routing/NotFoundDocument.d.ts.map +1 -0
- package/dist/routing/NotFoundDocument.js +1 -0
- package/dist/routing/SignedInRedirect.js +1 -47
- package/dist/routing/hooks/hooks.vite.js +1 -1
- package/dist/routing/hooks/index.js +1 -26
- package/dist/routing/hooks/types.js +0 -2
- package/dist/routing/hooks/useLocation.next.js +1 -35
- package/dist/routing/hooks/useLocation.vite.js +1 -13
- package/dist/routing/hooks/useMatch.next.js +1 -31
- package/dist/routing/hooks/useMatch.vite.js +1 -6
- package/dist/routing/hooks/useNavigate.next.js +1 -64
- package/dist/routing/hooks/useNavigate.vite.js +1 -61
- package/dist/routing/hooks/useParams.next.js +1 -9
- package/dist/routing/hooks/useParams.vite.js +1 -6
- package/dist/routing/hooks/useQueryParams.next.js +1 -66
- package/dist/routing/hooks/useQueryParams.vite.js +1 -66
- package/dist/routing/hooks/useRedirectGuard.next.js +1 -119
- package/dist/routing/hooks/useRedirectGuard.vite.js +1 -117
- package/dist/routing/hooks/useRouteParam.next.js +1 -38
- package/dist/routing/hooks/useRouteParam.vite.js +1 -38
- package/dist/routing/hooks/useRoutePath.next.js +1 -36
- package/dist/routing/hooks/useRoutePath.vite.js +1 -25
- package/dist/routing/hooks/useSearchParams.next.js +1 -22
- package/dist/routing/hooks/useSearchParams.vite.js +1 -22
- package/dist/routing/hooks/useUrlLanguage.next.js +1 -50
- package/dist/routing/hooks/useUrlLanguage.vite.js +1 -41
- package/dist/routing/index.d.ts +1 -0
- package/dist/routing/index.d.ts.map +1 -1
- package/dist/routing/index.js +1 -32
- package/dist/routing/link/InternalLink.next.d.ts +23 -0
- package/dist/routing/link/InternalLink.next.d.ts.map +1 -0
- package/dist/routing/link/InternalLink.next.js +1 -0
- package/dist/routing/link/InternalLink.vite.d.ts +22 -0
- package/dist/routing/link/InternalLink.vite.d.ts.map +1 -0
- package/dist/routing/link/InternalLink.vite.js +1 -0
- package/dist/routing/link/absolutePath.d.ts +17 -0
- package/dist/routing/link/absolutePath.d.ts.map +1 -0
- package/dist/routing/link/absolutePath.js +1 -0
- package/dist/routing/link/link.next.d.ts +12 -0
- package/dist/routing/link/link.next.d.ts.map +1 -0
- package/dist/routing/link/link.next.js +1 -0
- package/dist/routing/link/link.vite.d.ts +12 -0
- package/dist/routing/link/link.vite.d.ts.map +1 -0
- package/dist/routing/link/link.vite.js +1 -0
- package/dist/routing/link/types.d.ts +30 -0
- package/dist/routing/link/types.d.ts.map +1 -0
- package/dist/routing/link/types.js +0 -0
- package/dist/routing/parentRoute.js +1 -43
- package/dist/routing/useGoTo.d.ts.map +1 -1
- package/dist/routing/useGoTo.js +1 -59
- package/dist/routing/useNavigation.d.ts.map +1 -1
- package/dist/routing/useNavigation.js +1 -114
- package/dist/routing/useRouteDiscovery.d.ts +1 -0
- package/dist/routing/useRouteDiscovery.d.ts.map +1 -1
- package/dist/routing/useRouteDiscovery.js +1 -313
- package/dist/rsc.d.ts +28 -0
- package/dist/rsc.d.ts.map +1 -0
- package/dist/rsc.js +1 -0
- package/dist/styles/index.css +25 -4
- package/dist/styles/index.js +1 -10
- package/dist/styles/layoutConstants.js +1 -134
- package/dist/symbol-index.json +1 -1
- package/dist/utils/assetResolver.d.ts.map +1 -1
- package/dist/utils/assetResolver.js +1 -297
- package/dist/utils/index.js +1 -23
- package/dist/utils/sanitizeSvg.js +1 -51
- package/dist/utils/tList.js +1 -42
- package/dist/utils/useAISafe.d.ts.map +1 -1
- package/dist/utils/useAISafe.js +1 -53
- package/dist/utils/useAuthSafe.d.ts.map +1 -1
- package/dist/utils/useAuthSafe.js +1 -78
- package/dist/utils/useAuthVisibility.d.ts.map +1 -1
- package/dist/utils/useAuthVisibility.js +1 -63
- package/dist/utils/useBillingVisibility.d.ts.map +1 -1
- package/dist/utils/useBillingVisibility.js +1 -57
- package/dist/utils/useCrudSafe.d.ts.map +1 -1
- package/dist/utils/useCrudSafe.js +1 -75
- package/dist/utils/useDeleteAccountSafe.js +1 -52
- package/dist/utils/useFormStoreSafe.d.ts.map +1 -1
- package/dist/utils/useFormStoreSafe.js +1 -85
- package/dist/utils/useOAuthSafe.d.ts.map +1 -1
- package/dist/utils/useOAuthSafe.js +1 -38
- package/dist/utils/useSeo.js +1 -151
- package/dist/utils/useStripeBillingSafe.d.ts.map +1 -1
- package/dist/utils/useStripeBillingSafe.js +1 -81
- package/dist/vite-routing/AppRoutes.d.ts.map +1 -1
- package/dist/vite-routing/AppRoutes.js +1 -235
- package/dist/vite-routing/RootLayout.d.ts.map +1 -1
- package/dist/vite-routing/RootLayout.js +1 -205
- package/dist/vite-routing/index.js +1 -11
- package/dist/vite.js +1 -10
- package/guidelines/COMPONENTS.md +3 -3
- package/guidelines/PAGES.md +3 -0
- package/guidelines/ROUTING.md +15 -0
- package/guidelines/SEO.md +4 -1
- package/package.json +18 -8
- package/dist/ChildRowsPicker-63M4EQUQ.js +0 -1
- package/dist/ChildRowsPicker-ISP365ON.js +0 -1
- package/dist/ChildRowsPicker-PQFE6NCR.js +0 -1
- package/dist/ChildRowsPicker-XXFFSMWY.js +0 -1
- package/dist/CookieConsent-QOUAY6B4.js +0 -1
- package/dist/GoToDialog-KSBGOIWO.js +0 -1
- package/dist/GoToDialog-XBK5EZF4.js +0 -1
- package/dist/chunk-3CIZFGST.js +0 -1
- package/dist/chunk-LHMKU342.js +0 -1
- package/dist/chunk-MS7ZIW5Z.js +0 -1
- package/dist/chunk-O2XFH626.js +0 -1
- package/dist/chunk-P2DHZWPY.js +0 -1
- package/dist/components/common/lucideIconByName.d.ts +0 -9
- package/dist/components/common/lucideIconByName.d.ts.map +0 -1
- package/dist/components/common/lucideIconByName.js +0 -32
- package/dist/internal/layout/components/PerformanceHints.d.ts +0 -71
- package/dist/internal/layout/components/PerformanceHints.d.ts.map +0 -1
- package/dist/internal/layout/components/PerformanceHints.js +0 -71
|
@@ -1,433 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
// packages/ui/src/crud/components/EntityFormRenderer.tsx
|
|
4
|
-
/**
|
|
5
|
-
* @fileoverview EntityFormRenderer component
|
|
6
|
-
* @description Dumb renderer that composes form from entity definition.
|
|
7
|
-
* All orchestration logic lives in useEntityForm.
|
|
8
|
-
*
|
|
9
|
-
* @version 0.1.0
|
|
10
|
-
* @since 0.0.1
|
|
11
|
-
* @author AMBROISE PARK Consulting
|
|
12
|
-
*/
|
|
13
|
-
import { useEffect, useMemo, useRef, useState, } from 'react';
|
|
14
|
-
import { FormProvider, useWatch } from 'react-hook-form';
|
|
15
|
-
import { Alert, Badge, Button, DropdownMenu, Grid, Stack, Spinner, } from '@donotdev/components';
|
|
16
|
-
import { hasRoleAccess, useTranslation } from '@donotdev/core';
|
|
17
|
-
import { useNavigate } from '../../routing';
|
|
18
|
-
import { useAuthSafe } from '../../utils/useAuthSafe';
|
|
19
|
-
import { isCrudModuleAvailable, DisplayFieldRenderer, FormFieldRenderer, UploadProvider, useEntityForm, useFormStore, useFormError, useFieldConditions, translateFieldLabel, } from '../crudImports';
|
|
20
|
-
import { referencePrefillFromQuery } from './entityParent';
|
|
21
|
-
import { useRecordBreadcrumb } from './useRecordBreadcrumb';
|
|
22
|
-
const errorSummaryStyle = { gridColumn: '1 / -1', width: '100%' };
|
|
23
|
-
// RHF root errors may be a single message or named server errors.
|
|
24
|
-
function rootErrorMessages(error) {
|
|
25
|
-
if (!error || typeof error !== 'object')
|
|
26
|
-
return [];
|
|
27
|
-
return Object.entries(error).flatMap(([key, value]) => {
|
|
28
|
-
if (key === 'message' && typeof value === 'string')
|
|
29
|
-
return [value];
|
|
30
|
-
if (key === 'ref' || key === 'types')
|
|
31
|
-
return [];
|
|
32
|
-
return rootErrorMessages(value);
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* Read-only field the form writes (`editable: 'computed'`, or an input disabled
|
|
37
|
-
* by a condition).
|
|
38
|
-
*
|
|
39
|
-
* Subscribes to the field's live form value rather than reading the initial
|
|
40
|
-
* `defaultValues`, so fields written during the session — a computed value set
|
|
41
|
-
* by another field's component via `setValue`, for instance — display what the
|
|
42
|
-
* form will actually submit, not what it was loaded with.
|
|
43
|
-
*
|
|
44
|
-
* Mirrors FormFieldRenderer's contract: takes `control`, subscribes itself.
|
|
45
|
-
*/
|
|
46
|
-
function FormDisplayField({ name, config, control, t, }) {
|
|
47
|
-
// why: renderable field names are the entity's own field names
|
|
48
|
-
const value = useWatch({ control, name: name });
|
|
49
|
-
return (_jsx(DisplayFieldRenderer, { name: name, config: config, value: value, t: t }));
|
|
50
|
-
}
|
|
51
|
-
/**
|
|
52
|
-
* Value of a field in the stored row (`form.record`): an extension field
|
|
53
|
-
* (`offer.price`) reads the extension row under its key.
|
|
54
|
-
*/
|
|
55
|
-
function recordValue(record, name) {
|
|
56
|
-
const dot = name.indexOf('.');
|
|
57
|
-
if (dot === -1)
|
|
58
|
-
return record?.[name];
|
|
59
|
-
const nested = record?.[name.slice(0, dot)];
|
|
60
|
-
return typeof nested === 'object' && nested !== null
|
|
61
|
-
? nested[name.slice(dot + 1)]
|
|
62
|
-
: undefined;
|
|
63
|
-
}
|
|
64
|
-
/**
|
|
65
|
-
* EntityFormRenderer - Dumb component that renders a form from entity definition.
|
|
66
|
-
*
|
|
67
|
-
* All orchestration (uploads, validation, status tracking) is handled by useEntityForm.
|
|
68
|
-
* This component just:
|
|
69
|
-
* - Generates formId
|
|
70
|
-
* - Renders fields
|
|
71
|
-
* - Renders submit button with status from useEntityForm
|
|
72
|
-
* - Submits through `onSubmit`, or, without it, useEntityForm's default writer
|
|
73
|
-
* (the record plus the child rows joined to the form, one `bulkAcross`)
|
|
74
|
-
*
|
|
75
|
-
* @version 0.1.0
|
|
76
|
-
* @since 0.0.1
|
|
77
|
-
* @author AMBROISE PARK Consulting
|
|
78
|
-
*/
|
|
79
|
-
/**
|
|
80
|
-
* EntityFormRenderer - public API.
|
|
81
|
-
* Applies instanceKey as React key on the inner component for clean state isolation
|
|
82
|
-
* when navigating between entities on the same route (e.g. /cars/:id).
|
|
83
|
-
*/
|
|
84
|
-
export function EntityFormRenderer(props) {
|
|
85
|
-
const { instanceKey, ...rest } = props;
|
|
86
|
-
return _jsx(EntityFormRendererCore, { ...rest }, instanceKey);
|
|
87
|
-
}
|
|
88
|
-
function EntityFormRendererCore({ entity, onSubmit, t, className = '', submitText, loading = false, defaultValues, submitVariant = 'primary', secondaryButtonText, secondaryButtonVariant = 'outline', onSecondarySubmit, viewerRole: viewerRoleProp, operation: operationProp, formId: externalFormId, cancelText, cancelPath, successPath, onCancel, hideVisibilityInfo = false, }) {
|
|
89
|
-
// Safe guard: isCrudModuleAvailable is a module-level constant (immutable after load).
|
|
90
|
-
// Hooks below are either ALL called or NONE — no Rules-of-Hooks violation at runtime.
|
|
91
|
-
if (!isCrudModuleAvailable)
|
|
92
|
-
return null;
|
|
93
|
-
// why: without the prop, Op is FieldOperation (both operations), so the runtime
|
|
94
|
-
// default ('edit' with defaultValues, else 'create') is an Op
|
|
95
|
-
const operation = (operationProp ?? (defaultValues ? 'edit' : 'create'));
|
|
96
|
-
const navigate = useNavigate();
|
|
97
|
-
// Auto-detect role from auth; prop overrides (e.g. View-As preview)
|
|
98
|
-
const authRole = useAuthSafe('userRole');
|
|
99
|
-
const viewerRole = viewerRoleProp ?? authRole;
|
|
100
|
-
// Deterministic form ID: it also keys the auto-saved draft, so it must survive reloads.
|
|
101
|
-
// Several forms of the same entity on one page pass their own formId.
|
|
102
|
-
const formId = externalFormId ?? `entity-form-${entity.name}`;
|
|
103
|
-
// Entity + crud namespaces so translateLabel can resolve crud:status.* etc.
|
|
104
|
-
const { t: translationFn } = useTranslation([entity.namespace, 'crud']);
|
|
105
|
-
const { t: tCrud } = useTranslation('crud');
|
|
106
|
-
const translate = t || translationFn;
|
|
107
|
-
// Visibility badges (developer-facing) are for admins/super only
|
|
108
|
-
const isAdminOrSuper = viewerRole === 'admin' || viewerRole === 'super';
|
|
109
|
-
const showVisibilityBadges = !hideVisibilityInfo && isAdminOrSuper;
|
|
110
|
-
// Preview dropdown (View As) is available for user/admin/super, hidden with the badges
|
|
111
|
-
const canPreviewRole = !hideVisibilityInfo &&
|
|
112
|
-
(viewerRole === 'user' || viewerRole === 'admin' || viewerRole === 'super');
|
|
113
|
-
// Preview role state for View As toggle
|
|
114
|
-
const [previewRole, setPreviewRole] = useState(viewerRole === 'admin' || viewerRole === 'super' || viewerRole === 'user'
|
|
115
|
-
? viewerRole
|
|
116
|
-
: 'guest');
|
|
117
|
-
// Visibility → Badge variant mapping (inline, no separate file needed)
|
|
118
|
-
const visibilityBadgeVariant = {
|
|
119
|
-
guest: 'muted',
|
|
120
|
-
user: 'secondary',
|
|
121
|
-
admin: 'warning',
|
|
122
|
-
super: 'destructive',
|
|
123
|
-
technical: 'accent',
|
|
124
|
-
owner: 'secondary',
|
|
125
|
-
};
|
|
126
|
-
// Role hierarchy for filtering (higher index = more access)
|
|
127
|
-
const roleHierarchy = ['guest', 'user', 'admin', 'super'];
|
|
128
|
-
// Role display labels (hardcoded English - universal technical terms)
|
|
129
|
-
const roleLabels = {
|
|
130
|
-
guest: 'Guest',
|
|
131
|
-
user: 'User',
|
|
132
|
-
admin: 'Admin',
|
|
133
|
-
super: 'Super',
|
|
134
|
-
technical: 'System',
|
|
135
|
-
};
|
|
136
|
-
// Preview dropdown menu items (roles current viewer can assume)
|
|
137
|
-
const previewMenuItems = useMemo(() => roleHierarchy
|
|
138
|
-
.filter((role) => hasRoleAccess(viewerRole, role))
|
|
139
|
-
.map((role) => ({
|
|
140
|
-
label: roleLabels[role],
|
|
141
|
-
checked: previewRole === role,
|
|
142
|
-
onClick: () => setPreviewRole(role),
|
|
143
|
-
})), [previewRole, viewerRole]);
|
|
144
|
-
// Breadcrumb shows the edited record's name instead of its id
|
|
145
|
-
useRecordBreadcrumb(entity, operation === 'edit'
|
|
146
|
-
? defaultValues
|
|
147
|
-
: undefined);
|
|
148
|
-
// useEntityForm handles all orchestration
|
|
149
|
-
const form = useEntityForm(entity, {
|
|
150
|
-
formId,
|
|
151
|
-
operation,
|
|
152
|
-
defaultValues,
|
|
153
|
-
viewerRole,
|
|
154
|
-
t: translate,
|
|
155
|
-
loading,
|
|
156
|
-
successPath,
|
|
157
|
-
});
|
|
158
|
-
const { control, setValue, handleSubmit, fields: rawFields, formStatus, uploadProgress, isDirty, hasUserInteracted, resetForm, } = form;
|
|
159
|
-
const submissionError = useFormError(formId);
|
|
160
|
-
const { errors, submitCount } = form.formState;
|
|
161
|
-
const formRef = useRef(null);
|
|
162
|
-
const summaryRef = useRef(null);
|
|
163
|
-
// RHF keeps only the fields that have an error (cleared ones are unset)
|
|
164
|
-
const errorFields = Object.keys(errors).filter((name) => name !== 'root');
|
|
165
|
-
const rootMessages = rootErrorMessages(errors.root);
|
|
166
|
-
const hasErrors = errorFields.length > 0 || rootMessages.length > 0 || !!submissionError;
|
|
167
|
-
const previousFeedback = useRef({ submitCount: 0, rootKey: '', submissionError: null });
|
|
168
|
-
const rootKey = JSON.stringify(rootMessages);
|
|
169
|
-
useEffect(() => {
|
|
170
|
-
const previous = previousFeedback.current;
|
|
171
|
-
previousFeedback.current = { submitCount, rootKey, submissionError };
|
|
172
|
-
// Blur/condition revalidation may update errors while the user is editing.
|
|
173
|
-
// Announce them inline, but move focus only for a submit or a new root failure.
|
|
174
|
-
const submitted = submitCount > previous.submitCount;
|
|
175
|
-
const rootFailure = (rootKey !== previous.rootKey && rootKey !== '[]') ||
|
|
176
|
-
(!!submissionError && submissionError !== previous.submissionError);
|
|
177
|
-
if (!submitted && !rootFailure)
|
|
178
|
-
return;
|
|
179
|
-
const summary = summaryRef.current;
|
|
180
|
-
const formElement = formRef.current;
|
|
181
|
-
if (!summary || !formElement)
|
|
182
|
-
return;
|
|
183
|
-
// The orchestrator owns actionable field focus. Only focus the summary when
|
|
184
|
-
// there is no mounted, focusable invalid control in THIS form (e.g. a hidden
|
|
185
|
-
// field or a server/root error), including inside a Sheet's scroll container.
|
|
186
|
-
const invalidNames = Object.keys(errors).filter((name) => name !== 'root');
|
|
187
|
-
const hasActionableError = Array.from(formElement.querySelectorAll('input, textarea, select, button, [tabindex]')).some((control) => {
|
|
188
|
-
const name = control.getAttribute('name');
|
|
189
|
-
const invalid = control.getAttribute('aria-invalid') === 'true' ||
|
|
190
|
-
(name !== null &&
|
|
191
|
-
invalidNames.some((field) => name === field || name.startsWith(`${field}.`)));
|
|
192
|
-
if (!invalid ||
|
|
193
|
-
control.matches(':disabled, input[type="hidden"]') ||
|
|
194
|
-
control.closest('[hidden], [inert], [aria-hidden="true"]') ||
|
|
195
|
-
control.getClientRects().length === 0) {
|
|
196
|
-
return false;
|
|
197
|
-
}
|
|
198
|
-
for (let element = control; element; element = element.parentElement) {
|
|
199
|
-
const style = getComputedStyle(element);
|
|
200
|
-
if (style.display === 'none' || style.visibility === 'hidden')
|
|
201
|
-
return false;
|
|
202
|
-
if (element === formElement)
|
|
203
|
-
break;
|
|
204
|
-
}
|
|
205
|
-
return true;
|
|
206
|
-
});
|
|
207
|
-
if (hasActionableError)
|
|
208
|
-
return;
|
|
209
|
-
summary.focus({ preventScroll: true });
|
|
210
|
-
summary.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
|
211
|
-
}, [errors, submitCount, submissionError, rootKey]);
|
|
212
|
-
const isDirtyForBlocking = isDirty && hasUserInteracted;
|
|
213
|
-
// Create: prefill reference fields named in the URL (`?brandId=…`, from a nested
|
|
214
|
-
// EntityList's add button). After mount, client-only (no Suspense / hydration
|
|
215
|
-
// impact on SSR pages); runs after draft restore, so the URL parent wins.
|
|
216
|
-
const prefilled = useRef(false);
|
|
217
|
-
useEffect(() => {
|
|
218
|
-
if (operation !== 'create' || prefilled.current)
|
|
219
|
-
return;
|
|
220
|
-
prefilled.current = true;
|
|
221
|
-
const prefill = referencePrefillFromQuery(entity, new URLSearchParams(window.location.search), viewerRole);
|
|
222
|
-
for (const [field, value] of Object.entries(prefill)) {
|
|
223
|
-
// why: prefill keys are reference fields the form writes on create
|
|
224
|
-
// (referencePrefillFromQuery), values record ids
|
|
225
|
-
setValue(field, value);
|
|
226
|
-
}
|
|
227
|
-
}, [operation, entity, viewerRole, setValue]);
|
|
228
|
-
// Filter fields based on previewRole when visibility info is shown
|
|
229
|
-
const renderableFields = useMemo(() => {
|
|
230
|
-
if (!canPreviewRole)
|
|
231
|
-
return rawFields;
|
|
232
|
-
const previewRoleIndex = roleHierarchy.indexOf(previewRole);
|
|
233
|
-
return rawFields.filter(({ config }) => {
|
|
234
|
-
const fieldVisibility = config.visibility;
|
|
235
|
-
// 'hidden' fields are never shown, 'technical' always shown as read-only
|
|
236
|
-
if (fieldVisibility === 'hidden')
|
|
237
|
-
return false;
|
|
238
|
-
if (fieldVisibility === 'technical')
|
|
239
|
-
return true;
|
|
240
|
-
const fieldRoleIndex = roleHierarchy.indexOf(fieldVisibility);
|
|
241
|
-
return fieldRoleIndex <= previewRoleIndex;
|
|
242
|
-
});
|
|
243
|
-
}, [rawFields, canPreviewRole, previewRole]);
|
|
244
|
-
// Evaluate field conditions (visible/disabled/required/readonly) against live form values
|
|
245
|
-
const fieldConditions = useFieldConditions(renderableFields, control);
|
|
246
|
-
// Sync isDirty to FormStore (single source of truth)
|
|
247
|
-
// Use getState() to avoid subscribing to the action reference (Zustand anti-pattern)
|
|
248
|
-
useEffect(() => {
|
|
249
|
-
if (formId) {
|
|
250
|
-
useFormStore.getState().setIsDirty(formId, isDirtyForBlocking);
|
|
251
|
-
}
|
|
252
|
-
}, [formId, isDirtyForBlocking]);
|
|
253
|
-
// Handle cancel — auto-save ensures draft is persisted, no confirm needed
|
|
254
|
-
const handleCancel = () => {
|
|
255
|
-
resetForm();
|
|
256
|
-
if (onCancel) {
|
|
257
|
-
onCancel();
|
|
258
|
-
}
|
|
259
|
-
else if (cancelPath) {
|
|
260
|
-
navigate(cancelPath);
|
|
261
|
-
}
|
|
262
|
-
else {
|
|
263
|
-
navigate('back');
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
// onSubmit receives the written fields (FormValues), not the whole row
|
|
267
|
-
// No try/catch here — errors MUST propagate to useEntityForm's orchestrator
|
|
268
|
-
// which properly calls setError() and does NOT clearDraft/reset.
|
|
269
|
-
// Leaving on save (successPath) is useEntityForm's job: it leaves before the
|
|
270
|
-
// write and returns on rejection.
|
|
271
|
-
// Without onSubmit, useEntityForm's default writer saves the record and the
|
|
272
|
-
// child rows joined to this form (nested EntityList on this record).
|
|
273
|
-
const handleFormSubmit = onSubmit
|
|
274
|
-
? async (data) => {
|
|
275
|
-
await onSubmit(data);
|
|
276
|
-
}
|
|
277
|
-
: undefined;
|
|
278
|
-
// Determine if cancel button should show
|
|
279
|
-
// Show by default, hide only if cancelText is explicitly null
|
|
280
|
-
const showCancelButton = cancelText !== null;
|
|
281
|
-
const cancelButtonText = cancelText ?? tCrud('form.cancel');
|
|
282
|
-
// Common button container style (sticky footer)
|
|
283
|
-
const buttonContainerStyle = {
|
|
284
|
-
gridColumn: '1 / -1',
|
|
285
|
-
position: 'sticky',
|
|
286
|
-
bottom: 0,
|
|
287
|
-
backgroundColor: 'var(--background)',
|
|
288
|
-
borderTop: '1px solid var(--border)',
|
|
289
|
-
paddingTop: 'var(--gap-md)',
|
|
290
|
-
paddingBottom: 'var(--gap-md)',
|
|
291
|
-
zIndex: 10,
|
|
292
|
-
marginTop: 'var(--gap-lg)',
|
|
293
|
-
};
|
|
294
|
-
// Auto-detect loading for edit forms waiting for data
|
|
295
|
-
const isLoading = loading || (operation === 'edit' && !defaultValues);
|
|
296
|
-
// Compute button state from form status
|
|
297
|
-
const buttonState = useMemo(() => {
|
|
298
|
-
if (formStatus === 'uploading') {
|
|
299
|
-
return {
|
|
300
|
-
loading: true,
|
|
301
|
-
loadingText: uploadProgress < 100
|
|
302
|
-
? tCrud('form.uploading', {
|
|
303
|
-
progress: Math.round(uploadProgress),
|
|
304
|
-
})
|
|
305
|
-
: tCrud('form.processing'),
|
|
306
|
-
progress: uploadProgress,
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
if (formStatus === 'validating') {
|
|
310
|
-
return {
|
|
311
|
-
loading: true,
|
|
312
|
-
loadingText: tCrud('form.validating'),
|
|
313
|
-
};
|
|
314
|
-
}
|
|
315
|
-
if (formStatus === 'submitting') {
|
|
316
|
-
return {
|
|
317
|
-
loading: true,
|
|
318
|
-
loadingText: tCrud('form.saving'),
|
|
319
|
-
};
|
|
320
|
-
}
|
|
321
|
-
if (formStatus === 'success') {
|
|
322
|
-
return {
|
|
323
|
-
loading: false,
|
|
324
|
-
successText: tCrud('form.saved'),
|
|
325
|
-
};
|
|
326
|
-
}
|
|
327
|
-
if (formStatus === 'error') {
|
|
328
|
-
return {
|
|
329
|
-
loading: false,
|
|
330
|
-
errorText: tCrud('form.error'),
|
|
331
|
-
};
|
|
332
|
-
}
|
|
333
|
-
return { loading: false };
|
|
334
|
-
}, [formStatus, uploadProgress, tCrud]);
|
|
335
|
-
return (_jsx(FormProvider, { ...form, children: _jsx(UploadProvider, { formId: formId, children: _jsxs("div", { style: {
|
|
336
|
-
position: 'relative',
|
|
337
|
-
width: '100%',
|
|
338
|
-
gridColumn: '1 / -1',
|
|
339
|
-
display: 'contents',
|
|
340
|
-
}, children: [isLoading && _jsx(Spinner, { overlay: true }), _jsxs("form", { ref: formRef, id: formId, onSubmit: (e) => {
|
|
341
|
-
// The orchestrator records failure and preserves the draft before
|
|
342
|
-
// rethrowing. Consume only the final DOM event promise, never the
|
|
343
|
-
// consumer callback's rejection (which must remain a failure).
|
|
344
|
-
void handleSubmit(handleFormSubmit)(e).catch(() => { });
|
|
345
|
-
}, noValidate: true, className: className, style: { width: '100%', gridColumn: '1 / -1', display: 'contents' }, children: [hasErrors && (_jsx("div", { ref: summaryRef, tabIndex: -1, "aria-label": tCrud('form.error'), style: errorSummaryStyle, children: _jsxs(Alert, { variant: "error", title: tCrud(errorFields.length > 0 ? 'form.validationFailed' : 'form.error'), children: [errorFields.length > 0 && (_jsx("p", { children: tCrud('form.fixFields', {
|
|
346
|
-
fields: errorFields
|
|
347
|
-
.map((name) => translateFieldLabel(name, entity.fields[name], translate))
|
|
348
|
-
.join(', '),
|
|
349
|
-
}) })), rootMessages.map((message, index) => (_jsx("p", { children: translate(message) }, index))), submissionError && _jsx("p", { children: translate(submissionError) })] }) })), renderableFields.map(({ name, config, editable, written }) => {
|
|
350
|
-
// Evaluate dynamic conditions for this field
|
|
351
|
-
const cond = fieldConditions[name];
|
|
352
|
-
if (cond && !cond.visible)
|
|
353
|
-
return null;
|
|
354
|
-
// Apply condition overrides to field config
|
|
355
|
-
const effectiveConfig = cond && config.conditions?.required !== undefined
|
|
356
|
-
? {
|
|
357
|
-
...config,
|
|
358
|
-
// An explicit condition overrides static required in BOTH directions.
|
|
359
|
-
validation: { ...config.validation, required: cond.required },
|
|
360
|
-
}
|
|
361
|
-
: config;
|
|
362
|
-
// Condition-based disabled/readonly override editability
|
|
363
|
-
const effectiveEditable = editable && !cond?.disabled && !cond?.readonly;
|
|
364
|
-
// Show visibility badge for non-guest fields when visibility badges are enabled (admins/super only)
|
|
365
|
-
const showBadge = showVisibilityBadges && config.visibility !== 'guest';
|
|
366
|
-
const badgeVariant = config.visibility !== 'hidden'
|
|
367
|
-
? visibilityBadgeVariant[config.visibility]
|
|
368
|
-
: undefined;
|
|
369
|
-
const badgeLabel = roleLabels[config.visibility] ??
|
|
370
|
-
config.visibility;
|
|
371
|
-
// Read-only: a field the form writes from form state (computed, or an
|
|
372
|
-
// input disabled by a condition), any other from the stored row
|
|
373
|
-
// (technical, editable: false, role-denied: never in form state).
|
|
374
|
-
const fieldElement = !effectiveEditable ? (written ? (_jsx(FormDisplayField, { name: name, config: effectiveConfig, control: control, t: translate }, name)) : (_jsx(DisplayFieldRenderer, { name: name, config: effectiveConfig, value: recordValue(form.record, name), t: translate }, name))) : (_jsx(FormFieldRenderer, { name: name, config: effectiveConfig, control: control, t: translate }, name));
|
|
375
|
-
// If no badge needed, return field directly
|
|
376
|
-
if (!showBadge)
|
|
377
|
-
return fieldElement;
|
|
378
|
-
// Wrap field with badge indicator
|
|
379
|
-
return (_jsxs("div", { style: { position: 'relative' }, children: [_jsx(Badge, { as: "span", variant: badgeVariant, style: {
|
|
380
|
-
position: 'absolute',
|
|
381
|
-
top: 0,
|
|
382
|
-
insetInlineEnd: 0,
|
|
383
|
-
fontSize: 'var(--font-size-xs)',
|
|
384
|
-
zIndex: 1,
|
|
385
|
-
}, children: badgeLabel }), fieldElement] }, name));
|
|
386
|
-
}), (() => {
|
|
387
|
-
// Define all possible buttons (conditionally included)
|
|
388
|
-
const buttons = [];
|
|
389
|
-
// Cancel button
|
|
390
|
-
if (showCancelButton && cancelButtonText) {
|
|
391
|
-
buttons.push(_jsx(Button, { type: "button", intent: "cancel", onClick: handleCancel, disabled: buttonState.loading, variant: "outline", className: "dndev-w-full", children: cancelButtonText }, "cancel"));
|
|
392
|
-
}
|
|
393
|
-
// Preview dropdown (user/admin/super only)
|
|
394
|
-
if (canPreviewRole) {
|
|
395
|
-
const previewVariant = visibilityBadgeVariant[previewRole] || 'muted';
|
|
396
|
-
buttons.push(_jsx(DropdownMenu, { trigger: _jsxs(Button, { type: "button", intent: "preview", variant: previewVariant, disabled: buttonState.loading, className: "dndev-w-full", children: [tCrud('visibility.preview'), ": ", roleLabels[previewRole]] }), items: previewMenuItems }, "preview"));
|
|
397
|
-
}
|
|
398
|
-
// Secondary submit button
|
|
399
|
-
if (secondaryButtonText) {
|
|
400
|
-
buttons.push(_jsx(Button, { type: "button", onClick: () => {
|
|
401
|
-
if (onSecondarySubmit) {
|
|
402
|
-
// why: form state is typed for both operations (EntityFormState); at
|
|
403
|
-
// runtime it is the projection for this form's Op (the fields it
|
|
404
|
-
// writes), the shape onSubmit receives, not validated.
|
|
405
|
-
const currentValues = form.getValues();
|
|
406
|
-
onSecondarySubmit(currentValues);
|
|
407
|
-
}
|
|
408
|
-
}, loading: buttonState.loading, loadingText: buttonState.loadingText, progress: buttonState.progress, variant: secondaryButtonVariant, className: "dndev-w-full", children: secondaryButtonText }, "secondary"));
|
|
409
|
-
}
|
|
410
|
-
// Primary submit button (always shown)
|
|
411
|
-
buttons.push(_jsx(Button, { type: "submit", intent: "save", loading: buttonState.loading, loadingText: buttonState.loadingText, progress: buttonState.progress, variant: buttonState.successText
|
|
412
|
-
? 'success'
|
|
413
|
-
: buttonState.errorText
|
|
414
|
-
? 'destructive'
|
|
415
|
-
: submitVariant, disabled: !!buttonState.successText, className: "dndev-w-full", children: buttonState.successText ||
|
|
416
|
-
buttonState.errorText ||
|
|
417
|
-
submitText ||
|
|
418
|
-
tCrud('form.submit') }, "submit"));
|
|
419
|
-
const buttonCount = buttons.length;
|
|
420
|
-
// Single button: use Stack
|
|
421
|
-
if (buttonCount === 1) {
|
|
422
|
-
return (_jsx(Stack, { direction: "column", gap: "tight", style: buttonContainerStyle, children: buttons[0] }));
|
|
423
|
-
}
|
|
424
|
-
// Multiple buttons: responsive stacked on mobile, proportional on tablet+
|
|
425
|
-
const colTemplate = buttonCount === 2
|
|
426
|
-
? '1fr 2fr' // Cancel/Preview + Submit
|
|
427
|
-
: buttonCount === 3
|
|
428
|
-
? '1fr 1fr 2fr' // Cancel + Preview + Submit
|
|
429
|
-
: '1fr 1fr 1fr 2fr'; // Cancel + Preview + Secondary + Submit
|
|
430
|
-
return (_jsx(Grid, { cols: ['1fr', colTemplate, colTemplate, colTemplate], gap: "tight", style: buttonContainerStyle, children: buttons }));
|
|
431
|
-
})()] })] }) }) }));
|
|
432
|
-
}
|
|
433
|
-
export default EntityFormRenderer;
|
|
1
|
+
"use client";import{useEffect as H,useMemo as K,useRef as V,useState as Be}from"react";import{FormProvider as Ie,useWatch as Me}from"react-hook-form";import{Alert as De,Badge as Le,Button as P,DropdownMenu as Ne,Grid as je,Stack as He,Spinner as Ke}from"@donotdev/components";import{hasRoleAccess as Ue,useTranslation as de}from"@donotdev/core";import{useNavigate as qe}from"../../routing/index.js";import{useAuthSafe as ze}from"../../utils/useAuthSafe.js";import{isCrudModuleAvailable as Ge,DisplayFieldRenderer as ue,FormFieldRenderer as We,UploadProvider as $e,useEntityForm as Je,useFormStore as Qe,useFormError as Xe,useFieldConditions as Ye,translateFieldLabel as Ze}from"../crudImports.js";import{referencePrefillFromQuery as _e}from"./entityParent.js";import{useRecordBreadcrumb as et}from"./useRecordBreadcrumb.js";import{jsx as n,jsxs as k}from"react/jsx-runtime";var tt={gridColumn:"1 / -1",width:"100%"};function ce(r){return!r||typeof r!="object"?[]:Object.entries(r).flatMap(([i,s])=>i==="message"&&typeof s=="string"?[s]:i==="ref"||i==="types"?[]:ce(s))}function rt({name:r,config:i,control:s,t:p}){let A=Me({control:s,name:r});return n(ue,{name:r,config:i,value:A,t:p})}function nt(r,i){let s=i.indexOf(".");if(s===-1)return r?.[i];let p=r?.[i.slice(0,s)];return typeof p=="object"&&p!==null?p[i.slice(s+1)]:void 0}function it(r){let{instanceKey:i,...s}=r;return n(ot,{...s},i)}function ot({entity:r,onSubmit:i,t:s,className:p="",submitText:A,loading:U=!1,defaultValues:R,submitVariant:fe="primary",secondaryButtonText:q,secondaryButtonVariant:me="outline",onSecondarySubmit:z,viewerRole:pe,operation:ye,formId:ge,cancelText:G,cancelPath:W,successPath:ve,onCancel:$,hideVisibilityInfo:J=!1}){if(!Ge)return null;let F=ye??(R?"edit":"create"),Q=qe(),be=ze("userRole"),o=pe??be,y=ge??`entity-form-${r.name}`,{t:he}=de([r.namespace,"crud"]),{t:a}=de("crud"),g=s||he,Fe=!J&&(o==="admin"||o==="super"),B=!J&&(o==="user"||o==="admin"||o==="super"),[b,Ee]=Be(o==="admin"||o==="super"||o==="user"?o:"guest"),X={guest:"muted",user:"secondary",admin:"warning",super:"destructive",technical:"accent",owner:"secondary"},I=["guest","user","admin","super"],M={guest:"Guest",user:"User",admin:"Admin",super:"Super",technical:"System"},we=K(()=>I.filter(e=>Ue(o,e)).map(e=>({label:M[e],checked:b===e,onClick:()=>Ee(e)})),[b,o]);et(r,F==="edit"?R:void 0);let E=Je(r,{formId:y,operation:F,defaultValues:R,viewerRole:o,t:g,loading:U,successPath:ve}),{control:D,setValue:Y,handleSubmit:xe,fields:L,formStatus:h,uploadProgress:S,isDirty:ke,hasUserInteracted:Re,resetForm:Se}=E,v=Xe(y),{errors:T,submitCount:N}=E.formState,Z=V(null),_=V(null),C=Object.keys(T).filter(e=>e!=="root"),j=ce(T.root),Te=C.length>0||j.length>0||!!v,ee=V({submitCount:0,rootKey:"",submissionError:null}),O=JSON.stringify(j);H(()=>{let e=ee.current;ee.current={submitCount:N,rootKey:O,submissionError:v};let t=N>e.submitCount,d=O!==e.rootKey&&O!=="[]"||!!v&&v!==e.submissionError;if(!t&&!d)return;let c=_.current,f=Z.current;if(!c||!f)return;let w=Object.keys(T).filter(m=>m!=="root");Array.from(f.querySelectorAll("input, textarea, select, button, [tabindex]")).some(m=>{let x=m.getAttribute("name");if(!(m.getAttribute("aria-invalid")==="true"||x!==null&&w.some(u=>x===u||x.startsWith(`${u}.`)))||m.matches(':disabled, input[type="hidden"]')||m.closest('[hidden], [inert], [aria-hidden="true"]')||m.getClientRects().length===0)return!1;for(let u=m;u;u=u.parentElement){let le=getComputedStyle(u);if(le.display==="none"||le.visibility==="hidden")return!1;if(u===f)break}return!0})||(c.focus({preventScroll:!0}),c.scrollIntoView({block:"center",behavior:"smooth"}))},[T,N,v,O]);let te=ke&&Re,re=V(!1);H(()=>{if(F!=="create"||re.current)return;re.current=!0;let e=_e(r,new URLSearchParams(window.location.search),o);for(let[t,d]of Object.entries(e))Y(t,d)},[F,r,o,Y]);let ne=K(()=>{if(!B)return L;let e=I.indexOf(b);return L.filter(({config:t})=>{let d=t.visibility;return d==="hidden"?!1:d==="technical"?!0:I.indexOf(d)<=e})},[L,B,b]),Ce=Ye(ne,D);H(()=>{y&&Qe.getState().setIsDirty(y,te)},[y,te]);let Oe=()=>{Se(),$?$():Q(W||"back")},Ve=i?async e=>{await i(e)}:void 0,Pe=G!==null,ie=G??a("form.cancel"),oe={gridColumn:"1 / -1",position:"sticky",bottom:0,backgroundColor:"var(--background)",borderTop:"1px solid var(--border)",paddingTop:"var(--gap-md)",paddingBottom:"var(--gap-md)",zIndex:10,marginTop:"var(--gap-lg)"},Ae=U||F==="edit"&&!R,l=K(()=>h==="uploading"?{loading:!0,loadingText:S<100?a("form.uploading",{progress:Math.round(S)}):a("form.processing"),progress:S}:h==="validating"?{loading:!0,loadingText:a("form.validating")}:h==="submitting"?{loading:!0,loadingText:a("form.saving")}:h==="success"?{loading:!1,successText:a("form.saved")}:h==="error"?{loading:!1,errorText:a("form.error")}:{loading:!1},[h,S,a]);return n(Ie,{...E,children:n($e,{formId:y,children:k("div",{style:{position:"relative",width:"100%",gridColumn:"1 / -1",display:"contents"},children:[Ae&&n(Ke,{overlay:!0}),k("form",{ref:Z,id:y,onSubmit:e=>{xe(Ve)(e).catch(()=>{})},noValidate:!0,className:p,style:{width:"100%",gridColumn:"1 / -1",display:"contents"},children:[Te&&n("div",{ref:_,tabIndex:-1,"aria-label":a("form.error"),style:tt,children:k(De,{variant:"error",title:a(C.length>0?"form.validationFailed":"form.error"),children:[C.length>0&&n("p",{children:a("form.fixFields",{fields:C.map(e=>Ze(e,r.fields[e],g)).join(", ")})}),j.map((e,t)=>n("p",{children:g(e)},t)),v&&n("p",{children:g(v)})]})}),ne.map(({name:e,config:t,editable:d,written:c})=>{let f=Ce[e];if(f&&!f.visible)return null;let w=f&&t.conditions?.required!==void 0?{...t,validation:{...t.validation,required:f.required}}:t,se=d&&!f?.disabled&&!f?.readonly,m=Fe&&t.visibility!=="guest",x=t.visibility!=="hidden"?X[t.visibility]:void 0,ae=M[t.visibility]??t.visibility,u=se?n(We,{name:e,config:w,control:D,t:g},e):c?n(rt,{name:e,config:w,control:D,t:g},e):n(ue,{name:e,config:w,value:nt(E.record,e),t:g},e);return m?k("div",{style:{position:"relative"},children:[n(Le,{as:"span",variant:x,style:{position:"absolute",top:0,insetInlineEnd:0,fontSize:"var(--font-size-xs)",zIndex:1},children:ae}),u]},e):u}),(()=>{let e=[];if(Pe&&ie&&e.push(n(P,{type:"button",intent:"cancel",onClick:Oe,disabled:l.loading,variant:"outline",className:"dndev-w-full",children:ie},"cancel")),B){let c=X[b]||"muted";e.push(n(Ne,{trigger:k(P,{type:"button",intent:"preview",variant:c,disabled:l.loading,className:"dndev-w-full",children:[a("visibility.preview"),": ",M[b]]}),items:we},"preview"))}q&&e.push(n(P,{type:"button",onClick:()=>{if(z){let c=E.getValues();z(c)}},loading:l.loading,loadingText:l.loadingText,progress:l.progress,variant:me,className:"dndev-w-full",children:q},"secondary")),e.push(n(P,{type:"submit",intent:"save",loading:l.loading,loadingText:l.loadingText,progress:l.progress,variant:l.successText?"success":l.errorText?"destructive":fe,disabled:!!l.successText,className:"dndev-w-full",children:l.successText||l.errorText||A||a("form.submit")},"submit"));let t=e.length;if(t===1)return n(He,{direction:"column",gap:"tight",style:oe,children:e[0]});let d=t===2?"1fr 2fr":t===3?"1fr 1fr 2fr":"1fr 1fr 1fr 2fr";return n(je,{cols:["1fr",d,d,d],gap:"tight",style:oe,children:e})})()]})]})})})}var gt=it;export{it as EntityFormRenderer,gt as default};
|