@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,521 +1 @@
|
|
|
1
|
-
'use client';
|
|
2
|
-
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
-
// packages/ui/src/crud/components/EntityList.tsx
|
|
4
|
-
/**
|
|
5
|
-
* @fileoverview Entity List Component
|
|
6
|
-
* @description Table view for admin/internal CRUD operations.
|
|
7
|
-
* Features: Filters section + Results section with DataTable
|
|
8
|
-
*
|
|
9
|
-
* **Routing:** Convention basePath = `/${collection}`. View/Edit = basePath/:id, Create = basePath/new.
|
|
10
|
-
* Override basePath for nested routes; use onClick(id) to open sheet instead of navigating.
|
|
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 (no Add, selection or delete), 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
|
-
*
|
|
24
|
-
* **Joined to the parent's form:** with `parent`, `editable` (default) and an
|
|
25
|
-
* edit form open on that record, the list is a display of `useChildRows`: no own Save, deletes wait for
|
|
26
|
-
* the form's Save, pending counts + Discard; add opens a picker (link table:
|
|
27
|
-
* one reference besides the parent's) or adds a blank row. `parent.value: null`
|
|
28
|
-
* (parent not created yet) only shows "Create the draft before adding …".
|
|
29
|
-
*
|
|
30
|
-
* **Overrides:** `extraColumns` (app columns from the row with unsaved edits
|
|
31
|
-
* applied), `actions` (app toolbar content), `extend` (1:1 extensions: their
|
|
32
|
-
* columns, edited and saved with the rows; the list is then a display of
|
|
33
|
-
* `useChildRows`).
|
|
34
|
-
*
|
|
35
|
-
* **Read-only** (`editable={false}`): no Add, no row selection, no delete.
|
|
36
|
-
*
|
|
37
|
-
* @version 0.1.0
|
|
38
|
-
* @since 0.0.1
|
|
39
|
-
* @author AMBROISE PARK Consulting
|
|
40
|
-
*/
|
|
41
|
-
import { Search, Undo2 } from 'lucide-react';
|
|
42
|
-
import { Suspense, lazy, useCallback, useState } from 'react';
|
|
43
|
-
import { DataTable, Button, Stack, ActionButton, Section, Input, Alert, Text, } from '@donotdev/components';
|
|
44
|
-
import { describeEntity, getEntityByCollection, useTranslation, } from '@donotdev/core';
|
|
45
|
-
import { Link, useNavigate } from '../../routing';
|
|
46
|
-
import { useAuthSafe } from '../../utils/useAuthSafe';
|
|
47
|
-
import { cellEditFor } from './cellEditFor';
|
|
48
|
-
import { assertEntityParent, childCreatePath } from './entityParent';
|
|
49
|
-
import { isCrudModuleAvailable, translateFieldLabel, useCrud, useCrudFilters, useCrudList, useCrudPageSize, EntityFilters, formatValue, useReferenceResolver, useChildRows, useJoinedForm, applyFilters, applySearch, } from '../crudImports';
|
|
50
|
-
/** Link table picker: loaded on first use. */
|
|
51
|
-
const ChildRowsPicker = lazy(() => import('./ChildRowsPicker'));
|
|
52
|
-
/**
|
|
53
|
-
* Toolbar grid, by the number of cells after the first (search): refresh, add,
|
|
54
|
-
* app actions. Module-level: no style object per render.
|
|
55
|
-
*/
|
|
56
|
-
const TOOLBAR_STYLES = [0, 1, 2, 3, 4].map((after) => ({
|
|
57
|
-
display: 'grid',
|
|
58
|
-
gridTemplateColumns: ['1fr', ...Array(after).fill('auto')].join(' '),
|
|
59
|
-
}));
|
|
60
|
-
/**
|
|
61
|
-
* Columns of the entity's list fields (the parent column hidden), formatted,
|
|
62
|
-
* edited in their cells when `editing`.
|
|
63
|
-
*/
|
|
64
|
-
function entityColumns(entity, fieldsToShow, options) {
|
|
65
|
-
const { t, viewerRole, referenceData, editing, interactive } = options;
|
|
66
|
-
return fieldsToShow
|
|
67
|
-
.map((fieldName) => {
|
|
68
|
-
const fieldConfig = entity.fields[fieldName];
|
|
69
|
-
if (!fieldConfig)
|
|
70
|
-
return null;
|
|
71
|
-
const label = translateFieldLabel(fieldName, fieldConfig, t);
|
|
72
|
-
const fieldType = fieldConfig.type;
|
|
73
|
-
const isNumeric = fieldType === 'number' || fieldType === 'range';
|
|
74
|
-
const align = isNumeric ? 'end' : 'start';
|
|
75
|
-
return {
|
|
76
|
-
key: fieldName,
|
|
77
|
-
title: label,
|
|
78
|
-
dataIndex: fieldName,
|
|
79
|
-
sortable: interactive,
|
|
80
|
-
filterable: interactive,
|
|
81
|
-
align,
|
|
82
|
-
...(editing && {
|
|
83
|
-
edit: cellEditFor(entity, fieldName, viewerRole, referenceData, t),
|
|
84
|
-
}),
|
|
85
|
-
render: (value, record) => formatValue(value, fieldConfig, t, {
|
|
86
|
-
compact: true,
|
|
87
|
-
referenceData,
|
|
88
|
-
item: record,
|
|
89
|
-
}),
|
|
90
|
-
};
|
|
91
|
-
})
|
|
92
|
-
.filter(Boolean);
|
|
93
|
-
}
|
|
94
|
-
/** App columns (`extraColumns`), rendered from the row with its unsaved edits applied. */
|
|
95
|
-
function appColumns(extraColumns, edited) {
|
|
96
|
-
return (extraColumns ?? []).map((column) => ({
|
|
97
|
-
key: column.key,
|
|
98
|
-
title: column.title,
|
|
99
|
-
align: column.align ?? 'start',
|
|
100
|
-
render: (_value, record) => column.render(edited(record)),
|
|
101
|
-
}));
|
|
102
|
-
}
|
|
103
|
-
/** App toolbar content (`actions`), one toolbar cell. */
|
|
104
|
-
function ToolbarActions({ actions }) {
|
|
105
|
-
return (_jsx(Stack, { direction: "row", gap: "tight", align: "center", children: actions }));
|
|
106
|
-
}
|
|
107
|
-
/**
|
|
108
|
-
* Entity List Component - Table view for admin/internal operations
|
|
109
|
-
*
|
|
110
|
-
* Features:
|
|
111
|
-
* - Filters section (collapsible): closed unless filters are active (e.g. from the URL)
|
|
112
|
-
* - Results section with the search / refresh / add toolbar and the DataTable
|
|
113
|
-
* - Excel-like table display with formatted values
|
|
114
|
-
* - Open-link icon per row, bulk select, bulk delete of the checked rows
|
|
115
|
-
* - Auto-routing when handlers not provided
|
|
116
|
-
* - With `parent`, `editable` (default) and an edit form open on that record:
|
|
117
|
-
* joined to the form (`useChildRows`), saved by its Save
|
|
118
|
-
*/
|
|
119
|
-
export function EntityList(props) {
|
|
120
|
-
// Safe guard: isCrudModuleAvailable is a module-level constant (immutable after load).
|
|
121
|
-
if (!isCrudModuleAvailable)
|
|
122
|
-
return null;
|
|
123
|
-
const { entity, parent, preview, tone, editable = true } = props;
|
|
124
|
-
if (parent)
|
|
125
|
-
assertEntityParent(entity, parent);
|
|
126
|
-
// An editable list of child rows joins the edit form open on the parent record
|
|
127
|
-
// (latest opened wins). Read-only lists (`editable={false}`) never join.
|
|
128
|
-
const joinedForm = useJoinedForm(entity, parent);
|
|
129
|
-
if (parent && parent.value === null) {
|
|
130
|
-
return _jsx(ChildRowsCreateFirst, { entity: entity, tone: tone });
|
|
131
|
-
}
|
|
132
|
-
const savedParent = parent && parent.value !== null
|
|
133
|
-
? { field: parent.field, value: parent.value }
|
|
134
|
-
: undefined;
|
|
135
|
-
// With 1:1 extensions, or joined to the parent's form: a display of useChildRows.
|
|
136
|
-
if (!preview && (props.extend || (joinedForm && savedParent && editable))) {
|
|
137
|
-
return _jsx(RowsEntityList, { ...props, parent: savedParent });
|
|
138
|
-
}
|
|
139
|
-
return _jsx(StandaloneEntityList, { ...props, parent: savedParent });
|
|
140
|
-
}
|
|
141
|
-
/** `parent.value: null`: the parent is not created yet, rows cannot be added. */
|
|
142
|
-
function ChildRowsCreateFirst({ entity, tone, }) {
|
|
143
|
-
const { t } = useTranslation([entity.namespace, 'crud']);
|
|
144
|
-
return (_jsx(Section, { tone: tone, children: _jsx(Text, { level: "body", children: t('crud:childRows.createFirst', {
|
|
145
|
-
entity: t('name', { defaultValue: entity.name }),
|
|
146
|
-
}) }) }));
|
|
147
|
-
}
|
|
148
|
-
/** No form open on the parent: own Save, immediate delete, add opens the create page. */
|
|
149
|
-
function StandaloneEntityList({ entity, basePath, onClick, hideFilters = false, pagination = 'auto', pageSize: pageSizeProp, queryOptions, exportable = true, editable = true, parent, preview, tone, extraColumns, actions, }) {
|
|
150
|
-
const isPreview = !!preview;
|
|
151
|
-
const navigate = useNavigate();
|
|
152
|
-
const base = basePath ?? `/${entity.collection}`;
|
|
153
|
-
// Pre-fetch referenced collections for display resolution
|
|
154
|
-
const referenceData = useReferenceResolver(entity, !isPreview);
|
|
155
|
-
// Server-side pagination state (only used when pagination='server')
|
|
156
|
-
const [currentPage, setCurrentPage] = useState(1);
|
|
157
|
-
// Persisted page size — survives navigation, per collection
|
|
158
|
-
const { pageSize: storedPageSize, setPageSize: setStoredPageSize } = useCrudPageSize({
|
|
159
|
-
collection: entity.collection,
|
|
160
|
-
...(pageSizeProp != null && { defaultPageSize: pageSizeProp }),
|
|
161
|
-
});
|
|
162
|
-
const [searchQuery, setSearchQuery] = useState('');
|
|
163
|
-
// Filters panel starts closed so the table is above the fold; open when filters
|
|
164
|
-
// are already applied (URL or store), so they are never hidden.
|
|
165
|
-
const { filters } = useCrudFilters({ collection: entity.collection });
|
|
166
|
-
const hasActiveFilters = Object.keys(filters).length > 0;
|
|
167
|
-
// useCrudList now handles client-side filter + search + sort via `processed`
|
|
168
|
-
// effectiveMode tells us if auto-mode switched to server (for DataTable props)
|
|
169
|
-
const { data: listData, items: rawData, processed: fetchedData, loading: fetchLoading, mutate: refreshList, effectiveMode, } = useCrudList(entity, {
|
|
170
|
-
enabled: !isPreview,
|
|
171
|
-
pagination,
|
|
172
|
-
searchQuery,
|
|
173
|
-
...((queryOptions || parent) && {
|
|
174
|
-
queryOptions: parent
|
|
175
|
-
? {
|
|
176
|
-
...queryOptions,
|
|
177
|
-
where: [
|
|
178
|
-
...(queryOptions?.where ?? []),
|
|
179
|
-
{ field: parent.field, operator: '==', value: parent.value },
|
|
180
|
-
],
|
|
181
|
-
}
|
|
182
|
-
: queryOptions,
|
|
183
|
-
}),
|
|
184
|
-
...((pagination === 'server' || pagination === 'auto') && {
|
|
185
|
-
page: currentPage,
|
|
186
|
-
pageSize: storedPageSize,
|
|
187
|
-
}),
|
|
188
|
-
});
|
|
189
|
-
// In preview mode: use preview data, skip loading state
|
|
190
|
-
const filteredData = isPreview
|
|
191
|
-
? // why: public `preview` prop is untyped records (Record<string, unknown>); rows are trusted to match the entity
|
|
192
|
-
preview
|
|
193
|
-
: fetchedData;
|
|
194
|
-
const loading = isPreview ? false : fetchLoading;
|
|
195
|
-
// useCrud -> bulk save of in-place edits, bulk delete of checked rows
|
|
196
|
-
const { bulk } = useCrud(entity);
|
|
197
|
-
// In-place editing: unsaved cell values, keyed by record id
|
|
198
|
-
const isEditing = editable && !isPreview;
|
|
199
|
-
const viewerRole = useAuthSafe('userRole');
|
|
200
|
-
const [pendingChanges, setPendingChanges] = useState({});
|
|
201
|
-
// Checked rows (bulk delete); DataTable drops rows that leave the data
|
|
202
|
-
const [selectedIds, setSelectedIds] = useState([]);
|
|
203
|
-
const presentIds = new Set(filteredData.map((row) => row.id));
|
|
204
|
-
const checkedIds = selectedIds.filter((id) => presentIds.has(id));
|
|
205
|
-
const [saving, setSaving] = useState(false);
|
|
206
|
-
// Rows the last bulk save / delete did not write (they stay pending / checked)
|
|
207
|
-
const [failedCount, setFailedCount] = useState(0);
|
|
208
|
-
const pendingCount = Object.values(pendingChanges).reduce((sum, row) => sum + Object.keys(row).length, 0);
|
|
209
|
-
// Partial success: saved rows leave the pending set, failed rows stay pending
|
|
210
|
-
// (still marked) so nothing typed is lost; the alert gives the count to retry.
|
|
211
|
-
const handleSave = async () => {
|
|
212
|
-
setSaving(true);
|
|
213
|
-
setFailedCount(0);
|
|
214
|
-
try {
|
|
215
|
-
const { failed } = await bulk({
|
|
216
|
-
updates: Object.entries(pendingChanges).map(([id, patch]) => ({
|
|
217
|
-
id,
|
|
218
|
-
patch: patch,
|
|
219
|
-
})),
|
|
220
|
-
});
|
|
221
|
-
const failedIds = new Set(failed.map((f) => f.id));
|
|
222
|
-
setPendingChanges(Object.fromEntries(Object.entries(pendingChanges).filter(([id]) => failedIds.has(id))));
|
|
223
|
-
setFailedCount(failedIds.size);
|
|
224
|
-
}
|
|
225
|
-
catch {
|
|
226
|
-
// Batch not attempted: every edit stays pending
|
|
227
|
-
setFailedCount(Object.keys(pendingChanges).length);
|
|
228
|
-
}
|
|
229
|
-
finally {
|
|
230
|
-
setSaving(false);
|
|
231
|
-
}
|
|
232
|
-
};
|
|
233
|
-
const { t: tCrud } = useTranslation('crud');
|
|
234
|
-
// Entity + crud namespaces so formatValue can resolve crud:price.* etc.
|
|
235
|
-
const { t } = useTranslation([entity.namespace, 'crud']);
|
|
236
|
-
// Refresh handler - triggers manual refetch in useList
|
|
237
|
-
const handleRefresh = async () => {
|
|
238
|
-
await refreshList();
|
|
239
|
-
};
|
|
240
|
-
// Row click: onClick(id) if provided, else navigate to basePath/:id
|
|
241
|
-
const handleView = useCallback((id) => {
|
|
242
|
-
if (isPreview)
|
|
243
|
-
return;
|
|
244
|
-
if (onClick) {
|
|
245
|
-
onClick(id);
|
|
246
|
-
}
|
|
247
|
-
else {
|
|
248
|
-
navigate(`${base}/${id}`);
|
|
249
|
-
}
|
|
250
|
-
}, [base, navigate, onClick, isPreview]);
|
|
251
|
-
// Delete the checked rows in one bulk call (partial success): deleted rows leave
|
|
252
|
-
// the list, rows not deleted stay listed and checked; the alert gives the count.
|
|
253
|
-
const handleDeleteSelected = async () => {
|
|
254
|
-
if (isPreview)
|
|
255
|
-
return;
|
|
256
|
-
setFailedCount(0);
|
|
257
|
-
const { failed } = await bulk({ deletes: checkedIds });
|
|
258
|
-
const failedIds = new Set(failed.map((f) => f.id));
|
|
259
|
-
setSelectedIds(checkedIds.filter((id) => failedIds.has(id)));
|
|
260
|
-
setFailedCount(failedIds.size);
|
|
261
|
-
};
|
|
262
|
-
// Generate columns from entity.listFields or entity.fields.
|
|
263
|
-
// A nested list hides its parent column: every row has the same parent.
|
|
264
|
-
const fieldsToShow = (entity.listFields || Object.keys(entity.fields)).filter((fieldName) => fieldName !== parent?.field);
|
|
265
|
-
const dataColumns = entityColumns(entity, fieldsToShow, {
|
|
266
|
-
t,
|
|
267
|
-
viewerRole,
|
|
268
|
-
referenceData,
|
|
269
|
-
editing: isEditing,
|
|
270
|
-
interactive: !isPreview,
|
|
271
|
-
});
|
|
272
|
-
const columns = [
|
|
273
|
-
...dataColumns,
|
|
274
|
-
...appColumns(extraColumns, (row) => ({
|
|
275
|
-
...row,
|
|
276
|
-
...pendingChanges[row.id],
|
|
277
|
-
})),
|
|
278
|
-
];
|
|
279
|
-
// Entity name for section title
|
|
280
|
-
const entityName = t('name', { defaultValue: entity.name });
|
|
281
|
-
// Result count
|
|
282
|
-
const resultCount = filteredData.length;
|
|
283
|
-
// Always show table structure - DataTable will show skeleton rows when loading
|
|
284
|
-
return (_jsxs(_Fragment, { children: [!hideFilters && (_jsx(Section, { title: tCrud('filters.title', {
|
|
285
|
-
entity: entityName,
|
|
286
|
-
}), collapsible: true, defaultOpen: hasActiveFilters, tone: tone, children: _jsx(EntityFilters, { entity: entity, data: rawData, fieldsToFilter: fieldsToShow, viewerRole: viewerRole }) })), _jsx(Section, { title: loading
|
|
287
|
-
? tCrud('results.title.fetching')
|
|
288
|
-
: tCrud('results.title.count', {
|
|
289
|
-
count: resultCount,
|
|
290
|
-
}), tone: tone, children: _jsxs(Stack, { children: [_jsxs(Stack, { direction: "row", gap: "tight", align: "center", className: "dndev-w-full", style: TOOLBAR_STYLES[1 + (editable ? 1 : 0) + (actions ? 1 : 0)], 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, { intent: "reload", variant: "outline", onClick: handleRefresh, disabled: isPreview || loading, display: "compact", "aria-label": tCrud('actions.refresh') }), !editable ? null : isPreview ? (_jsx(Button, { intent: "add", display: "compact", disabled: true, children: tCrud('addNew') })) : (_jsx(Button, { intent: "add", display: "compact", render: ({ children, ...renderProps }) => (_jsx(Link, { path: parent ? childCreatePath(base, parent) : `${base}/new`, ...renderProps, children: children })), children: tCrud('addNew') })), actions && _jsx(ToolbarActions, { actions: actions })] }), 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, { intent: "save", display: "compact", onClick: handleSave, disabled: saving, children: saving ? tCrud('form.saving') : tCrud('actions.save') }), _jsx(Button, { icon: Undo2, variant: "outline", display: "compact", onClick: () => {
|
|
291
|
-
setPendingChanges({});
|
|
292
|
-
setFailedCount(0);
|
|
293
|
-
}, disabled: saving, children: tCrud('bulkEdit.discard') })] })), failedCount > 0 && (_jsx(Alert, { variant: "error", title: tCrud('bulkEdit.failed', { count: failedCount }) })), !isPreview && editable && checkedIds.length > 0 && (_jsx(Stack, { direction: "row", gap: "tight", align: "center", wrap: "wrap", children: _jsx(ActionButton, { action: handleDeleteSelected, confirmTitle: tCrud('delete.titleSelected', {
|
|
294
|
-
count: checkedIds.length,
|
|
295
|
-
}), confirmText: tCrud('delete.confirmSelected', {
|
|
296
|
-
count: checkedIds.length,
|
|
297
|
-
}), confirmLabel: tCrud('actions.delete'), cancelLabel: tCrud('actions.cancel'), variant: "outline", intent: "delete", 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),
|
|
298
|
-
// Read-only list (editable={false}): no selection, no delete
|
|
299
|
-
selectable: !isPreview && editable, getRowId: (row) => row.id, onSelect: (rows) => setSelectedIds(rows.map((row) => row.id)), openLabel: tCrud('actions.open'), ...(!isPreview &&
|
|
300
|
-
(onClick
|
|
301
|
-
? { onRowOpen: (row) => onClick(row.id) }
|
|
302
|
-
: { getRowHref: (row) => `${base}/${row.id}` })), ...(isEditing && {
|
|
303
|
-
editable: true,
|
|
304
|
-
pendingChanges,
|
|
305
|
-
onPendingChange: setPendingChanges,
|
|
306
|
-
editLabels: {
|
|
307
|
-
selected: tCrud('bulkEdit.selected'),
|
|
308
|
-
field: tCrud('bulkEdit.field'),
|
|
309
|
-
value: tCrud('bulkEdit.value'),
|
|
310
|
-
apply: tCrud('bulkEdit.apply'),
|
|
311
|
-
},
|
|
312
|
-
}),
|
|
313
|
-
// Pagination labels (translated)
|
|
314
|
-
showingLabel: tCrud('pagination.showing'), paginationPreviousLabel: tCrud('pagination.previous'), paginationNextLabel: tCrud('pagination.next'), paginationItemsPerPagePlaceholder: tCrud('pagination.itemsPerPagePlaceholder'),
|
|
315
|
-
// Persisted page size — always controlled via CrudStore
|
|
316
|
-
pageSize: storedPageSize, onPageSizeChange: setStoredPageSize, ...(!isPreview &&
|
|
317
|
-
effectiveMode === 'server' && {
|
|
318
|
-
currentPage,
|
|
319
|
-
total: listData?.total,
|
|
320
|
-
onPageChange: setCurrentPage,
|
|
321
|
-
}),
|
|
322
|
-
// Export functionality
|
|
323
|
-
exportable: isPreview ? false : exportable, exportFilename: `${entity.collection}-export`, exportLabel: tCrud('export') })] }) })] }));
|
|
324
|
-
}
|
|
325
|
-
/**
|
|
326
|
-
* The other reference field of a link table (the child has exactly one
|
|
327
|
-
* reference field besides the parent's: descriptor `value.kind === 'ref'`, any
|
|
328
|
-
* field type with `validation.reference`), or null.
|
|
329
|
-
*/
|
|
330
|
-
function linkFieldOf(entity, parentField) {
|
|
331
|
-
const others = Object.entries(describeEntity(entity).fields).filter(([name, { value }]) => name !== parentField && value.kind === 'ref' && value.ref !== undefined);
|
|
332
|
-
return others.length === 1 ? others[0][0] : null;
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* The list as a display of `useChildRows`:
|
|
336
|
-
* - **joined** (an edit form open on the parent record, `editable`): edits live
|
|
337
|
-
* in the form's draft and its Save writes them; no own Save, deletes wait for
|
|
338
|
-
* that Save, pending counts + Discard; all lines shown (no filters section,
|
|
339
|
-
* search, export or pagination); Add opens the picker (link table) or adds a
|
|
340
|
-
* blank row, never navigates;
|
|
341
|
-
* - **standalone with `extend`**: filters, search, pagination, export, own Save
|
|
342
|
-
* (rows and extensions in one write; deletes wait for it), Add opens the
|
|
343
|
-
* create page.
|
|
344
|
-
* `editable={false}`: read-only (no Add, no selection, no delete).
|
|
345
|
-
*/
|
|
346
|
-
function RowsEntityList({ entity, basePath, onClick, hideFilters = false, pageSize: pageSizeProp, exportable = true, editable = true, parent, tone, extraColumns, actions, extend, }) {
|
|
347
|
-
const navigate = useNavigate();
|
|
348
|
-
const base = basePath ?? `/${entity.collection}`;
|
|
349
|
-
const viewerRole = useAuthSafe('userRole');
|
|
350
|
-
const rows = useChildRows(entity, parent, {
|
|
351
|
-
viewerRole,
|
|
352
|
-
...(extend && { extend }),
|
|
353
|
-
});
|
|
354
|
-
const joined = rows.joined && editable;
|
|
355
|
-
const referenceData = useReferenceResolver(entity);
|
|
356
|
-
const { pageSize, setPageSize } = useCrudPageSize({
|
|
357
|
-
collection: entity.collection,
|
|
358
|
-
...(pageSizeProp != null && { defaultPageSize: pageSizeProp }),
|
|
359
|
-
});
|
|
360
|
-
const [searchQuery, setSearchQuery] = useState('');
|
|
361
|
-
const { filters } = useCrudFilters({ collection: entity.collection });
|
|
362
|
-
const hasActiveFilters = Object.keys(filters).length > 0;
|
|
363
|
-
const [selectedIds, setSelectedIds] = useState([]);
|
|
364
|
-
const [picking, setPicking] = useState(false);
|
|
365
|
-
const [saving, setSaving] = useState(false);
|
|
366
|
-
/** Why the last own Save did not write (invalid rows count, or the write error). */
|
|
367
|
-
const [saveError, setSaveError] = useState(null);
|
|
368
|
-
const { t: tCrud } = useTranslation('crud');
|
|
369
|
-
const { t } = useTranslation([entity.namespace, 'crud']);
|
|
370
|
-
// Link table (joined): add picks records of the other side (already linked excluded).
|
|
371
|
-
const linkField = parent && joined ? linkFieldOf(entity, parent.field) : null;
|
|
372
|
-
const linkCollection = linkField
|
|
373
|
-
? entity.fields[linkField]?.validation?.reference
|
|
374
|
-
: undefined;
|
|
375
|
-
const linkEntity = typeof linkCollection === 'string'
|
|
376
|
-
? getEntityByCollection(linkCollection)
|
|
377
|
-
: undefined;
|
|
378
|
-
if (linkCollection && !linkEntity) {
|
|
379
|
-
throw new Error(`EntityList: no entity defines collection "${String(linkCollection)}" (the other side of link table "${entity.collection}"). Define it with defineEntity().`);
|
|
380
|
-
}
|
|
381
|
-
const linkedIds = new Set(linkField
|
|
382
|
-
? rows.items.flatMap((row) => {
|
|
383
|
-
const linked = row[linkField];
|
|
384
|
-
return typeof linked === 'string' ? [linked] : [];
|
|
385
|
-
})
|
|
386
|
-
: []);
|
|
387
|
-
// Joined: every line shown. Standalone: filters and search on the rows as
|
|
388
|
-
// edited. The table shows them without their cell changes (overlaid as pending).
|
|
389
|
-
const baseById = new Map(rows.base.map((row) => [row.id, row]));
|
|
390
|
-
const addedIds = new Set(rows.edits.added.map((row) => row.id));
|
|
391
|
-
const shownIds = joined
|
|
392
|
-
? null
|
|
393
|
-
: new Set(applySearch(applyFilters(rows.items, filters, entity), searchQuery, entity).map((row) => row.id));
|
|
394
|
-
const data = shownIds ? rows.base.filter((row) => shownIds.has(row.id)) : rows.base;
|
|
395
|
-
const checkedIds = selectedIds.filter((id) => baseById.has(id));
|
|
396
|
-
const isEditing = editable &&
|
|
397
|
-
(rows.access.update || rows.extensionFields.some((field) => field.editable));
|
|
398
|
-
// Table edits (cells, paste, bulk apply, undo) → row values.
|
|
399
|
-
const applyPending = (next) => {
|
|
400
|
-
const previous = rows.edits.changes;
|
|
401
|
-
for (const id of new Set([...Object.keys(previous), ...Object.keys(next)])) {
|
|
402
|
-
const row = baseById.get(id);
|
|
403
|
-
if (!row)
|
|
404
|
-
continue;
|
|
405
|
-
const before = previous[id] ?? {};
|
|
406
|
-
const after = next[id] ?? {};
|
|
407
|
-
const patch = {};
|
|
408
|
-
for (const field of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
|
409
|
-
if (field in after) {
|
|
410
|
-
if (!(field in before) || before[field] !== after[field]) {
|
|
411
|
-
patch[field] = after[field];
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
else {
|
|
415
|
-
patch[field] = row[field];
|
|
416
|
-
}
|
|
417
|
-
}
|
|
418
|
-
if (Object.keys(patch).length > 0)
|
|
419
|
-
rows.update(id, patch);
|
|
420
|
-
}
|
|
421
|
-
};
|
|
422
|
-
const open = (id) => {
|
|
423
|
-
if (addedIds.has(id))
|
|
424
|
-
return; // not saved yet: no record to open
|
|
425
|
-
if (onClick)
|
|
426
|
-
onClick(id);
|
|
427
|
-
else
|
|
428
|
-
navigate(`${base}/${id}`);
|
|
429
|
-
};
|
|
430
|
-
const save = async () => {
|
|
431
|
-
setSaving(true);
|
|
432
|
-
setSaveError(null);
|
|
433
|
-
try {
|
|
434
|
-
await rows.save();
|
|
435
|
-
}
|
|
436
|
-
catch (error) {
|
|
437
|
-
// Not written: every edit stays pending. Invalid rows: the count (cells show each field).
|
|
438
|
-
setSaveError(error instanceof Error ? error.message : tCrud('form.saveFailed'));
|
|
439
|
-
}
|
|
440
|
-
finally {
|
|
441
|
-
setSaving(false);
|
|
442
|
-
}
|
|
443
|
-
};
|
|
444
|
-
const fieldsToShow = (entity.listFields || Object.keys(entity.fields)).filter((fieldName) => fieldName !== parent?.field);
|
|
445
|
-
// Extension columns: each extension entity's list fields the viewer may see, prefixed.
|
|
446
|
-
const extensionColumns = rows.extensionFields
|
|
447
|
-
.filter((field) => {
|
|
448
|
-
const ext = field.scope ? extend?.[field.scope] : undefined;
|
|
449
|
-
const unprefixed = field.name.slice((field.scope ?? '').length + 1);
|
|
450
|
-
return !ext?.entity.listFields || ext.entity.listFields.includes(unprefixed);
|
|
451
|
-
})
|
|
452
|
-
.map((field) => {
|
|
453
|
-
const { scope } = field;
|
|
454
|
-
const ext = scope ? extend?.[scope] : undefined;
|
|
455
|
-
if (!scope || !ext) {
|
|
456
|
-
throw new Error(`EntityList: extension field "${field.name}" has no extension "${scope}".`);
|
|
457
|
-
}
|
|
458
|
-
const unprefixed = field.name.slice(scope.length + 1);
|
|
459
|
-
const isNumeric = field.config.type === 'number' || field.config.type === 'range';
|
|
460
|
-
return {
|
|
461
|
-
key: field.name,
|
|
462
|
-
title: translateFieldLabel(field.name, field.config, t),
|
|
463
|
-
dataIndex: field.name,
|
|
464
|
-
sortable: true,
|
|
465
|
-
filterable: !joined,
|
|
466
|
-
align: isNumeric ? 'end' : 'start',
|
|
467
|
-
...(isEditing &&
|
|
468
|
-
field.editable && {
|
|
469
|
-
edit: cellEditFor(ext.entity, unprefixed, viewerRole, referenceData, t),
|
|
470
|
-
}),
|
|
471
|
-
render: (value, record) => formatValue(value, field.config, t, {
|
|
472
|
-
compact: true,
|
|
473
|
-
referenceData,
|
|
474
|
-
item: record,
|
|
475
|
-
}),
|
|
476
|
-
};
|
|
477
|
-
});
|
|
478
|
-
const columns = [
|
|
479
|
-
...entityColumns(entity, fieldsToShow, {
|
|
480
|
-
t,
|
|
481
|
-
viewerRole,
|
|
482
|
-
referenceData,
|
|
483
|
-
editing: isEditing && rows.access.update,
|
|
484
|
-
interactive: true,
|
|
485
|
-
}),
|
|
486
|
-
...extensionColumns,
|
|
487
|
-
...appColumns(extraColumns, (row) => ({
|
|
488
|
-
...row,
|
|
489
|
-
...rows.edits.changes[row.id],
|
|
490
|
-
})),
|
|
491
|
-
];
|
|
492
|
-
const entityName = t('name', { defaultValue: entity.name });
|
|
493
|
-
const showAdd = editable && rows.access.create;
|
|
494
|
-
const toolbarCells = 1 + (showAdd ? 1 : 0) + (actions ? 1 : 0);
|
|
495
|
-
return (_jsxs(_Fragment, { children: [!joined && !hideFilters && (_jsx(Section, { title: tCrud('filters.title', { entity: entityName }), collapsible: true, defaultOpen: hasActiveFilters, tone: tone, children: _jsx(EntityFilters, { entity: entity, data: rows.items, fieldsToFilter: fieldsToShow, viewerRole: viewerRole }) })), _jsx(Section, { title: rows.loading
|
|
496
|
-
? tCrud('results.title.fetching')
|
|
497
|
-
: tCrud('results.title.count', { count: data.length }), tone: tone, children: _jsxs(Stack, { children: [_jsxs(Stack, { direction: "row", gap: "tight", align: "center", className: "dndev-w-full", style: TOOLBAR_STYLES[joined ? toolbarCells - 1 : toolbarCells], children: [!joined && (_jsx(Input, { placeholder: tCrud('actions.searchPlaceholder'), value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), icon: Search, className: "dndev-w-full" })), _jsx(Button, { intent: "reload", variant: "outline", onClick: () => void rows.refresh(), disabled: rows.loading, display: "compact", "aria-label": tCrud('actions.refresh') }), showAdd &&
|
|
498
|
-
(joined ? (
|
|
499
|
-
// Joined: rows are added in place (picker or blank row), never a navigation.
|
|
500
|
-
_jsx(Button, { type: "button", intent: "add", display: "compact", onClick: () => (linkField ? setPicking(true) : rows.add([{}])), disabled: rows.loading, children: tCrud('addNew') })) : (_jsx(Button, { intent: "add", display: "compact", render: ({ children, ...renderProps }) => (_jsx(Link, { path: parent ? childCreatePath(base, parent) : `${base}/new`, ...renderProps, children: children })), children: tCrud('addNew') }))), actions && _jsx(ToolbarActions, { actions: actions })] }), rows.pendingCount > 0 && (_jsxs(Stack, { direction: "row", gap: "tight", align: "center", wrap: "wrap", children: [_jsx(Text, { level: "body", children: tCrud('bulkEdit.pending', { count: rows.pendingCount }) }), !joined && (_jsx(Button, { type: "button", intent: "save", display: "compact", onClick: () => void save(), disabled: saving, children: saving ? tCrud('form.saving') : tCrud('actions.save') })), _jsx(Button, { type: "button", icon: Undo2, variant: "outline", display: "compact", onClick: () => {
|
|
501
|
-
rows.discard();
|
|
502
|
-
setSaveError(null);
|
|
503
|
-
}, disabled: saving, children: tCrud('bulkEdit.discard') })] })), saveError && _jsx(Alert, { variant: "error", title: saveError }), editable &&
|
|
504
|
-
checkedIds.length > 0 &&
|
|
505
|
-
(rows.access.delete || checkedIds.every((id) => addedIds.has(id))) && (_jsx(Stack, { direction: "row", gap: "tight", align: "center", wrap: "wrap", children: _jsx(Button, { type: "button", variant: "outline", intent: "delete", display: "compact", onClick: () => {
|
|
506
|
-
rows.remove(checkedIds);
|
|
507
|
-
setSelectedIds([]);
|
|
508
|
-
}, children: tCrud('bulkEdit.deleteSelected', { count: checkedIds.length }) }) })), _jsx(DataTable, { data: data, columns: columns, sortable: true, searchable: false, pagination: !joined, loading: rows.loading, onRowClick: (row) => open(row.id), selectable: editable, getRowId: (row) => row.id, onSelect: (selected) => setSelectedIds(selected.map((row) => row.id)), openLabel: tCrud('actions.open'), onRowOpen: (row) => open(row.id),
|
|
509
|
-
// Fields breaking the entity's rules, checked on every change
|
|
510
|
-
cellErrors: rows.errors, ...(isEditing && {
|
|
511
|
-
editable: true,
|
|
512
|
-
pendingChanges: rows.edits.changes,
|
|
513
|
-
onPendingChange: applyPending,
|
|
514
|
-
editLabels: {
|
|
515
|
-
selected: tCrud('bulkEdit.selected'),
|
|
516
|
-
field: tCrud('bulkEdit.field'),
|
|
517
|
-
value: tCrud('bulkEdit.value'),
|
|
518
|
-
apply: tCrud('bulkEdit.apply'),
|
|
519
|
-
},
|
|
520
|
-
}), showingLabel: tCrud('pagination.showing'), paginationPreviousLabel: tCrud('pagination.previous'), paginationNextLabel: tCrud('pagination.next'), paginationItemsPerPagePlaceholder: tCrud('pagination.itemsPerPagePlaceholder'), pageSize: pageSize, onPageSizeChange: setPageSize, exportable: !joined && exportable, exportFilename: `${entity.collection}-export`, exportLabel: tCrud('export') })] }) }), picking && linkField && linkEntity && (_jsx(Suspense, { fallback: null, children: _jsx(ChildRowsPicker, { entity: linkEntity, viewerRole: viewerRole, excludedIds: linkedIds, onPick: (ids) => rows.add(ids.map((id) => ({ [linkField]: id }))), onClose: () => setPicking(false) }) }))] }));
|
|
521
|
-
}
|
|
1
|
+
"use client";import{Search as he,Undo2 as ye}from"lucide-react";import{Suspense as Ae,lazy as Ne,useCallback as Ve,useState as v}from"react";import{DataTable as be,Button as k,Stack as T,ActionButton as Me,Section as K,Input as we,Alert as ve,Text as me}from"@donotdev/components";import{describeEntity as Qe,getEntityByCollection as _e,useTranslation as W}from"@donotdev/core";import{Link as ke,useNavigate as Se}from"../../routing/index.js";import{useAuthSafe as Ee}from"../../utils/useAuthSafe.js";import{cellEditFor as Ce}from"./cellEditFor.js";import{assertEntityParent as He,childCreatePath as Pe}from"./entityParent.js";import{isCrudModuleAvailable as Je,translateFieldLabel as Le,useCrud as Ue,useCrudFilters as Re,useCrudList as Ye,useCrudPageSize as Te,EntityFilters as xe,formatValue as Fe,useReferenceResolver as De,useChildRows as Ge,useJoinedForm as Ke,applyFilters as We,applySearch as Xe}from"../crudImports.js";import{Fragment as Be,jsx as n,jsxs as z}from"react/jsx-runtime";var Ze=Ne(()=>import("./ChildRowsPicker.js")),Ie=[0,1,2,3,4].map(t=>({display:"grid",gridTemplateColumns:["1fr",...Array(t).fill("auto")].join(" ")}));function Oe(t,p,o){let{t:b,viewerRole:g,referenceData:P,editing:m,interactive:f}=o;return p.map(h=>{let y=t.fields[h];if(!y)return null;let x=Le(h,y,b),S=y.type;return{key:h,title:x,dataIndex:h,sortable:f,filterable:f,align:S==="number"||S==="range"?"end":"start",...m&&{edit:Ce(t,h,g,P,b)},render:(l,a)=>Fe(l,y,b,{compact:!0,referenceData:P,item:a})}}).filter(Boolean)}function je(t,p){return(t??[]).map(o=>({key:o.key,title:o.title,align:o.align??"start",render:(b,g)=>o.render(p(g))}))}function ze({actions:t}){return n(T,{direction:"row",gap:"tight",align:"center",children:t})}function pt(t){if(!Je)return null;let{entity:p,parent:o,preview:b,tone:g,editable:P=!0}=t;o&&He(p,o);let m=Ke(p,o);if(o&&o.value===null)return n(qe,{entity:p,tone:g});let f=o&&o.value!==null?{field:o.field,value:o.value}:void 0;return!b&&(t.extend||m&&f&&P)?n(nt,{...t,parent:f}):n(et,{...t,parent:f})}function qe({entity:t,tone:p}){let{t:o}=W([t.namespace,"crud"]);return n(K,{tone:p,children:n(me,{level:"body",children:o("crud:childRows.createFirst",{entity:o("name",{defaultValue:t.name})})})})}function et({entity:t,basePath:p,onClick:o,hideFilters:b=!1,pagination:g="auto",pageSize:P,queryOptions:m,exportable:f=!0,editable:h=!0,parent:y,preview:x,tone:S,extraColumns:X,actions:F}){let l=!!x,a=Se(),u=p??`/${t.collection}`,M=De(t,!l),[Z,ce]=v(1),{pageSize:Q,setPageSize:de}=Te({collection:t.collection,...P!=null&&{defaultPageSize:P}}),[_,ue]=v(""),{filters:pe}=Re({collection:t.collection}),q=Object.keys(pe).length>0,{data:ge,items:ee,processed:H,loading:te,mutate:ne,effectiveMode:J}=Ye(t,{enabled:!l,pagination:g,searchQuery:_,...(m||y)&&{queryOptions:y?{...m,where:[...m?.where??[],{field:y.field,operator:"==",value:y.value}]}:m},...(g==="server"||g==="auto")&&{page:Z,pageSize:Q}}),r=l?x:H,L=l?!1:te,{bulk:E}=Ue(t),D=h&&!l,A=Ee("userRole"),[I,N]=v({}),[ie,U]=v([]),ae=new Set(r.map(i=>i.id)),w=ie.filter(i=>ae.has(i)),[B,oe]=v(!1),[Y,O]=v(0),G=Object.values(I).reduce((i,d)=>i+Object.keys(d).length,0),fe=async()=>{oe(!0),O(0);try{let{failed:i}=await E({updates:Object.entries(I).map(([R,$e])=>({id:R,patch:$e}))}),d=new Set(i.map(R=>R.id));N(Object.fromEntries(Object.entries(I).filter(([R])=>d.has(R)))),O(d.size)}catch{O(Object.keys(I).length)}finally{oe(!1)}},{t:s}=W("crud"),{t:se}=W([t.namespace,"crud"]),le=async()=>{await ne()},re=Ve(i=>{l||(o?o(i):a(`${u}/${i}`))},[u,a,o,l]),e=async()=>{if(l)return;O(0);let{failed:i}=await E({deletes:w}),d=new Set(i.map(R=>R.id));U(w.filter(R=>d.has(R))),O(d.size)},c=(t.listFields||Object.keys(t.fields)).filter(i=>i!==y?.field),V=[...Oe(t,c,{t:se,viewerRole:A,referenceData:M,editing:D,interactive:!l}),...je(X,i=>({...i,...I[i.id]}))],$=se("name",{defaultValue:t.name}),j=r.length;return z(Be,{children:[!b&&n(K,{title:s("filters.title",{entity:$}),collapsible:!0,defaultOpen:q,tone:S,children:n(xe,{entity:t,data:ee,fieldsToFilter:c,viewerRole:A})}),n(K,{title:L?s("results.title.fetching"):s("results.title.count",{count:j}),tone:S,children:z(T,{children:[z(T,{direction:"row",gap:"tight",align:"center",className:"dndev-w-full",style:Ie[1+(h?1:0)+(F?1:0)],children:[n(we,{placeholder:s("actions.searchPlaceholder"),value:_,onChange:i=>ue(i.target.value),icon:he,className:"dndev-w-full",disabled:l}),n(k,{intent:"reload",variant:"outline",onClick:le,disabled:l||L,display:"compact","aria-label":s("actions.refresh")}),h?l?n(k,{intent:"add",display:"compact",disabled:!0,children:s("addNew")}):n(k,{intent:"add",display:"compact",render:({children:i,...d})=>n(ke,{path:y?Pe(u,y):`${u}/new`,...d,children:i}),children:s("addNew")}):null,F&&n(ze,{actions:F})]}),D&&G>0&&z(T,{direction:"row",gap:"tight",align:"center",wrap:"wrap",children:[n(me,{level:"body",children:s("bulkEdit.pending",{count:G})}),n(k,{intent:"save",display:"compact",onClick:fe,disabled:B,children:s(B?"form.saving":"actions.save")}),n(k,{icon:ye,variant:"outline",display:"compact",onClick:()=>{N({}),O(0)},disabled:B,children:s("bulkEdit.discard")})]}),Y>0&&n(ve,{variant:"error",title:s("bulkEdit.failed",{count:Y})}),!l&&h&&w.length>0&&n(T,{direction:"row",gap:"tight",align:"center",wrap:"wrap",children:n(Me,{action:e,confirmTitle:s("delete.titleSelected",{count:w.length}),confirmText:s("delete.confirmSelected",{count:w.length}),confirmLabel:s("actions.delete"),cancelLabel:s("actions.cancel"),variant:"outline",intent:"delete",display:"compact",children:s("bulkEdit.deleteSelected",{count:w.length})})}),n(be,{data:r,columns:V,sortable:!l,searchable:!1,pagination:!0,loading:L,onRowClick:l?void 0:i=>re(i.id),selectable:!l&&h,getRowId:i=>i.id,onSelect:i=>U(i.map(d=>d.id)),openLabel:s("actions.open"),...!l&&(o?{onRowOpen:i=>o(i.id)}:{getRowHref:i=>`${u}/${i.id}`}),...D&&{editable:!0,pendingChanges:I,onPendingChange:N,editLabels:{selected:s("bulkEdit.selected"),field:s("bulkEdit.field"),value:s("bulkEdit.value"),apply:s("bulkEdit.apply")}},showingLabel:s("pagination.showing"),paginationPreviousLabel:s("pagination.previous"),paginationNextLabel:s("pagination.next"),paginationItemsPerPagePlaceholder:s("pagination.itemsPerPagePlaceholder"),pageSize:Q,onPageSizeChange:de,...!l&&J==="server"&&{currentPage:Z,total:ge?.total,onPageChange:ce},exportable:l?!1:f,exportFilename:`${t.collection}-export`,exportLabel:s("export")})]})})]})}function tt(t,p){let o=Object.entries(Qe(t).fields).filter(([b,{value:g}])=>b!==p&&g.kind==="ref"&&g.ref!==void 0);return o.length===1?o[0][0]:null}function nt({entity:t,basePath:p,onClick:o,hideFilters:b=!1,pageSize:g,exportable:P=!0,editable:m=!0,parent:f,tone:h,extraColumns:y,actions:x,extend:S}){let X=Se(),F=p??`/${t.collection}`,l=Ee("userRole"),a=Ge(t,f,{viewerRole:l,...S&&{extend:S}}),u=a.joined&&m,M=De(t),{pageSize:Z,setPageSize:ce}=Te({collection:t.collection,...g!=null&&{defaultPageSize:g}}),[Q,de]=v(""),{filters:_}=Re({collection:t.collection}),ue=Object.keys(_).length>0,[pe,q]=v([]),[ge,ee]=v(!1),[H,te]=v(!1),[ne,J]=v(null),{t:r}=W("crud"),{t:L}=W([t.namespace,"crud"]),E=f&&u?tt(t,f.field):null,D=E?t.fields[E]?.validation?.reference:void 0,A=typeof D=="string"?_e(D):void 0;if(D&&!A)throw new Error(`EntityList: no entity defines collection "${String(D)}" (the other side of link table "${t.collection}"). Define it with defineEntity().`);let I=new Set(E?a.items.flatMap(e=>{let c=e[E];return typeof c=="string"?[c]:[]}):[]),N=new Map(a.base.map(e=>[e.id,e])),ie=new Set(a.edits.added.map(e=>e.id)),U=u?null:new Set(Xe(We(a.items,_,t),Q,t).map(e=>e.id)),ae=U?a.base.filter(e=>U.has(e.id)):a.base,w=pe.filter(e=>N.has(e)),B=m&&(a.access.update||a.extensionFields.some(e=>e.editable)),oe=e=>{let c=a.edits.changes;for(let C of new Set([...Object.keys(c),...Object.keys(e)])){let V=N.get(C);if(!V)continue;let $=c[C]??{},j=e[C]??{},i={};for(let d of new Set([...Object.keys($),...Object.keys(j)]))d in j?(!(d in $)||$[d]!==j[d])&&(i[d]=j[d]):i[d]=V[d];Object.keys(i).length>0&&a.update(C,i)}},Y=e=>{ie.has(e)||(o?o(e):X(`${F}/${e}`))},O=async()=>{te(!0),J(null);try{await a.save()}catch(e){J(e instanceof Error?e.message:r("form.saveFailed"))}finally{te(!1)}},G=(t.listFields||Object.keys(t.fields)).filter(e=>e!==f?.field),fe=a.extensionFields.filter(e=>{let c=e.scope?S?.[e.scope]:void 0,C=e.name.slice((e.scope??"").length+1);return!c?.entity.listFields||c.entity.listFields.includes(C)}).map(e=>{let{scope:c}=e,C=c?S?.[c]:void 0;if(!c||!C)throw new Error(`EntityList: extension field "${e.name}" has no extension "${c}".`);let V=e.name.slice(c.length+1),$=e.config.type==="number"||e.config.type==="range";return{key:e.name,title:Le(e.name,e.config,L),dataIndex:e.name,sortable:!0,filterable:!u,align:$?"end":"start",...B&&e.editable&&{edit:Ce(C.entity,V,l,M,L)},render:(j,i)=>Fe(j,e.config,L,{compact:!0,referenceData:M,item:i})}}),s=[...Oe(t,G,{t:L,viewerRole:l,referenceData:M,editing:B&&a.access.update,interactive:!0}),...fe,...je(y,e=>({...e,...a.edits.changes[e.id]}))],se=L("name",{defaultValue:t.name}),le=m&&a.access.create,re=1+(le?1:0)+(x?1:0);return z(Be,{children:[!u&&!b&&n(K,{title:r("filters.title",{entity:se}),collapsible:!0,defaultOpen:ue,tone:h,children:n(xe,{entity:t,data:a.items,fieldsToFilter:G,viewerRole:l})}),n(K,{title:a.loading?r("results.title.fetching"):r("results.title.count",{count:ae.length}),tone:h,children:z(T,{children:[z(T,{direction:"row",gap:"tight",align:"center",className:"dndev-w-full",style:Ie[u?re-1:re],children:[!u&&n(we,{placeholder:r("actions.searchPlaceholder"),value:Q,onChange:e=>de(e.target.value),icon:he,className:"dndev-w-full"}),n(k,{intent:"reload",variant:"outline",onClick:()=>{a.refresh()},disabled:a.loading,display:"compact","aria-label":r("actions.refresh")}),le&&(u?n(k,{type:"button",intent:"add",display:"compact",onClick:()=>E?ee(!0):a.add([{}]),disabled:a.loading,children:r("addNew")}):n(k,{intent:"add",display:"compact",render:({children:e,...c})=>n(ke,{path:f?Pe(F,f):`${F}/new`,...c,children:e}),children:r("addNew")})),x&&n(ze,{actions:x})]}),a.pendingCount>0&&z(T,{direction:"row",gap:"tight",align:"center",wrap:"wrap",children:[n(me,{level:"body",children:r("bulkEdit.pending",{count:a.pendingCount})}),!u&&n(k,{type:"button",intent:"save",display:"compact",onClick:()=>{O()},disabled:H,children:r(H?"form.saving":"actions.save")}),n(k,{type:"button",icon:ye,variant:"outline",display:"compact",onClick:()=>{a.discard(),J(null)},disabled:H,children:r("bulkEdit.discard")})]}),ne&&n(ve,{variant:"error",title:ne}),m&&w.length>0&&(a.access.delete||w.every(e=>ie.has(e)))&&n(T,{direction:"row",gap:"tight",align:"center",wrap:"wrap",children:n(k,{type:"button",variant:"outline",intent:"delete",display:"compact",onClick:()=>{a.remove(w),q([])},children:r("bulkEdit.deleteSelected",{count:w.length})})}),n(be,{data:ae,columns:s,sortable:!0,searchable:!1,pagination:!u,loading:a.loading,onRowClick:e=>Y(e.id),selectable:m,getRowId:e=>e.id,onSelect:e=>q(e.map(c=>c.id)),openLabel:r("actions.open"),onRowOpen:e=>Y(e.id),cellErrors:a.errors,...B&&{editable:!0,pendingChanges:a.edits.changes,onPendingChange:oe,editLabels:{selected:r("bulkEdit.selected"),field:r("bulkEdit.field"),value:r("bulkEdit.value"),apply:r("bulkEdit.apply")}},showingLabel:r("pagination.showing"),paginationPreviousLabel:r("pagination.previous"),paginationNextLabel:r("pagination.next"),paginationItemsPerPagePlaceholder:r("pagination.itemsPerPagePlaceholder"),pageSize:Z,onPageSizeChange:ce,exportable:!u&&P,exportFilename:`${t.collection}-export`,exportLabel:r("export")})]})}),ge&&E&&A&&n(Ae,{fallback:null,children:n(Ze,{entity:A,viewerRole:l,excludedIds:I,onPick:e=>a.add(e.map(c=>({[E]:c}))),onClose:()=>ee(!1)})})]})}export{pt as EntityList};
|
|
@@ -1,87 +1 @@
|
|
|
1
|
-
|
|
2
|
-
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
-
// packages/ui/src/crud/components/EntityRecommendations.tsx
|
|
4
|
-
/**
|
|
5
|
-
* @fileoverview Reusable recommendations section for related entities
|
|
6
|
-
* @description Fetches and displays related entity cards in a grid.
|
|
7
|
-
* Caller defines "related by what" via queryOptions.
|
|
8
|
-
*
|
|
9
|
-
* @version 0.1.0
|
|
10
|
-
* @since 0.0.15
|
|
11
|
-
* @author AMBROISE PARK Consulting
|
|
12
|
-
*/
|
|
13
|
-
import { Card, Section, Skeleton, Stack } from '@donotdev/components';
|
|
14
|
-
import { useTranslation, useBreakpoint } from '@donotdev/core';
|
|
15
|
-
import { isCrudModuleAvailable, useCrudCardList } from '../crudImports';
|
|
16
|
-
import { CrudCard } from './CrudCardLink';
|
|
17
|
-
/**
|
|
18
|
-
* Displays a grid of related entity cards.
|
|
19
|
-
* Uses useCrudCardList (listCard schema) so cards render identically to EntityCardList.
|
|
20
|
-
*
|
|
21
|
-
* **Title resolution (i18n):**
|
|
22
|
-
* 1. `title` prop — if provided, used as-is (pre-translated string)
|
|
23
|
-
* 2. `recommendations.title` in entity namespace — consumer override
|
|
24
|
-
* 3. `recommendations.title` in `crud` namespace — framework default ("You may also like")
|
|
25
|
-
*
|
|
26
|
-
* Consumers override by adding to their entity translation file:
|
|
27
|
-
* ```json
|
|
28
|
-
* { "recommendations": { "title": "Similar Apartments" } }
|
|
29
|
-
* ```
|
|
30
|
-
*
|
|
31
|
-
* @example
|
|
32
|
-
* ```tsx
|
|
33
|
-
* // Auto-translated title (entity namespace → crud fallback)
|
|
34
|
-
* <EntityRecommendations
|
|
35
|
-
* entity={apartmentEntity}
|
|
36
|
-
* queryOptions={{
|
|
37
|
-
* where: [
|
|
38
|
-
* { field: 'district_code', operator: 'eq', value: current.district_code },
|
|
39
|
-
* { field: 'id', operator: 'neq', value: current.id },
|
|
40
|
-
* ],
|
|
41
|
-
* limit: 3,
|
|
42
|
-
* }}
|
|
43
|
-
* />
|
|
44
|
-
*
|
|
45
|
-
* // Explicit title override
|
|
46
|
-
* <EntityRecommendations
|
|
47
|
-
* entity={apartmentEntity}
|
|
48
|
-
* title="Nearby Apartments"
|
|
49
|
-
* queryOptions={...}
|
|
50
|
-
* />
|
|
51
|
-
* ```
|
|
52
|
-
*
|
|
53
|
-
* @version 0.1.0
|
|
54
|
-
* @since 0.0.15
|
|
55
|
-
* @author AMBROISE PARK Consulting
|
|
56
|
-
*/
|
|
57
|
-
export function EntityRecommendations({ entity, queryOptions, title, basePath, cols = [1, 1, 3, 3], tone, className, }) {
|
|
58
|
-
// Safe guard: isCrudModuleAvailable is a module-level constant (immutable after load).
|
|
59
|
-
if (!isCrudModuleAvailable)
|
|
60
|
-
return null;
|
|
61
|
-
const { t } = useTranslation([entity.namespace, 'crud']);
|
|
62
|
-
const { items, loading } = useCrudCardList(entity, {
|
|
63
|
-
queryOptions,
|
|
64
|
-
});
|
|
65
|
-
// Must be called before any early return to satisfy Rules of Hooks.
|
|
66
|
-
const bp = useBreakpoint('current');
|
|
67
|
-
if (!loading && items.length === 0) {
|
|
68
|
-
return null;
|
|
69
|
-
}
|
|
70
|
-
const resolvedBasePath = basePath ?? `/${entity.collection}`;
|
|
71
|
-
const resolvedTitle = title ?? t('recommendations.title');
|
|
72
|
-
const bpIndex = {
|
|
73
|
-
mobile: 0,
|
|
74
|
-
tablet: 1,
|
|
75
|
-
laptop: 2,
|
|
76
|
-
desktop: 3,
|
|
77
|
-
};
|
|
78
|
-
const currentCols = (Array.isArray(cols)
|
|
79
|
-
? cols[bpIndex[bp] ?? 3]
|
|
80
|
-
: typeof cols === 'number'
|
|
81
|
-
? cols
|
|
82
|
-
: 3) ?? 1;
|
|
83
|
-
const skeletonCount = (typeof currentCols === 'number' ? currentCols : 3) * 3;
|
|
84
|
-
return (_jsx(Section, { title: resolvedTitle, gridCols: cols, tone: tone, className: className, children: loading
|
|
85
|
-
? Array.from({ length: skeletonCount }, (_, i) => (_jsx(Card, { title: _jsx(Skeleton, { width: "60%" }), subtitle: _jsx(Skeleton, { width: "40%" }), content: _jsxs(Stack, { direction: "column", gap: "tight", children: [_jsx(Skeleton, { width: "80%" }), _jsx(Skeleton, { width: "50%" })] }), elevated: true }, i)))
|
|
86
|
-
: items.map((item) => (_jsx(CrudCard, { item: item, entity: entity, detailHref: `${resolvedBasePath}/${item.id}` }, item.id))) }));
|
|
87
|
-
}
|
|
1
|
+
"use client";import{Card as g,Section as v,Skeleton as r,Stack as S}from"@donotdev/components";import{useTranslation as w,useBreakpoint as A}from"@donotdev/core";import{isCrudModuleAvailable as R,useCrudCardList as E}from"../crudImports.js";import{CrudCard as P}from"./CrudCardLink.js";import{jsx as t,jsxs as $}from"react/jsx-runtime";function I({entity:o,queryOptions:a,title:l,basePath:m,cols:e=[1,1,3,3],tone:c,className:u}){if(!R)return null;let{t:p}=w([o.namespace,"crud"]),{items:i,loading:d}=E(o,{queryOptions:a}),f=A("current");if(!d&&i.length===0)return null;let b=m??`/${o.collection}`,y=l??p("recommendations.title"),C={mobile:0,tablet:1,laptop:2,desktop:3},s=(Array.isArray(e)?e[C[f]??3]:typeof e=="number"?e:3)??1,h=(typeof s=="number"?s:3)*3;return t(v,{title:y,gridCols:e,tone:c,className:u,children:d?Array.from({length:h},(n,k)=>t(g,{title:t(r,{width:"60%"}),subtitle:t(r,{width:"40%"}),content:$(S,{direction:"column",gap:"tight",children:[t(r,{width:"80%"}),t(r,{width:"50%"})]}),elevated:!0},k)):i.map(n=>t(P,{item:n,entity:o,detailHref:`${b}/${n.id}`},n.id))})}export{I as EntityRecommendations};
|