@rebasepro/cms 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js +1 -1
  2. package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js.map +1 -1
  3. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.d.ts +7 -1
  4. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +9 -2
  5. package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
  6. package/dist/collection_editor/useLiveSchemaEditing.js +4 -1
  7. package/dist/collection_editor/useLiveSchemaEditing.js.map +1 -1
  8. package/dist/components/CollectionTableBinding/fields/TableReferenceField.js +1 -1
  9. package/dist/components/CollectionTableBinding/fields/TableReferenceField.js.map +1 -1
  10. package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.d.ts +1 -2
  11. package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js.map +1 -1
  12. package/dist/components/CollectionTableBinding/internal/EntityTableCell.d.ts +1 -2
  13. package/dist/components/CollectionTableBinding/internal/EntityTableCell.js.map +1 -1
  14. package/dist/components/CollectionViewBinding/CollectionViewActions.js +1 -1
  15. package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
  16. package/dist/components/CollectionViewBinding/CollectionViewBinding.js +2 -28
  17. package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
  18. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.d.ts +12 -0
  19. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js +33 -0
  20. package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js.map +1 -0
  21. package/dist/components/CollectionsScopeContext.d.ts +5 -1
  22. package/dist/components/CollectionsScopeContext.js +10 -2
  23. package/dist/components/CollectionsScopeContext.js.map +1 -1
  24. package/dist/components/DefaultAppBar.js +2 -1
  25. package/dist/components/DefaultAppBar.js.map +1 -1
  26. package/dist/components/DefaultDrawer.js +16 -4
  27. package/dist/components/DefaultDrawer.js.map +1 -1
  28. package/dist/components/DefaultMissingReference.d.ts +8 -0
  29. package/dist/components/DefaultMissingReference.js +13 -0
  30. package/dist/components/DefaultMissingReference.js.map +1 -0
  31. package/dist/components/EntityFormPanel.d.ts +7 -2
  32. package/dist/components/EntityFormPanel.js +72 -29
  33. package/dist/components/EntityFormPanel.js.map +1 -1
  34. package/dist/components/HomePage/ContentHomePage.js +4 -3
  35. package/dist/components/HomePage/ContentHomePage.js.map +1 -1
  36. package/dist/components/HomePage/HomePageDnD.js +3 -1
  37. package/dist/components/HomePage/HomePageDnD.js.map +1 -1
  38. package/dist/components/HomePage/SmallNavigationCard.js +25 -0
  39. package/dist/components/HomePage/SmallNavigationCard.js.map +1 -0
  40. package/dist/components/RebaseAuthGate.js +3 -2
  41. package/dist/components/RebaseAuthGate.js.map +1 -1
  42. package/dist/components/RebaseLayout.d.ts +4 -1
  43. package/dist/components/RebaseLayout.js +7 -1
  44. package/dist/components/RebaseLayout.js.map +1 -1
  45. package/dist/components/RebaseShell.d.ts +4 -1
  46. package/dist/components/RebaseShell.js.map +1 -1
  47. package/dist/components/SideDialogs.js +10 -4
  48. package/dist/components/SideDialogs.js.map +1 -1
  49. package/dist/components/app/Scaffold.js +5 -1
  50. package/dist/components/app/Scaffold.js.map +1 -1
  51. package/dist/components/field_configs.js +1 -1
  52. package/dist/components/history/EntityHistoryView.js +6 -4
  53. package/dist/components/history/EntityHistoryView.js.map +1 -1
  54. package/dist/components/history/LastEditedByIndicator.d.ts +2 -1
  55. package/dist/data_export/export/export.d.ts +2 -13
  56. package/dist/data_export/export/export.js +1 -36
  57. package/dist/data_export/export/export.js.map +1 -1
  58. package/dist/form/EntityForm.d.ts +1 -1
  59. package/dist/form/EntityForm.js +17 -13
  60. package/dist/form/EntityForm.js.map +1 -1
  61. package/dist/form/EntityFormBinding.d.ts +1 -1
  62. package/dist/form/EntityFormBinding.js +42 -4
  63. package/dist/form/EntityFormBinding.js.map +1 -1
  64. package/dist/form/PropertyFieldBinding.js +1 -1
  65. package/dist/form/components/FieldBlock.d.ts +8 -1
  66. package/dist/form/components/FieldBlock.js +16 -2
  67. package/dist/form/components/FieldBlock.js.map +1 -1
  68. package/dist/form/components/FormSections.js +1 -1
  69. package/dist/form/components/FormSections.js.map +1 -1
  70. package/dist/form/components/LabelWithIcon.js +5 -2
  71. package/dist/form/components/LabelWithIcon.js.map +1 -1
  72. package/dist/form/field_bindings/DateTimeFieldBinding.js +2 -1
  73. package/dist/form/field_bindings/DateTimeFieldBinding.js.map +1 -1
  74. package/dist/form/field_bindings/ReadOnlyFieldBinding.js +28 -1
  75. package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
  76. package/dist/form/field_bindings/RelationFieldBinding.js +7 -3
  77. package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
  78. package/dist/form/field_bindings/SelectFieldBinding.js +63 -42
  79. package/dist/form/field_bindings/SelectFieldBinding.js.map +1 -1
  80. package/dist/form/field_bindings/SwitchFieldBinding.js +2 -1
  81. package/dist/form/field_bindings/SwitchFieldBinding.js.map +1 -1
  82. package/dist/form/field_bindings/TextFieldBinding.js +8 -6
  83. package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
  84. package/dist/form/form_utils.d.ts +18 -1
  85. package/dist/form/form_utils.js +38 -2
  86. package/dist/form/form_utils.js.map +1 -1
  87. package/dist/form/index.d.ts +1 -1
  88. package/dist/form/label_placement.d.ts +23 -0
  89. package/dist/form/label_placement.js +71 -0
  90. package/dist/form/label_placement.js.map +1 -0
  91. package/dist/form/resolve_form_properties.d.ts +35 -3
  92. package/dist/form/resolve_form_properties.js +67 -6
  93. package/dist/form/resolve_form_properties.js.map +1 -1
  94. package/dist/hooks/useHistory.d.ts +5 -0
  95. package/dist/hooks/useHistory.js +22 -6
  96. package/dist/hooks/useHistory.js.map +1 -1
  97. package/dist/index.d.ts +50 -0
  98. package/dist/index.js +34 -7
  99. package/dist/preview/components/ReferencePreview.js +1 -1
  100. package/dist/preview/components/ReferencePreview.js.map +1 -1
  101. package/dist/preview/components/RelationPreview.js +1 -1
  102. package/dist/preview/components/RelationPreview.js.map +1 -1
  103. package/dist/types/components/EntityFormProps.d.ts +11 -0
  104. package/package.json +11 -10
  105. package/recipes/README.md +131 -0
  106. package/recipes/bulk-set-status.tsx +62 -0
  107. package/recipes/calendar-view.tsx +123 -0
  108. package/recipes/custom-login.tsx +60 -0
  109. package/recipes/my-preferences.tsx +68 -0
  110. package/recipes/orders-dashboard.tsx +125 -0
  111. package/recipes/site-settings.tsx +63 -0
@@ -102,7 +102,7 @@ function AICollectionGeneratorPopover({ existingCollection, onGenerated, generat
102
102
  },
103
103
  trigger: trigger ?? defaultTrigger,
104
104
  children: /* @__PURE__ */ jsxs("div", {
105
- className: "p-4 flex flex-col gap-3 min-w-[360px] max-w-[480px]",
105
+ className: "p-4 flex flex-col gap-3 w-[calc(100vw-2rem)] sm:w-auto sm:min-w-[360px] max-w-[480px]",
106
106
  children: [
107
107
  /* @__PURE__ */ jsxs("div", {
108
108
  className: "flex items-center gap-2",
@@ -1 +1 @@
1
- {"version":3,"file":"AICollectionGeneratorPopover.js","names":[],"sources":["../../../../src/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.tsx"],"sourcesContent":["\nimport { AIIcon, useTranslation } from \"@rebasepro/app\";\nimport { useCollectionRegistryController } from \"../../_cms_internals\";\nimport React, { useState } from \"react\";\nimport { useSafeSnackbarController } from \"../../useSafeSnackbarController\";\n\nimport {\n Button,\n CircularProgress,\n IconButton,\n Menu,\n SendIcon,\n TextField,\n Tooltip,\n Typography\n} from \"@rebasepro/ui\";\nimport {\n CollectionGenerationCallback,\n CollectionGenerationApiError,\n CollectionOperation\n} from \"../../api/generateCollectionApi\";\nimport { useCollectionsConfigController } from \"../../useCollectionsConfigController\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\nexport interface AICollectionGeneratorPopoverProps {\n /**\n * Current collection being edited (if modifying an existing collection)\n */\n existingCollection?: AdminCollection<any>;\n\n /**\n * Callback when a collection is generated or modified.\n * Includes the collection and optionally the operations that were applied.\n */\n onGenerated: (collection: AdminCollection, operations?: CollectionOperation[]) => void;\n\n /**\n * Callback function for generating/modifying collections.\n * The plugin is API-agnostic - the consumer provides the implementation.\n */\n generateCollection: CollectionGenerationCallback;\n\n /**\n * Optional custom trigger button. If not provided, a default AI button is used.\n */\n trigger?: React.ReactNode | any;\n\n /**\n * Size of the button\n */\n size?: \"small\" | \"medium\" | \"large\";\n\n /**\n * Whether to show the label text\n */\n showLabel?: boolean;\n\n /**\n * Optional analytics callback\n */\n onAnalyticsEvent?: (event: string, params?: object) => void;\n}\n\nexport function AICollectionGeneratorPopover({\n existingCollection,\n onGenerated,\n generateCollection,\n trigger,\n size = \"small\",\n showLabel = true,\n onAnalyticsEvent\n}: AICollectionGeneratorPopoverProps) {\n const { t } = useTranslation();\n const [menuOpen, setMenuOpen] = useState(false);\n const [prompt, setPrompt] = useState(\"\");\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const collectionRegistry = useCollectionRegistryController();\n const configController = useCollectionsConfigController();\n const snackbarController = useSafeSnackbarController();\n\n const existingCollections = collectionRegistry.collections ?? [];\n\n const handleGenerate = async () => {\n if (!prompt.trim()) return;\n\n setLoading(true);\n setError(null);\n\n const mode = existingCollection ? \"modify\" : \"create\";\n onAnalyticsEvent?.(\"ai_collection_generate_start\", { mode });\n\n try {\n const collectionsContext = existingCollections.map(c => ({\n slug: c.slug,\n name: c.name,\n properties: c.properties,\n propertiesOrder: c.propertiesOrder\n } as Partial<AdminCollection>));\n\n const result = await generateCollection({\n prompt: prompt.trim(),\n existingCollections: collectionsContext.slice(0, 30),\n ...(existingCollection && {\n existingCollection: {\n slug: existingCollection.slug,\n name: existingCollection.name,\n properties: existingCollection.properties,\n propertiesOrder: existingCollection.propertiesOrder\n } as Partial<AdminCollection>\n })\n });\n\n onGenerated(result.collection, result.operations);\n setMenuOpen(false);\n setPrompt(\"\");\n onAnalyticsEvent?.(\"ai_collection_generate_success\", {\n mode,\n operationsCount: result.operations?.length\n });\n snackbarController?.open({\n type: \"success\",\n message: existingCollection\n ? \"Collection updated with AI suggestions\"\n : \"Collection generated successfully\"\n });\n } catch (e) {\n console.error(\"Error generating collection:\", e);\n const errorMessage = e instanceof CollectionGenerationApiError\n ? e.message\n : \"Failed to generate collection. Please try again.\";\n setError(errorMessage);\n onAnalyticsEvent?.(\"ai_collection_generate_error\", {\n mode,\n error: errorMessage\n });\n snackbarController?.open({\n type: \"error\",\n message: errorMessage\n });\n } finally {\n setLoading(false);\n }\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n const tooltipTitle = configController?.readOnly\n ? (configController.readOnlyReason || \"Collection generation is disabled\")\n : undefined;\n\n const defaultTrigger = showLabel ? (\n <Tooltip title={tooltipTitle} asChild={true}>\n <Button\n variant=\"text\"\n size={size}\n disabled={loading || configController?.readOnly}\n startIcon={loading\n ? <CircularProgress size=\"smallest\"/>\n : <AIIcon size=\"small\"/>\n }\n >\n AI Assist\n </Button>\n </Tooltip>\n ) : (\n <Tooltip title={tooltipTitle} asChild={true}>\n <IconButton\n size={size}\n disabled={loading || configController?.readOnly}\n aria-label=\"AI Assist\"\n >\n {loading\n ? <CircularProgress size=\"smallest\"/>\n : <AIIcon size=\"small\"/>\n }\n </IconButton>\n </Tooltip>\n );\n\n return (\n <Menu\n open={menuOpen}\n onOpenChange={(open) => {\n setMenuOpen(open);\n if (!open) {\n setError(null);\n }\n }}\n trigger={trigger ?? defaultTrigger}\n >\n <div className=\"p-4 flex flex-col gap-3 min-w-[360px] max-w-[480px]\">\n <div className=\"flex items-center gap-2\">\n <AIIcon size=\"small\"/>\n <Typography variant=\"subtitle2\">\n {existingCollection ? \"Modify Collection with AI\" : \"Generate Collection with AI\"}\n </Typography>\n </div>\n\n <Typography variant=\"caption\" color=\"secondary\">\n {existingCollection\n ? t(\"describe_changes_to_make\")\n : t(\"describe_collection_to_create\")\n }\n </Typography>\n\n <TextField\n size=\"small\"\n multiline\n autoFocus\n aria-label={existingCollection\n ? t(\"describe_changes_to_make\")\n : t(\"describe_collection_to_create\")\n }\n className=\"w-full text-text-primary dark:text-text-primary-dark\"\n value={prompt}\n onChange={(e) => setPrompt(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={existingCollection\n ? \"e.g., Add a thumbnail image field with storage, make price required...\"\n : \"e.g., Create a products collection with name, price, description, and category...\"\n }\n disabled={loading}\n />\n\n {error && (\n <Typography variant=\"caption\" className=\"text-red-500\">\n {error}\n </Typography>\n )}\n\n <div className=\"flex justify-end gap-2\">\n <Button\n variant=\"text\"\n size=\"small\"\n onClick={() => setMenuOpen(false)}\n disabled={loading}\n >\n Cancel\n </Button>\n <Button\n variant=\"filled\"\n size=\"small\"\n onClick={handleGenerate}\n disabled={!prompt.trim() || loading}\n startIcon={loading ? <CircularProgress size=\"smallest\"/> : undefined}\n >\n {loading ? \"Generating...\" : \"Generate\"}\n </Button>\n </div>\n </div>\n </Menu>\n );\n}\n"],"mappings":";;;;;;;;;AA+DA,SAAgB,6BAA6B,EACzC,oBACA,aACA,oBACA,SACA,OAAO,SACP,YAAY,MACZ,oBACkC;CAClC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,QAAQ,aAAa,SAAS,EAAE;CACvC,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAC5C,MAAM,CAAC,OAAO,YAAY,SAAwB,IAAI;CAEtD,MAAM,qBAAqB,gCAAgC;CAC3D,MAAM,mBAAmB,+BAA+B;CACxD,MAAM,qBAAqB,0BAA0B;CAErD,MAAM,sBAAsB,mBAAmB,eAAe,CAAC;CAE/D,MAAM,iBA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MACL,eAAe,YAAY,KAAK;MAChC,UAAU;gBACb;KAEO,CAAA,GACR,oBAAC,QAAD;MACI,SAAQ;MACR,MAAK;MACL,SAAS;MACT,UAAU,CAAC,OAAO,KAAK,KAAK;MAC5B,WAAW,UAAU,oBAAC,kBAAD,EAAkB,MAAK,WAAW,CAAA,IAAI,KAAA;gBAE1D,UAAU,kBAAkB;KACzB,CAAA,CACP;;GACJ;;CACH,CAAA;AAEd"}
1
+ {"version":3,"file":"AICollectionGeneratorPopover.js","names":[],"sources":["../../../../src/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.tsx"],"sourcesContent":["\nimport { AIIcon, useTranslation } from \"@rebasepro/app\";\nimport { useCollectionRegistryController } from \"../../_cms_internals\";\nimport React, { useState } from \"react\";\nimport { useSafeSnackbarController } from \"../../useSafeSnackbarController\";\n\nimport {\n Button,\n CircularProgress,\n IconButton,\n Menu,\n SendIcon,\n TextField,\n Tooltip,\n Typography\n} from \"@rebasepro/ui\";\nimport {\n CollectionGenerationCallback,\n CollectionGenerationApiError,\n CollectionOperation\n} from \"../../api/generateCollectionApi\";\nimport { useCollectionsConfigController } from \"../../useCollectionsConfigController\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\nexport interface AICollectionGeneratorPopoverProps {\n /**\n * Current collection being edited (if modifying an existing collection)\n */\n existingCollection?: AdminCollection<any>;\n\n /**\n * Callback when a collection is generated or modified.\n * Includes the collection and optionally the operations that were applied.\n */\n onGenerated: (collection: AdminCollection, operations?: CollectionOperation[]) => void;\n\n /**\n * Callback function for generating/modifying collections.\n * The plugin is API-agnostic - the consumer provides the implementation.\n */\n generateCollection: CollectionGenerationCallback;\n\n /**\n * Optional custom trigger button. If not provided, a default AI button is used.\n */\n trigger?: React.ReactNode | any;\n\n /**\n * Size of the button\n */\n size?: \"small\" | \"medium\" | \"large\";\n\n /**\n * Whether to show the label text\n */\n showLabel?: boolean;\n\n /**\n * Optional analytics callback\n */\n onAnalyticsEvent?: (event: string, params?: object) => void;\n}\n\nexport function AICollectionGeneratorPopover({\n existingCollection,\n onGenerated,\n generateCollection,\n trigger,\n size = \"small\",\n showLabel = true,\n onAnalyticsEvent\n}: AICollectionGeneratorPopoverProps) {\n const { t } = useTranslation();\n const [menuOpen, setMenuOpen] = useState(false);\n const [prompt, setPrompt] = useState(\"\");\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const collectionRegistry = useCollectionRegistryController();\n const configController = useCollectionsConfigController();\n const snackbarController = useSafeSnackbarController();\n\n const existingCollections = collectionRegistry.collections ?? [];\n\n const handleGenerate = async () => {\n if (!prompt.trim()) return;\n\n setLoading(true);\n setError(null);\n\n const mode = existingCollection ? \"modify\" : \"create\";\n onAnalyticsEvent?.(\"ai_collection_generate_start\", { mode });\n\n try {\n const collectionsContext = existingCollections.map(c => ({\n slug: c.slug,\n name: c.name,\n properties: c.properties,\n propertiesOrder: c.propertiesOrder\n } as Partial<AdminCollection>));\n\n const result = await generateCollection({\n prompt: prompt.trim(),\n existingCollections: collectionsContext.slice(0, 30),\n ...(existingCollection && {\n existingCollection: {\n slug: existingCollection.slug,\n name: existingCollection.name,\n properties: existingCollection.properties,\n propertiesOrder: existingCollection.propertiesOrder\n } as Partial<AdminCollection>\n })\n });\n\n onGenerated(result.collection, result.operations);\n setMenuOpen(false);\n setPrompt(\"\");\n onAnalyticsEvent?.(\"ai_collection_generate_success\", {\n mode,\n operationsCount: result.operations?.length\n });\n snackbarController?.open({\n type: \"success\",\n message: existingCollection\n ? \"Collection updated with AI suggestions\"\n : \"Collection generated successfully\"\n });\n } catch (e) {\n console.error(\"Error generating collection:\", e);\n const errorMessage = e instanceof CollectionGenerationApiError\n ? e.message\n : \"Failed to generate collection. Please try again.\";\n setError(errorMessage);\n onAnalyticsEvent?.(\"ai_collection_generate_error\", {\n mode,\n error: errorMessage\n });\n snackbarController?.open({\n type: \"error\",\n message: errorMessage\n });\n } finally {\n setLoading(false);\n }\n };\n\n const handleKeyDown = (e: React.KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n e.preventDefault();\n handleGenerate();\n }\n };\n\n const tooltipTitle = configController?.readOnly\n ? (configController.readOnlyReason || \"Collection generation is disabled\")\n : undefined;\n\n const defaultTrigger = showLabel ? (\n <Tooltip title={tooltipTitle} asChild={true}>\n <Button\n variant=\"text\"\n size={size}\n disabled={loading || configController?.readOnly}\n startIcon={loading\n ? <CircularProgress size=\"smallest\"/>\n : <AIIcon size=\"small\"/>\n }\n >\n AI Assist\n </Button>\n </Tooltip>\n ) : (\n <Tooltip title={tooltipTitle} asChild={true}>\n <IconButton\n size={size}\n disabled={loading || configController?.readOnly}\n aria-label=\"AI Assist\"\n >\n {loading\n ? <CircularProgress size=\"smallest\"/>\n : <AIIcon size=\"small\"/>\n }\n </IconButton>\n </Tooltip>\n );\n\n return (\n <Menu\n open={menuOpen}\n onOpenChange={(open) => {\n setMenuOpen(open);\n if (!open) {\n setError(null);\n }\n }}\n trigger={trigger ?? defaultTrigger}\n >\n {/* A phone's width less its margins below `sm`, as the panel is\n positioned inside the viewport but never shrunk to it. */}\n <div className=\"p-4 flex flex-col gap-3 w-[calc(100vw-2rem)] sm:w-auto sm:min-w-[360px] max-w-[480px]\">\n <div className=\"flex items-center gap-2\">\n <AIIcon size=\"small\"/>\n <Typography variant=\"subtitle2\">\n {existingCollection ? \"Modify Collection with AI\" : \"Generate Collection with AI\"}\n </Typography>\n </div>\n\n <Typography variant=\"caption\" color=\"secondary\">\n {existingCollection\n ? t(\"describe_changes_to_make\")\n : t(\"describe_collection_to_create\")\n }\n </Typography>\n\n <TextField\n size=\"small\"\n multiline\n autoFocus\n aria-label={existingCollection\n ? t(\"describe_changes_to_make\")\n : t(\"describe_collection_to_create\")\n }\n className=\"w-full text-text-primary dark:text-text-primary-dark\"\n value={prompt}\n onChange={(e) => setPrompt(e.target.value)}\n onKeyDown={handleKeyDown}\n placeholder={existingCollection\n ? \"e.g., Add a thumbnail image field with storage, make price required...\"\n : \"e.g., Create a products collection with name, price, description, and category...\"\n }\n disabled={loading}\n />\n\n {error && (\n <Typography variant=\"caption\" className=\"text-red-500\">\n {error}\n </Typography>\n )}\n\n <div className=\"flex justify-end gap-2\">\n <Button\n variant=\"text\"\n size=\"small\"\n onClick={() => setMenuOpen(false)}\n disabled={loading}\n >\n Cancel\n </Button>\n <Button\n variant=\"filled\"\n size=\"small\"\n onClick={handleGenerate}\n disabled={!prompt.trim() || loading}\n startIcon={loading ? <CircularProgress size=\"smallest\"/> : undefined}\n >\n {loading ? \"Generating...\" : \"Generate\"}\n </Button>\n </div>\n </div>\n </Menu>\n );\n}\n"],"mappings":";;;;;;;;;AA+DA,SAAgB,6BAA6B,EACzC,oBACA,aACA,oBACA,SACA,OAAO,SACP,YAAY,MACZ,oBACkC;CAClC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,CAAC,QAAQ,aAAa,SAAS,EAAE;CACvC,MAAM,CAAC,SAAS,cAAc,SAAS,KAAK;CAC5C,MAAM,CAAC,OAAO,YAAY,SAAwB,IAAI;CAEtD,MAAM,qBAAqB,gCAAgC;CAC3D,MAAM,mBAAmB,+BAA+B;CACxD,MAAM,qBAAqB,0BAA0B;CAErD,MAAM,sBAAsB,mBAAmB,eAAe,CAAC;CAE/D,MAAM,iBAAiB,YAAY;EAC/B,IAAI,CAAC,OAAO,KAAK,GAAG;EAEpB,WAAW,IAAI;EACf,SAAS,IAAI;EAEb,MAAM,OAAO,qBAAqB,WAAW;EAC7C,mBAAmB,gCAAgC,EAAE,KAAK,CAAC;EAE3D,IAAI;GACA,MAAM,qBAAqB,oBAAoB,KAAI,OAAM;IACrD,MAAM,EAAE;IACR,MAAM,EAAE;IACR,YAAY,EAAE;IACd,iBAAiB,EAAE;GACvB,EAA8B;GAE9B,MAAM,SAAS,MAAM,mBAAmB;IACpC,QAAQ,OAAO,KAAK;IACpB,qBAAqB,mBAAmB,MAAM,GAAG,E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,QAAQ,CAAA;EAEnB,CAAA;CACP,CAAA;CAGb,OACI,oBAAC,MAAD;EACI,MAAM;EACN,eAAe,SAAS;GACpB,YAAY,IAAI;GAChB,IAAI,CAAC,MACD,SAAS,IAAI;EAErB;EACA,SAAS,WAAW;YAIpB,qBAAC,OAAD;GAAK,WAAU;aAAf;IACI,qBAAC,OAAD;KAAK,WAAU;eAAf,CACI,oBAAC,QAAD,EAAQ,MAAK,QAAQ,CAAA,GACrB,oBAAC,YAAD;MAAY,SAAQ;gBACf,qBAAqB,8BAA8B;KAC5C,CAAA,CACX;;IAEL,oBAAC,YAAD;KAAY,SAAQ;KAAU,OAAM;eAC/B,qBACK,EAAE,0BAA0B,IAC5B,EAAE,+BAA+B;IAE/B,CAAA;IAEZ,oBAAC,WAAD;KACI,MAAK;KACL,WAAA;KACA,WAAA;KACA,cAAY,qBACN,EAAE,0BAA0B,IAC5B,EAAE,+BAA+B;KAEvC,WAAU;KACV,OAAO;KACP,WAAW,MAAM,UAAU,EAAE,OAAO,KAAK;KACzC,WAAW;KACX,aAAa,qBACP,2EACA;KAEN,UAAU;IACb,CAAA;IAEA,SACG,oBAAC,YAAD;KAAY,SAAQ;KAAU,WAAU;eACnC;IACO,CAAA;IAGhB,qBAAC,OAAD;KAAK,WAAU;eAAf,CACI,oBAAC,QAAD;MACI,SAAQ;MACR,MAAK;MACL,eAAe,YAAY,KAAK;MAChC,UAAU;gBACb;KAEO,CAAA,GACR,oBAAC,QAAD;MACI,SAAQ;MACR,MAAK;MACL,SAAS;MACT,UAAU,CAAC,OAAO,KAAK,KAAK;MAC5B,WAAW,UAAU,oBAAC,kBAAD,EAAkB,MAAK,WAAW,CAAA,IAAI,KAAA;gBAE1D,UAAU,kBAAkB;KACzB,CAAA,CACP;;GACJ;;CACH,CAAA;AAEd"}
@@ -70,6 +70,12 @@ export interface SchemaChangeDialogProps {
70
70
  * they have decided.
71
71
  */
72
72
  applyRefusedBecause?: string;
73
+ /**
74
+ * The change can only be committed as source — the deployment applies
75
+ * nothing to its database — so {@link onSourceOnly} is the main action,
76
+ * labelled "Commit", and not refused by {@link applyRefusedBecause}.
77
+ */
78
+ sourceOnlyIsTheCommit?: boolean;
73
79
  /**
74
80
  * Where a confirmation would land — `owner/repo` and a branch.
75
81
  *
@@ -82,4 +88,4 @@ export interface SchemaChangeDialogProps {
82
88
  branch?: string;
83
89
  };
84
90
  }
85
- export declare function SchemaChangeDialog({ open, collectionId, plan, planError, result, applying, applyError, onConfirm, onRetry, onSourceOnly, onClose, applyRefusedBecause, target }: SchemaChangeDialogProps): React.JSX.Element;
91
+ export declare function SchemaChangeDialog({ open, collectionId, plan, planError, result, applying, applyError, onConfirm, onRetry, onSourceOnly, onClose, applyRefusedBecause, sourceOnlyIsTheCommit, target }: SchemaChangeDialogProps): React.JSX.Element;
@@ -205,7 +205,7 @@ function Applied({ result }) {
205
205
  ]
206
206
  });
207
207
  }
208
- function SchemaChangeDialog({ open, collectionId, plan, planError, result, applying, applyError, onConfirm, onRetry, onSourceOnly, onClose, applyRefusedBecause, target }) {
208
+ function SchemaChangeDialog({ open, collectionId, plan, planError, result, applying, applyError, onConfirm, onRetry, onSourceOnly, onClose, applyRefusedBecause, sourceOnlyIsTheCommit, target }) {
209
209
  const { t } = useTranslation();
210
210
  const verdict = plan?.verdict;
211
211
  const statements = plan?.statements.length ?? 0;
@@ -387,7 +387,14 @@ function SchemaChangeDialog({ open, collectionId, plan, planError, result, apply
387
387
  disabled: applying,
388
388
  children: t("schema_change_edit_source_only")
389
389
  }),
390
- !result && /* @__PURE__ */ jsx(Button, {
390
+ !result && sourceOnlyIsTheCommit && onSourceOnly && /* @__PURE__ */ jsx(Button, {
391
+ variant: "filled",
392
+ color: "primary",
393
+ onClick: onSourceOnly,
394
+ disabled: applying,
395
+ children: applying ? t("schema_change_committing") : t("schema_change_commit")
396
+ }),
397
+ !result && !(sourceOnlyIsTheCommit && onSourceOnly) && /* @__PURE__ */ jsx(Button, {
391
398
  variant: "filled",
392
399
  color: "primary",
393
400
  onClick: onConfirm,
@@ -1 +1 @@
1
- {"version":3,"file":"SchemaChangeDialog.js","names":[],"sources":["../../../../src/collection_editor/ui/collection_editor/SchemaChangeDialog.tsx"],"sourcesContent":["/**\n * What a schema change would do, before it does it.\n *\n * The dialog exists because a schema change has three possible verdicts and two\n * of them are refusals. Without a preview, the only way to discover that a\n * change is refused is to press a button on a live database and read what comes\n * back — which is a fine way to learn and a poor way to work.\n *\n * ## What it shows, in the order somebody reads it\n *\n * The verdict first, in a sentence, because it decides whether the rest is\n * worth reading. Then the changes, each with what it does and — when it is\n * refused — what to do instead. Then the things that are easy to skip past and\n * expensive to have skipped: constraints the change asks for that the database\n * will not end up enforcing. The SQL and the file list come last, collapsed,\n * for the reader who wants them; they are the evidence, not the summary.\n *\n * ## Why the button says \"Commit and apply\"\n *\n * Because that is the order, and the order is the feature. The commit lands\n * first, so a failed apply leaves the repository ahead of the database — the\n * ordinary state of every project between an edit and a deploy, which the next\n * boot reconciles. A button labelled \"Save\" would be describing a different,\n * worse thing.\n */\nimport React from \"react\";\nimport {\n Alert,\n Button,\n Chip,\n CircularProgress,\n cls,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n ExpandablePanel,\n Typography\n} from \"@rebasepro/ui\";\nimport { useTranslation } from \"@rebasepro/app\";\n\nimport type { LiveSchemaPlan, LiveSchemaResult, WithheldConstraint } from \"../../liveSchemaClient\";\n\nexport interface SchemaChangeDialogProps {\n open: boolean;\n /** The collection being changed, for the title. */\n collectionId: string;\n /** `undefined` while the plan is still being fetched. */\n plan?: LiveSchemaPlan;\n /** Set when planning itself failed — a network error, a refusal, a 500. */\n planError?: string;\n /** Set once the change has been applied, which turns this into a receipt. */\n result?: LiveSchemaResult;\n applying: boolean;\n /** Set when the apply threw rather than returning a result. */\n applyError?: string;\n onConfirm: () => void;\n /**\n * Ask again, when planning failed.\n *\n * A dropped connection should cost a click, not the whole wizard. The form\n * is already filled in, and making somebody redo it for a transient failure\n * teaches them to distrust the preview rather than the network.\n */\n onRetry?: () => void;\n /**\n * Write the collection source and leave the database alone.\n *\n * Offered only when the change is refused, and it is what keeps the editor\n * usable while it is. Removing a property is the ordinary case: the ensure\n * path has no `DROP COLUMN`, so a removal can never be applied — and\n * refusing the whole save over it would mean a dev could no longer delete a\n * field from a collection they are still designing.\n *\n * This is exactly what the editor did before live editing existed, so it is\n * not a new hazard; the difference is that it now says what it leaves\n * behind instead of reporting success.\n */\n onSourceOnly?: () => void;\n onClose: () => void;\n /**\n * Why this caller may preview but not apply, when that is the case.\n *\n * A person signed in with an API key, most often. Shown next to a disabled\n * button so the refusal arrives while they are deciding rather than after\n * they have decided.\n */\n applyRefusedBecause?: string;\n /**\n * Where a confirmation would land — `owner/repo` and a branch.\n *\n * On screen before the button, not in the receipt after it. A commit is\n * going somewhere, and which branch it is going to is the one fact somebody\n * cannot recover from being wrong about.\n */\n target?: { repository?: string; branch?: string };\n}\n\ntype Verdict = LiveSchemaPlan[\"verdict\"];\n\ntype Translate = ReturnType<typeof useTranslation>[\"t\"];\n\n/**\n * What the verdict means, in the words the reader needs rather than the enum's.\n *\n * `safe` is written twice because the two cases are genuinely different, and\n * saying \"can be made against the running database\" when nothing will be run is\n * the kind of small lie that teaches people to stop reading. A document\n * database has no table to alter, and a change that needs no DDL on a\n * relational one is in the same position: the commit *is* the change.\n */\nconst VERDICT_COPY: Record<Verdict, { titleKey: string; bodyKey: string; color: \"info\" | \"warning\" | \"error\" }> = {\n safe: {\n titleKey: \"schema_change_verdict_safe_title\",\n bodyKey: \"schema_change_verdict_safe_body\",\n color: \"info\"\n },\n diverges: {\n titleKey: \"schema_change_verdict_diverges_title\",\n bodyKey: \"schema_change_verdict_diverges_body\",\n color: \"warning\"\n },\n \"needs-migration\": {\n titleKey: \"schema_change_verdict_migration_title\",\n bodyKey: \"schema_change_verdict_migration_body\",\n color: \"error\"\n }\n};\n\nconst VERDICT_CHIP: Record<Verdict, { labelKey: string; scheme: \"greenLighter\" | \"orangeLighter\" | \"redLighter\" }> = {\n safe: { labelKey: \"schema_change_chip_safe\", scheme: \"greenLighter\" },\n diverges: { labelKey: \"schema_change_chip_diverges\", scheme: \"orangeLighter\" },\n \"needs-migration\": { labelKey: \"schema_change_chip_migration\", scheme: \"redLighter\" }\n};\n\nconst monospace = \"font-mono text-xs leading-relaxed\";\nconst codeBlock = cls(\n monospace,\n \"bg-surface-raised rounded-md p-3 overflow-x-auto whitespace-pre\"\n);\n\n/** A disclosure that starts closed. The evidence, for the reader who wants it. */\nfunction Details({ summary, count, children }: {\n summary: string;\n count: number;\n children: React.ReactNode;\n}) {\n if (count === 0) return null;\n return (\n <ExpandablePanel\n initiallyExpanded={false}\n titleClassName=\"!min-h-0 !py-2 px-3\"\n innerClassName=\"p-3\"\n title={<Typography variant=\"body2\" color=\"secondary\">{summary} ({count})</Typography>}\n >\n {children}\n </ExpandablePanel>\n );\n}\n\n/**\n * What still has to happen after this lands.\n *\n * Above the evidence and below the changes, because it is not a refusal and not\n * a detail: the change will apply, and something outside this dialog still has\n * to be done or a later environment will differ from this one.\n */\nfunction FollowUp({ items }: { items: string[] }) {\n const { t } = useTranslation();\n if (items.length === 0) return null;\n return (\n <Alert color=\"info\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {items.length === 1 ? t(\"schema_change_follow_up_one\") : t(\"schema_change_follow_up\")}\n </Typography>\n <ul className=\"space-y-2\">\n {items.map(item => (\n <li key={item} className=\"text-sm\">{item}</li>\n ))}\n </ul>\n </Alert>\n );\n}\n\n/**\n * The destination, short enough to read at a glance.\n *\n * A remote repository already reports itself as `owner/repo`, which is exactly\n * what somebody recognises. A local one reports an absolute path, and the\n * leading directories are the part nobody needs: what matters is which\n * checkout, and its name says that.\n */\nfunction repositoryLabel(repository: string): string {\n if (!repository.startsWith(\"/\")) return repository;\n return repository.split(\"/\").filter(Boolean).pop() ?? repository;\n}\n\nfunction WithheldConstraints({ constraints }: { constraints: WithheldConstraint[] }) {\n const { t } = useTranslation();\n if (constraints.length === 0) return null;\n return (\n <Alert color=\"warning\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {constraints.length === 1\n ? t(\"schema_change_withheld_one\")\n : t(\"schema_change_withheld_many\", { count: constraints.length })}\n </Typography>\n <ul className=\"space-y-2\">\n {constraints.map(constraint => (\n <li key={constraint.target} className=\"text-sm\">\n <Typography component=\"code\" variant=\"mono\" className=\"bg-surface-raised px-1 rounded-md\">\n {constraint.target}\n </Typography>\n <Typography variant=\"body2\" className=\"mt-1\">{constraint.reason}</Typography>\n <Typography variant=\"body2\" color=\"secondary\" className=\"mt-1\">\n {constraint.remedy}\n </Typography>\n </li>\n ))}\n </ul>\n </Alert>\n );\n}\n\n/**\n * How far a failed apply got, in a heading.\n *\n * The statements run one at a time with no transaction around them, so only\n * \"none ran\" means the database is as it was.\n */\nfunction partialApplyHeading(result: LiveSchemaResult, t: Translate): string {\n const ran = result.appliedStatements;\n if (ran === 0) return t(\"schema_change_db_not_changed\");\n if (ran === undefined) return t(\"schema_change_db_maybe_changed\");\n return t(\"schema_change_statements_partial\", { ran, total: result.statements.length });\n}\n\n/** The receipt. Shown in place of the plan once the change has been applied. */\nfunction Applied({ result }: { result: LiveSchemaResult }) {\n const { t } = useTranslation();\n return (\n <div className=\"flex flex-col gap-4\">\n <Alert color={result.applied || result.sourceOnly ? \"success\" : \"warning\"}>\n <Typography variant=\"body2\">{result.summary}</Typography>\n </Alert>\n\n {!result.applied && !result.sourceOnly && result.applyError && (\n // Deliberately not an error state. The commit landed, which is\n // the durable half; the database is now behind the repository,\n // which is where every project sits between an edit and a\n // deploy, and boot reconciles it.\n <Alert color=\"warning\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {partialApplyHeading(result, t)}\n </Typography>\n <Typography variant=\"body2\">{result.applyError}</Typography>\n <Typography variant=\"body2\" className=\"mt-2\">\n {t(\"schema_change_commit_holds\", { branch: result.committed.branch })}\n </Typography>\n </Alert>\n )}\n\n <WithheldConstraints constraints={result.withheldConstraints ?? []}/>\n <FollowUp items={result.followUp ?? []}/>\n\n <div>\n <Typography variant=\"label\" color=\"secondary\">{t(\"schema_change_committed\")}</Typography>\n <div className={cls(codeBlock, \"mt-1\")}>\n {t(\"schema_change_committed_on\", { sha: result.committed.sha.slice(0, 9), branch: result.committed.branch })}\n {\"\\n\"}\n {result.committed.files.map(file => ` ${file}`).join(\"\\n\")}\n </div>\n </div>\n </div>\n );\n}\n\nexport function SchemaChangeDialog({\n open,\n collectionId,\n plan,\n planError,\n result,\n applying,\n applyError,\n onConfirm,\n onRetry,\n onSourceOnly,\n onClose,\n applyRefusedBecause,\n target\n}: SchemaChangeDialogProps) {\n\n const { t } = useTranslation();\n const verdict = plan?.verdict;\n const statements = plan?.statements.length ?? 0;\n\n // \"Commit\" only when we positively know there is nothing to apply: a plan\n // that is going ahead and has no statements. A *refused* plan also has none\n // — because it will not run — and labelling that button \"Commit\" would be\n // describing the change it is refusing to make. Unknown reads as the fuller\n // action, which is the safer way to be wrong about a label.\n const commitOnly = Boolean(plan?.applicable) && statements === 0;\n\n // Described from the plan rather than from an assumption about the engine.\n // A document database runs nothing; so does a relational change that only\n // moves source. Both are a commit, and calling either one \"apply\" would be\n // describing something that does not happen.\n // A plan with changes and no statements still changes something — a\n // security rule takes effect when the server next starts — so \"there is\n // no schema change to make\" is said only when there is none.\n const copy = verdict === \"safe\" && commitOnly\n ? {\n title: t(\"schema_change_commit_only_title\"),\n body: plan && plan.changes.length > 0\n ? t(\"schema_change_commit_only_body\")\n : t(\"schema_change_commit_only_body_no_changes\"),\n color: \"info\" as const\n }\n : verdict\n ? {\n title: t(VERDICT_COPY[verdict].titleKey),\n body: t(VERDICT_COPY[verdict].bodyKey),\n color: VERDICT_COPY[verdict].color\n }\n : undefined;\n\n return (\n <Dialog open={open} onOpenChange={value => { if (!value) onClose(); }} maxWidth=\"3xl\">\n <DialogTitle className=\"flex items-center gap-2\">\n {result\n ? (result.sourceOnly ? t(\"schema_change_title_committed\") : t(\"schema_change_title_applied\"))\n : t(\"schema_change_title_review\")}\n <Typography component=\"code\" variant=\"mono\" color=\"secondary\">\n {collectionId}\n </Typography>\n </DialogTitle>\n\n <DialogContent className=\"flex flex-col gap-4\">\n {planError && (\n <Alert color=\"error\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {t(\"schema_change_plan_failed\")}\n </Typography>\n <Typography variant=\"body2\">{planError}</Typography>\n </Alert>\n )}\n\n {!plan && !planError && !result && (\n <div className=\"flex items-center gap-3 py-6\">\n <CircularProgress size=\"small\"/>\n <Typography variant=\"body2\" color=\"secondary\">\n {t(\"schema_change_planning\")}\n </Typography>\n </div>\n )}\n\n {result && <Applied result={result}/>}\n\n {plan && !result && copy && (\n <>\n <Alert color={copy.color}>\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {copy.title}\n </Typography>\n <Typography variant=\"body2\">{copy.body}</Typography>\n </Alert>\n\n {applyError && (\n <Alert color=\"error\">\n <Typography variant=\"body2\">{applyError}</Typography>\n </Alert>\n )}\n\n {plan.changes.length === 0 && (\n <Typography variant=\"body2\" color=\"secondary\">\n {t(\"schema_change_source_only_changes\")}\n </Typography>\n )}\n\n {!plan.applicable && onSourceOnly && (\n // Said per change: what a removal leaves behind is\n // not what a type change or a new required field\n // does, and the one that breaks every insert has to\n // be on screen before the button is pressed.\n <Alert color=\"warning\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {t(\"schema_change_source_only_title\")}\n </Typography>\n <ul className=\"space-y-1\">\n {plan.changes.filter(change => change.verdict !== \"safe\" && change.sourceOnly).map((change, index) => (\n <li key={`${change.property ?? change.collection}.${index}`} className=\"text-sm\">\n {change.sourceOnly}\n </li>\n ))}\n </ul>\n </Alert>\n )}\n\n {plan.changes.length > 0 && (\n <ul className=\"flex flex-col gap-3\">\n {plan.changes.map((change, index) => (\n <li\n key={`${change.collection}.${change.property ?? \"\"}.${index}`}\n className=\"flex gap-3\"\n >\n <Chip\n size=\"smallest\"\n colorScheme={VERDICT_CHIP[change.verdict].scheme}\n className=\"shrink-0 mt-0.5\"\n >\n {t(VERDICT_CHIP[change.verdict].labelKey)}\n </Chip>\n <div className=\"min-w-0\">\n <Typography variant=\"body2\">{change.detail}</Typography>\n {change.remedy && (\n <Typography\n variant=\"body2\"\n color=\"secondary\"\n className=\"mt-1\"\n >\n {change.remedy}\n </Typography>\n )}\n </div>\n </li>\n ))}\n </ul>\n )}\n\n <WithheldConstraints constraints={plan.withheldConstraints ?? []}/>\n <FollowUp items={plan.followUp ?? []}/>\n\n {applyRefusedBecause && (\n <Alert color=\"info\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {t(\"schema_change_preview_only\")}\n </Typography>\n <Typography variant=\"body2\">{applyRefusedBecause}</Typography>\n </Alert>\n )}\n\n <Details summary={t(\"schema_change_statements\")} count={plan.statements.length}>\n <div className={codeBlock}>{plan.statements.join(\"\\n\")}</div>\n </Details>\n\n <Details summary={t(\"schema_change_files\")} count={plan.files.length}>\n <div className={codeBlock}>{plan.files.join(\"\\n\")}</div>\n </Details>\n\n <Details summary={t(\"schema_change_message\")} count={plan.message ? 1 : 0}>\n <div className={codeBlock}>{plan.message}</div>\n </Details>\n </>\n )}\n </DialogContent>\n\n <DialogActions>\n {!result && target?.repository && (\n <Typography variant=\"caption\" color=\"secondary\" className={cls(monospace, \"mr-auto truncate\")}>\n → {repositoryLabel(target.repository)}{target.branch ? ` · ${target.branch}` : \"\"}\n </Typography>\n )}\n <Button variant=\"text\" onClick={onClose} disabled={applying}>\n {result ? t(\"close\") : t(\"cancel\")}\n </Button>\n {!result && planError && onRetry && (\n <Button variant=\"outlined\" onClick={onRetry}>\n {t(\"retry\")}\n </Button>\n )}\n {!result && plan && !plan.applicable && onSourceOnly && (\n <Button variant=\"outlined\" onClick={onSourceOnly} disabled={applying}>\n {t(\"schema_change_edit_source_only\")}\n </Button>\n )}\n {!result && (\n <Button\n variant=\"filled\"\n color=\"primary\"\n onClick={onConfirm}\n // `applicable` is the server's word, not a\n // re-derivation from the verdicts on screen:\n // `applySchemaChange` re-checks it before it writes\n // anything, so a button that disagreed would only\n // produce the same refusal one click later. The same\n // goes for the permission — `/apply` checks it too, and\n // this only saves somebody the round trip.\n disabled={!plan?.applicable || applying || Boolean(applyRefusedBecause)}\n >\n {applying\n ? (commitOnly ? t(\"schema_change_committing\") : t(\"schema_change_applying\"))\n : (commitOnly ? t(\"schema_change_commit\") : t(\"schema_change_commit_and_apply\"))}\n </Button>\n )}\n </DialogActions>\n </Dialog>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AA+GA,IAAM,eAA4G;CAC9G,MAAM;EACF,UAAU;EACV,SAAS;EACT,OAAO;CACX;CACA,UAAU;EACN,UAAU;EACV,SAAS;EACT,OAAO;CACX;CACA,mBAAmB;EACf,UAAU;EACV,SAAS;EACT,OAAO;CACX;AACJ;AAEA,IAAM,eAA+G;CACjH,MAAM;EAAE,UAAU;EAA2B,QAAQ;CAAe;CACpE,UAAU;EAAE,UAAU;EAA+B,QAAQ;CAAgB;CAC7E,mBAAmB;EAAE,UAAU;EAAgC,QAAQ;CAAa;AACxF;AAEA,IAAM,YAAY;AAClB,IAAM,YAAY,IACd,WACA,iEACJ;;AAGA,SAAS,QAAQ,EAAE,SAAS,OAAO,YAIhC;CACC,IAAI,UAAU,GAAG,OAAO;CACxB,OACI,oBAAC,iBAAD;EACI,mBAAmB;EACnB,gBAAe;EACf,gBAAe;EACf,OAAO,qBAAC,YAAD;GAAY,SAAQ;GAAQ,OAAM;aAAlC;IAA+C;IAAQ;IAAG;IAAM;GAAa;;EAEnF;CACY,CAAA;AAEzB;;;;;;;;AASA,SAAS,SAAS,EAAE,SAA8B;CAC9C,MAAM,EAAE,MAAM,eAAe;CAC7B,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,OACI,qBAAC,OAAD;EAAO,OAAM;YAAb,CACI,oBAAC,YAAD;GAAY,SAAQ;GAAQ,WAAU;aACjC,MAAM,WAAW,IAAI,EAAE,6BAA6B,IAAI,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AC,UAAU,aAAa,WACrB,oBAAC,QAAD;KAAQ,SAAQ;KAAW,SAAS;eAC/B,EAAE,OAAO;IACN,CAAA;IAEX,CAAC,UAAU,QAAQ,CAAC,KAAK,cAAc,gBACpC,oBAAC,QAAD;KAAQ,SAAQ;KAAW,SAAS;KAAc,UAAU;eACvD,EAAE,gCAAgC;IAC/B,CAAA;IAEX,CAAC,UACE,oBAAC,QAAD;KACI,SAAQ;KACR,OAAM;KACN,SAAS;KAQT,UAAU,CAAC,MAAM,cAAc,YAAY,QAAQ,mBAAmB;eAErE,WACM,aAAa,EAAE,0BAA0B,IAAI,EAAE,wBAAwB,IACvE,aAAa,EAAE,sBAAsB,IAAI,EAAE,gCAAgC;IAC9E,CAAA;GAED,EAAA,CAAA;EACX;;AAEhB"}
1
+ {"version":3,"file":"SchemaChangeDialog.js","names":[],"sources":["../../../../src/collection_editor/ui/collection_editor/SchemaChangeDialog.tsx"],"sourcesContent":["/**\n * What a schema change would do, before it does it.\n *\n * The dialog exists because a schema change has three possible verdicts and two\n * of them are refusals. Without a preview, the only way to discover that a\n * change is refused is to press a button on a live database and read what comes\n * back — which is a fine way to learn and a poor way to work.\n *\n * ## What it shows, in the order somebody reads it\n *\n * The verdict first, in a sentence, because it decides whether the rest is\n * worth reading. Then the changes, each with what it does and — when it is\n * refused — what to do instead. Then the things that are easy to skip past and\n * expensive to have skipped: constraints the change asks for that the database\n * will not end up enforcing. The SQL and the file list come last, collapsed,\n * for the reader who wants them; they are the evidence, not the summary.\n *\n * ## Why the button says \"Commit and apply\"\n *\n * Because that is the order, and the order is the feature. The commit lands\n * first, so a failed apply leaves the repository ahead of the database — the\n * ordinary state of every project between an edit and a deploy, which the next\n * boot reconciles. A button labelled \"Save\" would be describing a different,\n * worse thing.\n */\nimport React from \"react\";\nimport {\n Alert,\n Button,\n Chip,\n CircularProgress,\n cls,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n ExpandablePanel,\n Typography\n} from \"@rebasepro/ui\";\nimport { useTranslation } from \"@rebasepro/app\";\n\nimport type { LiveSchemaPlan, LiveSchemaResult, WithheldConstraint } from \"../../liveSchemaClient\";\n\nexport interface SchemaChangeDialogProps {\n open: boolean;\n /** The collection being changed, for the title. */\n collectionId: string;\n /** `undefined` while the plan is still being fetched. */\n plan?: LiveSchemaPlan;\n /** Set when planning itself failed — a network error, a refusal, a 500. */\n planError?: string;\n /** Set once the change has been applied, which turns this into a receipt. */\n result?: LiveSchemaResult;\n applying: boolean;\n /** Set when the apply threw rather than returning a result. */\n applyError?: string;\n onConfirm: () => void;\n /**\n * Ask again, when planning failed.\n *\n * A dropped connection should cost a click, not the whole wizard. The form\n * is already filled in, and making somebody redo it for a transient failure\n * teaches them to distrust the preview rather than the network.\n */\n onRetry?: () => void;\n /**\n * Write the collection source and leave the database alone.\n *\n * Offered only when the change is refused, and it is what keeps the editor\n * usable while it is. Removing a property is the ordinary case: the ensure\n * path has no `DROP COLUMN`, so a removal can never be applied — and\n * refusing the whole save over it would mean a dev could no longer delete a\n * field from a collection they are still designing.\n *\n * This is exactly what the editor did before live editing existed, so it is\n * not a new hazard; the difference is that it now says what it leaves\n * behind instead of reporting success.\n */\n onSourceOnly?: () => void;\n onClose: () => void;\n /**\n * Why this caller may preview but not apply, when that is the case.\n *\n * A person signed in with an API key, most often. Shown next to a disabled\n * button so the refusal arrives while they are deciding rather than after\n * they have decided.\n */\n applyRefusedBecause?: string;\n /**\n * The change can only be committed as source — the deployment applies\n * nothing to its database — so {@link onSourceOnly} is the main action,\n * labelled \"Commit\", and not refused by {@link applyRefusedBecause}.\n */\n sourceOnlyIsTheCommit?: boolean;\n /**\n * Where a confirmation would land — `owner/repo` and a branch.\n *\n * On screen before the button, not in the receipt after it. A commit is\n * going somewhere, and which branch it is going to is the one fact somebody\n * cannot recover from being wrong about.\n */\n target?: { repository?: string; branch?: string };\n}\n\ntype Verdict = LiveSchemaPlan[\"verdict\"];\n\ntype Translate = ReturnType<typeof useTranslation>[\"t\"];\n\n/**\n * What the verdict means, in the words the reader needs rather than the enum's.\n *\n * `safe` is written twice because the two cases are genuinely different, and\n * saying \"can be made against the running database\" when nothing will be run is\n * the kind of small lie that teaches people to stop reading. A document\n * database has no table to alter, and a change that needs no DDL on a\n * relational one is in the same position: the commit *is* the change.\n */\nconst VERDICT_COPY: Record<Verdict, { titleKey: string; bodyKey: string; color: \"info\" | \"warning\" | \"error\" }> = {\n safe: {\n titleKey: \"schema_change_verdict_safe_title\",\n bodyKey: \"schema_change_verdict_safe_body\",\n color: \"info\"\n },\n diverges: {\n titleKey: \"schema_change_verdict_diverges_title\",\n bodyKey: \"schema_change_verdict_diverges_body\",\n color: \"warning\"\n },\n \"needs-migration\": {\n titleKey: \"schema_change_verdict_migration_title\",\n bodyKey: \"schema_change_verdict_migration_body\",\n color: \"error\"\n }\n};\n\nconst VERDICT_CHIP: Record<Verdict, { labelKey: string; scheme: \"greenLighter\" | \"orangeLighter\" | \"redLighter\" }> = {\n safe: { labelKey: \"schema_change_chip_safe\", scheme: \"greenLighter\" },\n diverges: { labelKey: \"schema_change_chip_diverges\", scheme: \"orangeLighter\" },\n \"needs-migration\": { labelKey: \"schema_change_chip_migration\", scheme: \"redLighter\" }\n};\n\nconst monospace = \"font-mono text-xs leading-relaxed\";\nconst codeBlock = cls(\n monospace,\n \"bg-surface-raised rounded-md p-3 overflow-x-auto whitespace-pre\"\n);\n\n/** A disclosure that starts closed. The evidence, for the reader who wants it. */\nfunction Details({ summary, count, children }: {\n summary: string;\n count: number;\n children: React.ReactNode;\n}) {\n if (count === 0) return null;\n return (\n <ExpandablePanel\n initiallyExpanded={false}\n titleClassName=\"!min-h-0 !py-2 px-3\"\n innerClassName=\"p-3\"\n title={<Typography variant=\"body2\" color=\"secondary\">{summary} ({count})</Typography>}\n >\n {children}\n </ExpandablePanel>\n );\n}\n\n/**\n * What still has to happen after this lands.\n *\n * Above the evidence and below the changes, because it is not a refusal and not\n * a detail: the change will apply, and something outside this dialog still has\n * to be done or a later environment will differ from this one.\n */\nfunction FollowUp({ items }: { items: string[] }) {\n const { t } = useTranslation();\n if (items.length === 0) return null;\n return (\n <Alert color=\"info\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {items.length === 1 ? t(\"schema_change_follow_up_one\") : t(\"schema_change_follow_up\")}\n </Typography>\n <ul className=\"space-y-2\">\n {items.map(item => (\n <li key={item} className=\"text-sm\">{item}</li>\n ))}\n </ul>\n </Alert>\n );\n}\n\n/**\n * The destination, short enough to read at a glance.\n *\n * A remote repository already reports itself as `owner/repo`, which is exactly\n * what somebody recognises. A local one reports an absolute path, and the\n * leading directories are the part nobody needs: what matters is which\n * checkout, and its name says that.\n */\nfunction repositoryLabel(repository: string): string {\n if (!repository.startsWith(\"/\")) return repository;\n return repository.split(\"/\").filter(Boolean).pop() ?? repository;\n}\n\nfunction WithheldConstraints({ constraints }: { constraints: WithheldConstraint[] }) {\n const { t } = useTranslation();\n if (constraints.length === 0) return null;\n return (\n <Alert color=\"warning\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {constraints.length === 1\n ? t(\"schema_change_withheld_one\")\n : t(\"schema_change_withheld_many\", { count: constraints.length })}\n </Typography>\n <ul className=\"space-y-2\">\n {constraints.map(constraint => (\n <li key={constraint.target} className=\"text-sm\">\n <Typography component=\"code\" variant=\"mono\" className=\"bg-surface-raised px-1 rounded-md\">\n {constraint.target}\n </Typography>\n <Typography variant=\"body2\" className=\"mt-1\">{constraint.reason}</Typography>\n <Typography variant=\"body2\" color=\"secondary\" className=\"mt-1\">\n {constraint.remedy}\n </Typography>\n </li>\n ))}\n </ul>\n </Alert>\n );\n}\n\n/**\n * How far a failed apply got, in a heading.\n *\n * The statements run one at a time with no transaction around them, so only\n * \"none ran\" means the database is as it was.\n */\nfunction partialApplyHeading(result: LiveSchemaResult, t: Translate): string {\n const ran = result.appliedStatements;\n if (ran === 0) return t(\"schema_change_db_not_changed\");\n if (ran === undefined) return t(\"schema_change_db_maybe_changed\");\n return t(\"schema_change_statements_partial\", { ran, total: result.statements.length });\n}\n\n/** The receipt. Shown in place of the plan once the change has been applied. */\nfunction Applied({ result }: { result: LiveSchemaResult }) {\n const { t } = useTranslation();\n return (\n <div className=\"flex flex-col gap-4\">\n <Alert color={result.applied || result.sourceOnly ? \"success\" : \"warning\"}>\n <Typography variant=\"body2\">{result.summary}</Typography>\n </Alert>\n\n {!result.applied && !result.sourceOnly && result.applyError && (\n // Deliberately not an error state. The commit landed, which is\n // the durable half; the database is now behind the repository,\n // which is where every project sits between an edit and a\n // deploy, and boot reconciles it.\n <Alert color=\"warning\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {partialApplyHeading(result, t)}\n </Typography>\n <Typography variant=\"body2\">{result.applyError}</Typography>\n <Typography variant=\"body2\" className=\"mt-2\">\n {t(\"schema_change_commit_holds\", { branch: result.committed.branch })}\n </Typography>\n </Alert>\n )}\n\n <WithheldConstraints constraints={result.withheldConstraints ?? []}/>\n <FollowUp items={result.followUp ?? []}/>\n\n <div>\n <Typography variant=\"label\" color=\"secondary\">{t(\"schema_change_committed\")}</Typography>\n <div className={cls(codeBlock, \"mt-1\")}>\n {t(\"schema_change_committed_on\", { sha: result.committed.sha.slice(0, 9), branch: result.committed.branch })}\n {\"\\n\"}\n {result.committed.files.map(file => ` ${file}`).join(\"\\n\")}\n </div>\n </div>\n </div>\n );\n}\n\nexport function SchemaChangeDialog({\n open,\n collectionId,\n plan,\n planError,\n result,\n applying,\n applyError,\n onConfirm,\n onRetry,\n onSourceOnly,\n onClose,\n applyRefusedBecause,\n sourceOnlyIsTheCommit,\n target\n}: SchemaChangeDialogProps) {\n\n const { t } = useTranslation();\n const verdict = plan?.verdict;\n const statements = plan?.statements.length ?? 0;\n\n // \"Commit\" only when we positively know there is nothing to apply: a plan\n // that is going ahead and has no statements. A *refused* plan also has none\n // — because it will not run — and labelling that button \"Commit\" would be\n // describing the change it is refusing to make. Unknown reads as the fuller\n // action, which is the safer way to be wrong about a label.\n const commitOnly = Boolean(plan?.applicable) && statements === 0;\n\n // Described from the plan rather than from an assumption about the engine.\n // A document database runs nothing; so does a relational change that only\n // moves source. Both are a commit, and calling either one \"apply\" would be\n // describing something that does not happen.\n // A plan with changes and no statements still changes something — a\n // security rule takes effect when the server next starts — so \"there is\n // no schema change to make\" is said only when there is none.\n const copy = verdict === \"safe\" && commitOnly\n ? {\n title: t(\"schema_change_commit_only_title\"),\n body: plan && plan.changes.length > 0\n ? t(\"schema_change_commit_only_body\")\n : t(\"schema_change_commit_only_body_no_changes\"),\n color: \"info\" as const\n }\n : verdict\n ? {\n title: t(VERDICT_COPY[verdict].titleKey),\n body: t(VERDICT_COPY[verdict].bodyKey),\n color: VERDICT_COPY[verdict].color\n }\n : undefined;\n\n return (\n <Dialog open={open} onOpenChange={value => { if (!value) onClose(); }} maxWidth=\"3xl\">\n <DialogTitle className=\"flex items-center gap-2\">\n {result\n ? (result.sourceOnly ? t(\"schema_change_title_committed\") : t(\"schema_change_title_applied\"))\n : t(\"schema_change_title_review\")}\n <Typography component=\"code\" variant=\"mono\" color=\"secondary\">\n {collectionId}\n </Typography>\n </DialogTitle>\n\n <DialogContent className=\"flex flex-col gap-4\">\n {planError && (\n <Alert color=\"error\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {t(\"schema_change_plan_failed\")}\n </Typography>\n <Typography variant=\"body2\">{planError}</Typography>\n </Alert>\n )}\n\n {!plan && !planError && !result && (\n <div className=\"flex items-center gap-3 py-6\">\n <CircularProgress size=\"small\"/>\n <Typography variant=\"body2\" color=\"secondary\">\n {t(\"schema_change_planning\")}\n </Typography>\n </div>\n )}\n\n {result && <Applied result={result}/>}\n\n {plan && !result && copy && (\n <>\n <Alert color={copy.color}>\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {copy.title}\n </Typography>\n <Typography variant=\"body2\">{copy.body}</Typography>\n </Alert>\n\n {applyError && (\n <Alert color=\"error\">\n <Typography variant=\"body2\">{applyError}</Typography>\n </Alert>\n )}\n\n {plan.changes.length === 0 && (\n <Typography variant=\"body2\" color=\"secondary\">\n {t(\"schema_change_source_only_changes\")}\n </Typography>\n )}\n\n {!plan.applicable && onSourceOnly && (\n // Said per change: what a removal leaves behind is\n // not what a type change or a new required field\n // does, and the one that breaks every insert has to\n // be on screen before the button is pressed.\n <Alert color=\"warning\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {t(\"schema_change_source_only_title\")}\n </Typography>\n <ul className=\"space-y-1\">\n {plan.changes.filter(change => change.verdict !== \"safe\" && change.sourceOnly).map((change, index) => (\n <li key={`${change.property ?? change.collection}.${index}`} className=\"text-sm\">\n {change.sourceOnly}\n </li>\n ))}\n </ul>\n </Alert>\n )}\n\n {plan.changes.length > 0 && (\n <ul className=\"flex flex-col gap-3\">\n {plan.changes.map((change, index) => (\n <li\n key={`${change.collection}.${change.property ?? \"\"}.${index}`}\n className=\"flex gap-3\"\n >\n <Chip\n size=\"smallest\"\n colorScheme={VERDICT_CHIP[change.verdict].scheme}\n className=\"shrink-0 mt-0.5\"\n >\n {t(VERDICT_CHIP[change.verdict].labelKey)}\n </Chip>\n <div className=\"min-w-0\">\n <Typography variant=\"body2\">{change.detail}</Typography>\n {change.remedy && (\n <Typography\n variant=\"body2\"\n color=\"secondary\"\n className=\"mt-1\"\n >\n {change.remedy}\n </Typography>\n )}\n </div>\n </li>\n ))}\n </ul>\n )}\n\n <WithheldConstraints constraints={plan.withheldConstraints ?? []}/>\n <FollowUp items={plan.followUp ?? []}/>\n\n {applyRefusedBecause && (\n <Alert color=\"info\">\n <Typography variant=\"body2\" className=\"font-medium mb-1\">\n {t(\"schema_change_preview_only\")}\n </Typography>\n <Typography variant=\"body2\">{applyRefusedBecause}</Typography>\n </Alert>\n )}\n\n <Details summary={t(\"schema_change_statements\")} count={plan.statements.length}>\n <div className={codeBlock}>{plan.statements.join(\"\\n\")}</div>\n </Details>\n\n <Details summary={t(\"schema_change_files\")} count={plan.files.length}>\n <div className={codeBlock}>{plan.files.join(\"\\n\")}</div>\n </Details>\n\n <Details summary={t(\"schema_change_message\")} count={plan.message ? 1 : 0}>\n <div className={codeBlock}>{plan.message}</div>\n </Details>\n </>\n )}\n </DialogContent>\n\n <DialogActions>\n {!result && target?.repository && (\n <Typography variant=\"caption\" color=\"secondary\" className={cls(monospace, \"mr-auto truncate\")}>\n → {repositoryLabel(target.repository)}{target.branch ? ` · ${target.branch}` : \"\"}\n </Typography>\n )}\n <Button variant=\"text\" onClick={onClose} disabled={applying}>\n {result ? t(\"close\") : t(\"cancel\")}\n </Button>\n {!result && planError && onRetry && (\n <Button variant=\"outlined\" onClick={onRetry}>\n {t(\"retry\")}\n </Button>\n )}\n {!result && plan && !plan.applicable && onSourceOnly && (\n <Button variant=\"outlined\" onClick={onSourceOnly} disabled={applying}>\n {t(\"schema_change_edit_source_only\")}\n </Button>\n )}\n {!result && sourceOnlyIsTheCommit && onSourceOnly && (\n <Button variant=\"filled\" color=\"primary\" onClick={onSourceOnly} disabled={applying}>\n {applying ? t(\"schema_change_committing\") : t(\"schema_change_commit\")}\n </Button>\n )}\n {!result && !(sourceOnlyIsTheCommit && onSourceOnly) && (\n <Button\n variant=\"filled\"\n color=\"primary\"\n onClick={onConfirm}\n // `applicable` is the server's word, not a\n // re-derivation from the verdicts on screen:\n // `applySchemaChange` re-checks it before it writes\n // anything, so a button that disagreed would only\n // produce the same refusal one click later. The same\n // goes for the permission — `/apply` checks it too, and\n // this only saves somebody the round trip.\n disabled={!plan?.applicable || applying || Boolean(applyRefusedBecause)}\n >\n {applying\n ? (commitOnly ? t(\"schema_change_committing\") : t(\"schema_change_applying\"))\n : (commitOnly ? t(\"schema_change_commit\") : t(\"schema_change_commit_and_apply\"))}\n </Button>\n )}\n </DialogActions>\n </Dialog>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAqHA,IAAM,eAA4G;CAC9G,MAAM;EACF,UAAU;EACV,SAAS;EACT,OAAO;CACX;CACA,UAAU;EACN,UAAU;EACV,SAAS;EACT,OAAO;CACX;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;KACN,SAAS;KAQT,UAAU,CAAC,MAAM,cAAc,YAAY,QAAQ,mBAAmB;eAErE,WACM,aAAa,EAAE,0BAA0B,IAAI,EAAE,wBAAwB,IACvE,aAAa,EAAE,sBAAsB,IAAI,EAAE,gCAAgC;IAC9E,CAAA;GAED,EAAA,CAAA;EACX;;AAEhB"}
@@ -168,7 +168,9 @@ function useLiveSchemaEditing(options) {
168
168
  setApplyError(err instanceof Error ? err.message : String(err));
169
169
  });
170
170
  }, [client, pending]);
171
- const sourceOnlyOffered = Boolean(plan && !plan.applicable && plan.changes.filter((change) => change.verdict !== "safe").every((change) => change.sourceOnly));
171
+ const provisioningOff = status?.applyRefusedCode === "SCHEMA_EDITING_PROVISIONING_OFF";
172
+ const commitAsSourceOnly = Boolean(provisioningOff && plan?.applicable);
173
+ const sourceOnlyOffered = commitAsSourceOnly || Boolean(plan && !plan.applicable && plan.changes.filter((change) => change.verdict !== "safe").every((change) => change.sourceOnly));
172
174
  const onClose = useCallback(() => {
173
175
  if (applying) return;
174
176
  const settle = pending;
@@ -198,6 +200,7 @@ function useLiveSchemaEditing(options) {
198
200
  onConfirm,
199
201
  onRetry: planError ? onRetry : void 0,
200
202
  onSourceOnly: sourceOnlyOffered ? onSourceOnly : void 0,
203
+ sourceOnlyIsTheCommit: commitAsSourceOnly,
201
204
  onClose,
202
205
  applyRefusedBecause: status && !status.canApply ? status.applyRefusedBecause : void 0,
203
206
  target: status && {
@@ -1 +1 @@
1
- {"version":3,"file":"useLiveSchemaEditing.js","names":[],"sources":["../../src/collection_editor/useLiveSchemaEditing.tsx"],"sourcesContent":["/**\n * The plan-then-confirm flow, as a hook.\n *\n * Owns three things that belong together and nothing else: whether the backend\n * can edit its schema, the plan for the change somebody is making, and the\n * dialog they confirm it in. The config controller calls `reviewChange` and\n * awaits it; everything about *how* the confirmation happens stays here.\n *\n * ## Why `reviewChange` returns a promise that can reject\n *\n * Because the editor needs to know. A save that was cancelled must not leave\n * the form thinking it succeeded — the collection on screen would then differ\n * from the one on disk, and the next save would be computed from the wrong\n * `before`. Rejecting with {@link SchemaChangeCancelled} is how \"the person\n * said no\" reaches the caller as an outcome rather than as silence.\n */\nimport React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { lazyChunk } from \"@rebasepro/ui\";\n\nimport {\n createLiveSchemaClient,\n LiveSchemaError,\n SchemaChangeCancelled,\n type LiveSchemaClient,\n type LiveSchemaPlan,\n type LiveSchemaResult,\n type LiveSchemaStatus,\n type ProposedCollectionChange\n} from \"./liveSchemaClient\";\n\n// Re-exported so the hook stays the one import a caller needs.\nexport { SchemaChangeCancelled, isSchemaChangeCancelled } from \"./liveSchemaClient\";\n\n/**\n * Loaded when a change is actually being reviewed, not before.\n *\n * This hook is reached from the collections config controller, which is\n * constructed on every admin boot — so a static import would put the dialog and\n * the `@rebasepro/ui` surface it draws on into the **eager** bundle: everything\n * a browser downloads before the login screen paints. It cost 14 kB there, for\n * a dialog most sessions never open. The bundle budget caught it.\n */\nconst SchemaChangeDialog = lazyChunk(() =>\n import(\"./ui/collection_editor/SchemaChangeDialog\")\n .then(m => ({ default: m.SchemaChangeDialog }))\n);\n\nexport interface UseLiveSchemaEditingOptions {\n /** Base for the routes, e.g. `https://api.example.com/api/admin/schema`. */\n baseUrl: string;\n getAuthToken?: () => Promise<string | null> | string | null;\n /**\n * Identity of the signed-in user.\n *\n * Only used to re-ask: whether this backend will accept a schema change\n * depends on who is asking, and the answer to an anonymous probe does not\n * survive a sign-in.\n */\n authKey?: string | null;\n /**\n * Whether to ask the backend at all. `false` when the caller cannot be told\n * anything (`/status` needs `schema:read`) or the editor is read-only: the\n * answer is then \"not available\" without a request that could only be\n * refused. Defaults to `true`.\n */\n enabled?: boolean;\n /** Swappable for the tests, which have no server. */\n client?: LiveSchemaClient;\n}\n\n/** The answer when nobody asked. */\nconst NOT_ASKED: LiveSchemaStatus = { enabled: false, canPlan: false, canApply: false };\n\ninterface PendingChange {\n change: ProposedCollectionChange;\n resolve: () => void;\n reject: (err: Error) => void;\n}\n\nexport interface LiveSchemaEditing {\n /** `undefined` until the backend has answered. For rendering. */\n status?: LiveSchemaStatus;\n /**\n * The same answer, for deciding.\n *\n * `status` is undefined for one round trip after mount, and a caller that\n * read it to choose a code path would take the \"not available\" branch for\n * that window — so a save issued quickly after a page load would silently\n * skip the confirmation and write source only, while the same save a second\n * later would not. Timing-dependent behaviour with no visible difference is\n * the worst shape this could have.\n *\n * Resolves once, cached; never rejects, because every way of failing to get\n * an answer means the same thing to whoever is deciding.\n */\n ready: () => Promise<LiveSchemaStatus>;\n /**\n * Plan the change, show it, and settle when the person has decided.\n *\n * Resolves once the change has been applied — or written source-only, if\n * they chose that. Rejects with {@link SchemaChangeCancelled} if they\n * closed the dialog, and with the underlying error if planning or applying\n * failed in a way they did not choose.\n */\n reviewChange: (change: ProposedCollectionChange) => Promise<void>;\n /** Render this once, high enough that a dialog over the editor is not clipped. */\n dialog: React.ReactNode;\n}\n\nexport function useLiveSchemaEditing(options: UseLiveSchemaEditingOptions): LiveSchemaEditing {\n const { baseUrl, authKey } = options;\n const asking = options.enabled !== false;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const client = useMemo(\n () => options.client ?? createLiveSchemaClient({\n baseUrl,\n getAuthToken: () => optionsRef.current.getAuthToken?.() ?? null\n }),\n // `client` is either supplied once by a test or built from the URL. The\n // token getter is read through the ref so a new closure on every render\n // does not rebuild the client underneath an in-flight request.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [baseUrl, options.client]\n );\n\n const [status, setStatus] = useState<LiveSchemaStatus | undefined>();\n const [pending, setPending] = useState<PendingChange | undefined>();\n const [plan, setPlan] = useState<LiveSchemaPlan | undefined>();\n const [planError, setPlanError] = useState<string | undefined>();\n const [result, setResult] = useState<LiveSchemaResult | undefined>();\n const [applying, setApplying] = useState(false);\n const [applyError, setApplyError] = useState<string | undefined>();\n\n // The in-flight probe, so `ready()` can await the same one the effect\n // started rather than issuing a second. Keyed by client+authKey the same way\n // the effect is: a sign-in changes the answer, so it has to be re-asked.\n // `undefined` passed explicitly: React 19's `useRef` takes no zero-argument\n // overload, and omitting it is an error rather than a default.\n const probe = useRef<{ key: unknown[]; promise: Promise<LiveSchemaStatus> } | undefined>(undefined);\n\n /** Which review a plan response belongs to. See `reviewChange`. */\n const reviewToken = useRef(0);\n\n const ready = useCallback((): Promise<LiveSchemaStatus> => {\n if (!asking) return Promise.resolve(NOT_ASKED);\n const key = [client, authKey];\n const current = probe.current;\n if (!current || current.key[0] !== key[0] || current.key[1] !== key[1]) {\n probe.current = { key, promise: client.status() };\n }\n return probe.current!.promise;\n }, [client, authKey, asking]);\n\n useEffect(() => {\n let cancelled = false;\n void ready().then(answer => {\n if (!cancelled) setStatus(answer);\n });\n return () => { cancelled = true; };\n }, [ready]);\n\n /**\n * Ask what the change would do, and ignore an answer that arrives late.\n *\n * Separate from `reviewChange` so it can be issued *again* without starting\n * a new review: a plan that failed on a dropped connection should cost a\n * click, not the whole wizard — the person has already filled in the form,\n * and making them do it twice for a transient failure is the kind of thing\n * that teaches people to distrust the preview.\n */\n const requestPlan = useCallback(async (change: ProposedCollectionChange) => {\n // Identifies the review a response belongs to. A plan that arrives after\n // its review was replaced must not be shown: the dialog would describe\n // the *previous* change while the reader believes it describes this one.\n const token = ++reviewToken.current;\n try {\n const answer = await client.plan(change);\n if (token === reviewToken.current) setPlan(answer);\n } catch (err: unknown) {\n if (token !== reviewToken.current) return;\n setPlanError(\n err instanceof LiveSchemaError || err instanceof Error\n ? err.message\n : String(err)\n );\n }\n }, [client]);\n\n const onRetry = useCallback(() => {\n if (!pending) return;\n setPlanError(undefined);\n setPlan(undefined);\n void requestPlan(pending.change);\n }, [pending, requestPlan]);\n\n const clear = useCallback(() => {\n setPending(undefined);\n setPlan(undefined);\n setPlanError(undefined);\n setResult(undefined);\n setApplyError(undefined);\n setApplying(false);\n }, []);\n\n const reviewChange = useCallback((change: ProposedCollectionChange) => {\n return new Promise<void>((resolve, reject) => {\n // A second review while one is open — a double-clicked save —\n // replaces the pending one, and the one it replaces has to be\n // settled. `setPending` used to overwrite `resolve`/`reject` with\n // nobody left holding them, so the first caller's promise never\n // settled at all and the editor's save simply never returned.\n setPending(previous => {\n previous?.reject(new SchemaChangeCancelled());\n return { change, resolve, reject };\n });\n\n // Identifies the review a response belongs to. A plan that arrives\n // after its review was replaced must not be shown: the dialog would\n // describe the *previous* change while the reader believes it\n // describes this one, and the SQL on screen would be for something\n // they are not confirming.\n setPlan(undefined);\n setPlanError(undefined);\n setResult(undefined);\n setApplyError(undefined);\n setApplying(false);\n\n void requestPlan(change);\n });\n // `client` is not listed: this no longer touches it directly, and\n // `requestPlan` already carries that dependency.\n }, [requestPlan]);\n\n const onConfirm = useCallback(() => {\n if (!pending) return;\n setApplying(true);\n setApplyError(undefined);\n void client.apply(pending.change).then(\n answer => {\n setResult(answer);\n setApplying(false);\n // Resolved here, not on close. The change has happened, and the\n // dialog is now a receipt somebody may read for as long as they\n // like — holding the caller open until they close it would\n // leave the editor mid-save for no reason.\n pending.resolve();\n setPending(undefined);\n },\n (err: unknown) => {\n setApplying(false);\n setApplyError(err instanceof Error ? err.message : String(err));\n }\n );\n }, [client, pending]);\n\n /**\n * \"Edit source only\": commit the collection, run nothing.\n *\n * Through the same door as an apply, so it is committed. It used to be a\n * write through the source-only editor that nobody committed, which every\n * later \"Commit and apply\" met as somebody else's work — 409, with the\n * dialog never saying why.\n */\n const onSourceOnly = useCallback(() => {\n if (!pending) return;\n setApplying(true);\n setApplyError(undefined);\n const settle = pending;\n void client.apply({ ...settle.change, sourceOnly: true }).then(\n answer => {\n setResult(answer);\n setApplying(false);\n settle.resolve();\n setPending(undefined);\n },\n (err: unknown) => {\n setApplying(false);\n setApplyError(err instanceof Error ? err.message : String(err));\n }\n );\n }, [client, pending]);\n\n // Offered only when every refused change says what it would leave behind.\n // One that does not may not be written to the source alone.\n const sourceOnlyOffered = Boolean(plan && !plan.applicable &&\n plan.changes.filter(change => change.verdict !== \"safe\").every(change => change.sourceOnly));\n\n const onClose = useCallback(() => {\n // Escape and the backdrop reach this too, and the Cancel *button* is the\n // only one of the three that was disabled while applying. Closing\n // mid-apply rejected the caller as cancelled while the commit and the\n // DDL carried on — reporting that nothing happened while something did,\n // which is the exact failure this whole feature exists to end.\n if (applying) return;\n\n const settle = pending;\n clear();\n // A dialog showing a result has already resolved; closing it is not a\n // cancellation of anything.\n if (settle && !result) settle.reject(new SchemaChangeCancelled());\n }, [applying, pending, result, clear]);\n\n // Not even a Suspense boundary until there is something to review — the\n // chunk is fetched by the first `reviewChange`, and an admin session that\n // never edits a collection never pays for it.\n const open = Boolean(pending) || Boolean(result);\n const dialog = open\n ? (\n <Suspense fallback={null}>\n <SchemaChangeDialog\n open={open}\n collectionId={pending?.change.collectionId ?? \"\"}\n plan={plan}\n planError={planError}\n result={result}\n applying={applying}\n applyError={applyError}\n onConfirm={onConfirm}\n onRetry={planError ? onRetry : undefined}\n onSourceOnly={sourceOnlyOffered ? onSourceOnly : undefined}\n onClose={onClose}\n applyRefusedBecause={\n status && !status.canApply ? status.applyRefusedBecause : undefined\n }\n target={status && {\n repository: status.repository,\n branch: status.branch\n }}\n />\n </Suspense>\n )\n : null;\n\n return { status, ready, reviewChange, dialog };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,IAAM,qBAAqB,gBACvB,OAAO,+CAA4C,CAC9C,MAAK,OAAM,EAAE,SAAS,EAAE,mBAAmB,EAAE,CACtD;;AA0BA,IAAM,YAA8B;CAAE,SAAS;CAAO,SAAS;CAAO,UAAU;AAAM;AAsCtF,SAAgB,qBAAqB,SAAyD;CAC1F,MAAM,EAAE,SAAS,YAAY;CAC7B,MAAM,SAAS,QAAQ,YAAY;CAEnC,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CAErB,MAAM,SAAS,cACL,QAAQ,UAAU,uBAAuB;EAC3C;EACA,oBAAoB,WAAW,QAAQ,eAAe,KAAK;CAC/D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AAM;GAAE,GAAG,OAAO;GAAQ,YAAY;EAAK,CAAC,CAAC,CAAC,MACtD,WAAU;GACN,UAAU,MAAM;GAChB,YAAY,KAAK;GACjB,OAAO,QAAQ;GACf,WAAW,KAAA,CAAS;EACxB,IACC,QAAiB;GACd,YAAY,KAAK;GACjB,cAAc,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;EAClE,CACJ;CACJ,GAAG,CAAC,QAAQ,OAAO,CAAC;CAIpB,MAAM,oBAAoB,QAAQ,QAAQ,CAAC,KAAK,cAC5C,KAAK,QAAQ,QAAO,WAAU,OAAO,YAAY,MAAM,CAAC,CAAC,OAAM,WAAU,OAAO,UAAU,CAAC;CAE/F,MAAM,UAAU,kBAAkB;EAM9B,IAAI,UAAU;EAEd,MAAM,SAAS;EACf,MAAM;EAGN,IAAI,UAAU,CAAC,QAAQ,OAAO,OAAO,IAAI,sBAAsB,CAAC;CACpE,GAAG;EAAC;EAAU;EAAS;EAAQ;CAAK,CAAC;CAKrC,MAAM,OAAO,QAAQ,OAAO,KAAK,QAAQ,MAAM;CA4B/C,OAAO;EAAE;EAAQ;EAAO;EAAc,QA3BvB,OAEP,oBAAC,UAAD;GAAU,UAAU;aAChB,oBAAC,oBAAD;IACU;IACN,cAAc,SAAS,OAAO,gBAAgB;IACxC;IACK;IACH;IACE;IACE;IACD;IACX,SAAS,YAAY,UAAU,KAAA;IAC/B,cAAc,oBAAoB,eAAe,KAAA;IACxC;IACT,qBACI,UAAU,CAAC,OAAO,WAAW,OAAO,sBAAsB,KAAA;IAE9D,QAAQ,UAAU;KACd,YAAY,OAAO;KACnB,QAAQ,OAAO;IACnB;GACH,CAAA;EACK,CAAA,IAEZ;CAEuC;AACjD"}
1
+ {"version":3,"file":"useLiveSchemaEditing.js","names":[],"sources":["../../src/collection_editor/useLiveSchemaEditing.tsx"],"sourcesContent":["/**\n * The plan-then-confirm flow, as a hook.\n *\n * Owns three things that belong together and nothing else: whether the backend\n * can edit its schema, the plan for the change somebody is making, and the\n * dialog they confirm it in. The config controller calls `reviewChange` and\n * awaits it; everything about *how* the confirmation happens stays here.\n *\n * ## Why `reviewChange` returns a promise that can reject\n *\n * Because the editor needs to know. A save that was cancelled must not leave\n * the form thinking it succeeded — the collection on screen would then differ\n * from the one on disk, and the next save would be computed from the wrong\n * `before`. Rejecting with {@link SchemaChangeCancelled} is how \"the person\n * said no\" reaches the caller as an outcome rather than as silence.\n */\nimport React, { Suspense, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { lazyChunk } from \"@rebasepro/ui\";\n\nimport {\n createLiveSchemaClient,\n LiveSchemaError,\n SchemaChangeCancelled,\n type LiveSchemaClient,\n type LiveSchemaPlan,\n type LiveSchemaResult,\n type LiveSchemaStatus,\n type ProposedCollectionChange\n} from \"./liveSchemaClient\";\n\n// Re-exported so the hook stays the one import a caller needs.\nexport { SchemaChangeCancelled, isSchemaChangeCancelled } from \"./liveSchemaClient\";\n\n/**\n * Loaded when a change is actually being reviewed, not before.\n *\n * This hook is reached from the collections config controller, which is\n * constructed on every admin boot — so a static import would put the dialog and\n * the `@rebasepro/ui` surface it draws on into the **eager** bundle: everything\n * a browser downloads before the login screen paints. It cost 14 kB there, for\n * a dialog most sessions never open. The bundle budget caught it.\n */\nconst SchemaChangeDialog = lazyChunk(() =>\n import(\"./ui/collection_editor/SchemaChangeDialog\")\n .then(m => ({ default: m.SchemaChangeDialog }))\n);\n\nexport interface UseLiveSchemaEditingOptions {\n /** Base for the routes, e.g. `https://api.example.com/api/admin/schema`. */\n baseUrl: string;\n getAuthToken?: () => Promise<string | null> | string | null;\n /**\n * Identity of the signed-in user.\n *\n * Only used to re-ask: whether this backend will accept a schema change\n * depends on who is asking, and the answer to an anonymous probe does not\n * survive a sign-in.\n */\n authKey?: string | null;\n /**\n * Whether to ask the backend at all. `false` when the caller cannot be told\n * anything (`/status` needs `schema:read`) or the editor is read-only: the\n * answer is then \"not available\" without a request that could only be\n * refused. Defaults to `true`.\n */\n enabled?: boolean;\n /** Swappable for the tests, which have no server. */\n client?: LiveSchemaClient;\n}\n\n/** The answer when nobody asked. */\nconst NOT_ASKED: LiveSchemaStatus = { enabled: false, canPlan: false, canApply: false };\n\ninterface PendingChange {\n change: ProposedCollectionChange;\n resolve: () => void;\n reject: (err: Error) => void;\n}\n\nexport interface LiveSchemaEditing {\n /** `undefined` until the backend has answered. For rendering. */\n status?: LiveSchemaStatus;\n /**\n * The same answer, for deciding.\n *\n * `status` is undefined for one round trip after mount, and a caller that\n * read it to choose a code path would take the \"not available\" branch for\n * that window — so a save issued quickly after a page load would silently\n * skip the confirmation and write source only, while the same save a second\n * later would not. Timing-dependent behaviour with no visible difference is\n * the worst shape this could have.\n *\n * Resolves once, cached; never rejects, because every way of failing to get\n * an answer means the same thing to whoever is deciding.\n */\n ready: () => Promise<LiveSchemaStatus>;\n /**\n * Plan the change, show it, and settle when the person has decided.\n *\n * Resolves once the change has been applied — or written source-only, if\n * they chose that. Rejects with {@link SchemaChangeCancelled} if they\n * closed the dialog, and with the underlying error if planning or applying\n * failed in a way they did not choose.\n */\n reviewChange: (change: ProposedCollectionChange) => Promise<void>;\n /** Render this once, high enough that a dialog over the editor is not clipped. */\n dialog: React.ReactNode;\n}\n\nexport function useLiveSchemaEditing(options: UseLiveSchemaEditingOptions): LiveSchemaEditing {\n const { baseUrl, authKey } = options;\n const asking = options.enabled !== false;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const client = useMemo(\n () => options.client ?? createLiveSchemaClient({\n baseUrl,\n getAuthToken: () => optionsRef.current.getAuthToken?.() ?? null\n }),\n // `client` is either supplied once by a test or built from the URL. The\n // token getter is read through the ref so a new closure on every render\n // does not rebuild the client underneath an in-flight request.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [baseUrl, options.client]\n );\n\n const [status, setStatus] = useState<LiveSchemaStatus | undefined>();\n const [pending, setPending] = useState<PendingChange | undefined>();\n const [plan, setPlan] = useState<LiveSchemaPlan | undefined>();\n const [planError, setPlanError] = useState<string | undefined>();\n const [result, setResult] = useState<LiveSchemaResult | undefined>();\n const [applying, setApplying] = useState(false);\n const [applyError, setApplyError] = useState<string | undefined>();\n\n // The in-flight probe, so `ready()` can await the same one the effect\n // started rather than issuing a second. Keyed by client+authKey the same way\n // the effect is: a sign-in changes the answer, so it has to be re-asked.\n // `undefined` passed explicitly: React 19's `useRef` takes no zero-argument\n // overload, and omitting it is an error rather than a default.\n const probe = useRef<{ key: unknown[]; promise: Promise<LiveSchemaStatus> } | undefined>(undefined);\n\n /** Which review a plan response belongs to. See `reviewChange`. */\n const reviewToken = useRef(0);\n\n const ready = useCallback((): Promise<LiveSchemaStatus> => {\n if (!asking) return Promise.resolve(NOT_ASKED);\n const key = [client, authKey];\n const current = probe.current;\n if (!current || current.key[0] !== key[0] || current.key[1] !== key[1]) {\n probe.current = { key, promise: client.status() };\n }\n return probe.current!.promise;\n }, [client, authKey, asking]);\n\n useEffect(() => {\n let cancelled = false;\n void ready().then(answer => {\n if (!cancelled) setStatus(answer);\n });\n return () => { cancelled = true; };\n }, [ready]);\n\n /**\n * Ask what the change would do, and ignore an answer that arrives late.\n *\n * Separate from `reviewChange` so it can be issued *again* without starting\n * a new review: a plan that failed on a dropped connection should cost a\n * click, not the whole wizard — the person has already filled in the form,\n * and making them do it twice for a transient failure is the kind of thing\n * that teaches people to distrust the preview.\n */\n const requestPlan = useCallback(async (change: ProposedCollectionChange) => {\n // Identifies the review a response belongs to. A plan that arrives after\n // its review was replaced must not be shown: the dialog would describe\n // the *previous* change while the reader believes it describes this one.\n const token = ++reviewToken.current;\n try {\n const answer = await client.plan(change);\n if (token === reviewToken.current) setPlan(answer);\n } catch (err: unknown) {\n if (token !== reviewToken.current) return;\n setPlanError(\n err instanceof LiveSchemaError || err instanceof Error\n ? err.message\n : String(err)\n );\n }\n }, [client]);\n\n const onRetry = useCallback(() => {\n if (!pending) return;\n setPlanError(undefined);\n setPlan(undefined);\n void requestPlan(pending.change);\n }, [pending, requestPlan]);\n\n const clear = useCallback(() => {\n setPending(undefined);\n setPlan(undefined);\n setPlanError(undefined);\n setResult(undefined);\n setApplyError(undefined);\n setApplying(false);\n }, []);\n\n const reviewChange = useCallback((change: ProposedCollectionChange) => {\n return new Promise<void>((resolve, reject) => {\n // A second review while one is open — a double-clicked save —\n // replaces the pending one, and the one it replaces has to be\n // settled. `setPending` used to overwrite `resolve`/`reject` with\n // nobody left holding them, so the first caller's promise never\n // settled at all and the editor's save simply never returned.\n setPending(previous => {\n previous?.reject(new SchemaChangeCancelled());\n return { change, resolve, reject };\n });\n\n // Identifies the review a response belongs to. A plan that arrives\n // after its review was replaced must not be shown: the dialog would\n // describe the *previous* change while the reader believes it\n // describes this one, and the SQL on screen would be for something\n // they are not confirming.\n setPlan(undefined);\n setPlanError(undefined);\n setResult(undefined);\n setApplyError(undefined);\n setApplying(false);\n\n void requestPlan(change);\n });\n // `client` is not listed: this no longer touches it directly, and\n // `requestPlan` already carries that dependency.\n }, [requestPlan]);\n\n const onConfirm = useCallback(() => {\n if (!pending) return;\n setApplying(true);\n setApplyError(undefined);\n void client.apply(pending.change).then(\n answer => {\n setResult(answer);\n setApplying(false);\n // Resolved here, not on close. The change has happened, and the\n // dialog is now a receipt somebody may read for as long as they\n // like — holding the caller open until they close it would\n // leave the editor mid-save for no reason.\n pending.resolve();\n setPending(undefined);\n },\n (err: unknown) => {\n setApplying(false);\n setApplyError(err instanceof Error ? err.message : String(err));\n }\n );\n }, [client, pending]);\n\n /**\n * \"Edit source only\": commit the collection, run nothing.\n *\n * Through the same door as an apply, so it is committed. It used to be a\n * write through the source-only editor that nobody committed, which every\n * later \"Commit and apply\" met as somebody else's work — 409, with the\n * dialog never saying why.\n */\n const onSourceOnly = useCallback(() => {\n if (!pending) return;\n setApplying(true);\n setApplyError(undefined);\n const settle = pending;\n void client.apply({ ...settle.change, sourceOnly: true }).then(\n answer => {\n setResult(answer);\n setApplying(false);\n settle.resolve();\n setPending(undefined);\n },\n (err: unknown) => {\n setApplying(false);\n setApplyError(err instanceof Error ? err.message : String(err));\n }\n );\n }, [client, pending]);\n\n // A deployment that provisions nothing applies no change from here, and\n // says to commit it as source only: for a change that could be applied,\n // that commit is the way through, and the dialog's main action.\n const provisioningOff = status?.applyRefusedCode === \"SCHEMA_EDITING_PROVISIONING_OFF\";\n const commitAsSourceOnly = Boolean(provisioningOff && plan?.applicable);\n\n // Offered only when every refused change says what it would leave behind.\n // One that does not may not be written to the source alone.\n const sourceOnlyOffered = commitAsSourceOnly || Boolean(plan && !plan.applicable &&\n plan.changes.filter(change => change.verdict !== \"safe\").every(change => change.sourceOnly));\n\n const onClose = useCallback(() => {\n // Escape and the backdrop reach this too, and the Cancel *button* is the\n // only one of the three that was disabled while applying. Closing\n // mid-apply rejected the caller as cancelled while the commit and the\n // DDL carried on — reporting that nothing happened while something did,\n // which is the exact failure this whole feature exists to end.\n if (applying) return;\n\n const settle = pending;\n clear();\n // A dialog showing a result has already resolved; closing it is not a\n // cancellation of anything.\n if (settle && !result) settle.reject(new SchemaChangeCancelled());\n }, [applying, pending, result, clear]);\n\n // Not even a Suspense boundary until there is something to review — the\n // chunk is fetched by the first `reviewChange`, and an admin session that\n // never edits a collection never pays for it.\n const open = Boolean(pending) || Boolean(result);\n const dialog = open\n ? (\n <Suspense fallback={null}>\n <SchemaChangeDialog\n open={open}\n collectionId={pending?.change.collectionId ?? \"\"}\n plan={plan}\n planError={planError}\n result={result}\n applying={applying}\n applyError={applyError}\n onConfirm={onConfirm}\n onRetry={planError ? onRetry : undefined}\n onSourceOnly={sourceOnlyOffered ? onSourceOnly : undefined}\n sourceOnlyIsTheCommit={commitAsSourceOnly}\n onClose={onClose}\n applyRefusedBecause={\n status && !status.canApply ? status.applyRefusedBecause : undefined\n }\n target={status && {\n repository: status.repository,\n branch: status.branch\n }}\n />\n </Suspense>\n )\n : null;\n\n return { status, ready, reviewChange, dialog };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,IAAM,qBA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ChB,oBAAC,oBAAD;IACU;IACN,cAAc,SAAS,OAAO,gBAAgB;IACxC;IACK;IACH;IACE;IACE;IACD;IACX,SAAS,YAAY,UAAU,KAAA;IAC/B,cAAc,oBAAoB,eAAe,KAAA;IACjD,uBAAuB;IACd;IACT,qBACI,UAAU,CAAC,OAAO,WAAW,OAAO,sBAAsB,KAAA;IAE9D,QAAQ,UAAU;KACd,YAAY,OAAO;KACnB,QAAQ,OAAO;IACnB;GACH,CAAA;EACK,CAAA,IAEZ;CAEuC;AACjD"}
@@ -1,4 +1,5 @@
1
1
  import { getPreviewSizeFrom } from "../../../preview/util.js";
2
+ import { DefaultMissingReference } from "../../DefaultMissingReference.js";
2
3
  import { useCollectionRegistryController } from "../../../hooks/navigation/contexts/CollectionRegistryContext.js";
3
4
  import { useReferencePaths } from "../../../hooks/useReferencePaths.js";
4
5
  import { ReferencePreview } from "../../../preview/components/ReferencePreview.js";
@@ -9,7 +10,6 @@ import { jsx } from "react/jsx-runtime";
9
10
  import { deepEqual } from "fast-equals";
10
11
  import { CollectionScopeProvider, ErrorView, useComponentOverride } from "@rebasepro/app";
11
12
  //#region src/components/CollectionTableBinding/fields/TableReferenceField.tsx
12
- var DefaultMissingReference = () => null;
13
13
  function TableReferenceFieldResolver(props) {
14
14
  const ResolvedMissingReference = useComponentOverride("Entity.MissingReference", DefaultMissingReference);
15
15
  const { path, collection } = props;
@@ -1 +1 @@
1
- {"version":3,"file":"TableReferenceField.js","names":[],"sources":["../../../../src/components/CollectionTableBinding/fields/TableReferenceField.tsx"],"sourcesContent":["import { useSelectionDialog } from \"../../../hooks/useSelectionDialog\";\n\nimport React, { useCallback, useEffect } from \"react\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { ReferencePreview } from \"../../../preview\";\nimport { Entity, EntityReference, FilterValues } from \"@rebasepro/types\";\nimport { CollectionSize, AdminCollection } from \"@rebasepro/cms-types\";\n\nimport { getPreviewSizeFrom } from \"../../../preview/util\";\nimport { useComponentOverride, ErrorView, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { useCollectionRegistryController } from \"../../../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useReferencePaths } from \"../../../hooks/useReferencePaths\";\nimport { CompactEntityCellField } from \"./CompactEntityCellField\";\n\ntype TableReferenceFieldProps = {\n name: string;\n disabled: boolean;\n internalValue: EntityReference | EntityReference[] | undefined | null;\n updateValue: (newValue: (EntityReference | EntityReference[] | null)) => void;\n size: CollectionSize;\n multiselect: boolean;\n previewProperties?: string[];\n path: string;\n fixedFilter?: FilterValues<string>;\n includeId?: boolean;\n includeEntityLink?: boolean;\n /** The cell is selected. */\n selected?: boolean;\n /**\n * Set by the cell's opener: opens the selection dialog, and is handed\n * back as closed at once — the dialog keeps its own state from there.\n */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n};\n\nconst DefaultMissingReference: React.FC<{ path: string }> = () => null;\n\nfunction TableReferenceFieldResolver(props: TableReferenceFieldProps & { collection: AdminCollection | undefined }) {\n const ResolvedMissingReference = useComponentOverride(\"Entity.MissingReference\", DefaultMissingReference);\n const { path, collection } = props;\n\n if (!collection) {\n if (ResolvedMissingReference !== DefaultMissingReference) {\n return <ResolvedMissingReference path={path}/>;\n } else {\n return <ErrorView error={`Collection not found: ${path}`}/>;\n }\n }\n return <TableReferenceFieldInternal {...props} collection={collection}/>;\n}\n\nexport function TableReferenceField(props: TableReferenceFieldProps) {\n const collectionRegistryController = useCollectionRegistryController();\n const { toCollectionPath } = useReferencePaths();\n const path = toCollectionPath(props.path);\n const collection = collectionRegistryController.getCollection(path);\n\n const content = (\n <TableReferenceFieldResolver\n {...props}\n path={path}\n collection={collection}\n />\n );\n\n if (collection) {\n return (\n <CollectionScopeProvider collection={collection}>\n {content}\n </CollectionScopeProvider>\n );\n }\n return content;\n}\n\nexport const TableReferenceFieldInternal = React.memo(\n function TableReferenceFieldInternal(props: TableReferenceFieldProps & {\n collection: AdminCollection;\n }) {\n const {\n name,\n internalValue,\n updateValue,\n multiselect,\n path,\n size,\n previewProperties,\n disabled,\n fixedFilter,\n collection,\n includeId,\n includeEntityLink,\n selected,\n open,\n onOpenChange\n } = props;\n\n const { referenceTo } = useReferencePaths();\n\n const onSingleEntitySelected = useCallback((entity: Entity<any>) => {\n updateValue(entity ? referenceTo(entity) : null);\n }, [updateValue, referenceTo]);\n\n const onMultipleEntitiesSelected = useCallback((entities: Entity<any>[]) => {\n updateValue(entities.map((e) => referenceTo(e)));\n }, [updateValue, referenceTo]);\n\n const selectedEntityIds = internalValue\n ? (Array.isArray(internalValue)\n ? internalValue.map((ref) => ref.id)\n : internalValue.id ? [internalValue.id] : [])\n : [];\n\n const referenceDialogController = useSelectionDialog({\n multiselect,\n path,\n collection,\n onMultipleEntitiesSelected,\n onSingleEntitySelected,\n selectedEntityIds,\n fixedFilter\n }\n );\n\n const handleOpen = () => {\n if (disabled)\n return;\n referenceDialogController.open();\n };\n\n // The cell's opener asks for the dialog. It is a request, not a state:\n // the dialog closes itself, so the request is handed straight back.\n useEffect(() => {\n if (!open) return;\n onOpenChange?.(false);\n handleOpen();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open]);\n\n const valueNotSet = !internalValue || (Array.isArray(internalValue) && internalValue.length === 0);\n\n if (!collection)\n return <ErrorView error={\"The specified collection does not exist\"}/>;\n\n // One line at every row size: the inline previews (each title opens\n // its record), the cell's opener to pick and a cross to clear. A single\n // record takes the row's preview size; a list stays lines.\n const refs: EntityReference[] = !internalValue ? [] : (Array.isArray(internalValue) ? internalValue : [internalValue]);\n return <CompactEntityCellField empty={valueNotSet}\n disabled={disabled}\n selected={selected}\n onClear={() => updateValue(multiselect ? [] : null)}>\n {refs.map((reference, index) =>\n reference && reference.isEntityReference && reference.isEntityReference()\n ? <ReferencePreview key={`compact_ref_${name}_${index}`}\n size={multiselect ? \"small\" : getPreviewSizeFrom(size)}\n reference={reference}\n hover={false}\n disabled={!path}\n previewProperties={previewProperties}\n includeId={includeId}\n includeEntityLink={includeEntityLink}/>\n : <ErrorView key={`compact_ref_${name}_${index}`} error={\"Value is not a reference\"}/>)}\n </CompactEntityCellField>;\n }, equal);\n"],"mappings":";;;;;;;;;;;AAqCA,IAAM,gCAA4D;AAElE,SAAS,4BAA4B,OAA+E;CAChH,MAAM,2BAA2B,qBAAqB,2BAA2B,uBAAuB;CACxG,MAAM,EAAE,MAAM,eAAe;CAE7B,IAAI,CAAC,YACD,IAAI,6BAA6B,yBAC7B,OAAO,oBAAC,0BAAD,EAAgC,KAAM,CAAA;MAE7C,OAAO,oBAAC,WAAD,EAAW,OAAO,yBAAyB,OAAQ,CAAA;CAGlE,OAAO,oBAAC,6BAAD;EAA6B,GAAI;EAAmB;CAAY,CAAA;AAC3E;AAEA,SAAgB,oBAAoB,OAAiC;CACjE,MAAM,+BAA+B,gCAAgC;CACrE,MAAM,EAAE,qBAAqB,kBAAkB;CAC/C,MAAM,OAAO,iBAAiB,MAAM,IAAI;CACxC,MAAM,aAAa,6BAA6B,cAAc,IAAI;CAElE,MAAM,UACF,oBAAC,6BAAD;EACI,GAAI;EACE;EACM;CACf,CAAA;CAGL,IAAI,YACA,OACI,oBAAC,yBAAD;EAAqC;YAChC;CACoB,CAAA;CAGjC,OAAO;AACX;AAEA,IAAa,8BAA8B,MAAM,KAC7C,SAAS,4BAA4B,OAElC;CACC,MAAM,EACF,MACA,eACA,aACA,aACA,MACA,MACA,mBACA,UACA,aACA,YACA,WACA,mBACA,UACA,MACA,iBACA;CAEJ,MAAM,EAAE,gBAAgB,kBAAkB;CAE1C,MAAM,yBAAyB,aAAa,WAAwB;EAChE,YAAY,SAAS,YAAY,MAAM,IAAI,IAAI;CACnD,GAAG,CAAC,aAAa,WAAW,CAAC;CAY7B,MAAM,4BAA4B,mBAAmB;EACjD;EACA;EACA;EACA,4BAd+B,aAAa,aAA4B;GACxE,YAAY,SAAS,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC;EACnD,GAAG,CAAC,aAAa,WAAW,CAYxB;EACA;EACA,mBAZsB,gBACnB,MAAM,QAAQ,aAAa,IACxB,cAAc,KAAK,QAAQ,IAAI,EAAE,IACjC,cAAc,KAAK,CAAC,cAAc,EAAE,IAAI,CAAC,IAC7C,CAAC;EASH;CACJ,CACA;CAEA,MAAM,mBAAmB;EACrB,IAAI,UACA;EACJ,0BAA0B,KAAK;CACnC;CAIA,gBAAgB;EACZ,IAAI,CAAC,MAAM;EACX,eAAe,KAAK;EACpB,WAAW;CAEf,GAAG,CAAC,IAAI,CAAC;CAET,MAAM,cAAc,CAAC,iBAAkB,MAAM,QAAQ,aAAa,KAAK,cAAc,WAAW;CAEhG,IAAI,CAAC,YACD,OAAO,oBAAC,WAAD,EAAW,OAAO,0CAA2C,CAAA;CAMxE,OAAO,oBAAC,wBAAD;EAAwB,OAAO;EACxB;EACA;EACV,eAAe,YAAY,cAAc,CAAC,IAAI,IAAI;aAJtB,CAAC,gBAAgB,CAAC,IAAK,MAAM,QAAQ,aAAa,IAAI,gBAAgB,CAAC,aAAa,EAAA,CAK1G,KAAK,WAAW,UAClB,aAAa,UAAU,qBAAqB,UAAU,kBAAkB,IAClE,oBAAC,kBAAD;GACE,MAAM,cAAc,UAAU,mBAAmB,IAAI;GAC1C;GACX,OAAO;GACP,UAAU,CAAC;GACQ;GACR;GACQ;EAAmB,GAPjB,eAAe,KAAK,GAAG,OAON,IACxC,oBAAC,WAAD,EAAgD,OAAO,2BAA4B,GAAnE,eAAe,KAAK,GAAG,OAA4C,CAAC;CAC1E,CAAA;AAC5B,GAAG,SAAK"}
1
+ {"version":3,"file":"TableReferenceField.js","names":[],"sources":["../../../../src/components/CollectionTableBinding/fields/TableReferenceField.tsx"],"sourcesContent":["import { useSelectionDialog } from \"../../../hooks/useSelectionDialog\";\n\nimport React, { useCallback, useEffect } from \"react\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { ReferencePreview } from \"../../../preview\";\nimport { Entity, EntityReference, FilterValues } from \"@rebasepro/types\";\nimport { CollectionSize, AdminCollection } from \"@rebasepro/cms-types\";\n\nimport { getPreviewSizeFrom } from \"../../../preview/util\";\nimport { useComponentOverride, ErrorView, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { useCollectionRegistryController } from \"../../../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useReferencePaths } from \"../../../hooks/useReferencePaths\";\nimport { CompactEntityCellField } from \"./CompactEntityCellField\";\nimport { DefaultMissingReference } from \"../../DefaultMissingReference\";\n\ntype TableReferenceFieldProps = {\n name: string;\n disabled: boolean;\n internalValue: EntityReference | EntityReference[] | undefined | null;\n updateValue: (newValue: (EntityReference | EntityReference[] | null)) => void;\n size: CollectionSize;\n multiselect: boolean;\n previewProperties?: string[];\n path: string;\n fixedFilter?: FilterValues<string>;\n includeId?: boolean;\n includeEntityLink?: boolean;\n /** The cell is selected. */\n selected?: boolean;\n /**\n * Set by the cell's opener: opens the selection dialog, and is handed\n * back as closed at once — the dialog keeps its own state from there.\n */\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n};\n\n\nfunction TableReferenceFieldResolver(props: TableReferenceFieldProps & { collection: AdminCollection | undefined }) {\n const ResolvedMissingReference = useComponentOverride(\"Entity.MissingReference\", DefaultMissingReference);\n const { path, collection } = props;\n\n if (!collection) {\n if (ResolvedMissingReference !== DefaultMissingReference) {\n return <ResolvedMissingReference path={path}/>;\n } else {\n return <ErrorView error={`Collection not found: ${path}`}/>;\n }\n }\n return <TableReferenceFieldInternal {...props} collection={collection}/>;\n}\n\nexport function TableReferenceField(props: TableReferenceFieldProps) {\n const collectionRegistryController = useCollectionRegistryController();\n const { toCollectionPath } = useReferencePaths();\n const path = toCollectionPath(props.path);\n const collection = collectionRegistryController.getCollection(path);\n\n const content = (\n <TableReferenceFieldResolver\n {...props}\n path={path}\n collection={collection}\n />\n );\n\n if (collection) {\n return (\n <CollectionScopeProvider collection={collection}>\n {content}\n </CollectionScopeProvider>\n );\n }\n return content;\n}\n\nexport const TableReferenceFieldInternal = React.memo(\n function TableReferenceFieldInternal(props: TableReferenceFieldProps & {\n collection: AdminCollection;\n }) {\n const {\n name,\n internalValue,\n updateValue,\n multiselect,\n path,\n size,\n previewProperties,\n disabled,\n fixedFilter,\n collection,\n includeId,\n includeEntityLink,\n selected,\n open,\n onOpenChange\n } = props;\n\n const { referenceTo } = useReferencePaths();\n\n const onSingleEntitySelected = useCallback((entity: Entity<any>) => {\n updateValue(entity ? referenceTo(entity) : null);\n }, [updateValue, referenceTo]);\n\n const onMultipleEntitiesSelected = useCallback((entities: Entity<any>[]) => {\n updateValue(entities.map((e) => referenceTo(e)));\n }, [updateValue, referenceTo]);\n\n const selectedEntityIds = internalValue\n ? (Array.isArray(internalValue)\n ? internalValue.map((ref) => ref.id)\n : internalValue.id ? [internalValue.id] : [])\n : [];\n\n const referenceDialogController = useSelectionDialog({\n multiselect,\n path,\n collection,\n onMultipleEntitiesSelected,\n onSingleEntitySelected,\n selectedEntityIds,\n fixedFilter\n }\n );\n\n const handleOpen = () => {\n if (disabled)\n return;\n referenceDialogController.open();\n };\n\n // The cell's opener asks for the dialog. It is a request, not a state:\n // the dialog closes itself, so the request is handed straight back.\n useEffect(() => {\n if (!open) return;\n onOpenChange?.(false);\n handleOpen();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [open]);\n\n const valueNotSet = !internalValue || (Array.isArray(internalValue) && internalValue.length === 0);\n\n if (!collection)\n return <ErrorView error={\"The specified collection does not exist\"}/>;\n\n // One line at every row size: the inline previews (each title opens\n // its record), the cell's opener to pick and a cross to clear. A single\n // record takes the row's preview size; a list stays lines.\n const refs: EntityReference[] = !internalValue ? [] : (Array.isArray(internalValue) ? internalValue : [internalValue]);\n return <CompactEntityCellField empty={valueNotSet}\n disabled={disabled}\n selected={selected}\n onClear={() => updateValue(multiselect ? [] : null)}>\n {refs.map((reference, index) =>\n reference && reference.isEntityReference && reference.isEntityReference()\n ? <ReferencePreview key={`compact_ref_${name}_${index}`}\n size={multiselect ? \"small\" : getPreviewSizeFrom(size)}\n reference={reference}\n hover={false}\n disabled={!path}\n previewProperties={previewProperties}\n includeId={includeId}\n includeEntityLink={includeEntityLink}/>\n : <ErrorView key={`compact_ref_${name}_${index}`} error={\"Value is not a reference\"}/>)}\n </CompactEntityCellField>;\n }, equal);\n"],"mappings":";;;;;;;;;;;;AAuCA,SAAS,4BAA4B,OAA+E;CAChH,MAAM,2BAA2B,qBAAqB,2BAA2B,uBAAuB;CACxG,MAAM,EAAE,MAAM,eAAe;CAE7B,IAAI,CAAC,YACD,IAAI,6BAA6B,yBAC7B,OAAO,oBAAC,0BAAD,EAAgC,KAAM,CAAA;MAE7C,OAAO,oBAAC,WAAD,EAAW,OAAO,yBAAyB,OAAQ,CAAA;CAGlE,OAAO,oBAAC,6BAAD;EAA6B,GAAI;EAAmB;CAAY,CAAA;AAC3E;AAEA,SAAgB,oBAAoB,OAAiC;CACjE,MAAM,+BAA+B,gCAAgC;CACrE,MAAM,EAAE,qBAAqB,kBAAkB;CAC/C,MAAM,OAAO,iBAAiB,MAAM,IAAI;CACxC,MAAM,aAAa,6BAA6B,cAAc,IAAI;CAElE,MAAM,UACF,oBAAC,6BAAD;EACI,GAAI;EACE;EACM;CACf,CAAA;CAGL,IAAI,YACA,OACI,oBAAC,yBAAD;EAAqC;YAChC;CACoB,CAAA;CAGjC,OAAO;AACX;AAEA,IAAa,8BAA8B,MAAM,KAC7C,SAAS,4BAA4B,OAElC;CACC,MAAM,EACF,MACA,eACA,aACA,aACA,MACA,MACA,mBACA,UACA,aACA,YACA,WACA,mBACA,UACA,MACA,iBACA;CAEJ,MAAM,EAAE,gBAAgB,kBAAkB;CAE1C,MAAM,yBAAyB,aAAa,WAAwB;EAChE,YAAY,SAAS,YAAY,MAAM,IAAI,IAAI;CACnD,GAAG,CAAC,aAAa,WAAW,CAAC;CAY7B,MAAM,4BAA4B,mBAAmB;EACjD;EACA;EACA;EACA,4BAd+B,aAAa,aAA4B;GACxE,YAAY,SAAS,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC;EACnD,GAAG,CAAC,aAAa,WAAW,CAYxB;EACA;EACA,mBAZsB,gBACnB,MAAM,QAAQ,aAAa,IACxB,cAAc,KAAK,QAAQ,IAAI,EAAE,IACjC,cAAc,KAAK,CAAC,cAAc,EAAE,IAAI,CAAC,IAC7C,CAAC;EASH;CACJ,CACA;CAEA,MAAM,mBAAmB;EACrB,IAAI,UACA;EACJ,0BAA0B,KAAK;CACnC;CAIA,gBAAgB;EACZ,IAAI,CAAC,MAAM;EACX,eAAe,KAAK;EACpB,WAAW;CAEf,GAAG,CAAC,IAAI,CAAC;CAET,MAAM,cAAc,CAAC,iBAAkB,MAAM,QAAQ,aAAa,KAAK,cAAc,WAAW;CAEhG,IAAI,CAAC,YACD,OAAO,oBAAC,WAAD,EAAW,OAAO,0CAA2C,CAAA;CAMxE,OAAO,oBAAC,wBAAD;EAAwB,OAAO;EACxB;EACA;EACV,eAAe,YAAY,cAAc,CAAC,IAAI,IAAI;aAJtB,CAAC,gBAAgB,CAAC,IAAK,MAAM,QAAQ,aAAa,IAAI,gBAAgB,CAAC,aAAa,EAAA,CAK1G,KAAK,WAAW,UAClB,aAAa,UAAU,qBAAqB,UAAU,kBAAkB,IAClE,oBAAC,kBAAD;GACE,MAAM,cAAc,UAAU,mBAAmB,IAAI;GAC1C;GACX,OAAO;GACP,UAAU,CAAC;GACQ;GACR;GACQ;EAAmB,GAPjB,eAAe,KAAK,GAAG,OAON,IACxC,oBAAC,WAAD,EAAgD,OAAO,2BAA4B,GAAnE,eAAe,KAAK,GAAG,OAA4C,CAAC;CAC1E,CAAA;AAC5B,GAAG,SAAK"}
@@ -1,5 +1,5 @@
1
1
  import React from "react";
2
- interface CollectionTableToolbarProps {
2
+ export interface CollectionTableToolbarProps {
3
3
  loading: boolean;
4
4
  actionsStart?: React.ReactNode;
5
5
  actions?: React.ReactNode;
@@ -32,4 +32,3 @@ interface CollectionTableToolbarProps {
32
32
  */
33
33
  export declare function useToolbarLabels(): boolean;
34
34
  export declare function CollectionTableToolbar({ actions, actionsStart, loading, onTextSearch, title, viewModeToggle, initialSearchText, compact }: CollectionTableToolbarProps): React.JSX.Element;
35
- export {};
@@ -1 +1 @@
1
- {"version":3,"file":"CollectionTableToolbar.js","names":[],"sources":["../../../../src/components/CollectionTableBinding/internal/CollectionTableToolbar.tsx"],"sourcesContent":["import React, { useContext, useLayoutEffect, useRef, useState } from \"react\";\n\nimport { CircularProgress, cls, SearchBar } from \"@rebasepro/ui\";\nimport { useLargeLayout, useTranslation } from \"@rebasepro/app\";\n\ninterface CollectionTableToolbarProps {\n loading: boolean;\n actionsStart?: React.ReactNode;\n actions?: React.ReactNode;\n /**\n * View mode toggle button, positioned left of the search bar.\n */\n viewModeToggle?: React.ReactNode;\n title?: React.ReactNode,\n onTextSearch?: (searchString?: string) => void;\n /**\n * Initial search string to pre-populate the search bar (e.g. from URL params).\n */\n initialSearchText?: string;\n /**\n * When true the toolbar is in \"compact\" mode for the split-view left panel.\n * - Search bar, loading spinner, and view-mode toggle are hidden.\n * - Secondary actions remain inline (displayed horizontally).\n * - Only `actionsStart` (filters) and the add button (last child of `actions`) remain visible.\n */\n compact?: boolean;\n}\n\nconst ToolbarLabelsContext = React.createContext(true);\n\n/**\n * Whether the toolbar this control sits in has room for its controls' labels\n * (\"Filters\", \"Add existing\", \"Add Tag\"), or wants their icon-only forms.\n *\n * Decided by the toolbar's own width, not the window's: a relation tab beside\n * the split list is a narrow toolbar in a wide window, and its labelled\n * controls overflowed the left group and were drawn over the search bar.\n * `true` outside a toolbar.\n */\nexport function useToolbarLabels(): boolean {\n return useContext(ToolbarLabelsContext);\n}\n\n/**\n * Whether `row` — the toolbar's controls at their natural width — fits in\n * `container`. Once it has not, the width the labelled controls needed is kept,\n * and the labels come back only when the container has that much room again:\n * measured on the icon-only row, they would always seem to fit.\n */\nfunction useLabelsFit(\n container: React.RefObject<HTMLDivElement | null>,\n row: React.RefObject<HTMLDivElement | null>\n): boolean {\n const [labelled, setLabelled] = useState(true);\n const labelledRef = useRef(true);\n const labelledWidth = useRef<number | undefined>(undefined);\n\n useLayoutEffect(() => {\n const containerElement = container.current;\n const rowElement = row.current;\n if (!containerElement || !rowElement || typeof ResizeObserver === \"undefined\") return undefined;\n\n const measure = () => {\n const available = containerElement.clientWidth;\n let next = labelledRef.current;\n if (labelledRef.current) {\n const needed = rowElement.scrollWidth;\n if (needed > available + 1) {\n labelledWidth.current = needed;\n next = false;\n }\n } else if (labelledWidth.current !== undefined && available >= labelledWidth.current) {\n next = true;\n }\n if (next !== labelledRef.current) {\n labelledRef.current = next;\n setLabelled(next);\n }\n };\n\n // The container for the room there is, the row for what the controls\n // take — a selection count appearing widens the row, not the toolbar.\n const observer = new ResizeObserver(measure);\n observer.observe(containerElement);\n observer.observe(rowElement);\n measure();\n return () => observer.disconnect();\n }, [container, row]);\n\n return labelled;\n}\n\nexport function CollectionTableToolbar({\n actions,\n actionsStart,\n loading,\n onTextSearch,\n title,\n viewModeToggle,\n initialSearchText,\n compact = false\n}: CollectionTableToolbarProps) {\n\n const largeLayout = useLargeLayout();\n const { t } = useTranslation();\n\n const containerRef = useRef<HTMLDivElement>(null);\n const rowRef = useRef<HTMLDivElement>(null);\n const labelled = useLabelsFit(containerRef, rowRef);\n\n // Split actions into \"primary\" (add button = last child) and \"secondary\" (everything else)\n const actionChildren = React.Children.toArray(actions);\n const addButton = actionChildren.length > 0 ? actionChildren[actionChildren.length - 1] : null;\n const secondaryActions = actionChildren.slice(0, -1);\n\n return (\n <div\n ref={containerRef}\n className={cls(\"no-scrollbar min-h-[52px] overflow-x-auto bg-surface-sheet flex w-full\")}>\n\n {/* At least as wide as the toolbar, and never narrower than its\n controls: the two groups cannot be squeezed into each other.\n When even the icon-only controls do not fit, the toolbar\n scrolls. */}\n <div\n ref={rowRef}\n className={\"px-2 md:px-4 flex flex-row justify-between items-center min-w-full w-max\"}>\n\n <ToolbarLabelsContext.Provider value={labelled}>\n\n <div className=\"flex items-center gap-1 md:mr-4 mr-2\">\n\n {/* View toggle — hidden in compact */}\n {!compact && viewModeToggle}\n\n {title && <div className={\"flex items-center\"}>\n {title}\n </div>}\n\n {actionsStart}\n\n </div>\n\n <div className=\"flex items-center gap-1\">\n\n {/* Loading spinner — hidden in compact */}\n {largeLayout && !compact && loading && (\n <div className=\"mr-4\">\n <CircularProgress size={\"smallest\"}/>\n </div>\n )}\n\n {/* Search bar — hidden in compact */}\n {!compact && onTextSearch &&\n <SearchBar\n key={\"search-bar\"}\n size={\"small\"}\n placeholder={t(\"search\")}\n onTextSearch={onTextSearch}\n expandable={true}\n initialValue={initialSearchText}/>}\n\n {/* Secondary actions — always inline */}\n <div className=\"flex items-center gap-1\">\n {secondaryActions}\n </div>\n\n {/* Add button — always visible */}\n {addButton}\n\n </div>\n\n </ToolbarLabelsContext.Provider>\n\n </div>\n\n </div>\n );\n}\n"],"mappings":";;;;;AA4BA,IAAM,uBAAuB,MAAM,cAAc,IAAI;;;;;;;;;;AAWrD,SAAgB,mBAA4B;CACxC,OAAO,WAAW,oBAAoB;AAC1C;;;;;;;AAQA,SAAS,aACL,WACA,KACO;CACP,MAAM,CAAC,UAAU,eAAe,SAAS,IAAI;CAC7C,MAAM,cAAc,OAAO,IAAI;CAC/B,MAAM,gBAAgB,OAA2B,KAAA,CAAS;CAE1D,sBAAsB;EAClB,MAAM,mBAAmB,UAAU;EACnC,MAAM,aAAa,IAAI;EACvB,IAAI,CAAC,oBAAoB,CAAC,cAAc,OAAO,mBAAmB,aAAa,OAAO,KAAA;EAEtF,MAAM,gBAAgB;GAClB,MAAM,YAAY,iBAAiB;GACnC,IAAI,OAAO,YAAY;GACvB,IAAI,YAAY,SAAS;IACrB,MAAM,SAAS,WAAW;IAC1B,IAAI,SAAS,YAAY,GAAG;KACxB,cAAc,UAAU;KACxB,OAAO;IACX;GACJ,OAAO,IAAI,cAAc,YAAY,KAAA,KAAa,aAAa,cAAc,SACzE,OAAO;GAEX,IAAI,SAAS,YAAY,SAAS;IAC9B,YAAY,UAAU;IACtB,YAAY,IAAI;G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}
1
+ {"version":3,"file":"CollectionTableToolbar.js","names":[],"sources":["../../../../src/components/CollectionTableBinding/internal/CollectionTableToolbar.tsx"],"sourcesContent":["import React, { useContext, useLayoutEffect, useRef, useState } from \"react\";\n\nimport { CircularProgress, cls, SearchBar } from \"@rebasepro/ui\";\nimport { useLargeLayout, useTranslation } from \"@rebasepro/app\";\n\nexport interface CollectionTableToolbarProps {\n loading: boolean;\n actionsStart?: React.ReactNode;\n actions?: React.ReactNode;\n /**\n * View mode toggle button, positioned left of the search bar.\n */\n viewModeToggle?: React.ReactNode;\n title?: React.ReactNode,\n onTextSearch?: (searchString?: string) => void;\n /**\n * Initial search string to pre-populate the search bar (e.g. from URL params).\n */\n initialSearchText?: string;\n /**\n * When true the toolbar is in \"compact\" mode for the split-view left panel.\n * - Search bar, loading spinner, and view-mode toggle are hidden.\n * - Secondary actions remain inline (displayed horizontally).\n * - Only `actionsStart` (filters) and the add button (last child of `actions`) remain visible.\n */\n compact?: boolean;\n}\n\nconst ToolbarLabelsContext = React.createContext(true);\n\n/**\n * Whether the toolbar this control sits in has room for its controls' labels\n * (\"Filters\", \"Add existing\", \"Add Tag\"), or wants their icon-only forms.\n *\n * Decided by the toolbar's own width, not the window's: a relation tab beside\n * the split list is a narrow toolbar in a wide window, and its labelled\n * controls overflowed the left group and were drawn over the search bar.\n * `true` outside a toolbar.\n */\nexport function useToolbarLabels(): boolean {\n return useContext(ToolbarLabelsContext);\n}\n\n/**\n * Whether `row` — the toolbar's controls at their natural width — fits in\n * `container`. Once it has not, the width the labelled controls needed is kept,\n * and the labels come back only when the container has that much room again:\n * measured on the icon-only row, they would always seem to fit.\n */\nfunction useLabelsFit(\n container: React.RefObject<HTMLDivElement | null>,\n row: React.RefObject<HTMLDivElement | null>\n): boolean {\n const [labelled, setLabelled] = useState(true);\n const labelledRef = useRef(true);\n const labelledWidth = useRef<number | undefined>(undefined);\n\n useLayoutEffect(() => {\n const containerElement = container.current;\n const rowElement = row.current;\n if (!containerElement || !rowElement || typeof ResizeObserver === \"undefined\") return undefined;\n\n const measure = () => {\n const available = containerElement.clientWidth;\n let next = labelledRef.current;\n if (labelledRef.current) {\n const needed = rowElement.scrollWidth;\n if (needed > available + 1) {\n labelledWidth.current = needed;\n next = false;\n }\n } else if (labelledWidth.current !== undefined && available >= labelledWidth.current) {\n next = true;\n }\n if (next !== labelledRef.current) {\n labelledRef.current = next;\n setLabelled(next);\n }\n };\n\n // The container for the room there is, the row for what the controls\n // take — a selection count appearing widens the row, not the toolbar.\n const observer = new ResizeObserver(measure);\n observer.observe(containerElement);\n observer.observe(rowElement);\n measure();\n return () => observer.disconnect();\n }, [container, row]);\n\n return labelled;\n}\n\nexport function CollectionTableToolbar({\n actions,\n actionsStart,\n loading,\n onTextSearch,\n title,\n viewModeToggle,\n initialSearchText,\n compact = false\n}: CollectionTableToolbarProps) {\n\n const largeLayout = useLargeLayout();\n const { t } = useTranslation();\n\n const containerRef = useRef<HTMLDivElement>(null);\n const rowRef = useRef<HTMLDivElement>(null);\n const labelled = useLabelsFit(containerRef, rowRef);\n\n // Split actions into \"primary\" (add button = last child) and \"secondary\" (everything else)\n const actionChildren = React.Children.toArray(actions);\n const addButton = actionChildren.length > 0 ? actionChildren[actionChildren.length - 1] : null;\n const secondaryActions = actionChildren.slice(0, -1);\n\n return (\n <div\n ref={containerRef}\n className={cls(\"no-scrollbar min-h-[52px] overflow-x-auto bg-surface-sheet flex w-full\")}>\n\n {/* At least as wide as the toolbar, and never narrower than its\n controls: the two groups cannot be squeezed into each other.\n When even the icon-only controls do not fit, the toolbar\n scrolls. */}\n <div\n ref={rowRef}\n className={\"px-2 md:px-4 flex flex-row justify-between items-center min-w-full w-max\"}>\n\n <ToolbarLabelsContext.Provider value={labelled}>\n\n <div className=\"flex items-center gap-1 md:mr-4 mr-2\">\n\n {/* View toggle — hidden in compact */}\n {!compact && viewModeToggle}\n\n {title && <div className={\"flex items-center\"}>\n {title}\n </div>}\n\n {actionsStart}\n\n </div>\n\n <div className=\"flex items-center gap-1\">\n\n {/* Loading spinner — hidden in compact */}\n {largeLayout && !compact && loading && (\n <div className=\"mr-4\">\n <CircularProgress size={\"smallest\"}/>\n </div>\n )}\n\n {/* Search bar — hidden in compact */}\n {!compact && onTextSearch &&\n <SearchBar\n key={\"search-bar\"}\n size={\"small\"}\n placeholder={t(\"search\")}\n onTextSearch={onTextSearch}\n expandable={true}\n initialValue={initialSearchText}/>}\n\n {/* Secondary actions — always inline */}\n <div className=\"flex items-center gap-1\">\n {secondaryActions}\n </div>\n\n {/* Add button — always visible */}\n {addButton}\n\n </div>\n\n </ToolbarLabelsContext.Provider>\n\n </div>\n\n </div>\n );\n}\n"],"mappings":";;;;;AA4BA,IAAM,uBAAuB,MAAM,cAAc,IAAI;;;;;;;;;;AAWrD,SAAgB,mBAA4B;CACxC,OAAO,WAAW,oBAAoB;AAC1C;;;;;;;AAQA,SAAS,aACL,WACA,KACO;CACP,MAAM,CAAC,UAAU,eAAe,SAAS,IAAI;CAC7C,MAAM,cAAc,OAAO,IAAI;CAC/B,MAAM,gBAAgB,OAA2B,KAAA,CAAS;CAE1D,sBAAsB;EAClB,MAAM,mBAAmB,UAAU;EACnC,MAAM,aAAa,IAAI;EACvB,IAAI,CAAC,oBAAoB,CAAC,cAAc,OAAO,mBAAmB,aAAa,OAAO,KAAA;EAEtF,MAAM,gBAAgB;GAClB,MAAM,YAAY,iBAAiB;GACnC,IAAI,OAAO,YAAY;GACvB,IAAI,YAAY,SAAS;IACrB,MAAM,SAAS,WAAW;IAC1B,IAAI,SAAS,YAAY,GAAG;KACxB,cAAc,UAAU;KACxB,OAAO;IACX;GACJ,OAAO,IAAI,cAAc,YAAY,KAAA,KAAa,aAAa,cAAc,SACzE,OAAO;GAEX,IAAI,SAAS,YAAY,SAAS;IAC9B,YAAY,UAAU;IACtB,YAAY,IAAI;GACpB;EACJ;EAIA,MAAM,WAAW,IAAI,eAAe,OAAO;EAC3C,SAAS,QAAQ,gBAAgB;EACjC,SAAS,QAAQ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
15
  }
16
- interface EntityTableCellProps {
16
+ export interface EntityTableCellProps {
17
17
  children: React.ReactNode;
18
18
  actions?: React.ReactNode;
19
19
  /**
@@ -52,4 +52,3 @@ interface EntityTableCellProps {
52
52
  /** How many cells are being measured right now — for tests. */
53
53
  export declare function measuredTableCellCount(): number;
54
54
  export declare const EntityTableCell: React.FunctionComponent<EntityTableCellProps>;
55
- export {};