@rebasepro/cms 0.25.0 → 0.26.0

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 (125) hide show
  1. package/dist/collection_editor/liveSchemaClient.d.ts +3 -3
  2. package/dist/collection_editor/liveSchemaClient.js.map +1 -1
  3. package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js +1 -1
  4. package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js.map +1 -1
  5. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.d.ts +7 -1
  6. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +61 -50
  7. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
  8. package/dist/collection_editor/ui/collection_editor/properties/DateTimePropertyField.js +22 -22
  9. package/dist/collection_editor/ui/collection_editor/properties/DateTimePropertyField.js.map +1 -1
  10. package/dist/collection_editor/ui/collection_editor/properties/NumberPropertyField.js +14 -14
  11. package/dist/collection_editor/ui/collection_editor/properties/NumberPropertyField.js.map +1 -1
  12. package/dist/collection_editor/ui/collection_editor/properties/StringPropertyField.js +24 -24
  13. package/dist/collection_editor/ui/collection_editor/properties/StringPropertyField.js.map +1 -1
  14. package/dist/collection_editor/useLiveSchemaEditing.js +4 -1
  15. package/dist/collection_editor/useLiveSchemaEditing.js.map +1 -1
  16. package/dist/components/CollectionTableBinding/fields/TableReferenceField.js +1 -1
  17. package/dist/components/CollectionTableBinding/fields/TableReferenceField.js.map +1 -1
  18. package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.d.ts +1 -2
  19. package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js.map +1 -1
  20. package/dist/components/CollectionTableBinding/internal/EntityTableCell.d.ts +1 -2
  21. package/dist/components/CollectionTableBinding/internal/EntityTableCell.js.map +1 -1
  22. package/dist/components/CollectionViewBinding/CollectionViewActions.js +1 -1
  23. package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
  24. package/dist/components/CollectionViewBinding/CollectionViewBinding.js +2 -28
  25. package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
  26. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.d.ts +12 -0
  27. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js +33 -0
  28. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js.map +1 -0
  29. package/dist/components/CollectionsScopeContext.d.ts +5 -1
  30. package/dist/components/CollectionsScopeContext.js +10 -2
  31. package/dist/components/CollectionsScopeContext.js.map +1 -1
  32. package/dist/components/DefaultAppBar.js +2 -1
  33. package/dist/components/DefaultAppBar.js.map +1 -1
  34. package/dist/components/DefaultDrawer.js +16 -4
  35. package/dist/components/DefaultDrawer.js.map +1 -1
  36. package/dist/components/DefaultMissingReference.d.ts +8 -0
  37. package/dist/components/DefaultMissingReference.js +13 -0
  38. package/dist/components/DefaultMissingReference.js.map +1 -0
  39. package/dist/components/DeleteEntityDialog.js +9 -9
  40. package/dist/components/DeleteEntityDialog.js.map +1 -1
  41. package/dist/components/EntityFormPanel.d.ts +7 -2
  42. package/dist/components/EntityFormPanel.js +72 -29
  43. package/dist/components/EntityFormPanel.js.map +1 -1
  44. package/dist/components/HomePage/ContentHomePage.js +4 -3
  45. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  46. package/dist/components/HomePage/HomePageDnD.js +3 -1
  47. package/dist/components/HomePage/HomePageDnD.js.map +1 -1
  48. package/dist/components/HomePage/SmallNavigationCard.js +25 -0
  49. package/dist/components/HomePage/SmallNavigationCard.js.map +1 -0
  50. package/dist/components/RebaseAuthGate.js +3 -2
  51. package/dist/components/RebaseAuthGate.js.map +1 -1
  52. package/dist/components/RebaseLayout.d.ts +4 -1
  53. package/dist/components/RebaseLayout.js +7 -1
  54. package/dist/components/RebaseLayout.js.map +1 -1
  55. package/dist/components/RebaseShell.d.ts +4 -1
  56. package/dist/components/RebaseShell.js.map +1 -1
  57. package/dist/components/ReferenceTable/SelectionTableBinding.js +4 -3
  58. package/dist/components/ReferenceTable/SelectionTableBinding.js.map +1 -1
  59. package/dist/components/RelationSelector.js +2 -2
  60. package/dist/components/RelationSelector.js.map +1 -1
  61. package/dist/components/SideDialogs.js +10 -4
  62. package/dist/components/SideDialogs.js.map +1 -1
  63. package/dist/components/app/Scaffold.js +5 -1
  64. package/dist/components/app/Scaffold.js.map +1 -1
  65. package/dist/components/field_configs.js +1 -1
  66. package/dist/components/history/EntityHistoryView.js +6 -4
  67. package/dist/components/history/EntityHistoryView.js.map +1 -1
  68. package/dist/components/history/LastEditedByIndicator.d.ts +2 -1
  69. package/dist/data_export/export/export.d.ts +2 -13
  70. package/dist/data_export/export/export.js +1 -36
  71. package/dist/data_export/export/export.js.map +1 -1
  72. package/dist/form/EntityForm.d.ts +1 -1
  73. package/dist/form/EntityForm.js +17 -13
  74. package/dist/form/EntityForm.js.map +1 -1
  75. package/dist/form/EntityFormBinding.d.ts +1 -1
  76. package/dist/form/EntityFormBinding.js +42 -4
  77. package/dist/form/EntityFormBinding.js.map +1 -1
  78. package/dist/form/PropertyFieldBinding.js +1 -1
  79. package/dist/form/components/FieldBlock.d.ts +8 -1
  80. package/dist/form/components/FieldBlock.js +16 -2
  81. package/dist/form/components/FieldBlock.js.map +1 -1
  82. package/dist/form/components/FormSections.js +1 -1
  83. package/dist/form/components/FormSections.js.map +1 -1
  84. package/dist/form/components/LabelWithIcon.js +5 -2
  85. package/dist/form/components/LabelWithIcon.js.map +1 -1
  86. package/dist/form/field_bindings/DateTimeFieldBinding.js +2 -1
  87. package/dist/form/field_bindings/DateTimeFieldBinding.js.map +1 -1
  88. package/dist/form/field_bindings/ReadOnlyFieldBinding.js +28 -1
  89. package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
  90. package/dist/form/field_bindings/RelationFieldBinding.js +7 -3
  91. package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
  92. package/dist/form/field_bindings/SelectFieldBinding.js +63 -42
  93. package/dist/form/field_bindings/SelectFieldBinding.js.map +1 -1
  94. package/dist/form/field_bindings/SwitchFieldBinding.js +2 -1
  95. package/dist/form/field_bindings/SwitchFieldBinding.js.map +1 -1
  96. package/dist/form/field_bindings/TextFieldBinding.js +8 -6
  97. package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
  98. package/dist/form/form_utils.d.ts +18 -1
  99. package/dist/form/form_utils.js +38 -2
  100. package/dist/form/form_utils.js.map +1 -1
  101. package/dist/form/index.d.ts +1 -1
  102. package/dist/form/label_placement.d.ts +23 -0
  103. package/dist/form/label_placement.js +71 -0
  104. package/dist/form/label_placement.js.map +1 -0
  105. package/dist/form/resolve_form_properties.d.ts +35 -3
  106. package/dist/form/resolve_form_properties.js +67 -6
  107. package/dist/form/resolve_form_properties.js.map +1 -1
  108. package/dist/hooks/useHistory.d.ts +5 -0
  109. package/dist/hooks/useHistory.js +22 -6
  110. package/dist/hooks/useHistory.js.map +1 -1
  111. package/dist/index.d.ts +50 -0
  112. package/dist/index.js +34 -7
  113. package/dist/preview/components/ReferencePreview.js +1 -1
  114. package/dist/preview/components/ReferencePreview.js.map +1 -1
  115. package/dist/preview/components/RelationPreview.js +1 -1
  116. package/dist/preview/components/RelationPreview.js.map +1 -1
  117. package/dist/types/components/EntityFormProps.d.ts +11 -0
  118. package/package.json +11 -10
  119. package/recipes/README.md +131 -0
  120. package/recipes/bulk-set-status.tsx +62 -0
  121. package/recipes/calendar-view.tsx +123 -0
  122. package/recipes/custom-login.tsx +60 -0
  123. package/recipes/my-preferences.tsx +68 -0
  124. package/recipes/orders-dashboard.tsx +125 -0
  125. package/recipes/site-settings.tsx +63 -0
@@ -3,7 +3,7 @@ import { EntityHistoryEntry } from "./EntityHistoryEntry.js";
3
3
  import { useEffect, useRef, useState } from "react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
  import { ErrorBoundary, HistoryIcon, IconButton, Label, Tooltip, Typography, cls } from "@rebasepro/ui";
6
- import { ConfirmationDialog, useAuthController, useSnackbarController, useTranslation } from "@rebasepro/app";
6
+ import { ConfirmationDialog, usePermissions, useSnackbarController, useTranslation } from "@rebasepro/app";
7
7
  //#region src/components/history/EntityHistoryView.tsx
8
8
  /**
9
9
  * Entity history tab view. Shows a paginated list of entity revisions
@@ -12,7 +12,7 @@ import { ConfirmationDialog, useAuthController, useSnackbarController, useTransl
12
12
  function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
13
13
  const { t } = useTranslation();
14
14
  const snackbarController = useSnackbarController();
15
- useAuthController();
15
+ const { canEdit } = usePermissions();
16
16
  const dirty = formContext?.formex.dirty;
17
17
  const slug = collection.slug;
18
18
  const entityId = entity?.id;
@@ -50,6 +50,7 @@ function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
50
50
  className: "flex items-center justify-center h-full",
51
51
  children: /* @__PURE__ */ jsx(Label, { children: t("history_new_entity") ?? "History is only available for existing records" })
52
52
  });
53
+ const editable = canEdit(collection, entity.path ?? slug, entity);
53
54
  async function doRevert(historyId) {
54
55
  setIsReverting(true);
55
56
  try {
@@ -66,8 +67,9 @@ function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
66
67
  });
67
68
  } catch (error) {
68
69
  console.error("Error reverting entity:", error);
70
+ const reason = error instanceof Error ? error.message : void 0;
69
71
  snackbarController.open({
70
- message: t("history_revert_error") ?? "Error reverting entity",
72
+ message: [t("history_revert_error") ?? "Error reverting entity", reason].filter(Boolean).join(": "),
71
73
  type: "error"
72
74
  });
73
75
  } finally {
@@ -102,7 +104,7 @@ function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
102
104
  entry,
103
105
  collection,
104
106
  size: "medium",
105
- actions: /* @__PURE__ */ jsx(Tooltip, {
107
+ actions: editable && /* @__PURE__ */ jsx(Tooltip, {
106
108
  title: t("history_revert") ?? "Revert to this version",
107
109
  className: "m-2 grow-0 self-start",
108
110
  children: /* @__PURE__ */ jsx(IconButton, {
@@ -1 +1 @@
1
- {"version":3,"file":"EntityHistoryView.js","names":[],"sources":["../../../src/components/history/EntityHistoryView.tsx"],"sourcesContent":["\nimport type { EntityCustomViewParams } from \"@rebasepro/cms-types\";\nimport { useRef, useEffect } from \"react\";\nimport { cls, IconButton, Label, Tooltip, Typography } from \"@rebasepro/ui\";\nimport { ErrorBoundary, HistoryIcon } from \"@rebasepro/ui\";\nimport { EntityHistoryEntry } from \"./EntityHistoryEntry\";\nimport { useSnackbarController, useAuthController, useTranslation } from \"@rebasepro/app\";\nimport { ConfirmationDialog } from \"@rebasepro/app\";\nimport { useState } from \"react\";\nimport { useHistory } from \"../../hooks/useHistory\";\n\n/**\n * Entity history tab view. Shows a paginated list of entity revisions\n * fetched from the backend API. Supports infinite scroll and revert.\n */\nexport function EntityHistoryView<M extends Record<string, unknown>>({\n entity,\n collection,\n formContext,\n refreshToken\n}: EntityCustomViewParams<M> & {\n /** Bumped once per save, so the list picks up the revision it just made. */\n refreshToken?: number;\n}) {\n\n const { t } = useTranslation();\n const snackbarController = useSnackbarController();\n const authController = useAuthController();\n const dirty = formContext?.formex.dirty;\n\n const slug = collection.slug;\n const entityId = entity?.id;\n\n const {\n entries,\n isLoading,\n hasMore,\n loadMore,\n revert\n } = useHistory({\n slug,\n entityId,\n enabled: !!entityId,\n pageSize: 10,\n refreshToken\n });\n\n const [revertHistoryId, setRevertHistoryId] = useState<string | undefined>();\n const [isReverting, setIsReverting] = useState(false);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const loadMoreRef = useRef<HTMLDivElement>(null);\n\n // Intersection observer for infinite scroll\n useEffect(() => {\n const currentContainer = containerRef.current;\n const currentLoadMore = loadMoreRef.current;\n\n if (!currentContainer || !currentLoadMore || !hasMore || isLoading) return;\n\n const observer = new IntersectionObserver(\n (observerEntries) => {\n if (observerEntries[0].isIntersecting && hasMore && !isLoading) {\n loadMore();\n }\n },\n {\n root: currentContainer,\n rootMargin: \"0px 0px 200px 0px\",\n threshold: 0.01\n }\n );\n\n observer.observe(currentLoadMore);\n\n return () => observer.disconnect();\n }, [hasMore, isLoading, entries.length, loadMore]);\n\n if (!entity) {\n return <div className=\"flex items-center justify-center h-full\">\n <Label>{t(\"history_new_entity\") ?? \"History is only available for existing records\"}</Label>\n </div>;\n }\n\n async function doRevert(historyId: string) {\n setIsReverting(true);\n try {\n const revertedValues = await revert(historyId);\n setRevertHistoryId(undefined);\n\n // Reset the form with the reverted values so the UI updates\n // immediately without requiring a page refresh.\n if (formContext?.formex?.resetForm && revertedValues) {\n formContext.formex.resetForm({\n values: revertedValues as M,\n submitCount: 0,\n touched: {}\n });\n }\n\n snackbarController.open({\n message: t(\"history_reverted\") ?? \"Reverted to selected version\",\n type: \"info\"\n });\n } catch (error) {\n console.error(\"Error reverting entity:\", error);\n snackbarController.open({\n message: t(\"history_revert_error\") ?? \"Error reverting entity\",\n type: \"error\"\n });\n } finally {\n setIsReverting(false);\n }\n }\n\n const revertEntry = revertHistoryId\n ? entries.find(e => e.id === revertHistoryId)\n : undefined;\n\n // `p-8` plus a `mt-24` heading were sized for a full-width tab that no\n // longer exists. In the inspector panel that was 96px of nothing above the\n // first revision, and 32px of gutter on each side of a 448px column.\n return <div\n ref={containerRef}\n className={cls(\"relative flex-1 h-full overflow-auto w-full flex flex-col gap-4 p-4 sm:p-5\")}>\n <div className=\"flex flex-col gap-2 max-w-6xl mx-auto w-full\">\n\n {isLoading && entries.length === 0 && (\n <div className=\"flex flex-col gap-4\">\n {[1, 2, 3].map(i => (\n <div key={i} className=\"flex flex-col gap-2 animate-pulse\">\n <div className=\"h-4 w-48 bg-surface-raised rounded\"/>\n <div className=\"h-12 w-full bg-surface-raised rounded-lg border border-hairline-strong\"/>\n </div>\n ))}\n </div>\n )}\n\n {!isLoading && entries.length === 0 && <>\n <Label>\n {t(\"history_empty\") ?? \"No history available\"}\n </Label>\n <Typography variant={\"caption\"}>\n {t(\"history_empty_description\") ?? \"When you save a record, a new version is created and stored in the history.\"}\n </Typography>\n </>}\n\n {entries.map((entry) => (\n <div key={entry.id} className=\"flex flex-col gap-2 w-full\">\n <EntityHistoryEntry\n entry={entry}\n collection={collection}\n size={\"medium\"}\n actions={\n <Tooltip title={t(\"history_revert\") ?? \"Revert to this version\"}\n className={\"m-2 grow-0 self-start\"}>\n <IconButton aria-label={t(\"history_revert\") ?? \"Revert to this version\"}\n onClick={() => {\n if (dirty) {\n snackbarController.open({\n message: t(\"history_revert_dirty\") ?? \"Please save or discard your changes before reverting\",\n type: \"warning\"\n });\n } else {\n setRevertHistoryId(entry.id);\n }\n }}>\n <HistoryIcon/>\n </IconButton>\n </Tooltip>\n }\n />\n </div>\n ))}\n\n {/* Load more sentinel */}\n {entries.length > 0 && (\n <div ref={loadMoreRef} className=\"py-4 text-center\">\n {isLoading && <Label>{t(\"loading\")}</Label>}\n {!hasMore && entries.length > 10 && <Label>{t(\"history_no_more\") ?? \"No more history\"}</Label>}\n </div>\n )}\n </div>\n\n <ErrorBoundary>\n <ConfirmationDialog\n open={Boolean(revertHistoryId)}\n onAccept={() => {\n if (revertHistoryId) doRevert(revertHistoryId);\n }}\n onCancel={() => setRevertHistoryId(undefined)}\n title={<Typography variant={\"subtitle2\"}>{t(\"history_revert_title\") ?? \"Revert data to this version?\"}</Typography>}\n body={revertEntry\n ? <div className=\"p-4\">\n <Typography variant={\"caption\"} color={\"secondary\"}>\n This will save the entity with the values from{\" \"}\n {new Date(revertEntry.updated_at).toLocaleString()}.\n A new history entry will be created for the revert.\n </Typography>\n </div>\n : null\n }\n />\n </ErrorBoundary>\n </div>;\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,kBAAqD,EACjE,QACA,YACA,aACA,gBAID;CAEC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,qBAAqB,sBAAsB;CAC1B,kBAAkB;CACzC,MAAM,QAAQ,aAAa,OAAO;CAElC,MAAM,OAAO,WAAW;CACxB,MAAM,WAAW,QAAQ;CAEzB,MAAM,EACF,SACA,WACA,SACA,UACA,WACA,WAAW;EACX;EACA;EACA,SAA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,oBAAC,OAAD,EAAA,UAAQ,EAAE,iBAAiB,KAAK,kBAAyB,CAAA,CAC5F;;GAER;MAEL,oBAAC,eAAD,EAAA,UACI,oBAAC,oBAAD;GACI,MAAM,QAAQ,eAAe;GAC7B,gBAAgB;IACZ,IAAI,iBAAiB,SAAS,eAAe;GACjD;GACA,gBAAgB,mBAAmB,KAAA,CAAS;GAC5C,OAAO,oBAAC,YAAD;IAAY,SAAS;cAAc,EAAE,sBAAsB,KAAK;GAA2C,CAAA;GAClH,MAAM,cACA,oBAAC,OAAD;IAAK,WAAU;cACb,qBAAC,YAAD;KAAY,SAAS;KAAW,OAAO;eAAvC;MAAoD;MACD;MAC9C,IAAI,KAAK,YAAY,UAAU,CAAC,CAAC,eAAe;MAAE;KAE3C;;GACX,CAAA,IACH;EAET,CAAA,EACU,CAAA,CACd;;AACT"}
1
+ {"version":3,"file":"EntityHistoryView.js","names":[],"sources":["../../../src/components/history/EntityHistoryView.tsx"],"sourcesContent":["\nimport type { EntityCustomViewParams } from \"@rebasepro/cms-types\";\nimport { useRef, useEffect } from \"react\";\nimport { cls, IconButton, Label, Tooltip, Typography } from \"@rebasepro/ui\";\nimport { ErrorBoundary, HistoryIcon } from \"@rebasepro/ui\";\nimport { EntityHistoryEntry } from \"./EntityHistoryEntry\";\nimport { usePermissions, useSnackbarController, useTranslation } from \"@rebasepro/app\";\nimport { ConfirmationDialog } from \"@rebasepro/app\";\nimport { useState } from \"react\";\nimport { useHistory } from \"../../hooks/useHistory\";\n\n/**\n * Entity history tab view. Shows a paginated list of entity revisions\n * fetched from the backend API. Supports infinite scroll and revert.\n */\nexport function EntityHistoryView<M extends Record<string, unknown>>({\n entity,\n collection,\n formContext,\n refreshToken\n}: EntityCustomViewParams<M> & {\n /** Bumped once per save, so the list picks up the revision it just made. */\n refreshToken?: number;\n}) {\n\n const { t } = useTranslation();\n const snackbarController = useSnackbarController();\n const { canEdit } = usePermissions();\n const dirty = formContext?.formex.dirty;\n\n const slug = collection.slug;\n const entityId = entity?.id;\n\n const {\n entries,\n isLoading,\n hasMore,\n loadMore,\n revert\n } = useHistory({\n slug,\n entityId,\n enabled: !!entityId,\n pageSize: 10,\n refreshToken\n });\n\n const [revertHistoryId, setRevertHistoryId] = useState<string | undefined>();\n const [isReverting, setIsReverting] = useState(false);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const loadMoreRef = useRef<HTMLDivElement>(null);\n\n // Intersection observer for infinite scroll\n useEffect(() => {\n const currentContainer = containerRef.current;\n const currentLoadMore = loadMoreRef.current;\n\n if (!currentContainer || !currentLoadMore || !hasMore || isLoading) return;\n\n const observer = new IntersectionObserver(\n (observerEntries) => {\n if (observerEntries[0].isIntersecting && hasMore && !isLoading) {\n loadMore();\n }\n },\n {\n root: currentContainer,\n rootMargin: \"0px 0px 200px 0px\",\n threshold: 0.01\n }\n );\n\n observer.observe(currentLoadMore);\n\n return () => observer.disconnect();\n }, [hasMore, isLoading, entries.length, loadMore]);\n\n if (!entity) {\n return <div className=\"flex items-center justify-center h-full\">\n <Label>{t(\"history_new_entity\") ?? \"History is only available for existing records\"}</Label>\n </div>;\n }\n\n // A revert writes the record: offered only to someone who may edit it,\n // which no one may while access is simulated.\n const editable = canEdit(collection, entity.path ?? slug, entity);\n\n async function doRevert(historyId: string) {\n setIsReverting(true);\n try {\n const revertedValues = await revert(historyId);\n setRevertHistoryId(undefined);\n\n // Reset the form with the reverted values so the UI updates\n // immediately without requiring a page refresh.\n if (formContext?.formex?.resetForm && revertedValues) {\n formContext.formex.resetForm({\n values: revertedValues as M,\n submitCount: 0,\n touched: {}\n });\n }\n\n snackbarController.open({\n message: t(\"history_reverted\") ?? \"Reverted to selected version\",\n type: \"info\"\n });\n } catch (error) {\n console.error(\"Error reverting entity:\", error);\n const reason = error instanceof Error ? error.message : undefined;\n snackbarController.open({\n message: [t(\"history_revert_error\") ?? \"Error reverting entity\", reason].filter(Boolean).join(\": \"),\n type: \"error\"\n });\n } finally {\n setIsReverting(false);\n }\n }\n\n const revertEntry = revertHistoryId\n ? entries.find(e => e.id === revertHistoryId)\n : undefined;\n\n // `p-8` plus a `mt-24` heading were sized for a full-width tab that no\n // longer exists. In the inspector panel that was 96px of nothing above the\n // first revision, and 32px of gutter on each side of a 448px column.\n return <div\n ref={containerRef}\n className={cls(\"relative flex-1 h-full overflow-auto w-full flex flex-col gap-4 p-4 sm:p-5\")}>\n <div className=\"flex flex-col gap-2 max-w-6xl mx-auto w-full\">\n\n {isLoading && entries.length === 0 && (\n <div className=\"flex flex-col gap-4\">\n {[1, 2, 3].map(i => (\n <div key={i} className=\"flex flex-col gap-2 animate-pulse\">\n <div className=\"h-4 w-48 bg-surface-raised rounded\"/>\n <div className=\"h-12 w-full bg-surface-raised rounded-lg border border-hairline-strong\"/>\n </div>\n ))}\n </div>\n )}\n\n {!isLoading && entries.length === 0 && <>\n <Label>\n {t(\"history_empty\") ?? \"No history available\"}\n </Label>\n <Typography variant={\"caption\"}>\n {t(\"history_empty_description\") ?? \"When you save a record, a new version is created and stored in the history.\"}\n </Typography>\n </>}\n\n {entries.map((entry) => (\n <div key={entry.id} className=\"flex flex-col gap-2 w-full\">\n <EntityHistoryEntry\n entry={entry}\n collection={collection}\n size={\"medium\"}\n actions={editable &&\n <Tooltip title={t(\"history_revert\") ?? \"Revert to this version\"}\n className={\"m-2 grow-0 self-start\"}>\n <IconButton aria-label={t(\"history_revert\") ?? \"Revert to this version\"}\n onClick={() => {\n if (dirty) {\n snackbarController.open({\n message: t(\"history_revert_dirty\") ?? \"Please save or discard your changes before reverting\",\n type: \"warning\"\n });\n } else {\n setRevertHistoryId(entry.id);\n }\n }}>\n <HistoryIcon/>\n </IconButton>\n </Tooltip>\n }\n />\n </div>\n ))}\n\n {/* Load more sentinel */}\n {entries.length > 0 && (\n <div ref={loadMoreRef} className=\"py-4 text-center\">\n {isLoading && <Label>{t(\"loading\")}</Label>}\n {!hasMore && entries.length > 10 && <Label>{t(\"history_no_more\") ?? \"No more history\"}</Label>}\n </div>\n )}\n </div>\n\n <ErrorBoundary>\n <ConfirmationDialog\n open={Boolean(revertHistoryId)}\n onAccept={() => {\n if (revertHistoryId) doRevert(revertHistoryId);\n }}\n onCancel={() => setRevertHistoryId(undefined)}\n title={<Typography variant={\"subtitle2\"}>{t(\"history_revert_title\") ?? \"Revert data to this version?\"}</Typography>}\n body={revertEntry\n ? <div className=\"p-4\">\n <Typography variant={\"caption\"} color={\"secondary\"}>\n This will save the entity with the values from{\" \"}\n {new Date(revertEntry.updated_at).toLocaleString()}.\n A new history entry will be created for the revert.\n </Typography>\n </div>\n : null\n }\n />\n </ErrorBoundary>\n </div>;\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,kBAAqD,EACjE,QACA,YACA,aACA,gBAID;CAEC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,qBAAqB,sBAAsB;CACjD,MAAM,EAAE,YAAY,eAAe;CACnC,MAAM,QAAQ,aAAa,OAAO;CAElC,MAAM,OAAO,WAAW;CACxB,MAAM,WAAW,QAAQ;CAEzB,MAAM,EACF,SACA,WACA,SACA,UACA,WACA,WAAW;EACX;EACA;EACA,SAAS,CAAC,CAAC;EACX,UAAU;EACV;CACJ,CAAC;CAED,MAAM,CAAC,iBAAiB,sBAAsB,SAA6B;CAC3E,MAAM,CAAC,aAAa,kBAAkB,SAAS,KAAK;CAEpD,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAuB,IAAI;CAG/C,gBAAgB;EACZ,MAAM,mBAAmB,aAAa;EACtC,MAAM,kBAAkB,YAAY;EAEpC,IAAI,CAAC,oBAAoB,CAAC,mBAAmB,CAAC,WAAW,WAAW;EAEpE,MAAM,WAAW,IAAI,sBAChB,oBAAoB;GACjB,IAAI,gBAAgB,EAAE,CAAC,kBAAkB,WAAW,CAAC,WACjD,SAAS;EAEjB,GACA;GACI,MAAM;GACN,YAAY;GACZ,WAAW;EACf,CACJ;EAEA,SAAS,QAAQ,eAAe;EAEhC,aAAa,SAAS,WAAW;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U;cACb,qBAAC,YAAD;KAAY,SAAS;KAAW,OAAO;eAAvC;MAAoD;MACD;MAC9C,IAAI,KAAK,YAAY,UAAU,CAAC,CAAC,eAAe;MAAE;KAE3C;;GACX,CAAA,IACH;EAET,CAAA,EACU,CAAA,CACd;;AACT"}
@@ -2,7 +2,8 @@ import React from "react";
2
2
  import type { AdminCollection } from "@rebasepro/cms-types";
3
3
  /**
4
4
  * Fetches the latest history entry from the backend API and displays
5
- * who last edited the entity and when.
5
+ * who last edited the entity and when — as the simulated identity while access
6
+ * is simulated, like the History tab.
6
7
  */
7
8
  export declare function LastEditedByIndicator({ path, entityId, collection }: {
8
9
  path: string;
@@ -1,4 +1,5 @@
1
1
  import { Entity, Properties } from "@rebasepro/types";
2
+ import { escapeCsvFormula, unescapeCsvFormula } from "@rebasepro/utils";
2
3
  interface Header {
3
4
  key: string;
4
5
  label: string;
@@ -52,19 +53,7 @@ export interface CsvExportWriter {
52
53
  finish(): BlobPart[];
53
54
  }
54
55
  export declare function createCsvExportWriter({ properties, propertiesOrder, additionalHeaders, flattenArrays, dateExportType }: CsvExportWriterParams): CsvExportWriter;
55
- /**
56
- * Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a
57
- * single quote — the standard OWASP mitigation. The apostrophe is consumed by
58
- * the spreadsheet as "treat the rest as text", so the value reads back intact.
59
- */
60
- export declare function escapeCsvFormula(value: string): string;
61
- /**
62
- * The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that
63
- * is an apostrophe followed by a formula trigger loses the apostrophe, as it
64
- * does when a spreadsheet reads it. Any other apostrophe is text.
65
- */
66
- export declare function unescapeCsvFormula(value: string): string;
56
+ export { escapeCsvFormula, unescapeCsvFormula };
67
57
  export declare function entryToCSVRow(entry: unknown[]): string;
68
58
  export declare function downloadBlob(content: BlobPart[], filename: string, contentType: string): void;
69
59
  export declare function downloadDataAsCsv(data: object[], name: string): void;
70
- export {};
@@ -1,5 +1,5 @@
1
1
  import { EntityRelation } from "@rebasepro/types";
2
- import { getArrayValuesCount, getValueInPath } from "@rebasepro/utils";
2
+ import { escapeCsvFormula, getArrayValuesCount, getValueInPath, unescapeCsvFormula } from "@rebasepro/utils";
3
3
  //#region src/data_export/export/export.ts
4
4
  function downloadEntitiesExport({ data, additionalData, properties, propertiesOrder, name, flattenArrays, additionalHeaders, exportType, dateExportType }) {
5
5
  console.debug("Downloading export", {
@@ -336,41 +336,6 @@ function processValuesForExport(inputValues, properties, exportType, dateExportT
336
336
  }
337
337
  return result;
338
338
  }
339
- /**
340
- * Characters that make a spreadsheet read a cell as a formula rather than text.
341
- *
342
- * Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and
343
- * Sheets strip the CSV quoting at parse time and then evaluate a cell whose
344
- * first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring
345
- * cells on click, `=cmd|'…'!A0` is worse.
346
- */
347
- var FORMULA_TRIGGERS = [
348
- "=",
349
- "+",
350
- "-",
351
- "@",
352
- " ",
353
- "\r"
354
- ];
355
- /**
356
- * Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a
357
- * single quote — the standard OWASP mitigation. The apostrophe is consumed by
358
- * the spreadsheet as "treat the rest as text", so the value reads back intact.
359
- */
360
- function escapeCsvFormula(value) {
361
- const first = value.charAt(0);
362
- if (!FORMULA_TRIGGERS.includes(first)) return value;
363
- if ((first === "-" || first === "+") && value.trim() !== "" && Number.isFinite(Number(value))) return value;
364
- return "'" + value;
365
- }
366
- /**
367
- * The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that
368
- * is an apostrophe followed by a formula trigger loses the apostrophe, as it
369
- * does when a spreadsheet reads it. Any other apostrophe is text.
370
- */
371
- function unescapeCsvFormula(value) {
372
- return value.charAt(0) === "'" && FORMULA_TRIGGERS.includes(value.charAt(1)) ? value.slice(1) : value;
373
- }
374
339
  function toCSVCell(v) {
375
340
  if (v === null || v === void 0) return "";
376
341
  return "\"" + escapeCsvFormula(Array.isArray(v) || typeof v === "object" && !(v instanceof Date) ? JSON.stringify(v) : String(v)).replaceAll("\"", "\"\"") + "\"";
@@ -1 +1 @@
1
- {"version":3,"file":"export.js","names":[],"sources":["../../../src/data_export/export/export.ts"],"sourcesContent":["import { Entity, EntityReference, EntityRelation, Properties, Property } from \"@rebasepro/types\";\nimport { type ArrayValuesCount, getArrayValuesCount, getValueInPath } from \"@rebasepro/utils\";\n\ninterface Header {\n key: string;\n label: string;\n}\n\nexport interface DownloadEntitiesExportParams<M extends Record<string, unknown>> {\n data: Entity<M>[];\n additionalData: Record<string, unknown>[] | undefined;\n properties: Properties;\n propertiesOrder: string[] | undefined;\n name: string;\n flattenArrays: boolean;\n additionalHeaders: string[] | undefined;\n exportType: \"csv\" | \"json\";\n dateExportType: \"timestamp\" | \"string\";\n}\n\nexport function downloadEntitiesExport<M extends Record<string, unknown>>({\n data,\n additionalData,\n properties,\n propertiesOrder,\n name,\n flattenArrays,\n additionalHeaders,\n exportType,\n dateExportType\n}: DownloadEntitiesExportParams<M>\n) {\n\n console.debug(\"Downloading export\", {\n dataLength: data.length,\n properties,\n exportType,\n dateExportType\n });\n\n if (exportType === \"csv\") {\n const writer = createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n });\n writer.addPage(data, additionalData);\n downloadBlob(writer.finish(), `${name}.csv`, \"text/csv\");\n } else {\n const exportableData = getEntityJsonExportableData(data, additionalData, properties, dateExportType);\n const json = JSON.stringify(exportableData, null, 2);\n downloadBlob([json], `${name}.json`, \"application/json\");\n }\n}\n\nexport function getEntityCSVExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n headers: Header[],\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"csv\", dateExportType)\n .map((entry) => headers.map((header) => getValueInPath(entry, header.key)));\n}\n\nexport function getEntityJsonExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"json\", dateExportType);\n}\n\n/**\n * Each entity as the record its export row is read from: `id`, the processed\n * values, then `additionalData[i]` over them. An `additionalData` longer than\n * `data` adds rows of its own.\n */\nfunction mergeExportRows(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): Record<string, unknown>[] {\n\n const mergedData: Record<string, unknown>[] = data.map(e => ({\n id: e.id,\n ...processValuesForExport(e.values, properties, exportType, dateExportType)\n }));\n\n if (additionalData) {\n additionalData.forEach((additional, index) => {\n mergedData[index] = { ...mergedData[index],\n...additional };\n });\n }\n\n return mergedData;\n}\n\n/**\n * The columns of an export, in groups: the `id`, then one group per property\n * in `propertiesOrder`, then one per additional header. A property's group is\n * the one that becomes a column per array item (`tags[0]`, `tags[1]`, …) when\n * arrays are flattened and some row holds more than one.\n */\ninterface ExportHeaderGroup {\n /** The property's key, for a property's group. */\n key?: string;\n property?: Property;\n /** The group's columns while its array is not expanded. */\n headers: Header[];\n}\n\nfunction getExportHeaderGroups(properties: Properties,\n propertiesOrder: string[] | undefined,\n additionalHeaders: string[] | undefined): ExportHeaderGroup[] {\n\n const groups: ExportHeaderGroup[] = [{ headers: [{ label: \"id\", key: \"id\" }] }];\n for (const childKey of propertiesOrder ?? Object.keys(properties)) {\n // The first column already is the id. A collection that declares its\n // key as a property named `id` wrote it twice, and the import refuses\n // a file with a duplicate header.\n if (childKey === \"id\") continue;\n const property = properties[childKey];\n if (!property) {\n console.warn(\"Property not found\", childKey, properties);\n continue;\n }\n groups.push({ key: childKey, property: property as Property, headers: getHeaders(property as Property, childKey, \"\") });\n }\n if (additionalHeaders) {\n groups.push(...additionalHeaders.map(h => ({ headers: [{ label: h, key: h }] })));\n }\n return groups;\n}\n\n/** How many columns per item the group's array spreads into, or 0 when it does not. */\nfunction expandedItemCount(group: ExportHeaderGroup, arrayValuesCount: ArrayValuesCount): number {\n if (group.key === undefined) return 0;\n const count = arrayValuesCount[group.key];\n return count > 1 ? count : 0;\n}\n\n/** The group's columns for array item `index`. */\nfunction itemHeaders(group: ExportHeaderGroup, index: number): Header[] {\n return getHeaders(group.property as Property, `${group.key}[${index}]`, \"\");\n}\n\nfunction headersOf(groups: ExportHeaderGroup[], arrayValuesCount: ArrayValuesCount): Header[] {\n return groups.flatMap((group) => {\n const count = expandedItemCount(group, arrayValuesCount);\n return count > 0\n ? Array.from({ length: count }, (_, i) => itemHeaders(group, i)).flat()\n : group.headers;\n });\n}\n\nfunction rowCells(entry: Record<string, unknown>, headers: Header[]): string[] {\n return headers.map((header) => toCSVCell(getValueInPath(entry, header.key)));\n}\n\nexport interface CsvExportWriterParams {\n properties: Properties;\n propertiesOrder: string[] | undefined;\n additionalHeaders: string[] | undefined;\n flattenArrays: boolean;\n dateExportType: \"timestamp\" | \"string\";\n}\n\n/**\n * Writes a CSV export one page of entities at a time.\n *\n * An export used to hold every entity it read, then a copy of every row, then\n * an array of cells per row, then the row strings — about 211 MB at its peak\n * for 100,000 rows × 20 columns, for a 32 MB file. Each page is now turned\n * into its CSV text as it arrives and its entities are let go; what is held\n * is the text itself.\n *\n * The file is the one the in-memory export wrote, byte for byte. What makes\n * that work across pages is `flattenArrays`: the columns an array spreads into\n * (`tags[0]` … `tags[n-1]`) depend on the longest array in *any* row, which\n * an early page cannot know. So a page is written with the columns known when\n * it arrives, and a row also keeps the cells of any array items those columns\n * leave out. At the end, a page written with fewer columns than the file has\n * is re-cut: its cells copied, and an array's swapped for, or extended with,\n * the kept item cells (or empty ones). Usually the longest array is met in the\n * first page and nothing is re-cut. A property key with `.` or `[` in it\n * resolves through other properties when spread, so an export with one keeps\n * its rows' records and writes them at the end, as before.\n */\nexport interface CsvExportWriter {\n /** One page of entities, with their additional-column values index for index. */\n addPage(data: Entity<Record<string, unknown>>[], additionalData?: Record<string, unknown>[]): void;\n /** The whole file, header row first. Once: the pages are handed over. */\n finish(): BlobPart[];\n}\n\n/**\n * A row's cells for the items of one array that its page's columns leave out,\n * kept in case the file has columns for them. The cells of items `0…n-1` in\n * one string, for an array its page did not spread; otherwise one string per\n * item, a hole where an item is not kept or its cells are all empty.\n */\ntype RowItemCells = string | (string | undefined)[];\n\ninterface CsvExportPage {\n /** The rows, `\\r\\n` after each. */\n text: string;\n rows: number;\n /** Per group, the items its array was spread into on this page; 0 when not spread. */\n spread: number[];\n /** By `row * groups + group`, for the rows that hold items `spread` leaves out. */\n items?: (RowItemCells | undefined)[];\n /** The rows' records, when the export cannot be re-cut (see the writer). */\n entries?: Record<string, unknown>[];\n}\n\nexport function createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n}: CsvExportWriterParams): CsvExportWriter {\n\n const groups = getExportHeaderGroups(properties, propertiesOrder, additionalHeaders);\n // The columns of item `i` of each group, built once per item, not per row.\n const itemHeaderCache: Header[][][] = groups.map(() => []);\n const headersOfItem = (groupIndex: number, index: number): Header[] =>\n itemHeaderCache[groupIndex][index] ??= itemHeaders(groups[groupIndex], index);\n // Cells per item; a group with none (a map with no properties) spreads\n // into no columns at all.\n const itemWidths = groups.map((group, groupIndex) => group.key === undefined ? 0 : headersOfItem(groupIndex, 0).length);\n const arrayValuesCount: ArrayValuesCount = {};\n // A key the spread column's path would read through some other property.\n const keepEntries = flattenArrays && groups.some((group) => group.key !== undefined && /[.[\\]]/.test(group.key));\n const pages: CsvExportPage[] = [];\n\n return {\n addPage(data, additionalData) {\n if (flattenArrays) {\n // Merged by maximum, which is what one pass over every row\n // computes.\n for (const [key, count] of Object.entries(getArrayValuesCount(data.map(d => d.values)))) {\n arrayValuesCount[key] = Math.max(arrayValuesCount[key] || 0, count);\n }\n }\n const spread = groups.map((group) => expandedItemCount(group, arrayValuesCount));\n const entries = mergeExportRows(data, additionalData, properties, \"csv\", dateExportType);\n if (keepEntries) {\n pages.push({ text: \"\", rows: entries.length, spread, entries });\n return;\n }\n const headers = headersOf(groups, arrayValuesCount);\n const lines: string[] = [];\n let items: CsvExportPage[\"items\"];\n entries.forEach((entry, row) => {\n lines.push(rowCells(entry, headers).join(\",\") + \"\\r\\n\");\n if (!flattenArrays) return;\n const bracketed = bracketedKeyIndices(entry);\n groups.forEach((group, groupIndex) => {\n if (group.key === undefined || itemWidths[groupIndex] === 0) return;\n const written = spread[groupIndex];\n const indices = itemIndicesWithValues(entry, group.key, bracketed)\n .filter((index) => index >= written);\n if (indices.length === 0) return;\n const value = entry[group.key];\n let cells: RowItemCells;\n if (written === 0 && Array.isArray(value) && indices.length === value.length) {\n cells = value.map((_, index) => rowCells(entry, headersOfItem(groupIndex, index)).join(\",\")).join(\",\");\n } else {\n cells = [];\n for (const index of indices) {\n cells[index] = rowCells(entry, headersOfItem(groupIndex, index)).join(\",\");\n }\n }\n (items ??= [])[row * groups.length + groupIndex] = cells;\n });\n });\n pages.push({ text: lines.join(\"\"), rows: entries.length, spread, items });\n },\n\n finish() {\n const counts = flattenArrays ? arrayValuesCount : {};\n const headers = headersOf(groups, counts);\n const parts: BlobPart[] = [entryToCSVRow(headers.map(h => h.label))];\n const spread = groups.map((group) => expandedItemCount(group, counts));\n\n // Handed over a page at a time, so a re-cut page and the text it\n // was cut from are not both held for the whole file.\n for (let page = pages.shift(); page; page = pages.shift()) {\n if (page.entries) {\n parts.push(page.entries.map((entry) => rowCells(entry, headers).join(\",\") + \"\\r\\n\").join(\"\"));\n } else if (page.spread.every((count, groupIndex) => count === spread[groupIndex])) {\n parts.push(page.text);\n } else {\n parts.push(recutPage(page, groups, spread, itemWidths));\n }\n }\n return parts;\n }\n };\n}\n\n/**\n * The record's own keys spelled `key[i]…`, by `key`: `getValueInPath` reads\n * one of those for the cell `key[i]` before anything else. Almost never there.\n */\nfunction bracketedKeyIndices(entry: Record<string, unknown>): Map<string, number[]> | undefined {\n let found: Map<string, number[]> | undefined;\n for (const own of Object.keys(entry)) {\n if (!own.includes(\"[\")) continue;\n const match = /^(.*?)\\[(\\d+)\\]/.exec(own);\n if (!match) continue;\n found ??= new Map();\n const indices = found.get(match[1]) ?? [];\n indices.push(Number(match[2]));\n found.set(match[1], indices);\n }\n return found;\n}\n\nconst NO_INDICES: number[] = [];\n\n/**\n * The array items of `entry[key]` whose spread cells may not all be empty —\n * every other item's are, as `getValueInPath` reads `key[i]` and\n * `key[i].child`: an array's own items, an object's own integer-named keys\n * (read as `key[i]` too), and a key of the record spelled `key[i]…` itself.\n * Over-including is harmless; the cells are computed, not assumed.\n */\nfunction itemIndicesWithValues(entry: Record<string, unknown>,\n key: string,\n bracketed: Map<string, number[]> | undefined): number[] {\n const value = entry[key];\n const extra = bracketed?.get(key);\n if (!extra) {\n // The common cases, without building a set per cell.\n if (Array.isArray(value)) return value.map((_, i) => i);\n if (value === null || typeof value !== \"object\") return NO_INDICES;\n }\n const indices = new Set<number>();\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) indices.add(i);\n } else if (value !== null && typeof value === \"object\") {\n for (const own of Object.getOwnPropertyNames(value)) {\n const match = /^(\\d+)(?:$|[.[])/.exec(own);\n if (match) indices.add(Number(match[1]));\n }\n }\n extra?.forEach((index) => indices.add(index));\n return [...indices];\n}\n\n/**\n * A page written with fewer columns than the file has, cut back into cells\n * and written again: each array the file spreads further than the page did\n * gets its kept item cells, or empty ones.\n */\nfunction recutPage(page: CsvExportPage, groups: ExportHeaderGroup[], spread: number[], itemWidths: number[]): string {\n const text = page.text;\n const out: string[] = [];\n let pos = 0;\n for (let row = 0; row < page.rows; row++) {\n const cells: string[] = [];\n let first = true;\n groups.forEach((group, groupIndex) => {\n const written = page.spread[groupIndex];\n const itemWidth = itemWidths[groupIndex];\n const width = written > 0 ? written * itemWidth : group.headers.length;\n const groupCells: string[] = [];\n for (let c = 0; c < width; c++) {\n if (!first) pos++; // the comma before every cell but the row's first\n first = false;\n const end = csvCellEnd(text, pos);\n groupCells.push(text.slice(pos, end));\n pos = end;\n }\n const count = spread[groupIndex];\n if (count === written) {\n cells.push(...groupCells);\n return;\n }\n // Spread further than the page was: the items it wrote stay.\n if (written > 0) cells.push(...groupCells);\n const items = page.items?.[row * groups.length + groupIndex];\n const dense = typeof items === \"string\" ? splitCsvCells(items) : undefined;\n for (let i = written; i < count; i++) {\n const itemCells = dense\n ? dense.slice(i * itemWidth, (i + 1) * itemWidth)\n : (typeof items === \"object\" && items[i] !== undefined ? splitCsvCells(items[i] as string) : []);\n for (let c = 0; c < itemWidth; c++) cells.push(itemCells[c] ?? \"\");\n }\n });\n pos += 2; // \"\\r\\n\"\n out.push(cells.join(\",\") + \"\\r\\n\");\n }\n return out.join(\"\");\n}\n\n/** The cells of a run of them joined with commas, as `toCSVCell` wrote them. */\nfunction splitCsvCells(text: string): string[] {\n const cells: string[] = [];\n let pos = 0;\n for (; ;) {\n const end = csvCellEnd(text, pos);\n cells.push(text.slice(pos, end));\n if (end >= text.length) return cells;\n pos = end + 1;\n }\n}\n\n/**\n * Where the cell starting at `start` ends. Every cell `toCSVCell` writes is\n * either empty or quoted with its own quotes doubled, so the next lone quote\n * closes it.\n */\nfunction csvCellEnd(text: string, start: number): number {\n if (text.charCodeAt(start) !== 34 /* \" */) return start;\n let i = start + 1;\n for (; ;) {\n const quote = text.indexOf(\"\\\"\", i);\n if (quote < 0) return text.length;\n if (text.charCodeAt(quote + 1) === 34) {\n i = quote + 2;\n } else {\n return quote + 1;\n }\n }\n}\n\n/**\n * Get headers for property. There could be more than one header per property\n * @param property\n * @param propertyKey\n * @param prefix\n */\nfunction getHeaders(property: Property, propertyKey: string, prefix = \"\"): Header[] {\n const currentKey = prefix ? `${prefix}.${propertyKey}` : propertyKey;\n if (property.type === \"map\" && property.properties) {\n return Object.entries(property.properties)\n .map(([childKey, p]) => getHeaders(p, childKey, currentKey))\n .flat();\n } else {\n return [{\n label: currentKey,\n key: currentKey\n }];\n }\n}\n\n/**\n * Read whatever a `date` column actually arrived as into a `Date`.\n *\n * The driver/WebSocket path revives `{ __type: \"date\" }` into a `Date`; the REST\n * path — which is the one the admin is on — leaves an ISO string, and an epoch\n * number is what a re-imported export carries. Returns `undefined` for anything\n * that is not a date, so the caller can pass the raw value through.\n */\nfunction toExportableDate(inputValue: unknown): Date | undefined {\n if (inputValue instanceof Date) return Number.isNaN(inputValue.getTime()) ? undefined : inputValue;\n if (typeof inputValue === \"number\" && Number.isFinite(inputValue)) return new Date(inputValue);\n if (typeof inputValue === \"string\" && inputValue.trim() !== \"\") {\n const parsed = new Date(inputValue);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n }\n return undefined;\n}\n\n/**\n * The id a relation value points at, for a relation property's value — an\n * `EntityRelation`, or the same thing still in its `{ __type: \"relation\" }`\n * wire form. `undefined` for anything else, so a bare foreign key passes\n * through as the id it already is.\n */\nfunction relationIdForExport(value: unknown): string | number | undefined {\n if (value instanceof EntityRelation) return value.id;\n if (typeof value === \"object\" && value !== null\n && \"__type\" in value && value.__type === \"relation\"\n && \"id\" in value && (typeof value.id === \"string\" || typeof value.id === \"number\")) {\n return value.id;\n }\n return undefined;\n}\n\nfunction processValueForExport(inputValue: unknown,\n property: Property,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): unknown {\n\n let value: unknown;\n if (property.type === \"relation\") {\n // A relation is exported as the id it points at — what the import\n // writes back — rather than the view-model object the admin holds,\n // which a CSV cell printed as `[object Object]`. To-many relations\n // are arrays of them.\n const toId = (item: unknown) => relationIdForExport(item) ?? item;\n value = Array.isArray(inputValue) ? inputValue.map(toId) : toId(inputValue);\n } else if (property.type === \"map\" && property.properties) {\n value = processValuesForExport(inputValue as Record<string, unknown>, property.properties as Properties, exportType, dateExportType);\n } else if (property.type === \"array\") {\n if (property.of && Array.isArray(inputValue)) {\n if (Array.isArray(property.of)) {\n value = property.of.map((p, i) => processValueForExport(inputValue[i], p, exportType, dateExportType));\n } else if (property.of.type === \"map\") {\n value = exportType === \"csv\"\n ? inputValue.map((e) => JSON.stringify(e))\n : inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n ;\n } else {\n value = inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n }\n } else {\n value = inputValue;\n }\n } else if (property.type === \"reference\" && inputValue && typeof inputValue === \"object\" && \"isEntityReference\" in inputValue && typeof (inputValue as EntityReference).isEntityReference === \"function\" && (inputValue as EntityReference).isEntityReference()) {\n const ref = inputValue ? inputValue as EntityReference : undefined;\n value = ref ? ref.fullPath : null;\n } else if (property.type === \"date\") {\n // Not `instanceof Date`: the admin reads over REST, and the REST row\n // pipeline hands dates back as the database wrote them — a string. That\n // made this branch dead on every live export, so both radio options\n // produced identical files. Normalise here, where the declared type says\n // the column is a date, and leave anything unparseable untouched rather\n // than exporting an invalid date as `null`.\n const date = toExportableDate(inputValue);\n value = date\n ? (dateExportType === \"timestamp\" ? date.getTime() : date.toISOString())\n : inputValue;\n } else {\n value = inputValue;\n }\n\n return value;\n}\n\nfunction processValuesForExport<M extends Record<string, unknown>>\n (inputValues: Record<string, unknown>,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n ): Record<string, unknown> {\n // One accumulator. Merging `{ [key]: value }` objects pairwise copied the\n // whole row once per property — the square of the property count, per row.\n const result: Record<string, unknown> = { ...inputValues };\n for (const [key, property] of Object.entries(properties)) {\n const inputValue = inputValues && (inputValues)[key];\n const updatedValue = processValueForExport(inputValue, property as Property, exportType, dateExportType);\n if (updatedValue === undefined) continue;\n if (key === \"__proto__\") {\n // An own property, as the object spread made it, not the prototype.\n Object.defineProperty(result, key, { value: updatedValue, enumerable: true, writable: true, configurable: true });\n } else {\n result[key] = updatedValue;\n }\n }\n return result;\n}\n\n/**\n * Characters that make a spreadsheet read a cell as a formula rather than text.\n *\n * Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and\n * Sheets strip the CSV quoting at parse time and then evaluate a cell whose\n * first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring\n * cells on click, `=cmd|'…'!A0` is worse.\n */\nconst FORMULA_TRIGGERS = [\"=\", \"+\", \"-\", \"@\", \"\\t\", \"\\r\"];\n\n/**\n * Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a\n * single quote — the standard OWASP mitigation. The apostrophe is consumed by\n * the spreadsheet as \"treat the rest as text\", so the value reads back intact.\n */\nexport function escapeCsvFormula(value: string): string {\n const first = value.charAt(0);\n if (!FORMULA_TRIGGERS.includes(first)) return value;\n // A signed number is not a formula, and prefixing it would turn every\n // negative amount in the file into text. `-1+1` is still neutralised,\n // because it is not a number.\n if ((first === \"-\" || first === \"+\") && value.trim() !== \"\" && Number.isFinite(Number(value))) return value;\n return \"'\" + value;\n}\n\n/**\n * The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that\n * is an apostrophe followed by a formula trigger loses the apostrophe, as it\n * does when a spreadsheet reads it. Any other apostrophe is text.\n */\nexport function unescapeCsvFormula(value: string): string {\n return value.charAt(0) === \"'\" && FORMULA_TRIGGERS.includes(value.charAt(1))\n ? value.slice(1)\n : value;\n}\n\nfunction toCSVCell(v: unknown): string {\n if (v === null || v === undefined) return \"\";\n // An array or object (a geopoint, a value no property declares) is written\n // as its JSON: `String()` of an object is `[object Object]`. Date\n // properties are normalised before they get here.\n const s = Array.isArray(v) || (typeof v === \"object\" && !(v instanceof Date))\n ? JSON.stringify(v)\n : String(v);\n return \"\\\"\" + escapeCsvFormula(s).replaceAll(\"\\\"\", \"\\\"\\\"\") + \"\\\"\";\n}\n\nexport function entryToCSVRow(entry: unknown[]) {\n return entry\n .map(toCSVCell)\n .join(\",\") + \"\\r\\n\";\n}\n\nexport function downloadBlob(content: BlobPart[], filename: string, contentType: string) {\n const blob = new Blob(content, { type: contentType });\n const url = URL.createObjectURL(blob);\n const pom = document.createElement(\"a\");\n pom.href = url;\n pom.setAttribute(\"download\", filename);\n pom.click();\n // Unrevoked, the URL kept the whole file in memory until the tab closed —\n // one more copy per export. The download holds its own reference once it\n // has started; the delay covers browsers that start it a moment after\n // `click()` returns.\n setTimeout(() => URL.revokeObjectURL(url), BLOB_URL_LIFETIME_MS);\n}\n\n/** How long an export's object URL outlives the click that downloads it. */\nconst BLOB_URL_LIFETIME_MS = 10_000;\n\nexport function downloadDataAsCsv(data: object[], name: string) {\n if (data.length === 0) return;\n\n const headers = Object.keys(data[0]);\n const csvContent = [\n headers.join(\",\"),\n ...data.map(row => headers.map(header => toCSVCell((row as Record<string, unknown>)[header])).join(\",\"))\n ].join(\"\\r\\n\");\n\n downloadBlob([csvContent], `${name}.csv`, \"text/csv\");\n}\n"],"mappings":";;;AAoBA,SAAgB,uBAA0D,EACtE,MACA,gBACA,YACA,iBACA,MACA,eACA,mBACA,YACA,kBAEF;CAEE,QAAQ,MAAM,sBAAsB;EAChC,YAAY,KAAK;EACjB;EACA;EACA;CACJ,CAAC;CAED,IAAI,eAAe,OAAO;EACtB,MAAM,SAAS,sBAAsB;GACjC;GACA;GACA;GACA;GACA;EACJ,CAAC;EACD,OAAO,QAAQ,MAAM,cAAc;EACnC,aAAa,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,UAAU;CAC3D,OAAO;EACH,MAAM,iBAAiB,4BAA4B,MAAM,gBAAgB,YAAY,cAAc;EAEnG,aAAa,CADA,KAAK,UAAU,gBAAgB,MAAM,CACpC,CAAI,GAAG,GAAG,KAAK,QAAQ,kBAAkB;CAC3D;AACJ;AAEA,SAAgB,2BAA2B,MACvC,gBACA,YACA,SACA,gBACF;CACE,OAAO,gBAAgB,MAAM,gBAAgB,YAAY,OAAO,cAAc,CAAC,CAC1E,KAAK,UAAU,QAAQ,KAAK,WAAW,eAAe,OAAO,OAAO,GAAG,CAAC,CAAC;AAClF;AAEA,SAAgB,4BAA4B,MACxC,gBACA,YACA,gBACF;CACE,OAAO,gBAAgB,MAAM,gBAAgB,YAAY,QAAQ,cAAc;AACnF;;;;;;AAOA,SAAS,gBAAgB,MACrB,gBACA,YACA,YACA,gBACyB;CAEzB,MAA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BAHJ,MAAM,QAAQ,CAAC,KAAM,OAAO,MAAM,YAAY,EAAE,aAAa,QACjE,KAAK,UAAU,CAAC,IAChB,OAAO,CAAC,CACkB,CAAC,CAAC,WAAW,MAAM,MAAM,IAAI;AACjE;AAEA,SAAgB,cAAc,OAAkB;CAC5C,OAAO,MACF,IAAI,SAAS,CAAC,CACd,KAAK,GAAG,IAAI;AACrB;AAEA,SAAgB,aAAa,SAAqB,UAAkB,aAAqB;CACrF,MAAM,OAAO,IAAI,KAAK,SAAS,EAAE,MAAM,YAAY,CAAC;CACpD,MAAM,MAAM,IAAI,gBAAgB,IAAI;CACpC,MAAM,MAAM,SAAS,cAAc,GAAG;CACtC,IAAI,OAAO;CACX,IAAI,aAAa,YAAY,QAAQ;CACrC,IAAI,MAAM;CAKV,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,oBAAoB;AACnE;;AAGA,IAAM,uBAAuB;AAE7B,SAAgB,kBAAkB,MAAgB,MAAc;CAC5D,IAAI,KAAK,WAAW,GAAG;CAEvB,MAAM,UAAU,OAAO,KAAK,KAAK,EAAE;CAMnC,aAAa,CALM,CACf,QAAQ,KAAK,GAAG,GAChB,GAAG,KAAK,KAAI,QAAO,QAAQ,KAAI,WAAU,UAAW,IAAgC,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAC3G,CAAC,CAAC,KAAK,MAEO,CAAU,GAAG,GAAG,KAAK,OAAO,UAAU;AACxD"}
1
+ {"version":3,"file":"export.js","names":[],"sources":["../../../src/data_export/export/export.ts"],"sourcesContent":["import { Entity, EntityReference, EntityRelation, Properties, Property } from \"@rebasepro/types\";\nimport { type ArrayValuesCount, escapeCsvFormula, getArrayValuesCount, getValueInPath, unescapeCsvFormula } from \"@rebasepro/utils\";\n\ninterface Header {\n key: string;\n label: string;\n}\n\nexport interface DownloadEntitiesExportParams<M extends Record<string, unknown>> {\n data: Entity<M>[];\n additionalData: Record<string, unknown>[] | undefined;\n properties: Properties;\n propertiesOrder: string[] | undefined;\n name: string;\n flattenArrays: boolean;\n additionalHeaders: string[] | undefined;\n exportType: \"csv\" | \"json\";\n dateExportType: \"timestamp\" | \"string\";\n}\n\nexport function downloadEntitiesExport<M extends Record<string, unknown>>({\n data,\n additionalData,\n properties,\n propertiesOrder,\n name,\n flattenArrays,\n additionalHeaders,\n exportType,\n dateExportType\n}: DownloadEntitiesExportParams<M>\n) {\n\n console.debug(\"Downloading export\", {\n dataLength: data.length,\n properties,\n exportType,\n dateExportType\n });\n\n if (exportType === \"csv\") {\n const writer = createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n });\n writer.addPage(data, additionalData);\n downloadBlob(writer.finish(), `${name}.csv`, \"text/csv\");\n } else {\n const exportableData = getEntityJsonExportableData(data, additionalData, properties, dateExportType);\n const json = JSON.stringify(exportableData, null, 2);\n downloadBlob([json], `${name}.json`, \"application/json\");\n }\n}\n\nexport function getEntityCSVExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n headers: Header[],\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"csv\", dateExportType)\n .map((entry) => headers.map((header) => getValueInPath(entry, header.key)));\n}\n\nexport function getEntityJsonExportableData(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n dateExportType: \"timestamp\" | \"string\"\n) {\n return mergeExportRows(data, additionalData, properties, \"json\", dateExportType);\n}\n\n/**\n * Each entity as the record its export row is read from: `id`, the processed\n * values, then `additionalData[i]` over them. An `additionalData` longer than\n * `data` adds rows of its own.\n */\nfunction mergeExportRows(data: Entity<Record<string, unknown>>[],\n additionalData: Record<string, unknown>[] | undefined,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): Record<string, unknown>[] {\n\n const mergedData: Record<string, unknown>[] = data.map(e => ({\n id: e.id,\n ...processValuesForExport(e.values, properties, exportType, dateExportType)\n }));\n\n if (additionalData) {\n additionalData.forEach((additional, index) => {\n mergedData[index] = { ...mergedData[index],\n...additional };\n });\n }\n\n return mergedData;\n}\n\n/**\n * The columns of an export, in groups: the `id`, then one group per property\n * in `propertiesOrder`, then one per additional header. A property's group is\n * the one that becomes a column per array item (`tags[0]`, `tags[1]`, …) when\n * arrays are flattened and some row holds more than one.\n */\ninterface ExportHeaderGroup {\n /** The property's key, for a property's group. */\n key?: string;\n property?: Property;\n /** The group's columns while its array is not expanded. */\n headers: Header[];\n}\n\nfunction getExportHeaderGroups(properties: Properties,\n propertiesOrder: string[] | undefined,\n additionalHeaders: string[] | undefined): ExportHeaderGroup[] {\n\n const groups: ExportHeaderGroup[] = [{ headers: [{ label: \"id\", key: \"id\" }] }];\n for (const childKey of propertiesOrder ?? Object.keys(properties)) {\n // The first column already is the id. A collection that declares its\n // key as a property named `id` wrote it twice, and the import refuses\n // a file with a duplicate header.\n if (childKey === \"id\") continue;\n const property = properties[childKey];\n if (!property) {\n console.warn(\"Property not found\", childKey, properties);\n continue;\n }\n groups.push({ key: childKey, property: property as Property, headers: getHeaders(property as Property, childKey, \"\") });\n }\n if (additionalHeaders) {\n groups.push(...additionalHeaders.map(h => ({ headers: [{ label: h, key: h }] })));\n }\n return groups;\n}\n\n/** How many columns per item the group's array spreads into, or 0 when it does not. */\nfunction expandedItemCount(group: ExportHeaderGroup, arrayValuesCount: ArrayValuesCount): number {\n if (group.key === undefined) return 0;\n const count = arrayValuesCount[group.key];\n return count > 1 ? count : 0;\n}\n\n/** The group's columns for array item `index`. */\nfunction itemHeaders(group: ExportHeaderGroup, index: number): Header[] {\n return getHeaders(group.property as Property, `${group.key}[${index}]`, \"\");\n}\n\nfunction headersOf(groups: ExportHeaderGroup[], arrayValuesCount: ArrayValuesCount): Header[] {\n return groups.flatMap((group) => {\n const count = expandedItemCount(group, arrayValuesCount);\n return count > 0\n ? Array.from({ length: count }, (_, i) => itemHeaders(group, i)).flat()\n : group.headers;\n });\n}\n\nfunction rowCells(entry: Record<string, unknown>, headers: Header[]): string[] {\n return headers.map((header) => toCSVCell(getValueInPath(entry, header.key)));\n}\n\nexport interface CsvExportWriterParams {\n properties: Properties;\n propertiesOrder: string[] | undefined;\n additionalHeaders: string[] | undefined;\n flattenArrays: boolean;\n dateExportType: \"timestamp\" | \"string\";\n}\n\n/**\n * Writes a CSV export one page of entities at a time.\n *\n * An export used to hold every entity it read, then a copy of every row, then\n * an array of cells per row, then the row strings — about 211 MB at its peak\n * for 100,000 rows × 20 columns, for a 32 MB file. Each page is now turned\n * into its CSV text as it arrives and its entities are let go; what is held\n * is the text itself.\n *\n * The file is the one the in-memory export wrote, byte for byte. What makes\n * that work across pages is `flattenArrays`: the columns an array spreads into\n * (`tags[0]` … `tags[n-1]`) depend on the longest array in *any* row, which\n * an early page cannot know. So a page is written with the columns known when\n * it arrives, and a row also keeps the cells of any array items those columns\n * leave out. At the end, a page written with fewer columns than the file has\n * is re-cut: its cells copied, and an array's swapped for, or extended with,\n * the kept item cells (or empty ones). Usually the longest array is met in the\n * first page and nothing is re-cut. A property key with `.` or `[` in it\n * resolves through other properties when spread, so an export with one keeps\n * its rows' records and writes them at the end, as before.\n */\nexport interface CsvExportWriter {\n /** One page of entities, with their additional-column values index for index. */\n addPage(data: Entity<Record<string, unknown>>[], additionalData?: Record<string, unknown>[]): void;\n /** The whole file, header row first. Once: the pages are handed over. */\n finish(): BlobPart[];\n}\n\n/**\n * A row's cells for the items of one array that its page's columns leave out,\n * kept in case the file has columns for them. The cells of items `0…n-1` in\n * one string, for an array its page did not spread; otherwise one string per\n * item, a hole where an item is not kept or its cells are all empty.\n */\ntype RowItemCells = string | (string | undefined)[];\n\ninterface CsvExportPage {\n /** The rows, `\\r\\n` after each. */\n text: string;\n rows: number;\n /** Per group, the items its array was spread into on this page; 0 when not spread. */\n spread: number[];\n /** By `row * groups + group`, for the rows that hold items `spread` leaves out. */\n items?: (RowItemCells | undefined)[];\n /** The rows' records, when the export cannot be re-cut (see the writer). */\n entries?: Record<string, unknown>[];\n}\n\nexport function createCsvExportWriter({\n properties,\n propertiesOrder,\n additionalHeaders,\n flattenArrays,\n dateExportType\n}: CsvExportWriterParams): CsvExportWriter {\n\n const groups = getExportHeaderGroups(properties, propertiesOrder, additionalHeaders);\n // The columns of item `i` of each group, built once per item, not per row.\n const itemHeaderCache: Header[][][] = groups.map(() => []);\n const headersOfItem = (groupIndex: number, index: number): Header[] =>\n itemHeaderCache[groupIndex][index] ??= itemHeaders(groups[groupIndex], index);\n // Cells per item; a group with none (a map with no properties) spreads\n // into no columns at all.\n const itemWidths = groups.map((group, groupIndex) => group.key === undefined ? 0 : headersOfItem(groupIndex, 0).length);\n const arrayValuesCount: ArrayValuesCount = {};\n // A key the spread column's path would read through some other property.\n const keepEntries = flattenArrays && groups.some((group) => group.key !== undefined && /[.[\\]]/.test(group.key));\n const pages: CsvExportPage[] = [];\n\n return {\n addPage(data, additionalData) {\n if (flattenArrays) {\n // Merged by maximum, which is what one pass over every row\n // computes.\n for (const [key, count] of Object.entries(getArrayValuesCount(data.map(d => d.values)))) {\n arrayValuesCount[key] = Math.max(arrayValuesCount[key] || 0, count);\n }\n }\n const spread = groups.map((group) => expandedItemCount(group, arrayValuesCount));\n const entries = mergeExportRows(data, additionalData, properties, \"csv\", dateExportType);\n if (keepEntries) {\n pages.push({ text: \"\", rows: entries.length, spread, entries });\n return;\n }\n const headers = headersOf(groups, arrayValuesCount);\n const lines: string[] = [];\n let items: CsvExportPage[\"items\"];\n entries.forEach((entry, row) => {\n lines.push(rowCells(entry, headers).join(\",\") + \"\\r\\n\");\n if (!flattenArrays) return;\n const bracketed = bracketedKeyIndices(entry);\n groups.forEach((group, groupIndex) => {\n if (group.key === undefined || itemWidths[groupIndex] === 0) return;\n const written = spread[groupIndex];\n const indices = itemIndicesWithValues(entry, group.key, bracketed)\n .filter((index) => index >= written);\n if (indices.length === 0) return;\n const value = entry[group.key];\n let cells: RowItemCells;\n if (written === 0 && Array.isArray(value) && indices.length === value.length) {\n cells = value.map((_, index) => rowCells(entry, headersOfItem(groupIndex, index)).join(\",\")).join(\",\");\n } else {\n cells = [];\n for (const index of indices) {\n cells[index] = rowCells(entry, headersOfItem(groupIndex, index)).join(\",\");\n }\n }\n (items ??= [])[row * groups.length + groupIndex] = cells;\n });\n });\n pages.push({ text: lines.join(\"\"), rows: entries.length, spread, items });\n },\n\n finish() {\n const counts = flattenArrays ? arrayValuesCount : {};\n const headers = headersOf(groups, counts);\n const parts: BlobPart[] = [entryToCSVRow(headers.map(h => h.label))];\n const spread = groups.map((group) => expandedItemCount(group, counts));\n\n // Handed over a page at a time, so a re-cut page and the text it\n // was cut from are not both held for the whole file.\n for (let page = pages.shift(); page; page = pages.shift()) {\n if (page.entries) {\n parts.push(page.entries.map((entry) => rowCells(entry, headers).join(\",\") + \"\\r\\n\").join(\"\"));\n } else if (page.spread.every((count, groupIndex) => count === spread[groupIndex])) {\n parts.push(page.text);\n } else {\n parts.push(recutPage(page, groups, spread, itemWidths));\n }\n }\n return parts;\n }\n };\n}\n\n/**\n * The record's own keys spelled `key[i]…`, by `key`: `getValueInPath` reads\n * one of those for the cell `key[i]` before anything else. Almost never there.\n */\nfunction bracketedKeyIndices(entry: Record<string, unknown>): Map<string, number[]> | undefined {\n let found: Map<string, number[]> | undefined;\n for (const own of Object.keys(entry)) {\n if (!own.includes(\"[\")) continue;\n const match = /^(.*?)\\[(\\d+)\\]/.exec(own);\n if (!match) continue;\n found ??= new Map();\n const indices = found.get(match[1]) ?? [];\n indices.push(Number(match[2]));\n found.set(match[1], indices);\n }\n return found;\n}\n\nconst NO_INDICES: number[] = [];\n\n/**\n * The array items of `entry[key]` whose spread cells may not all be empty —\n * every other item's are, as `getValueInPath` reads `key[i]` and\n * `key[i].child`: an array's own items, an object's own integer-named keys\n * (read as `key[i]` too), and a key of the record spelled `key[i]…` itself.\n * Over-including is harmless; the cells are computed, not assumed.\n */\nfunction itemIndicesWithValues(entry: Record<string, unknown>,\n key: string,\n bracketed: Map<string, number[]> | undefined): number[] {\n const value = entry[key];\n const extra = bracketed?.get(key);\n if (!extra) {\n // The common cases, without building a set per cell.\n if (Array.isArray(value)) return value.map((_, i) => i);\n if (value === null || typeof value !== \"object\") return NO_INDICES;\n }\n const indices = new Set<number>();\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i++) indices.add(i);\n } else if (value !== null && typeof value === \"object\") {\n for (const own of Object.getOwnPropertyNames(value)) {\n const match = /^(\\d+)(?:$|[.[])/.exec(own);\n if (match) indices.add(Number(match[1]));\n }\n }\n extra?.forEach((index) => indices.add(index));\n return [...indices];\n}\n\n/**\n * A page written with fewer columns than the file has, cut back into cells\n * and written again: each array the file spreads further than the page did\n * gets its kept item cells, or empty ones.\n */\nfunction recutPage(page: CsvExportPage, groups: ExportHeaderGroup[], spread: number[], itemWidths: number[]): string {\n const text = page.text;\n const out: string[] = [];\n let pos = 0;\n for (let row = 0; row < page.rows; row++) {\n const cells: string[] = [];\n let first = true;\n groups.forEach((group, groupIndex) => {\n const written = page.spread[groupIndex];\n const itemWidth = itemWidths[groupIndex];\n const width = written > 0 ? written * itemWidth : group.headers.length;\n const groupCells: string[] = [];\n for (let c = 0; c < width; c++) {\n if (!first) pos++; // the comma before every cell but the row's first\n first = false;\n const end = csvCellEnd(text, pos);\n groupCells.push(text.slice(pos, end));\n pos = end;\n }\n const count = spread[groupIndex];\n if (count === written) {\n cells.push(...groupCells);\n return;\n }\n // Spread further than the page was: the items it wrote stay.\n if (written > 0) cells.push(...groupCells);\n const items = page.items?.[row * groups.length + groupIndex];\n const dense = typeof items === \"string\" ? splitCsvCells(items) : undefined;\n for (let i = written; i < count; i++) {\n const itemCells = dense\n ? dense.slice(i * itemWidth, (i + 1) * itemWidth)\n : (typeof items === \"object\" && items[i] !== undefined ? splitCsvCells(items[i] as string) : []);\n for (let c = 0; c < itemWidth; c++) cells.push(itemCells[c] ?? \"\");\n }\n });\n pos += 2; // \"\\r\\n\"\n out.push(cells.join(\",\") + \"\\r\\n\");\n }\n return out.join(\"\");\n}\n\n/** The cells of a run of them joined with commas, as `toCSVCell` wrote them. */\nfunction splitCsvCells(text: string): string[] {\n const cells: string[] = [];\n let pos = 0;\n for (; ;) {\n const end = csvCellEnd(text, pos);\n cells.push(text.slice(pos, end));\n if (end >= text.length) return cells;\n pos = end + 1;\n }\n}\n\n/**\n * Where the cell starting at `start` ends. Every cell `toCSVCell` writes is\n * either empty or quoted with its own quotes doubled, so the next lone quote\n * closes it.\n */\nfunction csvCellEnd(text: string, start: number): number {\n if (text.charCodeAt(start) !== 34 /* \" */) return start;\n let i = start + 1;\n for (; ;) {\n const quote = text.indexOf(\"\\\"\", i);\n if (quote < 0) return text.length;\n if (text.charCodeAt(quote + 1) === 34) {\n i = quote + 2;\n } else {\n return quote + 1;\n }\n }\n}\n\n/**\n * Get headers for property. There could be more than one header per property\n * @param property\n * @param propertyKey\n * @param prefix\n */\nfunction getHeaders(property: Property, propertyKey: string, prefix = \"\"): Header[] {\n const currentKey = prefix ? `${prefix}.${propertyKey}` : propertyKey;\n if (property.type === \"map\" && property.properties) {\n return Object.entries(property.properties)\n .map(([childKey, p]) => getHeaders(p, childKey, currentKey))\n .flat();\n } else {\n return [{\n label: currentKey,\n key: currentKey\n }];\n }\n}\n\n/**\n * Read whatever a `date` column actually arrived as into a `Date`.\n *\n * The driver/WebSocket path revives `{ __type: \"date\" }` into a `Date`; the REST\n * path — which is the one the admin is on — leaves an ISO string, and an epoch\n * number is what a re-imported export carries. Returns `undefined` for anything\n * that is not a date, so the caller can pass the raw value through.\n */\nfunction toExportableDate(inputValue: unknown): Date | undefined {\n if (inputValue instanceof Date) return Number.isNaN(inputValue.getTime()) ? undefined : inputValue;\n if (typeof inputValue === \"number\" && Number.isFinite(inputValue)) return new Date(inputValue);\n if (typeof inputValue === \"string\" && inputValue.trim() !== \"\") {\n const parsed = new Date(inputValue);\n return Number.isNaN(parsed.getTime()) ? undefined : parsed;\n }\n return undefined;\n}\n\n/**\n * The id a relation value points at, for a relation property's value — an\n * `EntityRelation`, or the same thing still in its `{ __type: \"relation\" }`\n * wire form. `undefined` for anything else, so a bare foreign key passes\n * through as the id it already is.\n */\nfunction relationIdForExport(value: unknown): string | number | undefined {\n if (value instanceof EntityRelation) return value.id;\n if (typeof value === \"object\" && value !== null\n && \"__type\" in value && value.__type === \"relation\"\n && \"id\" in value && (typeof value.id === \"string\" || typeof value.id === \"number\")) {\n return value.id;\n }\n return undefined;\n}\n\nfunction processValueForExport(inputValue: unknown,\n property: Property,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n): unknown {\n\n let value: unknown;\n if (property.type === \"relation\") {\n // A relation is exported as the id it points at — what the import\n // writes back — rather than the view-model object the admin holds,\n // which a CSV cell printed as `[object Object]`. To-many relations\n // are arrays of them.\n const toId = (item: unknown) => relationIdForExport(item) ?? item;\n value = Array.isArray(inputValue) ? inputValue.map(toId) : toId(inputValue);\n } else if (property.type === \"map\" && property.properties) {\n value = processValuesForExport(inputValue as Record<string, unknown>, property.properties as Properties, exportType, dateExportType);\n } else if (property.type === \"array\") {\n if (property.of && Array.isArray(inputValue)) {\n if (Array.isArray(property.of)) {\n value = property.of.map((p, i) => processValueForExport(inputValue[i], p, exportType, dateExportType));\n } else if (property.of.type === \"map\") {\n value = exportType === \"csv\"\n ? inputValue.map((e) => JSON.stringify(e))\n : inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n ;\n } else {\n value = inputValue.map((e) => processValueForExport(e, property.of as Property, exportType, dateExportType));\n }\n } else {\n value = inputValue;\n }\n } else if (property.type === \"reference\" && inputValue && typeof inputValue === \"object\" && \"isEntityReference\" in inputValue && typeof (inputValue as EntityReference).isEntityReference === \"function\" && (inputValue as EntityReference).isEntityReference()) {\n const ref = inputValue ? inputValue as EntityReference : undefined;\n value = ref ? ref.fullPath : null;\n } else if (property.type === \"date\") {\n // Not `instanceof Date`: the admin reads over REST, and the REST row\n // pipeline hands dates back as the database wrote them — a string. That\n // made this branch dead on every live export, so both radio options\n // produced identical files. Normalise here, where the declared type says\n // the column is a date, and leave anything unparseable untouched rather\n // than exporting an invalid date as `null`.\n const date = toExportableDate(inputValue);\n value = date\n ? (dateExportType === \"timestamp\" ? date.getTime() : date.toISOString())\n : inputValue;\n } else {\n value = inputValue;\n }\n\n return value;\n}\n\nfunction processValuesForExport<M extends Record<string, unknown>>\n (inputValues: Record<string, unknown>,\n properties: Properties,\n exportType: \"csv\" | \"json\",\n dateExportType: \"timestamp\" | \"string\"\n ): Record<string, unknown> {\n // One accumulator. Merging `{ [key]: value }` objects pairwise copied the\n // whole row once per property — the square of the property count, per row.\n const result: Record<string, unknown> = { ...inputValues };\n for (const [key, property] of Object.entries(properties)) {\n const inputValue = inputValues && (inputValues)[key];\n const updatedValue = processValueForExport(inputValue, property as Property, exportType, dateExportType);\n if (updatedValue === undefined) continue;\n if (key === \"__proto__\") {\n // An own property, as the object spread made it, not the prototype.\n Object.defineProperty(result, key, { value: updatedValue, enumerable: true, writable: true, configurable: true });\n } else {\n result[key] = updatedValue;\n }\n }\n return result;\n}\n\n// One rule for every CSV the product writes — here, the SQL console's export\n// and the server's streamed download: `@rebasepro/utils`' csv helpers.\nexport { escapeCsvFormula, unescapeCsvFormula };\n\nfunction toCSVCell(v: unknown): string {\n if (v === null || v === undefined) return \"\";\n // An array or object (a geopoint, a value no property declares) is written\n // as its JSON: `String()` of an object is `[object Object]`. Date\n // properties are normalised before they get here.\n const s = Array.isArray(v) || (typeof v === \"object\" && !(v instanceof Date))\n ? JSON.stringify(v)\n : String(v);\n return \"\\\"\" + escapeCsvFormula(s).replaceAll(\"\\\"\", \"\\\"\\\"\") + \"\\\"\";\n}\n\nexport function entryToCSVRow(entry: unknown[]) {\n return entry\n .map(toCSVCell)\n .join(\",\") + \"\\r\\n\";\n}\n\nexport function downloadBlob(content: BlobPart[], filename: string, contentType: string) {\n const blob = new Blob(content, { type: contentType });\n const url = URL.createObjectURL(blob);\n const pom = document.createElement(\"a\");\n pom.href = url;\n pom.setAttribute(\"download\", filename);\n pom.click();\n // Unrevoked, the URL kept the whole file in memory until the tab closed —\n // one more copy per export. The download holds its own reference once it\n // has started; the delay covers browsers that start it a moment after\n // `click()` returns.\n setTimeout(() => URL.revokeObjectURL(url), BLOB_URL_LIFETIME_MS);\n}\n\n/** How long an export's object URL outlives the click that downloads it. */\nconst BLOB_URL_LIFETIME_MS = 10_000;\n\nexport function downloadDataAsCsv(data: object[], name: string) {\n if (data.length === 0) return;\n\n const headers = Object.keys(data[0]);\n const csvContent = [\n headers.join(\",\"),\n ...data.map(row => headers.map(header => toCSVCell((row as Record<string, unknown>)[header])).join(\",\"))\n ].join(\"\\r\\n\");\n\n downloadBlob([csvContent], `${name}.csv`, \"text/csv\");\n}\n"],"mappings":";;;AAoBA,SAAgB,uBAA0D,EACtE,MACA,gBACA,YACA,iBACA,MACA,eACA,mBACA,YACA,kBAEF;CAEE,QAAQ,MAAM,sBAAsB;EAChC,YAAY,KAAK;EACjB;EACA;EACA;CACJ,CAAC;CAED,IAAI,eAAe,OAAO;EACtB,MAAM,SAAS,sBAAsB;GACjC;GACA;GACA;GACA;GACA;EACJ,CAAC;EACD,OAAO,QAAQ,MAAM,cAAc;EACnC,aAAa,OAAO,OAAO,GAAG,GAAG,KAAK,OAAO,UAAU;CAC3D,OAAO;EACH,MAAM,iBAAiB,4BAA4B,MAAM,gBAAgB,YAAY,cAAc;EAEnG,aAAa,CADA,KAAK,UAAU,gBAAgB,MAAM,CACpC,CAAI,GAAG,GAAG,KAAK,QAAQ,kBAAkB;CAC3D;AACJ;AAEA,SAAgB,2BAA2B,MACvC,gBACA,YACA,SACA,gBACF;CACE,OAAO,gBAAgB,MAAM,gBAAgB,YAAY,OAAO,cAAc,CAAC,CAC1E,KAAK,UAAU,QAAQ,KAAK,WAAW,eAAe,OAAO,OAAO,GAAG,CAAC,CAAC;AAClF;AAEA,SAAgB,4BAA4B,MACxC,gBACA,YACA,gBACF;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,MAAM,MAAM,IAAI,gBAAgB,IAAI;CACpC,MAAM,MAAM,SAAS,cAAc,GAAG;CACtC,IAAI,OAAO;CACX,IAAI,aAAa,YAAY,QAAQ;CACrC,IAAI,MAAM;CAKV,iBAAiB,IAAI,gBAAgB,GAAG,GAAG,oBAAoB;AACnE;;AAGA,IAAM,uBAAuB;AAE7B,SAAgB,kBAAkB,MAAgB,MAAc;CAC5D,IAAI,KAAK,WAAW,GAAG;CAEvB,MAAM,UAAU,OAAO,KAAK,KAAK,EAAE;CAMnC,aAAa,CALM,CACf,QAAQ,KAAK,GAAG,GAChB,GAAG,KAAK,KAAI,QAAO,QAAQ,KAAI,WAAU,UAAW,IAAgC,OAAO,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAC3G,CAAC,CAAC,KAAK,MAEO,CAAU,GAAG,GAAG,KAAK,OAAO,UAAU;AACxD"}
@@ -9,4 +9,4 @@ import type { EntityFormProps } from "../types/components/EntityFormProps.js";
9
9
  *
10
10
  * @group Components
11
11
  */
12
- export declare function EntityForm<M extends Record<string, unknown>>({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode, formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent, showDefaultActions, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }: EntityFormProps<M>): React.JSX.Element;
12
+ export declare function EntityForm<M extends Record<string, unknown>>({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode, formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent, showDefaultActions, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }: EntityFormProps<M>): React.JSX.Element;
@@ -1,9 +1,10 @@
1
1
  import { FieldBlock, isSelfLabellingProperty, spanClass } from "./components/FieldBlock.js";
2
+ import { labelsInsideControl } from "./label_placement.js";
2
3
  import { AdditionalFieldValue } from "../components/AdditionalFieldValue.js";
3
4
  import { FormRail, RecordMeta } from "./components/FormRail.js";
4
5
  import { FormSections } from "./components/FormSections.js";
5
6
  import { useRailVisible } from "./components/useRailVisible.js";
6
- import { resolveFormProperty, resolvePropertiesForValidation } from "./resolve_form_properties.js";
7
+ import { formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults } from "./resolve_form_properties.js";
7
8
  import { FormUploadsContext, createFormUploadTracker } from "./form_uploads.js";
8
9
  import { applyValueTransforms, getEntitySchema, uniqueValueErrors } from "./validation.js";
9
10
  import { PropertyFieldBinding } from "./PropertyFieldBinding.js";
@@ -17,7 +18,7 @@ import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "rea
17
18
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
18
19
  import { deepEqual } from "fast-equals";
19
20
  import { Alert, AlignLeftIcon, Button, CircularProgressCenter, Dialog, DialogActions, DialogContent, DialogTitle, ErrorBoundary, Typography, cls, defaultBorderMixin, isKeyHandled, paperMixin, useDebouncedCallback } from "@rebasepro/ui";
20
- import { getCopyValues, getDefaultValuesFor } from "@rebasepro/common";
21
+ import { effectiveAccess, getCopyValues, getDefaultValuesFor } from "@rebasepro/common";
21
22
  import { flattenKeys, getFormFieldKeys, isDisabled, isHidden, isReadOnly, resolveFormLayout, useAuthController, useCustomizationController, useRebaseContext, useTranslation } from "@rebasepro/app";
22
23
  import { Formex, useCreateFormex } from "@rebasepro/forms";
23
24
  //#region src/form/EntityForm.tsx
@@ -30,10 +31,11 @@ import { Formex, useCreateFormex } from "@rebasepro/forms";
30
31
  *
31
32
  * @group Components
32
33
  */
33
- function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode = "full_screen", formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent = EntityFormActions, showDefaultActions = true, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }) {
34
+ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified, onIdChange, onSaved, entity, initialDirtyValues, onFormContextReady, initialStatus, className, onStatusChange, onEntityChange, openEntityMode = "full_screen", formex: formexProp, disabled: disabledProp, Builder, parentCollectionSlugs, parentEntityIds, EntityFormActionsComponent = EntityFormActions, showDefaultActions = true, navigateBack: navigateBackProp, children, onSubmit: onSubmitProp, onValuesChangeDeferred: onValuesChangeDeferredProp, onReset: onResetProp, uniqueFieldValidator: uniqueFieldValidatorProp, lockedPropertyKeys, beforeFields, afterFields, pluginActions: pluginActionsProp, computedInitialValues, hasLocalChanges: hasLocalChangesProp, localChangesData, manualApplyLocalChanges, localChangesCacheKey, onClearLocalChanges }) {
34
35
  const navigateBack = useCallback(() => {
35
36
  if (navigateBackProp) navigateBackProp();
36
37
  }, [navigateBackProp]);
38
+ const authController = useAuthController();
37
39
  const [status, setStatus] = useState(initialStatus);
38
40
  const updateStatus = (status) => {
39
41
  setStatus(status);
@@ -228,7 +230,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
228
230
  const lastSavedValues = useRef(baseInitialValues);
229
231
  const save = async (values) => {
230
232
  const writtenValues = applyValueTransforms(values, collection.properties);
231
- const valuesToSave = status === "existing" ? getChangedProperties(writtenValues, entity?.values || {}) : status === "new" ? withoutUnsetNulls(writtenValues, baseInitialValues) : writtenValues;
233
+ const valuesToSave = status === "existing" ? getChangedProperties(writtenValues, entity?.values || {}) : withoutUnwritableDefaults(status === "new" ? withoutUnsetNulls(writtenValues, baseInitialValues) : writtenValues, baseInitialValues, collection.properties, formViewer(authController));
232
234
  if (status === "existing" && Object.keys(valuesToSave).length === 0 && entity) return Promise.resolve(entity);
233
235
  lastSavedValues.current = values;
234
236
  if (!onSubmitProp) return;
@@ -343,7 +345,6 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
343
345
  if (uniqueFieldValidatorProp) return uniqueFieldValidatorProp;
344
346
  return defaultUniqueFieldValidator;
345
347
  }, [uniqueFieldValidatorProp, defaultUniqueFieldValidator]);
346
- const authController = useAuthController();
347
348
  const customizationController = useCustomizationController();
348
349
  const { t } = useTranslation();
349
350
  async function validationErrorsFor(values) {
@@ -448,18 +449,19 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
448
449
  if (status !== "new" && status !== "copy") return void 0;
449
450
  return [...layout.sections.flatMap((s) => s.fields), ...layout.sidebar].find((field) => {
450
451
  const property = collection.properties?.[field.key];
451
- return property ? !isFieldDisabled(property) : false;
452
+ return property ? !isFieldDisabled(field.key, property) : false;
452
453
  })?.key;
453
454
  }, [
454
455
  layout,
455
456
  collection,
456
457
  status,
457
- disabledProp
458
+ disabledProp,
459
+ lockedPropertyKeys
458
460
  ]);
459
- function isFieldDisabled(property) {
461
+ function isFieldDisabled(key, property) {
460
462
  const isNew = status === "new" || status === "copy";
461
463
  const isIdAndAuto = (property.type === "string" || property.type === "number") && "isId" in property && typeof property.isId === "string" && property.isId !== "manual";
462
- return Boolean(disabledProp || !autoSave && formex.isSubmitting || isReadOnly(property) || isDisabled(property) || !isNew && "isId" in property && Boolean(property.isId) || isNew && isIdAndAuto);
464
+ return Boolean(disabledProp || !autoSave && formex.isSubmitting || isReadOnly(property) || isDisabled(property) || !isNew && "isId" in property && Boolean(property.isId) || isNew && isIdAndAuto || isNew && lockedPropertyKeys?.includes(key));
463
465
  }
464
466
  const renderField = (field) => {
465
467
  if (field.additional) {
@@ -497,7 +499,7 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
497
499
  console.warn(`Property ${field.key} not found in collection ${collection.name} in properties or additional fields. Skipping.`);
498
500
  return null;
499
501
  }
500
- if (property.conditions?.hidden) {
502
+ if (property.conditions?.hidden || effectiveAccess(property)) {
501
503
  const shown = resolveFormProperty({
502
504
  propertyKey: field.key,
503
505
  property,
@@ -512,14 +514,15 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
512
514
  if (!shown || isHidden(shown)) return null;
513
515
  }
514
516
  const underlyingValueHasChanged = field.key in underlyingChanges && !deepEqual(formex.values[field.key], underlyingChanges[field.key]);
515
- const disabled = isFieldDisabled(property);
517
+ const disabled = isFieldDisabled(field.key, property);
516
518
  const selfLabelling = isSelfLabellingProperty(property);
519
+ const labelInside = !selfLabelling && labelsInsideControl(property, customizationController.propertyConfigs);
517
520
  const cmsFormFieldProps = {
518
521
  propertyKey: field.key,
519
522
  disabled,
520
523
  property,
521
524
  includeDescription: false,
522
- hideLabel: !selfLabelling,
525
+ hideLabel: !selfLabelling && !labelInside,
523
526
  underlyingValueHasChanged: underlyingValueHasChanged && !autoSave,
524
527
  context: fieldContext,
525
528
  partOfArray: false,
@@ -532,7 +535,8 @@ function EntityForm({ path, entityId: entityIdProp, collection, onValuesModified
532
535
  children: /* @__PURE__ */ jsx(FieldBlock, {
533
536
  propertyKey: field.key,
534
537
  property,
535
- showLabel: !selfLabelling,
538
+ showLabel: !selfLabelling && !labelInside,
539
+ labelInside,
536
540
  children: /* @__PURE__ */ jsx(PropertyFieldBinding, { ...cmsFormFieldProps })
537
541
  })
538
542
  }, `field_${field.key}`);