@rebasepro/cms 0.25.1 → 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 (111) hide show
  1. package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js +1 -1
  2. package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js.map +1 -1
  3. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.d.ts +7 -1
  4. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +9 -2
  5. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
  6. package/dist/collection_editor/useLiveSchemaEditing.js +4 -1
  7. package/dist/collection_editor/useLiveSchemaEditing.js.map +1 -1
  8. package/dist/components/CollectionTableBinding/fields/TableReferenceField.js +1 -1
  9. package/dist/components/CollectionTableBinding/fields/TableReferenceField.js.map +1 -1
  10. package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.d.ts +1 -2
  11. package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js.map +1 -1
  12. package/dist/components/CollectionTableBinding/internal/EntityTableCell.d.ts +1 -2
  13. package/dist/components/CollectionTableBinding/internal/EntityTableCell.js.map +1 -1
  14. package/dist/components/CollectionViewBinding/CollectionViewActions.js +1 -1
  15. package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
  16. package/dist/components/CollectionViewBinding/CollectionViewBinding.js +2 -28
  17. package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
  18. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.d.ts +12 -0
  19. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js +33 -0
  20. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js.map +1 -0
  21. package/dist/components/CollectionsScopeContext.d.ts +5 -1
  22. package/dist/components/CollectionsScopeContext.js +10 -2
  23. package/dist/components/CollectionsScopeContext.js.map +1 -1
  24. package/dist/components/DefaultAppBar.js +2 -1
  25. package/dist/components/DefaultAppBar.js.map +1 -1
  26. package/dist/components/DefaultDrawer.js +16 -4
  27. package/dist/components/DefaultDrawer.js.map +1 -1
  28. package/dist/components/DefaultMissingReference.d.ts +8 -0
  29. package/dist/components/DefaultMissingReference.js +13 -0
  30. package/dist/components/DefaultMissingReference.js.map +1 -0
  31. package/dist/components/EntityFormPanel.d.ts +7 -2
  32. package/dist/components/EntityFormPanel.js +72 -29
  33. package/dist/components/EntityFormPanel.js.map +1 -1
  34. package/dist/components/HomePage/ContentHomePage.js +4 -3
  35. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  36. package/dist/components/HomePage/HomePageDnD.js +3 -1
  37. package/dist/components/HomePage/HomePageDnD.js.map +1 -1
  38. package/dist/components/HomePage/SmallNavigationCard.js +25 -0
  39. package/dist/components/HomePage/SmallNavigationCard.js.map +1 -0
  40. package/dist/components/RebaseAuthGate.js +3 -2
  41. package/dist/components/RebaseAuthGate.js.map +1 -1
  42. package/dist/components/RebaseLayout.d.ts +4 -1
  43. package/dist/components/RebaseLayout.js +7 -1
  44. package/dist/components/RebaseLayout.js.map +1 -1
  45. package/dist/components/RebaseShell.d.ts +4 -1
  46. package/dist/components/RebaseShell.js.map +1 -1
  47. package/dist/components/SideDialogs.js +10 -4
  48. package/dist/components/SideDialogs.js.map +1 -1
  49. package/dist/components/app/Scaffold.js +5 -1
  50. package/dist/components/app/Scaffold.js.map +1 -1
  51. package/dist/components/field_configs.js +1 -1
  52. package/dist/components/history/EntityHistoryView.js +6 -4
  53. package/dist/components/history/EntityHistoryView.js.map +1 -1
  54. package/dist/components/history/LastEditedByIndicator.d.ts +2 -1
  55. package/dist/data_export/export/export.d.ts +2 -13
  56. package/dist/data_export/export/export.js +1 -36
  57. package/dist/data_export/export/export.js.map +1 -1
  58. package/dist/form/EntityForm.d.ts +1 -1
  59. package/dist/form/EntityForm.js +17 -13
  60. package/dist/form/EntityForm.js.map +1 -1
  61. package/dist/form/EntityFormBinding.d.ts +1 -1
  62. package/dist/form/EntityFormBinding.js +42 -4
  63. package/dist/form/EntityFormBinding.js.map +1 -1
  64. package/dist/form/PropertyFieldBinding.js +1 -1
  65. package/dist/form/components/FieldBlock.d.ts +8 -1
  66. package/dist/form/components/FieldBlock.js +16 -2
  67. package/dist/form/components/FieldBlock.js.map +1 -1
  68. package/dist/form/components/FormSections.js +1 -1
  69. package/dist/form/components/FormSections.js.map +1 -1
  70. package/dist/form/components/LabelWithIcon.js +5 -2
  71. package/dist/form/components/LabelWithIcon.js.map +1 -1
  72. package/dist/form/field_bindings/DateTimeFieldBinding.js +2 -1
  73. package/dist/form/field_bindings/DateTimeFieldBinding.js.map +1 -1
  74. package/dist/form/field_bindings/ReadOnlyFieldBinding.js +28 -1
  75. package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
  76. package/dist/form/field_bindings/RelationFieldBinding.js +7 -3
  77. package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
  78. package/dist/form/field_bindings/SelectFieldBinding.js +63 -42
  79. package/dist/form/field_bindings/SelectFieldBinding.js.map +1 -1
  80. package/dist/form/field_bindings/SwitchFieldBinding.js +2 -1
  81. package/dist/form/field_bindings/SwitchFieldBinding.js.map +1 -1
  82. package/dist/form/field_bindings/TextFieldBinding.js +8 -6
  83. package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
  84. package/dist/form/form_utils.d.ts +18 -1
  85. package/dist/form/form_utils.js +38 -2
  86. package/dist/form/form_utils.js.map +1 -1
  87. package/dist/form/index.d.ts +1 -1
  88. package/dist/form/label_placement.d.ts +23 -0
  89. package/dist/form/label_placement.js +71 -0
  90. package/dist/form/label_placement.js.map +1 -0
  91. package/dist/form/resolve_form_properties.d.ts +35 -3
  92. package/dist/form/resolve_form_properties.js +67 -6
  93. package/dist/form/resolve_form_properties.js.map +1 -1
  94. package/dist/hooks/useHistory.d.ts +5 -0
  95. package/dist/hooks/useHistory.js +22 -6
  96. package/dist/hooks/useHistory.js.map +1 -1
  97. package/dist/index.d.ts +50 -0
  98. package/dist/index.js +34 -7
  99. package/dist/preview/components/ReferencePreview.js +1 -1
  100. package/dist/preview/components/ReferencePreview.js.map +1 -1
  101. package/dist/preview/components/RelationPreview.js +1 -1
  102. package/dist/preview/components/RelationPreview.js.map +1 -1
  103. package/dist/types/components/EntityFormProps.d.ts +11 -0
  104. package/package.json +11 -10
  105. package/recipes/README.md +131 -0
  106. package/recipes/bulk-set-status.tsx +62 -0
  107. package/recipes/calendar-view.tsx +123 -0
  108. package/recipes/custom-login.tsx +60 -0
  109. package/recipes/my-preferences.tsx +68 -0
  110. package/recipes/orders-dashboard.tsx +125 -0
  111. package/recipes/site-settings.tsx +63 -0
@@ -1 +1 @@
1
- {"version":3,"file":"TextFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/TextFieldBinding.tsx"],"sourcesContent":["import { useTranslation } from \"@rebasepro/app\";\nimport type { FieldProps } from \"../../types/fields\";\nimport type { NumberProperty, StringProperty } from \"@rebasepro/types\";\nimport React, { useCallback } from \"react\";\n\nimport {\n cls,\n Collapse,\n fieldBackgroundHoverMixin,\n fieldBackgroundMixin,\n IconButton,\n TextareaAutosize,\n TextField,\n XIcon\n} from \"@rebasepro/ui\";\nimport { PreviewType } from \"@rebasepro/cms-types\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { PropertyPreview } from \"../../preview\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/**\n * Generic text field.\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function TextFieldBinding<T extends string | number>({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n }: FieldProps<StringProperty | NumberProperty>) {\n const { t } = useTranslation();\n\n let multiline: boolean | undefined;\n let url: boolean | PreviewType | undefined;\n if (property.type === \"string\") {\n multiline = property.admin?.multiline;\n // `url: true` alone earns the preview. A form field holding a URL that\n // renders as plain text is one you have to select and copy to follow,\n // and the property has already said what it is.\n url = property.admin?.urlPreview ?? property.url;\n }\n\n const displayValue = (value !== undefined && value !== null) ? String(value) : \"\";\n\n const handleClearClick = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setValue(null);\n }, [setValue]);\n\n const onChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n if (inputType === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue(null);\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue(numberValue as T);\n } else {\n setValue(null);\n }\n } else {\n // Emptied is NULL. Writing `\"\"` over a NULL the user only typed\n // into and deleted made `isNull` filters stop matching the row,\n // and collided on an optional unique column; `required` already\n // reads `\"\"` as missing.\n setValue(event.target.value === \"\" ? null : event.target.value as T);\n }\n };\n\n const isMultiline = Boolean(multiline);\n\n let inputType: \"number\" | \"email\" | \"url\" | undefined = undefined;\n if (property.type === \"number\") {\n inputType = \"number\";\n } else if (property.type === \"string\") {\n if (property.email) inputType = \"email\";\n else if (property.admin?.urlPreview || property.url) inputType = \"url\";\n }\n\n // `undefined` rather than an empty element: TextField and the multiline box\n // both reserve a label row whenever `label` is truthy, so a null-rendering\n // element would leave the gap behind without the text.\n const label = hideLabel\n ? undefined\n : (\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required || property.isId === true}\n title={property.name ?? propertyKey}/>\n );\n\n // The control needs a name of its own in two cases, and between them they\n // cover every text field in an entity form:\n //\n // - `hideLabel`, which the form sets for anything FieldBlock labels for it\n // (`hideLabel: !selfLabelling`). FieldBlock draws the name in a <span>\n // inside a <div> — not a <label>, and pointing at nothing — so suppressing\n // the field's own label left the input with no accessible name at all and\n // a screen reader fell back to reading its value back to you.\n // - the multiline branch below, which never associated anything: its label\n // is a decorative absolutely-positioned <div>, so it is unnamed whether or\n // not the form also drew one.\n //\n // The single-line TextField is already handled by the kit when a label is\n // present — it wires `aria-labelledby` — so it only needs this as a fallback.\n const accessibleName = property.name ?? propertyKey;\n return (<>\n {isMultiline ? (\n <div className={cls(\n \"rounded-md relative max-w-full min-h-[64px]\",\n fieldBackgroundMixin,\n fieldBackgroundHoverMixin,\n showError && error ? \"border border-red-500 dark:border-red-600\" : \"\"\n )}>\n {label && <div\n className=\"pointer-events-none absolute top-1 text-xs font-medium px-3 text-text-secondary dark:text-text-secondary-dark\">\n {label}\n </div>}\n <TextareaAutosize\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n disabled={disabled}\n aria-label={accessibleName}\n className={cls(\n \"rounded-md resize-none w-full outline-none text-sm bg-transparent min-h-[64px] px-3\",\n label ? \"pt-8 pb-2\" : \"py-2\",\n disabled && \"outline-none opacity-50 text-surface-accent-600 dark:text-surface-accent-500\",\n showError && error ? \"text-red-500 dark:text-red-600\" : \"\"\n )}\n />\n {property.admin?.clearable && (\n <div\n className=\"flex flex-row justify-center items-center absolute h-full right-0 top-0 mr-4\">\n <IconButton aria-label={t(\"clear\")} onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n </div>\n )}\n </div>\n ) : (\n <TextField\n size={size}\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n label={label}\n aria-label={label ? undefined : accessibleName}\n type={inputType}\n disabled={disabled}\n endAdornment={\n property.admin?.clearable && <IconButton aria-label={t(\"clear\")}\n onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n }\n error={showError ? !!error : undefined}\n inputClassName={error ? \"text-red-500 dark:text-red-600\" : \"\"}/>\n )}\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n disabled={disabled}\n property={property}/>\n\n {url && <Collapse\n className=\"mt-1 ml-1\"\n in={Boolean(value)}>\n <PropertyPreview\n value={value}\n property={property}\n size={size}/>\n </Collapse>}\n\n </>\n );\n\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,SA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ACA,2BACA,aAAa,QAAQ,8CAA8C,EACvE;aALA;IAMK,SAAS,oBAAC,OAAD;KACN,WAAU;eACT;IACA,CAAA;IACL,oBAAC,kBAAD;KACI,OAAO;KACG;KACC;KACD;KACV,cAAY;KACZ,WAAW,IACP,uFACA,QAAQ,cAAc,QACtB,YAAY,gFACZ,aAAa,QAAQ,mCAAmC,EAC5D;IACH,CAAA;IACA,SAAS,OAAO,aACb,oBAAC,OAAD;KACI,WAAU;eACV,oBAAC,YAAD;MAAY,cAAY,EAAE,OAAO;MAAG,SAAS;gBACzC,oBAAC,OAAD,CAAO,CAAA;KACC,CAAA;IACX,CAAA;GAER;OAEL,oBAAC,WAAD;GACU;GACN,OAAO;GACG;GACC;GACJ;GACP,cAAY,QAAQ,KAAA,IAAY;GAChC,MAAM;GACI;GACV,cACI,SAAS,OAAO,aAAa,oBAAC,YAAD;IAAY,cAAY,EAAE,OAAO;IAC1D,SAAS;cACT,oBAAC,OAAD,CAAO,CAAA;GACC,CAAA;GAEhB,OAAO,YAAY,CAAC,CAAC,QAAQ,KAAA;GAC7B,gBAAgB,QAAQ,mCAAmC;EAAI,CAAA;EAEvE,oBAAC,iBAAD;GAAqC;GACT;GACJ;GACG;GACA;EAAU,CAAA;EAEpC,OAAO,oBAAC,UAAD;GACJ,WAAU;GACV,IAAI,QAAQ,KAAK;aACjB,oBAAC,iBAAD;IACW;IACG;IACJ;GAAM,CAAA;EACV,CAAA;CAEZ,EAAA,CAAA;AAGV"}
1
+ {"version":3,"file":"TextFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/TextFieldBinding.tsx"],"sourcesContent":["import { useTranslation } from \"@rebasepro/app\";\nimport type { FieldProps } from \"../../types/fields\";\nimport type { NumberProperty, StringProperty } from \"@rebasepro/types\";\nimport React, { useCallback } from \"react\";\n\nimport {\n cls,\n Collapse,\n fieldBackgroundHoverMixin,\n fieldBackgroundMixin,\n IconButton,\n InputLabel,\n TextareaAutosize,\n TextField,\n XIcon\n} from \"@rebasepro/ui\";\nimport { PreviewType } from \"@rebasepro/cms-types\";\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { PropertyPreview } from \"../../preview\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/**\n * Generic text field.\n * This is one of the internal components that get mapped natively inside forms\n * and tables to the specified properties.\n * @group Form fields\n */\nexport function TextFieldBinding<T extends string | number>({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n }: FieldProps<StringProperty | NumberProperty>) {\n const { t } = useTranslation();\n\n let multiline: boolean | undefined;\n let url: boolean | PreviewType | undefined;\n if (property.type === \"string\") {\n multiline = property.admin?.multiline;\n // `url: true` alone earns the preview. A form field holding a URL that\n // renders as plain text is one you have to select and copy to follow,\n // and the property has already said what it is.\n url = property.admin?.urlPreview ?? property.url;\n }\n\n const displayValue = (value !== undefined && value !== null) ? String(value) : \"\";\n\n const handleClearClick = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setValue(null);\n }, [setValue]);\n\n const onChange = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n if (inputType === \"number\") {\n const numberValue = event.target.value ? parseFloat(event.target.value) : undefined;\n if (numberValue && isNaN(numberValue)) {\n setValue(null);\n } else if (numberValue !== undefined && numberValue !== null) {\n setValue(numberValue as T);\n } else {\n setValue(null);\n }\n } else {\n // Emptied is NULL. Writing `\"\"` over a NULL the user only typed\n // into and deleted made `isNull` filters stop matching the row,\n // and collided on an optional unique column; `required` already\n // reads `\"\"` as missing.\n setValue(event.target.value === \"\" ? null : event.target.value as T);\n }\n };\n\n const isMultiline = Boolean(multiline);\n\n let inputType: \"number\" | \"email\" | \"url\" | undefined = undefined;\n if (property.type === \"number\") {\n inputType = \"number\";\n } else if (property.type === \"string\") {\n if (property.email) inputType = \"email\";\n else if (property.admin?.urlPreview || property.url) inputType = \"url\";\n }\n\n // `undefined` rather than an empty element: TextField and the multiline box\n // both reserve a label row whenever `label` is truthy, so a null-rendering\n // element would leave the gap behind without the text.\n const label = hideLabel\n ? undefined\n : (\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required || property.isId === true}\n title={property.name ?? propertyKey}/>\n );\n\n // A value under a label inside the box is set at 16px, the FireCMS field:\n // the 64px box is sized for a 24px line. Everywhere a text field stands\n // without its label — a table cell, a dense dialog — it keeps the kit's 14.\n const valueText = label && size === \"large\" ? \"text-base\" : undefined;\n\n // The control needs a name of its own in two cases, and between them they\n // cover every text field in an entity form:\n //\n // - `hideLabel`, which the form sets for anything FieldBlock labels for it\n // (`hideLabel: !selfLabelling`). FieldBlock draws the name in a <span>\n // inside a <div> — not a <label>, and pointing at nothing — so suppressing\n // the field's own label left the input with no accessible name at all and\n // a screen reader fell back to reading its value back to you.\n // - the multiline branch below, which never associated anything: its label\n // is a decorative absolutely-positioned <div>, so it is unnamed whether or\n // not the form also drew one.\n //\n // The single-line TextField is already handled by the kit when a label is\n // present — it wires `aria-labelledby` — so it only needs this as a fallback.\n const accessibleName = property.name ?? propertyKey;\n return (<>\n {isMultiline ? (\n <div className={cls(\n \"rounded-lg relative max-w-full min-h-[64px]\",\n fieldBackgroundMixin,\n fieldBackgroundHoverMixin,\n showError && error ? \"border border-red-500 dark:border-red-600\" : \"\"\n )}>\n {/* The single-line field's shrunk label, at the same spot:\n this was its own 14px label pinned to the top, a size up\n from the label of the field above it. Always shrunk —\n the box is tall, and a label resting in its middle would\n sit on the text. */}\n {label && <InputLabel shrink\n className={cls(\n \"pointer-events-none absolute top-1\",\n showError && error\n ? \"text-red-500 dark:text-red-600\"\n : \"text-text-secondary dark:text-text-secondary-dark\"\n )}>\n {label}\n </InputLabel>}\n <TextareaAutosize\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n disabled={disabled}\n aria-label={accessibleName}\n className={cls(\n \"rounded-md resize-none w-full outline-none text-sm bg-transparent min-h-[64px] px-3\",\n valueText,\n label ? \"pt-8 pb-2\" : \"py-2\",\n disabled && \"outline-none opacity-50 text-surface-accent-600 dark:text-surface-accent-500\",\n showError && error ? \"text-red-500 dark:text-red-600\" : \"\"\n )}\n />\n {property.admin?.clearable && (\n <div\n className=\"flex flex-row justify-center items-center absolute h-full right-0 top-0 mr-4\">\n <IconButton aria-label={t(\"clear\")} onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n </div>\n )}\n </div>\n ) : (\n <TextField\n size={size}\n value={displayValue}\n onChange={onChange}\n autoFocus={autoFocus}\n label={label}\n aria-label={label ? undefined : accessibleName}\n type={inputType}\n disabled={disabled}\n endAdornment={\n property.admin?.clearable && <IconButton aria-label={t(\"clear\")}\n onClick={handleClearClick}>\n <XIcon/>\n </IconButton>\n }\n error={showError ? !!error : undefined}\n inputClassName={cls(valueText, error && \"text-red-500 dark:text-red-600\")}/>\n )}\n <FieldHelperText includeDescription={includeDescription}\n showError={showError}\n error={error}\n disabled={disabled}\n property={property}/>\n\n {url && <Collapse\n className=\"mt-1 ml-1\"\n in={Boolean(value)}>\n <PropertyPreview\n value={value}\n property={property}\n size={size}/>\n </Collapse>}\n\n </>\n );\n\n}\n"],"mappings":";;;;;;;;;;;;;;;AA4BA,SAAgB,iBAA4C,EACI,aACA,OACA,UACA,OACA,WACA,UACA,WACA,UACA,oBACA,WACA,OAAO,WACqC;CACxG,MAAM,EAAE,MAAM,eAAe;CAE7B,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS,SAAS,UAAU;EAC5B,YAAY,SAAS,OAAO;EAI5B,MAAM,SAAS,OAAO,cAAc,SAAS;CACjD;CAEA,MAAM,eAAgB,UAAU,KAAA,KAAa,UAAU,OAAQ,OAAO,KAAK,IAAI;CAE/E,MAAM,mBAAmB,aAAa,MAAwB;EAC1D,EAAE,gBAAgB;EAClB,EAAE,eAAe;EACjB,SAAS,IAAI;CACjB,GAAG,CAAC,QAAQ,CAAC;CAEb,MAA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AAG,SAAS;gBACzC,oBAAC,OAAD,CAAO,CAAA;KACC,CAAA;IACX,CAAA;GAER;OAEL,oBAAC,WAAD;GACU;GACN,OAAO;GACG;GACC;GACJ;GACP,cAAY,QAAQ,KAAA,IAAY;GAChC,MAAM;GACI;GACV,cACI,SAAS,OAAO,aAAa,oBAAC,YAAD;IAAY,cAAY,EAAE,OAAO;IAC1D,SAAS;cACT,oBAAC,OAAD,CAAO,CAAA;GACC,CAAA;GAEhB,OAAO,YAAY,CAAC,CAAC,QAAQ,KAAA;GAC7B,gBAAgB,IAAI,WAAW,SAAS,gCAAgC;EAAG,CAAA;EAEnF,oBAAC,iBAAD;GAAqC;GACT;GACJ;GACG;GACA;EAAU,CAAA;EAEpC,OAAO,oBAAC,UAAD;GACJ,WAAU;GACV,IAAI,QAAQ,KAAK;aACjB,oBAAC,iBAAD;IACW;IACG;IACJ;GAAM,CAAA;EACV,CAAA;CAEZ,EAAA,CAAA;AAGV"}
@@ -1,5 +1,6 @@
1
1
  import type { PropertyConfig, AdminCollection } from "@rebasepro/cms-types";
2
- import type { Entity, EntityStatus, EntityValues } from "@rebasepro/types";
2
+ import type { CollectionConfig, CollectionRegistryController, Entity, EntityStatus, EntityValues } from "@rebasepro/types";
3
+ import { EntityRelation } from "@rebasepro/types";
3
4
  import type { AuthController } from "@rebasepro/cms-types";
4
5
  import { z } from "zod";
5
6
  export declare function extractTouchedValues(values: unknown, touched: Record<string, boolean>): Record<string, unknown>;
@@ -91,6 +92,22 @@ export declare function getEditHandoffValues<M extends Record<string, unknown>>(
91
92
  storedValues?: Partial<M>;
92
93
  }): Partial<M> | undefined;
93
94
  export declare function getInitialEntityValues<M extends Record<string, unknown>>(authController: AuthController, collection: AdminCollection, path: string, status: "new" | "existing" | "copy", entity: Entity<M> | undefined, propertyConfigs?: Record<string, PropertyConfig>): Partial<EntityValues<M>>;
95
+ /**
96
+ * The link back to the parent that a record created under
97
+ * `parent/{id}/{relation}` takes from its address: `{ customer: <the parent> }`
98
+ * for a transaction created from a customer's Transactions tab.
99
+ *
100
+ * The server already stamps the parent's key onto a create through an owned
101
+ * `hasMany`/`hasOne`, so the address alone decides the link. The form did not
102
+ * know that: it opened the child's `belongsTo` empty, and a required one asked
103
+ * the user to pick the record they had just come from.
104
+ *
105
+ * Empty when the address does not decide a link — a root collection, a
106
+ * many-to-many (that link is a junction row, not a property), a `sourceKey`
107
+ * (the value is a column of the parent row, which the address does not carry),
108
+ * or a child with no `belongsTo` on the relation's foreign key.
109
+ */
110
+ export declare function getParentLinkValues(registry: Pick<CollectionRegistryController, "getCollection" | "getParentEntityIds">, path: string, collection: CollectionConfig): Record<string, EntityRelation>;
94
111
  export declare function zodToFormErrors(zodError: z.ZodError): Record<string, string>;
95
112
  /**
96
113
  * The fields a server refusal names, as form errors keyed by the property each
@@ -1,6 +1,7 @@
1
1
  import { deepEqual } from "fast-equals";
2
- import { buildConditionContext, evaluateCondition, getCopyValues, getDefaultValuesFor } from "@rebasepro/common";
2
+ import { buildConditionContext, evaluateCondition, findRelation, getCopyValues, getDefaultValuesFor, getEntityChildViews, resolveCollectionRelations } from "@rebasepro/common";
3
3
  import { getIn, setIn } from "@rebasepro/forms";
4
+ import { EntityRelation } from "@rebasepro/types";
4
5
  import { isPlainObject } from "@rebasepro/utils";
5
6
  //#region src/form/form_utils.ts
6
7
  function extractTouchedValues(values, touched) {
@@ -236,6 +237,41 @@ function getInitialEntityValues(authController, collection, path, status, entity
236
237
  throw new Error("Form has not been initialised with the correct parameters");
237
238
  }
238
239
  }
240
+ /**
241
+ * The link back to the parent that a record created under
242
+ * `parent/{id}/{relation}` takes from its address: `{ customer: <the parent> }`
243
+ * for a transaction created from a customer's Transactions tab.
244
+ *
245
+ * The server already stamps the parent's key onto a create through an owned
246
+ * `hasMany`/`hasOne`, so the address alone decides the link. The form did not
247
+ * know that: it opened the child's `belongsTo` empty, and a required one asked
248
+ * the user to pick the record they had just come from.
249
+ *
250
+ * Empty when the address does not decide a link — a root collection, a
251
+ * many-to-many (that link is a junction row, not a property), a `sourceKey`
252
+ * (the value is a column of the parent row, which the address does not carry),
253
+ * or a child with no `belongsTo` on the relation's foreign key.
254
+ */
255
+ function getParentLinkValues(registry, path, collection) {
256
+ if (registry.getParentEntityIds(path).length === 0) return {};
257
+ const segments = path.split("/").filter(Boolean);
258
+ if (segments.length < 3) return {};
259
+ const relationKey = segments[segments.length - 1];
260
+ const parentId = segments[segments.length - 2];
261
+ const parent = registry.getCollection(segments.slice(0, -2).join("/"));
262
+ if (!parent) return {};
263
+ const view = getEntityChildViews(parent).find((v) => v.key === relationKey);
264
+ if (view?.source.kind !== "relation" || view.source.mode !== "owned") return {};
265
+ const link = findRelation(resolveCollectionRelations(parent), view.source.relationKey);
266
+ if (!link || link.kind !== "hasMany" && link.kind !== "hasOne" || link.sourceKey) return {};
267
+ const childRelations = resolveCollectionRelations(collection);
268
+ for (const [key, property] of Object.entries(collection.properties ?? {})) {
269
+ if (property?.type !== "relation") continue;
270
+ const relation = childRelations[key];
271
+ if (relation?.kind === "belongsTo" && relation.localKey === link.foreignKeyOnTarget) return { [key]: new EntityRelation(parentId, relation.targetSlug) };
272
+ }
273
+ return {};
274
+ }
239
275
  function zodToFormErrors(zodError) {
240
276
  let errors = {};
241
277
  for (const issue of zodError.issues) {
@@ -275,6 +311,6 @@ function serverViolationErrors(error, propertyKeys) {
275
311
  return errors;
276
312
  }
277
313
  //#endregion
278
- export { extractTouchedValues, getChangedProperties, getChanges, getEditHandoffValues, getInitialEntityValues, getTouchedPropertyValues, getUnappliedLocalChanges, overlayEdit, removeEmptyContainers, serverViolationErrors, withoutUnsetNulls, zodToFormErrors };
314
+ export { extractTouchedValues, getChangedProperties, getChanges, getEditHandoffValues, getInitialEntityValues, getParentLinkValues, getTouchedPropertyValues, getUnappliedLocalChanges, overlayEdit, removeEmptyContainers, serverViolationErrors, withoutUnsetNulls, zodToFormErrors };
279
315
 
280
316
  //# sourceMappingURL=form_utils.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"form_utils.js","names":[],"sources":["../../src/form/form_utils.ts"],"sourcesContent":["\nimport type { PropertyConfig, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport type { AuthController } from \"@rebasepro/cms-types\";\nimport { deepEqual as equal } from \"fast-equals\";\nimport { getIn, setIn } from \"@rebasepro/forms\";\nimport { buildConditionContext, evaluateCondition, getCopyValues, getDefaultValuesFor } from \"@rebasepro/common\";\nimport { isPlainObject } from \"@rebasepro/utils\";\nimport { z } from \"zod\";\n\n// extract touched values for nested touched trees and map to current values\nexport function extractTouchedValues(values: unknown, touched: Record<string, boolean>): Record<string, unknown> {\n let acc: Record<string, unknown> = {};\n if (!touched || typeof touched !== \"object\") {\n return acc;\n }\n\n Object.entries(touched).forEach(([key, value]) => {\n if (value) {\n acc = setIn(acc, key, getIn(values, key)) as Record<string, unknown>;\n }\n })\n\n return acc;\n}\n\n/**\n * The edit to carry or back up: each top-level property the user touched,\n * **whole** — the same unit a save writes.\n *\n * `extractTouchedValues` builds a tree of only the touched paths, which is a\n * diff, and a diff cannot say \"this item is gone\": a list that shrank from\n * three items to one, or a key-value map with a key deleted, came back whole\n * when the diff was merged onto the stored record. Carrying the property whole\n * and overlaying it (see {@link overlayEdit}) shows exactly what the user left.\n *\n * Which properties count is still decided by the touched tree with its ghost\n * containers removed, so a field merely focused carries nothing.\n */\nexport function getTouchedPropertyValues<M extends Record<string, unknown>>(\n values: Partial<M>,\n touched: Record<string, boolean>\n): Partial<M> {\n const touchedTree = removeEmptyContainers(extractTouchedValues(values, touched ?? {}));\n const result: Record<string, unknown> = {};\n if (!touchedTree || typeof touchedTree !== \"object\") return result as Partial<M>;\n for (const key of Object.keys(touchedTree)) {\n if (Object.prototype.hasOwnProperty.call(values, key)) {\n result[key] = (values as Record<string, unknown>)[key];\n }\n }\n return result as Partial<M>;\n}\n\n/**\n * What a form shows when an edit is laid over `base`: each property the edit\n * carries replaces the base's, whole.\n *\n * Not `mergeDeep`, which merged arrays of maps index by index and kept the base\n * items past the edit's length, and kept map keys the edit had dropped — so a\n * deleted section or key came back when the edit changed layout or a draft was\n * restored, in a form that then read as clean.\n */\nexport function overlayEdit<M extends Record<string, unknown>>(base: Partial<M>, edit: Partial<M>): Partial<M> {\n return { ...base, ...edit };\n}\n\n/**\n * Recursively removes empty plain objects `{}` and empty arrays `[]` from a value tree.\n * This prevents ghost containers created by `setIn` intermediate path construction\n * (e.g. `{ address: {} }` when only `address.city` was touched but value is undefined)\n * from falsely triggering the unsaved local changes indicator.\n */\n/**\n * Check if a value is semantically empty (null, undefined, or empty string).\n */\nfunction isSemanticEmpty(v: unknown): boolean {\n return v === null || v === undefined || v === \"\";\n}\n\nexport function removeEmptyContainers(obj: unknown): unknown {\n if (Array.isArray(obj)) {\n const cleaned = obj.map(removeEmptyContainers);\n // Keep arrays even if they contain only nulls/undefined — that's intentional data\n return cleaned;\n }\n if (obj && typeof obj === \"object\" && Object.getPrototypeOf(obj) === Object.prototype) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n const cleaned = removeEmptyContainers((obj as Record<string, unknown>)[key]);\n // Skip empty plain objects\n if (cleaned && typeof cleaned === \"object\" && !Array.isArray(cleaned)\n && Object.getPrototypeOf(cleaned) === Object.prototype\n && Object.keys(cleaned).length === 0) {\n continue;\n }\n result[key] = cleaned;\n }\n // After cleaning, check if all remaining values are semantically empty\n // (null, undefined, or \"\"). This catches ghost objects like {type: \"\", value: null}\n // created by oneOf block initialization that aren't meaningful changes.\n if (Object.keys(result).length > 0 && Object.values(result).every(isSemanticEmpty)) {\n return {};\n }\n return result;\n }\n return obj;\n}\n\nexport function getChanges<T extends object>(source: Partial<T>, comparison: Partial<T>): Partial<T> {\n const changes: Partial<T> = {};\n\n if (!source) {\n return {};\n }\n if (!comparison) {\n return source;\n }\n\n const allKeys = Array.from(new Set([...Object.keys(source), ...Object.keys(comparison)]));\n\n for (const key of allKeys) {\n const sourceValue = (source as Record<string, unknown>)[key];\n const comparisonValue = (comparison as Record<string, unknown>)[key];\n\n if (equal(sourceValue, comparisonValue)) {\n continue;\n }\n\n const sourceHasKey = source && typeof source === \"object\" && Object.prototype.hasOwnProperty.call(source, key);\n const comparisonHasKey = comparison && typeof comparison === \"object\" && Object.prototype.hasOwnProperty.call(comparison, key);\n\n if (comparisonHasKey && !sourceHasKey) {\n (changes as Record<string, unknown>)[key] = undefined;\n } else if (Array.isArray(sourceValue)) {\n const comparisonArray = Array.isArray(comparisonValue) ? comparisonValue : [];\n if (sourceValue.length !== comparisonArray.length) {\n (changes as Record<string, unknown>)[key] = sourceValue;\n continue;\n }\n const hasChanges = sourceValue.some((item, index) => !equal(item, comparisonArray[index]));\n if (hasChanges) {\n (changes as Record<string, unknown>)[key] = sourceValue;\n }\n } else if (isPlainObject(sourceValue) && isPlainObject(comparisonValue)) {\n // Plain objects only. A `Date` has no keys of its own, so walking\n // into two different dates finds nothing and loses the edit; a\n // class instance (a relation) would come back as a bare `{ id }`\n // that no longer says what it is.\n const nestedChanges = getChanges(sourceValue, comparisonValue);\n if (Object.keys(nestedChanges).length > 0) {\n (changes as Record<string, unknown>)[key] = nestedChanges;\n }\n } else {\n (changes as Record<string, unknown>)[key] = sourceValue;\n }\n }\n\n return changes;\n}\n\n/**\n * What an update of a stored record sends: every top-level property whose value\n * differs from the stored one — whole.\n *\n * Whole, because that is the unit an update replaces. It sets each property it\n * carries, so the value sent *is* the property's new value: a map sent as the\n * one key that changed would erase every key left out, a key-value map with a\n * key removed would arrive empty, and a geopoint with one coordinate moved is\n * refused for lacking the other. {@link getChanges} walks into plain objects to\n * find what changed inside them, which is right for comparing a draft with the\n * form and wrong for a write.\n */\nexport function getChangedProperties<M extends Record<string, unknown>>(\n values: Partial<M>,\n storedValues: Partial<M>\n): Partial<M> {\n const changes: Partial<M> = {};\n const keys = new Set([...Object.keys(values), ...Object.keys(storedValues)]);\n for (const key of keys) {\n if (!equal(values[key], storedValues[key])) {\n (changes as Record<string, unknown>)[key] = values[key];\n }\n }\n return changes;\n}\n\n/**\n * What a create sends: the form's values without the empty ones nobody set.\n *\n * A key the form opened as `null` and still holds as `null` is not a value\n * the user chose. Sent, it is an explicit `NULL`, which beats the column's\n * `DEFAULT` — `published_at timestamptz DEFAULT now()` was created empty from\n * the panel and filled from the API. Left out, the database fills it. A\n * `null` the user set over an opening value (a declared default) is sent, and\n * so is every non-null value, `false` and `[]` included.\n */\nexport function withoutUnsetNulls<M extends Record<string, unknown>>(\n values: M,\n openingValues: Partial<M> | undefined\n): M {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) {\n const opening = openingValues?.[key];\n if ((value === null || value === undefined) && (opening === null || opening === undefined)) continue;\n result[key] = value;\n }\n return result as M;\n}\n\n/**\n * What the local-changes backup still has to offer, given what the form is\n * already showing — the answer the \"unsaved local changes\" banner is asking for.\n * `undefined` means there is nothing left to apply, and no banner.\n *\n * Measured against what the form *opens showing*, not against the stored\n * record. The banner exists to offer a draft the form is not already displaying,\n * and an edit carried across a change of layout is in both the backup and the\n * form: measuring against the stored values alone offered to restore the values\n * already on screen, over an edit the user had never left.\n */\nexport function getUnappliedLocalChanges<M extends Record<string, unknown>>(\n backupValues: Partial<M>,\n openingValues: Partial<M>\n): Partial<M> | undefined {\n if (!backupValues || typeof backupValues !== \"object\") return undefined;\n // The backup holds whole properties (see `getTouchedPropertyValues`), so\n // each one is compared whole and offered whole: a diff of it could not say\n // that a key was deleted, and `overlayEdit` lays down what it is given as\n // the property's entire value.\n const unapplied: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(backupValues)) {\n if (!equal(value, (openingValues as Record<string, unknown> | undefined)?.[key])) {\n unapplied[key] = value;\n }\n }\n return Object.keys(unapplied).length > 0 ? unapplied as Partial<M> : undefined;\n}\n\n/**\n * What travels when the same record changes layout — the split's \"hide list\",\n * full screen's \"show list\", the side panel's \"open full screen\". One mounted\n * form is replaced by another showing the same record, so the edit in progress\n * has to be handed over; left to the local-changes backup alone, the new form\n * met it as a draft from a closed tab and raised the \"unsaved local changes\"\n * banner over changes the user had made a second earlier and never left.\n *\n * Returns `undefined` when there is nothing to carry, which is its own answer: a\n * record nobody edited must open in the next layout exactly as clean as it was.\n *\n * Only what was edited here travels, keyed by `touched` — the same subset the\n * backup stores. Carrying the whole record instead marks every field touched in\n * the receiving form, which lights up every empty required field as an error and\n * writes the entire record back out as a \"local change\".\n */\nexport function getEditHandoffValues<M extends Record<string, unknown>>({\n status,\n dirty,\n values,\n touched,\n storedValues\n}: {\n status: EntityStatus;\n /** Whether `values` differ from what is stored. */\n dirty: boolean;\n values: Partial<M>;\n touched: Record<string, boolean>;\n /** The stored record, for the fallback below. Absent for a new one. */\n storedValues?: Partial<M>;\n}): Partial<M> | undefined {\n\n if (!values) return undefined;\n\n // A record with nothing stored behind it carries whole: there is no\n // baseline to fall back to, so anything not carried is simply lost.\n if (status === \"new\" || status === \"copy\") {\n return Object.keys(values).length > 0 ? values : undefined;\n }\n\n if (!dirty) return undefined;\n\n const touchedValues = getTouchedPropertyValues(values, touched ?? {});\n if (Object.keys(touchedValues).length > 0) {\n return touchedValues;\n }\n\n // Dirty with nothing touched — a value set programmatically, by a plugin or\n // a custom field that writes through `setFieldValue` without the blur that\n // marks it. Diffing against the stored record still finds it, and dropping\n // it here would hand over a form that opens clean over an edit.\n const changes = getChangedProperties(values, storedValues ?? {});\n return Object.keys(changes).length > 0 ? changes : undefined;\n}\n\n/**\n * A new record's values with each top-level `conditions.defaultValue` applied —\n * the rule evaluated against the declared defaults, as a new record has nothing\n * else yet. Without it the rule was documented, editable in Studio, and never\n * read: a new record opened with the static default.\n */\nfunction withConditionalDefaults<M extends Record<string, unknown>>(\n values: Partial<EntityValues<M>>,\n properties: AdminCollection[\"properties\"],\n path: string,\n authController: AuthController\n): Partial<EntityValues<M>> {\n let result = values;\n for (const [key, property] of Object.entries(properties ?? {})) {\n const rule = property?.conditions?.defaultValue;\n if (rule === undefined) continue;\n const context = buildConditionContext({\n propertyKey: key,\n values: values as Record<string, unknown>,\n path,\n authController\n });\n result = { ...result, [key]: evaluateCondition(rule, context) };\n }\n return result;\n}\n\n/**\n * `alwaysApplyDefaultValues`: a property's declared `defaultValue` fills a\n * stored value that is empty, inside maps too.\n *\n * A Postgres row carries every column, an unset one as `null`, so merging the\n * defaults *under* the row let `null` win and the flag did nothing. `false`,\n * `0` and `\"\"` are values the row holds, and are kept.\n */\nfunction fillDeclaredDefaults(properties: AdminCollection[\"properties\"], values: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = { ...values };\n for (const [key, property] of Object.entries(properties ?? {})) {\n if (!property || typeof property !== \"object\" || !(\"type\" in property)) continue;\n const current = result[key];\n if (current === null || current === undefined) {\n if (property.defaultValue !== undefined && property.defaultValue !== null) {\n result[key] = property.defaultValue;\n }\n } else if (property.type === \"map\" && property.properties && isPlainObject(current)) {\n result[key] = fillDeclaredDefaults(property.properties as AdminCollection[\"properties\"], current as Record<string, unknown>);\n }\n }\n return result;\n}\n\nexport function getInitialEntityValues<M extends Record<string, unknown>>(\n authController: AuthController,\n collection: AdminCollection,\n path: string,\n status: \"new\" | \"existing\" | \"copy\",\n entity: Entity<M> | undefined,\n propertyConfigs?: Record<string, PropertyConfig>\n): Partial<EntityValues<M>> {\n const properties = collection.properties;\n if ((status === \"existing\" || status === \"copy\") && entity) {\n let values: Partial<EntityValues<M>>;\n if (!collection.alwaysApplyDefaultValues) {\n values = entity.values ?? getDefaultValuesFor(properties);\n } else {\n values = fillDeclaredDefaults(properties, entity.values ?? {}) as Partial<EntityValues<M>>;\n }\n // A copy gets its own key, and leaves behind every relation it could\n // only take by re-pointing another row — see `getCopyValues`.\n if (status === \"copy\") {\n return getCopyValues(collection, values);\n }\n return values;\n } else if (status === \"new\") {\n return withConditionalDefaults(getDefaultValuesFor(properties), properties, path, authController);\n } else {\n console.error({\n status,\n entity\n });\n throw new Error(\"Form has not been initialised with the correct parameters\");\n }\n}\n\nexport function zodToFormErrors(zodError: z.ZodError): Record<string, string> {\n let errors: Record<string, string> = {};\n for (const issue of zodError.issues) {\n const path = issue.path.join(\".\");\n if (path && !getIn(errors, path)) {\n errors = setIn(errors, path, issue.message) as Record<string, string>;\n }\n }\n return errors;\n}\n\n/**\n * The fields a server refusal names, as form errors keyed by the property each\n * belongs to: `{ title: \"…\", address: \"…\" }`.\n *\n * The server answers a write it refuses with `details.violations` —\n * `[{ field, code, message }]`, `field` the wire path (`address.city`,\n * `tags[2]`). The form printed the sentence in its footer and marked no\n * field, so a unique 409 or a rule only the server checks left the user\n * hunting for the input. A path is marked on its top-level property, which is\n * the field the form shows; a field the form does not have is left out. The\n * first message for a property wins.\n */\nexport function serverViolationErrors(error: unknown, propertyKeys: readonly string[]): Record<string, string> {\n const errors: Record<string, string> = {};\n if (typeof error !== \"object\" || error === null || !(\"details\" in error)) return errors;\n const details = error.details;\n if (typeof details !== \"object\" || details === null || !(\"violations\" in details)) return errors;\n const violations = details.violations;\n if (!Array.isArray(violations)) return errors;\n for (const violation of violations) {\n if (typeof violation !== \"object\" || violation === null) continue;\n if (!(\"field\" in violation) || !(\"message\" in violation)) continue;\n const { field, message } = violation;\n if (typeof field !== \"string\" || typeof message !== \"string\") continue;\n const property = field.split(/[.[]/)[0];\n if (!propertyKeys.includes(property) || property in errors) continue;\n errors[property] = message;\n }\n return errors;\n}\n"],"mappings":";;;;;AAWA,SAAgB,qBAAqB,QAAiB,SAA2D;CAC7G,IAAI,MAA+B,CAAC;CACpC,IAAI,CAAC,WAAW,OAAO,YAAY,UAC/B,OAAO;CAGX,OAAO,QAAQ,OAAO,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EAC9C,IAAI,OACA,MAAM,MAAM,KAAK,KAAK,MAAM,QAAQ,GAAG,CAAC;CAEhD,CAAC;CAED,OAAO;AACX;;;;;;;;;;;;;;AAeA,SAAgB,yBACZ,QACA,SACU;CACV,MAAM,cAAc,sBAAsB,qBAAqB,QAAQ,WAAW,CAAC,CAAC,CAAC;CAC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AAM,QAAQ,MAAM,MAAM,OAAO;CAElD;CACA,OAAO;AACX;;;;;;;;;;;;;AAcA,SAAgB,sBAAsB,OAAgB,cAAyD;CAC3G,MAAM,SAAiC,CAAC;CACxC,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,EAAE,aAAa,QAAQ,OAAO;CACjF,MAAM,UAAU,MAAM;CACtB,IAAI,OAAO,YAAY,YAAY,YAAY,QAAQ,EAAE,gBAAgB,UAAU,OAAO;CAC1F,MAAM,aAAa,QAAQ;CAC3B,IAAI,CAAC,MAAM,QAAQ,UAAU,GAAG,OAAO;CACvC,KAAK,MAAM,aAAa,YAAY;EAChC,IAAI,OAAO,cAAc,YAAY,cAAc,MAAM;EACzD,IAAI,EAAE,WAAW,cAAc,EAAE,aAAa,YAAY;EAC1D,MAAM,EAAE,OAAO,YAAY;EAC3B,IAAI,OAAO,UAAU,YAAY,OAAO,YAAY,UAAU;EAC9D,MAAM,WAAW,MAAM,MAAM,MAAM,CAAC,CAAC;EACrC,IAAI,CAAC,aAAa,SAAS,QAAQ,KAAK,YAAY,QAAQ;EAC5D,OAAO,YAAY;CACvB;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"form_utils.js","names":[],"sources":["../../src/form/form_utils.ts"],"sourcesContent":["\nimport type { PropertyConfig, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { CollectionConfig, CollectionRegistryController, Entity, EntityStatus, EntityValues } from \"@rebasepro/types\";\nimport { EntityRelation } from \"@rebasepro/types\";\nimport type { AuthController } from \"@rebasepro/cms-types\";\nimport { deepEqual as equal } from \"fast-equals\";\nimport { getIn, setIn } from \"@rebasepro/forms\";\nimport {\n buildConditionContext,\n evaluateCondition,\n findRelation,\n getCopyValues,\n getDefaultValuesFor,\n getEntityChildViews,\n resolveCollectionRelations\n} from \"@rebasepro/common\";\nimport { isPlainObject } from \"@rebasepro/utils\";\nimport { z } from \"zod\";\n\n// extract touched values for nested touched trees and map to current values\nexport function extractTouchedValues(values: unknown, touched: Record<string, boolean>): Record<string, unknown> {\n let acc: Record<string, unknown> = {};\n if (!touched || typeof touched !== \"object\") {\n return acc;\n }\n\n Object.entries(touched).forEach(([key, value]) => {\n if (value) {\n acc = setIn(acc, key, getIn(values, key)) as Record<string, unknown>;\n }\n })\n\n return acc;\n}\n\n/**\n * The edit to carry or back up: each top-level property the user touched,\n * **whole** — the same unit a save writes.\n *\n * `extractTouchedValues` builds a tree of only the touched paths, which is a\n * diff, and a diff cannot say \"this item is gone\": a list that shrank from\n * three items to one, or a key-value map with a key deleted, came back whole\n * when the diff was merged onto the stored record. Carrying the property whole\n * and overlaying it (see {@link overlayEdit}) shows exactly what the user left.\n *\n * Which properties count is still decided by the touched tree with its ghost\n * containers removed, so a field merely focused carries nothing.\n */\nexport function getTouchedPropertyValues<M extends Record<string, unknown>>(\n values: Partial<M>,\n touched: Record<string, boolean>\n): Partial<M> {\n const touchedTree = removeEmptyContainers(extractTouchedValues(values, touched ?? {}));\n const result: Record<string, unknown> = {};\n if (!touchedTree || typeof touchedTree !== \"object\") return result as Partial<M>;\n for (const key of Object.keys(touchedTree)) {\n if (Object.prototype.hasOwnProperty.call(values, key)) {\n result[key] = (values as Record<string, unknown>)[key];\n }\n }\n return result as Partial<M>;\n}\n\n/**\n * What a form shows when an edit is laid over `base`: each property the edit\n * carries replaces the base's, whole.\n *\n * Not `mergeDeep`, which merged arrays of maps index by index and kept the base\n * items past the edit's length, and kept map keys the edit had dropped — so a\n * deleted section or key came back when the edit changed layout or a draft was\n * restored, in a form that then read as clean.\n */\nexport function overlayEdit<M extends Record<string, unknown>>(base: Partial<M>, edit: Partial<M>): Partial<M> {\n return { ...base, ...edit };\n}\n\n/**\n * Recursively removes empty plain objects `{}` and empty arrays `[]` from a value tree.\n * This prevents ghost containers created by `setIn` intermediate path construction\n * (e.g. `{ address: {} }` when only `address.city` was touched but value is undefined)\n * from falsely triggering the unsaved local changes indicator.\n */\n/**\n * Check if a value is semantically empty (null, undefined, or empty string).\n */\nfunction isSemanticEmpty(v: unknown): boolean {\n return v === null || v === undefined || v === \"\";\n}\n\nexport function removeEmptyContainers(obj: unknown): unknown {\n if (Array.isArray(obj)) {\n const cleaned = obj.map(removeEmptyContainers);\n // Keep arrays even if they contain only nulls/undefined — that's intentional data\n return cleaned;\n }\n if (obj && typeof obj === \"object\" && Object.getPrototypeOf(obj) === Object.prototype) {\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n const cleaned = removeEmptyContainers((obj as Record<string, unknown>)[key]);\n // Skip empty plain objects\n if (cleaned && typeof cleaned === \"object\" && !Array.isArray(cleaned)\n && Object.getPrototypeOf(cleaned) === Object.prototype\n && Object.keys(cleaned).length === 0) {\n continue;\n }\n result[key] = cleaned;\n }\n // After cleaning, check if all remaining values are semantically empty\n // (null, undefined, or \"\"). This catches ghost objects like {type: \"\", value: null}\n // created by oneOf block initialization that aren't meaningful changes.\n if (Object.keys(result).length > 0 && Object.values(result).every(isSemanticEmpty)) {\n return {};\n }\n return result;\n }\n return obj;\n}\n\nexport function getChanges<T extends object>(source: Partial<T>, comparison: Partial<T>): Partial<T> {\n const changes: Partial<T> = {};\n\n if (!source) {\n return {};\n }\n if (!comparison) {\n return source;\n }\n\n const allKeys = Array.from(new Set([...Object.keys(source), ...Object.keys(comparison)]));\n\n for (const key of allKeys) {\n const sourceValue = (source as Record<string, unknown>)[key];\n const comparisonValue = (comparison as Record<string, unknown>)[key];\n\n if (equal(sourceValue, comparisonValue)) {\n continue;\n }\n\n const sourceHasKey = source && typeof source === \"object\" && Object.prototype.hasOwnProperty.call(source, key);\n const comparisonHasKey = comparison && typeof comparison === \"object\" && Object.prototype.hasOwnProperty.call(comparison, key);\n\n if (comparisonHasKey && !sourceHasKey) {\n (changes as Record<string, unknown>)[key] = undefined;\n } else if (Array.isArray(sourceValue)) {\n const comparisonArray = Array.isArray(comparisonValue) ? comparisonValue : [];\n if (sourceValue.length !== comparisonArray.length) {\n (changes as Record<string, unknown>)[key] = sourceValue;\n continue;\n }\n const hasChanges = sourceValue.some((item, index) => !equal(item, comparisonArray[index]));\n if (hasChanges) {\n (changes as Record<string, unknown>)[key] = sourceValue;\n }\n } else if (isPlainObject(sourceValue) && isPlainObject(comparisonValue)) {\n // Plain objects only. A `Date` has no keys of its own, so walking\n // into two different dates finds nothing and loses the edit; a\n // class instance (a relation) would come back as a bare `{ id }`\n // that no longer says what it is.\n const nestedChanges = getChanges(sourceValue, comparisonValue);\n if (Object.keys(nestedChanges).length > 0) {\n (changes as Record<string, unknown>)[key] = nestedChanges;\n }\n } else {\n (changes as Record<string, unknown>)[key] = sourceValue;\n }\n }\n\n return changes;\n}\n\n/**\n * What an update of a stored record sends: every top-level property whose value\n * differs from the stored one — whole.\n *\n * Whole, because that is the unit an update replaces. It sets each property it\n * carries, so the value sent *is* the property's new value: a map sent as the\n * one key that changed would erase every key left out, a key-value map with a\n * key removed would arrive empty, and a geopoint with one coordinate moved is\n * refused for lacking the other. {@link getChanges} walks into plain objects to\n * find what changed inside them, which is right for comparing a draft with the\n * form and wrong for a write.\n */\nexport function getChangedProperties<M extends Record<string, unknown>>(\n values: Partial<M>,\n storedValues: Partial<M>\n): Partial<M> {\n const changes: Partial<M> = {};\n const keys = new Set([...Object.keys(values), ...Object.keys(storedValues)]);\n for (const key of keys) {\n if (!equal(values[key], storedValues[key])) {\n (changes as Record<string, unknown>)[key] = values[key];\n }\n }\n return changes;\n}\n\n/**\n * What a create sends: the form's values without the empty ones nobody set.\n *\n * A key the form opened as `null` and still holds as `null` is not a value\n * the user chose. Sent, it is an explicit `NULL`, which beats the column's\n * `DEFAULT` — `published_at timestamptz DEFAULT now()` was created empty from\n * the panel and filled from the API. Left out, the database fills it. A\n * `null` the user set over an opening value (a declared default) is sent, and\n * so is every non-null value, `false` and `[]` included.\n */\nexport function withoutUnsetNulls<M extends Record<string, unknown>>(\n values: M,\n openingValues: Partial<M> | undefined\n): M {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) {\n const opening = openingValues?.[key];\n if ((value === null || value === undefined) && (opening === null || opening === undefined)) continue;\n result[key] = value;\n }\n return result as M;\n}\n\n/**\n * What the local-changes backup still has to offer, given what the form is\n * already showing — the answer the \"unsaved local changes\" banner is asking for.\n * `undefined` means there is nothing left to apply, and no banner.\n *\n * Measured against what the form *opens showing*, not against the stored\n * record. The banner exists to offer a draft the form is not already displaying,\n * and an edit carried across a change of layout is in both the backup and the\n * form: measuring against the stored values alone offered to restore the values\n * already on screen, over an edit the user had never left.\n */\nexport function getUnappliedLocalChanges<M extends Record<string, unknown>>(\n backupValues: Partial<M>,\n openingValues: Partial<M>\n): Partial<M> | undefined {\n if (!backupValues || typeof backupValues !== \"object\") return undefined;\n // The backup holds whole properties (see `getTouchedPropertyValues`), so\n // each one is compared whole and offered whole: a diff of it could not say\n // that a key was deleted, and `overlayEdit` lays down what it is given as\n // the property's entire value.\n const unapplied: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(backupValues)) {\n if (!equal(value, (openingValues as Record<string, unknown> | undefined)?.[key])) {\n unapplied[key] = value;\n }\n }\n return Object.keys(unapplied).length > 0 ? unapplied as Partial<M> : undefined;\n}\n\n/**\n * What travels when the same record changes layout — the split's \"hide list\",\n * full screen's \"show list\", the side panel's \"open full screen\". One mounted\n * form is replaced by another showing the same record, so the edit in progress\n * has to be handed over; left to the local-changes backup alone, the new form\n * met it as a draft from a closed tab and raised the \"unsaved local changes\"\n * banner over changes the user had made a second earlier and never left.\n *\n * Returns `undefined` when there is nothing to carry, which is its own answer: a\n * record nobody edited must open in the next layout exactly as clean as it was.\n *\n * Only what was edited here travels, keyed by `touched` — the same subset the\n * backup stores. Carrying the whole record instead marks every field touched in\n * the receiving form, which lights up every empty required field as an error and\n * writes the entire record back out as a \"local change\".\n */\nexport function getEditHandoffValues<M extends Record<string, unknown>>({\n status,\n dirty,\n values,\n touched,\n storedValues\n}: {\n status: EntityStatus;\n /** Whether `values` differ from what is stored. */\n dirty: boolean;\n values: Partial<M>;\n touched: Record<string, boolean>;\n /** The stored record, for the fallback below. Absent for a new one. */\n storedValues?: Partial<M>;\n}): Partial<M> | undefined {\n\n if (!values) return undefined;\n\n // A record with nothing stored behind it carries whole: there is no\n // baseline to fall back to, so anything not carried is simply lost.\n if (status === \"new\" || status === \"copy\") {\n return Object.keys(values).length > 0 ? values : undefined;\n }\n\n if (!dirty) return undefined;\n\n const touchedValues = getTouchedPropertyValues(values, touched ?? {});\n if (Object.keys(touchedValues).length > 0) {\n return touchedValues;\n }\n\n // Dirty with nothing touched — a value set programmatically, by a plugin or\n // a custom field that writes through `setFieldValue` without the blur that\n // marks it. Diffing against the stored record still finds it, and dropping\n // it here would hand over a form that opens clean over an edit.\n const changes = getChangedProperties(values, storedValues ?? {});\n return Object.keys(changes).length > 0 ? changes : undefined;\n}\n\n/**\n * A new record's values with each top-level `conditions.defaultValue` applied —\n * the rule evaluated against the declared defaults, as a new record has nothing\n * else yet. Without it the rule was documented, editable in Studio, and never\n * read: a new record opened with the static default.\n */\nfunction withConditionalDefaults<M extends Record<string, unknown>>(\n values: Partial<EntityValues<M>>,\n properties: AdminCollection[\"properties\"],\n path: string,\n authController: AuthController\n): Partial<EntityValues<M>> {\n let result = values;\n for (const [key, property] of Object.entries(properties ?? {})) {\n const rule = property?.conditions?.defaultValue;\n if (rule === undefined) continue;\n const context = buildConditionContext({\n propertyKey: key,\n values: values as Record<string, unknown>,\n path,\n authController\n });\n result = { ...result, [key]: evaluateCondition(rule, context) };\n }\n return result;\n}\n\n/**\n * `alwaysApplyDefaultValues`: a property's declared `defaultValue` fills a\n * stored value that is empty, inside maps too.\n *\n * A Postgres row carries every column, an unset one as `null`, so merging the\n * defaults *under* the row let `null` win and the flag did nothing. `false`,\n * `0` and `\"\"` are values the row holds, and are kept.\n */\nfunction fillDeclaredDefaults(properties: AdminCollection[\"properties\"], values: Record<string, unknown>): Record<string, unknown> {\n const result: Record<string, unknown> = { ...values };\n for (const [key, property] of Object.entries(properties ?? {})) {\n if (!property || typeof property !== \"object\" || !(\"type\" in property)) continue;\n const current = result[key];\n if (current === null || current === undefined) {\n if (property.defaultValue !== undefined && property.defaultValue !== null) {\n result[key] = property.defaultValue;\n }\n } else if (property.type === \"map\" && property.properties && isPlainObject(current)) {\n result[key] = fillDeclaredDefaults(property.properties as AdminCollection[\"properties\"], current as Record<string, unknown>);\n }\n }\n return result;\n}\n\nexport function getInitialEntityValues<M extends Record<string, unknown>>(\n authController: AuthController,\n collection: AdminCollection,\n path: string,\n status: \"new\" | \"existing\" | \"copy\",\n entity: Entity<M> | undefined,\n propertyConfigs?: Record<string, PropertyConfig>\n): Partial<EntityValues<M>> {\n const properties = collection.properties;\n if ((status === \"existing\" || status === \"copy\") && entity) {\n let values: Partial<EntityValues<M>>;\n if (!collection.alwaysApplyDefaultValues) {\n values = entity.values ?? getDefaultValuesFor(properties);\n } else {\n values = fillDeclaredDefaults(properties, entity.values ?? {}) as Partial<EntityValues<M>>;\n }\n // A copy gets its own key, and leaves behind every relation it could\n // only take by re-pointing another row — see `getCopyValues`.\n if (status === \"copy\") {\n return getCopyValues(collection, values);\n }\n return values;\n } else if (status === \"new\") {\n return withConditionalDefaults(getDefaultValuesFor(properties), properties, path, authController);\n } else {\n console.error({\n status,\n entity\n });\n throw new Error(\"Form has not been initialised with the correct parameters\");\n }\n}\n\n/**\n * The link back to the parent that a record created under\n * `parent/{id}/{relation}` takes from its address: `{ customer: <the parent> }`\n * for a transaction created from a customer's Transactions tab.\n *\n * The server already stamps the parent's key onto a create through an owned\n * `hasMany`/`hasOne`, so the address alone decides the link. The form did not\n * know that: it opened the child's `belongsTo` empty, and a required one asked\n * the user to pick the record they had just come from.\n *\n * Empty when the address does not decide a link — a root collection, a\n * many-to-many (that link is a junction row, not a property), a `sourceKey`\n * (the value is a column of the parent row, which the address does not carry),\n * or a child with no `belongsTo` on the relation's foreign key.\n */\nexport function getParentLinkValues(\n registry: Pick<CollectionRegistryController, \"getCollection\" | \"getParentEntityIds\">,\n path: string,\n collection: CollectionConfig\n): Record<string, EntityRelation> {\n // Asked of the registry first: only it knows where a slug ends, and a\n // slashed root slug (`content/de-DE/podcasts`) has no parent at all.\n if (registry.getParentEntityIds(path).length === 0) return {};\n\n const segments = path.split(\"/\").filter(Boolean);\n if (segments.length < 3) return {};\n const relationKey = segments[segments.length - 1];\n const parentId = segments[segments.length - 2];\n const parent = registry.getCollection(segments.slice(0, -2).join(\"/\"));\n if (!parent) return {};\n\n const view = getEntityChildViews(parent).find(v => v.key === relationKey);\n if (view?.source.kind !== \"relation\" || view.source.mode !== \"owned\") return {};\n const link = findRelation(resolveCollectionRelations(parent), view.source.relationKey);\n if (!link || (link.kind !== \"hasMany\" && link.kind !== \"hasOne\") || link.sourceKey) return {};\n\n const childRelations = resolveCollectionRelations(collection);\n for (const [key, property] of Object.entries(collection.properties ?? {})) {\n if (property?.type !== \"relation\") continue;\n const relation = childRelations[key];\n if (relation?.kind === \"belongsTo\" && relation.localKey === link.foreignKeyOnTarget) {\n return { [key]: new EntityRelation(parentId, relation.targetSlug) };\n }\n }\n return {};\n}\n\nexport function zodToFormErrors(zodError: z.ZodError): Record<string, string> {\n let errors: Record<string, string> = {};\n for (const issue of zodError.issues) {\n const path = issue.path.join(\".\");\n if (path && !getIn(errors, path)) {\n errors = setIn(errors, path, issue.message) as Record<string, string>;\n }\n }\n return errors;\n}\n\n/**\n * The fields a server refusal names, as form errors keyed by the property each\n * belongs to: `{ title: \"…\", address: \"…\" }`.\n *\n * The server answers a write it refuses with `details.violations` —\n * `[{ field, code, message }]`, `field` the wire path (`address.city`,\n * `tags[2]`). The form printed the sentence in its footer and marked no\n * field, so a unique 409 or a rule only the server checks left the user\n * hunting for the input. A path is marked on its top-level property, which is\n * the field the form shows; a field the form does not have is left out. The\n * first message for a property wins.\n */\nexport function serverViolationErrors(error: unknown, propertyKeys: readonly string[]): Record<string, string> {\n const errors: Record<string, string> = {};\n if (typeof error !== \"object\" || error === null || !(\"details\" in error)) return errors;\n const details = error.details;\n if (typeof details !== \"object\" || details === null || !(\"violations\" in details)) return errors;\n const violations = details.violations;\n if (!Array.isArray(violations)) return errors;\n for (const violation of violations) {\n if (typeof violation !== \"object\" || violation === null) continue;\n if (!(\"field\" in violation) || !(\"message\" in violation)) continue;\n const { field, message } = violation;\n if (typeof field !== \"string\" || typeof message !== \"string\") continue;\n const property = field.split(/[.[]/)[0];\n if (!propertyKeys.includes(property) || property in errors) continue;\n errors[property] = message;\n }\n return errors;\n}\n"],"mappings":";;;;;;AAoBA,SAAgB,qBAAqB,QAAiB,SAA2D;CAC7G,IAAI,MAA+B,CAAC;CACpC,IAAI,CAAC,WAAW,OAAO,YAAY,UAC/B,OAAO;CAGX,OAAO,QAAQ,OAAO,CAAC,CAAC,SAAS,CAAC,KAAK,WAAW;EAC9C,IAAI,OACA,MAAM,MAAM,KAAK,KAAK,MAAM,QAAQ,GAAG,CAAC;CAEhD,CAAC;CAED,OAAO;AACX;;;;;;;;;;;;;;AAeA,SAAgB,yBACZ,QACA,SACU;CACV,MAAM,cAAc,sBAAsB,qBAAqB,QAAQ,WAAW,CAAC,CAAC,CAAC;CACrF,MAAM,SAAkC,CAAC;CACzC,IAAI,CAAC,eAAe,OAAO,gBAAgB,UAAU,OAAO;CAC5D,KAAK,MAAM,OAAO,OAAO,KAAK,WAAW,GACrC,IAAI,OAAO,UAAU,eAAe,KAAK,QAAQ,GAAG,GAChD,OAAO,OAAQ,OAAmC;CAG1D,OAAO;AACX;;;;;;;;;;AAWA,SAAgB,YAA+C,MAAkB,MAA8B;CAC3G,OAAO;EAAE,GAAG;EAAM,GAAG;CAAK;AAC9B;;;;;;;;;;AAWA,SAAS,gBAAgB,GAAqB;CAC1C,OAAO,MAAM,QAAQ,MAAM,KAAA,KAAa,MAAM;AAClD;AAEA,SAAgB,sBAAsB,KAAuB;CACzD,IAAI,MAAM,QAAQ,GAAG,GAGjB,OAFgB,IAAI,IAAI,qBAEjB;CAEX,IAAI,OAAO,OAAO,QAAQ,YAAY,OAAO,eAAe,GAAG,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ding } from "./field_bindings/VectorFieldBinding.js";
21
21
  export * from "./components/index.js";
22
22
  export { PropertyFieldBinding } from "./PropertyFieldBinding.js";
23
23
  export * from "./useClearRestoreValue.js";
24
- export { extractTouchedValues, removeEmptyContainers, getChanges, getInitialEntityValues, zodToFormErrors } from "./form_utils.js";
24
+ export { extractTouchedValues, removeEmptyContainers, getChanges, getInitialEntityValues, zodToFormErrors, getParentLinkValues, getTouchedPropertyValues, getUnappliedLocalChanges, overlayEdit } from "./form_utils.js";
@@ -0,0 +1,23 @@
1
+ import type { Property } from "@rebasepro/types";
2
+ import type { PropertyConfig } from "@rebasepro/cms-types";
3
+ /**
4
+ * Whether the form leaves this property's label to its binding, which draws it
5
+ * inside the control.
6
+ *
7
+ * Decided from the declared property, as `isSelfLabellingProperty` is. Anything
8
+ * the form cannot vouch for keeps the label above, where `FieldBlock` draws it
9
+ * whatever the editor renders: a custom `admin.Field`, a custom property config,
10
+ * and a built-in editor a plugin has replaced through `propertyConfigs`.
11
+ */
12
+ export declare function labelsInsideControl(property: Property, propertyConfigs?: Record<string, PropertyConfig>): boolean;
13
+ /**
14
+ * Whether a read-only value is one line, and so drawn like the one-line fields
15
+ * around it: a box of the same height with the label inside.
16
+ *
17
+ * Read-only properties are rendered by `ReadOnlyFieldBinding` whatever their
18
+ * type, so this asks of the value what `LABEL_INSIDE_FIELDS` asks of the
19
+ * editor. A computed subtotal paired with an editable tax amount is the case it
20
+ * exists for — with the label above, its box sat a label's height lower than
21
+ * the one beside it.
22
+ */
23
+ export declare function readOnlyLabelsInside(property: Property): boolean;
@@ -0,0 +1,71 @@
1
+ import { getFieldId } from "../components/field_ids.js";
2
+ import { isReadOnly } from "@rebasepro/app";
3
+ //#region src/form/label_placement.ts
4
+ /**
5
+ * Where a record-form field's label goes: inside its own box, or above it.
6
+ *
7
+ * A one-line control carries its label inside, the way FireCMS draws a field:
8
+ * a filled box, the label shrunk into its top edge, the value under it. Text,
9
+ * numbers, dates, switches and single selects are all one line, so they come
10
+ * out the same height, and two of them paired on a row line up box to box.
11
+ *
12
+ * Everything else keeps the label above, drawn by `FieldBlock`: a multi-select
13
+ * (its chips wrap onto more lines, and a label sitting on the first of them
14
+ * reads as one more chip), uploads, markdown, relations and references, and the
15
+ * panel editors, which carry a header of their own.
16
+ *
17
+ * Not exported from the package. Which editor draws its label where is the
18
+ * form's own decision, and it has to stay in step with the bindings: the ones
19
+ * listed here render their label inside when the form does not set
20
+ * `hideLabel`.
21
+ */
22
+ var LABEL_INSIDE_FIELDS = /* @__PURE__ */ new Set([
23
+ "text_field",
24
+ "multiline",
25
+ "url",
26
+ "email",
27
+ "number_input",
28
+ "select",
29
+ "number_select",
30
+ "date_time",
31
+ "switch"
32
+ ]);
33
+ /**
34
+ * Whether the form leaves this property's label to its binding, which draws it
35
+ * inside the control.
36
+ *
37
+ * Decided from the declared property, as `isSelfLabellingProperty` is. Anything
38
+ * the form cannot vouch for keeps the label above, where `FieldBlock` draws it
39
+ * whatever the editor renders: a custom `admin.Field`, a custom property config,
40
+ * and a built-in editor a plugin has replaced through `propertyConfigs`.
41
+ */
42
+ function labelsInsideControl(property, propertyConfigs) {
43
+ if (property.admin?.Field) return false;
44
+ if (isReadOnly(property)) return readOnlyLabelsInside(property);
45
+ const fieldId = getFieldId(property);
46
+ if (!fieldId || !LABEL_INSIDE_FIELDS.has(fieldId)) return false;
47
+ if (propertyConfigs?.[fieldId]?.property.admin?.Field) return false;
48
+ return true;
49
+ }
50
+ /**
51
+ * Whether a read-only value is one line, and so drawn like the one-line fields
52
+ * around it: a box of the same height with the label inside.
53
+ *
54
+ * Read-only properties are rendered by `ReadOnlyFieldBinding` whatever their
55
+ * type, so this asks of the value what `LABEL_INSIDE_FIELDS` asks of the
56
+ * editor. A computed subtotal paired with an editable tax amount is the case it
57
+ * exists for — with the label above, its box sat a label's height lower than
58
+ * the one beside it.
59
+ */
60
+ function readOnlyLabelsInside(property) {
61
+ switch (property.type) {
62
+ case "number":
63
+ case "date": return true;
64
+ case "string": return !property.admin?.markdown && !property.admin?.multiline && !property.storage;
65
+ default: return false;
66
+ }
67
+ }
68
+ //#endregion
69
+ export { labelsInsideControl, readOnlyLabelsInside };
70
+
71
+ //# sourceMappingURL=label_placement.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"label_placement.js","names":[],"sources":["../../src/form/label_placement.ts"],"sourcesContent":["import type { Property } from \"@rebasepro/types\";\nimport type { PropertyConfig } from \"@rebasepro/cms-types\";\nimport { isReadOnly } from \"@rebasepro/app\";\nimport { getFieldId } from \"../components/field_ids\";\n\n/**\n * Where a record-form field's label goes: inside its own box, or above it.\n *\n * A one-line control carries its label inside, the way FireCMS draws a field:\n * a filled box, the label shrunk into its top edge, the value under it. Text,\n * numbers, dates, switches and single selects are all one line, so they come\n * out the same height, and two of them paired on a row line up box to box.\n *\n * Everything else keeps the label above, drawn by `FieldBlock`: a multi-select\n * (its chips wrap onto more lines, and a label sitting on the first of them\n * reads as one more chip), uploads, markdown, relations and references, and the\n * panel editors, which carry a header of their own.\n *\n * Not exported from the package. Which editor draws its label where is the\n * form's own decision, and it has to stay in step with the bindings: the ones\n * listed here render their label inside when the form does not set\n * `hideLabel`.\n */\nconst LABEL_INSIDE_FIELDS: ReadonlySet<string> = new Set([\n \"text_field\",\n \"multiline\",\n \"url\",\n \"email\",\n \"number_input\",\n \"select\",\n \"number_select\",\n \"date_time\",\n \"switch\"\n]);\n\n/**\n * Whether the form leaves this property's label to its binding, which draws it\n * inside the control.\n *\n * Decided from the declared property, as `isSelfLabellingProperty` is. Anything\n * the form cannot vouch for keeps the label above, where `FieldBlock` draws it\n * whatever the editor renders: a custom `admin.Field`, a custom property config,\n * and a built-in editor a plugin has replaced through `propertyConfigs`.\n */\nexport function labelsInsideControl(\n property: Property,\n propertyConfigs?: Record<string, PropertyConfig>\n): boolean {\n if (property.admin?.Field) return false;\n if (isReadOnly(property)) return readOnlyLabelsInside(property);\n const fieldId = getFieldId(property);\n if (!fieldId || !LABEL_INSIDE_FIELDS.has(fieldId)) return false;\n if (propertyConfigs?.[fieldId]?.property.admin?.Field) return false;\n return true;\n}\n\n/**\n * Whether a read-only value is one line, and so drawn like the one-line fields\n * around it: a box of the same height with the label inside.\n *\n * Read-only properties are rendered by `ReadOnlyFieldBinding` whatever their\n * type, so this asks of the value what `LABEL_INSIDE_FIELDS` asks of the\n * editor. A computed subtotal paired with an editable tax amount is the case it\n * exists for — with the label above, its box sat a label's height lower than\n * the one beside it.\n */\nexport function readOnlyLabelsInside(property: Property): boolean {\n switch (property.type) {\n case \"number\":\n case \"date\":\n return true;\n case \"string\":\n return !property.admin?.markdown\n && !property.admin?.multiline\n && !property.storage;\n default:\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuBA,IAAM,sCAA2C,IAAI,IAAI;CACrD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ,CAAC;;;;;;;;;;AAWD,SAAgB,oBACZ,UACA,iBACO;CACP,IAAI,SAAS,OAAO,OAAO,OAAO;CAClC,IAAI,WAAW,QAAQ,GAAG,OAAO,qBAAqB,QAAQ;CAC9D,MAAM,UAAU,WAAW,QAAQ;CACnC,IAAI,CAAC,WAAW,CAAC,oBAAoB,IAAI,OAAO,GAAG,OAAO;CAC1D,IAAI,kBAAkB,QAAQ,EAAE,SAAS,OAAO,OAAO,OAAO;CAC9D,OAAO;AACX;;;;;;;;;;;AAYA,SAAgB,qBAAqB,UAA6B;CAC9D,QAAQ,SAAS,MAAjB;EACI,KAAK;EACL,KAAK,QACD,OAAO;EACX,KAAK,UACD,OAAO,CAAC,SAAS,OAAO,YACjB,CAAC,SAAS,OAAO,aACjB,CAAC,SAAS;EACrB,SACI,OAAO;CACf;AACJ"}
@@ -1,8 +1,9 @@
1
- import type { Properties, Property } from "@rebasepro/types";
2
- import type { ResolvePropertyProps } from "@rebasepro/common";
1
+ import type { AuthState, Properties, Property } from "@rebasepro/types";
2
+ import type { FieldViewer, ResolvePropertyProps } from "@rebasepro/common";
3
3
  /**
4
4
  * A property as the record form shows it and judges it, given the values the
5
- * form holds now: its `dynamicProps` applied, then its `conditions`.
5
+ * form holds now: its `dynamicProps` applied, then its `conditions`, then the
6
+ * signed-in user's field access (see {@link applyFieldAccess}).
6
7
  *
7
8
  * One function for both, so what a field looks like and what the save checks
8
9
  * cannot drift apart. They had: the field was resolved through `dynamicProps`
@@ -11,6 +12,37 @@ import type { ResolvePropertyProps } from "@rebasepro/common";
11
12
  * by the collection editor (and taught by the docs) did nothing anywhere.
12
13
  */
13
14
  export declare function resolveFormProperty<M extends Record<string, unknown> = Record<string, unknown>>(props: ResolvePropertyProps<M>): Property | null;
15
+ /**
16
+ * The signed-in user as a field rule judges them — the roles the condition
17
+ * context reads too, so `hasRole` and `access` agree on who is asking.
18
+ *
19
+ * Always a viewer, never `undefined`: `undefined` is the trusted server plane,
20
+ * which satisfies every non-empty rule. Nobody signed in is a viewer with no
21
+ * roles.
22
+ */
23
+ export declare function formViewer(authController: AuthState): FieldViewer;
24
+ /**
25
+ * `property.access` in the form, which is where the user meets it.
26
+ *
27
+ * The server enforces it either way — it strips a field the caller cannot
28
+ * read and refuses a write naming one they cannot set. The form did not read
29
+ * it, so a field the user could not write was an ordinary input whose edit
30
+ * came back as a 400 on save, and a field they could not read was an empty
31
+ * input inviting them to fill it. A field they cannot read is hidden; one they
32
+ * can read but not write is shown read-only.
33
+ */
34
+ export declare function applyFieldAccess(property: Property, viewer: FieldViewer): Property;
35
+ /**
36
+ * A new record's or a copy's values without the fields this user may not
37
+ * write that still hold what the form opened with.
38
+ *
39
+ * The form shows such a field read-only, so its value there is a default or
40
+ * the original record's — not an edit — and the server refuses a whole save
41
+ * that names it. A value that did change (a callback or plugin set it) is
42
+ * kept, and the server's refusal says why the save failed: dropping it would
43
+ * report success for an edit that did not happen.
44
+ */
45
+ export declare function withoutUnwritableDefaults<M extends Record<string, unknown>>(values: Partial<M>, openedWith: Partial<M>, properties: Properties, viewer: FieldViewer): Partial<M>;
14
46
  /**
15
47
  * The properties the form validates on submit: each resolved against `values`
16
48
  * (see {@link resolveFormProperty}), inside maps too, and only those the user
@@ -1,9 +1,11 @@
1
- import { buildConditionContext, resolveProperty } from "@rebasepro/common";
1
+ import { deepEqual } from "fast-equals";
2
+ import { buildConditionContext, canReadField, canWriteField, resolveProperty } from "@rebasepro/common";
2
3
  import { applyPropertyConditions, isDisabled, isHidden, isReadOnly } from "@rebasepro/app";
3
4
  //#region src/form/resolve_form_properties.ts
4
5
  /**
5
6
  * A property as the record form shows it and judges it, given the values the
6
- * form holds now: its `dynamicProps` applied, then its `conditions`.
7
+ * form holds now: its `dynamicProps` applied, then its `conditions`, then the
8
+ * signed-in user's field access (see {@link applyFieldAccess}).
7
9
  *
8
10
  * One function for both, so what a field looks like and what the save checks
9
11
  * cannot drift apart. They had: the field was resolved through `dynamicProps`
@@ -13,8 +15,8 @@ import { applyPropertyConditions, isDisabled, isHidden, isReadOnly } from "@reba
13
15
  */
14
16
  function resolveFormProperty(props) {
15
17
  const resolved = resolveProperty(props);
16
- if (!resolved?.conditions) return resolved;
17
- return applyPropertyConditions(resolved, buildConditionContext({
18
+ if (!resolved) return resolved;
19
+ return applyFieldAccess(resolved.conditions ? applyPropertyConditions(resolved, buildConditionContext({
18
20
  propertyKey: props.propertyKey,
19
21
  values: props.values,
20
22
  previousValues: props.previousValues,
@@ -22,7 +24,66 @@ function resolveFormProperty(props) {
22
24
  entityId: props.entityId === void 0 ? void 0 : String(props.entityId),
23
25
  index: props.index,
24
26
  authController: props.authController
25
- }));
27
+ })) : resolved, formViewer(props.authController));
28
+ }
29
+ /**
30
+ * The signed-in user as a field rule judges them — the roles the condition
31
+ * context reads too, so `hasRole` and `access` agree on who is asking.
32
+ *
33
+ * Always a viewer, never `undefined`: `undefined` is the trusted server plane,
34
+ * which satisfies every non-empty rule. Nobody signed in is a viewer with no
35
+ * roles.
36
+ */
37
+ function formViewer(authController) {
38
+ return { roles: (authController.user?.roles ?? []).map((r) => typeof r === "string" ? r : r.id) };
39
+ }
40
+ /**
41
+ * `property.access` in the form, which is where the user meets it.
42
+ *
43
+ * The server enforces it either way — it strips a field the caller cannot
44
+ * read and refuses a write naming one they cannot set. The form did not read
45
+ * it, so a field the user could not write was an ordinary input whose edit
46
+ * came back as a 400 on save, and a field they could not read was an empty
47
+ * input inviting them to fill it. A field they cannot read is hidden; one they
48
+ * can read but not write is shown read-only.
49
+ */
50
+ function applyFieldAccess(property, viewer) {
51
+ if (!canReadField(property, viewer)) return {
52
+ ...property,
53
+ conditions: {
54
+ ...property.conditions,
55
+ hidden: true
56
+ }
57
+ };
58
+ if (!canWriteField(property, viewer)) return {
59
+ ...property,
60
+ admin: {
61
+ ...property.admin,
62
+ readOnly: true
63
+ }
64
+ };
65
+ return property;
66
+ }
67
+ /**
68
+ * A new record's or a copy's values without the fields this user may not
69
+ * write that still hold what the form opened with.
70
+ *
71
+ * The form shows such a field read-only, so its value there is a default or
72
+ * the original record's — not an edit — and the server refuses a whole save
73
+ * that names it. A value that did change (a callback or plugin set it) is
74
+ * kept, and the server's refusal says why the save failed: dropping it would
75
+ * report success for an edit that did not happen.
76
+ */
77
+ function withoutUnwritableDefaults(values, openedWith, properties, viewer) {
78
+ let result;
79
+ for (const key of Object.keys(values)) {
80
+ const property = properties[key];
81
+ if (!property || canWriteField(property, viewer)) continue;
82
+ if (!deepEqual(values[key], openedWith[key])) continue;
83
+ result ??= { ...values };
84
+ delete result[key];
85
+ }
86
+ return result ?? values;
26
87
  }
27
88
  /**
28
89
  * Whether the user can change this field in the form at all. A field the form
@@ -73,6 +134,6 @@ function resolvePropertiesForValidation({ properties, propertyKey, isNew, ...pro
73
134
  return result;
74
135
  }
75
136
  //#endregion
76
- export { resolveFormProperty, resolvePropertiesForValidation };
137
+ export { applyFieldAccess, formViewer, resolveFormProperty, resolvePropertiesForValidation, withoutUnwritableDefaults };
77
138
 
78
139
  //# sourceMappingURL=resolve_form_properties.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolve_form_properties.js","names":[],"sources":["../../src/form/resolve_form_properties.ts"],"sourcesContent":["import type { Properties, Property } from \"@rebasepro/types\";\nimport type { ResolvePropertyProps } from \"@rebasepro/common\";\nimport { buildConditionContext, resolveProperty } from \"@rebasepro/common\";\nimport { applyPropertyConditions, isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\n\n/**\n * A property as the record form shows it and judges it, given the values the\n * form holds now: its `dynamicProps` applied, then its `conditions`.\n *\n * One function for both, so what a field looks like and what the save checks\n * cannot drift apart. They had: the field was resolved through `dynamicProps`\n * and nothing else, and the save was judged against the raw declaration — so a\n * `dynamicProps` validation was never checked, and a `conditions` rule written\n * by the collection editor (and taught by the docs) did nothing anywhere.\n */\nexport function resolveFormProperty<M extends Record<string, unknown> = Record<string, unknown>>(\n props: ResolvePropertyProps<M>\n): Property | null {\n const resolved = resolveProperty(props);\n if (!resolved?.conditions) return resolved;\n return applyPropertyConditions(resolved, buildConditionContext({\n propertyKey: props.propertyKey,\n values: props.values,\n previousValues: props.previousValues,\n path: props.path ?? \"\",\n entityId: props.entityId === undefined ? undefined : String(props.entityId),\n index: props.index,\n authController: props.authController\n }));\n}\n\n/**\n * Whether the user can change this field in the form at all. A field the form\n * keeps hidden, read-only or disabled cannot be fixed from it, so it is not the\n * form's to judge: holding the save against it left \"Please fix the\n * highlighted errors\" over a form with nothing highlighted. The server's own\n * checks — `required`, `NOT NULL` — still hold for it.\n */\nfunction isEditableInForm(property: Property): boolean {\n return !isHidden(property) && !isReadOnly(property) && !isDisabled(property);\n}\n\n/**\n * The properties the form validates on submit: each resolved against `values`\n * (see {@link resolveFormProperty}), inside maps too, and only those the user\n * can change.\n */\nexport function resolvePropertiesForValidation<M extends Record<string, unknown>>({\n properties,\n propertyKey,\n isNew,\n ...props\n}: Omit<ResolvePropertyProps<M>, \"property\"> & {\n properties: Properties;\n /**\n * Whether the record is being created. A field marked\n * `admin.filledByServer` or `databaseDefault` is not required then: the\n * server, or the database, fills it.\n */\n isNew?: boolean;\n}): Properties {\n const result: Record<string, Property> = {};\n for (const [key, raw] of Object.entries(properties as Record<string, Property>)) {\n if (!raw) continue;\n const childKey = propertyKey ? `${propertyKey}.${key}` : key;\n const formProperty = resolveFormProperty<M>({\n ...props,\n ignoreMissingFields: true,\n propertyKey: childKey,\n property: raw\n });\n if (!formProperty || !isEditableInForm(formProperty)) continue;\n const filledOnCreate = formProperty.admin?.filledByServer || formProperty.databaseDefault;\n const resolved = isNew && filledOnCreate && formProperty.validation?.required\n ? { ...formProperty, validation: { ...formProperty.validation, required: false } } as Property\n : formProperty;\n if (resolved.type === \"map\" && resolved.properties) {\n // `resolveProperty` walked the children for their `dynamicProps`\n // but not their conditions. Resolving them again applies both; a\n // builder is a function of the values, so applying it twice is\n // applying it once.\n result[key] = {\n ...resolved,\n properties: resolvePropertiesForValidation<M>({\n ...props,\n isNew,\n propertyKey: childKey,\n properties: resolved.properties as Properties\n })\n };\n } else {\n result[key] = resolved;\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,SAAgB,oBACZ,OACe;CACf,MAAM,WAAW,gBAAgB,KAAK;CACtC,IAAI,CAAC,UAAU,YAAY,OAAO;CAClC,OAAO,wBAAwB,UAAU,sBAAsB;EAC3D,aAAa,MAAM;EACnB,QAAQ,MAAM;EACd,gBAAgB,MAAM;EACtB,MAAM,MAAM,QAAQ;EACpB,UAAU,MAAM,aAAa,KAAA,IAAY,KAAA,IAAY,OAAO,MAAM,QAAQ;EAC1E,OAAO,MAAM;EACb,gBAAgB,MAAM;CAC1B,CAAC,CAAC;AACN;;;;;;;;AASA,SAAS,iBAAiB,UAA6B;CACnD,OAAO,CAAC,SAAS,QAAQ,KAAK,CAAC,WAAW,QAAQ,KAAK,CAAC,WAAW,QAAQ;AAC/E;;;;;;AAOA,SAAgB,+BAAkE,EAC9E,YACA,aACA,OACA,GAAG,SASQ;CACX,MAAM,SAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,UAAsC,GAAG;EAC7E,IAAI,CAAC,KAAK;EACV,MAAM,WAAW,cAAc,GAAG,YAAY,GAAG,QAAQ;EACzD,MAAM,eAAe,oBAAuB;GACxC,GAAG;GACH,qBAAqB;GACrB,aAAa;GACb,UAAU;EACd,CAAC;EACD,IAAI,CAAC,gBAAgB,CAAC,iBAAiB,YAAY,GAAG;EACtD,MAAM,iBAAiB,aAAa,OAAO,kBAAkB,aAAa;EAC1E,MAAM,WAAW,SAAS,kBAAkB,aAAa,YAAY,WAC/D;GAAE,GAAG;GAAc,YAAY;IAAE,GAAG,aAAa;IAAY,UAAU;GAAM;EAAE,IAC/E;EACN,IAAI,SAAS,SAAS,SAAS,SAAS,YAKpC,OAAO,OAAO;GACV,GAAG;GACH,YAAY,+BAAkC;IAC1C,GAAG;IACH;IACA,aAAa;IACb,YAAY,SAAS;GACzB,CAAC;EACL;OAEA,OAAO,OAAO;CAEtB;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"resolve_form_properties.js","names":[],"sources":["../../src/form/resolve_form_properties.ts"],"sourcesContent":["import type { AuthState, Properties, Property } from \"@rebasepro/types\";\nimport type { FieldViewer, ResolvePropertyProps } from \"@rebasepro/common\";\nimport { buildConditionContext, canReadField, canWriteField, resolveProperty } from \"@rebasepro/common\";\nimport { deepEqual as equal } from \"fast-equals\";\nimport { applyPropertyConditions, isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\n\n/**\n * A property as the record form shows it and judges it, given the values the\n * form holds now: its `dynamicProps` applied, then its `conditions`, then the\n * signed-in user's field access (see {@link applyFieldAccess}).\n *\n * One function for both, so what a field looks like and what the save checks\n * cannot drift apart. They had: the field was resolved through `dynamicProps`\n * and nothing else, and the save was judged against the raw declaration — so a\n * `dynamicProps` validation was never checked, and a `conditions` rule written\n * by the collection editor (and taught by the docs) did nothing anywhere.\n */\nexport function resolveFormProperty<M extends Record<string, unknown> = Record<string, unknown>>(\n props: ResolvePropertyProps<M>\n): Property | null {\n const resolved = resolveProperty(props);\n if (!resolved) return resolved;\n const conditioned = resolved.conditions\n ? applyPropertyConditions(resolved, buildConditionContext({\n propertyKey: props.propertyKey,\n values: props.values,\n previousValues: props.previousValues,\n path: props.path ?? \"\",\n entityId: props.entityId === undefined ? undefined : String(props.entityId),\n index: props.index,\n authController: props.authController\n }))\n : resolved;\n return applyFieldAccess(conditioned, formViewer(props.authController));\n}\n\n/**\n * The signed-in user as a field rule judges them — the roles the condition\n * context reads too, so `hasRole` and `access` agree on who is asking.\n *\n * Always a viewer, never `undefined`: `undefined` is the trusted server plane,\n * which satisfies every non-empty rule. Nobody signed in is a viewer with no\n * roles.\n */\nexport function formViewer(authController: AuthState): FieldViewer {\n const roles: unknown[] = authController.user?.roles ?? [];\n return { roles: roles.map(r => typeof r === \"string\" ? r : (r as { id: string }).id) };\n}\n\n/**\n * `property.access` in the form, which is where the user meets it.\n *\n * The server enforces it either way — it strips a field the caller cannot\n * read and refuses a write naming one they cannot set. The form did not read\n * it, so a field the user could not write was an ordinary input whose edit\n * came back as a 400 on save, and a field they could not read was an empty\n * input inviting them to fill it. A field they cannot read is hidden; one they\n * can read but not write is shown read-only.\n */\nexport function applyFieldAccess(property: Property, viewer: FieldViewer): Property {\n if (!canReadField(property, viewer)) {\n return { ...property, conditions: { ...property.conditions, hidden: true } } as Property;\n }\n if (!canWriteField(property, viewer)) {\n return { ...property, admin: { ...property.admin, readOnly: true } } as Property;\n }\n return property;\n}\n\n/**\n * A new record's or a copy's values without the fields this user may not\n * write that still hold what the form opened with.\n *\n * The form shows such a field read-only, so its value there is a default or\n * the original record's — not an edit — and the server refuses a whole save\n * that names it. A value that did change (a callback or plugin set it) is\n * kept, and the server's refusal says why the save failed: dropping it would\n * report success for an edit that did not happen.\n */\nexport function withoutUnwritableDefaults<M extends Record<string, unknown>>(\n values: Partial<M>,\n openedWith: Partial<M>,\n properties: Properties,\n viewer: FieldViewer\n): Partial<M> {\n let result: Partial<M> | undefined;\n for (const key of Object.keys(values)) {\n const property = (properties as Record<string, Property | undefined>)[key];\n if (!property || canWriteField(property, viewer)) continue;\n if (!equal(values[key], openedWith[key])) continue;\n result ??= { ...values };\n delete result[key];\n }\n return result ?? values;\n}\n\n/**\n * Whether the user can change this field in the form at all. A field the form\n * keeps hidden, read-only or disabled cannot be fixed from it, so it is not the\n * form's to judge: holding the save against it left \"Please fix the\n * highlighted errors\" over a form with nothing highlighted. The server's own\n * checks — `required`, `NOT NULL` — still hold for it.\n */\nfunction isEditableInForm(property: Property): boolean {\n return !isHidden(property) && !isReadOnly(property) && !isDisabled(property);\n}\n\n/**\n * The properties the form validates on submit: each resolved against `values`\n * (see {@link resolveFormProperty}), inside maps too, and only those the user\n * can change.\n */\nexport function resolvePropertiesForValidation<M extends Record<string, unknown>>({\n properties,\n propertyKey,\n isNew,\n ...props\n}: Omit<ResolvePropertyProps<M>, \"property\"> & {\n properties: Properties;\n /**\n * Whether the record is being created. A field marked\n * `admin.filledByServer` or `databaseDefault` is not required then: the\n * server, or the database, fills it.\n */\n isNew?: boolean;\n}): Properties {\n const result: Record<string, Property> = {};\n for (const [key, raw] of Object.entries(properties as Record<string, Property>)) {\n if (!raw) continue;\n const childKey = propertyKey ? `${propertyKey}.${key}` : key;\n const formProperty = resolveFormProperty<M>({\n ...props,\n ignoreMissingFields: true,\n propertyKey: childKey,\n property: raw\n });\n if (!formProperty || !isEditableInForm(formProperty)) continue;\n const filledOnCreate = formProperty.admin?.filledByServer || formProperty.databaseDefault;\n const resolved = isNew && filledOnCreate && formProperty.validation?.required\n ? { ...formProperty, validation: { ...formProperty.validation, required: false } } as Property\n : formProperty;\n if (resolved.type === \"map\" && resolved.properties) {\n // `resolveProperty` walked the children for their `dynamicProps`\n // but not their conditions. Resolving them again applies both; a\n // builder is a function of the values, so applying it twice is\n // applying it once.\n result[key] = {\n ...resolved,\n properties: resolvePropertiesForValidation<M>({\n ...props,\n isNew,\n propertyKey: childKey,\n properties: resolved.properties as Properties\n })\n };\n } else {\n result[key] = resolved;\n }\n }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B,UAA6B;CACnD,OAAO,CAAC,SAAS,QAAQ,KAAK,CAAC,WAAW,QAAQ,KAAK,CAAC,WAAW,QAAQ;AAC/E;;;;;;AAOA,SAAgB,+BAAkE,EAC9E,YACA,aACA,OACA,GAAG,SASQ;CACX,MAAM,SAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,KAAK,QAAQ,OAAO,QAAQ,UAAsC,GAAG;EAC7E,IAAI,CAAC,KAAK;EACV,MAAM,WAAW,cAAc,GAAG,YAAY,GAAG,QAAQ;EACzD,MAAM,eAAe,oBAAuB;GACxC,GAAG;GACH,qBAAqB;GACrB,aAAa;GACb,UAAU;EACd,CAAC;EACD,IAAI,CAAC,gBAAgB,CAAC,iBAAiB,YAAY,GAAG;EACtD,MAAM,iBAAiB,aAAa,OAAO,kBAAkB,aAAa;EAC1E,MAAM,WAAW,SAAS,kBAAkB,aAAa,YAAY,WAC/D;GAAE,GAAG;GAAc,YAAY;IAAE,GAAG,aAAa;IAAY,UAAU;GAAM;EAAE,IAC/E;EACN,IAAI,SAAS,SAAS,SAAS,SAAS,YAKpC,OAAO,OAAO;GACV,GAAG;GACH,YAAY,+BAAkC;IAC1C,GAAG;IACH;IACA,aAAa;IACb,YAAY,SAAS;GACzB,CAAC;EACL;OAEA,OAAO,OAAO;CAEtB;CACA,OAAO;AACX"}
@@ -17,6 +17,11 @@ export interface UseEntityHistoryResult {
17
17
  /**
18
18
  * Hook to fetch entity history from the backend REST API.
19
19
  * Replaces the old subcollection-based approach with a proper API call.
20
+ *
21
+ * While access is simulated ("Simulate access") every request carries the
22
+ * simulation, as the data views' `client.simulate()` does: the history is read
23
+ * as the simulated identity, and the server refuses a revert as the simulated
24
+ * write it would be.
20
25
  */
21
26
  export declare function useHistory(params: {
22
27
  slug: string;