@rebasepro/cms 0.29.0 → 0.29.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/collection_editor/serializable_types.d.ts +2 -0
- package/dist/collection_editor/ui/collection_editor/CollectionRelationsTab.d.ts +1 -1
- package/dist/components/CollectionPanel.js +22 -13
- package/dist/components/CollectionPanel.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +39 -14
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +11 -0
- package/dist/components/CollectionViewBinding/CollectionViewContent.js +19 -2
- package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/SlotValue.js.map +1 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +19 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.js +18 -7
- package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/components/HomePage/ContentHomePage.js +2 -3
- package/dist/components/HomePage/ContentHomePage.js.map +1 -1
- package/dist/components/RecordForm.d.ts +25 -4
- package/dist/components/RecordForm.js +21 -3
- package/dist/components/RecordForm.js.map +1 -1
- package/dist/components/RelationSelector.js.map +1 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +13 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js +19 -3
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
- package/dist/components/history/EntityHistoryEntry.js.map +1 -1
- package/dist/data_import/utils/save_entities.d.ts +10 -2
- package/dist/data_import/utils/save_entities.js.map +1 -1
- package/dist/editor/markdown.d.ts +10 -0
- package/dist/editor/markdown.js.map +1 -1
- package/dist/form/PropertyFieldBinding.js +4 -2
- package/dist/form/PropertyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
- package/dist/hooks/useBuildSidePanel.d.ts +10 -0
- package/dist/hooks/useBuildSidePanel.js +43 -4
- package/dist/hooks/useBuildSidePanel.js.map +1 -1
- package/dist/hooks/useResolvedNavigationFrom.d.ts +14 -2
- package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +2 -2
- package/dist/mcp_view/app_modules.js +4 -2
- package/dist/mcp_view/app_modules.js.map +1 -1
- package/dist/mcp_view/index.d.ts +1 -1
- package/dist/mcp_view/index.js +2 -2
- package/dist/mcp_view/index.js.map +1 -1
- package/dist/mcp_view/payload.js +7 -2
- package/dist/mcp_view/payload.js.map +1 -1
- package/dist/mcp_view/screen.js +1 -1
- package/dist/mcp_view/screen.js.map +1 -1
- package/dist/mcp_view/tool_driver.d.ts +25 -6
- package/dist/mcp_view/tool_driver.js +73 -35
- package/dist/mcp_view/tool_driver.js.map +1 -1
- package/dist/preview/compact_text.d.ts +1 -1
- package/dist/preview/compact_text.js.map +1 -1
- package/dist/selection/resolve_selection.d.ts +10 -2
- package/dist/selection/resolve_selection.js.map +1 -1
- package/dist/util/property_utils.d.ts +2 -2
- package/dist/util/property_utils.js.map +1 -1
- package/package.json +9 -9
|
@@ -225,6 +225,8 @@ export interface SerializableDateProperty extends SerializableBaseProperty {
|
|
|
225
225
|
mode?: "date" | "date_time";
|
|
226
226
|
timezone?: string;
|
|
227
227
|
autoValue?: "on_create" | "on_update";
|
|
228
|
+
/** A calendar day that is part of the primary key, as `DateProperty.isId`. */
|
|
229
|
+
isId?: "manual" | true;
|
|
228
230
|
}
|
|
229
231
|
/** JSON-serializable `GeopointProperty`. */
|
|
230
232
|
export interface SerializableGeopointProperty extends SerializableBaseProperty {
|
|
@@ -5,7 +5,7 @@ import { Relation, RelationKind, JoinStep, OnAction } from "@rebasepro/types";
|
|
|
5
5
|
*
|
|
6
6
|
* Deliberately not `Partial<Relation>`: `Relation` is a union, and a partial of
|
|
7
7
|
* a union distributes into "partial of each member", so a draft that has picked
|
|
8
|
-
* `kind: "manyToMany"` but not yet a junction table does not typecheck as
|
|
8
|
+
* `kind: "manyToMany"` but not yet a junction table does not typecheck as one
|
|
9
9
|
* member. A form in progress is not a relation — it becomes one on save.
|
|
10
10
|
*/
|
|
11
11
|
export type RelationDraft = {
|
|
@@ -4,11 +4,12 @@ import { useUrlController } from "../hooks/navigation/contexts/UrlContext.js";
|
|
|
4
4
|
import { CollectionAddButton } from "./CollectionViewBinding/CollectionAddButton.js";
|
|
5
5
|
import { CollectionSearchBar, CollectionToolbar, CollectionViewModeToggle } from "./CollectionViewBinding/CollectionToolbar.js";
|
|
6
6
|
import { ROW_ACTIONS_FIELD, RowActionsContext } from "./CollectionViewBinding/RowActions.js";
|
|
7
|
+
import { ViewTitleReportContext } from "./CollectionViewBinding/CollectionViewContent.js";
|
|
7
8
|
import { CollectionViewBinding } from "./CollectionViewBinding/CollectionViewBinding.js";
|
|
8
9
|
import { CollectionsScopeContext, isRegistered } from "./CollectionsScopeContext.js";
|
|
9
10
|
import { CollectionsProvider } from "./CollectionsProvider.js";
|
|
10
11
|
import { collectionPropOf } from "./collection_prop.js";
|
|
11
|
-
import { useContext, useMemo, useRef } from "react";
|
|
12
|
+
import { useContext, useMemo, useRef, useState } from "react";
|
|
12
13
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
13
14
|
import { deepEqual } from "fast-equals";
|
|
14
15
|
import { CircularProgressCenter, Typography, cls } from "@rebasepro/ui";
|
|
@@ -63,25 +64,33 @@ function CollectionPanelInner({ mergedCollection, overrides, path, title, viewMo
|
|
|
63
64
|
mergedCollection.slug,
|
|
64
65
|
rowActions
|
|
65
66
|
]);
|
|
67
|
+
const [viewDrawsTitle, setViewDrawsTitle] = useState(false);
|
|
68
|
+
const titleReport = useMemo(() => ({
|
|
69
|
+
path: path ?? mergedCollection.slug,
|
|
70
|
+
onViewDrawsTitle: setViewDrawsTitle
|
|
71
|
+
}), [path, mergedCollection.slug]);
|
|
66
72
|
return /* @__PURE__ */ jsxs("div", {
|
|
67
73
|
className: cls("flex flex-col min-h-0", className),
|
|
68
|
-
children: [title !== false && /* @__PURE__ */ jsx(Typography, {
|
|
74
|
+
children: [title !== false && !viewDrawsTitle && /* @__PURE__ */ jsx(Typography, {
|
|
69
75
|
variant: "subtitle2",
|
|
70
76
|
className: "font-semibold mb-2 text-surface-700 dark:text-surface-300",
|
|
71
77
|
children: title ?? mergedCollection.name
|
|
72
78
|
}), /* @__PURE__ */ jsx(RowActionsContext.Provider, {
|
|
73
79
|
value: rowActionsScope,
|
|
74
|
-
children: /* @__PURE__ */ jsx(
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
80
|
+
children: /* @__PURE__ */ jsx(ViewTitleReportContext.Provider, {
|
|
81
|
+
value: titleReport,
|
|
82
|
+
children: /* @__PURE__ */ jsx(ResolvedCollectionView, {
|
|
83
|
+
...mergedCollection,
|
|
84
|
+
collectionOverrides: overrides,
|
|
85
|
+
...highlightedIds !== void 0 && { highlightedIds },
|
|
86
|
+
...viewMode && { viewMode },
|
|
87
|
+
...fields && { fields },
|
|
88
|
+
...toolbarNode !== void 0 && { toolbar: toolbarNode },
|
|
89
|
+
...onRowClick && { onRowClick },
|
|
90
|
+
...title !== void 0 && { title },
|
|
91
|
+
path,
|
|
92
|
+
updateUrl
|
|
93
|
+
})
|
|
85
94
|
})
|
|
86
95
|
})]
|
|
87
96
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CollectionPanel.js","names":[],"sources":["../../src/components/CollectionPanel.tsx"],"sourcesContent":["\nimport type { ViewMode, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { FilterValues } from \"@rebasepro/types\";\nimport React, { useContext, useMemo, useRef } from \"react\";\nimport { deepEqual } from \"fast-equals\";\nimport { CollectionViewBinding } from \"./CollectionViewBinding/CollectionViewBinding\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useNavigationStateController } from \"../hooks/navigation/contexts/NavigationStateContext\";\nimport { useUrlController } from \"../hooks/navigation/contexts/UrlContext\";\nimport { CircularProgressCenter, cls, Typography } from \"@rebasepro/ui\";\nimport { useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { CollectionsScopeContext, isRegistered } from \"./CollectionsScopeContext\";\nimport { CollectionsProvider } from \"./CollectionsProvider\";\nimport { collectionPropOf } from \"./collection_prop\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { ROW_ACTIONS_FIELD, RowActionsContext, type RowActionsRenderer } from \"./CollectionViewBinding/RowActions\";\nimport {\n CollectionSearchBar,\n CollectionToolbar,\n CollectionViewModeToggle\n} from \"./CollectionViewBinding/CollectionToolbar\";\nimport { CollectionAddButton } from \"./CollectionViewBinding/CollectionAddButton\";\n\n/**\n * Props for the {@link CollectionPanel} component.\n *\n * This is a high-level, consumer-friendly wrapper around {@link CollectionViewBinding}\n * designed for embedding collection views inside custom pages (home pages,\n * dashboards, entity detail views, etc.).\n *\n * Name the collection — `collection=\"orders\"`, one registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above — or hand it over as a\n * value, `collection={ordersCollection}`. All other props are optional overrides that take precedence\n * over the collection's default configuration.\n *\n * @group Components\n */\nexport type CollectionPanelProps = CollectionPanelOptions & ({\n /**\n * The collection to display: its name (`\"orders\"`), registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above, or the collection\n * as a value — a `defineCollection` config or a resolved collection.\n * Handed over as a value where no CMS navigation is mounted above, the\n * panel brings its own {@link CollectionsProvider} for it, so it works\n * anywhere under `<Rebase>` and a router.\n */\n collection: AdminCollection | string;\n /**\n * Where the rows live, where that is not the collection's name: a\n * subcollection's full path, `posts/p1/comments`.\n */\n path?: string;\n} | {\n /**\n * @deprecated Name the collection with `collection`:\n * `<CollectionPanel collection=\"orders\"/>`. It warns once.\n */\n path: string;\n collection?: undefined;\n});\n\n/**\n * The display options of a {@link CollectionPanel}.\n *\n * @group Components\n */\nexport type CollectionPanelOptions = {\n\n /**\n * Optional title displayed above the collection.\n * Set to `false` to hide the title entirely.\n * Defaults to the collection's `name`.\n */\n title?: string | false;\n\n /**\n * The view mode the panel opens in, over the collection's default, the\n * one in the URL and the one the person last picked. They can still\n * switch.\n */\n viewMode?: ViewMode;\n\n /**\n * @deprecated Use {@link orderBy}: `orderBy=\"field:desc\"`. It warns once.\n */\n sort?: [string, \"asc\" | \"desc\"];\n\n /**\n * The order the rows open in, as `\"field:desc\"` or `[\"field\", \"desc\"]`.\n * The person can still sort by another column.\n */\n orderBy?: `${string}:asc` | `${string}:desc` | readonly [string, \"asc\" | \"desc\"];\n\n /**\n * Your own JSX on every row, card and kanban card — an \"Approve\" button,\n * a \"Ship\" — handed the row as the server sends it and its id:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" rowActions={(row, id) =>\n * <Button size=\"small\" onClick={() => update(\"orders\", id, { status: \"shipped\" })}>Ship</Button>}/>\n * ```\n *\n * In the table it is the last column; on a list row, a card and a kanban\n * card it sits beside the collection's own actions. A click on it does\n * not open the record.\n */\n rowActions?: RowActionsRenderer;\n\n /**\n * Maximum number of entities to display.\n */\n limit?: number;\n\n /**\n * Which rows the panel holds, as `useRows`' `where` takes it:\n * `{ status: [\"==\", \"pending\"] }`. The person's own filters on other\n * fields combine with it (AND); these fields cannot be changed or\n * cleared from the toolbar. It follows the prop, so a tab bar or a chart\n * click can drive it from state. Over the collection's `fixedFilter`,\n * field by field.\n */\n where?: FilterValues<string>;\n\n /**\n * Whether to sync filter/sort state with URL query params.\n * Defaults to `false` (embedded panels shouldn't hijack the URL).\n */\n updateUrl?: boolean;\n\n /**\n * Override the entity open mode when clicking a entity.\n */\n openEntityMode?: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n\n /**\n * The ids of the rows drawn as selected — the one a page shows beside\n * the list, say. `[]` draws none. Without it the panel highlights the\n * row last opened. Compared as strings, so an integer key's `5` and\n * `\"5\"` are one row.\n */\n highlightedIds?: (string | number)[];\n\n /**\n * Additional CSS class name for the container.\n */\n className?: string;\n\n /**\n * Any additional collection-level overrides (e.g. `previewProperties`,\n * `enabledViews`, `entityActions`, `defaultFilter`, etc.).\n */\n collectionOverrides?: Partial<AdminCollection>;\n\n /**\n * The properties the panel shows, in this order; the ones it leaves out\n * are not drawn.\n *\n * - Table: the columns.\n * - List, cards, kanban cards: what the row's or card's places — title,\n * image, subtitle, status, date, relation chips, the list's columns —\n * are filled from, earlier ones first. A place none of them fills\n * stays empty.\n *\n * For this panel it wins over `propertiesOrder`, the column order the\n * user saved, `listProperties` and what the cards infer. Column widths\n * the user drags still persist; the order is yours, so columns are not\n * dragged. A property hidden from collections stays hidden, and a\n * custom view is handed the whole collection.\n */\n fields?: string[];\n\n /**\n * The toolbar above the rows.\n *\n * - `\"full\"`, the default: the collection page's own toolbar.\n * - `\"compact\"`: the view-mode switch, search, and New where the person\n * may create.\n * - `\"none\"`: no toolbar.\n *\n * Or compose one from its pieces:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" toolbar={\n * <CollectionToolbar\n * start={<CollectionFiltersButton/>}\n * end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n * }/>\n * ```\n */\n toolbar?: \"full\" | \"compact\" | \"none\" | React.ReactElement;\n\n /**\n * Called with the row and its id when one is clicked, instead of the\n * panel opening it. Without it the record opens as `openEntityMode` says.\n *\n * The row is the one the server sends — the shape `useRows`, `useRow`\n * and `FieldValue` take: ISO date strings (`YYYY-MM-DD` for a date-only\n * column), and a belongsTo relation as its foreign key, under that key's\n * own name. It is exactly the record's columns; the id is the string the\n * admin addresses the record by — its primary key, a composite one's\n * parts joined by `:::` — which `highlightedIds` and\n * `useSidePanel().open` take.\n *\n * ```tsx\n * const [selectedId, setSelectedId] = useState<string>();\n * <CollectionPanel collection=\"orders\"\n * onRowClick={(row, id) => setSelectedId(id)}\n * highlightedIds={selectedId ? [selectedId] : []}/>\n * ```\n */\n onRowClick?: (row: Record<string, unknown>, id: string) => void;\n};\n\n/**\n * A high-level, reusable wrapper for embedding a Rebase collection view\n * inside custom pages (dashboards, home pages, entity detail views, etc.).\n *\n * Usage inside the CMS, by registered slug:\n * ```tsx\n * import { CollectionPanel } from \"@rebasepro/cms\";\n *\n * function MyDashboard() {\n * return (\n * <div>\n * <CollectionPanel collection=\"tasks\" title=\"Pending Tasks\" />\n * <CollectionPanel\n * collection=\"clients\"\n * viewMode=\"table\"\n * collectionOverrides={{\n * defaultFilter: { status: [\"!=\", \"completed\"] }\n * }}\n * />\n * </div>\n * );\n * }\n * ```\n *\n * Usage in a page of your own app, with the collection as a value — no\n * `<RebaseCMS>`, `<RebaseNavigation>` or `<RebaseShell>` needed, and any\n * React Router router will do. Records open in a side panel over the page:\n * ```tsx\n * <Rebase client={client} authController={authController}>\n * <BrowserRouter>\n * <CollectionPanel collection={postsCollection} />\n * </BrowserRouter>\n * </Rebase>\n * ```\n *\n * @group Components\n */\nfunction CollectionPanelInner({\n mergedCollection,\n overrides,\n path,\n title,\n viewMode,\n updateUrl,\n highlightedIds,\n fields,\n toolbar,\n onRowClick,\n rowActions,\n className\n}: ScopedPanelProps & { mergedCollection: AdminCollection; overrides: Partial<AdminCollection> }) {\n const ResolvedCollectionView = useComponentOverride(\"Collection.View\", CollectionViewBinding);\n const toolbarNode = toolbarOf(toolbar);\n const rowActionsScope = useMemo(\n () => rowActions ? { path: path ?? mergedCollection.slug, render: rowActions } : null,\n [path, mergedCollection.slug, rowActions]);\n\n // A column, so a height or a max-height on the panel reaches the view:\n // it sizes to its rows up to that, then scrolls inside.\n return (\n <div className={cls(\"flex flex-col min-h-0\", className)}>\n {title !== false && (\n <Typography\n variant=\"subtitle2\"\n className=\"font-semibold mb-2 text-surface-700 dark:text-surface-300\"\n >\n {title ?? mergedCollection.name}\n </Typography>\n )}\n <RowActionsContext.Provider value={rowActionsScope}>\n <ResolvedCollectionView\n {...mergedCollection}\n collectionOverrides={overrides}\n {...(highlightedIds !== undefined && { highlightedIds })}\n {...(viewMode && { viewMode })}\n {...(fields && { fields })}\n {...(toolbarNode !== undefined && { toolbar: toolbarNode })}\n {...(onRowClick && { onRowClick })}\n {...(title === false && { title })}\n path={path}\n updateUrl={updateUrl}\n />\n </RowActionsContext.Provider>\n </div>\n );\n}\n\nexport function CollectionPanel(rawProps: CollectionPanelProps) {\n const inScope = useContext(CollectionsScopeContext);\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const { collection, path } = collectionPropOf(rawProps.collection, rawProps.path);\n if (rawProps.collection === undefined) {\n warnDeprecated(\"CollectionPanel.path\", \"`<CollectionPanel path=\\\"…\\\"/>` names its collection with `collection` now: `<CollectionPanel collection=\\\"…\\\"/>`.\");\n }\n const props: ScopedPanelProps = { ...rawProps, collection, path };\n const ownCollections = useMemo(() => collection ? [collection] : [], [collection]);\n\n // A collection handed over as a value brings its own scope where there is\n // none above — or where the one above has settled without it, since a\n // collection the data layer does not know gives its rows no address.\n const needsOwnScope = collection !== undefined && (!inScope\n || (!navigationState.loading && !isRegistered(collectionRegistry.collections, path)));\n // Named by path with no scope above to look it up in: nothing will ever\n // register it, so it is not found rather than loading.\n if (!inScope && collection === undefined) return <CollectionNotFound className={props.className} path={path}/>;\n if (needsOwnScope) {\n return (\n <CollectionsProvider collections={ownCollections}>\n <CollectionPanelInScope {...props}/>\n </CollectionsProvider>\n );\n }\n return <CollectionPanelInScope {...props}/>;\n}\n\n/** A panel's props once its `collection` is a value or absent, and its `path` known. */\ntype ScopedPanelProps = CollectionPanelOptions & { collection?: AdminCollection; path: string };\n\nfunction CollectionPanelInScope(props: ScopedPanelProps) {\n const {\n viewMode,\n sort,\n limit,\n openEntityMode,\n className,\n collectionOverrides,\n where,\n orderBy,\n rowActions,\n collection: collectionProp\n } = props;\n if (sort !== undefined) warnDeprecated(\"CollectionPanel.sort\", \"`CollectionPanel`'s `sort` is `orderBy` now: `orderBy=\\\"field:desc\\\"`.\");\n const order = orderBy ? orderByTuple(orderBy) : sort;\n const orderKey = order ? order.join(\":\") : undefined;\n // Whether, not which: the column reads the renderer through context, so a\n // new function each render leaves the collection alone.\n const hasRowActions = rowActions !== undefined;\n const path = props.path ?? collectionProp?.slug ?? \"\";\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const urlController = useUrlController();\n // The registry's copy, also for a collection handed over as a value: it\n // carries the user's saved overrides and the plugins' changes. Not asked\n // before it has been filled.\n const lookUp = collectionRegistry.initialised || !navigationState.loading;\n const baseCollection = useMemo(\n () => lookUp ? collectionRegistry.getCollection(path) : undefined,\n [lookUp, collectionRegistry, path]);\n const routesMounted = urlController.routesMounted !== false;\n // Compared by value: it is an inline object at most call sites, and a new\n // one on every render would rebuild the overrides each time.\n const whereRef = useRef(where);\n if (!deepEqual(whereRef.current, where)) whereRef.current = where;\n const stableWhere = whereRef.current;\n\n // What this panel changes about the collection: the shorthand props over\n // the explicit overrides. Handed to the view as overrides, which it applies\n // over the registered collection it draws.\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n const merged: Partial<AdminCollection> = {\n ...(collectionOverrides ?? {}),\n ...(viewMode && { defaultViewMode: viewMode }),\n ...(order && { sort: order }),\n ...(limit && { pagination: limit }),\n ...(openEntityMode && { openEntityMode }),\n ...(stableWhere && {\n fixedFilter: { ...(baseCollection?.fixedFilter ?? {}), ...(collectionOverrides?.fixedFilter ?? {}), ...stableWhere }\n }),\n ...(hasRowActions && {\n additionalFields: [...(collectionOverrides?.additionalFields ?? baseCollection?.additionalFields ?? []), ROW_ACTIONS_FIELD]\n })\n };\n // Without CMS routes a record has no page of its own, nor a split\n // beside the list that a URL selects: it opens over the page.\n if (!routesMounted && (merged.openEntityMode ?? baseCollection?.openEntityMode) !== \"dialog\") {\n return { ...merged, openEntityMode: \"side_panel\" };\n }\n return merged;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `order` by its key: `orderBy` is an inline tuple at most call sites.\n }, [baseCollection, collectionOverrides, viewMode, orderKey, limit, openEntityMode, stableWhere, hasRowActions, routesMounted]);\n\n const mergedCollection = useMemo(\n () => baseCollection ? { ...baseCollection, ...overrides } as AdminCollection : undefined,\n [baseCollection, overrides]);\n\n if (!mergedCollection) {\n if (navigationState.loading) {\n return <div className={className}><CircularProgressCenter/></div>;\n }\n return <CollectionNotFound className={className} path={path}/>;\n }\n\n const content = (\n <CollectionPanelInner\n {...props}\n path={path}\n mergedCollection={mergedCollection}\n overrides={overrides}\n />\n );\n\n return (\n <CollectionScopeProvider collection={mergedCollection}>\n {content}\n </CollectionScopeProvider>\n );\n}\n\nfunction CollectionNotFound({ className, path }: { className?: string, path: string }) {\n return (\n <div className={className}>\n <Typography variant=\"body2\" color=\"secondary\">\n Collection "{path}" not found.\n </Typography>\n </div>\n );\n}\n\n/** `\"field:desc\"` or `[\"field\", \"desc\"]`, as the collection's `sort` takes it. */\nfunction orderByTuple(orderBy: NonNullable<CollectionPanelOptions[\"orderBy\"]>): [string, \"asc\" | \"desc\"] {\n if (typeof orderBy !== \"string\") return [orderBy[0], orderBy[1]];\n const at = orderBy.lastIndexOf(\":\");\n return [orderBy.slice(0, at), orderBy.slice(at + 1) as \"asc\" | \"desc\"];\n}\n\n/** The node a `toolbar` keyword stands for; a composed toolbar as it is. */\nfunction toolbarOf(toolbar: CollectionPanelOptions[\"toolbar\"]): React.ReactNode {\n if (toolbar === \"full\") return undefined;\n if (toolbar === \"none\") return null;\n if (toolbar === \"compact\") return COMPACT_TOOLBAR;\n return toolbar;\n}\n\nconst COMPACT_TOOLBAR = (\n <CollectionToolbar\n start={<CollectionViewModeToggle/>}\n end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0PA,SAAS,qBAAqB,EAC1B,kBACA,WACA,MACA,OACA,UACA,WACA,gBACA,QACA,SACA,YACA,YACA,aAC8F;CAC9F,MAAM,yBAAyB,qBAAqB,mBAAmB,qBAAqB;CAC5F,MAAM,cAAc,UAAU,OAAO;CACrC,MAAM,kBAAkB,cACd,aAAa;EAAE,MAAM,QAAQ,iBAAiB;EAAM,QAAQ;CAAW,IAAI,MACjF;EAAC;EAAM,iBAAiB;EAAM;CAAU,CAAC;CAI7C,OACI,qBAAC,OAAD;EAAK,WAAW,IAAI,yBAAyB,SAAS;YAAtD,CACK,UAAU,SACP,oBAAC,YAAD;GACI,SAAQ;GACR,WAAU;aAET,SAAS,iBAAiB;EACnB,CAAA,GAEhB,oBAAC,kBAAkB,UAAnB;GAA4B,OAAO;aAC/B,oBAAC,wBAAD;IACI,GAAI;IACJ,qBAAqB;IACrB,GAAK,mBAAmB,KAAA,KAAa,EAAE,eAAe;IACtD,GAAK,YAAY,EAAE,SAAS;IAC5B,GAAK,UAAU,EAAE,OAAO;IACxB,GAAK,gBAAgB,KAAA,KAAa,EAAE,SAAS,YAAY;IACzD,GAAK,cAAc,EAAE,WAAW;IAChC,GAAK,UAAU,SAAS,EAAE,MAAM;IAC1B;IACK;GACd,CAAA;EACuB,CAAA,CAC3B;;AAEb;AAEA,SAAgB,gBAAgB,UAAgC;CAC5D,MAAM,UAAU,WAAW,uBAAuB;CAClD,MAA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C;AAEA,SAAS,mBAAmB,EAAE,WAAW,QAA8C;CACnF,OACI,oBAAC,OAAD;EAAgB;YACZ,qBAAC,YAAD;GAAY,SAAQ;GAAQ,OAAM;aAAlC;IAA8C;IACxB;IAAK;GACf;;CACX,CAAA;AAEb;;AAGA,SAAS,aAAa,SAAmF;CACrG,IAAI,OAAO,YAAY,UAAU,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE;CAC/D,MAAM,KAAK,QAAQ,YAAY,GAAG;CAClC,OAAO,CAAC,QAAQ,MAAM,GAAG,EAAE,GAAG,QAAQ,MAAM,KAAK,CAAC,CAAmB;AACzE;;AAGA,SAAS,UAAU,SAA6D;CAC5E,IAAI,YAAY,QAAQ,OAAO,KAAA;CAC/B,IAAI,YAAY,QAAQ,OAAO;CAC/B,IAAI,YAAY,WAAW,OAAO;CAClC,OAAO;AACX;AAEA,IAAM,kBACF,oBAAC,mBAAD;CACI,OAAO,oBAAC,0BAAD,CAA0B,CAAA;CACjC,KAAK,qBAAA,UAAA,EAAA,UAAA,CAAE,oBAAC,qBAAD,CAAqB,CAAA,GAAC,oBAAC,qBAAD,CAAqB,CAAA,CAAG,EAAA,CAAA;AAAG,CAAA"}
|
|
1
|
+
{"version":3,"file":"CollectionPanel.js","names":[],"sources":["../../src/components/CollectionPanel.tsx"],"sourcesContent":["\nimport type { ViewMode, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { FilterValues } from \"@rebasepro/types\";\nimport React, { useContext, useMemo, useRef, useState } from \"react\";\nimport { deepEqual } from \"fast-equals\";\nimport { CollectionViewBinding } from \"./CollectionViewBinding/CollectionViewBinding\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useNavigationStateController } from \"../hooks/navigation/contexts/NavigationStateContext\";\nimport { useUrlController } from \"../hooks/navigation/contexts/UrlContext\";\nimport { CircularProgressCenter, cls, Typography } from \"@rebasepro/ui\";\nimport { useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { CollectionsScopeContext, isRegistered } from \"./CollectionsScopeContext\";\nimport { CollectionsProvider } from \"./CollectionsProvider\";\nimport { collectionPropOf } from \"./collection_prop\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { ROW_ACTIONS_FIELD, RowActionsContext, type RowActionsRenderer } from \"./CollectionViewBinding/RowActions\";\nimport { ViewTitleReportContext } from \"./CollectionViewBinding/CollectionViewContent\";\nimport {\n CollectionSearchBar,\n CollectionToolbar,\n CollectionViewModeToggle\n} from \"./CollectionViewBinding/CollectionToolbar\";\nimport { CollectionAddButton } from \"./CollectionViewBinding/CollectionAddButton\";\n\n/**\n * Props for the {@link CollectionPanel} component.\n *\n * This is a high-level, consumer-friendly wrapper around {@link CollectionViewBinding}\n * designed for embedding collection views inside custom pages (home pages,\n * dashboards, entity detail views, etc.).\n *\n * Name the collection — `collection=\"orders\"`, one registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above — or hand it over as a\n * value, `collection={ordersCollection}`. All other props are optional overrides that take precedence\n * over the collection's default configuration.\n *\n * @group Components\n */\nexport type CollectionPanelProps = CollectionPanelOptions & ({\n /**\n * The collection to display: its name (`\"orders\"`), registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above, or the collection\n * as a value — a `defineCollection` config or a resolved collection.\n * Handed over as a value where no CMS navigation is mounted above, the\n * panel brings its own {@link CollectionsProvider} for it, so it works\n * anywhere under `<Rebase>` and a router.\n */\n collection: AdminCollection | string;\n /**\n * Where the rows live, where that is not the collection's name: a\n * subcollection's full path, `posts/p1/comments`.\n */\n path?: string;\n} | {\n /**\n * @deprecated Name the collection with `collection`:\n * `<CollectionPanel collection=\"orders\"/>`. It warns once.\n */\n path: string;\n collection?: undefined;\n});\n\n/**\n * The display options of a {@link CollectionPanel}.\n *\n * @group Components\n */\nexport type CollectionPanelOptions = {\n\n /**\n * Optional title displayed above the collection.\n * Set to `false` to hide the title entirely.\n * Defaults to the collection's `name`.\n */\n title?: string | false;\n\n /**\n * The view mode the panel opens in, over the collection's default, the\n * one in the URL and the one the person last picked. They can still\n * switch.\n */\n viewMode?: ViewMode;\n\n /**\n * @deprecated Use {@link orderBy}: `orderBy=\"field:desc\"`. It warns once.\n */\n sort?: [string, \"asc\" | \"desc\"];\n\n /**\n * The order the rows open in, as `\"field:desc\"` or `[\"field\", \"desc\"]`.\n * The person can still sort by another column.\n */\n orderBy?: `${string}:asc` | `${string}:desc` | readonly [string, \"asc\" | \"desc\"];\n\n /**\n * Your own JSX on every row, card and kanban card — an \"Approve\" button,\n * a \"Ship\" — handed the row as the server sends it and its id:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" rowActions={(row, id) =>\n * <Button size=\"small\" onClick={() => update(\"orders\", id, { status: \"shipped\" })}>Ship</Button>}/>\n * ```\n *\n * In the table it is the last column; on a list row, a card and a kanban\n * card it sits beside the collection's own actions. A click on it does\n * not open the record.\n */\n rowActions?: RowActionsRenderer;\n\n /**\n * Maximum number of entities to display.\n */\n limit?: number;\n\n /**\n * Which rows the panel holds, as `useRows`' `where` takes it:\n * `{ status: [\"==\", \"pending\"] }`. The person's own filters on other\n * fields combine with it (AND); these fields cannot be changed or\n * cleared from the toolbar. It follows the prop, so a tab bar or a chart\n * click can drive it from state. Over the collection's `fixedFilter`,\n * field by field.\n */\n where?: FilterValues<string>;\n\n /**\n * Whether to sync filter/sort state with URL query params.\n * Defaults to `false` (embedded panels shouldn't hijack the URL).\n */\n updateUrl?: boolean;\n\n /**\n * Override the entity open mode when clicking a entity.\n */\n openEntityMode?: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n\n /**\n * The ids of the rows drawn as selected — the one a page shows beside\n * the list, say. `[]` draws none. Without it the panel highlights the\n * row last opened. Compared as strings, so an integer key's `5` and\n * `\"5\"` are one row.\n */\n highlightedIds?: (string | number)[];\n\n /**\n * Additional CSS class name for the container.\n */\n className?: string;\n\n /**\n * Any additional collection-level overrides (e.g. `previewProperties`,\n * `enabledViews`, `entityActions`, `defaultFilter`, etc.).\n */\n collectionOverrides?: Partial<AdminCollection>;\n\n /**\n * The properties the panel shows, in this order; the ones it leaves out\n * are not drawn.\n *\n * - Table: the columns.\n * - List, cards, kanban cards: what the row's or card's places — title,\n * image, subtitle, status, date, relation chips, the list's columns —\n * are filled from, earlier ones first. A place none of them fills\n * stays empty.\n *\n * For this panel it wins over `propertiesOrder`, the column order the\n * user saved, `listProperties` and what the cards infer. Column widths\n * the user drags still persist; the order is yours, so columns are not\n * dragged. A property hidden from collections stays hidden, and a\n * custom view is handed the whole collection.\n */\n fields?: string[];\n\n /**\n * The toolbar above the rows.\n *\n * - `\"full\"`, the default: the collection page's own toolbar.\n * - `\"compact\"`: the view-mode switch, search, and New where the person\n * may create.\n * - `\"none\"`: no toolbar.\n *\n * Or compose one from its pieces:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" toolbar={\n * <CollectionToolbar\n * start={<CollectionFiltersButton/>}\n * end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n * }/>\n * ```\n */\n toolbar?: \"full\" | \"compact\" | \"none\" | React.ReactElement;\n\n /**\n * Called with the row and its id when one is clicked, instead of the\n * panel opening it. Without it the record opens as `openEntityMode` says.\n *\n * The row is the one the server sends — the shape `useRows`, `useRow`\n * and `FieldValue` take: ISO date strings (`YYYY-MM-DD` for a date-only\n * column), and a belongsTo relation as its foreign key, under that key's\n * own name. It is exactly the record's columns; the id is the string the\n * admin addresses the record by — its primary key, a composite one's\n * parts joined by `:::` — which `highlightedIds` and\n * `useSidePanel().open` take.\n *\n * ```tsx\n * const [selectedId, setSelectedId] = useState<string>();\n * <CollectionPanel collection=\"orders\"\n * onRowClick={(row, id) => setSelectedId(id)}\n * highlightedIds={selectedId ? [selectedId] : []}/>\n * ```\n */\n onRowClick?: (row: Record<string, unknown>, id: string) => void;\n};\n\n/**\n * A high-level, reusable wrapper for embedding a Rebase collection view\n * inside custom pages (dashboards, home pages, entity detail views, etc.).\n *\n * Usage inside the CMS, by registered slug:\n * ```tsx\n * import { CollectionPanel } from \"@rebasepro/cms\";\n *\n * function MyDashboard() {\n * return (\n * <div>\n * <CollectionPanel collection=\"tasks\" title=\"Pending Tasks\" />\n * <CollectionPanel\n * collection=\"clients\"\n * viewMode=\"table\"\n * collectionOverrides={{\n * defaultFilter: { status: [\"!=\", \"completed\"] }\n * }}\n * />\n * </div>\n * );\n * }\n * ```\n *\n * Usage in a page of your own app, with the collection as a value — no\n * `<RebaseCMS>`, `<RebaseNavigation>` or `<RebaseShell>` needed, and any\n * React Router router will do. Records open in a side panel over the page:\n * ```tsx\n * <Rebase client={client} authController={authController}>\n * <BrowserRouter>\n * <CollectionPanel collection={postsCollection} />\n * </BrowserRouter>\n * </Rebase>\n * ```\n *\n * @group Components\n */\nfunction CollectionPanelInner({\n mergedCollection,\n overrides,\n path,\n title,\n viewMode,\n updateUrl,\n highlightedIds,\n fields,\n toolbar,\n onRowClick,\n rowActions,\n className\n}: ScopedPanelProps & { mergedCollection: AdminCollection; overrides: Partial<AdminCollection> }) {\n const ResolvedCollectionView = useComponentOverride(\"Collection.View\", CollectionViewBinding);\n const toolbarNode = toolbarOf(toolbar);\n const rowActionsScope = useMemo(\n () => rowActions ? { path: path ?? mergedCollection.slug, render: rowActions } : null,\n [path, mergedCollection.slug, rowActions]);\n // The list draws its title as its own heading: there the panel draws none,\n // and hands the view its title instead.\n const [viewDrawsTitle, setViewDrawsTitle] = useState(false);\n const titleReport = useMemo(\n () => ({ path: path ?? mergedCollection.slug, onViewDrawsTitle: setViewDrawsTitle }),\n [path, mergedCollection.slug]);\n\n // A column, so a height or a max-height on the panel reaches the view:\n // it sizes to its rows up to that, then scrolls inside.\n return (\n <div className={cls(\"flex flex-col min-h-0\", className)}>\n {title !== false && !viewDrawsTitle && (\n <Typography\n variant=\"subtitle2\"\n className=\"font-semibold mb-2 text-surface-700 dark:text-surface-300\"\n >\n {title ?? mergedCollection.name}\n </Typography>\n )}\n <RowActionsContext.Provider value={rowActionsScope}>\n <ViewTitleReportContext.Provider value={titleReport}>\n <ResolvedCollectionView\n {...mergedCollection}\n collectionOverrides={overrides}\n {...(highlightedIds !== undefined && { highlightedIds })}\n {...(viewMode && { viewMode })}\n {...(fields && { fields })}\n {...(toolbarNode !== undefined && { toolbar: toolbarNode })}\n {...(onRowClick && { onRowClick })}\n {...(title !== undefined && { title })}\n path={path}\n updateUrl={updateUrl}\n />\n </ViewTitleReportContext.Provider>\n </RowActionsContext.Provider>\n </div>\n );\n}\n\nexport function CollectionPanel(rawProps: CollectionPanelProps) {\n const inScope = useContext(CollectionsScopeContext);\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const { collection, path } = collectionPropOf(rawProps.collection, rawProps.path);\n if (rawProps.collection === undefined) {\n warnDeprecated(\"CollectionPanel.path\", \"`<CollectionPanel path=\\\"…\\\"/>` names its collection with `collection` now: `<CollectionPanel collection=\\\"…\\\"/>`.\");\n }\n const props: ScopedPanelProps = { ...rawProps, collection, path };\n const ownCollections = useMemo(() => collection ? [collection] : [], [collection]);\n\n // A collection handed over as a value brings its own scope where there is\n // none above — or where the one above has settled without it, since a\n // collection the data layer does not know gives its rows no address.\n const needsOwnScope = collection !== undefined && (!inScope\n || (!navigationState.loading && !isRegistered(collectionRegistry.collections, path)));\n // Named by path with no scope above to look it up in: nothing will ever\n // register it, so it is not found rather than loading.\n if (!inScope && collection === undefined) return <CollectionNotFound className={props.className} path={path}/>;\n if (needsOwnScope) {\n return (\n <CollectionsProvider collections={ownCollections}>\n <CollectionPanelInScope {...props}/>\n </CollectionsProvider>\n );\n }\n return <CollectionPanelInScope {...props}/>;\n}\n\n/** A panel's props once its `collection` is a value or absent, and its `path` known. */\ntype ScopedPanelProps = CollectionPanelOptions & { collection?: AdminCollection; path: string };\n\nfunction CollectionPanelInScope(props: ScopedPanelProps) {\n const {\n viewMode,\n sort,\n limit,\n openEntityMode,\n className,\n collectionOverrides,\n where,\n orderBy,\n rowActions,\n collection: collectionProp\n } = props;\n if (sort !== undefined) warnDeprecated(\"CollectionPanel.sort\", \"`CollectionPanel`'s `sort` is `orderBy` now: `orderBy=\\\"field:desc\\\"`.\");\n const order = orderBy ? orderByTuple(orderBy) : sort;\n const orderKey = order ? order.join(\":\") : undefined;\n // Whether, not which: the column reads the renderer through context, so a\n // new function each render leaves the collection alone.\n const hasRowActions = rowActions !== undefined;\n const path = props.path ?? collectionProp?.slug ?? \"\";\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const urlController = useUrlController();\n // The registry's copy, also for a collection handed over as a value: it\n // carries the user's saved overrides and the plugins' changes. Not asked\n // before it has been filled.\n const lookUp = collectionRegistry.initialised || !navigationState.loading;\n const baseCollection = useMemo(\n () => lookUp ? collectionRegistry.getCollection(path) : undefined,\n [lookUp, collectionRegistry, path]);\n const routesMounted = urlController.routesMounted !== false;\n // Compared by value: it is an inline object at most call sites, and a new\n // one on every render would rebuild the overrides each time.\n const whereRef = useRef(where);\n if (!deepEqual(whereRef.current, where)) whereRef.current = where;\n const stableWhere = whereRef.current;\n\n // What this panel changes about the collection: the shorthand props over\n // the explicit overrides. Handed to the view as overrides, which it applies\n // over the registered collection it draws.\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n const merged: Partial<AdminCollection> = {\n ...(collectionOverrides ?? {}),\n ...(viewMode && { defaultViewMode: viewMode }),\n ...(order && { sort: order }),\n ...(limit && { pagination: limit }),\n ...(openEntityMode && { openEntityMode }),\n ...(stableWhere && {\n fixedFilter: { ...(baseCollection?.fixedFilter ?? {}), ...(collectionOverrides?.fixedFilter ?? {}), ...stableWhere }\n }),\n ...(hasRowActions && {\n additionalFields: [...(collectionOverrides?.additionalFields ?? baseCollection?.additionalFields ?? []), ROW_ACTIONS_FIELD]\n })\n };\n // Without CMS routes a record has no page of its own, nor a split\n // beside the list that a URL selects: it opens over the page.\n if (!routesMounted && (merged.openEntityMode ?? baseCollection?.openEntityMode) !== \"dialog\") {\n return { ...merged, openEntityMode: \"side_panel\" };\n }\n return merged;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `order` by its key: `orderBy` is an inline tuple at most call sites.\n }, [baseCollection, collectionOverrides, viewMode, orderKey, limit, openEntityMode, stableWhere, hasRowActions, routesMounted]);\n\n const mergedCollection = useMemo(\n () => baseCollection ? { ...baseCollection, ...overrides } as AdminCollection : undefined,\n [baseCollection, overrides]);\n\n if (!mergedCollection) {\n if (navigationState.loading) {\n return <div className={className}><CircularProgressCenter/></div>;\n }\n return <CollectionNotFound className={className} path={path}/>;\n }\n\n const content = (\n <CollectionPanelInner\n {...props}\n path={path}\n mergedCollection={mergedCollection}\n overrides={overrides}\n />\n );\n\n return (\n <CollectionScopeProvider collection={mergedCollection}>\n {content}\n </CollectionScopeProvider>\n );\n}\n\nfunction CollectionNotFound({ className, path }: { className?: string, path: string }) {\n return (\n <div className={className}>\n <Typography variant=\"body2\" color=\"secondary\">\n Collection "{path}" not found.\n </Typography>\n </div>\n );\n}\n\n/** `\"field:desc\"` or `[\"field\", \"desc\"]`, as the collection's `sort` takes it. */\nfunction orderByTuple(orderBy: NonNullable<CollectionPanelOptions[\"orderBy\"]>): [string, \"asc\" | \"desc\"] {\n if (typeof orderBy !== \"string\") return [orderBy[0], orderBy[1]];\n const at = orderBy.lastIndexOf(\":\");\n return [orderBy.slice(0, at), orderBy.slice(at + 1) as \"asc\" | \"desc\"];\n}\n\n/** The node a `toolbar` keyword stands for; a composed toolbar as it is. */\nfunction toolbarOf(toolbar: CollectionPanelOptions[\"toolbar\"]): React.ReactNode {\n if (toolbar === \"full\") return undefined;\n if (toolbar === \"none\") return null;\n if (toolbar === \"compact\") return COMPACT_TOOLBAR;\n return toolbar;\n}\n\nconst COMPACT_TOOLBAR = (\n <CollectionToolbar\n start={<CollectionViewModeToggle/>}\n end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2PA,SAAS,qBAAqB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B;IAAK;GACf;;CACX,CAAA;AAEb;;AAGA,SAAS,aAAa,SAAmF;CACrG,IAAI,OAAO,YAAY,UAAU,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE;CAC/D,MAAM,KAAK,QAAQ,YAAY,GAAG;CAClC,OAAO,CAAC,QAAQ,MAAM,GAAG,EAAE,GAAG,QAAQ,MAAM,KAAK,CAAC,CAAmB;AACzE;;AAGA,SAAS,UAAU,SAA6D;CAC5E,IAAI,YAAY,QAAQ,OAAO,KAAA;CAC/B,IAAI,YAAY,QAAQ,OAAO;CAC/B,IAAI,YAAY,WAAW,OAAO;CAClC,OAAO;AACX;AAEA,IAAM,kBACF,oBAAC,mBAAD;CACI,OAAO,oBAAC,0BAAD,CAA0B,CAAA;CACjC,KAAK,qBAAA,UAAA,EAAA,UAAA,CAAE,oBAAC,qBAAD,CAAqB,CAAA,GAAC,oBAAC,qBAAD,CAAqB,CAAA,CAAG,EAAA,CAAA;AAAG,CAAA"}
|
|
@@ -8,7 +8,7 @@ interface PopupFormFieldProps<M extends Record<string, unknown>> {
|
|
|
8
8
|
path: string;
|
|
9
9
|
entityId: string | number;
|
|
10
10
|
tableKey: string;
|
|
11
|
-
propertyKey?: Extract<keyof M, string
|
|
11
|
+
propertyKey?: Extract<keyof M, string> | (string & {});
|
|
12
12
|
collection?: AdminCollection<M>;
|
|
13
13
|
cellRect?: DOMRect;
|
|
14
14
|
open: boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PopupFormField.js","names":[],"sources":["../../../../../src/components/CollectionTableBinding/internal/popup_field/PopupFormField.tsx"],"sourcesContent":["import type { Properties } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\n\nimport type { FormContext, PropertyFieldBindingProps } from \"../../../../types/fields\";\nimport type { Property } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useLayoutEffect, useState } from \"react\";\n\nimport { Button, DialogActions, IconButton, Portal, Typography, XIcon } from \"@rebasepro/ui\";\n\nimport { Entity, EntityValues } from \"@rebasepro/types\";\nimport { PluginProviderStack, useTranslation } from \"@rebasepro/app\";\nimport { Formex, FormexController, getIn, useCreateFormex } from \"@rebasepro/forms\";\nimport { useDraggable } from \"./useDraggable\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema } from \"../../../../form/validation\";\nimport { cellValidationProperties } from \"../../../../form/resolve_cell_property\";\nimport { useWindowSize } from \"./useWindowSize\";\nimport { getPropertyInPath } from \"../../../../util/property_utils\";\nimport { PropertyFieldBinding, zodToFormErrors } from \"../../../../form\";\nimport { useAuthController, useCustomizationController, useData, useRebaseContext } from \"@rebasepro/app\";\nimport type { OnCellValueChangeParams } from \"@rebasepro/app\";\nimport { isDisabled, isReadOnly } from \"@rebasepro/app\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { rowOfEntity } from \"@rebasepro/app\";\n\ninterface PopupFormFieldProps<M extends Record<string, unknown>> {\n customFieldValidator?: CustomFieldValidator;\n path: string;\n entityId: string | number;\n tableKey: string;\n propertyKey?: Extract<keyof M, string>;\n // `AdminCollection<M>`, not `<any>`: the admin block's key-shaped fields\n // (titleProperty, sort, propertiesOrder) are typed against M, and\n // `AdminCollection<any>` collapses them to `string` — which then fails to\n // flow into the `FormContext<M>` built below.\n collection?: AdminCollection<M>;\n cellRect?: DOMRect;\n open: boolean;\n onClose: () => void;\n container: HTMLElement | null;\n /**\n * Callback when the value of a cell has been edited\n * @param params\n */\n onCellValueChange?: (params: OnCellValueChangeParams<any, any>) => Promise<void> | void;\n}\n\nexport function PopupFormField<M extends Record<string, unknown>>(props: PopupFormFieldProps<M>) {\n if (!props.open) return null;\n return <PopupFormFieldLoading {...props}/>;\n\n}\n\nexport function PopupFormFieldLoading<M extends Record<string, unknown>>({\n tableKey,\n entityId,\n customFieldValidator,\n propertyKey,\n collection: inputCollection,\n path,\n cellRect,\n open,\n onClose,\n onCellValueChange,\n container\n}: PopupFormFieldProps<M>) {\n const dataClient = useData();\n const [entity, setEntity] = useState<Entity<M> | undefined>(undefined);\n useEffect(() => {\n if (hasEntityId(entityId) && inputCollection) {\n dataClient.collection(path).findById(entityId).then((result) => setEntity(result as Entity<M> | undefined));\n }\n }, [entityId, inputCollection, dataClient, path]);\n\n if (!entity) return null;\n return <PopupFormFieldInternal {...{\n tableKey,\n entityId,\n customFieldValidator,\n propertyKey,\n collection: inputCollection,\n path,\n cellRect,\n open,\n onClose,\n onCellValueChange,\n container\n }} entity={entity}/>;\n}\n\nexport function PopupFormFieldInternal<M extends Record<string, unknown>>({\n tableKey,\n entityId,\n customFieldValidator,\n propertyKey,\n collection,\n path,\n cellRect,\n open,\n onClose,\n onCellValueChange,\n container,\n entity\n}: PopupFormFieldProps<M> & {\n entity?: Entity<M>\n}) {\n const { t } = useTranslation();\n\n const rebaseContext = useRebaseContext();\n const authController = useAuthController();\n const customizationController = useCustomizationController();\n\n const [savingError, setSavingError] = React.useState<any>();\n const [popupLocation, setPopupLocation] = useState<{\n x: number,\n y: number\n }>();\n\n const windowSize = useWindowSize();\n\n const draggableRef = React.useRef<HTMLDivElement>(null);\n const innerRef = React.useRef<HTMLDivElement>(null);\n\n const initialPositionSet = React.useRef<boolean>(false);\n\n const getInitialLocation = useCallback(() => {\n if (!cellRect) throw Error(\"getInitialLocation error\");\n\n return {\n x: cellRect.left < windowSize.width - cellRect.right\n ? cellRect.x + cellRect.width / 2\n : cellRect.x - cellRect.width / 2,\n y: cellRect.top < windowSize.height - cellRect.bottom\n ? cellRect.y + cellRect.height / 2\n : cellRect.y - cellRect.height / 2\n };\n }, [cellRect, windowSize.height, windowSize.width]);\n\n const normalizePosition = useCallback((\n pos: { x: number, y: number },\n draggableBoundingRect: DOMRect,\n currentWindowSize: { width: number, height: number }\n ) => {\n if (!draggableBoundingRect || draggableBoundingRect.width === 0 || draggableBoundingRect.height === 0) {\n return pos;\n }\n return {\n x: Math.max(0, Math.min(pos.x, currentWindowSize.width - draggableBoundingRect.width)),\n y: Math.max(0, Math.min(pos.y, currentWindowSize.height - draggableBoundingRect.height))\n };\n }, []);\n\n const updatePopupLocation = useCallback((newPositionCandidate?: {\n x: number,\n y: number\n }) => {\n const draggableBoundingRect = draggableRef.current?.getBoundingClientRect();\n if (!cellRect || !draggableBoundingRect || draggableBoundingRect.width === 0 || draggableBoundingRect.height === 0) {\n return;\n }\n const basePosition = newPositionCandidate ?? getInitialLocation();\n const newNormalizedPosition = normalizePosition(basePosition, draggableBoundingRect, windowSize);\n\n if (!popupLocation || newNormalizedPosition.x !== popupLocation.x || newNormalizedPosition.y !== popupLocation.y) {\n setPopupLocation(newNormalizedPosition);\n }\n }, [cellRect, getInitialLocation, normalizePosition, popupLocation, windowSize]);\n\n useDraggable({\n containerRef: draggableRef,\n innerRef,\n x: popupLocation?.x,\n y: popupLocation?.y,\n onMove: updatePopupLocation\n });\n\n useEffect(\n () => {\n initialPositionSet.current = false;\n },\n [propertyKey, entity]\n );\n\n useLayoutEffect(\n () => {\n if (!cellRect || initialPositionSet.current) return;\n // Ensure draggableRef is available and has dimensions before initial positioning\n const draggableBoundingRect = draggableRef.current?.getBoundingClientRect();\n if (!draggableBoundingRect || draggableBoundingRect.width === 0 || draggableBoundingRect.height === 0) {\n // If not ready, perhaps wait or log. For now, just return.\n // This might need a retry mechanism or ensure content is rendered first.\n return;\n }\n updatePopupLocation();\n initialPositionSet.current = true;\n },\n [cellRect, updatePopupLocation] // Removed initialPositionSet.current from deps as it's a ref\n );\n\n useLayoutEffect(\n () => {\n updatePopupLocation(popupLocation);\n },\n [windowSize, cellRect, updatePopupLocation, popupLocation]\n );\n\n // Built per validation, from the properties resolved against the values\n // the popup holds: a `conditions` rule or a `dynamicProps` validation\n // depends on them, as it does in the record form.\n const validationSchemaFor = (values: Partial<M>) => {\n if (!collection || !hasEntityId(entityId) || !propertyKey) return undefined;\n return getEntitySchema(\n entityId,\n cellValidationProperties<M>(collection.properties, propertyKey as string, values, entity?.values, entityId, {\n path,\n authController,\n propertyConfigs: customizationController.propertyConfigs\n }),\n customFieldValidator);\n };\n\n const adaptResize = useCallback(() => {\n // When the popup resizes, we want to re-evaluate its position\n // based on its current location and new dimensions.\n return updatePopupLocation(popupLocation);\n }, [popupLocation, updatePopupLocation]);\n\n // Setup ResizeObserver\n useEffect(() => {\n const element = draggableRef.current;\n if (!element) return;\n\n const observer = new ResizeObserver(() => {\n adaptResize();\n });\n\n observer.observe(element);\n\n return () => {\n observer.unobserve(element);\n observer.disconnect();\n };\n }, [adaptResize, draggableRef]);\n\n const saveValue = async (values: M) => {\n setSavingError(null);\n if (collection && entity && onCellValueChange && propertyKey) {\n // Written the way the form writes it: with the string transforms\n // the properties declare (`trim`, `lowercase`, `uppercase`) applied.\n const writtenValues = applyValueTransforms(values, collection.properties);\n return onCellValueChange({\n // By path: a spread map's child is `address.street`, which is\n // nested in the form values, not a key of them.\n value: getIn(writtenValues, propertyKey as string),\n propertyKey: propertyKey as string,\n data: entity,\n setError: setSavingError,\n onValueUpdated: () => {\n }\n });\n }\n return Promise.resolve();\n };\n\n const formex = useCreateFormex<M>({\n initialValues: (entity?.values ?? {}) as EntityValues<M>,\n validation: async (values) => {\n const validationSchema = validationSchemaFor(values);\n if (!validationSchema) return {};\n const result = await validationSchema.safeParseAsync(values);\n if (result.success) return {};\n return zodToFormErrors(result.error) as Record<string, string>;\n },\n validateOnInitialRender: true,\n onSubmit: (values, actions) => {\n saveValue(values)\n .then(() => {\n formex.resetForm({\n values: values\n })\n onClose();\n })\n .finally(() => actions.setSubmitting(false));\n }\n });\n\n const {\n values,\n isSubmitting,\n setFieldValue,\n handleSubmit\n } = formex;\n\n const disabled = isSubmitting;\n\n const formContext: FormContext<M> = {\n collection: collection,\n id: entityId,\n row: entity ? rowOfEntity(entity, collection) : undefined,\n values,\n path,\n setFieldValue,\n save: saveValue,\n submit: handleSubmit,\n formex,\n status: \"existing\",\n openEntityMode: \"side_panel\",\n disabled: false\n };\n\n const property: Property | undefined = propertyKey && getPropertyInPath(collection?.properties ?? {} as Properties, propertyKey as string);\n const fieldProps: PropertyFieldBindingProps<M> | undefined = propertyKey && property\n ? {\n propertyKey: propertyKey as string,\n disabled: isSubmitting || isReadOnly(property) || isDisabled(property),\n property,\n includeDescription: false,\n underlyingValueHasChanged: false,\n context: formContext,\n partOfArray: false,\n minimalistView: true,\n autoFocus: open\n }\n : undefined;\n\n let internalForm = <>\n <div\n key={`popup_form_${tableKey}_${entityId}_${propertyKey}`}\n className=\"w-[700px] max-w-full max-h-[85vh]\">\n <form\n onSubmit={handleSubmit}\n noValidate>\n\n <div\n className=\"mb-1 p-4 flex flex-col relative\">\n <div\n ref={innerRef}\n className=\"cursor-auto\"\n style={{ cursor: \"auto !important\" }}>\n {fieldProps &&\n <PropertyFieldBinding {...fieldProps}/>}\n </div>\n </div>\n\n <DialogActions>\n <Button\n variant=\"filled\"\n color=\"primary\"\n type=\"submit\"\n disabled={disabled}\n >\n Save\n </Button>\n </DialogActions>\n\n </form>\n\n </div>\n\n </>;\n\n const plugins = customizationController.plugins;\n if (plugins && plugins.length > 0) {\n internalForm = (\n <PluginProviderStack\n plugins={plugins}\n scope=\"form\"\n scopeProps={{\n status: \"existing\",\n path,\n collection,\n entity,\n context: rebaseContext,\n currentEntityId: entityId,\n formContext\n }}>\n {internalForm}\n </PluginProviderStack>\n );\n }\n const form = <div\n className={`text-surface-900 dark:text-white overflow-auto rounded-xs rounded-md bg-surface-card ${!open ? \"hidden\" : \"\"} cursor-grab max-w-[100vw]`}>\n\n {internalForm}\n\n {savingError &&\n <Typography color={\"error\"}>\n {savingError.message}\n </Typography>\n }\n </div>;\n\n const draggable = (\n <div\n key={`draggable_${propertyKey as string}_${entityId}_${open}`}\n style={{\n boxShadow: \"0 0 0 2px rgba(128,128,128,0.2)\"\n }}\n className={`inline-block fixed z-20 shadow-outline rounded-md bg-surface-card ${!open ? \"invisible\" : \"visible\"\n } cursor-grab overflow-visible`}\n ref={draggableRef}>\n\n {/* ElementResizeListener removed from here */}\n\n <div\n className=\"overflow-hidden\">\n\n {form}\n\n <div\n className=\"absolute -top-3.5 -right-3.5 bg-surface-500 rounded-full\"\n style={{\n width: \"32px\",\n height: \"32px\"\n }}>\n <IconButton aria-label={t(\"close\")}\n size={\"small\"}\n onClick={(event) => {\n event.stopPropagation();\n onClose();\n }}>\n <XIcon className=\"text-white\"/>\n </IconButton>\n </div>\n </div>\n\n </div>\n );\n\n return (\n <Portal.Root asChild\n container={container}>\n <Formex value={formex as FormexController<Record<string, unknown>>}>\n {draggable}\n </Formex>\n </Portal.Root>\n );\n\n}\n"],"mappings":";;;;;;;;;;;;;;AA8CA,SAAgB,eAAkD,OAA+B;CAC7F,IAAI,CAAC,MAAM,MAAM,OAAO;CACxB,OAAO,oBAAC,uBAAD,EAAuB,GAAI,MAAO,CAAA;AAE7C;AAEA,SAAgB,sBAAyD,EACrE,UACA,UACA,sBACA,aACA,YAAY,iBACZ,MACA,UACA,MACA,SACA,mBACA,aACuB;CACvB,MAAM,aAAa,QAAQ;CAC3B,MAAM,CAAC,QAAQ,aAAa,SAAgC,KAAA,CAAS;CACrE,gBAAgB;EACZ,IAAI,YAAY,QAAQ,KAAK,iBACzB,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,MAAM,WAAW,UAAU,MAA+B,CAAC;CAElH,GAAG;EAAC;EAAU;EAAiB;EAAY;CAAI,CAAC;CAEhD,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,oBAAC,wBAAD;EACH;EACA;EACA;EACA;EACA,YAAY;EACZ;EACA;EACA;EACA;EACA;EACA;EACO;CAAQ,CAAA;AACvB;AAEA,SAAgB,uBAA0D,EACtE,UACA,UACA,sBACA,aACA,YACA,MACA,UACA,MACA,SACA,mBACA,WACA,UAGD;CACC,MAAM,EAAE,MAAM,eAAe;CAE7B,MAAM,gBAAgB,iBAAiB;CACvC,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,0BAA0B,2BAA2B;CAE3D,MAAM,CAAC,aAAa,kBAAkB,MAAM,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"}
|
|
1
|
+
{"version":3,"file":"PopupFormField.js","names":[],"sources":["../../../../../src/components/CollectionTableBinding/internal/popup_field/PopupFormField.tsx"],"sourcesContent":["import type { Properties } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\n\nimport type { FormContext, PropertyFieldBindingProps } from \"../../../../types/fields\";\nimport type { Property } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useLayoutEffect, useState } from \"react\";\n\nimport { Button, DialogActions, IconButton, Portal, Typography, XIcon } from \"@rebasepro/ui\";\n\nimport { Entity, EntityValues } from \"@rebasepro/types\";\nimport { PluginProviderStack, useTranslation } from \"@rebasepro/app\";\nimport { Formex, FormexController, getIn, useCreateFormex } from \"@rebasepro/forms\";\nimport { useDraggable } from \"./useDraggable\";\nimport { applyValueTransforms, CustomFieldValidator, getEntitySchema } from \"../../../../form/validation\";\nimport { cellValidationProperties } from \"../../../../form/resolve_cell_property\";\nimport { useWindowSize } from \"./useWindowSize\";\nimport { getPropertyInPath } from \"../../../../util/property_utils\";\nimport { PropertyFieldBinding, zodToFormErrors } from \"../../../../form\";\nimport { useAuthController, useCustomizationController, useData, useRebaseContext } from \"@rebasepro/app\";\nimport type { OnCellValueChangeParams } from \"@rebasepro/app\";\nimport { isDisabled, isReadOnly } from \"@rebasepro/app\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { rowOfEntity } from \"@rebasepro/app\";\n\ninterface PopupFormFieldProps<M extends Record<string, unknown>> {\n customFieldValidator?: CustomFieldValidator;\n path: string;\n entityId: string | number;\n tableKey: string;\n // A column, or a key inside one (`address.street`, `tags[1]`): the popup\n // edits the value at that path, as the table cell it opened from does.\n propertyKey?: Extract<keyof M, string> | (string & {});\n // `AdminCollection<M>`, not `<any>`: the admin block's key-shaped fields\n // (titleProperty, sort, propertiesOrder) are typed against M, and\n // `AdminCollection<any>` collapses them to `string` — which then fails to\n // flow into the `FormContext<M>` built below.\n collection?: AdminCollection<M>;\n cellRect?: DOMRect;\n open: boolean;\n onClose: () => void;\n container: HTMLElement | null;\n /**\n * Callback when the value of a cell has been edited\n * @param params\n */\n onCellValueChange?: (params: OnCellValueChangeParams<any, any>) => Promise<void> | void;\n}\n\nexport function PopupFormField<M extends Record<string, unknown>>(props: PopupFormFieldProps<M>) {\n if (!props.open) return null;\n return <PopupFormFieldLoading {...props}/>;\n\n}\n\nexport function PopupFormFieldLoading<M extends Record<string, unknown>>({\n tableKey,\n entityId,\n customFieldValidator,\n propertyKey,\n collection: inputCollection,\n path,\n cellRect,\n open,\n onClose,\n onCellValueChange,\n container\n}: PopupFormFieldProps<M>) {\n const dataClient = useData();\n const [entity, setEntity] = useState<Entity<M> | undefined>(undefined);\n useEffect(() => {\n if (hasEntityId(entityId) && inputCollection) {\n dataClient.collection(path).findById(entityId).then((result) => setEntity(result as Entity<M> | undefined));\n }\n }, [entityId, inputCollection, dataClient, path]);\n\n if (!entity) return null;\n return <PopupFormFieldInternal {...{\n tableKey,\n entityId,\n customFieldValidator,\n propertyKey,\n collection: inputCollection,\n path,\n cellRect,\n open,\n onClose,\n onCellValueChange,\n container\n }} entity={entity}/>;\n}\n\nexport function PopupFormFieldInternal<M extends Record<string, unknown>>({\n tableKey,\n entityId,\n customFieldValidator,\n propertyKey,\n collection,\n path,\n cellRect,\n open,\n onClose,\n onCellValueChange,\n container,\n entity\n}: PopupFormFieldProps<M> & {\n entity?: Entity<M>\n}) {\n const { t } = useTranslation();\n\n const rebaseContext = useRebaseContext();\n const authController = useAuthController();\n const customizationController = useCustomizationController();\n\n const [savingError, setSavingError] = React.useState<any>();\n const [popupLocation, setPopupLocation] = useState<{\n x: number,\n y: number\n }>();\n\n const windowSize = useWindowSize();\n\n const draggableRef = React.useRef<HTMLDivElement>(null);\n const innerRef = React.useRef<HTMLDivElement>(null);\n\n const initialPositionSet = React.useRef<boolean>(false);\n\n const getInitialLocation = useCallback(() => {\n if (!cellRect) throw Error(\"getInitialLocation error\");\n\n return {\n x: cellRect.left < windowSize.width - cellRect.right\n ? cellRect.x + cellRect.width / 2\n : cellRect.x - cellRect.width / 2,\n y: cellRect.top < windowSize.height - cellRect.bottom\n ? cellRect.y + cellRect.height / 2\n : cellRect.y - cellRect.height / 2\n };\n }, [cellRect, windowSize.height, windowSize.width]);\n\n const normalizePosition = useCallback((\n pos: { x: number, y: number },\n draggableBoundingRect: DOMRect,\n currentWindowSize: { width: number, height: number }\n ) => {\n if (!draggableBoundingRect || draggableBoundingRect.width === 0 || draggableBoundingRect.height === 0) {\n return pos;\n }\n return {\n x: Math.max(0, Math.min(pos.x, currentWindowSize.width - draggableBoundingRect.width)),\n y: Math.max(0, Math.min(pos.y, currentWindowSize.height - draggableBoundingRect.height))\n };\n }, []);\n\n const updatePopupLocation = useCallback((newPositionCandidate?: {\n x: number,\n y: number\n }) => {\n const draggableBoundingRect = draggableRef.current?.getBoundingClientRect();\n if (!cellRect || !draggableBoundingRect || draggableBoundingRect.width === 0 || draggableBoundingRect.height === 0) {\n return;\n }\n const basePosition = newPositionCandidate ?? getInitialLocation();\n const newNormalizedPosition = normalizePosition(basePosition, draggableBoundingRect, windowSize);\n\n if (!popupLocation || newNormalizedPosition.x !== popupLocation.x || newNormalizedPosition.y !== popupLocation.y) {\n setPopupLocation(newNormalizedPosition);\n }\n }, [cellRect, getInitialLocation, normalizePosition, popupLocation, windowSize]);\n\n useDraggable({\n containerRef: draggableRef,\n innerRef,\n x: popupLocation?.x,\n y: popupLocation?.y,\n onMove: updatePopupLocation\n });\n\n useEffect(\n () => {\n initialPositionSet.current = false;\n },\n [propertyKey, entity]\n );\n\n useLayoutEffect(\n () => {\n if (!cellRect || initialPositionSet.current) return;\n // Ensure draggableRef is available and has dimensions before initial positioning\n const draggableBoundingRect = draggableRef.current?.getBoundingClientRect();\n if (!draggableBoundingRect || draggableBoundingRect.width === 0 || draggableBoundingRect.height === 0) {\n // If not ready, perhaps wait or log. For now, just return.\n // This might need a retry mechanism or ensure content is rendered first.\n return;\n }\n updatePopupLocation();\n initialPositionSet.current = true;\n },\n [cellRect, updatePopupLocation] // Removed initialPositionSet.current from deps as it's a ref\n );\n\n useLayoutEffect(\n () => {\n updatePopupLocation(popupLocation);\n },\n [windowSize, cellRect, updatePopupLocation, popupLocation]\n );\n\n // Built per validation, from the properties resolved against the values\n // the popup holds: a `conditions` rule or a `dynamicProps` validation\n // depends on them, as it does in the record form.\n const validationSchemaFor = (values: Partial<M>) => {\n if (!collection || !hasEntityId(entityId) || !propertyKey) return undefined;\n return getEntitySchema(\n entityId,\n cellValidationProperties<M>(collection.properties, propertyKey as string, values, entity?.values, entityId, {\n path,\n authController,\n propertyConfigs: customizationController.propertyConfigs\n }),\n customFieldValidator);\n };\n\n const adaptResize = useCallback(() => {\n // When the popup resizes, we want to re-evaluate its position\n // based on its current location and new dimensions.\n return updatePopupLocation(popupLocation);\n }, [popupLocation, updatePopupLocation]);\n\n // Setup ResizeObserver\n useEffect(() => {\n const element = draggableRef.current;\n if (!element) return;\n\n const observer = new ResizeObserver(() => {\n adaptResize();\n });\n\n observer.observe(element);\n\n return () => {\n observer.unobserve(element);\n observer.disconnect();\n };\n }, [adaptResize, draggableRef]);\n\n const saveValue = async (values: M) => {\n setSavingError(null);\n if (collection && entity && onCellValueChange && propertyKey) {\n // Written the way the form writes it: with the string transforms\n // the properties declare (`trim`, `lowercase`, `uppercase`) applied.\n const writtenValues = applyValueTransforms(values, collection.properties);\n return onCellValueChange({\n // By path: a spread map's child is `address.street`, which is\n // nested in the form values, not a key of them.\n value: getIn(writtenValues, propertyKey as string),\n propertyKey: propertyKey as string,\n data: entity,\n setError: setSavingError,\n onValueUpdated: () => {\n }\n });\n }\n return Promise.resolve();\n };\n\n const formex = useCreateFormex<M>({\n initialValues: (entity?.values ?? {}) as EntityValues<M>,\n validation: async (values) => {\n const validationSchema = validationSchemaFor(values);\n if (!validationSchema) return {};\n const result = await validationSchema.safeParseAsync(values);\n if (result.success) return {};\n return zodToFormErrors(result.error) as Record<string, string>;\n },\n validateOnInitialRender: true,\n onSubmit: (values, actions) => {\n saveValue(values)\n .then(() => {\n formex.resetForm({\n values: values\n })\n onClose();\n })\n .finally(() => actions.setSubmitting(false));\n }\n });\n\n const {\n values,\n isSubmitting,\n setFieldValue,\n handleSubmit\n } = formex;\n\n const disabled = isSubmitting;\n\n const formContext: FormContext<M> = {\n collection: collection,\n id: entityId,\n row: entity ? rowOfEntity(entity, collection) : undefined,\n values,\n path,\n setFieldValue,\n save: saveValue,\n submit: handleSubmit,\n formex,\n status: \"existing\",\n openEntityMode: \"side_panel\",\n disabled: false\n };\n\n const property: Property | undefined = propertyKey && getPropertyInPath(collection?.properties ?? {} as Properties, propertyKey as string);\n const fieldProps: PropertyFieldBindingProps<M> | undefined = propertyKey && property\n ? {\n propertyKey: propertyKey as string,\n disabled: isSubmitting || isReadOnly(property) || isDisabled(property),\n property,\n includeDescription: false,\n underlyingValueHasChanged: false,\n context: formContext,\n partOfArray: false,\n minimalistView: true,\n autoFocus: open\n }\n : undefined;\n\n let internalForm = <>\n <div\n key={`popup_form_${tableKey}_${entityId}_${propertyKey}`}\n className=\"w-[700px] max-w-full max-h-[85vh]\">\n <form\n onSubmit={handleSubmit}\n noValidate>\n\n <div\n className=\"mb-1 p-4 flex flex-col relative\">\n <div\n ref={innerRef}\n className=\"cursor-auto\"\n style={{ cursor: \"auto !important\" }}>\n {fieldProps &&\n <PropertyFieldBinding {...fieldProps}/>}\n </div>\n </div>\n\n <DialogActions>\n <Button\n variant=\"filled\"\n color=\"primary\"\n type=\"submit\"\n disabled={disabled}\n >\n Save\n </Button>\n </DialogActions>\n\n </form>\n\n </div>\n\n </>;\n\n const plugins = customizationController.plugins;\n if (plugins && plugins.length > 0) {\n internalForm = (\n <PluginProviderStack\n plugins={plugins}\n scope=\"form\"\n scopeProps={{\n status: \"existing\",\n path,\n collection,\n entity,\n context: rebaseContext,\n currentEntityId: entityId,\n formContext\n }}>\n {internalForm}\n </PluginProviderStack>\n );\n }\n const form = <div\n className={`text-surface-900 dark:text-white overflow-auto rounded-xs rounded-md bg-surface-card ${!open ? \"hidden\" : \"\"} cursor-grab max-w-[100vw]`}>\n\n {internalForm}\n\n {savingError &&\n <Typography color={\"error\"}>\n {savingError.message}\n </Typography>\n }\n </div>;\n\n const draggable = (\n <div\n key={`draggable_${propertyKey as string}_${entityId}_${open}`}\n style={{\n boxShadow: \"0 0 0 2px rgba(128,128,128,0.2)\"\n }}\n className={`inline-block fixed z-20 shadow-outline rounded-md bg-surface-card ${!open ? \"invisible\" : \"visible\"\n } cursor-grab overflow-visible`}\n ref={draggableRef}>\n\n {/* ElementResizeListener removed from here */}\n\n <div\n className=\"overflow-hidden\">\n\n {form}\n\n <div\n className=\"absolute -top-3.5 -right-3.5 bg-surface-500 rounded-full\"\n style={{\n width: \"32px\",\n height: \"32px\"\n }}>\n <IconButton aria-label={t(\"close\")}\n size={\"small\"}\n onClick={(event) => {\n event.stopPropagation();\n onClose();\n }}>\n <XIcon className=\"text-white\"/>\n </IconButton>\n </div>\n </div>\n\n </div>\n );\n\n return (\n <Portal.Root asChild\n container={container}>\n <Formex value={formex as FormexController<Record<string, unknown>>}>\n {draggable}\n </Formex>\n </Portal.Root>\n );\n\n}\n"],"mappings":";;;;;;;;;;;;;;AAgDA,SAAgB,eAAkD,OAA+B;CAC7F,IAAI,CAAC,MAAM,MAAM,OAAO;CACxB,OAAO,oBAAC,uBAAD,EAAuB,GAAI,MAAO,CAAA;AAE7C;AAEA,SAAgB,sBAAyD,EACrE,UACA,UACA,sBACA,aACA,YAAY,iBACZ,MACA,UACA,MACA,SACA,mBACA,aACuB;CACvB,MAAM,aAAa,QAAQ;CAC3B,MAAM,CAAC,QAAQ,aAAa,SAAgC,KAAA,CAAS;CACrE,gBAAgB;EACZ,IAAI,YAAY,QAAQ,KAAK,iBACzB,WAAW,WAAW,IAAI,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,MAAM,WAAW,UAAU,MAA+B,CAAC;CAElH,GAAG;EAAC;EAAU;EAAiB;EAAY;C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IACI,WAAU;IACV,OAAO;KACH,OAAO;KACP,QAAQ;IACZ;cACA,oBAAC,YAAD;KAAY,cAAY,EAAE,OAAO;KAC7B,MAAM;KACN,UAAU,UAAU;MAChB,MAAM,gBAAgB;MACtB,QAAQ;KACZ;eACA,oBAAC,OAAD,EAAO,WAAU,aAAa,CAAA;IACtB,CAAA;GACX,CAAA,CACJ;;CAEJ,GAhCI,aAAa,YAAsB,GAAG,SAAS,GAAG,MAgCtD;CAGT,OACI,oBAAC,OAAO,MAAR;EAAa,SAAA;EACE;YACX,oBAAC,QAAD;GAAQ,OAAO;aACV;EACG,CAAA;CACC,CAAA;AAGrB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CollectionCardViewBinding.js","names":[],"sources":["../../../src/components/CollectionViewBinding/CollectionCardViewBinding.tsx"],"sourcesContent":["\nimport React, { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { deepEqual as equal } from \"fast-equals\";\nimport { Entity } from \"@rebasepro/types\";\nimport { CollectionSize, EntityTableController, EntitySelectionController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { EntityCardBinding, EntityCardBindingProps } from \"./EntityCardBinding\";\nimport {\n cls,\n CircularProgress,\n Typography,\n CardView\n} from \"@rebasepro/ui\";\nimport { useComponentOverride } from \"@rebasepro/app\";\n\nexport type CollectionCardViewBindingProps<M extends Record<string, unknown> = Record<string, unknown>> = {\n collection: AdminCollection<M>;\n tableController: EntityTableController<M>;\n onEntityClick?: (entity: Entity<M>) => void;\n selectionController?: EntitySelectionController<M>;\n selectionEnabled?: boolean;\n highlightedEntities?: Entity<M>[];\n emptyComponent?: React.ReactNode;\n onScroll?: (props: {\n scrollDirection: \"forward\" | \"backward\";\n scrollOffset: number;\n scrollUpdateWasRequested: boolean;\n }) => void;\n initialScroll?: number;\n /**\n * Size of the cards in the grid view.\n * - \"xs\": Extra small cards, most cards per row\n * - \"s\": Small cards\n * - \"m\": Medium cards (default)\n * - \"l\": Large cards\n * - \"xl\": Extra large cards, fewest cards per row\n */\n size?: CollectionSize;\n /** Draws a record's actions on its card; see {@link EntityCardBindingProps.renderActions}. */\n renderActions?: (entity: Entity<M>) => React.ReactNode;\n};\n\n/**\n * Card grid view for displaying entities with infinite scroll.\n * Alternative to the CollectionTableBinding for visual browsing.\n */\nexport function CollectionCardViewBinding<M extends Record<string, unknown> = Record<string, unknown>>({\n collection,\n tableController,\n onEntityClick,\n selectionController,\n selectionEnabled = true,\n highlightedEntities,\n emptyComponent,\n onScroll,\n initialScroll,\n size = \"m\",\n renderActions\n}: CollectionCardViewBindingProps<M>) {\n\n const ResolvedEntityCard = useComponentOverride(\"Collection.Card\", EntityCardBinding) as typeof EntityCardBinding;\n\n // Memoised, so a page, a push or a tick draws the cards that changed. The\n // grid draws every loaded card, and drew every one again on each update:\n // the 41st page of 50 cards cost 4,050 card renders.\n const MemoisedCard = useMemo(\n () => React.memo(ResolvedEntityCard, areCardPropsEqual) as unknown as typeof EntityCardBinding,\n [ResolvedEntityCard]);\n\n const {\n data,\n sparseData,\n onRowsRendered,\n dataLoading,\n noMoreToLoad,\n dataLoadingError,\n itemCount,\n setItemCount,\n pageSize = 50,\n paginationEnabled\n } = tableController;\n\n // The grid stops drawing cards when it goes (another view takes over):\n // say so, so the controller keeps every row held current again.\n useEffect(() => () => onRowsRendered?.(undefined), [onRowsRendered]);\n\n const handleEntityClick = useCallback((entity: Entity<M>) => {\n onEntityClick?.(entity);\n }, [onEntityClick]);\n\n // The handlers every card gets are the same two functions for the life of\n // the grid, reading what they need when they are called. One per card per\n // render — what `CardView` hands `renderCard` — would draw every card on\n // every update. The selection controller is a new object with each\n // selection, so it is read through the ref as well.\n const latest = useRef({ onEntityClick, selectionController, selectionEnabled });\n latest.current = { onEntityClick, selectionController, selectionEnabled };\n\n const handleSelectionChange = useCallback((entity: Entity<M>, selected: boolean) => {\n latest.current.selectionController?.toggleEntitySelection(entity, selected);\n }, []);\n\n /**\n * A card was clicked: a modifier click ticks it, any other opens it — what\n * the grid's own per-card handler does, for a `Collection.Card` override\n * that does not handle the modifier itself.\n */\n const handleCardClick = useCallback((entity: Entity<M>, event?: React.MouseEvent) => {\n const { onEntityClick, selectionController, selectionEnabled } = latest.current;\n if (event && (event.metaKey || event.ctrlKey) && selectionEnabled) {\n event.preventDefault();\n selectionController?.toggleEntitySelection(entity, !selectionController.isEntitySelected(entity));\n return;\n }\n onEntityClick?.(entity);\n }, []);\n\n // Built from the rows on screen rather than from a list of the selected:\n // in query mode there is no such list, and this Set only ever describes\n // which visible rows draw a ticked checkbox.\n const selectedIds = useMemo(\n () => new Set<string | number>(data.filter(e => selectionController?.isEntitySelected(e)).map(e => e.id)),\n [data, selectionController]\n );\n const highlightedIds = useMemo(() => new Set(highlightedEntities?.map(e => e.id)), [highlightedEntities]);\n\n const handleRowSelectionChange = useCallback((entity: Entity<M>, selected: boolean) => {\n handleSelectionChange(entity, selected);\n }, [handleSelectionChange]);\n\n return (\n <CardView<Entity<M>>\n data={sparseData ?? data}\n onRowsRendered={onRowsRendered}\n dataLoading={dataLoading}\n noMoreToLoad={noMoreToLoad}\n dataLoadingError={dataLoadingError}\n itemCount={itemCount}\n setItemCount={setItemCount}\n pageSize={pageSize}\n paginationEnabled={paginationEnabled}\n onItemClick={handleEntityClick}\n selectedIds={selectedIds}\n highlightedIds={highlightedIds}\n selectionEnabled={selectionEnabled}\n onSelectionChange={handleRowSelectionChange}\n onScroll={onScroll}\n initialScroll={initialScroll}\n size={size}\n emptyComponent={emptyComponent}\n renderCard={useCallback((entity, { selected, highlighted }) => (\n <MemoisedCard\n key={`${entity.path}_${entity.id}`}\n entity={entity}\n collection={collection}\n searchString={tableController.searchString}\n onClick={handleCardClick}\n selected={selected}\n highlighted={highlighted}\n onSelectionChange={handleRowSelectionChange}\n selectionEnabled={selectionEnabled}\n size={size}\n renderActions={renderActions}\n />\n ), [collection, selectionEnabled, size, handleRowSelectionChange, handleCardClick, MemoisedCard, tableController.searchString, renderActions])}\n />\n );\n}\n\n/**\n * Every prop by reference, except the row: a realtime frame decodes into new\n * row objects whether or not anything in them changed, so the row is compared\n * by value — the same row (id and path) with equal values draws the same card.\n */\nfunction areCardPropsEqual<M extends Record<string, unknown>>(\n a: EntityCardBindingProps<M>,\n b: EntityCardBindingProps<M>\n): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof EntityCardBindingProps<M>>;\n for (const key of keys) {\n if (key === \"entity\") continue;\n if (a[key] !== b[key]) return false;\n }\n return a.entity === b.entity || (\n a.entity.id === b.entity.id &&\n a.entity.path === b.entity.path &&\n equal(a.entity.values, b.entity.values)\n );\n}\n"],"mappings":";;;;;;;;;;;AA6CA,SAAgB,0BAAuF,EACnG,YACA,iBACA,eACA,qBACA,mBAAmB,MACnB,qBACA,gBACA,UACA,eACA,OAAO,KACP,iBACkC;CAElC,MAAM,qBAAqB,qBAAqB,mBAAmB,iBAAiB;CAKpF,MAAM,eAAe,cACX,MAAM,KAAK,oBAAoB,iBAAiB,GACtD,CAAC,kBAAkB,CAAC;CAExB,MAAM,EACF,MACA,YACA,gBACA,aACA,cACA,kBACA,WACA,cACA,WAAW,IACX,sBACA;CAIJ,sBAAsB,iBAAiB,KAAA,CAAS,GAAG,CAAC,cAAc,CAAC;CAEnE,MAAM,oBAAoB,aAAa,WAAsB;EACzD,gBAAgB,MAAM;CAC1B,GAAG,CAAC,aAAa,CAAC;CAOlB,MAAM,SAAS,OAAO;EAAE;EAAe;EAAqB;CAAiB,CAAC;CAC9E,OAAO,UAAU;EAAE;EAAe;EAAqB;CAAiB;CAExE,MAAM,wBAAwB,aAAa,QAAmB,aAAsB;EAChF,OAAO,QAAQ,qBAAqB,sBAAsB,QAAQ,QAAQ;CAC9E,GAAG,CAAC,CAAC;;;;;;CAOL,MAAM,kBAAkB,aAAa,QAAmB,UAA6B;EACjF,MAAM,EAAE,eAAe,qBAAqB,qBAAqB,OAAO;EACxE,IAAI,UAAU,MAAM,WAAW,MAAM,YAAY,kBAAkB;GA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OAAO,MACzB,EAAE,OAAO,SAAS,EAAE,OAAO,QAC3B,UAAM,EAAE,OAAO,QAAQ,EAAE,OAAO,MAAM;AAE9C"}
|
|
1
|
+
{"version":3,"file":"CollectionCardViewBinding.js","names":[],"sources":["../../../src/components/CollectionViewBinding/CollectionCardViewBinding.tsx"],"sourcesContent":["\nimport React, { useCallback, useEffect, useMemo, useRef } from \"react\";\nimport { deepEqual as equal } from \"fast-equals\";\nimport { Entity } from \"@rebasepro/types\";\nimport { CollectionSize, EntityTableController, EntitySelectionController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { EntityCardBinding, EntityCardBindingProps } from \"./EntityCardBinding\";\nimport {\n cls,\n CircularProgress,\n Typography,\n CardView\n} from \"@rebasepro/ui\";\nimport { useComponentOverride } from \"@rebasepro/app\";\n\nexport type CollectionCardViewBindingProps<M extends Record<string, unknown> = Record<string, unknown>> = {\n collection: AdminCollection<M>;\n tableController: EntityTableController<M>;\n onEntityClick?: (entity: Entity<M>) => void;\n selectionController?: EntitySelectionController<M>;\n selectionEnabled?: boolean;\n highlightedEntities?: Entity<M>[];\n emptyComponent?: React.ReactNode;\n onScroll?: (props: {\n scrollDirection: \"forward\" | \"backward\";\n scrollOffset: number;\n scrollUpdateWasRequested: boolean;\n }) => void;\n initialScroll?: number;\n /**\n * Size of the cards in the grid view.\n * - \"xs\": Extra small cards, most cards per row\n * - \"s\": Small cards\n * - \"m\": Medium cards (default)\n * - \"l\": Large cards\n * - \"xl\": Extra large cards, fewest cards per row\n */\n size?: CollectionSize;\n /** Draws a record's actions on its card; see {@link EntityCardBindingProps.renderActions}. */\n renderActions?: (entity: Entity<M>) => React.ReactNode;\n};\n\n/**\n * Card grid view for displaying entities with infinite scroll.\n * Alternative to the CollectionTableBinding for visual browsing.\n */\nexport function CollectionCardViewBinding<M extends Record<string, unknown> = Record<string, unknown>>({\n collection,\n tableController,\n onEntityClick,\n selectionController,\n selectionEnabled = true,\n highlightedEntities,\n emptyComponent,\n onScroll,\n initialScroll,\n size = \"m\",\n renderActions\n}: CollectionCardViewBindingProps<M>) {\n\n const ResolvedEntityCard = useComponentOverride(\"Collection.Card\", EntityCardBinding) as typeof EntityCardBinding;\n\n // Memoised, so a page, a push or a tick draws the cards that changed. The\n // grid draws every loaded card, and drew every one again on each update:\n // the 41st page of 50 cards cost 4,050 card renders.\n const MemoisedCard = useMemo(\n // `React.memo` erases the card's generic `M`; the memoised card takes the same props.\n () => React.memo(ResolvedEntityCard, areCardPropsEqual) as typeof EntityCardBinding,\n [ResolvedEntityCard]);\n\n const {\n data,\n sparseData,\n onRowsRendered,\n dataLoading,\n noMoreToLoad,\n dataLoadingError,\n itemCount,\n setItemCount,\n pageSize = 50,\n paginationEnabled\n } = tableController;\n\n // The grid stops drawing cards when it goes (another view takes over):\n // say so, so the controller keeps every row held current again.\n useEffect(() => () => onRowsRendered?.(undefined), [onRowsRendered]);\n\n const handleEntityClick = useCallback((entity: Entity<M>) => {\n onEntityClick?.(entity);\n }, [onEntityClick]);\n\n // The handlers every card gets are the same two functions for the life of\n // the grid, reading what they need when they are called. One per card per\n // render — what `CardView` hands `renderCard` — would draw every card on\n // every update. The selection controller is a new object with each\n // selection, so it is read through the ref as well.\n const latest = useRef({ onEntityClick, selectionController, selectionEnabled });\n latest.current = { onEntityClick, selectionController, selectionEnabled };\n\n const handleSelectionChange = useCallback((entity: Entity<M>, selected: boolean) => {\n latest.current.selectionController?.toggleEntitySelection(entity, selected);\n }, []);\n\n /**\n * A card was clicked: a modifier click ticks it, any other opens it — what\n * the grid's own per-card handler does, for a `Collection.Card` override\n * that does not handle the modifier itself.\n */\n const handleCardClick = useCallback((entity: Entity<M>, event?: React.MouseEvent) => {\n const { onEntityClick, selectionController, selectionEnabled } = latest.current;\n if (event && (event.metaKey || event.ctrlKey) && selectionEnabled) {\n event.preventDefault();\n selectionController?.toggleEntitySelection(entity, !selectionController.isEntitySelected(entity));\n return;\n }\n onEntityClick?.(entity);\n }, []);\n\n // Built from the rows on screen rather than from a list of the selected:\n // in query mode there is no such list, and this Set only ever describes\n // which visible rows draw a ticked checkbox.\n const selectedIds = useMemo(\n () => new Set<string | number>(data.filter(e => selectionController?.isEntitySelected(e)).map(e => e.id)),\n [data, selectionController]\n );\n const highlightedIds = useMemo(() => new Set(highlightedEntities?.map(e => e.id)), [highlightedEntities]);\n\n const handleRowSelectionChange = useCallback((entity: Entity<M>, selected: boolean) => {\n handleSelectionChange(entity, selected);\n }, [handleSelectionChange]);\n\n return (\n <CardView<Entity<M>>\n data={sparseData ?? data}\n onRowsRendered={onRowsRendered}\n dataLoading={dataLoading}\n noMoreToLoad={noMoreToLoad}\n dataLoadingError={dataLoadingError}\n itemCount={itemCount}\n setItemCount={setItemCount}\n pageSize={pageSize}\n paginationEnabled={paginationEnabled}\n onItemClick={handleEntityClick}\n selectedIds={selectedIds}\n highlightedIds={highlightedIds}\n selectionEnabled={selectionEnabled}\n onSelectionChange={handleRowSelectionChange}\n onScroll={onScroll}\n initialScroll={initialScroll}\n size={size}\n emptyComponent={emptyComponent}\n renderCard={useCallback((entity, { selected, highlighted }) => (\n <MemoisedCard\n key={`${entity.path}_${entity.id}`}\n entity={entity}\n collection={collection}\n searchString={tableController.searchString}\n onClick={handleCardClick}\n selected={selected}\n highlighted={highlighted}\n onSelectionChange={handleRowSelectionChange}\n selectionEnabled={selectionEnabled}\n size={size}\n renderActions={renderActions}\n />\n ), [collection, selectionEnabled, size, handleRowSelectionChange, handleCardClick, MemoisedCard, tableController.searchString, renderActions])}\n />\n );\n}\n\n/**\n * Every prop by reference, except the row: a realtime frame decodes into new\n * row objects whether or not anything in them changed, so the row is compared\n * by value — the same row (id and path) with equal values draws the same card.\n */\nfunction areCardPropsEqual<M extends Record<string, unknown>>(\n a: EntityCardBindingProps<M>,\n b: EntityCardBindingProps<M>\n): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]) as Set<keyof EntityCardBindingProps<M>>;\n for (const key of keys) {\n if (key === \"entity\") continue;\n if (a[key] !== b[key]) return false;\n }\n return a.entity === b.entity || (\n a.entity.id === b.entity.id &&\n a.entity.path === b.entity.path &&\n equal(a.entity.values, b.entity.values)\n );\n}\n"],"mappings":";;;;;;;;;;;AA6CA,SAAgB,0BAAuF,EACnG,YACA,iBACA,eACA,qBACA,mBAAmB,MACnB,qBACA,gBACA,UACA,eACA,OAAO,KACP,iBACkC;CAElC,MAAM,qBAAqB,qBAAqB,mBAAmB,iBAAiB;CAKpF,MAAM,eAAe,cAEX,MAAM,KAAK,oBAAoB,iBAAiB,GACtD,CAAC,kBAAkB,CAAC;CAExB,MAAM,EACF,MACA,YACA,gBACA,aACA,cACA,kBACA,WACA,cACA,WAAW,IACX,sBACA;CAIJ,sBAAsB,iBAAiB,KAAA,CAAS,GAAG,CAAC,cAAc,CAAC;CAEnE,MAAM,oBAAoB,aAAa,WAAsB;EACzD,gBAAgB,MAAM;CAC1B,GAAG,CAAC,aAAa,CAAC;CAOlB,MAAM,SAAS,OAAO;EAAE;EAAe;EAAqB;CAAiB,CAAC;CAC9E,OAAO,UAAU;EAAE;EAAe;EAAqB;CAAiB;CAExE,MAAM,wBAAwB,aAAa,QAAmB,aAAsB;EAChF,OAAO,QAAQ,qBAAqB,sBAAsB,QAAQ,QAAQ;CAC9E,GAAG,CAAC,CAAC;;;;;;CAOL,MAAM,kBAAkB,aAAa,QAAmB,UAA6B;EACjF,MAAM,EAAE,eAAe,qBAAqB,qBAAqB,OAAO;EACxE,IAAI,UAAU,MAAM,WAAW,MAAM,YAAY,kBAAkB;GAC/D,MAAM,eAAe;GACrB,qBAAqB,sBAAsB,QAAQ,CAAC,oBAAoB,iBAAiB,MAAM,CAAC;GAChG;EACJ;EACA,gBAAgB,MAAM;CAC1B,GAAG,CAAC,CAAC;CAKL,MAAM,cAAc,cACV,IAAI,IAAqB,KAAK,QAAO,MAAK,qBAAqB,iBAAiB,CAAC,CAAC,CAAC,CAAC,KAAI,MAAK,EAAE,EAAE,CAAC,GACxG,CAAC,MAAM,mBAAmB,CAC9B;CACA,MAAM,iBAAiB,cAAc,IAAI,IAAI,qBAAqB,KAAI,MAAK,EAAE,EAAE,CAAC,GAAG,CAAC,mBAAmB,CAAC;CAExG,MAAM,2BAA2B,aAAa,QAAmB,aAAsB;EACnF,sBAAsB,QAAQ,QAAQ;CAC1C,GAAG,CAAC,qBAAqB,CAAC;CAE1B,OACI,oBAAC,UAAD;EACI,MAAM,cAAc;EACJ;EACH;EACC;EACI;EACP;EACG;EACJ;EACS;EACnB,aAAa;EACA;EACG;EACE;EAClB,mBAAmB;EACT;EACK;EACT;EACU;EAChB,YAAY,aAAa,QAAQ,EAAE,UAAU,kBACzC,oBAAC,cAAD;GAEY;GACI;GACZ,cAAc,gBAAgB;GAC9B,SAAS;GACC;GACG;GACb,mBAAmB;GACD;GACZ;GACS;EAClB,GAXQ,GAAG,OAAO,KAAK,GAAG,OAAO,IAWjC,GACF;GAAC;GAAY;GAAkB;GAAM;GAA0B;GAAiB;GAAc,gBAAgB;GAAc;EAAa,CAAC;CAChJ,CAAA;AAET;;;;;;AAOA,SAAS,kBACL,GACA,GACO;CACP,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,GAAG,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC;CAC3D,KAAK,MAAM,OAAO,MAAM;EACpB,IAAI,QAAQ,UAAU;EACtB,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAClC;CACA,OAAO,EAAE,WAAW,EAAE,UAClB,EAAE,OAAO,OAAO,EAAE,OAAO,MACzB,EAAE,OAAO,SAAS,EAAE,OAAO,QAC3B,UAAM,EAAE,OAAO,QAAQ,EAAE,OAAO,MAAM;AAE9C"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { getResolvedPropertyInPath } from "../../util/property_utils.js";
|
|
2
2
|
import { formatCollectionDate } from "../../util/format_collection_date.js";
|
|
3
|
-
import { useCollectionSlotKeys, useEntitySlots, useImagePlace } from "./usePreviewSlots.js";
|
|
3
|
+
import { loadedRelationName, relationCardinality, resolveRelationDisplayName, useCollectionSlotKeys, useEntitySlots, useImagePlace } from "./usePreviewSlots.js";
|
|
4
4
|
import { PropertyPreview } from "../../preview/PropertyPreview.js";
|
|
5
5
|
import { useAdminContext } from "../../hooks/useAdminContext.js";
|
|
6
6
|
import { entityActionName, resolveEntityActionState } from "../../util/entity_actions.js";
|
|
@@ -172,18 +172,18 @@ function compactValueSummary(value, property) {
|
|
|
172
172
|
return null;
|
|
173
173
|
}
|
|
174
174
|
if (property.type === "relation") {
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
175
|
+
const named = (related) => {
|
|
176
|
+
if (typeof related === "string" || typeof related === "number") return String(related);
|
|
177
|
+
if (!related || typeof related !== "object") return null;
|
|
178
|
+
const obj = related;
|
|
179
|
+
return resolveRelationDisplayName(obj, property) ?? ("id" in obj ? String(obj.id) : null);
|
|
180
|
+
};
|
|
181
|
+
if (Array.isArray(value)) {
|
|
182
|
+
const names = value.map(named).filter((name) => name !== null);
|
|
183
|
+
if (names.length === 0) return null;
|
|
184
|
+
return names.length > 2 ? `${names.slice(0, 2).join(", ")} +${names.length - 2}` : names.join(", ");
|
|
185
185
|
}
|
|
186
|
-
return
|
|
186
|
+
return named(value);
|
|
187
187
|
}
|
|
188
188
|
return null;
|
|
189
189
|
}
|
|
@@ -294,7 +294,8 @@ function CollectionListViewBinding({ collection, tableController, onEntityClick,
|
|
|
294
294
|
]);
|
|
295
295
|
slotPriorities.delete(void 0);
|
|
296
296
|
if (columnMode) {
|
|
297
|
-
const
|
|
297
|
+
const declaredSubtitle = hasDeclaredDisplay(resolvedCollection, "subtitle") ? subtitleKey : void 0;
|
|
298
|
+
const keys = resolvedCollection.listProperties.filter((key) => key !== titleColumn?.key && key !== declaredSubtitle);
|
|
298
299
|
keys.forEach((key, index) => {
|
|
299
300
|
const property = resolvedCollection.properties[key];
|
|
300
301
|
if (!property) return;
|
|
@@ -349,6 +350,7 @@ function CollectionListViewBinding({ collection, tableController, onEntityClick,
|
|
|
349
350
|
columnMode,
|
|
350
351
|
resolvedCollection,
|
|
351
352
|
titleColumn?.key,
|
|
353
|
+
subtitleKey,
|
|
352
354
|
slotKeys.tagsKey,
|
|
353
355
|
statusPropertyKey,
|
|
354
356
|
datePropertyKey,
|
|
@@ -731,6 +733,7 @@ var ListRow = React.memo(function ListRow({ entity, collection, onClick, selecte
|
|
|
731
733
|
selected
|
|
732
734
|
]);
|
|
733
735
|
const useColumnMode = !!collection.listProperties && collection.listProperties.length > 0;
|
|
736
|
+
const subtitleIsColumn = useColumnMode && !!slots.subtitle && !hasDeclaredDisplay(collection, "subtitle") && collection.listProperties.some((key) => key === slots.subtitle?.propertyKey);
|
|
734
737
|
return /* @__PURE__ */ jsxs("div", {
|
|
735
738
|
className: cls("@container flex items-center gap-4 cursor-pointer group transition-colors duration-200 relative h-full mx-2 rounded-lg", rowClasses, isActive || selected ? "bg-surface-active" : highlighted ? "bg-surface-hover" : "hover:bg-surface-hover"),
|
|
736
739
|
onClick: handleClick,
|
|
@@ -806,7 +809,7 @@ var ListRow = React.memo(function ListRow({ entity, collection, onClick, selecte
|
|
|
806
809
|
offSlot ? /* @__PURE__ */ jsx(MatchExplanation, {
|
|
807
810
|
match: offSlot,
|
|
808
811
|
label: fieldLabel(collection.properties, offSlot.field)
|
|
809
|
-
}) : slots.subtitle && /* @__PURE__ */ jsx("div", {
|
|
812
|
+
}) : slots.subtitle && !subtitleIsColumn && /* @__PURE__ */ jsx("div", {
|
|
810
813
|
className: "truncate mt-0.5",
|
|
811
814
|
children: /* @__PURE__ */ jsx(Typography, {
|
|
812
815
|
variant: "caption",
|
|
@@ -931,6 +934,28 @@ function ListCell({ column, entity, slots }) {
|
|
|
931
934
|
className: "whitespace-nowrap text-surface-400 dark:text-surface-500 font-medium",
|
|
932
935
|
children: formatCollectionDate(value, property, { relativeTimeLabels }) ?? "—"
|
|
933
936
|
});
|
|
937
|
+
if (property.type === "relation" && relationCardinality(property.relation) !== "many") {
|
|
938
|
+
if (value === void 0 || value === null) return /* @__PURE__ */ jsx(EmptyCell, {});
|
|
939
|
+
const loaded = typeof value === "object" ? loadedRelationName(value, property) : void 0;
|
|
940
|
+
if (loaded) return /* @__PURE__ */ jsx(Typography, {
|
|
941
|
+
component: "div",
|
|
942
|
+
variant: "body2",
|
|
943
|
+
className: "text-surface-600 dark:text-surface-300 truncate",
|
|
944
|
+
children: loaded
|
|
945
|
+
});
|
|
946
|
+
return /* @__PURE__ */ jsx(Typography, {
|
|
947
|
+
component: "div",
|
|
948
|
+
variant: "body2",
|
|
949
|
+
className: "text-surface-600 dark:text-surface-300 truncate",
|
|
950
|
+
children: /* @__PURE__ */ jsx(PropertyPreview, {
|
|
951
|
+
propertyKey: column.key,
|
|
952
|
+
value,
|
|
953
|
+
property,
|
|
954
|
+
size: "small",
|
|
955
|
+
textOnly: true
|
|
956
|
+
})
|
|
957
|
+
});
|
|
958
|
+
}
|
|
934
959
|
if (isComplexPropertyType(property) && !hasOwnPreview(property, column.key, propertyConfigs, authController)) return /* @__PURE__ */ jsx(Typography, {
|
|
935
960
|
variant: "caption",
|
|
936
961
|
className: "text-surface-500 dark:text-surface-400 truncate",
|