@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.
Files changed (66) hide show
  1. package/dist/collection_editor/serializable_types.d.ts +2 -0
  2. package/dist/collection_editor/ui/collection_editor/CollectionRelationsTab.d.ts +1 -1
  3. package/dist/components/CollectionPanel.js +22 -13
  4. package/dist/components/CollectionPanel.js.map +1 -1
  5. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
  6. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
  7. package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
  8. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +39 -14
  9. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
  10. package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +11 -0
  11. package/dist/components/CollectionViewBinding/CollectionViewContent.js +19 -2
  12. package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
  13. package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -1
  14. package/dist/components/CollectionViewBinding/EntityCardBinding.js +1 -1
  15. package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
  16. package/dist/components/CollectionViewBinding/SlotValue.js.map +1 -1
  17. package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +19 -1
  18. package/dist/components/CollectionViewBinding/usePreviewSlots.js +18 -7
  19. package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
  20. package/dist/components/EntityPreviewBinding.js.map +1 -1
  21. package/dist/components/HomePage/ContentHomePage.js +2 -3
  22. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  23. package/dist/components/RecordForm.d.ts +25 -4
  24. package/dist/components/RecordForm.js +21 -3
  25. package/dist/components/RecordForm.js.map +1 -1
  26. package/dist/components/RelationSelector.js.map +1 -1
  27. package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +13 -1
  28. package/dist/components/SelectableTable/filters/FilterFieldBinding.js +19 -3
  29. package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
  30. package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
  31. package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
  32. package/dist/components/history/EntityHistoryEntry.js.map +1 -1
  33. package/dist/data_import/utils/save_entities.d.ts +10 -2
  34. package/dist/data_import/utils/save_entities.js.map +1 -1
  35. package/dist/editor/markdown.d.ts +10 -0
  36. package/dist/editor/markdown.js.map +1 -1
  37. package/dist/form/PropertyFieldBinding.js +4 -2
  38. package/dist/form/PropertyFieldBinding.js.map +1 -1
  39. package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
  40. package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
  41. package/dist/hooks/useBuildSidePanel.d.ts +10 -0
  42. package/dist/hooks/useBuildSidePanel.js +43 -4
  43. package/dist/hooks/useBuildSidePanel.js.map +1 -1
  44. package/dist/hooks/useResolvedNavigationFrom.d.ts +14 -2
  45. package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.js +2 -2
  48. package/dist/mcp_view/app_modules.js +4 -2
  49. package/dist/mcp_view/app_modules.js.map +1 -1
  50. package/dist/mcp_view/index.d.ts +1 -1
  51. package/dist/mcp_view/index.js +2 -2
  52. package/dist/mcp_view/index.js.map +1 -1
  53. package/dist/mcp_view/payload.js +7 -2
  54. package/dist/mcp_view/payload.js.map +1 -1
  55. package/dist/mcp_view/screen.js +1 -1
  56. package/dist/mcp_view/screen.js.map +1 -1
  57. package/dist/mcp_view/tool_driver.d.ts +25 -6
  58. package/dist/mcp_view/tool_driver.js +73 -35
  59. package/dist/mcp_view/tool_driver.js.map +1 -1
  60. package/dist/preview/compact_text.d.ts +1 -1
  61. package/dist/preview/compact_text.js.map +1 -1
  62. package/dist/selection/resolve_selection.d.ts +10 -2
  63. package/dist/selection/resolve_selection.js.map +1 -1
  64. package/dist/util/property_utils.d.ts +2 -2
  65. package/dist/util/property_utils.js.map +1 -1
  66. package/package.json +9 -9
@@ -2,7 +2,7 @@ import { LazySidePanelBinding } from "../components/lazy_record_views.js";
2
2
  import { Suspense, useCallback, useEffect, useMemo, useRef } from "react";
3
3
  import { jsx } from "react/jsx-runtime";
4
4
  import { CircularProgressCenter } from "@rebasepro/ui";
5
- import { hasEntityId } from "@rebasepro/common";
5
+ import { hasEntityId, warnDeprecated } from "@rebasepro/common";
6
6
  import { CONTAINER_FULL_WIDTH, CollectionScopeProvider, SIDE_PANEL_DEFAULT_WIDTH, getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView, useComponentOverride, useCustomizationController, useLargeLayout } from "@rebasepro/app";
7
7
  import { useLocation } from "react-router";
8
8
  //#region src/hooks/useBuildSidePanel.tsx
@@ -48,6 +48,43 @@ function getEntityViewWidth(props, small, customizationController) {
48
48
  if (props.collection?.sideDialogWidth) return typeof props.collection.sideDialogWidth === "number" ? `${props.collection.sideDialogWidth}px` : props.collection.sideDialogWidth;
49
49
  return SIDE_PANEL_DEFAULT_WIDTH;
50
50
  }
51
+ /**
52
+ * Accept the names `open` / `replace` took in 0.28: `entityId` for `id`, and
53
+ * `onUpdate` for `onSaved`. Untyped callers still passing them would
54
+ * otherwise open a blank "new record" form for a record that exists (and
55
+ * duplicate it on save), and never hear about the save.
56
+ *
57
+ * `onUpdate` used to receive the saved entity; it now gets `{ entity }` built
58
+ * from the saved row, after any `onSaved`.
59
+ */
60
+ function normalizeDeprecatedSidePanelProps(props) {
61
+ const { entityId, onUpdate, ...current } = props;
62
+ let result = current;
63
+ if (entityId !== void 0) {
64
+ warnDeprecated("SidePanelBindingProps.entityId", "`entityId` in `useSidePanel().open()` / `replace()` is deprecated; use `id` instead.");
65
+ if (current.id === void 0) result = {
66
+ ...result,
67
+ id: entityId
68
+ };
69
+ }
70
+ if (onUpdate) {
71
+ warnDeprecated("SidePanelBindingProps.onUpdate", "`onUpdate` in `useSidePanel().open()` / `replace()` is deprecated; use `onSaved` instead.");
72
+ const onSaved = current.onSaved;
73
+ const path = current.path;
74
+ result = {
75
+ ...result,
76
+ onSaved: (params) => {
77
+ onSaved?.(params);
78
+ onUpdate({ entity: {
79
+ id: params.id,
80
+ path,
81
+ values: params.row
82
+ } });
83
+ }
84
+ };
85
+ }
86
+ return result;
87
+ }
51
88
  var useBuildSidePanel = (collectionRegistryController, urlController, navigationStateController, sideDialogsController, authController) => {
52
89
  const location = useLocation();
53
90
  const initialised = useRef(false);
@@ -101,7 +138,8 @@ var useBuildSidePanel = (collectionRegistryController, urlController, navigation
101
138
  sideDialogsController.close();
102
139
  }, [sideDialogsController]);
103
140
  const routesMounted = urlController.routesMounted !== false;
104
- const open = useCallback((propsIn) => {
141
+ const open = useCallback((propsGiven) => {
142
+ const propsIn = normalizeDeprecatedSidePanelProps(propsGiven);
105
143
  const props = routesMounted ? propsIn : {
106
144
  ...propsIn,
107
145
  updateUrl: false,
@@ -124,7 +162,8 @@ var useBuildSidePanel = (collectionRegistryController, urlController, navigation
124
162
  authController.user,
125
163
  routesMounted
126
164
  ]);
127
- const replace = useCallback((propsIn) => {
165
+ const replace = useCallback((propsGiven) => {
166
+ const propsIn = normalizeDeprecatedSidePanelProps(propsGiven);
128
167
  const props = routesMounted ? propsIn : {
129
168
  ...propsIn,
130
169
  updateUrl: false,
@@ -217,6 +256,6 @@ var propsToSidePanel = (props, buildUrlCollectionPath, resolveIdsFrom, smallLayo
217
256
  };
218
257
  };
219
258
  //#endregion
220
- export { buildSidePanelsFromUrl, getEntityViewWidth, useBuildSidePanel };
259
+ export { buildSidePanelsFromUrl, getEntityViewWidth, normalizeDeprecatedSidePanelProps, useBuildSidePanel };
221
260
 
222
261
  //# sourceMappingURL=useBuildSidePanel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useBuildSidePanel.js","names":[],"sources":["../../src/hooks/useBuildSidePanel.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport type { CustomizationController, SidePanelBindingProps, SideDialogPanelProps, SideDialogsController, SidePanelController, UrlController, NavigationStateController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport { useLocation } from \"react-router\";\nimport { NavigationViewInternal } from \"@rebasepro/app\";\nimport { getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView } from \"@rebasepro/app\";\nimport { resolvedSelectedEntityView } from \"../util/resolutions\";\nimport { CONTAINER_FULL_WIDTH, SIDE_PANEL_DEFAULT_WIDTH } from \"@rebasepro/app\";\nimport { useCustomizationController, useLargeLayout, useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { JSON_TAB_VALUE, HISTORY_TAB_VALUE } from \"../util/view_constants\";\nimport React, { Suspense } from \"react\";\nimport { CircularProgressCenter } from \"@rebasepro/ui\";\n// Lazy: this hook runs on every page (the side-panel provider is mounted by\n// RebaseNavigation), and the panel's form stack is not needed until one opens.\nimport { LazySidePanelBinding as SidePanelBinding } from \"../components/lazy_record_views\";\n\n/**\n * Thin wrapper that resolves the Entity.SidePanel component override.\n * Because the JSX is created inside `propsToSidePanel` (a plain function,\n * not a React component), we need this wrapper so the hook is called at the\n * top level of a React component per the Rules of Hooks.\n */\nfunction ResolvedSidePanelBindingInner(props: SidePanelBindingProps) {\n const Resolved = useComponentOverride<SidePanelBindingProps>(\"Entity.SidePanel\", SidePanelBinding);\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Resolved {...props}/>\n </Suspense>;\n}\n\nfunction ResolvedSidePanelBinding(props: SidePanelBindingProps) {\n if (props.collection) {\n return (\n <CollectionScopeProvider collection={props.collection}>\n <ResolvedSidePanelBindingInner {...props}/>\n </CollectionScopeProvider>\n );\n }\n return <ResolvedSidePanelBindingInner {...props}/>;\n}\n\nconst NEW_URL_HASH = \"new_side\";\nconst SIDE_URL_HASH = \"side\";\n\n/**\n * How wide the side panel opens.\n *\n * One width for the whole panel, whatever tab is showing. It used to depend on\n * the selected tab — the form got one width and a subcollection or custom view\n * got `calc(55vw + 768px)` — so the panel physically resized under the cursor\n * every time you switched tabs. And the \"form\" width was derived from how\n * deeply nested the collection's *properties* were, which is not a thing anyone\n * can predict from looking at the panel.\n *\n * Now: `width` prop, then the collection's `sideDialogWidth`, then a default\n * sized for the content the panel actually has to hold — the form column plus\n * its metadata rail — capped so it never eats the whole window.\n */\nexport function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string {\n if (small) return CONTAINER_FULL_WIDTH;\n\n if (props.width) {\n return typeof props.width === \"number\" ? `${props.width}px` : props.width;\n }\n if (props.collection?.sideDialogWidth) {\n return typeof props.collection.sideDialogWidth === \"number\"\n ? `${props.collection.sideDialogWidth}px`\n : props.collection.sideDialogWidth;\n }\n return SIDE_PANEL_DEFAULT_WIDTH;\n}\n\nexport const useBuildSidePanel = (collectionRegistryController: CollectionRegistryController,\n urlController: UrlController,\n navigationStateController: NavigationStateController,\n sideDialogsController: SideDialogsController,\n authController: AuthController\n): SidePanelController => {\n\n const location = useLocation();\n const initialised = useRef<boolean>(false);\n const currentPanelKeysRef = useRef<string[]>([]);\n const customizationController = useCustomizationController();\n\n const smallLayout = !useLargeLayout();\n\n useEffect(() => {\n\n const newFlag = location.hash === `#${NEW_URL_HASH}`;\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n\n if (!navigationStateController.loading) {\n if ((newFlag || sideFlag) && urlController.isUrlCollectionPath(location.pathname)) {\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], newFlag);\n for (let i = 0; i < panelsFromUrl.length; i++) {\n const props = panelsFromUrl[i];\n if (i === 0)\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n else\n sideDialogsController.open(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController))\n }\n }\n initialised.current = true;\n }\n }, [navigationStateController.loading]);\n\n // sync panels if URL changes with #side\n // Use a ref for currentPanelKeys so this effect only fires on URL changes,\n // not on panel state changes. This prevents a race condition with React Router 7\n // where close() clears panels before the URL updates, causing the effect to\n // re-open the panel from the stale #side hash.\n currentPanelKeysRef.current = sideDialogsController.sidePanels.map(p => p.key);\n useEffect(() => {\n if (initialised.current) {\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n if (sideFlag) {\n const currentKeys = currentPanelKeysRef.current;\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], false);\n // if we have more panels than determined by the url, we ignore the url. We might have references open\n if (panelsFromUrl.length <= currentKeys.length) {\n return;\n }\n const lastPanel = panelsFromUrl[panelsFromUrl.length - 1];\n const panelProps = propsToSidePanel(lastPanel, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController);\n const lastCurrentPanel = currentKeys.length > 0 ? currentKeys[currentKeys.length - 1] : undefined;\n if (!lastCurrentPanel || lastCurrentPanel !== panelProps.key) {\n sideDialogsController.replace(panelProps);\n }\n }\n }\n }, [location.pathname, location.hash]);\n\n // update side panels to match browser size\n // Only update panel widths on layout change — don't recreate components.\n // Recreating components would unmount/remount SidePanelBinding, losing\n // scroll position, unsaved form state, and triggering unnecessary data fetches.\n useEffect(() => {\n const updatedSidePanels = sideDialogsController.sidePanels.map(sidePanelProps => {\n if (sidePanelProps.additional) {\n const entityProps = sidePanelProps.additional as SidePanelBindingProps;\n const newWidth = getEntityViewWidth(entityProps, smallLayout, customizationController);\n if (sidePanelProps.width !== newWidth) {\n return { ...sidePanelProps,\nwidth: newWidth };\n }\n }\n return sidePanelProps;\n });\n sideDialogsController.setSidePanels(updatedSidePanels);\n }, [smallLayout]);\n\n const close = useCallback(() => {\n sideDialogsController.close();\n }, [sideDialogsController]);\n\n // Where no CMS route serves the page, a panel is an overlay and nothing\n // more: it writes no URL (one would lead nowhere) and offers no way to a\n // full-screen route that does not exist.\n const routesMounted = urlController.routesMounted !== false;\n\n const open = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.id)) {\n throw Error(\"To open a copy, pass the id of the record to copy\");\n }\n\n const defaultSelectedView = resolveDefaultSelectedView(\n props.collection ? props.collection.defaultSelectedView : undefined,\n {\n status: props.copy ? \"copy\" : (hasEntityId(props.id) ? \"existing\" : \"new\"),\n id: props.id\n }\n );\n\n sideDialogsController.open(\n propsToSidePanel({\n ...props,\n selectedTab: props.selectedTab ?? defaultSelectedView\n },\n urlController.buildUrlCollectionPath,\n urlController.resolveDatabasePathsFrom,\n smallLayout,\n customizationController,\n authController\n ));\n\n }, [sideDialogsController, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, authController.user, routesMounted]);\n\n const replace = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.id)) {\n throw Error(\"To open a copy, pass the id of the record to copy\");\n }\n\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n\n }, [urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, sideDialogsController, smallLayout, authController.user, routesMounted]);\n\n return useMemo(() => ({\n close,\n open,\n replace\n }), [close, open, replace]);\n};\n\nexport function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[] {\n\n const navigationViewsForPath: NavigationViewInternal<any>[] = getNavigationEntriesFromPath({\n path,\n collections\n });\n\n let sidePanel: SidePanelBindingProps<any> | undefined = undefined;\n let lastCollectionPath = \"\";\n let lastCollectionId: string | undefined = undefined;\n for (let i = 0; i < navigationViewsForPath.length; i++) {\n const navigationEntry = navigationViewsForPath[i];\n\n if (navigationEntry.type === \"collection\") {\n lastCollectionPath = navigationEntry.slug;\n lastCollectionId = navigationEntry.collection.slug;\n }\n\n const previousEntry = navigationViewsForPath[i - 1];\n if (navigationEntry.type === \"entity\") {\n sidePanel = {\n path: navigationEntry.slug,\n id: navigationEntry.entityId,\n copy: false,\n collection: navigationEntry.parentCollection,\n width: navigationEntry.parentCollection?.sideDialogWidth\n };\n } else if (navigationEntry.type === \"custom_view\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.view.key;\n }\n } else if (navigationEntry.type === \"collection\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.collection.slug;\n }\n }\n\n }\n\n // `edit` is not a registered view, so the navigation parser skips it. Pick it\n // up from the raw path so that reloading an edit URL reopens the edit form\n // rather than silently dropping the user back on the detail view.\n if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith(\"/edit\")) {\n sidePanel.selectedTab = \"edit\";\n }\n\n // When the URL doesn't contain a tab segment but the collection has a\n // defaultSelectedView, resolve it so the panel opens with the correct\n // width and the URL is updated on the next replace() cycle.\n if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {\n const defaultView = resolveDefaultSelectedView(\n sidePanel.collection.defaultSelectedView,\n {\n status: sidePanel.copy ? \"copy\" : (hasEntityId(sidePanel.id) ? \"existing\" : \"new\"),\n id: sidePanel.id\n }\n );\n if (defaultView) {\n sidePanel.selectedTab = defaultView;\n }\n }\n\n if (newFlag) {\n sidePanel = {\n path: lastCollectionPath,\n copy: false\n }\n }\n\n return sidePanel ? [sidePanel] : [];\n}\n\nconst propsToSidePanel = (props: SidePanelBindingProps,\n buildUrlCollectionPath: (path: string) => string,\n resolveIdsFrom: (pathWithAliases: string) => string,\n smallLayout: boolean,\n customizationController: CustomizationController,\n authController: AuthController\n): SideDialogPanelProps => {\n\n const collectionPath = removeInitialAndTrailingSlashes(props.path);\n\n // The list's state — search, filters, sort, view mode — read from the\n // address bar at the moment the panel opens. Not react-router's\n // `location.search`: the list writes its state with `replaceState`, which\n // the router does not observe, so that value is whatever the view mounted\n // with, and the list reads a panel URL built from it back as its state.\n const locationSearch = typeof window !== \"undefined\" ? window.location.search : \"\";\n\n // When updateUrl is explicitly false, don't generate URL paths — the dialog\n // opens as an overlay without affecting the browser URL / router.\n const shouldUpdateUrl = props.updateUrl !== false;\n\n // `buildUrlCollectionPath` encodes every segment of the data path it is\n // given, the record id among them, so the query and the hash go after it.\n const urlPath = shouldUpdateUrl\n ? (hasEntityId(props.id)\n ? `${buildUrlCollectionPath(`${collectionPath}/${props.id}${props.selectedTab ? \"/\" + props.selectedTab : \"\"}`)}${locationSearch}#${SIDE_URL_HASH}`\n : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}`)\n : undefined;\n\n const parentUrlPath = shouldUpdateUrl\n ? buildUrlCollectionPath(collectionPath)\n : undefined;\n\n const resolvedPanelProps: SidePanelBindingProps<any> = {\n ...props,\n formProps: props.formProps\n };\n\n const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);\n return {\n key: `${props.path}/${props.id}`,\n component: <ResolvedSidePanelBinding {...resolvedPanelProps}/>,\n urlPath: urlPath,\n parentUrlPath: parentUrlPath,\n width: entityViewWidth,\n onClose: props.onClose,\n additional: resolvedPanelProps\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAS,8BAA8B,OAA8B;CACjE,MAAM,WAAW,qBAA4C,oBAAoB,oBAAgB;CACjG,OAAO,oB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cAAc,MAAM,MAAM,cAAc,IAAI,IAAI,eAAe,GAAG,kBAClI,GAAG,uBAAuB,cAAc,IAAI,eAAe,GAAG,iBAClE,KAAA;CAEN,MAAM,gBAAgB,kBAChB,uBAAuB,cAAc,IACrC,KAAA;CAEN,MAAM,qBAAiD;EACnD,GAAG;EACH,WAAW,MAAM;CACrB;CAEA,MAAM,kBAAkB,mBAAmB,OAAO,aAAa,uBAAuB;CACtF,OAAO;EACH,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM;EAC5B,WAAW,oBAAC,0BAAD,EAA0B,GAAI,mBAAoB,CAAA;EACpD;EACM;EACf,OAAO;EACP,SAAS,MAAM;EACf,YAAY;CAChB;AACJ"}
1
+ {"version":3,"file":"useBuildSidePanel.js","names":[],"sources":["../../src/hooks/useBuildSidePanel.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId, warnDeprecated } from \"@rebasepro/common\";\nimport type { CustomizationController, SidePanelBindingProps, SideDialogPanelProps, SideDialogsController, SidePanelController, UrlController, NavigationStateController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport { useLocation } from \"react-router\";\nimport { NavigationViewInternal } from \"@rebasepro/app\";\nimport { getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView } from \"@rebasepro/app\";\nimport { resolvedSelectedEntityView } from \"../util/resolutions\";\nimport { CONTAINER_FULL_WIDTH, SIDE_PANEL_DEFAULT_WIDTH } from \"@rebasepro/app\";\nimport { useCustomizationController, useLargeLayout, useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { JSON_TAB_VALUE, HISTORY_TAB_VALUE } from \"../util/view_constants\";\nimport React, { Suspense } from \"react\";\nimport { CircularProgressCenter } from \"@rebasepro/ui\";\n// Lazy: this hook runs on every page (the side-panel provider is mounted by\n// RebaseNavigation), and the panel's form stack is not needed until one opens.\nimport { LazySidePanelBinding as SidePanelBinding } from \"../components/lazy_record_views\";\n\n/**\n * Thin wrapper that resolves the Entity.SidePanel component override.\n * Because the JSX is created inside `propsToSidePanel` (a plain function,\n * not a React component), we need this wrapper so the hook is called at the\n * top level of a React component per the Rules of Hooks.\n */\nfunction ResolvedSidePanelBindingInner(props: SidePanelBindingProps) {\n const Resolved = useComponentOverride<SidePanelBindingProps>(\"Entity.SidePanel\", SidePanelBinding);\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Resolved {...props}/>\n </Suspense>;\n}\n\nfunction ResolvedSidePanelBinding(props: SidePanelBindingProps) {\n if (props.collection) {\n return (\n <CollectionScopeProvider collection={props.collection}>\n <ResolvedSidePanelBindingInner {...props}/>\n </CollectionScopeProvider>\n );\n }\n return <ResolvedSidePanelBindingInner {...props}/>;\n}\n\nconst NEW_URL_HASH = \"new_side\";\nconst SIDE_URL_HASH = \"side\";\n\n/**\n * How wide the side panel opens.\n *\n * One width for the whole panel, whatever tab is showing. It used to depend on\n * the selected tab — the form got one width and a subcollection or custom view\n * got `calc(55vw + 768px)` — so the panel physically resized under the cursor\n * every time you switched tabs. And the \"form\" width was derived from how\n * deeply nested the collection's *properties* were, which is not a thing anyone\n * can predict from looking at the panel.\n *\n * Now: `width` prop, then the collection's `sideDialogWidth`, then a default\n * sized for the content the panel actually has to hold — the form column plus\n * its metadata rail — capped so it never eats the whole window.\n */\nexport function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string {\n if (small) return CONTAINER_FULL_WIDTH;\n\n if (props.width) {\n return typeof props.width === \"number\" ? `${props.width}px` : props.width;\n }\n if (props.collection?.sideDialogWidth) {\n return typeof props.collection.sideDialogWidth === \"number\"\n ? `${props.collection.sideDialogWidth}px`\n : props.collection.sideDialogWidth;\n }\n return SIDE_PANEL_DEFAULT_WIDTH;\n}\n\n/**\n * Accept the names `open` / `replace` took in 0.28: `entityId` for `id`, and\n * `onUpdate` for `onSaved`. Untyped callers still passing them would\n * otherwise open a blank \"new record\" form for a record that exists (and\n * duplicate it on save), and never hear about the save.\n *\n * `onUpdate` used to receive the saved entity; it now gets `{ entity }` built\n * from the saved row, after any `onSaved`.\n */\nexport function normalizeDeprecatedSidePanelProps<M extends Record<string, unknown>>(props: SidePanelBindingProps<M>): SidePanelBindingProps<M> {\n const { entityId, onUpdate, ...current } = props;\n let result: SidePanelBindingProps<M> = current;\n if (entityId !== undefined) {\n warnDeprecated(\"SidePanelBindingProps.entityId\",\n \"`entityId` in `useSidePanel().open()` / `replace()` is deprecated; use `id` instead.\");\n if (current.id === undefined) result = { ...result, id: entityId };\n }\n if (onUpdate) {\n warnDeprecated(\"SidePanelBindingProps.onUpdate\",\n \"`onUpdate` in `useSidePanel().open()` / `replace()` is deprecated; use `onSaved` instead.\");\n const onSaved = current.onSaved;\n const path = current.path;\n result = {\n ...result,\n onSaved: (params) => {\n onSaved?.(params);\n onUpdate({ entity: { id: params.id, path, values: params.row } });\n }\n };\n }\n return result;\n}\n\nexport const useBuildSidePanel = (collectionRegistryController: CollectionRegistryController,\n urlController: UrlController,\n navigationStateController: NavigationStateController,\n sideDialogsController: SideDialogsController,\n authController: AuthController\n): SidePanelController => {\n\n const location = useLocation();\n const initialised = useRef<boolean>(false);\n const currentPanelKeysRef = useRef<string[]>([]);\n const customizationController = useCustomizationController();\n\n const smallLayout = !useLargeLayout();\n\n useEffect(() => {\n\n const newFlag = location.hash === `#${NEW_URL_HASH}`;\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n\n if (!navigationStateController.loading) {\n if ((newFlag || sideFlag) && urlController.isUrlCollectionPath(location.pathname)) {\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], newFlag);\n for (let i = 0; i < panelsFromUrl.length; i++) {\n const props = panelsFromUrl[i];\n if (i === 0)\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n else\n sideDialogsController.open(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController))\n }\n }\n initialised.current = true;\n }\n }, [navigationStateController.loading]);\n\n // sync panels if URL changes with #side\n // Use a ref for currentPanelKeys so this effect only fires on URL changes,\n // not on panel state changes. This prevents a race condition with React Router 7\n // where close() clears panels before the URL updates, causing the effect to\n // re-open the panel from the stale #side hash.\n currentPanelKeysRef.current = sideDialogsController.sidePanels.map(p => p.key);\n useEffect(() => {\n if (initialised.current) {\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n if (sideFlag) {\n const currentKeys = currentPanelKeysRef.current;\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], false);\n // if we have more panels than determined by the url, we ignore the url. We might have references open\n if (panelsFromUrl.length <= currentKeys.length) {\n return;\n }\n const lastPanel = panelsFromUrl[panelsFromUrl.length - 1];\n const panelProps = propsToSidePanel(lastPanel, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController);\n const lastCurrentPanel = currentKeys.length > 0 ? currentKeys[currentKeys.length - 1] : undefined;\n if (!lastCurrentPanel || lastCurrentPanel !== panelProps.key) {\n sideDialogsController.replace(panelProps);\n }\n }\n }\n }, [location.pathname, location.hash]);\n\n // update side panels to match browser size\n // Only update panel widths on layout change — don't recreate components.\n // Recreating components would unmount/remount SidePanelBinding, losing\n // scroll position, unsaved form state, and triggering unnecessary data fetches.\n useEffect(() => {\n const updatedSidePanels = sideDialogsController.sidePanels.map(sidePanelProps => {\n if (sidePanelProps.additional) {\n const entityProps = sidePanelProps.additional as SidePanelBindingProps;\n const newWidth = getEntityViewWidth(entityProps, smallLayout, customizationController);\n if (sidePanelProps.width !== newWidth) {\n return { ...sidePanelProps,\nwidth: newWidth };\n }\n }\n return sidePanelProps;\n });\n sideDialogsController.setSidePanels(updatedSidePanels);\n }, [smallLayout]);\n\n const close = useCallback(() => {\n sideDialogsController.close();\n }, [sideDialogsController]);\n\n // Where no CMS route serves the page, a panel is an overlay and nothing\n // more: it writes no URL (one would lead nowhere) and offers no way to a\n // full-screen route that does not exist.\n const routesMounted = urlController.routesMounted !== false;\n\n const open = useCallback((propsGiven: SidePanelBindingProps<any>) => {\n const propsIn = normalizeDeprecatedSidePanelProps(propsGiven);\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.id)) {\n throw Error(\"To open a copy, pass the id of the record to copy\");\n }\n\n const defaultSelectedView = resolveDefaultSelectedView(\n props.collection ? props.collection.defaultSelectedView : undefined,\n {\n status: props.copy ? \"copy\" : (hasEntityId(props.id) ? \"existing\" : \"new\"),\n id: props.id\n }\n );\n\n sideDialogsController.open(\n propsToSidePanel({\n ...props,\n selectedTab: props.selectedTab ?? defaultSelectedView\n },\n urlController.buildUrlCollectionPath,\n urlController.resolveDatabasePathsFrom,\n smallLayout,\n customizationController,\n authController\n ));\n\n }, [sideDialogsController, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, authController.user, routesMounted]);\n\n const replace = useCallback((propsGiven: SidePanelBindingProps<any>) => {\n const propsIn = normalizeDeprecatedSidePanelProps(propsGiven);\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.id)) {\n throw Error(\"To open a copy, pass the id of the record to copy\");\n }\n\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n\n }, [urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, sideDialogsController, smallLayout, authController.user, routesMounted]);\n\n return useMemo(() => ({\n close,\n open,\n replace\n }), [close, open, replace]);\n};\n\nexport function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[] {\n\n const navigationViewsForPath: NavigationViewInternal<any>[] = getNavigationEntriesFromPath({\n path,\n collections\n });\n\n let sidePanel: SidePanelBindingProps<any> | undefined = undefined;\n let lastCollectionPath = \"\";\n let lastCollectionId: string | undefined = undefined;\n for (let i = 0; i < navigationViewsForPath.length; i++) {\n const navigationEntry = navigationViewsForPath[i];\n\n if (navigationEntry.type === \"collection\") {\n lastCollectionPath = navigationEntry.slug;\n lastCollectionId = navigationEntry.collection.slug;\n }\n\n const previousEntry = navigationViewsForPath[i - 1];\n if (navigationEntry.type === \"entity\") {\n sidePanel = {\n path: navigationEntry.slug,\n id: navigationEntry.entityId,\n copy: false,\n collection: navigationEntry.parentCollection,\n width: navigationEntry.parentCollection?.sideDialogWidth\n };\n } else if (navigationEntry.type === \"custom_view\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.view.key;\n }\n } else if (navigationEntry.type === \"collection\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.collection.slug;\n }\n }\n\n }\n\n // `edit` is not a registered view, so the navigation parser skips it. Pick it\n // up from the raw path so that reloading an edit URL reopens the edit form\n // rather than silently dropping the user back on the detail view.\n if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith(\"/edit\")) {\n sidePanel.selectedTab = \"edit\";\n }\n\n // When the URL doesn't contain a tab segment but the collection has a\n // defaultSelectedView, resolve it so the panel opens with the correct\n // width and the URL is updated on the next replace() cycle.\n if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {\n const defaultView = resolveDefaultSelectedView(\n sidePanel.collection.defaultSelectedView,\n {\n status: sidePanel.copy ? \"copy\" : (hasEntityId(sidePanel.id) ? \"existing\" : \"new\"),\n id: sidePanel.id\n }\n );\n if (defaultView) {\n sidePanel.selectedTab = defaultView;\n }\n }\n\n if (newFlag) {\n sidePanel = {\n path: lastCollectionPath,\n copy: false\n }\n }\n\n return sidePanel ? [sidePanel] : [];\n}\n\nconst propsToSidePanel = (props: SidePanelBindingProps,\n buildUrlCollectionPath: (path: string) => string,\n resolveIdsFrom: (pathWithAliases: string) => string,\n smallLayout: boolean,\n customizationController: CustomizationController,\n authController: AuthController\n): SideDialogPanelProps => {\n\n const collectionPath = removeInitialAndTrailingSlashes(props.path);\n\n // The list's state — search, filters, sort, view mode — read from the\n // address bar at the moment the panel opens. Not react-router's\n // `location.search`: the list writes its state with `replaceState`, which\n // the router does not observe, so that value is whatever the view mounted\n // with, and the list reads a panel URL built from it back as its state.\n const locationSearch = typeof window !== \"undefined\" ? window.location.search : \"\";\n\n // When updateUrl is explicitly false, don't generate URL paths — the dialog\n // opens as an overlay without affecting the browser URL / router.\n const shouldUpdateUrl = props.updateUrl !== false;\n\n // `buildUrlCollectionPath` encodes every segment of the data path it is\n // given, the record id among them, so the query and the hash go after it.\n const urlPath = shouldUpdateUrl\n ? (hasEntityId(props.id)\n ? `${buildUrlCollectionPath(`${collectionPath}/${props.id}${props.selectedTab ? \"/\" + props.selectedTab : \"\"}`)}${locationSearch}#${SIDE_URL_HASH}`\n : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}`)\n : undefined;\n\n const parentUrlPath = shouldUpdateUrl\n ? buildUrlCollectionPath(collectionPath)\n : undefined;\n\n const resolvedPanelProps: SidePanelBindingProps<any> = {\n ...props,\n formProps: props.formProps\n };\n\n const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);\n return {\n key: `${props.path}/${props.id}`,\n component: <ResolvedSidePanelBinding {...resolvedPanelProps}/>,\n urlPath: urlPath,\n parentUrlPath: parentUrlPath,\n width: entityViewWidth,\n onClose: props.onClose,\n additional: resolvedPanelProps\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAS,8BAA8B,OAA8B;CACjE,MAAM,WAAW,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AU,cAAc;CAM5B,IAAI,aAAa,CAAC,UAAU,eAAe,UAAU,YAAY;EAC7D,MAAM,cAAc,2BAChB,UAAU,WAAW,qBACrB;GACI,QAAQ,UAAU,OAAO,SAAU,YAAY,UAAU,EAAE,IAAI,aAAa;GAC5E,IAAI,UAAU;EAClB,CACJ;EACA,IAAI,aACA,UAAU,cAAc;CAEhC;CAEA,IAAI,SACA,YAAY;EACR,MAAM;EACN,MAAM;CACV;CAGJ,OAAO,YAAY,CAAC,SAAS,IAAI,CAAC;AACtC;AAEA,IAAM,oBAAoB,OACtB,wBACA,gBACA,aACA,yBACA,mBACuB;CAEvB,MAAM,iBAAiB,gCAAgC,MAAM,IAAI;CAOjE,MAAM,iBAAiB,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;CAIhF,MAAM,kBAAkB,MAAM,cAAc;CAI5C,MAAM,UAAU,kBACT,YAAY,MAAM,EAAE,IACjB,GAAG,uBAAuB,GAAG,eAAe,GAAG,MAAM,KAAK,MAAM,cAAc,MAAM,MAAM,cAAc,IAAI,IAAI,eAAe,GAAG,kBAClI,GAAG,uBAAuB,cAAc,IAAI,eAAe,GAAG,iBAClE,KAAA;CAEN,MAAM,gBAAgB,kBAChB,uBAAuB,cAAc,IACrC,KAAA;CAEN,MAAM,qBAAiD;EACnD,GAAG;EACH,WAAW,MAAM;CACrB;CAEA,MAAM,kBAAkB,mBAAmB,OAAO,aAAa,uBAAuB;CACtF,OAAO;EACH,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM;EAC5B,WAAW,oBAAC,0BAAD,EAA0B,GAAI,mBAAoB,CAAA;EACpD;EACM;EACf,OAAO;EACP,SAAS,MAAM;EACf,YAAY;CAChB;AACJ"}
@@ -1,5 +1,5 @@
1
1
  import type { EntityCustomView, AdminCollection } from "@rebasepro/cms-types";
2
- import { Entity, User } from "@rebasepro/types";
2
+ import { Entity, SDKCollectionClient, User } from "@rebasepro/types";
3
3
  import { RebaseContext } from "@rebasepro/cms-types";
4
4
  /**
5
5
  * @see resolveNavigationFrom
@@ -35,6 +35,18 @@ interface ResolvedNavigationEntityCustom<M extends Record<string, unknown>> {
35
35
  path: string;
36
36
  view: EntityCustomView<M>;
37
37
  }
38
+ /**
39
+ * What {@link resolveNavigationFrom} reads from the context it is handed: the
40
+ * navigation and the registry, and `data` to read an entity by its id. A
41
+ * `RebaseContext` is one.
42
+ *
43
+ * @group Hooks and utilities
44
+ */
45
+ export type NavigationResolutionContext<USER extends User = User> = Pick<RebaseContext<USER>, "navigationStateController" | "collectionRegistryController"> & {
46
+ data: {
47
+ collection(slug: string): Pick<SDKCollectionClient, "findById">;
48
+ };
49
+ };
38
50
  /**
39
51
  * Use this function to retrieve an array of navigation entries (resolved
40
52
  * collection, entity or entity custom_view) for the given path. You need to pass the app context
@@ -48,7 +60,7 @@ interface ResolvedNavigationEntityCustom<M extends Record<string, unknown>> {
48
60
  */
49
61
  export declare function resolveNavigationFrom<M extends Record<string, unknown>, USER extends User>({ path, context }: {
50
62
  path: string;
51
- context: RebaseContext<USER>;
63
+ context: NavigationResolutionContext<USER>;
52
64
  }): Promise<ResolvedNavigationEntry<M>[]>;
53
65
  /**
54
66
  * @group Hooks and utilities
@@ -1 +1 @@
1
- {"version":3,"file":"useResolvedNavigationFrom.js","names":[],"sources":["../../src/hooks/useResolvedNavigationFrom.tsx"],"sourcesContent":["\nimport type { EntityCustomView, AdminCollection } from \"@rebasepro/cms-types\";\nimport { Entity, User } from \"@rebasepro/types\";\nimport { RebaseContext } from \"@rebasepro/cms-types\";\nimport { useEffect, useState, useMemo } from \"react\";\nimport { getNavigationEntriesFromPath } from \"@rebasepro/app\";\nimport { useAdminContext } from \"./useAdminContext\";\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\nexport type ResolvedNavigationEntry<M extends Record<string, unknown>> =\n | ResolvedNavigationEntity<M>\n | ResolvedNavigationCollection<M>\n | ResolvedNavigationEntityCustom<M>;\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\nexport interface ResolvedNavigationEntity<M extends Record<string, unknown>> {\n type: \"entity\";\n entity: Entity<M>;\n entityId: string | number;\n path: string;\n parentCollection: AdminCollection<M>;\n}\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\nexport interface ResolvedNavigationCollection<M extends Record<string, unknown>> {\n type: \"collection\";\n path: string;\n collection: AdminCollection<M>;\n}\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\ninterface ResolvedNavigationEntityCustom<M extends Record<string, unknown>> {\n type: \"custom_view\";\n path: string;\n view: EntityCustomView<M>;\n}\n\n/**\n * Use this function to retrieve an array of navigation entries (resolved\n * collection, entity or entity custom_view) for the given path. You need to pass the app context\n * that you receive in different callbacks, such as the save hooks.\n *\n * It will take into account the `navigation` provided at the `Rebase` level.\n *\n * @param path\n * @param context\n * @group Hooks and utilities\n */\nexport function resolveNavigationFrom<M extends Record<string, unknown>, USER extends User>({\n path,\n context\n}: {\n path: string,\n context: RebaseContext<USER>\n}): Promise<ResolvedNavigationEntry<M>[]> {\n\n const data = context.data;\n const { navigationStateController, collectionRegistryController } = context;\n\n if (!navigationStateController || !collectionRegistryController) {\n throw Error(\"Calling resolveNavigationFrom, but main navigation has not yet been initialised\");\n }\n\n const navigationEntries = getNavigationEntriesFromPath({\n path,\n collections: collectionRegistryController.collections ?? []\n });\n\n const resultPromises: Promise<ResolvedNavigationEntry<any>>[] = navigationEntries\n .map((entry) => {\n if (entry.type === \"collection\") {\n return Promise.resolve(entry);\n } else if (entry.type === \"entity\") {\n const collection = collectionRegistryController.getCollection(entry.slug);\n if (!collection) {\n throw Error(`No collection defined in the navigation for the entity with path ${entry.slug}`);\n }\n // `context.data` is the flat SDK layer; re-wrap the row into the\n // Entity view-model the navigation entry expects. The address is\n // the one we just fetched by — reading it back off the row would\n // find nothing, since a row is only its columns.\n return data.collection(entry.slug).findById(entry.entityId)\n .then((row) => {\n if (!row) return undefined;\n const entity = { id: entry.entityId, path: entry.slug, values: row };\n return { ...entry,\nentity };\n });\n } else if (entry.type === \"custom_view\") {\n return Promise.resolve(entry);\n } else {\n throw Error(\"Unmapped element in useEntitiesFromPath\");\n }\n })\n .filter(v => Boolean(v)) as Promise<ResolvedNavigationEntry<any>>[];\n\n return Promise.all(resultPromises);\n}\n\n/**\n * @group Hooks and utilities\n */\nexport interface NavigationFromProps {\n path: string;\n}\n\n/**\n * @group Hooks and utilities\n */\nexport interface NavigationFrom<M extends Record<string, unknown>> {\n data?: ResolvedNavigationEntry<M>[]\n dataLoading: boolean,\n dataLoadingError?: Error\n}\n\n/**\n * Use this hook to retrieve an array of navigation entries (resolved\n * collection or entity) for the given path. You can use this hook\n * in any React component that lives under `Rebase`\n * @group Hooks and utilities\n */\nexport function useResolvedNavigationFrom<M extends Record<string, unknown>>(\n {\n path\n }: NavigationFromProps): NavigationFrom<M> {\n\n const context = useAdminContext();\n const { navigationStateController, collectionRegistryController } = context;\n\n const [data, setData] = useState<ResolvedNavigationEntry<M>[] | undefined>();\n const [dataLoading, setDataLoading] = useState<boolean>(false);\n const [dataLoadingError, setDataLoadingError] = useState<Error | undefined>();\n\n useEffect(() => {\n if (navigationStateController && collectionRegistryController) {\n setDataLoading(true);\n setDataLoadingError(undefined);\n resolveNavigationFrom<M, User>({ path,\ncontext })\n .then(setData)\n .catch((e) => setDataLoadingError(e))\n .finally(() => setDataLoading(false));\n }\n\n }, [path, context]);\n\n return useMemo(() => {\n if (!navigationStateController) {\n return { dataLoading: true };\n }\n return { data,\ndataLoading,\ndataLoadingError };\n }, [navigationStateController, data, dataLoading, dataLoadingError]);\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4DA,SAAgB,sBAA4E,EACxF,MACA,WAIsC;CAEtC,MAAM,OAAO,QAAQ;CACrB,MAAM,EAAE,2BAA2B,iCAAiC;CAEpE,IAAI,CAAC,6BAA6B,CAAC,8BAC/B,MAAM,MAAM,iFAAiF;CAQjG,MAAM,iBALoB,6BAA6B;EACnD;EACA,aAAa,6B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K;EAE/B,OAAO;GAAE;GACjB;GACA;EAAiB;CACb,GAAG;EAAC;EAA2B;EAAM;EAAa;CAAgB,CAAC;AACvE"}
1
+ {"version":3,"file":"useResolvedNavigationFrom.js","names":[],"sources":["../../src/hooks/useResolvedNavigationFrom.tsx"],"sourcesContent":["\nimport type { EntityCustomView, AdminCollection } from \"@rebasepro/cms-types\";\nimport { Entity, SDKCollectionClient, User } from \"@rebasepro/types\";\nimport { RebaseContext } from \"@rebasepro/cms-types\";\nimport { useEffect, useState, useMemo } from \"react\";\nimport { getNavigationEntriesFromPath } from \"@rebasepro/app\";\nimport { useAdminContext } from \"./useAdminContext\";\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\nexport type ResolvedNavigationEntry<M extends Record<string, unknown>> =\n | ResolvedNavigationEntity<M>\n | ResolvedNavigationCollection<M>\n | ResolvedNavigationEntityCustom<M>;\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\nexport interface ResolvedNavigationEntity<M extends Record<string, unknown>> {\n type: \"entity\";\n entity: Entity<M>;\n entityId: string | number;\n path: string;\n parentCollection: AdminCollection<M>;\n}\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\nexport interface ResolvedNavigationCollection<M extends Record<string, unknown>> {\n type: \"collection\";\n path: string;\n collection: AdminCollection<M>;\n}\n\n/**\n * @see resolveNavigationFrom\n * @group Hooks and utilities\n */\ninterface ResolvedNavigationEntityCustom<M extends Record<string, unknown>> {\n type: \"custom_view\";\n path: string;\n view: EntityCustomView<M>;\n}\n\n/**\n * What {@link resolveNavigationFrom} reads from the context it is handed: the\n * navigation and the registry, and `data` to read an entity by its id. A\n * `RebaseContext` is one.\n *\n * @group Hooks and utilities\n */\nexport type NavigationResolutionContext<USER extends User = User> =\n Pick<RebaseContext<USER>, \"navigationStateController\" | \"collectionRegistryController\"> & {\n data: { collection(slug: string): Pick<SDKCollectionClient, \"findById\"> };\n };\n\n/**\n * Use this function to retrieve an array of navigation entries (resolved\n * collection, entity or entity custom_view) for the given path. You need to pass the app context\n * that you receive in different callbacks, such as the save hooks.\n *\n * It will take into account the `navigation` provided at the `Rebase` level.\n *\n * @param path\n * @param context\n * @group Hooks and utilities\n */\nexport function resolveNavigationFrom<M extends Record<string, unknown>, USER extends User>({\n path,\n context\n}: {\n path: string,\n context: NavigationResolutionContext<USER>\n}): Promise<ResolvedNavigationEntry<M>[]> {\n\n const data = context.data;\n const { navigationStateController, collectionRegistryController } = context;\n\n if (!navigationStateController || !collectionRegistryController) {\n throw Error(\"Calling resolveNavigationFrom, but main navigation has not yet been initialised\");\n }\n\n const navigationEntries = getNavigationEntriesFromPath({\n path,\n collections: collectionRegistryController.collections ?? []\n });\n\n const resultPromises: Promise<ResolvedNavigationEntry<any>>[] = navigationEntries\n .map((entry) => {\n if (entry.type === \"collection\") {\n return Promise.resolve(entry);\n } else if (entry.type === \"entity\") {\n const collection = collectionRegistryController.getCollection(entry.slug);\n if (!collection) {\n throw Error(`No collection defined in the navigation for the entity with path ${entry.slug}`);\n }\n // `context.data` is the flat SDK layer; re-wrap the row into the\n // Entity view-model the navigation entry expects. The address is\n // the one we just fetched by — reading it back off the row would\n // find nothing, since a row is only its columns.\n return data.collection(entry.slug).findById(entry.entityId)\n .then((row) => {\n if (!row) return undefined;\n const entity = { id: entry.entityId, path: entry.slug, values: row };\n return { ...entry,\nentity };\n });\n } else if (entry.type === \"custom_view\") {\n return Promise.resolve(entry);\n } else {\n throw Error(\"Unmapped element in useEntitiesFromPath\");\n }\n })\n .filter(v => Boolean(v)) as Promise<ResolvedNavigationEntry<any>>[];\n\n return Promise.all(resultPromises);\n}\n\n/**\n * @group Hooks and utilities\n */\nexport interface NavigationFromProps {\n path: string;\n}\n\n/**\n * @group Hooks and utilities\n */\nexport interface NavigationFrom<M extends Record<string, unknown>> {\n data?: ResolvedNavigationEntry<M>[]\n dataLoading: boolean,\n dataLoadingError?: Error\n}\n\n/**\n * Use this hook to retrieve an array of navigation entries (resolved\n * collection or entity) for the given path. You can use this hook\n * in any React component that lives under `Rebase`\n * @group Hooks and utilities\n */\nexport function useResolvedNavigationFrom<M extends Record<string, unknown>>(\n {\n path\n }: NavigationFromProps): NavigationFrom<M> {\n\n const context = useAdminContext();\n const { navigationStateController, collectionRegistryController } = context;\n\n const [data, setData] = useState<ResolvedNavigationEntry<M>[] | undefined>();\n const [dataLoading, setDataLoading] = useState<boolean>(false);\n const [dataLoadingError, setDataLoadingError] = useState<Error | undefined>();\n\n useEffect(() => {\n if (navigationStateController && collectionRegistryController) {\n setDataLoading(true);\n setDataLoadingError(undefined);\n resolveNavigationFrom<M, User>({ path,\ncontext })\n .then(setData)\n .catch((e) => setDataLoadingError(e))\n .finally(() => setDataLoading(false));\n }\n\n }, [path, context]);\n\n return useMemo(() => {\n if (!navigationStateController) {\n return { dataLoading: true };\n }\n return { data,\ndataLoading,\ndataLoadingError };\n }, [navigationStateController, data, dataLoading, dataLoadingError]);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwEA,SAAgB,sBAA4E,EACxF,MACA,WAIsC;CAEtC,MAAM,OAAO,QAAQ;CACrB,MAAM,EAAE,2BAA2B,iCAAiC;CAEpE,IAAI,CAAC,6BAA6B,CAAC,8BAC/B,MAAM,MAAM,iFAAiF;CAQjG,MAAM,iBALoB,6BAA6B;EACnD;EACA,aAAa,6BAA6B,eAAe,CAAC;CAC9D,CAEgE,CAAA,CAC3D,KAAK,UAAU;EACZ,IAAI,MAAM,SAAS,cACf,OAAO,QAAQ,QAAQ,KAAK;OACzB,IAAI,MAAM,SAAS,UAAU;GAEhC,IAAI,CADe,6BAA6B,cAAc,MAAM,IAC/D,GACD,MAAM,MAAM,oEAAoE,MAAM,MAAM;GAMhG,OAAO,KAAK,WAAW,MAAM,IAAI,CAAC,CAAC,SAAS,MAAM,QAAQ,CAAC,CACtD,MAAM,QAAQ;IACX,IAAI,CAAC,KAAK,OAAO,KAAA;IACjB,MAAM,SAAS;KAAE,IAAI,MAAM;KAAU,MAAM,MAAM;KAAM,QAAQ;IAAI;IACnE,OAAO;KAAE,GAAG;KACpC;IAAO;GACa,CAAC;EACT,OAAO,IAAI,MAAM,SAAS,eACtB,OAAO,QAAQ,QAAQ,KAAK;OAE5B,MAAM,MAAM,yCAAyC;CAE7D,CAAC,CAAC,CACD,QAAO,MAAK,QAAQ,CAAC,CAAC;CAE3B,OAAO,QAAQ,IAAI,cAAc;AACrC;;;;;;;AAwBA,SAAgB,0BACZ,EACI,QACuC;CAE3C,MAAM,UAAU,gBAAgB;CAChC,MAAM,EAAE,2BAA2B,iCAAiC;CAEpE,MAAM,CAAC,MAAM,WAAW,SAAmD;CAC3E,MAAM,CAAC,aAAa,kBAAkB,SAAkB,KAAK;CAC7D,MAAM,CAAC,kBAAkB,uBAAuB,SAA4B;CAE5E,gBAAgB;EACZ,IAAI,6BAA6B,8BAA8B;GAC3D,eAAe,IAAI;GACnB,oBAAoB,KAAA,CAAS;GAC7B,sBAA+B;IAAE;IAC7C;GAAQ,CAAC,CAAC,CACO,KAAK,OAAO,CAAC,CACb,OAAO,MAAM,oBAAoB,CAAC,CAAC,CAAC,CACpC,cAAc,eAAe,KAAK,CAAC;EAC5C;CAEJ,GAAG,CAAC,MAAM,OAAO,CAAC;CAElB,OAAO,cAAc;EACjB,IAAI,CAAC,2BACD,OAAO,EAAE,aAAa,KAAK;EAE/B,OAAO;GAAE;GACjB;GACA;EAAiB;CACb,GAAG;EAAC;EAA2B;EAAM;EAAa;CAAgB,CAAC;AACvE"}
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ export * from "./form/index.js";
5
5
  export * from "./preview/index.js";
6
6
  export * from "./routes/index.js";
7
7
  export { EntityViewBinding, SelectionTableBinding, SelectableTable, SelectableTableContext, CollectionViewBinding, CollectionViewActions, CollectionCardViewBinding, EntityCardBinding, useSelectionController, PropertyConfigBadge, PropertyKeyHint, CollectionTableBinding, CollectionRowActions, VirtualTableInput, ArrayContainer, type ArrayEntryParams, ReferenceWidget, SearchIconsView, FieldCaption, EntityPreviewBinding, getFieldConfig, getFieldId, getDefaultFieldConfig, getDefaultFieldId, DEFAULT_FIELD_CONFIGS, editEntityAction, copyEntityAction, deleteEntityAction, resetPasswordAction, SidePanelProvider, Scaffold, AppBar, Drawer, DefaultDrawer, DrawerFooterActions, DrawerNavigationItem, DrawerNavigationGroup, AdminModeSyncer, RebaseCMS, RebaseShell, RebaseAuthGate, RebaseNavigation, RebaseLayout, RebaseRouteDefs, SideDialogs, useApp, CollectionPanel, CollectionsProvider, RecordForm, EntityFormPanel, RecordDetail, FieldValue } from "./components/index.js";
8
- export type { EntityViewBindingProps, CollectionViewBindingProps, SelectionProps, SelectableTableProps, CollectionPanelProps, CollectionPanelOptions, CollectionsProviderProps, RecordFormProps, RecordFormOptions, EntityFormPanelProps, RecordDetailProps, RecordDetailOptions, RecordPanelCollection, FieldValueProps, DrawerNavigationGroupProps, DrawerNavigationItemProps } from "./components/index.js";
8
+ export type { EntityViewBindingProps, CollectionViewBindingProps, SelectionProps, SelectableTableProps, CollectionPanelProps, CollectionPanelOptions, CollectionsProviderProps, RecordFormProps, RecordFormOptions, EntityFormPanelProps, EntityFormPanelSavedParams, RecordDetailProps, RecordDetailOptions, RecordPanelCollection, FieldValueProps, DrawerNavigationGroupProps, DrawerNavigationItemProps } from "./components/index.js";
9
9
  export * from "./hooks/index.js";
10
10
  export { addInitialSlash, removeInitialSlash, removeTrailingSlash, removeInitialAndTrailingSlashes, getLastSegment, getCollectionBySlugWithin, getCollectionPathsCombinations, resolveCollectionPathIds, mergeEntityActions, resolveEntityAction, resolveEntityView, isReferenceProperty, isRelationProperty, getIconForWidget, getIconForProperty, getPropertyInPath, getResolvedPropertyInPath, getBracketNotation, getPropertiesWithPropertiesOrder, getDefaultPropertiesOrder, getEntityPreviewKeys, getEntityTitlePropertyKey, getEntityTitlePropertyKeyForEntity } from "./util/index.js";
11
11
  export { mapPropertyToConfig, mapPropertiesToConfigs } from "./util/propertyConfigMapper.js";
package/dist/index.js CHANGED
@@ -63,7 +63,7 @@ import { SelectableTable } from "./components/SelectableTable/SelectableTable.js
63
63
  import { CollectionTableBinding } from "./components/CollectionTableBinding/CollectionTableBinding.js";
64
64
  import { VirtualTableInput } from "./components/CollectionTableBinding/index.js";
65
65
  import { useSelectionController } from "./components/CollectionViewBinding/useSelectionController.js";
66
- import { buildSidePanelsFromUrl, getEntityViewWidth, useBuildSidePanel } from "./hooks/useBuildSidePanel.js";
66
+ import { buildSidePanelsFromUrl, getEntityViewWidth, normalizeDeprecatedSidePanelProps, useBuildSidePanel } from "./hooks/useBuildSidePanel.js";
67
67
  import { resolveNavigationFrom, useResolvedNavigationFrom } from "./hooks/useResolvedNavigationFrom.js";
68
68
  import { useHistory } from "./hooks/useHistory.js";
69
69
  import { useBuildCollectionRegistryController } from "./hooks/navigation/useBuildCollectionRegistryController.js";
@@ -181,4 +181,4 @@ import { CollectionGenerationApiError, DEFAULT_COLLECTION_GENERATION_ENDPOINT, b
181
181
  import { MissingReferenceWidget } from "./collection_editor/ui/MissingReferenceWidget.js";
182
182
  import { getFullId, getFullIdPath, idToPropertiesPath, namespaceToPropertiesOrderPath, namespaceToPropertiesPath } from "./collection_editor/ui/collection_editor/util.js";
183
183
  import { SmallNavigationCard } from "./components/HomePage/SmallNavigationCard.js";
184
- export { AdditionalFieldValue, AdminModeSyncer, AppBar, ArrayContainer, ArrayCustomShapedFieldBinding, ArrayEnumPreview, ArrayOfMapsPreview, ArrayOfReferencesFieldBinding, ArrayOfReferencesPreview, ArrayOfStorageComponentsPreview, ArrayOfStringsPreview, ArrayOneOfPreview, ArrayPropertyEnumPreview, ArrayPropertyPreview, BasicExportAction, BlockFieldBinding, BooleanFilterField, BooleanPreview, CollectionAddButton, CollectionCardViewBinding, CollectionFiltersButton, CollectionGenerationApiError, CollectionPanel, CollectionRegistryContext, CollectionRowActions, CollectionSearchBar, CollectionTableBinding, CollectionTableToolbar, CollectionToolbar, CollectionViewActions, CollectionViewBinding, CollectionViewModeToggle, CollectionsProvider, CreationResultDialog, CustomViewRoute, DEFAULT_COLLECTION_GENERATION_ENDPOINT, DEFAULT_FIELD_CONFIGS, DataNewPropertiesMapping, DatePreview, DateTimeFieldBinding, DateTimeFilterField, DefaultDrawer, DetailViewBinding, Drawer, DrawerExpansionContext, DrawerFooterActions, DrawerNavigationGroup, DrawerNavigationItem, EXPORT_PAGE_SIZE, EditViewBinding, EditorAIControllerProvider, EditorCollectionAction, EmptyValue, EntityCardBinding, EntityForm, EntityFormBinding, EntityFormPanel, EntityPreviewBinding, EntityTableCell, EntityViewBinding, EnumValuesChip, ExportCollectionAction, FavouritesView, FieldBlock, FieldCaption, FieldHelperText, FieldValue, FormField, FormRail, FormSections, Highlighted, IMPORT_BATCH_MAX_BYTES, IMPORT_BATCH_SIZE, ImagePreview, ImportCollectionAction, ImportConversionProblems, ImportDataPreview, ImportFileUpload, ImportNewPropertyFieldPreview, ImportSaveInProgress, InlineEntityListPreview, KeyValueFieldBinding, KeyValuePreview, LABEL_ICON_SIZE, LabelWithIcon, LiveSchemaError, MAX_EXPORT_ROWS, MAX_SELECTION_ROWS, MapFieldBinding, MapPropertyPreview, MarkdownEditorFieldBinding, MatchExplanation, MissingReferenceWidget, MultiSelectFieldBinding, NAVIGATION_DEFAULT_GROUP_NAME, NavigationCard, NavigationCardBinding, NavigationGroup, NavigationStateContext, NestedEntityPreviewBoundary, NumberPropertyPreview, PropertyConfigBadge, PropertyFieldBinding, PropertyKeyHint, PropertyPreview, PropertySelectEntry, PropertyTableCell, ReadOnlyFieldBinding, RebaseAuthGate, RebaseCMS, RebaseLayout, RebaseNavigation, RebaseRoute, RebaseRouteDefs, RebaseShell, RecordDetail, RecordForm, RecordMeta, ReferenceFieldBinding, ReferenceFilterField, ReferencePreview, ReferenceWidget, RelationFilterField, RelationPreview, RepeatFieldBinding, SELECTION_PAGE_SIZE, Scaffold, SchemaChangeCancelled, SearchIconsView, SelectFieldBinding, SelectableTable, SelectableTableContext, SelectionMenu, SelectionTableBinding, SideDialogs, SidePanelControllerContext, SidePanelProvider, SkeletonPropertyComponent, SlotValue, SmallNavigationCard, StorageThumbnail, StorageThumbnailInternal, StorageUploadFieldBinding, StringNumberFilterField, StringPropertyPreview, SwitchFieldBinding, TagChips, TextFieldBinding, UrlComponentPreview, UrlContext, UserPreview, VectorFieldBinding, VirtualTableInput, addInitialSlash, asUnavailable, buildCollectionGenerationCallback, buildSidePanelsFromUrl, convertDataToEntity, convertFileToJson, convertImportData, copyEntityAction, createLiveSchemaClient, createStaticDataController, deleteEntityAction, detectCsvDelimiter, downloadBlob, downloadDataAsCsv, downloadEntitiesExport, editEntityAction, entityActionName, entryToCSVRow, escapeCsvFormula, extractTouchedValues, fetchAllEntitiesForExport, fieldLabel, flattenEntry, formatDatePreview, fromSerializableCollectionConfig, fromSerializableCollectionConfigs, fromSerializableProperties, fromSerializableProperty, getBracketNotation, getChanges, getCollectionBySlugWithin, getCollectionPathsCombinations, getDatePropertyMode, getDatePropertyTimezone, getDefaultFieldConfig, getDefaultFieldId, getDefaultPropertiesOrder, getEntityCSVExportableData, getEntityJsonExportableData, getEntityPreviewKeys, getEntityTitlePropertyKey, getEntityTitlePropertyKeyForEntity, getEntityViewWidth, getFieldConfig, getFieldId, getFullId, getFullIdPath, getIconForProperty, getIconForWidget, getInferenceType, getInitialEntityValues, getLastSegment, getParentLinkValues, getPropertiesWithPropertiesOrder, getPropertyInPath, getResolvedPropertyInPath, getTouchedPropertyValues, getUnappliedLocalChanges, getUserLabel, idToPropertiesPath, isEmptyPreviewValue, isReferenceProperty, isRelationProperty, isSchemaChangeCancelled, isSelfLabellingProperty, mapPropertiesToConfigs, mapPropertyToConfig, mappedColumnTarget, mergeEntityActions, namespaceToPropertiesOrderPath, namespaceToPropertiesPath, overlayEdit, parseCsvRows, parseCsvToObjects, processValueMapping, propertiesToColumns, removeEmptyContainers, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, renderSkeletonCaptionText, renderSkeletonIcon, renderSkeletonImageThumbnail, renderSkeletonText, resetPasswordAction, resolveCollectionPathIds, resolveCollectionSlotKeys, resolveEntityAction, resolveEntityActionState, resolveEntityView, resolveNavigationFrom, resolveSelection, sanitizeUrl, saveImportedEntities, selectionQueryToFindParams, serializeSelectionQuery, slashDateOrdersByColumn, spanClass, toSerializableCollectionConfig, toSerializableProperties, toSerializableProperty, unescapeCsvFormula, unlinkEntityAction, useAdminContext, useApp, useBreadcrumbsController, useBuildCollectionRegistryController, useBuildNavigationStateController, useBuildSidePanel, useBuildUrlController, useChildViewSource, useClearRestoreValue, useCollectionDataController, useCollectionEditorController, useCollectionLargeLayout, useCollectionRegistryController, useCollectionSlotKeys, useCollectionsConfigController, useDateFnsLocale, useDrawerExpandedWhile, useDrawerExpansion, useEntitySlots, useEntityTitle, useHistory, useImagePlace, useImportConfig, useJsonCollectionsConfigController, useLiveSchemaEditing, useLocalCollectionsConfigController, useNavigationStateController, useProvidedEditorAIController, useResolvedCollections, useResolvedNavigationFrom, useResolvedUser, useResolvedViews, useSearchExplanation, useSelectionController, useSelectionDialog, useSideDialogContext, useSideDialogsController, useSidePanel, useToolbarLabels, useTopLevelNavigation, useUrlController, validateCollectionJson, zodToFormErrors };
184
+ export { AdditionalFieldValue, AdminModeSyncer, AppBar, ArrayContainer, ArrayCustomShapedFieldBinding, ArrayEnumPreview, ArrayOfMapsPreview, ArrayOfReferencesFieldBinding, ArrayOfReferencesPreview, ArrayOfStorageComponentsPreview, ArrayOfStringsPreview, ArrayOneOfPreview, ArrayPropertyEnumPreview, ArrayPropertyPreview, BasicExportAction, BlockFieldBinding, BooleanFilterField, BooleanPreview, CollectionAddButton, CollectionCardViewBinding, CollectionFiltersButton, CollectionGenerationApiError, CollectionPanel, CollectionRegistryContext, CollectionRowActions, CollectionSearchBar, CollectionTableBinding, CollectionTableToolbar, CollectionToolbar, CollectionViewActions, CollectionViewBinding, CollectionViewModeToggle, CollectionsProvider, CreationResultDialog, CustomViewRoute, DEFAULT_COLLECTION_GENERATION_ENDPOINT, DEFAULT_FIELD_CONFIGS, DataNewPropertiesMapping, DatePreview, DateTimeFieldBinding, DateTimeFilterField, DefaultDrawer, DetailViewBinding, Drawer, DrawerExpansionContext, DrawerFooterActions, DrawerNavigationGroup, DrawerNavigationItem, EXPORT_PAGE_SIZE, EditViewBinding, EditorAIControllerProvider, EditorCollectionAction, EmptyValue, EntityCardBinding, EntityForm, EntityFormBinding, EntityFormPanel, EntityPreviewBinding, EntityTableCell, EntityViewBinding, EnumValuesChip, ExportCollectionAction, FavouritesView, FieldBlock, FieldCaption, FieldHelperText, FieldValue, FormField, FormRail, FormSections, Highlighted, IMPORT_BATCH_MAX_BYTES, IMPORT_BATCH_SIZE, ImagePreview, ImportCollectionAction, ImportConversionProblems, ImportDataPreview, ImportFileUpload, ImportNewPropertyFieldPreview, ImportSaveInProgress, InlineEntityListPreview, KeyValueFieldBinding, KeyValuePreview, LABEL_ICON_SIZE, LabelWithIcon, LiveSchemaError, MAX_EXPORT_ROWS, MAX_SELECTION_ROWS, MapFieldBinding, MapPropertyPreview, MarkdownEditorFieldBinding, MatchExplanation, MissingReferenceWidget, MultiSelectFieldBinding, NAVIGATION_DEFAULT_GROUP_NAME, NavigationCard, NavigationCardBinding, NavigationGroup, NavigationStateContext, NestedEntityPreviewBoundary, NumberPropertyPreview, PropertyConfigBadge, PropertyFieldBinding, PropertyKeyHint, PropertyPreview, PropertySelectEntry, PropertyTableCell, ReadOnlyFieldBinding, RebaseAuthGate, RebaseCMS, RebaseLayout, RebaseNavigation, RebaseRoute, RebaseRouteDefs, RebaseShell, RecordDetail, RecordForm, RecordMeta, ReferenceFieldBinding, ReferenceFilterField, ReferencePreview, ReferenceWidget, RelationFilterField, RelationPreview, RepeatFieldBinding, SELECTION_PAGE_SIZE, Scaffold, SchemaChangeCancelled, SearchIconsView, SelectFieldBinding, SelectableTable, SelectableTableContext, SelectionMenu, SelectionTableBinding, SideDialogs, SidePanelControllerContext, SidePanelProvider, SkeletonPropertyComponent, SlotValue, SmallNavigationCard, StorageThumbnail, StorageThumbnailInternal, StorageUploadFieldBinding, StringNumberFilterField, StringPropertyPreview, SwitchFieldBinding, TagChips, TextFieldBinding, UrlComponentPreview, UrlContext, UserPreview, VectorFieldBinding, VirtualTableInput, addInitialSlash, asUnavailable, buildCollectionGenerationCallback, buildSidePanelsFromUrl, convertDataToEntity, convertFileToJson, convertImportData, copyEntityAction, createLiveSchemaClient, createStaticDataController, deleteEntityAction, detectCsvDelimiter, downloadBlob, downloadDataAsCsv, downloadEntitiesExport, editEntityAction, entityActionName, entryToCSVRow, escapeCsvFormula, extractTouchedValues, fetchAllEntitiesForExport, fieldLabel, flattenEntry, formatDatePreview, fromSerializableCollectionConfig, fromSerializableCollectionConfigs, fromSerializableProperties, fromSerializableProperty, getBracketNotation, getChanges, getCollectionBySlugWithin, getCollectionPathsCombinations, getDatePropertyMode, getDatePropertyTimezone, getDefaultFieldConfig, getDefaultFieldId, getDefaultPropertiesOrder, getEntityCSVExportableData, getEntityJsonExportableData, getEntityPreviewKeys, getEntityTitlePropertyKey, getEntityTitlePropertyKeyForEntity, getEntityViewWidth, getFieldConfig, getFieldId, getFullId, getFullIdPath, getIconForProperty, getIconForWidget, getInferenceType, getInitialEntityValues, getLastSegment, getParentLinkValues, getPropertiesWithPropertiesOrder, getPropertyInPath, getResolvedPropertyInPath, getTouchedPropertyValues, getUnappliedLocalChanges, getUserLabel, idToPropertiesPath, isEmptyPreviewValue, isReferenceProperty, isRelationProperty, isSchemaChangeCancelled, isSelfLabellingProperty, mapPropertiesToConfigs, mapPropertyToConfig, mappedColumnTarget, mergeEntityActions, namespaceToPropertiesOrderPath, namespaceToPropertiesPath, normalizeDeprecatedSidePanelProps, overlayEdit, parseCsvRows, parseCsvToObjects, processValueMapping, propertiesToColumns, removeEmptyContainers, removeInitialAndTrailingSlashes, removeInitialSlash, removeTrailingSlash, renderSkeletonCaptionText, renderSkeletonIcon, renderSkeletonImageThumbnail, renderSkeletonText, resetPasswordAction, resolveCollectionPathIds, resolveCollectionSlotKeys, resolveEntityAction, resolveEntityActionState, resolveEntityView, resolveNavigationFrom, resolveSelection, sanitizeUrl, saveImportedEntities, selectionQueryToFindParams, serializeSelectionQuery, slashDateOrdersByColumn, spanClass, toSerializableCollectionConfig, toSerializableProperties, toSerializableProperty, unescapeCsvFormula, unlinkEntityAction, useAdminContext, useApp, useBreadcrumbsController, useBuildCollectionRegistryController, useBuildNavigationStateController, useBuildSidePanel, useBuildUrlController, useChildViewSource, useClearRestoreValue, useCollectionDataController, useCollectionEditorController, useCollectionLargeLayout, useCollectionRegistryController, useCollectionSlotKeys, useCollectionsConfigController, useDateFnsLocale, useDrawerExpandedWhile, useDrawerExpansion, useEntitySlots, useEntityTitle, useHistory, useImagePlace, useImportConfig, useJsonCollectionsConfigController, useLiveSchemaEditing, useLocalCollectionsConfigController, useNavigationStateController, useProvidedEditorAIController, useResolvedCollections, useResolvedNavigationFrom, useResolvedUser, useResolvedViews, useSearchExplanation, useSelectionController, useSelectionDialog, useSideDialogContext, useSideDialogsController, useSidePanel, useToolbarLabels, useTopLevelNavigation, useUrlController, validateCollectionJson, zodToFormErrors };
@@ -64,10 +64,12 @@ function AppCollectionPanel(props) {
64
64
  }
65
65
  function AppRecordForm({ collectionOverrides, ...props }) {
66
66
  useCollectionCheck()(collectionPropOf(props.collection, props.path).path);
67
- const { formAutoSave: _formAutoSave, ...overrides } = collectionOverrides ?? {};
68
67
  return /* @__PURE__ */ jsx(RecordForm, {
69
68
  ...props,
70
- ...collectionOverrides && { collectionOverrides: overrides }
69
+ collectionOverrides: {
70
+ ...collectionOverrides,
71
+ formAutoSave: false
72
+ }
71
73
  });
72
74
  }
73
75
  function AppRecordDetail(props) {
@@ -1 +1 @@
1
- {"version":3,"file":"app_modules.js","names":[],"sources":["../../src/mcp_view/app_modules.tsx"],"sourcesContent":["/**\n * What an app the model wrote imports (show_app): the modules of\n * `MCP_APP_MODULES`, each the package's own exports — `@rebasepro/cms`'s\n * blocks, `@rebasepro/app`'s row hooks, the UI kit, React — so the code reads\n * as Rebase code does anywhere, and the parts are the ones the admin panel is\n * made of.\n *\n * One thing differs from the packages: an app was opened with a list of\n * collections (show_app's `collections`), and every export that names one\n * holds the app to it, with an error that says which it may use. The rows an\n * app reads and writes go through the tool driver, as the person, under their\n * RLS and their connection's scopes: that is what bounds an app, which can do\n * nothing the model could not with the same tools. `useRowWrites` asks them\n * before each write (`confirmingDriver` in `tool_driver.ts`), a courtesy\n * against an app writing without a click; the admin's own controls in it — a\n * form's Save, a delete — behave as on a show_collection screen. A form whose\n * overrides make it save itself is not handed to an app: it would write on\n * mount, unasked.\n */\nimport React, { createContext, useCallback, useContext, useMemo } from \"react\";\nimport * as jsxRuntime from \"react/jsx-runtime\";\nimport * as UI from \"@rebasepro/ui\";\nimport { useAggregate, useRow, useRowCount, useRows, useRowWrites, type UseRowWritesResult } from \"@rebasepro/app\";\nimport type { SidePanelBindingProps, SidePanelController } from \"@rebasepro/cms-types\";\nimport {\n getCollectionDataPath,\n type McpAppModule,\n type McpAppModuleExport\n} from \"@rebasepro/types\";\nimport { CollectionPanel, type CollectionPanelProps } from \"../components/CollectionPanel\";\nimport { RecordForm, type RecordFormProps } from \"../components/RecordForm\";\nimport { RecordDetail, type RecordDetailProps } from \"../components/RecordDetail\";\nimport { FieldValue, type FieldValueProps } from \"../components/FieldValue\";\nimport {\n CollectionFiltersButton,\n CollectionSearchBar,\n CollectionToolbar,\n CollectionViewModeToggle\n} from \"../components/CollectionViewBinding/CollectionToolbar\";\nimport { CollectionAddButton } from \"../components/CollectionViewBinding/CollectionAddButton\";\nimport { FormField } from \"../form/FormField\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { collectionPropOf } from \"../components/collection_prop\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\n\n/** The collections the app was opened with, by the names the model gave. */\nconst AppCollectionsContext = createContext<readonly string[] | undefined>(undefined);\n\n/** Around an app's component: the collections its imports may name. */\nexport function AppCollections({ names, children }: { names: readonly string[]; children: React.ReactNode }) {\n return <AppCollectionsContext.Provider value={names}>{children}</AppCollectionsContext.Provider>;\n}\n\n/**\n * Throws, for a collection the app was not opened with. A name counts by\n * what the model listed, or by the collection it names — its slug or the\n * name the tools take — so `orders` and the table it lives in are one.\n */\nfunction useCollectionCheck(): (name: string | undefined) => void {\n const allowed = useContext(AppCollectionsContext);\n const registry = useCollectionRegistryController();\n return useCallback((name: string | undefined) => {\n if (allowed === undefined || name === undefined || allowed.includes(name)) return;\n const collection = registry.getCollection(name);\n if (collection && (allowed.includes(collection.slug)\n || allowed.includes(getCollectionDataPath(collection)))) return;\n throw new Error(`\"${name}\" is not one of this app's collections (${allowed.join(\", \")}). `\n + \"List it in show_app's `collections`.\");\n }, [allowed, registry]);\n}\n\nfunction AppCollectionPanel(props: CollectionPanelProps) {\n useCollectionCheck()(collectionPropOf(props.collection, props.path).path);\n return <CollectionPanel {...props}/>;\n}\n\nfunction AppRecordForm({ collectionOverrides, ...props }: RecordFormProps) {\n useCollectionCheck()(collectionPropOf(props.collection, props.path).path);\n // A form that saves itself writes the values it was seeded with on mount.\n const { formAutoSave: _formAutoSave, ...overrides } = collectionOverrides ?? {};\n return <RecordForm {...props} {...(collectionOverrides && { collectionOverrides: overrides })}/>;\n}\n\nfunction AppRecordDetail(props: RecordDetailProps) {\n useCollectionCheck()(collectionPropOf(props.collection, props.path).path);\n return <RecordDetail {...props}/>;\n}\n\nfunction AppFieldValue(props: FieldValueProps) {\n useCollectionCheck()(props.collection);\n return <FieldValue {...props}/>;\n}\n\nfunction useAppSidePanel(): SidePanelController {\n const check = useCollectionCheck();\n const panel = useSidePanel();\n return useMemo(() => {\n const checked = <M extends Record<string, unknown>>(props: SidePanelBindingProps<M>) => {\n check(props.path);\n return props;\n };\n return {\n close: () => panel.close(),\n open: props => panel.open(checked(props)),\n replace: props => panel.replace(checked(props))\n };\n }, [panel, check]);\n}\n\n/** The row hooks, each held to the app's collections. */\nconst useAppRows: typeof useRows = (collection, options) => {\n useCollectionCheck()(collection);\n return useRows(collection, options);\n};\n\nconst useAppRow: typeof useRow = (collection, id) => {\n useCollectionCheck()(collection);\n return useRow(collection, id);\n};\n\nconst useAppRowCount: typeof useRowCount = (collection, where) => {\n useCollectionCheck()(collection);\n return useRowCount(collection, where);\n};\n\nconst useAppAggregate: typeof useAggregate = (collection, params) => {\n useCollectionCheck()(collection);\n return useAggregate(collection, params);\n};\n\n/** Writes are checked when they are made: a refused one rejects, as a failed write does. */\nfunction useAppRowWrites(): UseRowWritesResult {\n const check = useCollectionCheck();\n const writes = useRowWrites();\n return useMemo(() => {\n const checked = <T, >(collection: string, write: () => Promise<T>): Promise<T> => {\n try {\n check(collection);\n } catch (error) {\n return Promise.reject(error);\n }\n return write();\n };\n return {\n ...writes,\n create: (collection, values, id) => checked(collection, () => writes.create(collection, values, id)),\n update: (collection, id, values) => checked(collection, () => writes.update(collection, id, values)),\n remove: (collection, id) => checked(collection, () => writes.remove(collection, id))\n };\n }, [writes, check]);\n}\n\n/** A module's served exports: exactly its names in `MCP_APP_MODULES`, no more, no fewer. */\ntype Served<M extends McpAppModule> = Record<McpAppModuleExport<M>, unknown>;\n\nconst APP_MODULE: Served<\"@rebasepro/app\"> = {\n useRows: useAppRows,\n useRow: useAppRow,\n useRowCount: useAppRowCount,\n useAggregate: useAppAggregate,\n useRowWrites: useAppRowWrites\n};\n\nconst CMS_MODULE: Served<\"@rebasepro/cms\"> = {\n CollectionPanel: AppCollectionPanel,\n CollectionToolbar,\n CollectionSearchBar,\n CollectionFiltersButton,\n CollectionViewModeToggle,\n CollectionAddButton,\n RecordForm: AppRecordForm,\n RecordDetail: AppRecordDetail,\n FormField,\n FieldValue: AppFieldValue,\n useSidePanel: useAppSidePanel\n};\n\n/** Every module an app may import, by name. */\nexport const APP_MODULE_EXPORTS: Record<McpAppModule, object> = {\n \"react\": React,\n \"react/jsx-runtime\": jsxRuntime,\n \"@rebasepro/ui\": UI,\n \"@reb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QAAQ,kBAAkB,OAAO,OAAO,YAAY,QAAQ,EAAE,CAAC;GACnG,SAAS,YAAY,IAAI,WAAW,QAAQ,kBAAkB,OAAO,OAAO,YAAY,IAAI,MAAM,CAAC;GACnG,SAAS,YAAY,OAAO,QAAQ,kBAAkB,OAAO,OAAO,YAAY,EAAE,CAAC;EACvF;CACJ,GAAG,CAAC,QAAQ,KAAK,CAAC;AACtB;;AA4BA,IAAa,qBAAmD;CAC5D,SAAS;CACT,qBAAqB;CACrB,iBAAiB;CACjB,kBAAkB;EA1BlB,SAAS;EACT,QAAQ;EACR,aAAa;EACb,cAAc;EACd,cAAc;CAsBI;CAClB,kBAAkB;EAnBlB,iBAAiB;EACjB;EACA;EACA;EACA;EACA;EACA,YAAY;EACZ,cAAc;EACd;EACA,YAAY;EACZ,cAAc;CASI;AACtB"}
1
+ {"version":3,"file":"app_modules.js","names":[],"sources":["../../src/mcp_view/app_modules.tsx"],"sourcesContent":["/**\n * What an app the model wrote imports (show_app): the modules of\n * `MCP_APP_MODULES`, each the package's own exports — `@rebasepro/cms`'s\n * blocks, `@rebasepro/app`'s row hooks, the UI kit, React — so the code reads\n * as Rebase code does anywhere, and the parts are the ones the admin panel is\n * made of.\n *\n * One thing differs from the packages: an app was opened with a list of\n * collections (show_app's `collections`), and every export that names one\n * holds the app to it, with an error that says which it may use. The rows an\n * app reads and writes go through the tool driver, as the person, under their\n * RLS and their connection's scopes: that is what bounds an app, which can do\n * nothing the model could not with the same tools. `useRowWrites` asks them\n * before each write (`confirmingDriver` in `tool_driver.ts`), a courtesy\n * against an app writing without a click; the admin's own controls in it — a\n * form's Save, a delete — behave as on a show_collection screen. A form whose\n * overrides make it save itself is not handed to an app: it would write on\n * mount, unasked.\n */\nimport React, { createContext, useCallback, useContext, useMemo } from \"react\";\nimport * as jsxRuntime from \"react/jsx-runtime\";\nimport * as UI from \"@rebasepro/ui\";\nimport { useAggregate, useRow, useRowCount, useRows, useRowWrites, type UseRowWritesResult } from \"@rebasepro/app\";\nimport type { SidePanelBindingProps, SidePanelController } from \"@rebasepro/cms-types\";\nimport {\n getCollectionDataPath,\n type McpAppModule,\n type McpAppModuleExport\n} from \"@rebasepro/types\";\nimport { CollectionPanel, type CollectionPanelProps } from \"../components/CollectionPanel\";\nimport { RecordForm, type RecordFormProps } from \"../components/RecordForm\";\nimport { RecordDetail, type RecordDetailProps } from \"../components/RecordDetail\";\nimport { FieldValue, type FieldValueProps } from \"../components/FieldValue\";\nimport {\n CollectionFiltersButton,\n CollectionSearchBar,\n CollectionToolbar,\n CollectionViewModeToggle\n} from \"../components/CollectionViewBinding/CollectionToolbar\";\nimport { CollectionAddButton } from \"../components/CollectionViewBinding/CollectionAddButton\";\nimport { FormField } from \"../form/FormField\";\nimport { useSidePanel } from \"../hooks/useSidePanel\";\nimport { collectionPropOf } from \"../components/collection_prop\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\n\n/** The collections the app was opened with, by the names the model gave. */\nconst AppCollectionsContext = createContext<readonly string[] | undefined>(undefined);\n\n/** Around an app's component: the collections its imports may name. */\nexport function AppCollections({ names, children }: { names: readonly string[]; children: React.ReactNode }) {\n return <AppCollectionsContext.Provider value={names}>{children}</AppCollectionsContext.Provider>;\n}\n\n/**\n * Throws, for a collection the app was not opened with. A name counts by\n * what the model listed, or by the collection it names — its slug or the\n * name the tools take — so `orders` and the table it lives in are one.\n */\nfunction useCollectionCheck(): (name: string | undefined) => void {\n const allowed = useContext(AppCollectionsContext);\n const registry = useCollectionRegistryController();\n return useCallback((name: string | undefined) => {\n if (allowed === undefined || name === undefined || allowed.includes(name)) return;\n const collection = registry.getCollection(name);\n if (collection && (allowed.includes(collection.slug)\n || allowed.includes(getCollectionDataPath(collection)))) return;\n throw new Error(`\"${name}\" is not one of this app's collections (${allowed.join(\", \")}). `\n + \"List it in show_app's `collections`.\");\n }, [allowed, registry]);\n}\n\nfunction AppCollectionPanel(props: CollectionPanelProps) {\n useCollectionCheck()(collectionPropOf(props.collection, props.path).path);\n return <CollectionPanel {...props}/>;\n}\n\nfunction AppRecordForm({ collectionOverrides, ...props }: RecordFormProps) {\n useCollectionCheck()(collectionPropOf(props.collection, props.path).path);\n // A form that saves itself writes the values it was seeded with on mount,\n // with nobody's click: off, whether the override or the collection asked\n // for it. The overrides merge over the collection the form opens.\n return <RecordForm {...props} collectionOverrides={{ ...collectionOverrides, formAutoSave: false }}/>;\n}\n\nfunction AppRecordDetail(props: RecordDetailProps) {\n useCollectionCheck()(collectionPropOf(props.collection, props.path).path);\n return <RecordDetail {...props}/>;\n}\n\nfunction AppFieldValue(props: FieldValueProps) {\n useCollectionCheck()(props.collection);\n return <FieldValue {...props}/>;\n}\n\nfunction useAppSidePanel(): SidePanelController {\n const check = useCollectionCheck();\n const panel = useSidePanel();\n return useMemo(() => {\n const checked = <M extends Record<string, unknown>>(props: SidePanelBindingProps<M>) => {\n check(props.path);\n return props;\n };\n return {\n close: () => panel.close(),\n open: props => panel.open(checked(props)),\n replace: props => panel.replace(checked(props))\n };\n }, [panel, check]);\n}\n\n/** The row hooks, each held to the app's collections. */\nconst useAppRows: typeof useRows = (collection, options) => {\n useCollectionCheck()(collection);\n return useRows(collection, options);\n};\n\nconst useAppRow: typeof useRow = (collection, id) => {\n useCollectionCheck()(collection);\n return useRow(collection, id);\n};\n\nconst useAppRowCount: typeof useRowCount = (collection, where) => {\n useCollectionCheck()(collection);\n return useRowCount(collection, where);\n};\n\nconst useAppAggregate: typeof useAggregate = (collection, params) => {\n useCollectionCheck()(collection);\n return useAggregate(collection, params);\n};\n\n/** Writes are checked when they are made: a refused one rejects, as a failed write does. */\nfunction useAppRowWrites(): UseRowWritesResult {\n const check = useCollectionCheck();\n const writes = useRowWrites();\n return useMemo(() => {\n const checked = <T, >(collection: string, write: () => Promise<T>): Promise<T> => {\n try {\n check(collection);\n } catch (error) {\n return Promise.reject(error);\n }\n return write();\n };\n return {\n ...writes,\n create: (collection, values, id) => checked(collection, () => writes.create(collection, values, id)),\n update: (collection, id, values) => checked(collection, () => writes.update(collection, id, values)),\n remove: (collection, id) => checked(collection, () => writes.remove(collection, id))\n };\n }, [writes, check]);\n}\n\n/** A module's served exports: exactly its names in `MCP_APP_MODULES`, no more, no fewer. */\ntype Served<M extends McpAppModule> = Record<McpAppModuleExport<M>, unknown>;\n\nconst APP_MODULE: Served<\"@rebasepro/app\"> = {\n useRows: useAppRows,\n useRow: useAppRow,\n useRowCount: useAppRowCount,\n useAggregate: useAppAggregate,\n useRowWrites: useAppRowWrites\n};\n\nconst CMS_MODULE: Served<\"@rebasepro/cms\"> = {\n CollectionPanel: AppCollectionPanel,\n CollectionToolbar,\n CollectionSearchBar,\n CollectionFiltersButton,\n CollectionViewModeToggle,\n CollectionAddButton,\n RecordForm: AppRecordForm,\n RecordDetail: AppRecordDetail,\n FormField,\n FieldValue: AppFieldValue,\n useSidePanel: useAppSidePanel\n};\n\n/** Every module an app may import, by name. */\nexport const APP_MODULE_EXPORTS: Record<McpAppModule, object> = {\n \"react\": React,\n \"react/jsx-runtime\": jsxRuntime,\n \"@rebasepro/ui\": UI,\n \"@rebasepro/app\": APP_MODULE,\n \"@rebasepro/cms\": CMS_MODULE\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAM,wBAAwB,cAA6C,KAAA,CAAS;;AAGpF,SAAgB,eAAe,EAAE,OAAO,YAAqE;CACzG,OAAO,oBAAC,sBAAsB,UAAvB;EAAgC,OAAO;EAAQ;CAAyC,CAAA;AACnG;;;;;;AAOA,SAAS,qBAAyD;CAC9D,MAAM,UAAU,WAAW,qBAAqB;CAChD,MAAM,WAAW,gCAAgC;CACjD,OAAO,aAAa,SAA6B;EAC7C,IAAI,YAAY,KAAA,KAAa,SAAS,KAAA,KAAa,QAAQ,SAAS,IAAI,GAAG;EAC3E,MAAM,aAAa,SAAS,cAAc,IAAI;EAC9C,IAAI,eAAe,QAAQ,SAAS,WAAW,IAAI,KAC5C,QAAQ,S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PS_PROTOCOL_VERSION, McpAppBridge, isRecord } from "./bridge.js";
5
5
  export type { HostContext, ToolResult, DisplayMode } from "./bridge.js";
6
- export { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite } from "./tool_driver.js";
6
+ export { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite, describeRefusal } from "./tool_driver.js";
7
7
  export type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from "./tool_driver.js";
8
8
  export { parseResult, actionsOf, filterOf } from "./payload.js";
9
9
  export type { Screen, Block } from "./payload.js";
@@ -1,5 +1,5 @@
1
1
  import { McpAppBridge, isRecord } from "./bridge.js";
2
- import { createToolDriver, describeChanges, describeFailedWrite } from "./tool_driver.js";
2
+ import { createToolDriver, describeChanges, describeRefusal } from "./tool_driver.js";
3
3
  import { findCollection, parseResult } from "./payload.js";
4
4
  import { describeAppError } from "./code_app.js";
5
5
  import { createViewStore } from "./store.js";
@@ -204,7 +204,7 @@ function modelContext(bridge) {
204
204
  send();
205
205
  },
206
206
  writeFailed: (failure) => {
207
- state.refused = `The app tried to ${describeFailedWrite(failure)}, and the server refused: ${failure.message}`;
207
+ state.refused = describeRefusal(failure);
208
208
  send();
209
209
  },
210
210
  appError: (error) => {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/mcp_view/index.tsx"],"sourcesContent":["/**\n * `@rebasepro/cms/mcp-view`: a project's admin app, inside an MCP App view.\n *\n * A client like Claude shows what the show_* tools open (a collection, a\n * record, an app the model wrote) in a sandboxed frame next to the\n * conversation. This is what runs in that frame: it speaks the host's\n * protocol, reads and writes through the server's tools as the person, and\n * draws with the admin panel's own components — inside the project's own\n * admin app, so its custom views, entity views, fields, previews, actions,\n * plugins and slots are the ones drawn.\n *\n * ```ts\n * // the project's view entry (the Vite plugin generates it)\n * import { startMcpView } from \"@rebasepro/cms/mcp-view\";\n * startMcpView({ mountApp: () => import(\"./main\") });\n * ```\n *\n * The app mounts as it does on its own page; `<Rebase>`, `<RebaseCMS>`,\n * `<RebaseStudio>` and `<RebaseShell>` find the embed host this sets\n * (`setRebaseEmbedHost` in `@rebasepro/app`) and stand in what the frame\n * cannot give them: data through the tools, the person already signed in,\n * no routes, no network.\n *\n * @module\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { getTitlePropertyKeyForValues, looksLikeIdentifierValue, setRebaseEmbedHost, type RebaseEmbedHost } from \"@rebasepro/app\";\nimport type { AdminCollection, AuthController } from \"@rebasepro/cms-types\";\nimport type { SecurityRule, User } from \"@rebasepro/types\";\nimport { Alert } from \"@rebasepro/ui\";\nimport { McpAppBridge, type HostContext, type ToolResult } from \"./bridge\";\nimport { createToolDriver, describeChanges, describeFailedWrite, type ToolDriver, type ViewChange, type WriteFailure } from \"./tool_driver\";\nimport { findCollection, parseResult, type Screen } from \"./payload\";\nimport { describeAppError, type AppError } from \"./code_app\";\nimport { McpScreen, type PendingPlan } from \"./screen\";\nimport { VIEW_STORAGE_SOURCE } from \"./storage_source\";\nimport { createViewStore } from \"./store\";\n\nexport { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from \"./bridge\";\nimport { isRecord } from \"./bridge\";\nexport type { HostContext, ToolResult, DisplayMode } from \"./bridge\";\nexport { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite } from \"./tool_driver\";\nexport type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from \"./tool_driver\";\nexport { parseResult, actionsOf, filterOf } from \"./payload\";\nexport type { Screen, Block } from \"./payload\";\n\nexport interface McpViewOptions {\n /**\n * Mount the app, once the host is set: import the project's entry (which\n * renders its app as it would on its page), or render a default one into\n * `#root`. Given the screen the tool opened, for an app with no\n * collections of its own.\n */\n mountApp: (screen: Screen) => void | Promise<unknown>;\n /**\n * Draw a result from a server that predates the admin panel's views\n * (show_collection's columns only): the old table, where the view has it.\n */\n mountTable?: (bridge: McpAppBridge, container: HTMLElement) => void;\n /** Name and version the view gives the host. */\n appInfo?: { name: string; version: string };\n /** The channel to the host; a new one on this window's parent by default. */\n bridge?: McpAppBridge;\n}\n\n/**\n * Connect to the host, wait for the tool's result, set the embed host from\n * it, and mount the app.\n */\nexport function startMcpView(options: McpViewOptions): McpAppBridge {\n installSubmitFix();\n const bridge = options.bridge ?? new McpAppBridge();\n let started = false;\n\n bridge.ontoolresult = (result: ToolResult) => {\n if (started) return;\n started = true;\n const parsed = parseResult(result);\n if (parsed.kind === \"table\") {\n const container = document.getElementById(\"root\");\n if (container && options.mountTable) options.mountTable(bridge, container);\n else showError(\"This view cannot draw this result.\");\n return;\n }\n if (parsed.kind === \"error\") {\n showError(parsed.message);\n return;\n }\n setRebaseEmbedHost(embedHost(bridge, parsed.screen));\n Promise.resolve(options.mountApp(parsed.screen))\n .catch(error => showError(`The view could not start: ${error instanceof Error ? error.message : String(error)}`));\n };\n\n // The host's light or dark, on the class the UI kit's `dark:` variant reads.\n bridge.watchHostContext(context => {\n if (context.theme) document.documentElement.classList.toggle(\"dark\", context.theme === \"dark\");\n });\n\n void bridge.connect(options.appInfo ?? { name: \"rebase\", version: \"0.3.0\" });\n return bridge;\n}\n\n/** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */\nfunction embedHost(bridge: McpAppBridge, screen: Screen): RebaseEmbedHost {\n const pending = createViewStore<PendingPlan | undefined>(undefined);\n const refused = createViewStore<WriteFailure | undefined>(undefined);\n const context = createViewStore<HostContext>(bridge.hostContext);\n bridge.watchHostContext(next => context.set(next));\n\n const told = modelContext(bridge);\n const tools: ToolDriver = createToolDriver({\n callTool: (name, args) => bridge.callTool(name, args),\n actions: screen.actions,\n ...(screen.firstPage && { seed: screen.firstPage }),\n ...(screen.seeds && { seeds: screen.seeds }),\n // A collection by whichever name it was read or written under: its\n // data path (the tools' name, the model's) or its slug (the admin's).\n collection: name => findCollection(screen.collections, name),\n confirm: plan => new Promise<boolean>(resolve => pending.set({\n plan,\n answer: confirmed => {\n pending.set(undefined);\n resolve(confirmed);\n }\n })),\n onChange: told.changes,\n rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),\n onWriteFailed: failure => {\n refused.set(failure);\n told.writeFailed(failure);\n }\n });\n\n const host: RebaseEmbedHost = {\n dataDriver: tools.driver,\n // Code can write without a click, so the row hooks ask the person\n // before each write; a save made with the admin's own controls goes\n // as on any screen. A courtesy, not the boundary: every call is the\n // server's tool as the person, under their RLS and granted scopes.\n rowHooksDriver: tools.confirmingDriver,\n authController: viewerAuth(screen.viewer),\n storageSource: VIEW_STORAGE_SOURCE,\n mode: bridge.hostContext.theme === \"dark\" ? \"dark\" : \"light\",\n narrowCollections: collections => narrowCollections(collections, screen.collections),\n renderCms: () => (\n <McpScreen\n bridge={bridge}\n screen={screen}\n hostContext={context}\n pendingPlan={pending}\n writeFailure={refused}\n onAppError={told.appError}\n />\n )\n };\n // The theme follows the host's.\n bridge.watchHostContext(next => {\n const mode = next.theme === \"dark\" ? \"dark\" : \"light\";\n if (mode !== host.mode) {\n host.mode = mode;\n setRebaseEmbedHost({ ...host });\n }\n });\n return host;\n}\n\n/**\n * The app's collections as this person may see them here: the project's own\n * configs — with their components — narrowed as the server narrowed the ones\n * it sent (`McpViewPayload` in the server's `mcp/mcp-view.ts`). A field the\n * server left out is left out; one it made read-only is read-only; its\n * security rules (the project's, and the one closing what the connection was\n * not granted) are the ones checked. A collection the server sent nothing\n * for is shown with every change closed: this screen did not ask for it.\n *\n * Where the app has no collections of its own (the view without a project),\n * the server's configs are the collections.\n */\nexport function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[] {\n if (own.length === 0) return [...sent];\n const bySlug = new Map(sent.map(collection => [collection.slug, collection]));\n return own.map((collection): AdminCollection => {\n const narrowed = bySlug.get(collection.slug);\n if (!narrowed) {\n return { ...collection, securityRules: [...(collection.securityRules ?? []), CLOSED] };\n }\n const copy = { ...collection };\n return Object.assign(copy, {\n properties: narrowProperties(collection.properties, narrowed.properties),\n securityRules: narrowed.securityRules ?? collection.securityRules\n });\n });\n}\n\n/** The fields the server sent, with its read-only marks; the project's own config for each. */\nfunction narrowProperties<P extends Record<string, unknown>>(own: P, sent: Record<string, unknown>): P {\n const narrowed = { ...own };\n for (const key of Object.keys(narrowed)) {\n const sentProperty = sent[key];\n if (!sentProperty) {\n delete narrowed[key];\n continue;\n }\n const property = narrowed[key];\n if (isRecord(sentProperty) && isRecord(sentProperty.admin) && sentProperty.admin.readOnly === true && isRecord(property)) {\n Object.assign(narrowed, { [key]: { ...property, admin: { ...(isRecord(property.admin) ? property.admin : {}), readOnly: true } } });\n }\n }\n return narrowed;\n}\n\n/** A restrictive rule no account passes, closing every change. */\nconst CLOSED: SecurityRule = {\n name: \"mcp_view_not_opened\",\n mode: \"restrictive\",\n operations: [\"insert\", \"update\", \"delete\"],\n roles: [\"__mcp_view_not_opened__\"]\n};\n\n/**\n * The person the server drew the screen for, as the admin panel asks about\n * them: the security rules it evaluates before offering an action read\n * `uid` and `roles`. Signing out means nothing here — the host holds the\n * connection.\n */\nfunction viewerAuth(viewer: Screen[\"viewer\"]): AuthController {\n const user: User = {\n uid: viewer.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"mcp\",\n isAnonymous: false,\n roles: viewer.roles\n };\n return {\n user,\n initialLoading: false,\n authLoading: false,\n loginSkipped: true,\n storageEnabled: false,\n signOut: async () => undefined,\n getAuthToken: async () => \"\",\n extra: undefined,\n setExtra: () => undefined\n };\n}\n\n/**\n * What the model is told, sent with the person's next message: the changes\n * they made here, and an app's failure. Each update replaces the last, so\n * both go every time.\n */\nfunction modelContext(bridge: McpAppBridge) {\n const state: { changes?: string; refused?: string; error?: string } = {};\n const send = () => {\n const text = [state.changes, state.refused, state.error].filter(Boolean).join(\"\\n\");\n if (text) void bridge.updateModelContext(text).catch(() => undefined);\n };\n return {\n changes: (changes: readonly ViewChange[]) => {\n state.changes = describeChanges(changes);\n send();\n },\n writeFailed: (failure: WriteFailure) => {\n state.refused = `The app tried to ${describeFailedWrite(failure)}, and the server refused: ${failure.message}`;\n send();\n },\n appError: (error: AppError) => {\n state.error = describeAppError(error);\n send();\n }\n };\n}\n\n/**\n * A row's title, as the admin names the record: the collection's title\n * property where the row carries a readable value for it. Nothing where it\n * does not — an opaque id says no more than the caller's fallback.\n */\nexport function rowTitle(collection: AdminCollection | undefined, id: string, row: Record<string, unknown> | undefined): string | undefined {\n if (!collection || !row) return undefined;\n const key = getTitlePropertyKeyForValues(collection, row, id);\n const value = key ? row[key] : undefined;\n if (typeof value === \"number\") return String(value);\n return typeof value === \"string\" && value.trim() !== \"\" && !looksLikeIdentifierValue(value) ? value : undefined;\n}\n\n/** An error where the app would be, before it could start. */\nfunction showError(message: string): void {\n const container = document.getElementById(\"root\") ?? document.body.appendChild(document.createElement(\"div\"));\n createRoot(container).render(<div className=\"p-4\"><Alert color=\"error\" size=\"small\">{message}</Alert></div>);\n}\n\n/**\n * A host may sandbox the view without `allow-forms`, and then a form's submit\n * button submits nothing: the browser drops the submission before the form's\n * `submit` event — the admin panel's record form saves on that event. The\n * click still happens, so it is turned into the event itself, after the click\n * has finished (a button's own handler may say which save it was).\n */\nfunction installSubmitFix(): void {\n document.addEventListener(\"click\", (event) => {\n const button = event.target instanceof Element ? event.target.closest(\"button[type=submit]\") : null;\n if (!(button instanceof HTMLButtonElement) || !button.form || button.disabled) return;\n event.preventDefault();\n const form = button.form;\n setTimeout(() => form.dispatchEvent(new SubmitEvent(\"submit\", { bubbles: true, cancelable: true, submitter: button })));\n }, true);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAsEA,SAAgB,aAAa,SAAuC;CAChE,iBAAiB;CACjB,MAAM,SAAS,QAAQ,UAAU,IAAI,aAAa;CAClD,IAAI,UAAU;CAEd,OAAO,gBAAgB,WAAuB;EAC1C,IAAI,SAAS;EACb,UAAU;EACV,MAAM,SAAS,YAAY,MAAM;EACjC,IAAI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pC,MAAM,UAAU,oBAAoB,oBAAoB,OAAO,EAAE,4BAA4B,QAAQ;GACrG,KAAK;EACT;EACA,WAAW,UAAoB;GAC3B,MAAM,QAAQ,iBAAiB,KAAK;GACpC,KAAK;EACT;CACJ;AACJ;;;;;;AAOA,SAAgB,SAAS,YAAyC,IAAY,KAA8D;CACxI,IAAI,CAAC,cAAc,CAAC,KAAK,OAAO,KAAA;CAChC,MAAM,MAAM,6BAA6B,YAAY,KAAK,EAAE;CAC5D,MAAM,QAAQ,MAAM,IAAI,OAAO,KAAA;CAC/B,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,MAAM,MAAM,CAAC,yBAAyB,KAAK,IAAI,QAAQ,KAAA;AAC1G;;AAGA,SAAS,UAAU,SAAuB;CAEtC,WADkB,SAAS,eAAe,MAAM,KAAK,SAAS,KAAK,YAAY,SAAS,cAAc,KAAK,CAAC,CACxF,CAAC,CAAC,OAAO,oBAAC,OAAD;EAAK,WAAU;YAAM,oBAAC,OAAD;GAAO,OAAM;GAAQ,MAAK;aAAS;EAAe,CAAA;CAAM,CAAA,CAAC;AAC/G;;;;;;;;AASA,SAAS,mBAAyB;CAC9B,SAAS,iBAAiB,UAAU,UAAU;EAC1C,MAAM,SAAS,MAAM,kBAAkB,UAAU,MAAM,OAAO,QAAQ,qBAAqB,IAAI;EAC/F,IAAI,EAAE,kBAAkB,sBAAsB,CAAC,OAAO,QAAQ,OAAO,UAAU;EAC/E,MAAM,eAAe;EACrB,MAAM,OAAO,OAAO;EACpB,iBAAiB,KAAK,cAAc,IAAI,YAAY,UAAU;GAAE,SAAS;GAAM,YAAY;GAAM,WAAW;EAAO,CAAC,CAAC,CAAC;CAC1H,GAAG,IAAI;AACX"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/mcp_view/index.tsx"],"sourcesContent":["/**\n * `@rebasepro/cms/mcp-view`: a project's admin app, inside an MCP App view.\n *\n * A client like Claude shows what the show_* tools open (a collection, a\n * record, an app the model wrote) in a sandboxed frame next to the\n * conversation. This is what runs in that frame: it speaks the host's\n * protocol, reads and writes through the server's tools as the person, and\n * draws with the admin panel's own components — inside the project's own\n * admin app, so its custom views, entity views, fields, previews, actions,\n * plugins and slots are the ones drawn.\n *\n * ```ts\n * // the project's view entry (the Vite plugin generates it)\n * import { startMcpView } from \"@rebasepro/cms/mcp-view\";\n * startMcpView({ mountApp: () => import(\"./main\") });\n * ```\n *\n * The app mounts as it does on its own page; `<Rebase>`, `<RebaseCMS>`,\n * `<RebaseStudio>` and `<RebaseShell>` find the embed host this sets\n * (`setRebaseEmbedHost` in `@rebasepro/app`) and stand in what the frame\n * cannot give them: data through the tools, the person already signed in,\n * no routes, no network.\n *\n * @module\n */\nimport React from \"react\";\nimport { createRoot } from \"react-dom/client\";\nimport { getTitlePropertyKeyForValues, looksLikeIdentifierValue, setRebaseEmbedHost, type RebaseEmbedHost } from \"@rebasepro/app\";\nimport type { AdminCollection, AuthController } from \"@rebasepro/cms-types\";\nimport type { SecurityRule, User } from \"@rebasepro/types\";\nimport { Alert } from \"@rebasepro/ui\";\nimport { McpAppBridge, type HostContext, type ToolResult } from \"./bridge\";\nimport { createToolDriver, describeChanges, describeRefusal, type ToolDriver, type ViewChange, type WriteFailure } from \"./tool_driver\";\nimport { findCollection, parseResult, type Screen } from \"./payload\";\nimport { describeAppError, type AppError } from \"./code_app\";\nimport { McpScreen, type PendingPlan } from \"./screen\";\nimport { VIEW_STORAGE_SOURCE } from \"./storage_source\";\nimport { createViewStore } from \"./store\";\n\nexport { APPS_PROTOCOL_VERSION, McpAppBridge, isRecord } from \"./bridge\";\nimport { isRecord } from \"./bridge\";\nexport type { HostContext, ToolResult, DisplayMode } from \"./bridge\";\nexport { createToolDriver, DEFAULT_ACTIONS, SaveCancelledError, describeChanges, describeFailedWrite, describeRefusal } from \"./tool_driver\";\nexport type { CallTool, SeedPage, ToolDriver, ViewActions, WritePlan, ViewChange, WriteFailure } from \"./tool_driver\";\nexport { parseResult, actionsOf, filterOf } from \"./payload\";\nexport type { Screen, Block } from \"./payload\";\n\nexport interface McpViewOptions {\n /**\n * Mount the app, once the host is set: import the project's entry (which\n * renders its app as it would on its page), or render a default one into\n * `#root`. Given the screen the tool opened, for an app with no\n * collections of its own.\n */\n mountApp: (screen: Screen) => void | Promise<unknown>;\n /**\n * Draw a result from a server that predates the admin panel's views\n * (show_collection's columns only): the old table, where the view has it.\n */\n mountTable?: (bridge: McpAppBridge, container: HTMLElement) => void;\n /** Name and version the view gives the host. */\n appInfo?: { name: string; version: string };\n /** The channel to the host; a new one on this window's parent by default. */\n bridge?: McpAppBridge;\n}\n\n/**\n * Connect to the host, wait for the tool's result, set the embed host from\n * it, and mount the app.\n */\nexport function startMcpView(options: McpViewOptions): McpAppBridge {\n installSubmitFix();\n const bridge = options.bridge ?? new McpAppBridge();\n let started = false;\n\n bridge.ontoolresult = (result: ToolResult) => {\n if (started) return;\n started = true;\n const parsed = parseResult(result);\n if (parsed.kind === \"table\") {\n const container = document.getElementById(\"root\");\n if (container && options.mountTable) options.mountTable(bridge, container);\n else showError(\"This view cannot draw this result.\");\n return;\n }\n if (parsed.kind === \"error\") {\n showError(parsed.message);\n return;\n }\n setRebaseEmbedHost(embedHost(bridge, parsed.screen));\n Promise.resolve(options.mountApp(parsed.screen))\n .catch(error => showError(`The view could not start: ${error instanceof Error ? error.message : String(error)}`));\n };\n\n // The host's light or dark, on the class the UI kit's `dark:` variant reads.\n bridge.watchHostContext(context => {\n if (context.theme) document.documentElement.classList.toggle(\"dark\", context.theme === \"dark\");\n });\n\n void bridge.connect(options.appInfo ?? { name: \"rebase\", version: \"0.3.0\" });\n return bridge;\n}\n\n/** What the app runs on, here: the tools, the person, the frame's storage and theme, and the screen to draw. */\nfunction embedHost(bridge: McpAppBridge, screen: Screen): RebaseEmbedHost {\n const pending = createViewStore<PendingPlan | undefined>(undefined);\n const refused = createViewStore<WriteFailure | undefined>(undefined);\n const context = createViewStore<HostContext>(bridge.hostContext);\n bridge.watchHostContext(next => context.set(next));\n\n const told = modelContext(bridge);\n const tools: ToolDriver = createToolDriver({\n callTool: (name, args) => bridge.callTool(name, args),\n actions: screen.actions,\n ...(screen.firstPage && { seed: screen.firstPage }),\n ...(screen.seeds && { seeds: screen.seeds }),\n // A collection by whichever name it was read or written under: its\n // data path (the tools' name, the model's) or its slug (the admin's).\n collection: name => findCollection(screen.collections, name),\n confirm: plan => new Promise<boolean>(resolve => pending.set({\n plan,\n answer: confirmed => {\n pending.set(undefined);\n resolve(confirmed);\n }\n })),\n onChange: told.changes,\n rowLabel: (name, id, row) => rowTitle(findCollection(screen.collections, name), id, row),\n onWriteFailed: failure => {\n refused.set(failure);\n told.writeFailed(failure);\n }\n });\n\n const host: RebaseEmbedHost = {\n dataDriver: tools.driver,\n // Code can write without a click, so the row hooks ask the person\n // before each write; a save made with the admin's own controls goes\n // as on any screen. A courtesy, not the boundary: every call is the\n // server's tool as the person, under their RLS and granted scopes.\n rowHooksDriver: tools.confirmingDriver,\n authController: viewerAuth(screen.viewer),\n storageSource: VIEW_STORAGE_SOURCE,\n mode: bridge.hostContext.theme === \"dark\" ? \"dark\" : \"light\",\n narrowCollections: collections => narrowCollections(collections, screen.collections),\n renderCms: () => (\n <McpScreen\n bridge={bridge}\n screen={screen}\n hostContext={context}\n pendingPlan={pending}\n writeFailure={refused}\n onAppError={told.appError}\n />\n )\n };\n // The theme follows the host's.\n bridge.watchHostContext(next => {\n const mode = next.theme === \"dark\" ? \"dark\" : \"light\";\n if (mode !== host.mode) {\n host.mode = mode;\n setRebaseEmbedHost({ ...host });\n }\n });\n return host;\n}\n\n/**\n * The app's collections as this person may see them here: the project's own\n * configs — with their components — narrowed as the server narrowed the ones\n * it sent (`McpViewPayload` in the server's `mcp/mcp-view.ts`). A field the\n * server left out is left out; one it made read-only is read-only; its\n * security rules (the project's, and the one closing what the connection was\n * not granted) are the ones checked. A collection the server sent nothing\n * for is shown with every change closed: this screen did not ask for it.\n *\n * Where the app has no collections of its own (the view without a project),\n * the server's configs are the collections.\n */\nexport function narrowCollections(own: AdminCollection[], sent: readonly AdminCollection[]): AdminCollection[] {\n if (own.length === 0) return [...sent];\n const bySlug = new Map(sent.map(collection => [collection.slug, collection]));\n return own.map((collection): AdminCollection => {\n const narrowed = bySlug.get(collection.slug);\n if (!narrowed) {\n return { ...collection, securityRules: [...(collection.securityRules ?? []), CLOSED] };\n }\n const copy = { ...collection };\n return Object.assign(copy, {\n properties: narrowProperties(collection.properties, narrowed.properties),\n securityRules: narrowed.securityRules ?? collection.securityRules\n });\n });\n}\n\n/** The fields the server sent, with its read-only marks; the project's own config for each. */\nfunction narrowProperties<P extends Record<string, unknown>>(own: P, sent: Record<string, unknown>): P {\n const narrowed = { ...own };\n for (const key of Object.keys(narrowed)) {\n const sentProperty = sent[key];\n if (!sentProperty) {\n delete narrowed[key];\n continue;\n }\n const property = narrowed[key];\n if (isRecord(sentProperty) && isRecord(sentProperty.admin) && sentProperty.admin.readOnly === true && isRecord(property)) {\n Object.assign(narrowed, { [key]: { ...property, admin: { ...(isRecord(property.admin) ? property.admin : {}), readOnly: true } } });\n }\n }\n return narrowed;\n}\n\n/** A restrictive rule no account passes, closing every change. */\nconst CLOSED: SecurityRule = {\n name: \"mcp_view_not_opened\",\n mode: \"restrictive\",\n operations: [\"insert\", \"update\", \"delete\"],\n roles: [\"__mcp_view_not_opened__\"]\n};\n\n/**\n * The person the server drew the screen for, as the admin panel asks about\n * them: the security rules it evaluates before offering an action read\n * `uid` and `roles`. Signing out means nothing here — the host holds the\n * connection.\n */\nfunction viewerAuth(viewer: Screen[\"viewer\"]): AuthController {\n const user: User = {\n uid: viewer.uid,\n displayName: null,\n email: null,\n photoURL: null,\n providerId: \"mcp\",\n isAnonymous: false,\n roles: viewer.roles\n };\n return {\n user,\n initialLoading: false,\n authLoading: false,\n loginSkipped: true,\n storageEnabled: false,\n signOut: async () => undefined,\n getAuthToken: async () => \"\",\n extra: undefined,\n setExtra: () => undefined\n };\n}\n\n/**\n * What the model is told, sent with the person's next message: the changes\n * they made here, and an app's failure. Each update replaces the last, so\n * both go every time.\n */\nfunction modelContext(bridge: McpAppBridge) {\n const state: { changes?: string; refused?: string; error?: string } = {};\n const send = () => {\n const text = [state.changes, state.refused, state.error].filter(Boolean).join(\"\\n\");\n if (text) void bridge.updateModelContext(text).catch(() => undefined);\n };\n return {\n changes: (changes: readonly ViewChange[]) => {\n state.changes = describeChanges(changes);\n send();\n },\n writeFailed: (failure: WriteFailure) => {\n state.refused = describeRefusal(failure);\n send();\n },\n appError: (error: AppError) => {\n state.error = describeAppError(error);\n send();\n }\n };\n}\n\n/**\n * A row's title, as the admin names the record: the collection's title\n * property where the row carries a readable value for it. Nothing where it\n * does not — an opaque id says no more than the caller's fallback.\n */\nexport function rowTitle(collection: AdminCollection | undefined, id: string, row: Record<string, unknown> | undefined): string | undefined {\n if (!collection || !row) return undefined;\n const key = getTitlePropertyKeyForValues(collection, row, id);\n const value = key ? row[key] : undefined;\n if (typeof value === \"number\") return String(value);\n return typeof value === \"string\" && value.trim() !== \"\" && !looksLikeIdentifierValue(value) ? value : undefined;\n}\n\n/** An error where the app would be, before it could start. */\nfunction showError(message: string): void {\n const container = document.getElementById(\"root\") ?? document.body.appendChild(document.createElement(\"div\"));\n createRoot(container).render(<div className=\"p-4\"><Alert color=\"error\" size=\"small\">{message}</Alert></div>);\n}\n\n/**\n * A host may sandbox the view without `allow-forms`, and then a form's submit\n * button submits nothing: the browser drops the submission before the form's\n * `submit` event — the admin panel's record form saves on that event. The\n * click still happens, so it is turned into the event itself, after the click\n * has finished (a button's own handler may say which save it was).\n */\nfunction installSubmitFix(): void {\n document.addEventListener(\"click\", (event) => {\n const button = event.target instanceof Element ? event.target.closest(\"button[type=submit]\") : null;\n if (!(button instanceof HTMLButtonElement) || !button.form || button.disabled) return;\n event.preventDefault();\n const form = button.form;\n setTimeout(() => form.dispatchEvent(new SubmitEvent(\"submit\", { bubbles: true,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AAc,IAAI,YAAY,UAAU;GAAE,SAAS;GAAM,YAAY;GAAM,WAAW;EAAO,CAAC,CAAC,CAAC;CAC1H,GAAG,IAAI;AACX"}
@@ -36,8 +36,13 @@ function parseResult(result) {
36
36
  message: "The screen has no blocks."
37
37
  };
38
38
  const viewer = isRecord(view.viewer) ? view.viewer : {};
39
+ const readAt = typeof view.readAt === "number" && Number.isFinite(view.readAt) ? view.readAt : void 0;
40
+ const stamped = (page) => readAt === void 0 ? page : {
41
+ ...page,
42
+ readAt
43
+ };
39
44
  const firstPage = firstPageOf(blocks[0], content);
40
- const seeds = Array.isArray(view.seeds) ? view.seeds.flatMap(seedOf) : [];
45
+ const seeds = Array.isArray(view.seeds) ? view.seeds.flatMap(seedOf).map(stamped) : [];
41
46
  return {
42
47
  kind: "screen",
43
48
  screen: {
@@ -49,7 +54,7 @@ function parseResult(result) {
49
54
  roles: Array.isArray(viewer.roles) ? viewer.roles.filter((role) => typeof role === "string") : []
50
55
  },
51
56
  actions: actionsOf(content.actions),
52
- ...firstPage && { firstPage },
57
+ ...firstPage && { firstPage: stamped(firstPage) },
53
58
  ...seeds.length > 0 && { seeds }
54
59
  }
55
60
  };