@rebasepro/cms 0.29.1 → 0.29.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/collection_editor/serializable_types.d.ts +2 -0
  2. package/dist/collection_editor/ui/collection_editor/CollectionRelationsTab.d.ts +1 -1
  3. package/dist/components/CollectionPanel.js +22 -13
  4. package/dist/components/CollectionPanel.js.map +1 -1
  5. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
  6. package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
  7. package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
  8. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +39 -14
  9. package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
  10. package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +11 -0
  11. package/dist/components/CollectionViewBinding/CollectionViewContent.js +19 -2
  12. package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
  13. package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -1
  14. package/dist/components/CollectionViewBinding/EntityCardBinding.js +1 -1
  15. package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
  16. package/dist/components/CollectionViewBinding/SlotValue.js.map +1 -1
  17. package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +19 -1
  18. package/dist/components/CollectionViewBinding/usePreviewSlots.js +18 -7
  19. package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
  20. package/dist/components/EntityPreviewBinding.js.map +1 -1
  21. package/dist/components/HomePage/ContentHomePage.js +2 -3
  22. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  23. package/dist/components/RecordForm.d.ts +25 -4
  24. package/dist/components/RecordForm.js +21 -3
  25. package/dist/components/RecordForm.js.map +1 -1
  26. package/dist/components/RelationSelector.js.map +1 -1
  27. package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +13 -1
  28. package/dist/components/SelectableTable/filters/FilterFieldBinding.js +19 -3
  29. package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
  30. package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
  31. package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
  32. package/dist/components/history/EntityHistoryEntry.js.map +1 -1
  33. package/dist/data_import/utils/save_entities.d.ts +10 -2
  34. package/dist/data_import/utils/save_entities.js.map +1 -1
  35. package/dist/editor/markdown.d.ts +10 -0
  36. package/dist/editor/markdown.js.map +1 -1
  37. package/dist/form/PropertyFieldBinding.js +4 -2
  38. package/dist/form/PropertyFieldBinding.js.map +1 -1
  39. package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
  40. package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
  41. package/dist/hooks/useBuildSidePanel.d.ts +10 -0
  42. package/dist/hooks/useBuildSidePanel.js +43 -4
  43. package/dist/hooks/useBuildSidePanel.js.map +1 -1
  44. package/dist/hooks/useResolvedNavigationFrom.d.ts +14 -2
  45. package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
  46. package/dist/index.d.ts +1 -1
  47. package/dist/index.js +2 -2
  48. package/dist/mcp_view/app_modules.js +4 -2
  49. package/dist/mcp_view/app_modules.js.map +1 -1
  50. package/dist/mcp_view/index.d.ts +1 -1
  51. package/dist/mcp_view/index.js +2 -2
  52. package/dist/mcp_view/index.js.map +1 -1
  53. package/dist/mcp_view/payload.js +7 -2
  54. package/dist/mcp_view/payload.js.map +1 -1
  55. package/dist/mcp_view/screen.js +1 -1
  56. package/dist/mcp_view/screen.js.map +1 -1
  57. package/dist/mcp_view/tool_driver.d.ts +25 -6
  58. package/dist/mcp_view/tool_driver.js +73 -35
  59. package/dist/mcp_view/tool_driver.js.map +1 -1
  60. package/dist/preview/compact_text.d.ts +1 -1
  61. package/dist/preview/compact_text.js.map +1 -1
  62. package/dist/selection/resolve_selection.d.ts +10 -2
  63. package/dist/selection/resolve_selection.js.map +1 -1
  64. package/dist/util/property_utils.d.ts +2 -2
  65. package/dist/util/property_utils.js.map +1 -1
  66. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"EntityHistoryEntry.js","names":[],"sources":["../../../src/components/history/EntityHistoryEntry.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport * as React from \"react\";\n\nimport { ArrowLeftIcon, Chip, cls, defaultBorderMixin, iconSize, Tooltip, Typography } from \"@rebasepro/ui\";\nimport { PreviewSize } from \"../../types/components/PropertyPreviewProps\";\nimport { getPropertyInPath } from \"../../util/property_utils\";\nimport { PropertyPreview } from \"../../preview/PropertyPreview\";\nimport { SkeletonPropertyComponent } from \"../../preview/property_previews/SkeletonPropertyComponent\";\nimport { useAuthController } from \"@rebasepro/app\";\nimport { UserChip } from \"./UserChip\";\nimport { HistoryEntryData } from \"../../hooks\";\nimport { getValueInPath } from \"@rebasepro/utils\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\n/**\n * Recursive deep equality for primitives, arrays and plain objects.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a == null || b == null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return false;\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== (b as unknown[]).length) return false;\n return a.every((item, i) => deepEqual(item, (b as unknown[])[i]));\n }\n\n if (Array.isArray(b)) return false;\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every(key => key in bObj && deepEqual(aObj[key], bObj[key]));\n}\n\nexport type EntityHistoryEntryProps = {\n size: PreviewSize;\n actions?: React.ReactNode;\n collection?: AdminCollection;\n hover?: boolean;\n entry: HistoryEntryData;\n onClick?: (e: React.SyntheticEvent) => void;\n};\n\nfunction PreviousValueView({\n previousValueInPath,\n childProperty,\n propertyKey\n}: {\n previousValueInPath: unknown;\n childProperty: Property;\n propertyKey: string;\n}) {\n if (typeof previousValueInPath === \"string\" || typeof previousValueInPath === \"number\") {\n return <Typography variant={\"caption\"} color={\"secondary\"} className=\"line-through\">\n {previousValueInPath}\n </Typography>;\n } else if (typeof previousValueInPath === \"boolean\") {\n return <Typography variant={\"caption\"} color={\"secondary\"} className=\"line-through\">\n {previousValueInPath ? \"true\" : \"false\"}\n </Typography>;\n } else {\n return <Tooltip\n side={\"left\"}\n title={<div className={\"flex flex-col gap-2\"}>\n <Typography variant={\"caption\"} color={\"secondary\"}>\n Previous value\n </Typography>\n <PropertyPreview\n propertyKey={propertyKey as string}\n value={previousValueInPath as never}\n property={childProperty as Property}\n size={\"small\"}/>\n </div>}>\n <ArrowLeftIcon size={iconSize.smallest} color={\"disabled\"} className={\"mb-1\"}/>\n </Tooltip>\n }\n}\n\n/**\n * Displays a single entity history revision entry.\n * Adapted from the entity_history plugin — now reads from backend API data.\n */\nexport function EntityHistoryEntry({\n actions,\n hover,\n collection,\n size,\n entry\n}: EntityHistoryEntryProps) {\n\n const authController = useAuthController();\n\n // The backend reports the whole row as changed, which includes the columns\n // that cannot meaningfully change: a timestamp it stamps itself on every\n // write, and the primary key, which is what identifies the row being\n // revised. Every revision was listing `updated_at: <now>` and `id: <the id\n // in the title bar>` around the one field the user actually edited.\n const changedFields = React.useMemo(() => {\n const all = entry.changed_fields;\n if (!all || !collection) return all;\n return all.filter(key => {\n const property = getPropertyInPath(collection.properties, key);\n if (!property) return true;\n if (\"isId\" in property && property.isId) return false;\n return !(property.type === \"date\" && \"autoValue\" in property && property.autoValue);\n });\n }, [entry.changed_fields, collection]);\n\n const previousValues = entry.previous_values;\n const updatedOn = new Date(entry.updated_at);\n const updatedBy = entry.updated_by;\n\n // Resolve user display\n const currentUser = authController.user;\n const userDisplay = updatedBy === currentUser?.uid\n ? currentUser\n : undefined;\n\n return <div className={\"@container/histentry w-full flex flex-col gap-2\"}>\n <div className={\"flex items-center flex-wrap gap-2\"}>\n <Typography variant={\"body2\"} color={\"secondary\"}>\n {updatedOn.toLocaleString()}\n </Typography>\n <Chip size={\"small\"}>\n {entry.action}\n </Chip>\n {!userDisplay && updatedBy && <Chip size={\"small\"}>{updatedBy}</Chip>}\n {userDisplay && <UserChip user={userDisplay}/>}\n </div>\n <div\n className={cls(\n \"bg-surface-card\",\n \"min-h-[44px]\",\n \"w-full\",\n \"items-center\",\n hover ? \"hover:bg-surface-hover\" : \"\",\n size === \"small\" ? \"p-1\" : \"px-2 py-1\",\n \"flex border rounded-lg\",\n defaultBorderMixin\n )}>\n\n {actions}\n\n <div className={\"flex flex-col grow w-full m-1 shrink min-w-0\"}>\n\n {changedFields && collection && changedFields.map((key: string) => {\n const childProperty = getPropertyInPath(collection.properties, key);\n const valueInPath = entry.values ? getValueInPath(entry.values, key) : undefined;\n const previousValueInPath = previousValues ? getValueInPath(previousValues, key) : undefined;\n\n const element = childProperty\n ? <PropertyPreview\n propertyKey={key}\n value={valueInPath as never}\n property={childProperty as Property}\n size={\"small\"}/>\n : <Typography variant={\"body2\"}>\n {typeof valueInPath === \"string\" ? valueInPath : JSON.stringify(valueInPath)}\n </Typography>;\n\n // The key column used to be `min-w-[200px] w-1/5` beside a\n // `w-4/5` value — 200px of label and 80% of the row, which\n // adds up to more than the row in anything narrower than a\n // full page. In the inspector that pushed every value off\n // the right edge and wrapped ids one character per line.\n // It stacks until the entry itself is wide enough.\n return (\n <div key={\"ref_prev_\" + key}\n className=\"flex flex-col @sm/histentry:flex-row @sm/histentry:items-baseline gap-x-4 gap-y-0.5 w-full my-1.5\">\n <Typography variant={\"caption\"}\n color={\"secondary\"}\n className=\"shrink-0 break-all @sm/histentry:w-40 @sm/histentry:text-right @sm/histentry:break-normal @sm/histentry:truncate\">\n {key}\n </Typography>\n <div className=\"min-w-0 flex-1 flex flex-col items-start gap-0.5\">\n {previousValueInPath !== undefined && !deepEqual(previousValueInPath, valueInPath) &&\n <PreviousValueView previousValueInPath={previousValueInPath}\n childProperty={childProperty as Property}\n propertyKey={key}/>\n }\n {element}\n </div>\n </div>\n );\n })}\n\n {(!changedFields || changedFields.length === 0) && (\n <Typography variant={\"caption\"} color={\"secondary\"}>\n {entry.action === \"create\" ? \"Entity created\" :\n entry.action === \"delete\" ? \"Entity deleted\" : \"No field changes recorded\"}\n </Typography>\n )}\n\n </div>\n\n </div>\n </div>;\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,SAAS,UAAU,GAAY,GAAqB;CAChD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,KAAK,QAAQ,KAAK,MAAM,OAAO,MAAM;CACzC,IAAI,OAAO,MAAM,OAAO,GAAG,OAAO;CAClC,IAAI,OAAO,MAAM,UAAU,OAAO;CAElC,IAAI,MAAM,QAAQ,CAAC,GAAG;EAClB,IAAI,CAAC,MAAM,QAAQ,CAAC,KAAK,EAAE,WAAY,EAAgB,QAAQ,OAAO;EACtE,OAAO,EAAE,OAAO,MAAM,MAAM,UAAU,MAAO,EAAgB,EAAE,CAAC;CACpE;CAEA,IAAI,MAAM,QAAQ,CAAC,GAAG,OAAO;CAE7B,MAAM,OAAO;CACb,MAAM,OAAO;CACb,MAAM,QAAQ,OAAO,KAAK,IAAI;CAC9B,MAAM,QAAQ,OAAO,KAAK,IAAI;CAC9B,IAAI,MAAM,WAAW,MAAM,QAAQ,OAAO;CAC1C,OAAO,MAAM,OAAM,QAAO,OAAO,QAAQ,UAAU,KAAK,MAAM,KAAK,IAAI,CAAC;AAC5E;AAWA,SAAS,kBAAkB,EACvB,qBACA,eACA,eAKD;CACC,IAAI,OAAO,wBAAwB,YAAY,OAAO,wBAAwB,UAC1E,OAAO,oBAAC,YAAD;EAAY,SAAS;EAAW,OAAO;EAAa,WAAU;YAChE;CACO,CAAA;MACT,IAAI,OAAO,wBAAwB,WACtC,OAAO,oBAAC,YAAD;EAAY,SAAS;EAAW,OAAO;EAAa,WAAU;YAChE,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eAAe,oBAAC,UAAD,EAAU,MAAM,YAAa,CAAA;GAC5C;MACL,qBAAC,OAAD;GACI,WAAW,IACP,mBACA,gBACA,UACA,gBACA,QAAQ,2BAA2B,IACnC,SAAS,UAAU,QAAQ,aAC3B,0BACA,kBACJ;aAVJ,CAYK,SAED,qBAAC,OAAD;IAAK,WAAW;cAAhB,CAEK,iBAAiB,cAAc,cAAc,KAAK,QAAgB;KAC/D,MAAM,gBAAgB,oBAAkB,WAAW,YAAY,GAAG;KAClE,MAAM,cAAc,MAAM,SAAS,eAAe,MAAM,QAAQ,GAAG,IAAI,KAAA;KACvE,MAAM,sBAAsB,iBAAiB,eAAe,gBAAgB,GAAG,IAAI,KAAA;KAEnF,MAAM,UAAU,gBACV,oBAAC,iBAAD;MACE,aAAa;MACb,OAAO;MACP,UAAU;MACV,MAAM;KAAS,CAAA,IACjB,oBAAC,YAAD;MAAY,SAAS;gBAClB,OAAO,gBAAgB,WAAW,cAAc,KAAK,UAAU,WAAW;KACnE,CAAA;KAQhB,OACI,qBAAC,OAAD;MACI,WAAU;gBADd,CAEI,oBAAC,YAAD;OAAY,SAAS;OACjB,OAAO;OACP,WAAU;iBACT;MACO,CAAA,GACZ,qBAAC,OAAD;OAAK,WAAU;iBAAf,CACK,wBAAwB,KAAA,KAAa,CAAC,UAAU,qBAAqB,WAAW,KAC7E,oBAAC,mBAAD;QAAwC;QACrB;QACf,aAAa;OAAK,CAAA,GAEzB,OACA;QACJ;QAfK,cAAc,GAenB;IAEb,CAAC,IAEC,CAAC,iBAAiB,cAAc,WAAW,MACzC,oBAAC,YAAD;KAAY,SAAS;KAAW,OAAO;eAClC,MAAM,WAAW,WAAW,mBACzB,MAAM,WAAW,WAAW,mBAAmB;IAC3C,CAAA,CAGf;KAEJ;IACJ;;AACT"}
1
+ {"version":3,"file":"EntityHistoryEntry.js","names":[],"sources":["../../../src/components/history/EntityHistoryEntry.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport * as React from \"react\";\n\nimport { ArrowLeftIcon, Chip, cls, defaultBorderMixin, iconSize, Tooltip, Typography } from \"@rebasepro/ui\";\nimport { PreviewSize } from \"../../types/components/PropertyPreviewProps\";\nimport { getPropertyInPath } from \"../../util/property_utils\";\nimport { PropertyPreview } from \"../../preview/PropertyPreview\";\nimport { SkeletonPropertyComponent } from \"../../preview/property_previews/SkeletonPropertyComponent\";\nimport { useAuthController } from \"@rebasepro/app\";\nimport { UserChip } from \"./UserChip\";\nimport { HistoryEntryData } from \"../../hooks\";\nimport { getValueInPath } from \"@rebasepro/utils\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\n/**\n * Recursive deep equality for primitives, arrays and plain objects.\n */\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a == null || b == null) return a === b;\n if (typeof a !== typeof b) return false;\n if (typeof a !== \"object\") return false;\n\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== (b as unknown[]).length) return false;\n return a.every((item, i) => deepEqual(item, (b as unknown[])[i]));\n }\n\n if (Array.isArray(b)) return false;\n\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every(key => key in bObj && deepEqual(aObj[key], bObj[key]));\n}\n\nexport type EntityHistoryEntryProps = {\n size: PreviewSize;\n actions?: React.ReactNode;\n collection?: AdminCollection;\n hover?: boolean;\n entry: HistoryEntryData;\n onClick?: (e: React.SyntheticEvent) => void;\n};\n\nfunction PreviousValueView({\n previousValueInPath,\n childProperty,\n propertyKey\n}: {\n previousValueInPath: unknown;\n childProperty: Property;\n propertyKey: string;\n}) {\n if (typeof previousValueInPath === \"string\" || typeof previousValueInPath === \"number\") {\n return <Typography variant={\"caption\"} color={\"secondary\"} className=\"line-through\">\n {previousValueInPath}\n </Typography>;\n } else if (typeof previousValueInPath === \"boolean\") {\n return <Typography variant={\"caption\"} color={\"secondary\"} className=\"line-through\">\n {previousValueInPath ? \"true\" : \"false\"}\n </Typography>;\n } else {\n return <Tooltip\n side={\"left\"}\n title={<div className={\"flex flex-col gap-2\"}>\n <Typography variant={\"caption\"} color={\"secondary\"}>\n Previous value\n </Typography>\n <PropertyPreview\n propertyKey={propertyKey as string}\n value={previousValueInPath}\n property={childProperty as Property}\n size={\"small\"}/>\n </div>}>\n <ArrowLeftIcon size={iconSize.smallest} color={\"disabled\"} className={\"mb-1\"}/>\n </Tooltip>\n }\n}\n\n/**\n * Displays a single entity history revision entry.\n * Adapted from the entity_history plugin — now reads from backend API data.\n */\nexport function EntityHistoryEntry({\n actions,\n hover,\n collection,\n size,\n entry\n}: EntityHistoryEntryProps) {\n\n const authController = useAuthController();\n\n // The backend reports the whole row as changed, which includes the columns\n // that cannot meaningfully change: a timestamp it stamps itself on every\n // write, and the primary key, which is what identifies the row being\n // revised. Every revision was listing `updated_at: <now>` and `id: <the id\n // in the title bar>` around the one field the user actually edited.\n const changedFields = React.useMemo(() => {\n const all = entry.changed_fields;\n if (!all || !collection) return all;\n return all.filter(key => {\n const property = getPropertyInPath(collection.properties, key);\n if (!property) return true;\n if (\"isId\" in property && property.isId) return false;\n return !(property.type === \"date\" && \"autoValue\" in property && property.autoValue);\n });\n }, [entry.changed_fields, collection]);\n\n const previousValues = entry.previous_values;\n const updatedOn = new Date(entry.updated_at);\n const updatedBy = entry.updated_by;\n\n // Resolve user display\n const currentUser = authController.user;\n const userDisplay = updatedBy === currentUser?.uid\n ? currentUser\n : undefined;\n\n return <div className={\"@container/histentry w-full flex flex-col gap-2\"}>\n <div className={\"flex items-center flex-wrap gap-2\"}>\n <Typography variant={\"body2\"} color={\"secondary\"}>\n {updatedOn.toLocaleString()}\n </Typography>\n <Chip size={\"small\"}>\n {entry.action}\n </Chip>\n {!userDisplay && updatedBy && <Chip size={\"small\"}>{updatedBy}</Chip>}\n {userDisplay && <UserChip user={userDisplay}/>}\n </div>\n <div\n className={cls(\n \"bg-surface-card\",\n \"min-h-[44px]\",\n \"w-full\",\n \"items-center\",\n hover ? \"hover:bg-surface-hover\" : \"\",\n size === \"small\" ? \"p-1\" : \"px-2 py-1\",\n \"flex border rounded-lg\",\n defaultBorderMixin\n )}>\n\n {actions}\n\n <div className={\"flex flex-col grow w-full m-1 shrink min-w-0\"}>\n\n {changedFields && collection && changedFields.map((key: string) => {\n const childProperty = getPropertyInPath(collection.properties, key);\n const valueInPath = entry.values ? getValueInPath(entry.values, key) : undefined;\n const previousValueInPath = previousValues ? getValueInPath(previousValues, key) : undefined;\n\n const element = childProperty\n ? <PropertyPreview\n propertyKey={key}\n value={valueInPath}\n property={childProperty as Property}\n size={\"small\"}/>\n : <Typography variant={\"body2\"}>\n {typeof valueInPath === \"string\" ? valueInPath : JSON.stringify(valueInPath)}\n </Typography>;\n\n // The key column used to be `min-w-[200px] w-1/5` beside a\n // `w-4/5` value — 200px of label and 80% of the row, which\n // adds up to more than the row in anything narrower than a\n // full page. In the inspector that pushed every value off\n // the right edge and wrapped ids one character per line.\n // It stacks until the entry itself is wide enough.\n return (\n <div key={\"ref_prev_\" + key}\n className=\"flex flex-col @sm/histentry:flex-row @sm/histentry:items-baseline gap-x-4 gap-y-0.5 w-full my-1.5\">\n <Typography variant={\"caption\"}\n color={\"secondary\"}\n className=\"shrink-0 break-all @sm/histentry:w-40 @sm/histentry:text-right @sm/histentry:break-normal @sm/histentry:truncate\">\n {key}\n </Typography>\n <div className=\"min-w-0 flex-1 flex flex-col items-start gap-0.5\">\n {previousValueInPath !== undefined && !deepEqual(previousValueInPath, valueInPath) &&\n <PreviousValueView previousValueInPath={previousValueInPath}\n childProperty={childProperty as Property}\n propertyKey={key}/>\n }\n {element}\n </div>\n </div>\n );\n })}\n\n {(!changedFields || changedFields.length === 0) && (\n <Typography variant={\"caption\"} color={\"secondary\"}>\n {entry.action === \"create\" ? \"Entity created\" :\n entry.action === \"delete\" ? \"Entity deleted\" : \"No field changes recorded\"}\n </Typography>\n )}\n\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KAC/D,MAAM,gBAAgB,oBAAkB,WAAW,YAAY,GAAG;KAClE,MAAM,cAAc,MAAM,SAAS,eAAe,MAAM,QAAQ,GAAG,IAAI,KAAA;KACvE,MAAM,sBAAsB,iBAAiB,eAAe,gBAAgB,GAAG,IAAI,KAAA;KAEnF,MAAM,UAAU,gBACV,oBAAC,iBAAD;MACE,aAAa;MACb,OAAO;MACP,UAAU;MACV,MAAM;KAAS,CAAA,IACjB,oBAAC,YAAD;MAAY,SAAS;gBAClB,OAAO,gBAAgB,WAAW,cAAc,KAAK,UAAU,WAAW;KACnE,CAAA;KAQhB,OACI,qBAAC,OAAD;MACI,WAAU;gBADd,CAEI,oBAAC,YAAD;OAAY,SAAS;OACjB,OAAO;OACP,WAAU;iBACT;MACO,CAAA,GACZ,qBAAC,OAAD;OAAK,WAAU;iBAAf,CACK,wBAAwB,KAAA,KAAa,CAAC,UAAU,qBAAqB,WAAW,KAC7E,oBAAC,mBAAD;QAAwC;QACrB;QACf,aAAa;OAAK,CAAA,GAEzB,OACA;QACJ;QAfK,cAAc,GAenB;IAEb,CAAC,IAEC,CAAC,iBAAiB,cAAc,WAAW,MACzC,oBAAC,YAAD;KAAY,SAAS;KAAW,OAAO;eAClC,MAAM,WAAW,WAAW,mBACzB,MAAM,WAAW,WAAW,mBAAmB;IAC3C,CAAA,CAGf;KAEJ;IACJ;;AACT"}
@@ -1,4 +1,10 @@
1
- import { CollectionConfig, Entity, RebaseData } from "@rebasepro/types";
1
+ import type { CollectionAccessor, CollectionConfig, Entity } from "@rebasepro/types";
2
+ /**
3
+ * The reads and writes an import makes through a collection accessor. A
4
+ * `RebaseData` accessor is one, and so is any source that can find rows by id
5
+ * and create and update them.
6
+ */
7
+ export type ImportAccessor = Pick<CollectionAccessor, "find" | "findById" | "create" | "update" | "createMany" | "updateMany">;
2
8
  /**
3
9
  * Rows written per request, and per transaction where the data source has one.
4
10
  *
@@ -49,7 +55,9 @@ export interface ImportSaveError extends Error {
49
55
  *
50
56
  * @throws {ImportSaveError} naming the rows that were not written.
51
57
  */
52
- export declare function saveImportedEntities(dataClient: RebaseData, path: string, data: Partial<Entity<any>>[], { offset, batchSize, maxBatchBytes, onBatchCommitted, bulkUnsupported, collection }?: {
58
+ export declare function saveImportedEntities(dataClient: {
59
+ collection(slug: string): ImportAccessor;
60
+ }, path: string, data: Partial<Entity<any>>[], { offset, batchSize, maxBatchBytes, onBatchCommitted, bulkUnsupported, collection }?: {
53
61
  offset?: number;
54
62
  batchSize?: number;
55
63
  /** See {@link IMPORT_BATCH_MAX_BYTES}. */
@@ -1 +1 @@
1
- {"version":3,"file":"save_entities.js","names":[],"sources":["../../../src/data_import/utils/save_entities.ts"],"sourcesContent":["import { CollectionAccessor, CollectionConfig, Entity, RebaseData } from \"@rebasepro/types\";\nimport { findEntitiesByIds } from \"../../util/find_entities_by_ids\";\n\n/**\n * Rows written per request, and per transaction where the data source has one.\n *\n * It was 25, which made a 10,000-row import 400 sequential round trips. The\n * server takes up to 1,000 rows per `POST /bulk`; 500 keeps a failed batch's\n * rollback small enough to retry, and the byte cap below bounds the body.\n */\nexport const IMPORT_BATCH_SIZE = 500;\n\n/**\n * The most JSON one batch carries, in UTF-8 bytes. ~1 MB: a tenth of the\n * server's default body limit (10 MB, `maxBodySize`), and under the 1 MiB a\n * reverse proxy commonly allows by default (nginx's `client_max_body_size`),\n * so wide rows shrink the batch instead of failing it with a 413. A row larger\n * than this still goes, alone.\n */\nexport const IMPORT_BATCH_MAX_BYTES = 1_000_000;\n\n/**\n * An import failure that says where it stopped.\n *\n * \"Error saving data / null value in column \"sku\" violates not-null constraint\"\n * on a ten-thousand-row import named no row, and the Retry button restarted at\n * zero — where the rows already written now conflicted, so it could never\n * succeed. Both halves of that are what this carries.\n */\nexport interface ImportSaveError extends Error {\n /** Rows written and confirmed before the failure. Where a retry resumes. */\n committed: number;\n /** Index of the first row that was not written, 0-based. */\n failedFrom: number;\n /** Index after the last row of the batch that was not written. */\n failedTo: number;\n /**\n * Index of the row the server named as the cause, 0-based, when it named\n * one (`Row 37: …` — every server message about one row of a bulk write\n * starts that way, counted within the batch). The message is rewritten to\n * name it the way the file does: from 1, counted from the first row.\n */\n failedRow?: number;\n}\n\n/** The row a bulk write takes: the values, with the chosen id as a column. */\nfunction toBulkRow(entity: Partial<Entity<any>>): Record<string, unknown> {\n const values = { ...(entity.values ?? {}) } as Record<string, unknown>;\n if (entity.id !== undefined && entity.id !== null && entity.id !== \"\") {\n // Exactly what single-row `create(values, id)` puts on the wire.\n values.id = entity.id;\n }\n return values;\n}\n\nfunction isBulkUnsupported(error: unknown): boolean {\n if ((error as { code?: string })?.code === \"BULK_UNSUPPORTED\") return true;\n const message = (error as Error)?.message ?? \"\";\n return /bulk writes are not supported|does not support bulk/i.test(message);\n}\n\n/** The body was refused for its size: a proxy's or the server's 413, or too many rows. */\nfunction isTooLarge(error: unknown): boolean {\n const status = (error as { status?: number; statusCode?: number })?.status\n ?? (error as { statusCode?: number })?.statusCode;\n if (status === 413) return true;\n const code = (error as { code?: string })?.code;\n return code === \"PAYLOAD_TOO_LARGE\" || code === \"BULK_TOO_LARGE\";\n}\n\n/** The length of a string in UTF-8 bytes, which is what a body limit counts. */\nfunction utf8Length(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xD800 && code <= 0xDBFF) {\n bytes += 4;\n i++;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** `{\"rows\":[`, `],\"upsert\":true}` and some slack. */\nconst BULK_ENVELOPE_BYTES = 64;\n\n/**\n * Where the batch starting at `start` ends: at `maxRows` rows, or before the\n * row that would take the body past `maxBytes` — never before one row.\n */\nfunction batchEnd(data: Partial<Entity<any>>[], start: number, maxRows: number, maxBytes: number): number {\n let bytes = BULK_ENVELOPE_BYTES;\n let end = start;\n while (end < data.length && end - start < maxRows) {\n const rowBytes = utf8Length(JSON.stringify(toBulkRow(data[end]))) + 1;\n if (end > start && bytes + rowBytes > maxBytes) break;\n bytes += rowBytes;\n end++;\n }\n return end;\n}\n\n/**\n * The row a server message names, counted within the batch, and the message\n * with that row counted the way the user's file counts it.\n */\nfunction locateFailedRow(error: unknown, start: number): { row: number, message: string } | undefined {\n const message = (error as Error)?.message;\n if (typeof message !== \"string\") return undefined;\n const match = /^Row (\\d+)(?: of \\d+)?/.exec(message);\n if (!match) return undefined;\n const row = start + Number(match[1]);\n return { row, message: `Row ${row + 1}` + message.slice(match[0].length) };\n}\n\nfunction isConflict(error: unknown): boolean {\n const status = (error as { status?: number; statusCode?: number })?.status\n ?? (error as { statusCode?: number })?.statusCode;\n if (status === 409) return true;\n const code = (error as { code?: string })?.code;\n return code === \"CONFLICT\" || code === \"23505\";\n}\n\n/**\n * The server refused a row only for the required columns it leaves out.\n *\n * `POST /bulk` with `upsert: true` judges each row as a create, since it may\n * insert, so a row meant to update a stored record with some of its columns\n * (`id,price`) is refused as `'name' is required`.\n */\nfunction isMissingRequiredOnly(error: unknown): boolean {\n const violations = (error as { details?: { violations?: unknown } })?.details?.violations;\n return Array.isArray(violations) && violations.length > 0\n && violations.every(v => (v as { code?: unknown })?.code === \"required\");\n}\n\n/**\n * Whether the collection's rows are the users, read the way the server reads it\n * (`collection.auth`, `true` or `{ enabled: true }`).\n *\n * The server refuses an upsert there: a create hashes the password and runs\n * `onCreateUser`, an update may not demote the last administrator, and an\n * upsert decides between the two too late to follow either rule.\n */\nfunction isAuthCollection(collection: CollectionConfig | undefined): boolean {\n const auth = collection?.auth;\n return auth === true || (!!auth && typeof auth === \"object\" && auth.enabled === true);\n}\n\n/**\n * The row a user creation takes. A row that carries a `password` asks the\n * server to waive its password policy (`skipPasswordPolicy`): the accounts in\n * an import had their passwords set under another system's rules. The server\n * honours it only for an administrator.\n */\nfunction toUserCreationRow(entity: Partial<Entity<any>>): Record<string, unknown> {\n const row = toBulkRow(entity);\n return typeof row.password === \"string\" && row.password !== \"\" ? { ...row, skipPasswordPolicy: true } : row;\n}\n\n/**\n * A batch split by whether each row's id is stored: the rows whose id is\n * stored are updates — the given columns are written, the rest keep their\n * values, as the per-row path and the preview's \"overwritten\" say — and the\n * others are created, where a new row still needs every required column. A\n * refusal of one of those names its row in `batch`.\n *\n * Used when the bulk upsert refused a batch for missing required columns\n * (the creates then go back as an upsert), and for every batch of the auth\n * collection, which takes no upsert (the creates go as a plain bulk create,\n * which the server runs through user creation).\n */\nasync function writeUpdatesAndCreates(accessor: CollectionAccessor,\n batch: Partial<Entity<any>>[],\n collection: CollectionConfig,\n createMany: NonNullable<CollectionAccessor[\"createMany\"]>,\n upsert: boolean): Promise<void> {\n\n const ids = batch.map(entity => entity.id).filter((id): id is string | number => id !== undefined && id !== null && id !== \"\");\n const stored = await findEntitiesByIds(accessor, collection, ids);\n const isUpdate = (entity: Partial<Entity<any>>) => entity.id !== undefined && entity.id !== null && stored.has(String(entity.id));\n\n const updates = batch.filter(isUpdate);\n if (updates.length > 0) {\n if (accessor.updateMany) {\n await accessor.updateMany(updates.map(entity => ({ id: entity.id as string | number, data: entity.values ?? {} })));\n } else {\n for (const entity of updates) await accessor.update(entity.id as string | number, entity.values ?? {});\n }\n }\n\n const creates = batch.map((entity, index) => ({ entity, index })).filter(({ entity }) => !isUpdate(entity));\n if (creates.length === 0) return;\n try {\n const rows = creates.map(({ entity }) => isAuthCollection(collection) ? toUserCreationRow(entity) : toBulkRow(entity));\n await (upsert ? createMany(rows, { upsert: true }) : createMany(rows));\n } catch (e) {\n // \"Row 1\" of the rows sent is \"Row <n>\" of the batch.\n const message = (e as Error)?.message;\n const match = typeof message === \"string\" ? /^Row (\\d+)/.exec(message) : null;\n if (match && creates[Number(match[1])]) {\n (e as Error).message = `Row ${creates[Number(match[1])].index}` + message.slice(match[0].length);\n }\n throw e;\n }\n}\n\n/**\n * Write one batch, all-or-nothing wherever the data source can.\n *\n * `POST /<collection>/bulk` validates every row before the transaction opens,\n * names a failure by row index, and takes the `upsert` flag the preview screen\n * promises — none of which one `create` per row inside a `Promise.all` could\n * offer, since `Promise.all` does not cancel its siblings and every request was\n * its own transaction.\n */\nasync function writeBatch(accessor: CollectionAccessor,\n batch: Partial<Entity<any>>[],\n bulkUnsupported: { current: boolean },\n written: { count: number },\n collection: CollectionConfig | undefined): Promise<void> {\n\n if (accessor.createMany && !bulkUnsupported.current) {\n try {\n if (collection && isAuthCollection(collection)) {\n // Not one transaction: the updates are written before the\n // creates, and a retry of the batch writes them again, to the\n // same values — while a stored id among the creates is a\n // conflict, never an overwrite of a user's password.\n await writeUpdatesAndCreates(accessor, batch, collection, accessor.createMany.bind(accessor), false);\n written.count = batch.length;\n return;\n }\n await accessor.createMany(batch.map(toBulkRow), { upsert: true });\n written.count = batch.length;\n return;\n } catch (e) {\n if (collection && !isAuthCollection(collection) && isMissingRequiredOnly(e) && batch.some(entity => entity.id !== undefined && entity.id !== null && entity.id !== \"\")) {\n // Not one transaction any more: a refused create leaves the\n // updates before it written, and a retry of the batch writes\n // them again, to the same values.\n await writeUpdatesAndCreates(accessor, batch, collection, accessor.createMany.bind(accessor), true);\n written.count = batch.length;\n return;\n }\n if (!isBulkUnsupported(e)) throw e;\n // A data source without bulk writes: remember it, so the failed\n // round trip is not paid again on every later batch.\n bulkUnsupported.current = true;\n }\n }\n\n // Sequential, not `Promise.all`: a rejected write does not cancel its\n // siblings, so a parallel batch commits an indeterminate subset of itself\n // and nobody can say which rows landed.\n const usersCollection = !!collection && isAuthCollection(collection);\n for (const entity of batch) {\n try {\n const values = usersCollection\n ? toUserCreationRow({ values: entity.values })\n : entity.values ?? {};\n await accessor.create(values, entity.id);\n } catch (e) {\n // Without `/bulk` there is no upsert, so the preview's promise is\n // honoured the only way left: a row that collided on an id the user\n // supplied is overwritten. A row with no id had nothing to collide\n // on, and every other failure is still a failure.\n if (entity.id === undefined || !isConflict(e)) throw e;\n await accessor.update(entity.id, entity.values ?? {});\n }\n written.count++;\n }\n}\n\n/**\n * Write imported entities in batches, reporting what was committed.\n *\n * Resumable on purpose: a failure at row 4 000 leaves rows 1–3 999 in the table\n * whatever this does, so the only useful thing to report is where to carry on\n * from. `offset` is that point — the Retry button passes back the `committed`\n * count of the error it is retrying, instead of starting from zero and\n * conflicting on every row that already exists.\n *\n * @throws {ImportSaveError} naming the rows that were not written.\n */\nexport async function saveImportedEntities(dataClient: RebaseData,\n path: string,\n data: Partial<Entity<any>>[],\n {\n offset = 0,\n batchSize = IMPORT_BATCH_SIZE,\n maxBatchBytes = IMPORT_BATCH_MAX_BYTES,\n onBatchCommitted = () => undefined,\n bulkUnsupported = { current: false },\n collection\n }: {\n offset?: number;\n batchSize?: number;\n /** See {@link IMPORT_BATCH_MAX_BYTES}. */\n maxBatchBytes?: number;\n onBatchCommitted?: (rowsWritten: number) => void;\n bulkUnsupported?: { current: boolean };\n /**\n * The collection written to. With it, a row that updates a stored\n * record with some of its columns is written as an update rather\n * than refused for the required columns it leaves out.\n */\n collection?: CollectionConfig;\n } = {}): Promise<void> {\n\n console.debug(\"Saving imported data\", offset, batchSize);\n\n const accessor = dataClient.collection(path);\n\n // Lowered for the rest of the import when a batch is refused for its\n // size — a server or proxy configured below the byte cap — so an import\n // that worked in small batches does not fail in large ones.\n let maxRows = Math.max(1, batchSize);\n let start = offset;\n while (start < data.length) {\n const batch = data.slice(start, batchEnd(data, start, maxRows, maxBatchBytes));\n const written = { count: 0 };\n try {\n await writeBatch(accessor, batch, bulkUnsupported, written, collection);\n } catch (e) {\n if (written.count === 0 && batch.length > 1 && isTooLarge(e)) {\n maxRows = Math.max(1, Math.floor(batch.length / 2));\n continue;\n }\n const located = locateFailedRow(e, start + written.count);\n throw Object.assign(e as Error, {\n committed: start + written.count,\n failedFrom: start + written.count,\n failedTo: start + batch.length,\n ...(located ? { failedRow: located.row, message: located.message } : {})\n }) as ImportSaveError;\n }\n start += batch.length;\n onBatchCommitted(start);\n }\n\n onBatchCommitted(data.length);\n}\n"],"mappings":";;;;;;;;;AAUA,IAAa,oBAAoB;;;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1E,SAAS,GAAG;GACR,IAAI,QAAQ,UAAU,KAAK,MAAM,SAAS,KAAK,WAAW,CAAC,GAAG;IAC1D,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;IAClD;GACJ;GACA,MAAM,UAAU,gBAAgB,GAAG,QAAQ,QAAQ,KAAK;GACxD,MAAM,OAAO,OAAO,GAAY;IAC5B,WAAW,QAAQ,QAAQ;IAC3B,YAAY,QAAQ,QAAQ;IAC5B,UAAU,QAAQ,MAAM;IACxB,GAAI,UAAU;KAAE,WAAW,QAAQ;KAAK,SAAS,QAAQ;IAAQ,IAAI,CAAC;GAC1E,CAAC;EACL;EACA,SAAS,MAAM;EACf,iBAAiB,KAAK;CAC1B;CAEA,iBAAiB,KAAK,MAAM;AAChC"}
1
+ {"version":3,"file":"save_entities.js","names":[],"sources":["../../../src/data_import/utils/save_entities.ts"],"sourcesContent":["import type { CollectionAccessor, CollectionConfig, Entity } from \"@rebasepro/types\";\nimport { findEntitiesByIds } from \"../../util/find_entities_by_ids\";\n\n/**\n * The reads and writes an import makes through a collection accessor. A\n * `RebaseData` accessor is one, and so is any source that can find rows by id\n * and create and update them.\n */\nexport type ImportAccessor = Pick<CollectionAccessor, \"find\" | \"findById\" | \"create\" | \"update\" | \"createMany\" | \"updateMany\">;\n\n/**\n * Rows written per request, and per transaction where the data source has one.\n *\n * It was 25, which made a 10,000-row import 400 sequential round trips. The\n * server takes up to 1,000 rows per `POST /bulk`; 500 keeps a failed batch's\n * rollback small enough to retry, and the byte cap below bounds the body.\n */\nexport const IMPORT_BATCH_SIZE = 500;\n\n/**\n * The most JSON one batch carries, in UTF-8 bytes. ~1 MB: a tenth of the\n * server's default body limit (10 MB, `maxBodySize`), and under the 1 MiB a\n * reverse proxy commonly allows by default (nginx's `client_max_body_size`),\n * so wide rows shrink the batch instead of failing it with a 413. A row larger\n * than this still goes, alone.\n */\nexport const IMPORT_BATCH_MAX_BYTES = 1_000_000;\n\n/**\n * An import failure that says where it stopped.\n *\n * \"Error saving data / null value in column \"sku\" violates not-null constraint\"\n * on a ten-thousand-row import named no row, and the Retry button restarted at\n * zero — where the rows already written now conflicted, so it could never\n * succeed. Both halves of that are what this carries.\n */\nexport interface ImportSaveError extends Error {\n /** Rows written and confirmed before the failure. Where a retry resumes. */\n committed: number;\n /** Index of the first row that was not written, 0-based. */\n failedFrom: number;\n /** Index after the last row of the batch that was not written. */\n failedTo: number;\n /**\n * Index of the row the server named as the cause, 0-based, when it named\n * one (`Row 37: …` — every server message about one row of a bulk write\n * starts that way, counted within the batch). The message is rewritten to\n * name it the way the file does: from 1, counted from the first row.\n */\n failedRow?: number;\n}\n\n/** The row a bulk write takes: the values, with the chosen id as a column. */\nfunction toBulkRow(entity: Partial<Entity<any>>): Record<string, unknown> {\n const values = { ...(entity.values ?? {}) } as Record<string, unknown>;\n if (entity.id !== undefined && entity.id !== null && entity.id !== \"\") {\n // Exactly what single-row `create(values, id)` puts on the wire.\n values.id = entity.id;\n }\n return values;\n}\n\nfunction isBulkUnsupported(error: unknown): boolean {\n if ((error as { code?: string })?.code === \"BULK_UNSUPPORTED\") return true;\n const message = (error as Error)?.message ?? \"\";\n return /bulk writes are not supported|does not support bulk/i.test(message);\n}\n\n/** The body was refused for its size: a proxy's or the server's 413, or too many rows. */\nfunction isTooLarge(error: unknown): boolean {\n const status = (error as { status?: number; statusCode?: number })?.status\n ?? (error as { statusCode?: number })?.statusCode;\n if (status === 413) return true;\n const code = (error as { code?: string })?.code;\n return code === \"PAYLOAD_TOO_LARGE\" || code === \"BULK_TOO_LARGE\";\n}\n\n/** The length of a string in UTF-8 bytes, which is what a body limit counts. */\nfunction utf8Length(text: string): number {\n let bytes = 0;\n for (let i = 0; i < text.length; i++) {\n const code = text.charCodeAt(i);\n if (code < 0x80) bytes += 1;\n else if (code < 0x800) bytes += 2;\n else if (code >= 0xD800 && code <= 0xDBFF) {\n bytes += 4;\n i++;\n } else bytes += 3;\n }\n return bytes;\n}\n\n/** `{\"rows\":[`, `],\"upsert\":true}` and some slack. */\nconst BULK_ENVELOPE_BYTES = 64;\n\n/**\n * Where the batch starting at `start` ends: at `maxRows` rows, or before the\n * row that would take the body past `maxBytes` — never before one row.\n */\nfunction batchEnd(data: Partial<Entity<any>>[], start: number, maxRows: number, maxBytes: number): number {\n let bytes = BULK_ENVELOPE_BYTES;\n let end = start;\n while (end < data.length && end - start < maxRows) {\n const rowBytes = utf8Length(JSON.stringify(toBulkRow(data[end]))) + 1;\n if (end > start && bytes + rowBytes > maxBytes) break;\n bytes += rowBytes;\n end++;\n }\n return end;\n}\n\n/**\n * The row a server message names, counted within the batch, and the message\n * with that row counted the way the user's file counts it.\n */\nfunction locateFailedRow(error: unknown, start: number): { row: number, message: string } | undefined {\n const message = (error as Error)?.message;\n if (typeof message !== \"string\") return undefined;\n const match = /^Row (\\d+)(?: of \\d+)?/.exec(message);\n if (!match) return undefined;\n const row = start + Number(match[1]);\n return { row, message: `Row ${row + 1}` + message.slice(match[0].length) };\n}\n\nfunction isConflict(error: unknown): boolean {\n const status = (error as { status?: number; statusCode?: number })?.status\n ?? (error as { statusCode?: number })?.statusCode;\n if (status === 409) return true;\n const code = (error as { code?: string })?.code;\n return code === \"CONFLICT\" || code === \"23505\";\n}\n\n/**\n * The server refused a row only for the required columns it leaves out.\n *\n * `POST /bulk` with `upsert: true` judges each row as a create, since it may\n * insert, so a row meant to update a stored record with some of its columns\n * (`id,price`) is refused as `'name' is required`.\n */\nfunction isMissingRequiredOnly(error: unknown): boolean {\n const violations = (error as { details?: { violations?: unknown } })?.details?.violations;\n return Array.isArray(violations) && violations.length > 0\n && violations.every(v => (v as { code?: unknown })?.code === \"required\");\n}\n\n/**\n * Whether the collection's rows are the users, read the way the server reads it\n * (`collection.auth`, `true` or `{ enabled: true }`).\n *\n * The server refuses an upsert there: a create hashes the password and runs\n * `onCreateUser`, an update may not demote the last administrator, and an\n * upsert decides between the two too late to follow either rule.\n */\nfunction isAuthCollection(collection: CollectionConfig | undefined): boolean {\n const auth = collection?.auth;\n return auth === true || (!!auth && typeof auth === \"object\" && auth.enabled === true);\n}\n\n/**\n * The row a user creation takes. A row that carries a `password` asks the\n * server to waive its password policy (`skipPasswordPolicy`): the accounts in\n * an import had their passwords set under another system's rules. The server\n * honours it only for an administrator.\n */\nfunction toUserCreationRow(entity: Partial<Entity<any>>): Record<string, unknown> {\n const row = toBulkRow(entity);\n return typeof row.password === \"string\" && row.password !== \"\" ? { ...row, skipPasswordPolicy: true } : row;\n}\n\n/**\n * A batch split by whether each row's id is stored: the rows whose id is\n * stored are updates — the given columns are written, the rest keep their\n * values, as the per-row path and the preview's \"overwritten\" say — and the\n * others are created, where a new row still needs every required column. A\n * refusal of one of those names its row in `batch`.\n *\n * Used when the bulk upsert refused a batch for missing required columns\n * (the creates then go back as an upsert), and for every batch of the auth\n * collection, which takes no upsert (the creates go as a plain bulk create,\n * which the server runs through user creation).\n */\nasync function writeUpdatesAndCreates(accessor: ImportAccessor,\n batch: Partial<Entity<any>>[],\n collection: CollectionConfig,\n createMany: NonNullable<CollectionAccessor[\"createMany\"]>,\n upsert: boolean): Promise<void> {\n\n const ids = batch.map(entity => entity.id).filter((id): id is string | number => id !== undefined && id !== null && id !== \"\");\n const stored = await findEntitiesByIds(accessor, collection, ids);\n const isUpdate = (entity: Partial<Entity<any>>) => entity.id !== undefined && entity.id !== null && stored.has(String(entity.id));\n\n const updates = batch.filter(isUpdate);\n if (updates.length > 0) {\n if (accessor.updateMany) {\n await accessor.updateMany(updates.map(entity => ({ id: entity.id as string | number, data: entity.values ?? {} })));\n } else {\n for (const entity of updates) await accessor.update(entity.id as string | number, entity.values ?? {});\n }\n }\n\n const creates = batch.map((entity, index) => ({ entity, index })).filter(({ entity }) => !isUpdate(entity));\n if (creates.length === 0) return;\n try {\n const rows = creates.map(({ entity }) => isAuthCollection(collection) ? toUserCreationRow(entity) : toBulkRow(entity));\n await (upsert ? createMany(rows, { upsert: true }) : createMany(rows));\n } catch (e) {\n // \"Row 1\" of the rows sent is \"Row <n>\" of the batch.\n const message = (e as Error)?.message;\n const match = typeof message === \"string\" ? /^Row (\\d+)/.exec(message) : null;\n if (match && creates[Number(match[1])]) {\n (e as Error).message = `Row ${creates[Number(match[1])].index}` + message.slice(match[0].length);\n }\n throw e;\n }\n}\n\n/**\n * Write one batch, all-or-nothing wherever the data source can.\n *\n * `POST /<collection>/bulk` validates every row before the transaction opens,\n * names a failure by row index, and takes the `upsert` flag the preview screen\n * promises — none of which one `create` per row inside a `Promise.all` could\n * offer, since `Promise.all` does not cancel its siblings and every request was\n * its own transaction.\n */\nasync function writeBatch(accessor: ImportAccessor,\n batch: Partial<Entity<any>>[],\n bulkUnsupported: { current: boolean },\n written: { count: number },\n collection: CollectionConfig | undefined): Promise<void> {\n\n if (accessor.createMany && !bulkUnsupported.current) {\n try {\n if (collection && isAuthCollection(collection)) {\n // Not one transaction: the updates are written before the\n // creates, and a retry of the batch writes them again, to the\n // same values — while a stored id among the creates is a\n // conflict, never an overwrite of a user's password.\n await writeUpdatesAndCreates(accessor, batch, collection, accessor.createMany.bind(accessor), false);\n written.count = batch.length;\n return;\n }\n await accessor.createMany(batch.map(toBulkRow), { upsert: true });\n written.count = batch.length;\n return;\n } catch (e) {\n if (collection && !isAuthCollection(collection) && isMissingRequiredOnly(e) && batch.some(entity => entity.id !== undefined && entity.id !== null && entity.id !== \"\")) {\n // Not one transaction any more: a refused create leaves the\n // updates before it written, and a retry of the batch writes\n // them again, to the same values.\n await writeUpdatesAndCreates(accessor, batch, collection, accessor.createMany.bind(accessor), true);\n written.count = batch.length;\n return;\n }\n if (!isBulkUnsupported(e)) throw e;\n // A data source without bulk writes: remember it, so the failed\n // round trip is not paid again on every later batch.\n bulkUnsupported.current = true;\n }\n }\n\n // Sequential, not `Promise.all`: a rejected write does not cancel its\n // siblings, so a parallel batch commits an indeterminate subset of itself\n // and nobody can say which rows landed.\n const usersCollection = !!collection && isAuthCollection(collection);\n for (const entity of batch) {\n try {\n const values = usersCollection\n ? toUserCreationRow({ values: entity.values })\n : entity.values ?? {};\n await accessor.create(values, entity.id);\n } catch (e) {\n // Without `/bulk` there is no upsert, so the preview's promise is\n // honoured the only way left: a row that collided on an id the user\n // supplied is overwritten. A row with no id had nothing to collide\n // on, and every other failure is still a failure.\n if (entity.id === undefined || !isConflict(e)) throw e;\n await accessor.update(entity.id, entity.values ?? {});\n }\n written.count++;\n }\n}\n\n/**\n * Write imported entities in batches, reporting what was committed.\n *\n * Resumable on purpose: a failure at row 4 000 leaves rows 1–3 999 in the table\n * whatever this does, so the only useful thing to report is where to carry on\n * from. `offset` is that point — the Retry button passes back the `committed`\n * count of the error it is retrying, instead of starting from zero and\n * conflicting on every row that already exists.\n *\n * @throws {ImportSaveError} naming the rows that were not written.\n */\nexport async function saveImportedEntities(dataClient: { collection(slug: string): ImportAccessor },\n path: string,\n data: Partial<Entity<any>>[],\n {\n offset = 0,\n batchSize = IMPORT_BATCH_SIZE,\n maxBatchBytes = IMPORT_BATCH_MAX_BYTES,\n onBatchCommitted = () => undefined,\n bulkUnsupported = { current: false },\n collection\n }: {\n offset?: number;\n batchSize?: number;\n /** See {@link IMPORT_BATCH_MAX_BYTES}. */\n maxBatchBytes?: number;\n onBatchCommitted?: (rowsWritten: number) => void;\n bulkUnsupported?: { current: boolean };\n /**\n * The collection written to. With it, a row that updates a stored\n * record with some of its columns is written as an update rather\n * than refused for the required columns it leaves out.\n */\n collection?: CollectionConfig;\n } = {}): Promise<void> {\n\n console.debug(\"Saving imported data\", offset, batchSize);\n\n const accessor = dataClient.collection(path);\n\n // Lowered for the rest of the import when a batch is refused for its\n // size — a server or proxy configured below the byte cap — so an import\n // that worked in small batches does not fail in large ones.\n let maxRows = Math.max(1, batchSize);\n let start = offset;\n while (start < data.length) {\n const batch = data.slice(start, batchEnd(data, start, maxRows, maxBatchBytes));\n const written = { count: 0 };\n try {\n await writeBatch(accessor, batch, bulkUnsupported, written, collection);\n } catch (e) {\n if (written.count === 0 && batch.length > 1 && isTooLarge(e)) {\n maxRows = Math.max(1, Math.floor(batch.length / 2));\n continue;\n }\n const located = locateFailedRow(e, start + written.count);\n throw Object.assign(e as Error, {\n committed: start + written.count,\n failedFrom: start + written.count,\n failedTo: start + batch.length,\n ...(located ? { failedRow: located.row, message: located.message } : {})\n }) as ImportSaveError;\n }\n start += batch.length;\n onBatchCommitted(start);\n }\n\n onBatchCommitted(data.length);\n}\n"],"mappings":";;;;;;;;;AAiBA,IAAa,oBAAoB;;;;;;;;AASjC,IAAa,yBAAyB;;AA2BtC,SAAS,UAAU,QAAuD;CACtE,MAAM,SAAS,EAAE,GAAI,OAAO,UAAU,CAAC,EAAG;CAC1C,IAAI,OAAO,OAAO,KAAA,KAAa,OAAO,OAAO,QAAQ,OAAO,OAAO,IAE/D,OAAO,KAAK,OAAO;CAEvB,OAAO;AACX;AAEA,SAAS,kBAAkB,OAAyB;CAChD,IAAK,OAA6B,SAAS,oBAAoB,OAAO;CACtE,MAAM,UAAW,OAAiB,WAAW;CAC7C,OAAO,uDAAuD,KAAK,OAAO;AAC9E;;AAGA,SAAS,WAAW,OAAyB;CAGzC,KAFgB,OAAoD,UAC5D,OAAmC,gBAC5B,KAAK,OAAO;CAC3B,MAAM,OAAQ,OAA6B;CAC3C,OAAO,SAAS,uBAAuB,SAAS;AACpD;;AAGA,SAAS,WAAW,MAAsB;CACtC,IAAI,QAAQ;CACZ,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EAClC,MAAM,OAAO,KAAK,WAAW,CAAC;EAC9B,IAAI,OAAO,KAAM,SAAS;OACrB,IAAI,OAAO,MAAO,SAAS;OAC3B,IAAI,QAAQ,SAAU,QAAQ,OAAQ;GACvC,SAAS;GACT;EACJ,OAAO,SAAS;CACpB;CACA,OAAO;AACX;;AAGA,IAAM,sBAAsB;;;;;AAM5B,SAAS,SAAS,MAA8B,OAAe,SAAiB,UAA0B;CACtG,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,OAAO,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,MAAM,WAAW,WAAW,WAAW,IAAI;CAK3C,IAAI,UAAU,KAAK,IAAI,GAAG,SAAS;CACnC,IAAI,QAAQ;CACZ,OAAO,QAAQ,KAAK,QAAQ;EACxB,MAAM,QAAQ,KAAK,MAAM,OAAO,SAAS,MAAM,OAAO,SAAS,aAAa,CAAC;EAC7E,MAAM,UAAU,EAAE,OAAO,EAAE;EAC3B,IAAI;GACA,MAAM,WAAW,UAAU,OAAO,iBAAiB,SAAS,UAAU;EAC1E,SAAS,GAAG;GACR,IAAI,QAAQ,UAAU,KAAK,MAAM,SAAS,KAAK,WAAW,CAAC,GAAG;IAC1D,UAAU,KAAK,IAAI,GAAG,KAAK,MAAM,MAAM,SAAS,CAAC,CAAC;IAClD;GACJ;GACA,MAAM,UAAU,gBAAgB,GAAG,QAAQ,QAAQ,KAAK;GACxD,MAAM,OAAO,OAAO,GAAY;IAC5B,WAAW,QAAQ,QAAQ;IAC3B,YAAY,QAAQ,QAAQ;IAC5B,UAAU,QAAQ,MAAM;IACxB,GAAI,UAAU;KAAE,WAAW,QAAQ;KAAK,SAAS,QAAQ;IAAQ,IAAI,CAAC;GAC1E,CAAC;EACL;EACA,SAAS,MAAM;EACf,iBAAiB,KAAK;CAC1B;CAEA,iBAAiB,KAAK,MAAM;AAChC"}
@@ -1,4 +1,14 @@
1
1
  import { MarkdownParser, MarkdownSerializer } from "prosemirror-markdown";
2
+ /**
3
+ * ProseMirror's MarkdownSerializerState exposes an `out` string property
4
+ * that accumulates the serialised output. The published typings do not
5
+ * include it, so it is declared here, on the class itself.
6
+ */
7
+ declare module "prosemirror-markdown" {
8
+ interface MarkdownSerializerState {
9
+ out: string;
10
+ }
11
+ }
2
12
  export declare const markdownParser: MarkdownParser;
3
13
  export declare const markdownSerializer: MarkdownSerializer;
4
14
  export declare const parser: MarkdownParser;
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.js","names":[],"sources":["../../src/editor/markdown.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/triple-slash-reference */\n/// <reference path=\"./markdown-it-plugins.d.ts\" />\nimport {\n MarkdownParser,\n MarkdownSerializer,\n defaultMarkdownParser,\n defaultMarkdownSerializer\n} from \"prosemirror-markdown\";\nimport markdownIt from \"markdown-it\";\nimport markdownItTaskLists from \"markdown-it-task-lists\";\nimport markdownItMark from \"markdown-it-mark\";\nimport markdownItIns from \"markdown-it-ins\";\n\nimport { schema } from \"./schema\";\n\n/**\n * ProseMirror's MarkdownSerializerState exposes an `out` string property\n * that accumulates the serialised output. The published typings do not\n * include it, so we extend the type locally to avoid `as any` casts.\n */\ninterface MarkdownSerializerStateWithOutput {\n out: string;\n}\n\nconst parserTokens: any = {\n ...defaultMarkdownParser.tokens,\n em: { mark: \"italic\" },\n strong: { mark: \"bold\" },\n html_inline: { ignore: true,\nnoCloseToken: true },\n html_block: { ignore: true,\nnoCloseToken: true },\n s: {\n mark: \"strike\"\n },\n task_list: {\n block: \"task_list\"\n },\n task_item: {\n block: \"task_item\",\n getAttrs: (tok: any) => ({ checked: tok.attrGet(\"checked\") === \"true\" })\n },\n mark: {\n mark: \"highlight\"\n },\n ins: {\n mark: \"underline\"\n },\n table: { block: \"table\" },\n thead: { ignore: true },\n tbody: { ignore: true },\n tr: { block: \"table_row\" },\n th: { block: \"table_header\" },\n td: { block: \"table_cell\" }\n};\n\nconst md = markdownIt({ html: false })\n .use(markdownItTaskLists)\n .use(markdownItMark)\n .use(markdownItIns);\n\n// Unwrap images from paragraphs so they can be parsed as block nodes by ProseMirror\nmd.core.ruler.after(\"inline\", \"image-to-block\", (state: any) => {\n const tokens = state.tokens;\n for (let i = tokens.length - 2; i >= 1; i--) {\n if (\n tokens[i - 1] && tokens[i - 1].type === \"paragraph_open\" &&\n tokens[i] && tokens[i].type === \"inline\" &&\n tokens[i + 1] && tokens[i + 1].type === \"paragraph_close\"\n ) {\n const inlineTokens = tokens[i].children || [];\n if (inlineTokens.length === 1 && inlineTokens[0].type === \"image\") {\n state.tokens.splice(i - 1, 3, inlineTokens[0]);\n // No need to adjust index when looping backward!\n }\n }\n }\n});\n\n// Wrap inline tokens inside table cells into paragraphs to satisfy ProseMirror table cell schema (block+)\nmd.core.ruler.after(\"inline\", \"tables-wrap-paragraphs\", (state: any) => {\n const tokens = state.tokens;\n for (let i = tokens.length - 1; i >= 0; i--) {\n if (tokens[i].type === \"td_open\" || tokens[i].type === \"th_open\") {\n let closeIndex = i + 1;\n while (closeIndex < tokens.length && tokens[closeIndex].type !== \"td_close\" && tokens[closeIndex].type !== \"th_close\") {\n closeIndex++;\n }\n if (closeIndex < tokens.length) {\n const pOpen = new state.Token(\"paragraph_open\", \"p\", 1);\n pOpen.block = true;\n const pClose = new state.Token(\"paragraph_close\", \"p\", -1);\n pClose.block = true;\n\n state.tokens.splice(closeIndex, 0, pClose);\n state.tokens.splice(i + 1, 0, pOpen);\n }\n }\n }\n});\n\nexport const markdownParser = new MarkdownParser(schema, md, parserTokens);\n\n\nexport const markdownSerializer = new MarkdownSerializer(\n {\n ...defaultMarkdownSerializer.nodes,\n // Use \"-\" as bullet character to match markdown-it output and prevent\n // serialization round-trip from changing \"- \" to \"* \" and dirtying the form.\n bullet_list(state, node) {\n state.renderList(node, \" \", () => \"- \");\n },\n // Add custom serialization for task lists\n task_list(state, node) {\n state.renderList(node, \" \", () => \"- \");\n },\n task_item(state, node) {\n state.write(`[${node.attrs.checked ? \"x\" : \" \"}] `);\n state.renderContent(node);\n },\n horizontal_rule(state, node) {\n state.write(node.attrs.markup || \"---\");\n state.closeBlock(node);\n },\n image(state, node) {\n const rawSrc = node.attrs.src || \"\";\n const src = rawSrc.replace(/ /g, \"%20\");\n state.write(\"![\" + state.esc(node.attrs.alt || \"\") + \"](\" + src.replace(/[\\(\\)]/g, \"\\\\$&\") +\n (node.attrs.title ? ' \"' + node.attrs.title.replace(/\"/g, '\\\\\"') + '\"' : \"\") + \")\");\n state.closeBlock(node);\n },\n table(state, node) {\n // Access the internal `.out` accumulator with a typed cast (see MarkdownSerializerStateWithOutput).\n const stateInternal = state as unknown as MarkdownSerializerStateWithOutput;\n node.forEach((row, _, i) => {\n row.forEach((cell, _, j) => {\n if (j === 0) state.write(\"| \");\n else state.write(\" \");\n\n // Capture cell content by tracking state.out length.\n // This avoids monkey-patching state.write which loses\n // flushClose/delim handling and can produce \"undefined\" text.\n const startLen = stateInternal.out.length;\n let first = true;\n cell.forEach((block) => {\n if (!first) stateInternal.out += \"<br>\";\n state.renderInline(block);\n first = false;\n });\n const cellContent = stateInternal.out.slice(startLen);\n // Remove the rendered content from state.out; we'll re-add it escaped\n stateInternal.out = stateInternal.out.slice(0, startLen);\n state.write(cellContent.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \"));\n state.write(\" |\");\n });\n state.write(\"\\n\");\n if (i === 0) {\n row.forEach((cell, _, j) => {\n state.write(j === 0 ? \"|---|\" : \"---|\");\n });\n state.write(\"\\n\");\n }\n });\n state.closeBlock(node);\n },\n table_row() {},\n table_cell() {},\n table_header() {}\n },\n {\n ...defaultMarkdownSerializer.marks,\n bold: defaultMarkdownSerializer.marks.strong,\n italic: defaultMarkdownSerializer.marks.em,\n strike: { open: \"~~\",\nclose: \"~~\",\nmixable: true,\nexpelEnclosingWhitespace: true },\n highlight: { open: \"==\",\nclose: \"==\",\nmixable: true,\nexpelEnclosingWhitespace: true },\n underline: { open: \"++\",\nclose: \"++\",\nmixable: true,\nexpelEnclosingWhitespace: true },\n link: {\n ...defaultMarkdownSerializer.marks.link,\n close(state: any, mark, parent, index) {\n const inAutolink = state.inAutolink;\n state.inAutolink = undefined;\n const href = mark.attrs.href.replace(/ /g, \"%20\");\n return inAutolink ? \">\"\n : \"](\" + href.replace(/[\\(\\)\"]/g, \"\\\\$&\") + (mark.attrs.title ? ` \"${mark.attrs.title.replace(/\"/g, '\\\\\"')}\"` : \"\") + \")\";\n }\n },\n // textStyle (colored text from HTML) has no markdown equivalent — emit content as-is\n textStyle: { open: \"\",\nclose: \"\",\nmixable: true,\nexpelEnclosingWhitespace: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A0B;CAAK;CACvB,MAAM;EACF,GAAG,0BAA0B,MAAM;EACnC,MAAM,OAAY,MAAM,QAAQ,OAAO;GACnC,MAAM,aAAa,MAAM;GACzB,MAAM,aAAa,KAAA;GACnB,MAAM,OAAO,KAAK,MAAM,KAAK,QAAQ,MAAM,KAAK;GAChD,OAAO,aAAa,MACd,OAAO,KAAK,QAAQ,YAAY,MAAM,KAAK,KAAK,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,QAAQ,MAAM,MAAK,EAAE,KAAK,MAAM;EAC9H;CACJ;CAEA,WAAW;EAAE,MAAM;EAC3B,OAAO;EACP,SAAS;EACT,0BAA0B;CAAK;AAC3B,CACJ;AACA,IAAa,SAAS;AACtB,IAAa,aAAa"}
1
+ {"version":3,"file":"markdown.js","names":[],"sources":["../../src/editor/markdown.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/triple-slash-reference */\n/// <reference path=\"./markdown-it-plugins.d.ts\" />\nimport {\n MarkdownParser,\n MarkdownSerializer,\n defaultMarkdownParser,\n defaultMarkdownSerializer\n} from \"prosemirror-markdown\";\nimport markdownIt from \"markdown-it\";\nimport markdownItTaskLists from \"markdown-it-task-lists\";\nimport markdownItMark from \"markdown-it-mark\";\nimport markdownItIns from \"markdown-it-ins\";\n\nimport { schema } from \"./schema\";\n\n/**\n * ProseMirror's MarkdownSerializerState exposes an `out` string property\n * that accumulates the serialised output. The published typings do not\n * include it, so it is declared here, on the class itself.\n */\ndeclare module \"prosemirror-markdown\" {\n interface MarkdownSerializerState {\n out: string;\n }\n}\n\nconst parserTokens: any = {\n ...defaultMarkdownParser.tokens,\n em: { mark: \"italic\" },\n strong: { mark: \"bold\" },\n html_inline: { ignore: true,\nnoCloseToken: true },\n html_block: { ignore: true,\nnoCloseToken: true },\n s: {\n mark: \"strike\"\n },\n task_list: {\n block: \"task_list\"\n },\n task_item: {\n block: \"task_item\",\n getAttrs: (tok: any) => ({ checked: tok.attrGet(\"checked\") === \"true\" })\n },\n mark: {\n mark: \"highlight\"\n },\n ins: {\n mark: \"underline\"\n },\n table: { block: \"table\" },\n thead: { ignore: true },\n tbody: { ignore: true },\n tr: { block: \"table_row\" },\n th: { block: \"table_header\" },\n td: { block: \"table_cell\" }\n};\n\nconst md = markdownIt({ html: false })\n .use(markdownItTaskLists)\n .use(markdownItMark)\n .use(markdownItIns);\n\n// Unwrap images from paragraphs so they can be parsed as block nodes by ProseMirror\nmd.core.ruler.after(\"inline\", \"image-to-block\", (state: any) => {\n const tokens = state.tokens;\n for (let i = tokens.length - 2; i >= 1; i--) {\n if (\n tokens[i - 1] && tokens[i - 1].type === \"paragraph_open\" &&\n tokens[i] && tokens[i].type === \"inline\" &&\n tokens[i + 1] && tokens[i + 1].type === \"paragraph_close\"\n ) {\n const inlineTokens = tokens[i].children || [];\n if (inlineTokens.length === 1 && inlineTokens[0].type === \"image\") {\n state.tokens.splice(i - 1, 3, inlineTokens[0]);\n // No need to adjust index when looping backward!\n }\n }\n }\n});\n\n// Wrap inline tokens inside table cells into paragraphs to satisfy ProseMirror table cell schema (block+)\nmd.core.ruler.after(\"inline\", \"tables-wrap-paragraphs\", (state: any) => {\n const tokens = state.tokens;\n for (let i = tokens.length - 1; i >= 0; i--) {\n if (tokens[i].type === \"td_open\" || tokens[i].type === \"th_open\") {\n let closeIndex = i + 1;\n while (closeIndex < tokens.length && tokens[closeIndex].type !== \"td_close\" && tokens[closeIndex].type !== \"th_close\") {\n closeIndex++;\n }\n if (closeIndex < tokens.length) {\n const pOpen = new state.Token(\"paragraph_open\", \"p\", 1);\n pOpen.block = true;\n const pClose = new state.Token(\"paragraph_close\", \"p\", -1);\n pClose.block = true;\n\n state.tokens.splice(closeIndex, 0, pClose);\n state.tokens.splice(i + 1, 0, pOpen);\n }\n }\n }\n});\n\nexport const markdownParser = new MarkdownParser(schema, md, parserTokens);\n\n\nexport const markdownSerializer = new MarkdownSerializer(\n {\n ...defaultMarkdownSerializer.nodes,\n // Use \"-\" as bullet character to match markdown-it output and prevent\n // serialization round-trip from changing \"- \" to \"* \" and dirtying the form.\n bullet_list(state, node) {\n state.renderList(node, \" \", () => \"- \");\n },\n // Add custom serialization for task lists\n task_list(state, node) {\n state.renderList(node, \" \", () => \"- \");\n },\n task_item(state, node) {\n state.write(`[${node.attrs.checked ? \"x\" : \" \"}] `);\n state.renderContent(node);\n },\n horizontal_rule(state, node) {\n state.write(node.attrs.markup || \"---\");\n state.closeBlock(node);\n },\n image(state, node) {\n const rawSrc = node.attrs.src || \"\";\n const src = rawSrc.replace(/ /g, \"%20\");\n state.write(\"![\" + state.esc(node.attrs.alt || \"\") + \"](\" + src.replace(/[\\(\\)]/g, \"\\\\$&\") +\n (node.attrs.title ? ' \"' + node.attrs.title.replace(/\"/g, '\\\\\"') + '\"' : \"\") + \")\");\n state.closeBlock(node);\n },\n table(state, node) {\n // The internal `.out` accumulator, declared on the class above.\n const stateInternal = state;\n node.forEach((row, _, i) => {\n row.forEach((cell, _, j) => {\n if (j === 0) state.write(\"| \");\n else state.write(\" \");\n\n // Capture cell content by tracking state.out length.\n // This avoids monkey-patching state.write which loses\n // flushClose/delim handling and can produce \"undefined\" text.\n const startLen = stateInternal.out.length;\n let first = true;\n cell.forEach((block) => {\n if (!first) stateInternal.out += \"<br>\";\n state.renderInline(block);\n first = false;\n });\n const cellContent = stateInternal.out.slice(startLen);\n // Remove the rendered content from state.out; we'll re-add it escaped\n stateInternal.out = stateInternal.out.slice(0, startLen);\n state.write(cellContent.replace(/\\|/g, \"\\\\|\").replace(/\\n/g, \" \"));\n state.write(\" |\");\n });\n state.write(\"\\n\");\n if (i === 0) {\n row.forEach((cell, _, j) => {\n state.write(j === 0 ? \"|---|\" : \"---|\");\n });\n state.write(\"\\n\");\n }\n });\n state.closeBlock(node);\n },\n table_row() {},\n table_cell() {},\n table_header() {}\n },\n {\n ...defaultMarkdownSerializer.marks,\n bold: defaultMarkdownSerializer.marks.strong,\n italic: defaultMarkdownSerializer.marks.em,\n strike: { open: \"~~\",\nclose: \"~~\",\nmixable: true,\nexpelEnclosingWhitespace: true },\n highlight: { open: \"==\",\nclose: \"==\",\nmixable: true,\nexpelEnclosingWhitespace: true },\n underline: { open: \"++\",\nclose: \"++\",\nmixable: true,\nexpelEnclosingWhitespace: true },\n link: {\n ...defaultMarkdownSerializer.marks.link,\n close(state: any, mark, parent, index) {\n const inAutolink = state.inAutolink;\n state.inAutolink = undefined;\n const href = mark.attrs.href.replace(/ /g, \"%20\");\n return inAutolink ? \">\"\n : \"](\" + href.replace(/[\\(\\)\"]/g, \"\\\\$&\") + (mark.attrs.title ? ` \"${mark.attrs.title.replace(/\"/g, '\\\\\"')}\"` : \"\") + \")\";\n }\n },\n // textStyle (colored text from HTML) has no markdown equivalent — emit content as-is\n textStyle: { open: \"\",\nclose: \"\",\nmixable: true,\nexpelEnclosingWhitespace: true }\n }\n);\nexport const parser = markdownParser;\nexport const serializer = markdownSerializer;\n"],"mappings":";;;;;;;AA0BA,IAAM,eAAoB;CACtB,GAAG,sBAAsB;CACzB,IAAI,EAAE,MAAM,SAAS;CACrB,QAAQ,EAAE,MAAM,OAAO;CACvB,aAAa;EAAE,QAAQ;EAC3B,cAAc;CAAK;CACf,YAAY;EAAE,QAAQ;EAC1B,cAAc;CAAK;CACf,GAAG,EACC,MAAM,SACV;CACA,WAAW,EACP,OAAO,YACX;CACA,WAAW;EACP,OAAO;EACP,WAAW,SAAc,EAAE,SAAS,IAAI,QAAQ,SAAS,MAAM,OAAO;CAC1E;CACA,MAAM,EACF,MAAM,YACV;CACA,KAAK,EACD,MAAM,YACV;CACA,OAAO,EAAE,OAAO,QAAQ;CACxB,OAAO,EAAE,QAAQ,KAAK;CACtB,OAAO,EAAE,QAAQ,KAAK;CACtB,IAAI,EAAE,OAAO,YAAY;CACzB,IAAI,EAAE,OAAO,eAAe;CAC5B,IAAI,EAAE,OAAO,aAAa;AAC9B;AAEA,IAAM,KAAK,WAAW,EAAE,MAAM,MAAM,CAAC,CAAC,CACjC,IAAI,mBAAmB,CA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;GAChB,IAAI,MAAM,GAAG;IACT,IAAI,SAAS,MAAM,GAAG,MAAM;KACxB,MAAM,MAAM,MAAM,IAAI,UAAU,MAAM;IAC1C,CAAC;IACD,MAAM,MAAM,IAAI;GACpB;EACJ,CAAC;EACD,MAAM,WAAW,IAAI;CACzB;CACA,YAAY,CAAC;CACb,aAAa,CAAC;CACd,eAAe,CAAC;AACpB,GACA;CACI,GAAG,0BAA0B;CAC7B,MAAM,0BAA0B,MAAM;CACtC,QAAQ,0BAA0B,MAAM;CACxC,QAAQ;EAAE,MAAM;EACxB,OAAO;EACP,SAAS;EACT,0BAA0B;CAAK;CACvB,WAAW;EAAE,MAAM;EAC3B,OAAO;EACP,SAAS;EACT,0BAA0B;CAAK;CACvB,WAAW;EAAE,MAAM;EAC3B,OAAO;EACP,SAAS;EACT,0BAA0B;CAAK;CACvB,MAAM;EACF,GAAG,0BAA0B,MAAM;EACnC,MAAM,OAAY,MAAM,QAAQ,OAAO;GACnC,MAAM,aAAa,MAAM;GACzB,MAAM,aAAa,KAAA;GACnB,MAAM,OAAO,KAAK,MAAM,KAAK,QAAQ,MAAM,KAAK;GAChD,OAAO,aAAa,MACd,OAAO,KAAK,QAAQ,YAAY,MAAM,KAAK,KAAK,MAAM,QAAQ,KAAK,KAAK,MAAM,MAAM,QAAQ,MAAM,MAAK,EAAE,KAAK,MAAM;EAC9H;CACJ;CAEA,WAAW;EAAE,MAAM;EAC3B,OAAO;EACP,SAAS;EACT,0BAA0B;CAAK;AAC3B,CACJ;AACA,IAAa,SAAS;AACtB,IAAa,aAAa"}
@@ -52,8 +52,10 @@ var DEEP_COMPARED_FIELD_PROPS = /* @__PURE__ */ new Set([
52
52
  function sameProps(a, b, deep) {
53
53
  const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
54
54
  for (const key of keys) {
55
- if (Object.is(a[key], b[key])) continue;
56
- if (deep.has(key) && deepEqual(a[key], b[key])) continue;
55
+ const x = Reflect.get(a, key);
56
+ const y = Reflect.get(b, key);
57
+ if (Object.is(x, y)) continue;
58
+ if (deep.has(key) && deepEqual(x, y)) continue;
57
59
  return false;
58
60
  }
59
61
  return true;
@@ -1 +1 @@
1
- {"version":3,"file":"PropertyFieldBinding.js","names":[],"sources":["../../src/form/PropertyFieldBinding.tsx"],"sourcesContent":["\nimport type { FieldProps as CoreFieldProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { FieldProps, PropertyFieldBindingProps } from \"../types/fields\";\nimport type { Property } from \"@rebasepro/types\";\nimport type { RebasePlugin, PluginFieldBuilderParams, PropertyConfig } from \"@rebasepro/cms-types\";\nimport React, { ComponentType, ReactElement, Suspense, useCallback, useRef } from \"react\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { resolveComponentRef } from \"@rebasepro/app\";\n\nimport { FormexController, getIn, useFormexGetter, useFormexSelector } from \"@rebasepro/forms\";\n\n;\nimport { ReadOnlyFieldBinding } from \"./field_bindings/ReadOnlyFieldBinding\";\nimport { resolveFormProperty } from \"./resolve_form_properties\";\nimport { useClearRestoreValue } from \"./useClearRestoreValue\";\n\nimport { isPropertyBuilder, resolveProperty } from \"@rebasepro/common\";\nimport { isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useRebaseContext, useSlot, useTranslation } from \"@rebasepro/app\";\nimport { Typography } from \"@rebasepro/ui\";\nimport { getFieldConfig, getFieldId } from \"../components/field_configs\";\nimport { ErrorBoundary } from \"@rebasepro/ui\";\n\n/**\n * This component renders a form field creating the corresponding configuration\n * from a property. For example if bound to a string property, it will generate\n * a text field.\n *\n * You can use it when you are creating a custom field, and need to\n * render additional fields mapped to properties. This is useful if you\n * need to build a complex property mapping, like an array where each index\n * is a different property.\n *\n * Please note that if you build a custom field in a component, the\n * **validation** passed in the property will have no effect. You need to set\n * the validation in the `AdminCollection` definition.\n *\n * @param propertyKey You can use nested names such as `address.street` or `friends[2]`\n * @param property\n * @param context\n * @param includeDescription\n * @param underlyingValueHasChanged\n * @param disabled\n * @param tableMode\n * @param partOfArray\n * @param autoFocus\n * @group Form custom fields\n */\nexport const PropertyFieldBinding = React.memo(PropertyFieldBindingInternal,\n (a: PropertyFieldBindingProps<Record<string, unknown>>, b: PropertyFieldBindingProps<Record<string, unknown>>) =>\n sameProps(a as unknown as Record<string, unknown>, b as unknown as Record<string, unknown>, DEEP_COMPARED_BINDING_PROPS)\n) as typeof PropertyFieldBindingInternal;\n\n/**\n * Props compared by value rather than identity: a property is re-resolved\n * (`dynamicProps`, enums, a parent's `mergeDeep`) into a new object on every\n * render of whatever holds it, and an error for an array or map is a new\n * sub-object of the errors map whenever anything is validated.\n */\nconst DEEP_COMPARED_BINDING_PROPS = new Set([\"property\"]);\nconst DEEP_COMPARED_FIELD_PROPS = new Set([\"property\", \"error\", \"customProps\"]);\n\nfunction sameProps(a: Record<string, unknown>, b: Record<string, unknown>, deep: Set<string>): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n if (Object.is(a[key], b[key])) continue;\n if (deep.has(key) && equal(a[key], b[key])) continue;\n return false;\n }\n return true;\n}\n\nfunction PropertyFieldBindingInternal<M extends Record<string, unknown> = Record<string, unknown>>\n({\n propertyKey,\n property,\n context,\n includeDescription,\n hideLabel,\n underlyingValueHasChanged,\n disabled: disabledProp,\n partOfArray,\n partOfBlock,\n minimalistView,\n autoFocus,\n index,\n size,\n onPropertyChange\n }: PropertyFieldBindingProps<M>): ReactElement<PropertyFieldBindingProps<M>> {\n\n const authController = useAuthController();\n const customizationController = useCustomizationController();\n // Decided on the property as declared: once resolved, a builder or a rule\n // no longer says it was one.\n const alwaysRender = shouldPropertyReRender(property as Property, customizationController.plugins, customizationController.propertyConfigs);\n\n // This field's own slice of the form, so a change anywhere else does not\n // reach it. Through the form's context — which `Field` read — every field\n // of a record form re-rendered on every keystroke anywhere in it: all 500\n // items of an array nobody was typing into. A field that reads the rest of\n // the form while rendering takes the whole controller, and with it every\n // change, as it always has.\n const selectSlice = useCallback((formex: FormexController<Record<string, unknown>>): FieldSlice => ({\n formex: alwaysRender ? formex : undefined,\n value: getIn(formex.values, propertyKey),\n error: getIn(formex.errors, propertyKey) as FieldSlice[\"error\"],\n touched: getIn(formex.touched, propertyKey) as boolean | undefined,\n submitted: formex.submitCount > 0,\n isSubmitting: formex.isSubmitting\n }), [propertyKey, alwaysRender]);\n const slice = useFormexSelector(selectSlice, sameSlice);\n const getFormex = useFormexGetter<Record<string, unknown>>();\n // What the property is resolved against. Read, not subscribed to, for a\n // field that is not `alwaysRender`: nothing it declares reads the values.\n const values = (slice.formex ?? getFormex()).values;\n\n let Component: ComponentType<FieldProps<Property, any, any>> | undefined;\n // `dynamicProps` and `conditions` both, as the save judges it.\n const resolvedProperty = resolveFormProperty({\n propertyKey,\n property: property,\n values,\n path: context.path,\n entityId: context.id,\n propertyConfigs: customizationController.propertyConfigs,\n index,\n authController\n }) as Property | null;\n\n const readOnly = resolvedProperty ? isReadOnly(resolvedProperty) : true;\n const disabled = disabledProp || readOnly || (resolvedProperty ? isDisabled(resolvedProperty) : false) || context.disabled;\n\n if (resolvedProperty === null || isHidden(resolvedProperty)) {\n return <></>;\n } else if (readOnly) {\n Component = ReadOnlyFieldBinding;\n } else if (resolvedProperty.admin?.Field) {\n const resolved = resolveComponentRef(resolvedProperty.admin.Field);\n if (resolved) {\n Component = resolved as ComponentType<FieldProps<Property, any, any>>;\n }\n } else {\n const propertyConfig = getFieldConfig(resolvedProperty, customizationController.propertyConfigs);\n if (!propertyConfig) {\n throw new Error(`INTERNAL: Could not find field config for property ${propertyKey}`);\n }\n const configProperty = resolveProperty({\n propertyKey,\n property: propertyConfig.property as Property,\n values,\n path: context.path,\n entityId: context.id,\n propertyConfigs: customizationController.propertyConfigs,\n index,\n authController\n }) as Property | null;\n Component = resolveComponentRef(configProperty?.admin?.Field) as ComponentType<FieldProps<Property, any, any>> | undefined;\n }\n if (!Component) {\n console.warn(`No field component found for property ${propertyKey}`);\n console.warn(\"Property:\", property);\n return (\n <div className={\"w-full\"}>\n {`Currently the field ${resolvedProperty.type} is not supported`}\n </div>\n );\n }\n\n const componentProps: ResolvedPropertyFieldBindingProps<M> = {\n propertyKey,\n property: resolvedProperty,\n includeDescription,\n hideLabel,\n underlyingValueHasChanged,\n context,\n disabled,\n partOfArray,\n partOfBlock,\n minimalistView,\n autoFocus,\n size,\n onPropertyChange\n };\n\n // Keyed on the path, as the `Field` it replaces was: an array item that\n // moves to another index is a new field there.\n return <FieldInternal\n key={propertyKey}\n Component={Component as ComponentType<FieldProps<Property, any, any>>}\n alwaysRender={alwaysRender}\n componentProps={componentProps}\n slice={slice}\n getFormex={getFormex}/>;\n\n}\n\n/**\n * What one field reads from the form. `formex` is set only for a field that\n * re-renders on every change (see {@link shouldPropertyReRender}).\n */\ntype FieldSlice = {\n formex: FormexController<Record<string, unknown>> | undefined;\n value: unknown;\n error: string | string[] | Record<string, unknown> | undefined;\n touched: boolean | undefined;\n submitted: boolean;\n isSubmitting: boolean;\n};\n\nfunction sameSlice(a: FieldSlice, b: FieldSlice): boolean {\n return a.formex === b.formex &&\n Object.is(a.value, b.value) &&\n a.touched === b.touched &&\n a.submitted === b.submitted &&\n a.isSubmitting === b.isSubmitting &&\n // An array's or a map's error is a sub-object of the errors map, new\n // whenever anything is validated.\n (Object.is(a.error, b.error) || equal(a.error, b.error));\n}\n\ntype ResolvedPropertyFieldBindingProps<M extends Record<string, unknown> = Record<string, unknown>> =\n Omit<PropertyFieldBindingProps<M>, \"property\">\n & {\n property: Property\n};\n\nfunction FieldInternal<CustomProps, M extends Record<string, unknown>>\n({\n Component,\n alwaysRender,\n componentProps: {\n propertyKey,\n property,\n includeDescription,\n hideLabel,\n underlyingValueHasChanged,\n partOfArray,\n partOfBlock,\n minimalistView,\n autoFocus,\n context,\n disabled,\n size,\n onPropertyChange\n },\n slice,\n getFormex\n }:\n {\n Component: ComponentType<FieldProps<Property, any, any>>,\n alwaysRender: boolean,\n componentProps: ResolvedPropertyFieldBindingProps<M>,\n slice: FieldSlice,\n getFormex: () => FormexController<Record<string, unknown>>\n }) {\n\n const { plugins } = useCustomizationController();\n const { t } = useTranslation();\n\n // This is the one component every form field goes through, which is why the\n // two field slots render here rather than in each field binding: a slot\n // honoured by the string field and not by the date field is worse than one\n // that never renders at all.\n const rebaseContext = useRebaseContext();\n const fieldSlotProps = React.useMemo(() => ({\n propertyKey,\n property,\n path: context.path ?? \"\",\n id: context.id,\n collection: context.collection,\n context: rebaseContext\n }), [propertyKey, property, context.path, context.id, context.collection, rebaseContext]);\n const beforeField = useSlot(\"entity.field.before\", fieldSlotProps);\n const afterField = useSlot(\"entity.field.after\", fieldSlotProps);\n\n const customFieldProps: unknown = property.admin?.customProps;\n const { value, error, touched, isSubmitting } = slice;\n\n const showError = Boolean(error &&\n (slice.submitted || property.validation?.unique) &&\n (!Array.isArray(error) || !!error.filter((e: unknown) => !!e).length));\n\n const WrappedComponent: ComponentType<FieldProps<Property, any, any>> | null = useWrappedComponent<unknown, any>({\n path: context.path,\n collection: context.collection,\n propertyKey: propertyKey,\n property: property,\n Component: Component as ComponentType<FieldProps<Property, unknown, M>>,\n plugins: plugins\n });\n const UsedComponent: ComponentType<FieldProps<Property, any, any>> = WrappedComponent ?? Component;\n\n // Read the controller when called, not when rendered: this component\n // re-renders with its own slice only, and the form moves on without it.\n const setValue = useCallback((value: unknown | null, shouldValidate?: boolean) => {\n const formex = getFormex();\n formex.setFieldTouched(propertyKey, true, false);\n formex.setFieldValue(propertyKey, value, shouldValidate);\n }, [getFormex, propertyKey]);\n\n const setFieldValue = useCallback((otherPropertyKey: string, value: unknown | null, shouldValidate?: boolean) => {\n const formex = getFormex();\n formex.setFieldTouched(propertyKey, true, false);\n formex.setFieldValue(otherPropertyKey, value, shouldValidate);\n }, [getFormex, propertyKey]);\n\n // `disabled: { clearOnDisabled: true }`, for every field: called here and\n // not in each binding, where six of them never did and a disabled relation\n // kept its value and saved it.\n useClearRestoreValue({ property: property as Property, value, setValue });\n\n // A parent that builds `onPropertyChange` inline (an array item's\n // `storeProps`, a map's wrapper) would otherwise hand every child a new\n // function on each of its renders, and every child would re-render for it.\n const onPropertyChangeRef = useRef(onPropertyChange);\n onPropertyChangeRef.current = onPropertyChange;\n const stableOnPropertyChange = useCallback((changed: Partial<Property>) => onPropertyChangeRef.current?.(changed), []);\n\n const cmsFieldProps: FieldProps<Property, CustomProps, M> = {\n propertyKey,\n value,\n setValue,\n setFieldValue,\n error: error as string | undefined,\n touched,\n showError,\n isSubmitting,\n includeDescription: includeDescription ?? true,\n hideLabel: hideLabel ?? false,\n property: property as Property,\n disabled: disabled ?? false,\n underlyingValueHasChanged: underlyingValueHasChanged ?? false,\n partOfArray: partOfArray ?? false,\n partOfBlock: partOfBlock ?? false,\n minimalistView: minimalistView ?? false,\n autoFocus: autoFocus ?? false,\n customProps: customFieldProps as CustomProps,\n context,\n size,\n onPropertyChange: onPropertyChange ? stableOnPropertyChange : undefined\n };\n\n return (\n <ErrorBoundary>\n {beforeField}\n\n <Suspense fallback={null}>\n <MemoisedField Component={UsedComponent}\n alwaysRender={alwaysRender}\n fieldProps={cmsFieldProps as FieldProps<Property, any, any>}/>\n </Suspense>\n\n {afterField}\n\n {underlyingValueHasChanged && !isSubmitting &&\n <Typography variant={\"caption\"} className={\"ml-3.5\"}>\n {t(\"value_updated_elsewhere\")}\n </Typography>}\n\n </ErrorBoundary>);\n\n}\n\ntype MemoisedFieldProps = {\n Component: ComponentType<FieldProps<Property, any, any>>,\n alwaysRender: boolean,\n fieldProps: FieldProps<Property, any, any>\n};\n\n/**\n * The field's own component, rendered again only when its own slice of the\n * form changed — value, error, touched, the flags — or when the context it\n * draws the record from did (see `fieldContext` in `EntityForm`). Every field\n * of the form used to re-render on every keystroke anywhere in it.\n *\n * A field that may read *another* field's value while rendering cannot know\n * when to re-render from its own props, so those always do: see\n * {@link shouldPropertyReRender}.\n */\nconst MemoisedField = React.memo(\n function MemoisedField({ Component, fieldProps }: MemoisedFieldProps) {\n return <Component {...fieldProps}/>;\n },\n (prev: MemoisedFieldProps, next: MemoisedFieldProps) =>\n !next.alwaysRender &&\n prev.Component === next.Component &&\n sameProps(prev.fieldProps as unknown as Record<string, unknown>, next.fieldProps as unknown as Record<string, unknown>, DEEP_COMPARED_FIELD_PROPS)\n);\n\n/**\n * Whether a field has to re-render on every change to the form, because what\n * it draws can depend on values other than its own:\n * - a plugin `fieldBuilder` wraps it in a component of the plugin's;\n * - a custom `admin.Field` gets the whole form through `context`;\n * - `dynamicProps` and `conditions` are functions of every value;\n * - a storage path or file name given as a function is built from the values\n * the binding holds;\n * - a custom `propertyConfig` whose property says any of the above, since the\n * field is resolved through it.\n * Inside maps, arrays and blocks too, since their bindings render the children.\n */\nconst shouldPropertyReRender = (property: Property | undefined, plugins?: RebasePlugin[], propertyConfigs?: Record<string, PropertyConfig>): boolean => {\n if (!property) return false;\n if (plugins?.some((plugin) => plugin.fieldBuilder)) {\n return true;\n }\n const recurse = (child: unknown) => shouldPropertyReRender(child as Property, plugins, propertyConfigs);\n if (isPropertyBuilder(property) || property.conditions || property.admin?.Field) {\n return true;\n }\n const storage = \"storage\" in property ? property.storage : undefined;\n if (storage && (typeof storage.storagePath === \"function\" || typeof storage.fileName === \"function\")) {\n return true;\n }\n const configProperty = property.propertyConfig ? propertyConfigs?.[property.propertyConfig]?.property : undefined;\n if (configProperty && configProperty !== property && recurse(configProperty)) {\n return true;\n }\n if (property.type === \"map\" && property.properties) {\n return Object.values(property.properties).some(recurse);\n }\n if (property.type === \"array\") {\n if (Array.isArray(property.of)) {\n return property.of.some(recurse);\n }\n if (property.of && recurse(property.of)) {\n return true;\n }\n if (property.oneOf?.properties) {\n return Object.values(property.oneOf.properties).some(recurse);\n }\n }\n return false;\n}\n\ninterface UseWrappedComponentParams<M extends Record<string, unknown> = Record<string, unknown>> {\n path?: string,\n collection?: AdminCollection<M>,\n propertyKey: string,\n property: Property,\n Component: ComponentType<FieldProps<Property, unknown, M>>,\n plugins?: RebasePlugin[]\n}\n\nfunction useWrappedComponent<T, M extends Record<string, unknown> = Record<string, unknown>>(\n {\n path,\n collection,\n propertyKey,\n property,\n Component,\n plugins\n }: UseWrappedComponentParams<M>\n): ComponentType<FieldProps<Property, unknown, M>> | null {\n\n // A fold, in plugin order: each plugin's `wrap` is handed the field as the\n // plugins before it left it, so every wrapper renders — the first plugin's\n // closest to the field, the last one's outermost. A plugin that returns\n // null, or is not `enabled` for this field, passes it on unchanged.\n const wrapperRef = useRef<ComponentType<FieldProps<Property, unknown, M>> | null>((() => {\n let Wrapped: ComponentType<FieldProps<Property, unknown, M>> | null = null;\n if (plugins) {\n plugins.forEach((plugin) => {\n const fieldId = getFieldId(property);\n if (fieldId && plugin.fieldBuilder) {\n const params: PluginFieldBuilderParams = {\n fieldConfigId: fieldId,\n propertyKey,\n property,\n Field: (Wrapped ?? Component) as ComponentType<CoreFieldProps<Property, unknown, Record<string, unknown>>>,\n plugin,\n path,\n collection: collection as AdminCollection | undefined\n };\n const enabled = plugin.fieldBuilder.enabled?.(params);\n if (enabled === undefined || enabled)\n Wrapped = (plugin.fieldBuilder.wrap(params) as ComponentType<FieldProps<Property, unknown, M>> | null) ?? Wrapped;\n }\n if (!fieldId) {\n console.warn(\"INTERNAL: Field id not found for property\", property);\n }\n });\n }\n return Wrapped;\n })());\n\n return wrapperRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,uBAAuB,MAAM,KAAK,+BAC1C,GAAuD,MACpD,UAAU,GAAyC,GAAyC,2BAA2B,CAC/H;;;;;;;AAQA,IAAM,8CAA8B,IAAI,IAAI,CAAC,UAAU,CAAC;AACxD,IAAM,4CAA4B,IAAI,IAAI;CAAC;CAAY;CAAS;AAAa,CAAC;AAE9E,SAAS,UAAU,GAA4B,GAA4B,MAA4B;CACnG,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,GAAG,GAAG,OAAO,KAAK,CAAC,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K,OAAO;CAE1D,IAAI,SAAS,SAAS,SAAS;EAC3B,IAAI,MAAM,QAAQ,SAAS,EAAE,GACzB,OAAO,SAAS,GAAG,KAAK,OAAO;EAEnC,IAAI,SAAS,MAAM,QAAQ,SAAS,EAAE,GAClC,OAAO;EAEX,IAAI,SAAS,OAAO,YAChB,OAAO,OAAO,OAAO,SAAS,MAAM,UAAU,CAAC,CAAC,KAAK,OAAO;CAEpE;CACA,OAAO;AACX;AAWA,SAAS,oBACL,EACI,MACA,YACA,aACA,UACA,WACA,WAEkD;CAiCtD,OA3BmB,cAAsE;EACrF,IAAI,UAAkE;EACtE,IAAI,SACA,QAAQ,SAAS,WAAW;GACxB,MAAM,UAAU,WAAW,QAAQ;GACnC,IAAI,WAAW,OAAO,cAAc;IAChC,MAAM,SAAmC;KACrC,eAAe;KACf;KACA;KACA,OAAQ,WAAW;KACnB;KACA;KACY;IAChB;IACA,MAAM,UAAU,OAAO,aAAa,UAAU,MAAM;IACpD,IAAI,YAAY,KAAA,KAAa,SACzB,UAAW,OAAO,aAAa,KAAK,MAAM,KAAgE;GAClH;GACA,IAAI,CAAC,SACD,QAAQ,KAAK,6CAA6C,QAAQ;EAE1E,CAAC;EAEL,OAAO;CACX,EAAA,CAAG,CAEI,CAAA,CAAW;AACtB"}
1
+ {"version":3,"file":"PropertyFieldBinding.js","names":[],"sources":["../../src/form/PropertyFieldBinding.tsx"],"sourcesContent":["\nimport type { FieldProps as CoreFieldProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { FieldProps, PropertyFieldBindingProps } from \"../types/fields\";\nimport type { Property } from \"@rebasepro/types\";\nimport type { RebasePlugin, PluginFieldBuilderParams, PropertyConfig } from \"@rebasepro/cms-types\";\nimport React, { ComponentType, ReactElement, Suspense, useCallback, useRef } from \"react\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { resolveComponentRef } from \"@rebasepro/app\";\n\nimport { FormexController, getIn, useFormexGetter, useFormexSelector } from \"@rebasepro/forms\";\n\n;\nimport { ReadOnlyFieldBinding } from \"./field_bindings/ReadOnlyFieldBinding\";\nimport { resolveFormProperty } from \"./resolve_form_properties\";\nimport { useClearRestoreValue } from \"./useClearRestoreValue\";\n\nimport { isPropertyBuilder, resolveProperty } from \"@rebasepro/common\";\nimport { isDisabled, isHidden, isReadOnly } from \"@rebasepro/app\";\nimport { useAuthController, useCustomizationController, useRebaseContext, useSlot, useTranslation } from \"@rebasepro/app\";\nimport { Typography } from \"@rebasepro/ui\";\nimport { getFieldConfig, getFieldId } from \"../components/field_configs\";\nimport { ErrorBoundary } from \"@rebasepro/ui\";\n\n/**\n * This component renders a form field creating the corresponding configuration\n * from a property. For example if bound to a string property, it will generate\n * a text field.\n *\n * You can use it when you are creating a custom field, and need to\n * render additional fields mapped to properties. This is useful if you\n * need to build a complex property mapping, like an array where each index\n * is a different property.\n *\n * Please note that if you build a custom field in a component, the\n * **validation** passed in the property will have no effect. You need to set\n * the validation in the `AdminCollection` definition.\n *\n * @param propertyKey You can use nested names such as `address.street` or `friends[2]`\n * @param property\n * @param context\n * @param includeDescription\n * @param underlyingValueHasChanged\n * @param disabled\n * @param tableMode\n * @param partOfArray\n * @param autoFocus\n * @group Form custom fields\n */\nexport const PropertyFieldBinding = React.memo(PropertyFieldBindingInternal,\n (a: PropertyFieldBindingProps<Record<string, unknown>>, b: PropertyFieldBindingProps<Record<string, unknown>>) =>\n sameProps(a, b, DEEP_COMPARED_BINDING_PROPS)\n) as typeof PropertyFieldBindingInternal;\n\n/**\n * Props compared by value rather than identity: a property is re-resolved\n * (`dynamicProps`, enums, a parent's `mergeDeep`) into a new object on every\n * render of whatever holds it, and an error for an array or map is a new\n * sub-object of the errors map whenever anything is validated.\n */\nconst DEEP_COMPARED_BINDING_PROPS = new Set([\"property\"]);\nconst DEEP_COMPARED_FIELD_PROPS = new Set([\"property\", \"error\", \"customProps\"]);\n\nfunction sameProps(a: object, b: object, deep: Set<string>): boolean {\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n const x: unknown = Reflect.get(a, key);\n const y: unknown = Reflect.get(b, key);\n if (Object.is(x, y)) continue;\n if (deep.has(key) && equal(x, y)) continue;\n return false;\n }\n return true;\n}\n\nfunction PropertyFieldBindingInternal<M extends Record<string, unknown> = Record<string, unknown>>\n({\n propertyKey,\n property,\n context,\n includeDescription,\n hideLabel,\n underlyingValueHasChanged,\n disabled: disabledProp,\n partOfArray,\n partOfBlock,\n minimalistView,\n autoFocus,\n index,\n size,\n onPropertyChange\n }: PropertyFieldBindingProps<M>): ReactElement<PropertyFieldBindingProps<M>> {\n\n const authController = useAuthController();\n const customizationController = useCustomizationController();\n // Decided on the property as declared: once resolved, a builder or a rule\n // no longer says it was one.\n const alwaysRender = shouldPropertyReRender(property as Property, customizationController.plugins, customizationController.propertyConfigs);\n\n // This field's own slice of the form, so a change anywhere else does not\n // reach it. Through the form's context — which `Field` read — every field\n // of a record form re-rendered on every keystroke anywhere in it: all 500\n // items of an array nobody was typing into. A field that reads the rest of\n // the form while rendering takes the whole controller, and with it every\n // change, as it always has.\n const selectSlice = useCallback((formex: FormexController<Record<string, unknown>>): FieldSlice => ({\n formex: alwaysRender ? formex : undefined,\n value: getIn(formex.values, propertyKey),\n error: getIn(formex.errors, propertyKey) as FieldSlice[\"error\"],\n touched: getIn(formex.touched, propertyKey) as boolean | undefined,\n submitted: formex.submitCount > 0,\n isSubmitting: formex.isSubmitting\n }), [propertyKey, alwaysRender]);\n const slice = useFormexSelector(selectSlice, sameSlice);\n const getFormex = useFormexGetter<Record<string, unknown>>();\n // What the property is resolved against. Read, not subscribed to, for a\n // field that is not `alwaysRender`: nothing it declares reads the values.\n const values = (slice.formex ?? getFormex()).values;\n\n let Component: ComponentType<FieldProps<Property, any, any>> | undefined;\n // `dynamicProps` and `conditions` both, as the save judges it.\n const resolvedProperty = resolveFormProperty({\n propertyKey,\n property: property,\n values,\n path: context.path,\n entityId: context.id,\n propertyConfigs: customizationController.propertyConfigs,\n index,\n authController\n }) as Property | null;\n\n const readOnly = resolvedProperty ? isReadOnly(resolvedProperty) : true;\n const disabled = disabledProp || readOnly || (resolvedProperty ? isDisabled(resolvedProperty) : false) || context.disabled;\n\n if (resolvedProperty === null || isHidden(resolvedProperty)) {\n return <></>;\n } else if (readOnly) {\n Component = ReadOnlyFieldBinding;\n } else if (resolvedProperty.admin?.Field) {\n const resolved = resolveComponentRef(resolvedProperty.admin.Field);\n if (resolved) {\n Component = resolved as ComponentType<FieldProps<Property, any, any>>;\n }\n } else {\n const propertyConfig = getFieldConfig(resolvedProperty, customizationController.propertyConfigs);\n if (!propertyConfig) {\n throw new Error(`INTERNAL: Could not find field config for property ${propertyKey}`);\n }\n const configProperty = resolveProperty({\n propertyKey,\n property: propertyConfig.property as Property,\n values,\n path: context.path,\n entityId: context.id,\n propertyConfigs: customizationController.propertyConfigs,\n index,\n authController\n }) as Property | null;\n Component = resolveComponentRef(configProperty?.admin?.Field) as ComponentType<FieldProps<Property, any, any>> | undefined;\n }\n if (!Component) {\n console.warn(`No field component found for property ${propertyKey}`);\n console.warn(\"Property:\", property);\n return (\n <div className={\"w-full\"}>\n {`Currently the field ${resolvedProperty.type} is not supported`}\n </div>\n );\n }\n\n const componentProps: ResolvedPropertyFieldBindingProps<M> = {\n propertyKey,\n property: resolvedProperty,\n includeDescription,\n hideLabel,\n underlyingValueHasChanged,\n context,\n disabled,\n partOfArray,\n partOfBlock,\n minimalistView,\n autoFocus,\n size,\n onPropertyChange\n };\n\n // Keyed on the path, as the `Field` it replaces was: an array item that\n // moves to another index is a new field there.\n return <FieldInternal\n key={propertyKey}\n Component={Component as ComponentType<FieldProps<Property, any, any>>}\n alwaysRender={alwaysRender}\n componentProps={componentProps}\n slice={slice}\n getFormex={getFormex}/>;\n\n}\n\n/**\n * What one field reads from the form. `formex` is set only for a field that\n * re-renders on every change (see {@link shouldPropertyReRender}).\n */\ntype FieldSlice = {\n formex: FormexController<Record<string, unknown>> | undefined;\n value: unknown;\n error: string | string[] | Record<string, unknown> | undefined;\n touched: boolean | undefined;\n submitted: boolean;\n isSubmitting: boolean;\n};\n\nfunction sameSlice(a: FieldSlice, b: FieldSlice): boolean {\n return a.formex === b.formex &&\n Object.is(a.value, b.value) &&\n a.touched === b.touched &&\n a.submitted === b.submitted &&\n a.isSubmitting === b.isSubmitting &&\n // An array's or a map's error is a sub-object of the errors map, new\n // whenever anything is validated.\n (Object.is(a.error, b.error) || equal(a.error, b.error));\n}\n\ntype ResolvedPropertyFieldBindingProps<M extends Record<string, unknown> = Record<string, unknown>> =\n Omit<PropertyFieldBindingProps<M>, \"property\">\n & {\n property: Property\n};\n\nfunction FieldInternal<CustomProps, M extends Record<string, unknown>>\n({\n Component,\n alwaysRender,\n componentProps: {\n propertyKey,\n property,\n includeDescription,\n hideLabel,\n underlyingValueHasChanged,\n partOfArray,\n partOfBlock,\n minimalistView,\n autoFocus,\n context,\n disabled,\n size,\n onPropertyChange\n },\n slice,\n getFormex\n }:\n {\n Component: ComponentType<FieldProps<Property, any, any>>,\n alwaysRender: boolean,\n componentProps: ResolvedPropertyFieldBindingProps<M>,\n slice: FieldSlice,\n getFormex: () => FormexController<Record<string, unknown>>\n }) {\n\n const { plugins } = useCustomizationController();\n const { t } = useTranslation();\n\n // This is the one component every form field goes through, which is why the\n // two field slots render here rather than in each field binding: a slot\n // honoured by the string field and not by the date field is worse than one\n // that never renders at all.\n const rebaseContext = useRebaseContext();\n const fieldSlotProps = React.useMemo(() => ({\n propertyKey,\n property,\n path: context.path ?? \"\",\n id: context.id,\n collection: context.collection,\n context: rebaseContext\n }), [propertyKey, property, context.path, context.id, context.collection, rebaseContext]);\n const beforeField = useSlot(\"entity.field.before\", fieldSlotProps);\n const afterField = useSlot(\"entity.field.after\", fieldSlotProps);\n\n const customFieldProps: unknown = property.admin?.customProps;\n const { value, error, touched, isSubmitting } = slice;\n\n const showError = Boolean(error &&\n (slice.submitted || property.validation?.unique) &&\n (!Array.isArray(error) || !!error.filter((e: unknown) => !!e).length));\n\n const WrappedComponent: ComponentType<FieldProps<Property, any, any>> | null = useWrappedComponent<unknown, any>({\n path: context.path,\n collection: context.collection,\n propertyKey: propertyKey,\n property: property,\n Component: Component as ComponentType<FieldProps<Property, unknown, M>>,\n plugins: plugins\n });\n const UsedComponent: ComponentType<FieldProps<Property, any, any>> = WrappedComponent ?? Component;\n\n // Read the controller when called, not when rendered: this component\n // re-renders with its own slice only, and the form moves on without it.\n const setValue = useCallback((value: unknown | null, shouldValidate?: boolean) => {\n const formex = getFormex();\n formex.setFieldTouched(propertyKey, true, false);\n formex.setFieldValue(propertyKey, value, shouldValidate);\n }, [getFormex, propertyKey]);\n\n const setFieldValue = useCallback((otherPropertyKey: string, value: unknown | null, shouldValidate?: boolean) => {\n const formex = getFormex();\n formex.setFieldTouched(propertyKey, true, false);\n formex.setFieldValue(otherPropertyKey, value, shouldValidate);\n }, [getFormex, propertyKey]);\n\n // `disabled: { clearOnDisabled: true }`, for every field: called here and\n // not in each binding, where six of them never did and a disabled relation\n // kept its value and saved it.\n useClearRestoreValue({ property: property as Property, value, setValue });\n\n // A parent that builds `onPropertyChange` inline (an array item's\n // `storeProps`, a map's wrapper) would otherwise hand every child a new\n // function on each of its renders, and every child would re-render for it.\n const onPropertyChangeRef = useRef(onPropertyChange);\n onPropertyChangeRef.current = onPropertyChange;\n const stableOnPropertyChange = useCallback((changed: Partial<Property>) => onPropertyChangeRef.current?.(changed), []);\n\n const cmsFieldProps: FieldProps<Property, CustomProps, M> = {\n propertyKey,\n value,\n setValue,\n setFieldValue,\n error: error as string | undefined,\n touched,\n showError,\n isSubmitting,\n includeDescription: includeDescription ?? true,\n hideLabel: hideLabel ?? false,\n property: property as Property,\n disabled: disabled ?? false,\n underlyingValueHasChanged: underlyingValueHasChanged ?? false,\n partOfArray: partOfArray ?? false,\n partOfBlock: partOfBlock ?? false,\n minimalistView: minimalistView ?? false,\n autoFocus: autoFocus ?? false,\n customProps: customFieldProps as CustomProps,\n context,\n size,\n onPropertyChange: onPropertyChange ? stableOnPropertyChange : undefined\n };\n\n return (\n <ErrorBoundary>\n {beforeField}\n\n <Suspense fallback={null}>\n <MemoisedField Component={UsedComponent}\n alwaysRender={alwaysRender}\n fieldProps={cmsFieldProps as FieldProps<Property, any, any>}/>\n </Suspense>\n\n {afterField}\n\n {underlyingValueHasChanged && !isSubmitting &&\n <Typography variant={\"caption\"} className={\"ml-3.5\"}>\n {t(\"value_updated_elsewhere\")}\n </Typography>}\n\n </ErrorBoundary>);\n\n}\n\ntype MemoisedFieldProps = {\n Component: ComponentType<FieldProps<Property, any, any>>,\n alwaysRender: boolean,\n fieldProps: FieldProps<Property, any, any>\n};\n\n/**\n * The field's own component, rendered again only when its own slice of the\n * form changed — value, error, touched, the flags — or when the context it\n * draws the record from did (see `fieldContext` in `EntityForm`). Every field\n * of the form used to re-render on every keystroke anywhere in it.\n *\n * A field that may read *another* field's value while rendering cannot know\n * when to re-render from its own props, so those always do: see\n * {@link shouldPropertyReRender}.\n */\nconst MemoisedField = React.memo(\n function MemoisedField({ Component, fieldProps }: MemoisedFieldProps) {\n return <Component {...fieldProps}/>;\n },\n (prev: MemoisedFieldProps, next: MemoisedFieldProps) =>\n !next.alwaysRender &&\n prev.Component === next.Component &&\n sameProps(prev.fieldProps, next.fieldProps, DEEP_COMPARED_FIELD_PROPS)\n);\n\n/**\n * Whether a field has to re-render on every change to the form, because what\n * it draws can depend on values other than its own:\n * - a plugin `fieldBuilder` wraps it in a component of the plugin's;\n * - a custom `admin.Field` gets the whole form through `context`;\n * - `dynamicProps` and `conditions` are functions of every value;\n * - a storage path or file name given as a function is built from the values\n * the binding holds;\n * - a custom `propertyConfig` whose property says any of the above, since the\n * field is resolved through it.\n * Inside maps, arrays and blocks too, since their bindings render the children.\n */\nconst shouldPropertyReRender = (property: Property | undefined, plugins?: RebasePlugin[], propertyConfigs?: Record<string, PropertyConfig>): boolean => {\n if (!property) return false;\n if (plugins?.some((plugin) => plugin.fieldBuilder)) {\n return true;\n }\n const recurse = (child: unknown) => shouldPropertyReRender(child as Property, plugins, propertyConfigs);\n if (isPropertyBuilder(property) || property.conditions || property.admin?.Field) {\n return true;\n }\n const storage = \"storage\" in property ? property.storage : undefined;\n if (storage && (typeof storage.storagePath === \"function\" || typeof storage.fileName === \"function\")) {\n return true;\n }\n const configProperty = property.propertyConfig ? propertyConfigs?.[property.propertyConfig]?.property : undefined;\n if (configProperty && configProperty !== property && recurse(configProperty)) {\n return true;\n }\n if (property.type === \"map\" && property.properties) {\n return Object.values(property.properties).some(recurse);\n }\n if (property.type === \"array\") {\n if (Array.isArray(property.of)) {\n return property.of.some(recurse);\n }\n if (property.of && recurse(property.of)) {\n return true;\n }\n if (property.oneOf?.properties) {\n return Object.values(property.oneOf.properties).some(recurse);\n }\n }\n return false;\n}\n\ninterface UseWrappedComponentParams<M extends Record<string, unknown> = Record<string, unknown>> {\n path?: string,\n collection?: AdminCollection<M>,\n propertyKey: string,\n property: Property,\n Component: ComponentType<FieldProps<Property, unknown, M>>,\n plugins?: RebasePlugin[]\n}\n\nfunction useWrappedComponent<T, M extends Record<string, unknown> = Record<string, unknown>>(\n {\n path,\n collection,\n propertyKey,\n property,\n Component,\n plugins\n }: UseWrappedComponentParams<M>\n): ComponentType<FieldProps<Property, unknown, M>> | null {\n\n // A fold, in plugin order: each plugin's `wrap` is handed the field as the\n // plugins before it left it, so every wrapper renders — the first plugin's\n // closest to the field, the last one's outermost. A plugin that returns\n // null, or is not `enabled` for this field, passes it on unchanged.\n const wrapperRef = useRef<ComponentType<FieldProps<Property, unknown, M>> | null>((() => {\n let Wrapped: ComponentType<FieldProps<Property, unknown, M>> | null = null;\n if (plugins) {\n plugins.forEach((plugin) => {\n const fieldId = getFieldId(property);\n if (fieldId && plugin.fieldBuilder) {\n const params: PluginFieldBuilderParams = {\n fieldConfigId: fieldId,\n propertyKey,\n property,\n Field: (Wrapped ?? Component) as ComponentType<CoreFieldProps<Property, unknown, Record<string, unknown>>>,\n plugin,\n path,\n collection: collection as AdminCollection | undefined\n };\n const enabled = plugin.fieldBuilder.enabled?.(params);\n if (enabled === undefined || enabled)\n Wrapped = (plugin.fieldBuilder.wrap(params) as ComponentType<FieldProps<Property, unknown, M>> | null) ?? Wrapped;\n }\n if (!fieldId) {\n console.warn(\"INTERNAL: Field id not found for property\", property);\n }\n });\n }\n return Wrapped;\n })());\n\n return wrapperRef.current;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,IAAa,uBAAuB,MAAM,KAAK,+BAC1C,GAAuD,MACpD,UAAU,GAAG,GAAG,2BAA2B,CACnD;;;;;;;AAQA,IAAM,8CAA8B,IAAI,IAAI,CAAC,UAAU,CAAC;AACxD,IAAM,4CAA4B,IAAI,IAAI;CAAC;CAAY;CAAS;AAAa,CAAC;AAE9E,SAAS,UAAU,GAAW,GAAW,MAA4B;CACjE,MAAM,uBAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,GAAG,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC;CAC3D,KAAK,MAAM,OAAO,MAAM;EACpB,MAAM,IAAa,QAAQ,IAAI,GAAG,GAAG;EACrC,MAAM,IAAa,QAAQ,IAAI,GAAG,GAAG;EACrC,IAAI,OAAO,GAAG,GAAG,CAAC,GAAG;EACrB,IAAI,KAAK,IAAI,GAAG,KAAK,UAAM,GAAG,CAAC,GAAG;EAClC,OAAO;CACX;CACA,OAAO;AACX;AAEA,SAAS,6BACR,EACI,aACA,UACA,SACA,oBACA,WACA,2BACA,UAAU,cACV,aACA,aACA,gBACA,WACA,OACA,MACA,oBACyE;CAE1E,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,0BAA0B,2BAA2B;CAG3D,MAAM,eAAe,uBAAuB,UAAsB,wBAAwB,SAAS,wBAAwB,eAAe;CAgB1I,MAAM,QAAQ,kBARM,aAAa,YAAmE;EAChG,QAAQ,eAAe,SAAS,KAAA;EAChC,OAAO,MAAM,OAAO,QAAQ,WAAW;EACvC,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;KACY;IAChB;IACA,MAAM,UAAU,OAAO,aAAa,UAAU,MAAM;IACpD,IAAI,YAAY,KAAA,KAAa,SACzB,UAAW,OAAO,aAAa,KAAK,MAAM,KAAgE;GAClH;GACA,IAAI,CAAC,SACD,QAAQ,KAAK,6CAA6C,QAAQ;EAE1E,CAAC;EAEL,OAAO;CACX,EAAA,CAAG,CAEI,CAAA,CAAW;AACtB"}
@@ -1 +1 @@
1
- {"version":3,"file":"BinaryFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/BinaryFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { BinaryProperty } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport { Button, CheckIcon, cls, defaultBorderMixin, IconButton, PencilIcon, TextField, Trash2Icon } from \"@rebasepro/ui\";\n\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/** Base64, optionally padded. Empty is allowed — that is a cleared field. */\nexport const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n\n/** Decoded byte count of a base64 string, without decoding it. */\nexport function decodedBytes(base64: string): number {\n const clean = base64.replace(/\\s/g, \"\");\n if (!clean) return 0;\n const padding = clean.endsWith(\"==\") ? 2 : clean.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, (clean.length * 3) / 4 - padding);\n}\n\nexport function humanSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Field binding for `type: \"binary\"`, whose value is a base64-encoded string.\n *\n * Before this there was no binary field. The widget lookup mapped the type\n * straight to `text_field`, so a binary column rendered as an ordinary string\n * input — offering multiline, markdown and email options that mean nothing for\n * bytes, and, worse, pushing the property through a widget whose editor merges\n * `type: \"string\"`. Opening a binary property and touching its widget silently\n * changed its type.\n *\n * Shown collapsed by default. Base64 is long, unreadable and never worth\n * scrolling past to reach the next field; what a person actually wants to know\n * is whether there is anything in there and how big it is.\n *\n * @group Form fields\n */\nexport function BinaryFieldBinding({\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<BinaryProperty>) {\n\n const stored = typeof value === \"string\" ? value : \"\";\n const [text, setText] = useState(stored);\n const [isEditing, setIsEditing] = useState(false);\n\n useEffect(() => {\n setText(typeof value === \"string\" ? value : \"\");\n }, [value]);\n\n const handleClear = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setText(\"\");\n setValue(null);\n }, [setValue]);\n\n const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const raw = e.target.value;\n setText(raw);\n setValue(raw === \"\" ? null : (raw as never));\n }, [setValue]);\n\n const malformed = text.trim() !== \"\" && !BASE64.test(text.replace(/\\s/g, \"\"));\n const bytes = malformed ? 0 : decodedBytes(text);\n const isPopulated = text.trim() !== \"\";\n\n const localError = malformed ? \"Not valid base64\" : undefined;\n\n return (\n <div className=\"flex flex-col gap-2 w-full\">\n {/* The row goes away with the label rather than emptying out. Left\n unconditional it still contributed its `mb-1` and the column's\n `gap-2`, which — on top of the `mt-2` that used to sit on the\n wrapper — pushed this control 20px below the one next to it\n while the two labels stayed level. */}\n {!hideLabel && <div className=\"flex items-center justify-between mb-1\">\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n />\n </div>}\n\n <div className=\"w-full\">\n {!isEditing ? (\n <div className={cls(\"flex items-center justify-between gap-2 p-4 rounded-xl border bg-surface-field\", defaultBorderMixin)}>\n <div className=\"flex items-center gap-2.5 min-w-0\">\n <div className={`w-2.5 h-2.5 rounded-full shrink-0 ${isPopulated ? \"bg-emerald-500\" : \"bg-surface-300 dark:bg-surface-600\"}`}/>\n <span className=\"text-sm font-semibold text-text-primary truncate\">\n {malformed\n ? \"Invalid base64\"\n : isPopulated ? `${humanSize(bytes)} of binary data` : \"Empty\"}\n </span>\n </div>\n <div className=\"flex items-center gap-2 shrink-0\">\n {!disabled && (\n <Button\n variant=\"outlined\"\n size=\"small\"\n onClick={() => setIsEditing(true)}\n startIcon={<PencilIcon size={14}/>}\n >\n {isPopulated ? \"Edit base64\" : \"Add base64\"}\n </Button>\n )}\n {isPopulated && !disabled && (\n <IconButton\n size=\"small\"\n onClick={handleClear}\n className=\"text-text-secondary hover:text-red-500\"\n aria-label=\"Clear binary value\"\n >\n <Trash2Icon size={14}/>\n </IconButton>\n )}\n </div>\n </div>\n ) : (\n <div className={cls(\"flex flex-col gap-2 p-4 rounded-xl border\", defaultBorderMixin)}>\n <TextField\n size={size}\n aria-label={`${property.name ?? propertyKey} base64 value`}\n value={text}\n onChange={onChange}\n autoFocus={autoFocus ?? true}\n multiline\n minRows={4}\n disabled={disabled}\n placeholder=\"Base64-encoded bytes, e.g. iVBORw0KGgo…\"\n error={showError ? Boolean(error) || malformed : malformed}\n inputClassName={`font-mono text-xs ${malformed ? \"text-red-500\" : \"\"}`}\n />\n <div className=\"flex justify-end\">\n <Button\n variant=\"filled\"\n size=\"small\"\n onClick={() => setIsEditing(false)}\n startIcon={<CheckIcon size={14}/>}\n >\n Done\n </Button>\n </div>\n </div>\n )}\n </div>\n\n <FieldHelperText\n includeDescription={includeDescription}\n showError={showError || malformed}\n error={error || localError}\n disabled={disabled}\n property={property}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,SAAS;;AAGtB,SAAgB,aAAa,QAAwB;CACjD,MAAM,QAAQ,OAAO,QAAQ,OAAO,EAAE;CACtC,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,UAAU,MAAM,SAAS,IAAI,IAAI,IAAI,MAAM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;GAER,CAAA;GAEL,oBAAC,iBAAD;IACwB;IACpB,WAAW,aAAa;IACxB,OAAO,SAAS;IACN;IACA;GACb,CAAA;EACA;;AAEb"}
1
+ {"version":3,"file":"BinaryFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/BinaryFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { BinaryProperty } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport { Button, CheckIcon, cls, defaultBorderMixin, IconButton, PencilIcon, TextField, Trash2Icon } from \"@rebasepro/ui\";\n\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/** Base64, optionally padded. Empty is allowed — that is a cleared field. */\nexport const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n\n/** Decoded byte count of a base64 string, without decoding it. */\nexport function decodedBytes(base64: string): number {\n const clean = base64.replace(/\\s/g, \"\");\n if (!clean) return 0;\n const padding = clean.endsWith(\"==\") ? 2 : clean.endsWith(\"=\") ? 1 : 0;\n return Math.max(0, (clean.length * 3) / 4 - padding);\n}\n\nexport function humanSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Field binding for `type: \"binary\"`, whose value is a base64-encoded string.\n *\n * Before this there was no binary field. The widget lookup mapped the type\n * straight to `text_field`, so a binary column rendered as an ordinary string\n * input — offering multiline, markdown and email options that mean nothing for\n * bytes, and, worse, pushing the property through a widget whose editor merges\n * `type: \"string\"`. Opening a binary property and touching its widget silently\n * changed its type.\n *\n * Shown collapsed by default. Base64 is long, unreadable and never worth\n * scrolling past to reach the next field; what a person actually wants to know\n * is whether there is anything in there and how big it is.\n *\n * @group Form fields\n */\nexport function BinaryFieldBinding({\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<BinaryProperty>) {\n\n const stored = typeof value === \"string\" ? value : \"\";\n const [text, setText] = useState(stored);\n const [isEditing, setIsEditing] = useState(false);\n\n useEffect(() => {\n setText(typeof value === \"string\" ? value : \"\");\n }, [value]);\n\n const handleClear = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setText(\"\");\n setValue(null);\n }, [setValue]);\n\n const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n const raw = e.target.value;\n setText(raw);\n setValue(raw === \"\" ? null : (raw));\n }, [setValue]);\n\n const malformed = text.trim() !== \"\" && !BASE64.test(text.replace(/\\s/g, \"\"));\n const bytes = malformed ? 0 : decodedBytes(text);\n const isPopulated = text.trim() !== \"\";\n\n const localError = malformed ? \"Not valid base64\" : undefined;\n\n return (\n <div className=\"flex flex-col gap-2 w-full\">\n {/* The row goes away with the label rather than emptying out. Left\n unconditional it still contributed its `mb-1` and the column's\n `gap-2`, which — on top of the `mt-2` that used to sit on the\n wrapper — pushed this control 20px below the one next to it\n while the two labels stayed level. */}\n {!hideLabel && <div className=\"flex items-center justify-between mb-1\">\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n />\n </div>}\n\n <div className=\"w-full\">\n {!isEditing ? (\n <div className={cls(\"flex items-center justify-between gap-2 p-4 rounded-xl border bg-surface-field\", defaultBorderMixin)}>\n <div className=\"flex items-center gap-2.5 min-w-0\">\n <div className={`w-2.5 h-2.5 rounded-full shrink-0 ${isPopulated ? \"bg-emerald-500\" : \"bg-surface-300 dark:bg-surface-600\"}`}/>\n <span className=\"text-sm font-semibold text-text-primary truncate\">\n {malformed\n ? \"Invalid base64\"\n : isPopulated ? `${humanSize(bytes)} of binary data` : \"Empty\"}\n </span>\n </div>\n <div className=\"flex items-center gap-2 shrink-0\">\n {!disabled && (\n <Button\n variant=\"outlined\"\n size=\"small\"\n onClick={() => setIsEditing(true)}\n startIcon={<PencilIcon size={14}/>}\n >\n {isPopulated ? \"Edit base64\" : \"Add base64\"}\n </Button>\n )}\n {isPopulated && !disabled && (\n <IconButton\n size=\"small\"\n onClick={handleClear}\n className=\"text-text-secondary hover:text-red-500\"\n aria-label=\"Clear binary value\"\n >\n <Trash2Icon size={14}/>\n </IconButton>\n )}\n </div>\n </div>\n ) : (\n <div className={cls(\"flex flex-col gap-2 p-4 rounded-xl border\", defaultBorderMixin)}>\n <TextField\n size={size}\n aria-label={`${property.name ?? propertyKey} base64 value`}\n value={text}\n onChange={onChange}\n autoFocus={autoFocus ?? true}\n multiline\n minRows={4}\n disabled={disabled}\n placeholder=\"Base64-encoded bytes, e.g. iVBORw0KGgo…\"\n error={showError ? Boolean(error) || malformed : malformed}\n inputClassName={`font-mono text-xs ${malformed ? \"text-red-500\" : \"\"}`}\n />\n <div className=\"flex justify-end\">\n <Button\n variant=\"filled\"\n size=\"small\"\n onClick={() => setIsEditing(false)}\n startIcon={<CheckIcon size={14}/>}\n >\n Done\n </Button>\n </div>\n </div>\n )}\n </div>\n\n <FieldHelperText\n includeDescription={includeDescription}\n showError={showError || malformed}\n error={error || localError}\n disabled={disabled}\n property={property}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,SAAS;;AAGtB,SAAgB,aAAa,QAAwB;CACjD,MAAM,QAAQ,OAAO,QAAQ,OAAO,EAAE;CACtC,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,UAAU,MAAM,SAAS,IAAI,IAAI,IAAI,MAAM,SAAS,GAAG,IAAI,IAAI;CACrE,OAAO,KAAK,IAAI,GAAI,MAAM,SAAS,IAAK,IAAI,OAAO;AACvD;AAEA,SAAgB,UAAU,OAAuB;CAC7C,IAAI,QAAQ,MAAM,OAAO,GAAG,M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],"sources":["../../../src/form/field_bindings/GeopointFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { GeopointProperty } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport { IconButton, TextField, Trash2Icon } from \"@rebasepro/ui\";\n\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/** Latitude runs −90…90, longitude −180…180. Anything else is not a place. */\nconst LAT_RANGE: [number, number] = [-90, 90];\nconst LNG_RANGE: [number, number] = [-180, 180];\n\ninterface Coordinates { latitude: number; longitude: number }\n\n/**\n * Read whatever the driver handed us as a pair of coordinates.\n *\n * A geopoint arrives as a `GeoPoint` instance from the client, but as a plain\n * object once it has been through JSON — and PostGIS-backed rows may present it\n * as `{ x, y }`, where `x` is the longitude. Reading only one of those shapes\n * would render an empty field over data that is actually there.\n */\nexport function readCoordinates(value: unknown): Coordinates | null {\n if (!value || typeof value !== \"object\") return null;\n const v = value as Record<string, unknown>;\n\n const lat = typeof v.latitude === \"number\" ? v.latitude : (typeof v.y === \"number\" ? v.y : undefined);\n const lng = typeof v.longitude === \"number\" ? v.longitude : (typeof v.x === \"number\" ? v.x : undefined);\n\n if (typeof lat !== \"number\" || typeof lng !== \"number\") return null;\n return { latitude: lat, longitude: lng };\n}\n\nconst inRange = (n: number, [min, max]: [number, number]) => n >= min && n <= max;\n\n/**\n * Field binding for `type: \"geopoint\"`.\n *\n * The model has defined this type all along and the admin had no way to render\n * it: the widget lookup fell off the end of its chain, logged to the console\n * and returned undefined, so the field simply did not appear on the form. A\n * geopoint column was invisible in the admin panel, and unreachable in the\n * property editor.\n *\n * Two number inputs rather than a map. A map needs a tile provider, which means\n * a network dependency and an API key, and neither belongs in a field binding\n * that has to work offline and in every deployment. Coordinates are typed,\n * pasted and copied far more often than they are dropped on a map.\n *\n * @group Form fields\n */\nexport function GeopointFieldBinding({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n}: FieldProps<GeopointProperty>) {\n\n const coordinates = readCoordinates(value);\n\n // Held as text while editing: a half-typed \"-\" or \"12.\" is not a number\n // yet, and rounding it through `Number` on every keystroke fights the user.\n const [latText, setLatText] = useState(() => coordinates ? String(coordinates.latitude) : \"\");\n const [lngText, setLngText] = useState(() => coordinates ? String(coordinates.longitude) : \"\");\n\n useEffect(() => {\n const next = readCoordinates(value);\n setLatText(next ? String(next.latitude) : \"\");\n setLngText(next ? String(next.longitude) : \"\");\n }, [coordinates?.latitude, coordinates?.longitude]);\n\n const commit = useCallback((rawLat: string, rawLng: string) => {\n // Both empty means \"no location\", which is different from 0,0 — a real\n // point in the Gulf of Guinea, and the classic way a cleared field\n // turns into a wrong one.\n if (rawLat.trim() === \"\" && rawLng.trim() === \"\") {\n setValue(null);\n return;\n }\n // One side filled and the other still empty is a location half typed,\n // not a location. Committing it would send the empty side through\n // `Number(\"\")`, which is 0 and perfectly finite — so typing a latitude\n // and pausing used to write longitude 0 and drop the point in the Gulf\n // of Guinea. Hold until both sides are there; `halfEntered` below says\n // so in the meantime.\n if (rawLat.trim() === \"\" || rawLng.trim() === \"\") return;\n\n const latitude = Number(rawLat);\n const longitude = Number(rawLng);\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return;\n setValue({ latitude, longitude } as never);\n }, [setValue]);\n\n const handleClear = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setLatText(\"\");\n setLngText(\"\");\n setValue(null);\n }, [setValue]);\n\n const latNumber = Number(latText);\n const lngNumber = Number(lngText);\n const latInvalid = latText.trim() !== \"\" && (!Number.isFinite(latNumber) || !inRange(latNumber, LAT_RANGE));\n const lngInvalid = lngText.trim() !== \"\" && (!Number.isFinite(lngNumber) || !inRange(lngNumber, LNG_RANGE));\n\n // One side filled and the other empty is not a point.\n const halfEntered = (latText.trim() === \"\") !== (lngText.trim() === \"\");\n\n const localError = latInvalid\n ? `Latitude must be between ${LAT_RANGE[0]} and ${LAT_RANGE[1]}`\n : lngInvalid\n ? `Longitude must be between ${LNG_RANGE[0]} and ${LNG_RANGE[1]}`\n : halfEntered\n ? \"A location needs both a latitude and a longitude\"\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-2 w-full\">\n {/* Label only, and only when there is one: a row that survives\n `hideLabel` still spends its `mb-1` and the column's `gap-2`, so\n the pair of inputs sat below the control next to them even\n though the two labels were level. */}\n {!hideLabel && <div className=\"flex items-center justify-between mb-1\">\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n />\n </div>}\n\n {/* Clear sits beside the inputs rather than above them, so\n entering a location does not grow the field by a row and\n knock it out of line with its neighbour. */}\n <div className=\"flex gap-4 w-full items-center\">\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Latitude\"\n value={latText}\n autoFocus={autoFocus}\n disabled={disabled}\n error={showError ? Boolean(error) || latInvalid : latInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLatText(e.target.value);\n commit(e.target.value, lngText);\n }}\n placeholder=\"e.g. 41.3874\"\n inputClassName=\"font-mono\"\n />\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Longitude\"\n value={lngText}\n disabled={disabled}\n error={showError ? Boolean(error) || lngInvalid : lngInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLngText(e.target.value);\n commit(latText, e.target.value);\n }}\n placeholder=\"e.g. 2.1686\"\n inputClassName=\"font-mono\"\n />\n {!disabled && (latText || lngText) && (\n <IconButton\n size=\"small\"\n onClick={handleClear}\n className=\"shrink-0 text-text-secondary hover:text-red-500\"\n aria-label=\"Clear location\"\n >\n <Trash2Icon size={14}/>\n </IconButton>\n )}\n </div>\n\n <FieldHelperText\n includeDescription={includeDescription}\n showError={showError || Bo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ClD,WAAW,MAAiE;OACxE,WAAW,EAAE,OAAO,KAAK;OACzB,OAAO,EAAE,OAAO,OAAO,OAAO;MAClC;MACA,aAAY;MACZ,gBAAe;KAClB,CAAA;KACD,oBAAC,WAAD;MACI,WAAU;MACJ;MACN,OAAM;MACN,OAAO;MACG;MACV,OAAO,YAAY,QAAQ,KAAK,KAAK,aAAa;MAClD,WAAW,MAAiE;OACxE,WAAW,EAAE,OAAO,KAAK;OACzB,OAAO,SAAS,EAAE,OAAO,KAAK;MAClC;MACA,aAAY;MACZ,gBAAe;KAClB,CAAA;KACA,CAAC,aAAa,WAAW,YACtB,oBAAC,YAAD;MACI,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAW;gBAEX,oBAAC,YAAD,EAAY,MAAM,GAAI,CAAA;KACd,CAAA;IAEf;;GAEL,oBAAC,iBAAD;IACwB;IACpB,WAAW,aAAa,QAAQ,UAAU;IAC1C,OAAO,SAAS;IACN;IACA;GACb,CAAA;EACA;;AAEb"}
1
+ {"version":3,"file":"GeopointFieldBinding.js","names":[],"sources":["../../../src/form/field_bindings/GeopointFieldBinding.tsx"],"sourcesContent":["import type { FieldProps } from \"../../types/fields\";\nimport type { GeopointProperty } from \"@rebasepro/types\";\nimport React, { useCallback, useEffect, useState } from \"react\";\nimport { IconButton, TextField, Trash2Icon } from \"@rebasepro/ui\";\n\nimport { FieldHelperText } from \"../components/FieldHelperText\";\nimport { LabelWithIcon } from \"../components/LabelWithIcon\";\nimport { getIconForProperty } from \"../../util/property_utils\";\n\n/** Latitude runs −90…90, longitude −180…180. Anything else is not a place. */\nconst LAT_RANGE: [number, number] = [-90, 90];\nconst LNG_RANGE: [number, number] = [-180, 180];\n\ninterface Coordinates { latitude: number; longitude: number }\n\n/**\n * Read whatever the driver handed us as a pair of coordinates.\n *\n * A geopoint arrives as a `GeoPoint` instance from the client, but as a plain\n * object once it has been through JSON — and PostGIS-backed rows may present it\n * as `{ x, y }`, where `x` is the longitude. Reading only one of those shapes\n * would render an empty field over data that is actually there.\n */\nexport function readCoordinates(value: unknown): Coordinates | null {\n if (!value || typeof value !== \"object\") return null;\n const v = value as Record<string, unknown>;\n\n const lat = typeof v.latitude === \"number\" ? v.latitude : (typeof v.y === \"number\" ? v.y : undefined);\n const lng = typeof v.longitude === \"number\" ? v.longitude : (typeof v.x === \"number\" ? v.x : undefined);\n\n if (typeof lat !== \"number\" || typeof lng !== \"number\") return null;\n return { latitude: lat, longitude: lng };\n}\n\nconst inRange = (n: number, [min, max]: [number, number]) => n >= min && n <= max;\n\n/**\n * Field binding for `type: \"geopoint\"`.\n *\n * The model has defined this type all along and the admin had no way to render\n * it: the widget lookup fell off the end of its chain, logged to the console\n * and returned undefined, so the field simply did not appear on the form. A\n * geopoint column was invisible in the admin panel, and unreachable in the\n * property editor.\n *\n * Two number inputs rather than a map. A map needs a tile provider, which means\n * a network dependency and an API key, and neither belongs in a field binding\n * that has to work offline and in every deployment. Coordinates are typed,\n * pasted and copied far more often than they are dropped on a map.\n *\n * @group Form fields\n */\nexport function GeopointFieldBinding({\n propertyKey,\n value,\n setValue,\n error,\n showError,\n disabled,\n autoFocus,\n property,\n includeDescription,\n hideLabel,\n size = \"large\"\n}: FieldProps<GeopointProperty>) {\n\n const coordinates = readCoordinates(value);\n\n // Held as text while editing: a half-typed \"-\" or \"12.\" is not a number\n // yet, and rounding it through `Number` on every keystroke fights the user.\n const [latText, setLatText] = useState(() => coordinates ? String(coordinates.latitude) : \"\");\n const [lngText, setLngText] = useState(() => coordinates ? String(coordinates.longitude) : \"\");\n\n useEffect(() => {\n const next = readCoordinates(value);\n setLatText(next ? String(next.latitude) : \"\");\n setLngText(next ? String(next.longitude) : \"\");\n }, [coordinates?.latitude, coordinates?.longitude]);\n\n const commit = useCallback((rawLat: string, rawLng: string) => {\n // Both empty means \"no location\", which is different from 0,0 — a real\n // point in the Gulf of Guinea, and the classic way a cleared field\n // turns into a wrong one.\n if (rawLat.trim() === \"\" && rawLng.trim() === \"\") {\n setValue(null);\n return;\n }\n // One side filled and the other still empty is a location half typed,\n // not a location. Committing it would send the empty side through\n // `Number(\"\")`, which is 0 and perfectly finite — so typing a latitude\n // and pausing used to write longitude 0 and drop the point in the Gulf\n // of Guinea. Hold until both sides are there; `halfEntered` below says\n // so in the meantime.\n if (rawLat.trim() === \"\" || rawLng.trim() === \"\") return;\n\n const latitude = Number(rawLat);\n const longitude = Number(rawLng);\n if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return;\n setValue({ latitude, longitude });\n }, [setValue]);\n\n const handleClear = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n e.preventDefault();\n setLatText(\"\");\n setLngText(\"\");\n setValue(null);\n }, [setValue]);\n\n const latNumber = Number(latText);\n const lngNumber = Number(lngText);\n const latInvalid = latText.trim() !== \"\" && (!Number.isFinite(latNumber) || !inRange(latNumber, LAT_RANGE));\n const lngInvalid = lngText.trim() !== \"\" && (!Number.isFinite(lngNumber) || !inRange(lngNumber, LNG_RANGE));\n\n // One side filled and the other empty is not a point.\n const halfEntered = (latText.trim() === \"\") !== (lngText.trim() === \"\");\n\n const localError = latInvalid\n ? `Latitude must be between ${LAT_RANGE[0]} and ${LAT_RANGE[1]}`\n : lngInvalid\n ? `Longitude must be between ${LNG_RANGE[0]} and ${LNG_RANGE[1]}`\n : halfEntered\n ? \"A location needs both a latitude and a longitude\"\n : undefined;\n\n return (\n <div className=\"flex flex-col gap-2 w-full\">\n {/* Label only, and only when there is one: a row that survives\n `hideLabel` still spends its `mb-1` and the column's `gap-2`, so\n the pair of inputs sat below the control next to them even\n though the two labels were level. */}\n {!hideLabel && <div className=\"flex items-center justify-between mb-1\">\n <LabelWithIcon\n icon={getIconForProperty(property, \"small\")}\n required={property.validation?.required}\n title={property.name ?? propertyKey}\n />\n </div>}\n\n {/* Clear sits beside the inputs rather than above them, so\n entering a location does not grow the field by a row and\n knock it out of line with its neighbour. */}\n <div className=\"flex gap-4 w-full items-center\">\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Latitude\"\n value={latText}\n autoFocus={autoFocus}\n disabled={disabled}\n error={showError ? Boolean(error) || latInvalid : latInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLatText(e.target.value);\n commit(e.target.value, lngText);\n }}\n placeholder=\"e.g. 41.3874\"\n inputClassName=\"font-mono\"\n />\n <TextField\n className=\"flex-1\"\n size={size}\n label=\"Longitude\"\n value={lngText}\n disabled={disabled}\n error={showError ? Boolean(error) || lngInvalid : lngInvalid}\n onChange={(e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {\n setLngText(e.target.value);\n commit(latText, e.target.value);\n }}\n placeholder=\"e.g. 2.1686\"\n inputClassName=\"font-mono\"\n />\n {!disabled && (latText || lngText) && (\n <IconButton\n size=\"small\"\n onClick={handleClear}\n className=\"shrink-0 text-text-secondary hover:text-red-500\"\n aria-label=\"Clear location\"\n >\n <Trash2Icon size={14}/>\n </IconButton>\n )}\n </div>\n\n <FieldHelperText\n includeDescription={includeDescription}\n showError={showError || Boolean(localError)}\n error={error || localError}\n disabled={disabled}\n property={property}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;AAUA,IAAM,YAA8B,CAAC,KAAK,EAAE;AAC5C,IAAM,YAA8B,CAAC,MAAM,GAAG;;;;;;;;;AAY9C,SAAgB,gBAAgB,OAAoC;CAChE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,IAAI;CAEV,MAAM,MAAM,OAAO,EAAE,aAAa,WAAW,EAAE,WAAY,OAAO,EAAE,MAAM,WAAW,EAAE,IAAI,KAAA;CAC3F,MAAM,MAAM,OAAO,EAAE,cAAc,WAAW,EAAE,YAAa,OAAO,EAAE,MAAM,WAAW,EAAE,IAAI,KAAA;CAE7F,IAAI,OAAO,QAAQ,YAAY,OAAO,QAAQ,UAAU,OAAO;CAC/D,OAAO;EAAE,UAAU;EAAK,WAAW;CAAI;AAC3C;AAEA,IAAM,WAAW,GAAW,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;IACA;GACb,CAAA;EACA;;AAEb"}
@@ -16,5 +16,15 @@ import { AuthController } from "@rebasepro/cms-types";
16
16
  * its metadata rail — capped so it never eats the whole window.
17
17
  */
18
18
  export declare function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string;
19
+ /**
20
+ * Accept the names `open` / `replace` took in 0.28: `entityId` for `id`, and
21
+ * `onUpdate` for `onSaved`. Untyped callers still passing them would
22
+ * otherwise open a blank "new record" form for a record that exists (and
23
+ * duplicate it on save), and never hear about the save.
24
+ *
25
+ * `onUpdate` used to receive the saved entity; it now gets `{ entity }` built
26
+ * from the saved row, after any `onSaved`.
27
+ */
28
+ export declare function normalizeDeprecatedSidePanelProps<M extends Record<string, unknown>>(props: SidePanelBindingProps<M>): SidePanelBindingProps<M>;
19
29
  export declare const useBuildSidePanel: (collectionRegistryController: CollectionRegistryController, urlController: UrlController, navigationStateController: NavigationStateController, sideDialogsController: SideDialogsController, authController: AuthController) => SidePanelController;
20
30
  export declare function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[];