@rebasepro/cms 0.29.1 → 0.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) 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/fields/TableStorageUpload.js +1 -1
  6. package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js.map +1 -1
  7. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
  8. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
  9. package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
  10. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +39 -14
  11. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
  12. package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +11 -0
  13. package/dist/components/CollectionViewBinding/CollectionViewContent.js +19 -2
  14. package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
  15. package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -1
  16. package/dist/components/CollectionViewBinding/EntityCardBinding.js +1 -1
  17. package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
  18. package/dist/components/CollectionViewBinding/SlotValue.js.map +1 -1
  19. package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +19 -1
  20. package/dist/components/CollectionViewBinding/usePreviewSlots.js +18 -7
  21. package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
  22. package/dist/components/EntityPreviewBinding.d.ts +20 -0
  23. package/dist/components/EntityPreviewBinding.js +121 -18
  24. package/dist/components/EntityPreviewBinding.js.map +1 -1
  25. package/dist/components/HomePage/ContentHomePage.js +2 -3
  26. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  27. package/dist/components/RecordForm.d.ts +25 -4
  28. package/dist/components/RecordForm.js +21 -3
  29. package/dist/components/RecordForm.js.map +1 -1
  30. package/dist/components/RelationSelector.js.map +1 -1
  31. package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +13 -1
  32. package/dist/components/SelectableTable/filters/FilterFieldBinding.js +19 -3
  33. package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
  34. package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
  35. package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
  36. package/dist/components/history/EntityHistoryEntry.js.map +1 -1
  37. package/dist/data_import/utils/save_entities.d.ts +10 -2
  38. package/dist/data_import/utils/save_entities.js.map +1 -1
  39. package/dist/editor/markdown.d.ts +10 -0
  40. package/dist/editor/markdown.js.map +1 -1
  41. package/dist/form/PropertyFieldBinding.js +4 -2
  42. package/dist/form/PropertyFieldBinding.js.map +1 -1
  43. package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
  44. package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
  45. package/dist/hooks/useBuildSidePanel.d.ts +10 -0
  46. package/dist/hooks/useBuildSidePanel.js +43 -4
  47. package/dist/hooks/useBuildSidePanel.js.map +1 -1
  48. package/dist/hooks/useResolvedNavigationFrom.d.ts +14 -2
  49. package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
  50. package/dist/index.d.ts +3 -1
  51. package/dist/index.js +4 -2
  52. package/dist/mcp_view/app_modules.js +4 -2
  53. package/dist/mcp_view/app_modules.js.map +1 -1
  54. package/dist/mcp_view/bridge.d.ts +21 -1
  55. package/dist/mcp_view/bridge.js.map +1 -1
  56. package/dist/mcp_view/index.d.ts +7 -7
  57. package/dist/mcp_view/index.js +7 -2
  58. package/dist/mcp_view/index.js.map +1 -1
  59. package/dist/mcp_view/payload.js +7 -2
  60. package/dist/mcp_view/payload.js.map +1 -1
  61. package/dist/mcp_view/screen.d.ts +6 -4
  62. package/dist/mcp_view/screen.js +15 -43
  63. package/dist/mcp_view/screen.js.map +1 -1
  64. package/dist/mcp_view/tool_driver.d.ts +58 -6
  65. package/dist/mcp_view/tool_driver.js +256 -117
  66. package/dist/mcp_view/tool_driver.js.map +1 -1
  67. package/dist/mcp_view/write_review.d.ts +35 -0
  68. package/dist/mcp_view/write_review.js +144 -0
  69. package/dist/mcp_view/write_review.js.map +1 -0
  70. package/dist/preview/compact_text.d.ts +1 -1
  71. package/dist/preview/compact_text.js.map +1 -1
  72. package/dist/preview/components/RelationPreview.js +7 -2
  73. package/dist/preview/components/RelationPreview.js.map +1 -1
  74. package/dist/saved_apps/SavedAppsView.d.ts +17 -0
  75. package/dist/saved_apps/SavedAppsView.js +167 -0
  76. package/dist/saved_apps/SavedAppsView.js.map +1 -0
  77. package/dist/saved_apps/admin_apps_client.d.ts +24 -0
  78. package/dist/saved_apps/admin_apps_client.js +46 -0
  79. package/dist/saved_apps/admin_apps_client.js.map +1 -0
  80. package/dist/saved_apps/saved_app_frame.d.ts +20 -0
  81. package/dist/saved_apps/saved_app_frame.js +143 -0
  82. package/dist/saved_apps/saved_app_frame.js.map +1 -0
  83. package/dist/selection/resolve_selection.d.ts +10 -2
  84. package/dist/selection/resolve_selection.js.map +1 -1
  85. package/dist/util/property_utils.d.ts +2 -2
  86. package/dist/util/property_utils.js.map +1 -1
  87. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"GeopointFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/GeopointFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { GeopointProperty } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport { IconButton, TextField, Trash2Icon } from \"@rebasepro/ui\";\n\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/** Latitude runs −90…90, longitude −180…180. Anything else is not a place. */\nconst LAT_RANGE: [number, number] = [-90, 90];\nconst LNG_RANGE: [number, number] = [-180, 180];\n\ninterface Coordinates { latitude: number; longitude: number }\n\n/**\n * Read whatever the driver handed us as a pair of coordinates.\n *\n * A geopoint arrives as a `GeoPoint` instance from the client, but as a plain\n * object once it has been through JSON — and PostGIS-backed rows may present it\n * as `{ x, y }`, where `x` is the longitude. Reading only one of those shapes\n * would render an empty field over data that is actually there.\n */\nexport function readCoordinates(value: unknown): Coordinates | null {\n if (!value || typeof value !== \"object\") return null;\n const v = value as Record<string, unknown>;\n\n const lat = typeof v.latitude === \"number\" ? v.latitude : (typeof v.y === \"number\" ? v.y : undefined);\n const lng = typeof v.longitude === \"number\" ? v.longitude : (typeof v.x === \"number\" ? v.x : undefined);\n\n if (typeof lat !== \"number\" || typeof lng !== \"number\") return null;\n return { latitude: lat, longitude: lng };\n}\n\nconst inRange = (n: number, [min, max]: [number, number]) => n >= min && n <= max;\n\n/**\n * Field binding for `type: \"geopoint\"`.\n *\n * The model has defined this type all along and the admin had no way to render\n * it: the widget lookup fell off the end of its chain, logged to the console\n * and returned undefined, so the field simply did not appear on the form. A\n * geopoint column was invisible in the admin panel, and unreachable in the\n * property editor.\n *\n * Two number inputs rather than a map. A map needs a tile provider, which means\n * a network dependency and an API key, and neither belongs in a field binding\n * that has to work offline and in every deployment. Coordinates are typed,\n * pasted and copied far more often than they are dropped on a map.\n *\n * @group Form fields\n */\nexport function GeopointFieldBinding({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n}: FieldProps<GeopointProperty>) {\n\n const coordinates = readCoordinates(value);\n\n // Held as text while editing: a half-typed \"-\" or \"12.\" is not a number\n // yet, and rounding it through `Number` on every keystroke fights the user.\n const [latText, setLatText] = useState(() => coordinates ? String(coordinates.latitude) : \"\");\n const [lngText, setLngText] = useState(() => coordinates ? String(coordinates.longitude) : \"\");\n\n useEffect(() => {\n const next = readCoordinates(value);\n setLatText(next ? String(next.latitude) : \"\");\n setLngText(next ? String(next.longitude) : \"\");\n }, [coordinates?.latitude, coordinates?.longitude]);\n\n const commit = useCallback((rawLat: string, rawLng: string) => {\n // Both empty means \"no location\", which is different from 0,0 — a real\n // point in the Gulf of Guinea, and the classic way a cleared field\n // turns into a wrong one.\n if (rawLat.trim() === \"\" && rawLng.trim() === \"\") {\n setValue(null);\n return;\n }\n // One side filled and the other still empty is a location half typed,\n // not a location. Committing it would send the empty side through\n // `Number(\"\")`, which is 0 and perfectly finite — so typing a latitude\n // and pausing used to write longitude 0 and drop the point in the Gulf\n // of Guinea. Hold until both sides are there; `halfEntered` below says\n // so in the meantime.\n if (rawLat.trim() === \"\" || rawLng.trim() === \"\") return;\n\n const latitude = Number(rawLat);\n const longitude = Number(rawLng);\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return;\n setValue({ latitude, longitude } as never);\n }, [setValue]);\n\n const handleClear = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setLatText(\"\");\n setLngText(\"\");\n setValue(null);\n }, [setValue]);\n\n const latNumber = Number(latText);\n const lngNumber = Number(lngText);\n const latInvalid = latText.trim() !== \"\" && (!Number.isFinite(latNumber) || !inRange(latNumber, LAT_RANGE));\n const lngInvalid = lngText.trim() !== \"\" && (!Number.isFinite(lngNumber) || !inRange(lngNumber, LNG_RANGE));\n\n // One side filled and the other empty is not a point.\n const halfEntered = (latText.trim() === \"\") !== (lngText.trim() === \"\");\n\n const localError = latInvalid\n ? `Latitude must be between ${LAT_RANGE[0]} and ${LAT_RANGE[1]}`\n : lngInvalid\n ? `Longitude must be between ${LNG_RANGE[0]} and ${LNG_RANGE[1]}`\n : halfEntered\n ? \"A location needs both a latitude and a longitude\"\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-2 w-full\">\n {/* Label only, and only when there is one: a row that survives\n `hideLabel` still spends its `mb-1` and the column's `gap-2`, so\n the pair of inputs sat below the control next to them even\n though the two labels were level. */}\n {!hideLabel && <div className=\"flex items-center justify-between mb-1\">\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n />\n </div>}\n\n {/* Clear sits beside the inputs rather than above them, so\n entering a location does not grow the field by a row and\n knock it out of line with its neighbour. */}\n <div className=\"flex gap-4 w-full items-center\">\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Latitude\"\n value={latText}\n autoFocus={autoFocus}\n disabled={disabled}\n error={showError ? Boolean(error) || latInvalid : latInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLatText(e.target.value);\n commit(e.target.value, lngText);\n }}\n placeholder=\"e.g. 41.3874\"\n inputClassName=\"font-mono\"\n />\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Longitude\"\n value={lngText}\n disabled={disabled}\n error={showError ? Boolean(error) || lngInvalid : lngInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLngText(e.target.value);\n commit(latText, e.target.value);\n }}\n placeholder=\"e.g. 2.1686\"\n inputClassName=\"font-mono\"\n />\n {!disabled && (latText || lngText) && (\n <IconButton\n size=\"small\"\n onClick={handleClear}\n className=\"shrink-0 text-text-secondary hover:text-red-500\"\n aria-label=\"Clear location\"\n >\n <Trash2Icon size={14}/>\n </IconButton>\n )}\n </div>\n\n <FieldHelperText\n includeDescription={includeDescription}\n showError={showError || Boolean(localError)}\n error={error || localError}\n disabled={disabled}\n property={property}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;AAUA,IAAM,YAA8B,CAAC,KAAK,EAAE;AAC5C,IAAM,YAA8B,CAAC,MAAM,GAAG;;;;;;;;;AAY9C,SAAgB,gBAAgB,OAAoC;CAChE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,IAAI;CAEV,MAAM,MAAM,OAAO,EAAE,aAAa,WAAW,EAA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AAO,KAAK;MAClC;MACA,aAAY;MACZ,gBAAe;KAClB,CAAA;KACA,CAAC,aAAa,WAAW,YACtB,oBAAC,YAAD;MACI,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAW;gBAEX,oBAAC,YAAD,EAAY,MAAM,GAAI,CAAA;KACd,CAAA;IAEf;;GAEL,oBAAC,iBAAD;IACwB;IACpB,WAAW,aAAa,QAAQ,UAAU;IAC1C,OAAO,SAAS;IACN;IACA;GACb,CAAA;EACA;;AAEb"}
1
+ {"version":3,"file":"GeopointFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/GeopointFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { GeopointProperty } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport { IconButton, TextField, Trash2Icon } from \"@rebasepro/ui\";\n\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/** Latitude runs −90…90, longitude −180…180. Anything else is not a place. */\nconst LAT_RANGE: [number, number] = [-90, 90];\nconst LNG_RANGE: [number, number] = [-180, 180];\n\ninterface Coordinates { latitude: number; longitude: number }\n\n/**\n * Read whatever the driver handed us as a pair of coordinates.\n *\n * A geopoint arrives as a `GeoPoint` instance from the client, but as a plain\n * object once it has been through JSON — and PostGIS-backed rows may present it\n * as `{ x, y }`, where `x` is the longitude. Reading only one of those shapes\n * would render an empty field over data that is actually there.\n */\nexport function readCoordinates(value: unknown): Coordinates | null {\n if (!value || typeof value !== \"object\") return null;\n const v = value as Record<string, unknown>;\n\n const lat = typeof v.latitude === \"number\" ? v.latitude : (typeof v.y === \"number\" ? v.y : undefined);\n const lng = typeof v.longitude === \"number\" ? v.longitude : (typeof v.x === \"number\" ? v.x : undefined);\n\n if (typeof lat !== \"number\" || typeof lng !== \"number\") return null;\n return { latitude: lat, longitude: lng };\n}\n\nconst inRange = (n: number, [min, max]: [number, number]) => n >= min && n <= max;\n\n/**\n * Field binding for `type: \"geopoint\"`.\n *\n * The model has defined this type all along and the admin had no way to render\n * it: the widget lookup fell off the end of its chain, logged to the console\n * and returned undefined, so the field simply did not appear on the form. A\n * geopoint column was invisible in the admin panel, and unreachable in the\n * property editor.\n *\n * Two number inputs rather than a map. A map needs a tile provider, which means\n * a network dependency and an API key, and neither belongs in a field binding\n * that has to work offline and in every deployment. Coordinates are typed,\n * pasted and copied far more often than they are dropped on a map.\n *\n * @group Form fields\n */\nexport function GeopointFieldBinding({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n}: FieldProps<GeopointProperty>) {\n\n const coordinates = readCoordinates(value);\n\n // Held as text while editing: a half-typed \"-\" or \"12.\" is not a number\n // yet, and rounding it through `Number` on every keystroke fights the user.\n const [latText, setLatText] = useState(() => coordinates ? String(coordinates.latitude) : \"\");\n const [lngText, setLngText] = useState(() => coordinates ? String(coordinates.longitude) : \"\");\n\n useEffect(() => {\n const next = readCoordinates(value);\n setLatText(next ? String(next.latitude) : \"\");\n setLngText(next ? String(next.longitude) : \"\");\n }, [coordinates?.latitude, coordinates?.longitude]);\n\n const commit = useCallback((rawLat: string, rawLng: string) => {\n // Both empty means \"no location\", which is different from 0,0 — a real\n // point in the Gulf of Guinea, and the classic way a cleared field\n // turns into a wrong one.\n if (rawLat.trim() === \"\" && rawLng.trim() === \"\") {\n setValue(null);\n return;\n }\n // One side filled and the other still empty is a location half typed,\n // not a location. Committing it would send the empty side through\n // `Number(\"\")`, which is 0 and perfectly finite — so typing a latitude\n // and pausing used to write longitude 0 and drop the point in the Gulf\n // of Guinea. Hold until both sides are there; `halfEntered` below says\n // so in the meantime.\n if (rawLat.trim() === \"\" || rawLng.trim() === \"\") return;\n\n const latitude = Number(rawLat);\n const longitude = Number(rawLng);\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return;\n setValue({ latitude, longitude });\n }, [setValue]);\n\n const handleClear = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setLatText(\"\");\n setLngText(\"\");\n setValue(null);\n }, [setValue]);\n\n const latNumber = Number(latText);\n const lngNumber = Number(lngText);\n const latInvalid = latText.trim() !== \"\" && (!Number.isFinite(latNumber) || !inRange(latNumber, LAT_RANGE));\n const lngInvalid = lngText.trim() !== \"\" && (!Number.isFinite(lngNumber) || !inRange(lngNumber, LNG_RANGE));\n\n // One side filled and the other empty is not a point.\n const halfEntered = (latText.trim() === \"\") !== (lngText.trim() === \"\");\n\n const localError = latInvalid\n ? `Latitude must be between ${LAT_RANGE[0]} and ${LAT_RANGE[1]}`\n : lngInvalid\n ? `Longitude must be between ${LNG_RANGE[0]} and ${LNG_RANGE[1]}`\n : halfEntered\n ? \"A location needs both a latitude and a longitude\"\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-2 w-full\">\n {/* Label only, and only when there is one: a row that survives\n `hideLabel` still spends its `mb-1` and the column's `gap-2`, so\n the pair of inputs sat below the control next to them even\n though the two labels were level. */}\n {!hideLabel && <div className=\"flex items-center justify-between mb-1\">\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n />\n </div>}\n\n {/* Clear sits beside the inputs rather than above them, so\n entering a location does not grow the field by a row and\n knock it out of line with its neighbour. */}\n <div className=\"flex gap-4 w-full items-center\">\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Latitude\"\n value={latText}\n autoFocus={autoFocus}\n disabled={disabled}\n error={showError ? Boolean(error) || latInvalid : latInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLatText(e.target.value);\n commit(e.target.value, lngText);\n }}\n placeholder=\"e.g. 41.3874\"\n inputClassName=\"font-mono\"\n />\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Longitude\"\n value={lngText}\n disabled={disabled}\n error={showError ? Boolean(error) || lngInvalid : lngInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLngText(e.target.value);\n commit(latText, e.target.value);\n }}\n placeholder=\"e.g. 2.1686\"\n inputClassName=\"font-mono\"\n />\n {!disabled && (latText || lngText) && (\n <IconButton\n size=\"small\"\n onClick={handleClear}\n className=\"shrink-0 text-text-secondary hover:text-red-500\"\n aria-label=\"Clear location\"\n >\n <Trash2Icon size={14}/>\n </IconButton>\n )}\n </div>\n\n <FieldHelperText\n includeDescription={includeDescription}\n showError={showError || Boolean(localError)}\n error={error || localError}\n disabled={disabled}\n property={property}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;AAUA,IAAM,YAA8B,CAAC,KAAK,EAAE;AAC5C,IAAM,YAA8B,CAAC,MAAM,GAAG;;;;;;;;;AAY9C,SAAgB,gBAAgB,OAAoC;CAChE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,IAAI;CAEV,MAAM,MAAM,OAAO,EAAE,aAAa,WAAW,EAAE,WAAY,OAAO,EAAE,MAAM,WAAW,EAAE,IAAI,KAAA;CAC3F,MAAM,MAAM,OAAO,EAAE,cAAc,WAAW,EAAE,YAAa,OAAO,EAAE,MAAM,WAAW,EAAE,IAAI,KAAA;CAE7F,IAAI,OAAO,QAAQ,YAAY,OAAO,QAAQ,UAAU,OAAO;CAC/D,OAAO;EAAE,UAAU;EAAK,WAAW;CAAI;AAC3C;AAEA,IAAM,WAAW,GAAW,CAAC,KAAK,SAA2B,KAAK,OAAO,KAAK;;;;;;;;;;;;;;;;;AAkB9E,SAAgB,qBAAqB,EACjC,aACA,OACA,UACA,OACA,WACA,UACA,WACA,UACA,oBACA,WACA,OAAO,WACsB;CAE7B,MAAM,cAAc,gBAAgB,KAAK;CAIzC,MAAM,CAAC,SAAS,cAAc,eAAe,cAAc,OAAO,YAAY,QAAQ,IAAI,EAAE;CAC5F,MAAM,CAAC,SAAS,cAAc,eAAe,cAAc,OAA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,OAAD;EAAK,WAAU;YAAf;GAKK,CAAC,aAAa,oBAAC,OAAD;IAAK,WAAU;cAC1B,oBAAC,eAAD;KACI,MAAM,mBAAmB,UAAU,OAAO;KAC1C,UAAU,SAAS,YAAY;KAC/B,OAAO,SAAS,QAAQ;IAC3B,CAAA;GACA,CAAA;GAKL,qBAAC,OAAD;IAAK,WAAU;cAAf;KACI,oBAAC,WAAD;MACI,WAAU;MACJ;MACN,OAAM;MACN,OAAO;MACI;MACD;MACV,OAAO,YAAY,QAAQ,KAAK,KAAK,aAAa;MAClD,WAAW,MAAiE;OACxE,WAAW,EAAE,OAAO,KAAK;OACzB,OAAO,EAAE,OAAO,OAAO,OAAO;MAClC;MACA,aAAY;MACZ,gBAAe;KAClB,CAAA;KACD,oBAAC,WAAD;MACI,WAAU;MACJ;MACN,OAAM;MACN,OAAO;MACG;MACV,OAAO,YAAY,QAAQ,KAAK,KAAK,aAAa;MAClD,WAAW,MAAiE;OACxE,WAAW,EAAE,OAAO,KAAK;OACzB,OAAO,SAAS,EAAE,OAAO,KAAK;MAClC;MACA,aAAY;MACZ,gBAAe;KAClB,CAAA;KACA,CAAC,aAAa,WAAW,YACtB,oBAAC,YAAD;MACI,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAW;gBAEX,oBAAC,YAAD,EAAY,MAAM,GAAI,CAAA;KACd,CAAA;IAEf;;GAEL,oBAAC,iBAAD;IACwB;IACpB,WAAW,aAAa,QAAQ,UAAU;IAC1C,OAAO,SAAS;IACN;IACA;GACb,CAAA;EACA;;AAEb"}
@@ -16,5 +16,15 @@ import { AuthController } from "@rebasepro/cms-types";
16
16
  * its metadata rail — capped so it never eats the whole window.
17
17
  */
18
18
  export declare function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string;
19
+ /**
20
+ * Accept the names `open` / `replace` took in 0.28: `entityId` for `id`, and
21
+ * `onUpdate` for `onSaved`. Untyped callers still passing them would
22
+ * otherwise open a blank "new record" form for a record that exists (and
23
+ * duplicate it on save), and never hear about the save.
24
+ *
25
+ * `onUpdate` used to receive the saved entity; it now gets `{ entity }` built
26
+ * from the saved row, after any `onSaved`.
27
+ */
28
+ export declare function normalizeDeprecatedSidePanelProps<M extends Record<string, unknown>>(props: SidePanelBindingProps<M>): SidePanelBindingProps<M>;
19
29
  export declare const useBuildSidePanel: (collectionRegistryController: CollectionRegistryController, urlController: UrlController, navigationStateController: NavigationStateController, sideDialogsController: SideDialogsController, authController: AuthController) => SidePanelController;
20
30
  export declare function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[];
@@ -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,oBAAC,UAAD;EAAU,UAAU,oBAAC,wBAAD,CAAwB,CAAA;YAC/C,oBAAC,UAAD,EAAU,GAAI,MAAO,CAAA;CACf,CAAA;AACd;AAEA,SAAS,yBAAyB,OAA8B;CAC5D,IAAI,MAAM,YACN,OACI,oBAAC,yBAAD;EAAyB,YAAY,MAAM;YACvC,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;CACrB,CAAA;CAGjC,OAAO,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;AACrD;AAEA,IAAM,eAAe;AACrB,IAAM,gBAAgB;;;;;;;;;;;;;;;AAgBtB,SAAgB,mBAAmB,OAAmC,OAAgB,yBAA0D;CAC5I,IAAI,OAAO,OAAO;CAElB,IAAI,MAAM,OACN,OAAO,OAAO,MAAM,UAAU,WAAW,GAAG,MAAM,MAAM,MAAM,MAAM;CAExE,IAAI,MAAM,YAAY,iBAClB,OAAO,OAAO,MAAM,WAAW,oBAAoB,WAC7C,GAAG,MAAM,WAAW,gBAAgB,MACpC,MAAM,WAAW;CAE3B,OAAO;AACX;AAEA,IAAa,qBAAqB,8BAC9B,eACA,2BACA,uBACA,mBACsB;CAEtB,MAAM,WAAW,YAAY;CAC7B,MAAM,cAAc,OAAgB,KAAK;CACzC,MAAM,sBAAsB,OAAiB,CAAC,CAAC;CAC/C,MAAM,0BAA0B,2BAA2B;CAE3D,MAAM,cAAc,CAAC,eAAe;CAEpC,gBAAgB;EAEZ,MAAM,UAAU,SAAS,SAAS,IAAI;EACtC,MAAM,WAAW,SAAS,SAAS,IAA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B,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
+ {"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,qBAA4C,oBAAoB,oBAAgB;CACjG,OAAO,oBAAC,UAAD;EAAU,UAAU,oBAAC,wBAAD,CAAwB,CAAA;YAC/C,oBAAC,UAAD,EAAU,GAAI,MAAO,CAAA;CACf,CAAA;AACd;AAEA,SAAS,yBAAyB,OAA8B;CAC5D,IAAI,MAAM,YACN,OACI,oBAAC,yBAAD;EAAyB,YAAY,MAAM;YACvC,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;CACrB,CAAA;CAGjC,OAAO,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;AACrD;AAEA,IAAM,eAAe;AACrB,IAAM,gBAAgB;;;;;;;;;;;;;;;AAgBtB,SAAgB,mBAAmB,OAAmC,OAAgB,yBAA0D;CAC5I,IAAI,OAAO,OAAO;CAElB,IAAI,MAAM,OACN,OAAO,OAAO,MAAM,UAAU,WAAW,GAAG,MAAM,MAAM,MAAM,MAAM;CAExE,IAAI,MAAM,YAAY,iBAClB,OAAO,OAAO,MAAM,WAAW,oBAAoB,WAC7C,GAAG,MAAM,WAAW,gBAAgB,MACpC,MAAM,WAAW;CAE3B,OAAO;AACX;;;;;;;;;;AAWA,SAAgB,kCAAqE,OAA2D;CAC5I,MAAM,EAAE,UAAU,UAAU,GAAG,YAAY;CAC3C,IAAI,SAAmC;CACvC,IAAI,aAAa,KAAA,GAAW;EACxB,eAAe,kCACX,sFAAsF;EAC1F,IAAI,QAAQ,OAAO,KAAA,GAAW,SAAS;GAAE,GAAG;GAAQ,IAAI;EAAS;CACrE;CACA,IAAI,UAAU;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BAAD,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 }, [navig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BAAoB,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"}
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,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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";
@@ -72,3 +72,5 @@ export type { DetailViewBindingProps } from "./components/DetailViewBinding.js";
72
72
  export { NavigationCardBinding } from "./components/HomePage/NavigationCardBinding.js";
73
73
  export { NavigationGroup } from "./components/HomePage/NavigationGroup.js";
74
74
  export { FavouritesView } from "./components/HomePage/FavouritesView.js";
75
+ export { SavedAppsView, savedAppsView } from "./saved_apps/SavedAppsView.js";
76
+ export { SavedAppFrame, sandboxedViewDocument } from "./saved_apps/saved_app_frame.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,6 @@ 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
+ import { SavedAppFrame, sandboxedViewDocument } from "./saved_apps/saved_app_frame.js";
185
+ import { SavedAppsView, savedAppsView } from "./saved_apps/SavedAppsView.js";
186
+ 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, SavedAppFrame, SavedAppsView, 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, sandboxedViewDocument, sanitizeUrl, saveImportedEntities, savedAppsView, 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 \"@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,WA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
+ {"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,SAAS,sBAAsB,UAAU,CAAC,IAAI;EAC7D,MAAM,IAAI,MAAM,IAAI,KAAK,0CAA0C,QAAQ,KAAK,IAAI,EAAE,0CAC1C;CAChD,GAAG,CAAC,SAAS,QAAQ,CAAC;AAC1B;AAEA,SAAS,mBAAmB,OAA6B;CACrD,mBAAmB,CAAC,CAAC,iBAAiB,MAAM,YAAY,MAAM,IAAI,CAAC,CAAC,IAAI;CACxE,OAAO,oBAAC,iBAAD,EAAiB,GAAI,MAAO,CAAA;AACvC;AAEA,SAAS,cAAc,EAAE,qBAAqB,GAAG,SAA0B;CACvE,mBAAmB,CAAC,CAAC,iBAAiB,MAAM,YAAY,MAAM,IAAI,CAAC,CAAC,IAAI;CAIxE,OAAO,oBAAC,YAAD;EAAY,GAAI;EAAO,qBAAqB;GAAE,GAAG;GAAqB,cAAc;E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O;IACZ,OAAO,QAAQ,OAAO,KAAK;GAC/B;GACA,OAAO,MAAM;EACjB;EACA,OAAO;GACH,GAAG;GACH,SAAS,YAAY,QAAQ,OAAO,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"}
@@ -34,11 +34,31 @@ export interface HostContext {
34
34
  availableDisplayModes?: DisplayMode[];
35
35
  locale?: string;
36
36
  }
37
+ /**
38
+ * What the view needs of its channel: the call that opened it, the host's
39
+ * context, and the tools. {@link McpAppBridge} is the MCP Apps host's; a
40
+ * page that reaches the server another way (an artifact, through the
41
+ * viewer's connector) brings its own.
42
+ */
43
+ export interface ViewBridge {
44
+ readonly hostContext: HostContext;
45
+ watchHostContext(watcher: (context: HostContext) => void): () => void;
46
+ ontoolinput: ((args: Record<string, unknown>) => void) | undefined;
47
+ ontoolresult: ((result: ToolResult) => void) | undefined;
48
+ connect(appInfo: {
49
+ name: string;
50
+ version: string;
51
+ }): Promise<void>;
52
+ callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;
53
+ updateModelContext(text: string): Promise<void>;
54
+ requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined>;
55
+ sizeChanged(height: number): void;
56
+ }
37
57
  /** The host end of the channel: the parent window, in a host. */
38
58
  export interface HostWindow {
39
59
  postMessage(message: unknown, targetOrigin: string): void;
40
60
  }
41
- export declare class McpAppBridge {
61
+ export declare class McpAppBridge implements ViewBridge {
42
62
  onhostcontext?: (context: HostContext) => void;
43
63
  /** Everything the host has said about its context so far, each update merged in. */
44
64
  hostContext: HostContext;
@@ -1 +1 @@
1
- {"version":3,"file":"bridge.js","names":[],"sources":["../../src/mcp_view/bridge.ts"],"sourcesContent":["/**\n * The view's side of the MCP Apps protocol (`io.modelcontextprotocol/ui`,\n * revision 2026-01-26): JSON-RPC 2.0 over `postMessage` with the host window.\n *\n * Hand-written rather than taken from `@modelcontextprotocol/ext-apps`, whose\n * `App` carries the MCP SDK and zod — half a megabyte, in a document a host\n * downloads for every table it shows. A view needs a handful of messages:\n *\n * - `ui/initialize` → the host's context (theme, display mode), then\n * `ui/notifications/initialized`;\n * - the host's `ui/notifications/tool-input` and `…/tool-result`: the call\n * that opened this view, and its answer;\n * - `tools/call`, which the host relays to the MCP server with its own\n * credential — the view holds none;\n * - `ui/update-model-context`, to tell the model what the person did here;\n * - `ui/notifications/size-changed`, so the host sizes the iframe to fit;\n * - `ui/request-display-mode`, to open the view fullscreen where the host\n * offers it.\n */\n\nexport const APPS_PROTOCOL_VERSION = \"2026-01-26\";\n\nexport interface ToolResult {\n content?: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n isError?: boolean;\n}\n\nexport type DisplayMode = \"inline\" | \"fullscreen\" | \"pip\";\n\n/** The modes this view can be shown in. Declared at the handshake. */\nconst VIEW_DISPLAY_MODES: DisplayMode[] = [\"inline\", \"fullscreen\"];\n\nexport interface HostContext {\n theme?: \"light\" | \"dark\";\n displayMode?: DisplayMode;\n /** The modes the host will show this view in; absent, only the one it is in. */\n availableDisplayModes?: DisplayMode[];\n locale?: string;\n}\n\ninterface Pending {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n}\n\ntype JsonRpcId = string | number;\n\n/** The host end of the channel: the parent window, in a host. */\nexport interface HostWindow {\n postMessage(message: unknown, targetOrigin: string): void;\n}\n\nexport class McpAppBridge {\n onhostcontext?: (context: HostContext) => void;\n\n /** Everything the host has said about its context so far, each update merged in. */\n hostContext: HostContext = {};\n private readonly contextWatchers = new Set<(context: HostContext) => void>();\n\n /** Called with the whole context now and on every change; returns the unsubscribe. */\n watchHostContext(watcher: (context: HostContext) => void): () => void {\n this.contextWatchers.add(watcher);\n watcher(this.hostContext);\n return () => {\n this.contextWatchers.delete(watcher);\n };\n }\n\n /**\n * The call that opened this view, and its answer. Kept, because the host\n * may send them before a handler is set — a React effect runs after the\n * first paint — and it sends each once.\n */\n toolInput?: Record<string, unknown>;\n toolResult?: ToolResult;\n private inputHandler?: (args: Record<string, unknown>) => void;\n private resultHandler?: (result: ToolResult) => void;\n\n set ontoolinput(handler: ((args: Record<string, unknown>) => void) | undefined) {\n this.inputHandler = handler;\n if (handler && this.toolInput) handler(this.toolInput);\n }\n\n set ontoolresult(handler: ((result: ToolResult) => void) | undefined) {\n this.resultHandler = handler;\n if (handler && this.toolResult) handler(this.toolResult);\n }\n\n private nextId = 1;\n private connected = false;\n private height?: number;\n private readonly pending = new Map<JsonRpcId, Pending>();\n private readonly host: HostWindow;\n\n /** `events` is where the host's messages arrive: this view's window. */\n constructor(host: HostWindow = window.parent, events: EventTarget = window) {\n this.host = host;\n events.addEventListener(\"message\", this.receive);\n }\n\n async connect(appInfo: { name: string; version: string }): Promise<void> {\n const result = await this.request(\"ui/initialize\", {\n appInfo,\n appCapabilities: { availableDisplayModes: VIEW_DISPLAY_MODES },\n protocolVersion: APPS_PROTOCOL_VERSION\n });\n if (isRecord(result) && isRecord(result.hostContext)) this.contextChanged(hostContextOf(result.hostContext));\n this.notify(\"ui/notifications/initialized\", {});\n this.connected = true;\n // A size measured before the handshake is held until now: nothing\n // but `ui/initialize` may reach the host before it.\n if (this.height !== undefined) this.notify(\"ui/notifications/size-changed\", { height: this.height });\n }\n\n /** A tool on this view's MCP server, called through the host. */\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n const result = await this.request(\"tools/call\", { name, arguments: args });\n return isRecord(result) ? toolResultOf(result) : {};\n }\n\n /**\n * What the model should know about this view, sent with the person's next\n * message. Each call replaces the last.\n */\n async updateModelContext(text: string): Promise<void> {\n await this.request(\"ui/update-model-context\", { content: [{ type: \"text\", text }] });\n }\n\n /**\n * Ask the host to show this view in `mode`. The answer is the mode it is\n * in now, which may not be the one asked for.\n */\n async requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined> {\n const result = await this.request(\"ui/request-display-mode\", { mode });\n return isRecord(result) && isDisplayMode(result.mode) ? result.mode : undefined;\n }\n\n /** The document's height, for the host to size the iframe to. Sent when it changes. */\n sizeChanged(height: number): void {\n if (height === this.height) return;\n this.height = height;\n if (this.connected) this.notify(\"ui/notifications/size-changed\", { height });\n }\n\n private contextChanged(update: HostContext): void {\n this.hostContext = { ...this.hostContext, ...update };\n this.onhostcontext?.(update);\n for (const watcher of this.contextWatchers) watcher(this.hostContext);\n }\n\n private request(method: string, params: Record<string, unknown>): Promise<unknown> {\n const id = this.nextId++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.host.postMessage({ jsonrpc: \"2.0\", id, method, params }, \"*\");\n });\n }\n\n private notify(method: string, params: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", method, params }, \"*\");\n }\n\n private respond(id: JsonRpcId, result: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", id, result }, \"*\");\n }\n\n private readonly receive = (event: Event): void => {\n // Only the host speaks to this view. The sandbox gives the iframe an\n // opaque origin, so the window is the check, not the origin.\n if (!(event instanceof MessageEvent) || event.source !== this.host) return;\n const message: unknown = event.data;\n if (!isRecord(message) || message.jsonrpc !== \"2.0\") return;\n const id = typeof message.id === \"string\" || typeof message.id === \"number\" ? message.id : undefined;\n\n if (id !== undefined && (\"result\" in message || \"error\" in message)) {\n const pending = this.pending.get(id);\n if (!pending) return;\n this.pending.delete(id);\n if (isRecord(message.error)) pending.reject(new Error(String(message.error.message ?? \"The host refused the request.\")));\n else pending.resolve(message.result);\n return;\n }\n\n const params = isRecord(message.params) ? message.params : {};\n switch (message.method) {\n case \"ui/notifications/tool-input\":\n this.toolInput = isRecord(params.arguments) ? params.arguments : {};\n this.inputHandler?.(this.toolInput);\n return;\n case \"ui/notifications/tool-result\":\n this.toolResult = toolResultOf(params);\n this.resultHandler?.(this.toolResult);\n return;\n case \"ui/notifications/host-context-changed\":\n this.contextChanged(hostContextOf(params));\n return;\n // Requests the host may send. Nothing to clean up, nothing to report.\n case \"ui/resource-teardown\":\n case \"ping\":\n if (id !== undefined) this.respond(id, {});\n return;\n }\n };\n}\n\nfunction toolResultOf(value: Record<string, unknown>): ToolResult {\n return {\n content: Array.isArray(value.content)\n ? value.content.filter(isRecord).map(block => ({\n type: String(block.type),\n ...(typeof block.text === \"string\" && { text: block.text })\n }))\n : undefined,\n structuredContent: value.structuredContent,\n isError: value.isError === true\n };\n}\n\n/** The fields of the host's context this view reads. A partial update leaves the rest out. */\nfunction hostContextOf(value: Record<string, unknown>): HostContext {\n return {\n ...((value.theme === \"light\" || value.theme === \"dark\") && { theme: value.theme }),\n ...(isDisplayMode(value.displayMode) && { displayMode: value.displayMode }),\n ...(Array.isArray(value.availableDisplayModes) && {\n availableDisplayModes: value.availableDisplayModes.filter(isDisplayMode)\n }),\n ...(typeof value.locale === \"string\" && { locale: value.locale })\n };\n}\n\nfunction isDisplayMode(value: unknown): value is DisplayMode {\n return value === \"inline\" || value === \"fullscreen\" || value === \"pip\";\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,wBAAwB;;AAWrC,IAAM,qBAAoC,CAAC,UAAU,YAAY;AAsBjE,IAAa,eAAb,MAA0B;CACtB;;CAGA,cAA2B,CAAC;CAC5B,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B,MAAM,sBAAsB,OAAO,aAAa,EAC3E;EACA,GAAI,OAAO,MAAM,WAAW,YAAY,EAAE,QAAQ,MAAM,OAAO;CACnE;AACJ;AAEA,SAAS,cAAc,OAAsC;CACzD,OAAO,UAAU,YAAY,UAAU,gBAAgB,UAAU;AACrE;AAEA,SAAgB,SAAS,OAAkD;CACvE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC9E"}
1
+ {"version":3,"file":"bridge.js","names":[],"sources":["../../src/mcp_view/bridge.ts"],"sourcesContent":["/**\n * The view's side of the MCP Apps protocol (`io.modelcontextprotocol/ui`,\n * revision 2026-01-26): JSON-RPC 2.0 over `postMessage` with the host window.\n *\n * Hand-written rather than taken from `@modelcontextprotocol/ext-apps`, whose\n * `App` carries the MCP SDK and zod — half a megabyte, in a document a host\n * downloads for every table it shows. A view needs a handful of messages:\n *\n * - `ui/initialize` → the host's context (theme, display mode), then\n * `ui/notifications/initialized`;\n * - the host's `ui/notifications/tool-input` and `…/tool-result`: the call\n * that opened this view, and its answer;\n * - `tools/call`, which the host relays to the MCP server with its own\n * credential — the view holds none;\n * - `ui/update-model-context`, to tell the model what the person did here;\n * - `ui/notifications/size-changed`, so the host sizes the iframe to fit;\n * - `ui/request-display-mode`, to open the view fullscreen where the host\n * offers it.\n */\n\nexport const APPS_PROTOCOL_VERSION = \"2026-01-26\";\n\nexport interface ToolResult {\n content?: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n isError?: boolean;\n}\n\nexport type DisplayMode = \"inline\" | \"fullscreen\" | \"pip\";\n\n/** The modes this view can be shown in. Declared at the handshake. */\nconst VIEW_DISPLAY_MODES: DisplayMode[] = [\"inline\", \"fullscreen\"];\n\nexport interface HostContext {\n theme?: \"light\" | \"dark\";\n displayMode?: DisplayMode;\n /** The modes the host will show this view in; absent, only the one it is in. */\n availableDisplayModes?: DisplayMode[];\n locale?: string;\n}\n\ninterface Pending {\n resolve: (result: unknown) => void;\n reject: (error: Error) => void;\n}\n\ntype JsonRpcId = string | number;\n\n/**\n * What the view needs of its channel: the call that opened it, the host's\n * context, and the tools. {@link McpAppBridge} is the MCP Apps host's; a\n * page that reaches the server another way (an artifact, through the\n * viewer's connector) brings its own.\n */\nexport interface ViewBridge {\n readonly hostContext: HostContext;\n watchHostContext(watcher: (context: HostContext) => void): () => void;\n ontoolinput: ((args: Record<string, unknown>) => void) | undefined;\n ontoolresult: ((result: ToolResult) => void) | undefined;\n connect(appInfo: { name: string; version: string }): Promise<void>;\n callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;\n updateModelContext(text: string): Promise<void>;\n requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined>;\n sizeChanged(height: number): void;\n}\n\n/** The host end of the channel: the parent window, in a host. */\nexport interface HostWindow {\n postMessage(message: unknown, targetOrigin: string): void;\n}\n\nexport class McpAppBridge implements ViewBridge {\n onhostcontext?: (context: HostContext) => void;\n\n /** Everything the host has said about its context so far, each update merged in. */\n hostContext: HostContext = {};\n private readonly contextWatchers = new Set<(context: HostContext) => void>();\n\n /** Called with the whole context now and on every change; returns the unsubscribe. */\n watchHostContext(watcher: (context: HostContext) => void): () => void {\n this.contextWatchers.add(watcher);\n watcher(this.hostContext);\n return () => {\n this.contextWatchers.delete(watcher);\n };\n }\n\n /**\n * The call that opened this view, and its answer. Kept, because the host\n * may send them before a handler is set — a React effect runs after the\n * first paint — and it sends each once.\n */\n toolInput?: Record<string, unknown>;\n toolResult?: ToolResult;\n private inputHandler?: (args: Record<string, unknown>) => void;\n private resultHandler?: (result: ToolResult) => void;\n\n set ontoolinput(handler: ((args: Record<string, unknown>) => void) | undefined) {\n this.inputHandler = handler;\n if (handler && this.toolInput) handler(this.toolInput);\n }\n\n set ontoolresult(handler: ((result: ToolResult) => void) | undefined) {\n this.resultHandler = handler;\n if (handler && this.toolResult) handler(this.toolResult);\n }\n\n private nextId = 1;\n private connected = false;\n private height?: number;\n private readonly pending = new Map<JsonRpcId, Pending>();\n private readonly host: HostWindow;\n\n /** `events` is where the host's messages arrive: this view's window. */\n constructor(host: HostWindow = window.parent, events: EventTarget = window) {\n this.host = host;\n events.addEventListener(\"message\", this.receive);\n }\n\n async connect(appInfo: { name: string; version: string }): Promise<void> {\n const result = await this.request(\"ui/initialize\", {\n appInfo,\n appCapabilities: { availableDisplayModes: VIEW_DISPLAY_MODES },\n protocolVersion: APPS_PROTOCOL_VERSION\n });\n if (isRecord(result) && isRecord(result.hostContext)) this.contextChanged(hostContextOf(result.hostContext));\n this.notify(\"ui/notifications/initialized\", {});\n this.connected = true;\n // A size measured before the handshake is held until now: nothing\n // but `ui/initialize` may reach the host before it.\n if (this.height !== undefined) this.notify(\"ui/notifications/size-changed\", { height: this.height });\n }\n\n /** A tool on this view's MCP server, called through the host. */\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n const result = await this.request(\"tools/call\", { name, arguments: args });\n return isRecord(result) ? toolResultOf(result) : {};\n }\n\n /**\n * What the model should know about this view, sent with the person's next\n * message. Each call replaces the last.\n */\n async updateModelContext(text: string): Promise<void> {\n await this.request(\"ui/update-model-context\", { content: [{ type: \"text\", text }] });\n }\n\n /**\n * Ask the host to show this view in `mode`. The answer is the mode it is\n * in now, which may not be the one asked for.\n */\n async requestDisplayMode(mode: DisplayMode): Promise<DisplayMode | undefined> {\n const result = await this.request(\"ui/request-display-mode\", { mode });\n return isRecord(result) && isDisplayMode(result.mode) ? result.mode : undefined;\n }\n\n /** The document's height, for the host to size the iframe to. Sent when it changes. */\n sizeChanged(height: number): void {\n if (height === this.height) return;\n this.height = height;\n if (this.connected) this.notify(\"ui/notifications/size-changed\", { height });\n }\n\n private contextChanged(update: HostContext): void {\n this.hostContext = { ...this.hostContext, ...update };\n this.onhostcontext?.(update);\n for (const watcher of this.contextWatchers) watcher(this.hostContext);\n }\n\n private request(method: string, params: Record<string, unknown>): Promise<unknown> {\n const id = this.nextId++;\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject });\n this.host.postMessage({ jsonrpc: \"2.0\", id, method, params }, \"*\");\n });\n }\n\n private notify(method: string, params: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", method, params }, \"*\");\n }\n\n private respond(id: JsonRpcId, result: Record<string, unknown>): void {\n this.host.postMessage({ jsonrpc: \"2.0\", id, result }, \"*\");\n }\n\n private readonly receive = (event: Event): void => {\n // Only the host speaks to this view. The sandbox gives the iframe an\n // opaque origin, so the window is the check, not the origin.\n if (!(event instanceof MessageEvent) || event.source !== this.host) return;\n const message: unknown = event.data;\n if (!isRecord(message) || message.jsonrpc !== \"2.0\") return;\n const id = typeof message.id === \"string\" || typeof message.id === \"number\" ? message.id : undefined;\n\n if (id !== undefined && (\"result\" in message || \"error\" in message)) {\n const pending = this.pending.get(id);\n if (!pending) return;\n this.pending.delete(id);\n if (isRecord(message.error)) pending.reject(new Error(String(message.error.message ?? \"The host refused the request.\")));\n else pending.resolve(message.result);\n return;\n }\n\n const params = isRecord(message.params) ? message.params : {};\n switch (message.method) {\n case \"ui/notifications/tool-input\":\n this.toolInput = isRecord(params.arguments) ? params.arguments : {};\n this.inputHandler?.(this.toolInput);\n return;\n case \"ui/notifications/tool-result\":\n this.toolResult = toolResultOf(params);\n this.resultHandler?.(this.toolResult);\n return;\n case \"ui/notifications/host-context-changed\":\n this.contextChanged(hostContextOf(params));\n return;\n // Requests the host may send. Nothing to clean up, nothing to report.\n case \"ui/resource-teardown\":\n case \"ping\":\n if (id !== undefined) this.respond(id, {});\n return;\n }\n };\n}\n\nfunction toolResultOf(value: Record<string, unknown>): ToolResult {\n return {\n content: Array.isArray(value.content)\n ? value.content.filter(isRecord).map(block => ({\n type: String(block.type),\n ...(typeof block.text === \"string\" && { text: block.text })\n }))\n : undefined,\n structuredContent: value.structuredContent,\n isError: value.isError === true\n };\n}\n\n/** The fields of the host's context this view reads. A partial update leaves the rest out. */\nfunction hostContextOf(value: Record<string, unknown>): HostContext {\n return {\n ...((value.theme === \"light\" || value.theme === \"dark\") && { theme: value.theme }),\n ...(isDisplayMode(value.displayMode) && { displayMode: value.displayMode }),\n ...(Array.isArray(value.availableDisplayModes) && {\n availableDisplayModes: value.availableDisplayModes.filter(isDisplayMode)\n }),\n ...(typeof value.locale === \"string\" && { locale: value.locale })\n };\n}\n\nfunction isDisplayMode(value: unknown): value is DisplayMode {\n return value === \"inline\" || value === \"fullscreen\" || value === \"pip\";\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,wBAAwB;;AAWrC,IAAM,qBAAoC,CAAC,UAAU,YAAY;AAwCjE,IAAa,eAAb,MAAgD;CAC5C;;CAGA,cAA2B,CAAC;CAC5B,kCAAmC,IAAI,IAAoC;;CAG3E,iBAAiB,SAAqD;EAClE,KAAK,gBAAgB,IAAI,OAAO;EAChC,QAAQ,KAAK,WAAW;EACxB,aAAa;GACT,KAAK,gBAAgB,OAAO,OAAO;EACvC;CACJ;;;;;;CAOA;CACA;CACA;CACA;CAEA,IAAI,YAAY,SAAgE;EAC5E,KAAK,eAAe;EACpB,IAAI,WAAW,KAAK,WAAW,QAAQ,KAAK,SAAS;CACzD;CAEA,IAAI,aAAa,SAAqD;EAClE,KAAK,gBAAgB;EACrB,IAAI,WAAW,KAAK,YAAY,QAAQ,KAAK,UAAU;CAC3D;CAEA,SAAiB;CACjB,YAAoB;CACpB;CACA,0BAA2B,IAAI,IAAwB;CACvD;;CAGA,YAAY,OAAmB,OAAO,QAAQ,SAAsB,QAAQ;EACxE,KAAK,OAAO;EACZ,OAAO,iBAAiB,WAAW,KAAK,OAAO;CACnD;CAEA,MAAM,QAAQ,SAA2D;EACrE,MAAM,SAAS,MAAM,KAAK,QAAQ,iBAAiB;GAC/C;GACA,iBAAiB,EAAE,uBAAuB,mBAAmB;GAC7D,iBAAiB;EACrB,CAAC;EACD,IAAI,SAAS,MAAM,K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