@rebasepro/cms 0.30.0 → 0.31.0-canary.g59cd6fd
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.
- package/README.md +8 -8
- package/dist/collection_editor/ConfigControllerProvider.js +25 -22
- package/dist/collection_editor/ConfigControllerProvider.js.map +1 -1
- package/dist/collection_editor/firestore_callee.d.ts +10 -0
- package/dist/collection_editor/firestore_callee.js +15 -0
- package/dist/collection_editor/firestore_callee.js.map +1 -0
- package/dist/collection_editor/firestore_edit.d.ts +62 -0
- package/dist/collection_editor/firestore_edit.js +339 -0
- package/dist/collection_editor/firestore_edit.js.map +1 -0
- package/dist/collection_editor/index.d.ts +2 -3
- package/dist/collection_editor/liveSchemaClient.d.ts +44 -22
- package/dist/collection_editor/liveSchemaClient.js +9 -3
- package/dist/collection_editor/liveSchemaClient.js.map +1 -1
- package/dist/collection_editor/property_column.d.ts +86 -0
- package/dist/collection_editor/property_column.js +719 -0
- package/dist/collection_editor/property_column.js.map +1 -0
- package/dist/collection_editor/serializable_types.d.ts +2 -24
- package/dist/collection_editor/serializable_utils.d.ts +1 -1
- package/dist/collection_editor/serializable_utils.js +2 -1
- package/dist/collection_editor/serializable_utils.js.map +1 -1
- package/dist/collection_editor/split_edit.d.ts +106 -0
- package/dist/collection_editor/split_edit.js +564 -0
- package/dist/collection_editor/split_edit.js.map +1 -0
- package/dist/collection_editor/split_edit_error.d.ts +25 -0
- package/dist/collection_editor/split_edit_error.js +35 -0
- package/dist/collection_editor/split_edit_error.js.map +1 -0
- package/dist/collection_editor/types/collection_editor_controller.d.ts +1 -1
- package/dist/collection_editor/types/config_controller.d.ts +67 -1
- package/dist/collection_editor/ui/collection_editor/CollectionEditorDialog.d.ts +6 -5
- package/dist/collection_editor/ui/collection_editor/CollectionEditorDialog.js +44 -12
- package/dist/collection_editor/ui/collection_editor/CollectionEditorDialog.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/CollectionPropertiesEditorForm.js +18 -3
- package/dist/collection_editor/ui/collection_editor/CollectionPropertiesEditorForm.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/CollectionRLSTab.js +94 -55
- package/dist/collection_editor/ui/collection_editor/CollectionRLSTab.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/CollectionRelationsTab.d.ts +2 -1
- package/dist/collection_editor/ui/collection_editor/DisplaySettingsForm.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/EnumForm.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/EnumForm.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/GeneralSettingsForm.js +3 -3
- package/dist/collection_editor/ui/collection_editor/GeneralSettingsForm.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/KanbanConfigSection.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/PropertyEditView.d.ts +2 -3
- package/dist/collection_editor/ui/collection_editor/PropertyEditView.js +1 -1
- package/dist/collection_editor/ui/collection_editor/PropertyEditView.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/PropertyFieldPreview.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/PropertyFieldPreview.js +1 -1
- package/dist/collection_editor/ui/collection_editor/PropertyFieldPreview.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/PropertyTree.d.ts +7 -4
- package/dist/collection_editor/ui/collection_editor/PropertyTree.js +15 -5
- package/dist/collection_editor/ui/collection_editor/PropertyTree.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +1 -1
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/SchemaEditRefusalView.d.ts +20 -0
- package/dist/collection_editor/ui/collection_editor/SchemaEditRefusalView.js +74 -0
- package/dist/collection_editor/ui/collection_editor/SchemaEditRefusalView.js.map +1 -0
- package/dist/collection_editor/ui/collection_editor/import/CollectionEditorImportDataPreview.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/import/CollectionEditorImportDataPreview.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/import/CollectionEditorImportMapping.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/import/clean_import_data.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/import/clean_import_data.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/BlockPropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/DateTimePropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/EnumPropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/MapPropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/ReferencePropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/RelationPropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/RepeatPropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/conditions/ConditionsEditor.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/conditions/EnumConditionsEditor.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/conditions/property_paths.d.ts +1 -1
- package/dist/collection_editor/ui/collection_editor/rlsRuleForm.d.ts +34 -0
- package/dist/collection_editor/ui/collection_editor/rlsRuleForm.js +50 -0
- package/dist/collection_editor/ui/collection_editor/rlsRuleForm.js.map +1 -0
- package/dist/collection_editor/ui/collection_editor/utils/update_property_for_widget.d.ts +1 -2
- package/dist/collection_editor/ui/collection_editor/utils/update_property_for_widget.js.map +1 -1
- package/dist/collection_editor/useDetachRulesConfirmation.d.ts +16 -0
- package/dist/collection_editor/useDetachRulesConfirmation.js +48 -0
- package/dist/collection_editor/useDetachRulesConfirmation.js.map +1 -0
- package/dist/collection_editor/useLiveSchemaEditing.d.ts +2 -2
- package/dist/collection_editor/useLiveSchemaEditing.js +1 -1
- package/dist/collection_editor/useLiveSchemaEditing.js.map +1 -1
- package/dist/collection_editor/useLocalCollectionsConfigController.d.ts +54 -10
- package/dist/collection_editor/useLocalCollectionsConfigController.js +394 -122
- package/dist/collection_editor/useLocalCollectionsConfigController.js.map +1 -1
- package/dist/collection_editor/validateCollectionJson.js.map +1 -1
- package/dist/components/CollectionPanel.d.ts +10 -9
- package/dist/components/CollectionPanel.js +5 -2
- package/dist/components/CollectionPanel.js.map +1 -1
- package/dist/components/CollectionTableBinding/CollectionRowActions.d.ts +1 -2
- package/dist/components/CollectionTableBinding/CollectionRowActions.js.map +1 -1
- package/dist/components/CollectionTableBinding/CollectionTableBinding.js.map +1 -1
- package/dist/components/CollectionTableBinding/CollectionTableBindingProps.d.ts +3 -5
- package/dist/components/CollectionTableBinding/PropertyTableCell.d.ts +2 -2
- package/dist/components/CollectionTableBinding/PropertyTableCell.js.map +1 -1
- package/dist/components/CollectionTableBinding/column_utils.d.ts +1 -1
- package/dist/components/CollectionTableBinding/column_utils.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableMultipleRelationField.d.ts +2 -2
- package/dist/components/CollectionTableBinding/fields/TableMultipleRelationField.js +1 -2
- package/dist/components/CollectionTableBinding/fields/TableMultipleRelationField.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.d.ts +2 -2
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.js +2 -2
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableRelationField.d.ts +2 -2
- package/dist/components/CollectionTableBinding/fields/TableRelationField.js +1 -2
- package/dist/components/CollectionTableBinding/fields/TableRelationField.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableRelationSelectorField.d.ts +2 -1
- package/dist/components/CollectionTableBinding/fields/TableRelationSelectorField.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.d.ts +2 -2
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/VirtualTableSelect.d.ts +1 -1
- package/dist/components/CollectionTableBinding/fields/VirtualTableSelect.js +1 -1
- package/dist/components/CollectionTableBinding/fields/VirtualTableSelect.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/common.d.ts +1 -2
- package/dist/components/CollectionTableBinding/internal/common.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js +2 -2
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
- package/dist/components/CollectionTableBinding/table_bindings.d.ts +2 -2
- package/dist/components/CollectionTableBinding/table_bindings.js.map +1 -1
- package/dist/components/CollectionViewBinding/BoardCardBinding.d.ts +1 -1
- package/dist/components/CollectionViewBinding/BoardCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionBoardViewBinding.d.ts +1 -2
- package/dist/components/CollectionViewBinding/CollectionBoardViewBinding.js +9 -5
- package/dist/components/CollectionViewBinding/CollectionBoardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.d.ts +1 -2
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionEntityActions.d.ts +1 -1
- package/dist/components/CollectionViewBinding/CollectionEntityActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.d.ts +1 -2
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +1 -1
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionToolbar.js +1 -1
- package/dist/components/CollectionViewBinding/CollectionToolbar.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewActions.js +2 -4
- package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewBinding.d.ts +6 -6
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewContent.js +1 -2
- package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewStartActions.d.ts +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewStartActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CustomViewHost.d.ts +1 -2
- package/dist/components/CollectionViewBinding/CustomViewHost.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntitiesCount.js +3 -3
- package/dist/components/CollectionViewBinding/EntitiesCount.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -2
- package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntityIdHeaderWidget.js +1 -1
- package/dist/components/CollectionViewBinding/EntityIdHeaderWidget.js.map +1 -1
- package/dist/components/CollectionViewBinding/FilterPresetsButton.d.ts +1 -2
- package/dist/components/CollectionViewBinding/FilterPresetsButton.js +1 -1
- package/dist/components/CollectionViewBinding/FilterPresetsButton.js.map +1 -1
- package/dist/components/CollectionViewBinding/FiltersButton.d.ts +1 -2
- package/dist/components/CollectionViewBinding/FiltersButton.js.map +1 -1
- package/dist/components/CollectionViewBinding/FiltersDialog.d.ts +1 -1
- package/dist/components/CollectionViewBinding/FiltersDialog.js.map +1 -1
- package/dist/components/CollectionViewBinding/PluginColumnSlots.d.ts +1 -2
- package/dist/components/CollectionViewBinding/PluginColumnSlots.js.map +1 -1
- package/dist/components/CollectionViewBinding/RowActions.d.ts +1 -2
- package/dist/components/CollectionViewBinding/RowActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/SortButton.d.ts +1 -1
- package/dist/components/CollectionViewBinding/SortButton.js.map +1 -1
- package/dist/components/CollectionViewBinding/SplitListView.d.ts +1 -2
- package/dist/components/CollectionViewBinding/SplitListView.js.map +1 -1
- package/dist/components/CollectionViewBinding/hooks/useCollectionInlineEditor.d.ts +1 -2
- package/dist/components/CollectionViewBinding/hooks/useCollectionInlineEditor.js +1 -1
- package/dist/components/CollectionViewBinding/hooks/useCollectionInlineEditor.js.map +1 -1
- package/dist/components/CollectionViewBinding/hooks/useKanbanDragAndDrop.d.ts +1 -2
- package/dist/components/CollectionViewBinding/hooks/useKanbanDragAndDrop.js.map +1 -1
- package/dist/components/CollectionViewBinding/useBoardDataController.d.ts +2 -1
- package/dist/components/CollectionViewBinding/useBoardDataController.js +3 -3
- package/dist/components/CollectionViewBinding/useBoardDataController.js.map +1 -1
- package/dist/components/CollectionViewBinding/useCollectionViewState.d.ts +2 -4
- package/dist/components/CollectionViewBinding/useCollectionViewState.js +14 -19
- package/dist/components/CollectionViewBinding/useCollectionViewState.js.map +1 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +1 -3
- package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
- package/dist/components/CollectionViewBinding/useSelectionController.d.ts +1 -2
- package/dist/components/CollectionViewBinding/useSelectionController.js.map +1 -1
- package/dist/components/CollectionsProvider.d.ts +23 -8
- package/dist/components/CollectionsProvider.js +23 -7
- package/dist/components/CollectionsProvider.js.map +1 -1
- package/dist/components/DefaultDrawer.js +1 -1
- package/dist/components/DeleteEntityDialog.d.ts +1 -1
- package/dist/components/DeleteEntityDialog.js +1 -1
- package/dist/components/DeleteEntityDialog.js.map +1 -1
- package/dist/components/DetailViewBinding.js +3 -3
- package/dist/components/DetailViewBinding.js.map +1 -1
- package/dist/components/EditFormActions.js.map +1 -1
- package/dist/components/EditViewBinding.d.ts +2 -1
- package/dist/components/EditViewBinding.js +6 -6
- package/dist/components/EditViewBinding.js.map +1 -1
- package/dist/components/EntityDisplayHeader.d.ts +1 -2
- package/dist/components/EntityDisplayHeader.js.map +1 -1
- package/dist/components/EntityInspector.d.ts +1 -2
- package/dist/components/EntityInspector.js.map +1 -1
- package/dist/components/EntityPreviewBinding.d.ts +1 -1
- package/dist/components/EntityPreviewBinding.js +1 -1
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/components/EntityViewBinding.d.ts +1 -1
- package/dist/components/EntityViewBinding.js.map +1 -1
- package/dist/components/EntityViewBody.d.ts +1 -1
- package/dist/components/EntityViewBody.js +3 -4
- package/dist/components/EntityViewBody.js.map +1 -1
- package/dist/components/FieldValue.js +2 -2
- package/dist/components/FieldValue.js.map +1 -1
- package/dist/components/HomePage/ContentHomePage.js +12 -3
- package/dist/components/HomePage/ContentHomePage.js.map +1 -1
- package/dist/components/InlineEntityPreview.d.ts +1 -1
- package/dist/components/InlineEntityPreview.js.map +1 -1
- package/dist/components/PropertyCollectionView.d.ts +2 -2
- package/dist/components/PropertyCollectionView.js.map +1 -1
- package/dist/components/PropertyConfigBadge.js.map +1 -1
- package/dist/components/RebaseCMS.d.ts +22 -3
- package/dist/components/RebaseCMS.js +32 -14
- package/dist/components/RebaseCMS.js.map +1 -1
- package/dist/components/RebaseNavigation.js +106 -31
- package/dist/components/RebaseNavigation.js.map +1 -1
- package/dist/components/RecordDetail.js +4 -1
- package/dist/components/RecordDetail.js.map +1 -1
- package/dist/components/RecordForm.d.ts +5 -5
- package/dist/components/RecordForm.js +5 -2
- package/dist/components/RecordForm.js.map +1 -1
- package/dist/components/ReferenceTable/SelectionTableBinding.d.ts +2 -2
- package/dist/components/ReferenceTable/SelectionTableBinding.js +1 -1
- package/dist/components/ReferenceTable/SelectionTableBinding.js.map +1 -1
- package/dist/components/ReferenceWidget.d.ts +2 -1
- package/dist/components/ReferenceWidget.js +2 -2
- package/dist/components/ReferenceWidget.js.map +1 -1
- package/dist/components/RelationSelector.d.ts +2 -1
- package/dist/components/RelationSelector.js +2 -3
- package/dist/components/RelationSelector.js.map +1 -1
- package/dist/components/SelectableTable/SelectableTable.d.ts +2 -2
- package/dist/components/SelectableTable/SelectableTable.js.map +1 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +2 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js +3 -3
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
- package/dist/components/SelectableTable/filters/ReferenceFilterField.js +2 -2
- package/dist/components/SelectableTable/filters/ReferenceFilterField.js.map +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.js +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
- package/dist/components/SelectableTable/filters/StringNumberFilterField.d.ts +1 -1
- package/dist/components/SelectableTable/filters/StringNumberFilterField.js.map +1 -1
- package/dist/components/SelectableTable/filters/null_filter.d.ts +1 -3
- package/dist/components/SelectableTable/filters/null_filter.js.map +1 -1
- package/dist/components/SidePanelBinding.js +1 -1
- package/dist/components/SidePanelBinding.js.map +1 -1
- package/dist/components/field_configs.d.ts +1 -2
- package/dist/components/field_configs.js.map +1 -1
- package/dist/components/field_ids.d.ts +1 -1
- package/dist/components/field_ids.js +1 -1
- package/dist/components/field_ids.js.map +1 -1
- package/dist/components/history/EntityHistoryEntry.js.map +1 -1
- package/dist/components/history/EntityHistoryView.d.ts +1 -2
- package/dist/components/history/EntityHistoryView.js +1 -1
- package/dist/components/history/EntityHistoryView.js.map +1 -1
- package/dist/data_export/export/BasicExportAction.d.ts +1 -1
- package/dist/data_export/export/BasicExportAction.js.map +1 -1
- package/dist/data_export/export/ExportCollectionAction.js +2 -2
- package/dist/data_export/export/ExportCollectionAction.js.map +1 -1
- package/dist/data_export/export/additional_fields.d.ts +1 -1
- package/dist/data_export/export/additional_fields.js.map +1 -1
- package/dist/data_export/export/export.d.ts +1 -1
- package/dist/data_export/export/export.js +1 -1
- package/dist/data_export/export/export.js.map +1 -1
- package/dist/data_export/export/fetch_export_data.d.ts +3 -2
- package/dist/data_export/export/fetch_export_data.js.map +1 -1
- package/dist/data_import/components/DataNewPropertiesMapping.d.ts +1 -1
- package/dist/data_import/components/DataNewPropertiesMapping.js.map +1 -1
- package/dist/data_import/components/ImportNewPropertyFieldPreview.d.ts +1 -1
- package/dist/data_import/components/ImportNewPropertyFieldPreview.js.map +1 -1
- package/dist/data_import/hooks/useImportConfig.js.map +1 -1
- package/dist/data_import/import/ImportCollectionAction.d.ts +2 -2
- package/dist/data_import/import/ImportCollectionAction.js.map +1 -1
- package/dist/data_import/types/column_mapping.d.ts +1 -1
- package/dist/data_import/utils/data.d.ts +1 -2
- package/dist/data_import/utils/data.js +1 -2
- package/dist/data_import/utils/data.js.map +1 -1
- package/dist/data_import/utils/get_import_inference_type.d.ts +1 -1
- package/dist/data_import/utils/get_import_inference_type.js.map +1 -1
- package/dist/data_import/utils/id_column.d.ts +1 -1
- package/dist/data_import/utils/id_column.js.map +1 -1
- package/dist/data_import/utils/import_columns.d.ts +1 -1
- package/dist/data_import/utils/import_columns.js.map +1 -1
- package/dist/data_import/utils/save_entities.d.ts +3 -3
- package/dist/data_import/utils/save_entities.js +1 -1
- package/dist/data_import/utils/save_entities.js.map +1 -1
- package/dist/form/EntityForm.js +2 -1
- package/dist/form/EntityForm.js.map +1 -1
- package/dist/form/EntityFormActions.js.map +1 -1
- package/dist/form/EntityFormBinding.js +2 -2
- package/dist/form/EntityFormBinding.js.map +1 -1
- package/dist/form/FormFieldsContext.d.ts +1 -4
- package/dist/form/FormFieldsContext.js +1 -1
- package/dist/form/FormFieldsContext.js.map +1 -1
- package/dist/form/PropertyFieldBinding.js +6 -8
- package/dist/form/PropertyFieldBinding.js.map +1 -1
- package/dist/form/components/FieldBlock.d.ts +1 -2
- package/dist/form/components/FieldBlock.js.map +1 -1
- package/dist/form/components/FieldHelperText.d.ts +1 -1
- package/dist/form/components/FieldHelperText.js.map +1 -1
- package/dist/form/components/FormRail.d.ts +1 -1
- package/dist/form/components/FormRail.js.map +1 -1
- package/dist/form/components/LocalChangesMenu.d.ts +1 -1
- package/dist/form/components/LocalChangesMenu.js.map +1 -1
- package/dist/form/components/StorageItemPreview.d.ts +1 -1
- package/dist/form/components/StorageItemPreview.js.map +1 -1
- package/dist/form/field_bindings/ArrayCustomShapedFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/ArrayCustomShapedFieldBinding.js +1 -1
- package/dist/form/field_bindings/ArrayCustomShapedFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ArrayOfReferencesFieldBinding.d.ts +2 -2
- package/dist/form/field_bindings/ArrayOfReferencesFieldBinding.js +2 -2
- package/dist/form/field_bindings/ArrayOfReferencesFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/BinaryFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/BlockFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/BlockFieldBinding.js +1 -1
- package/dist/form/field_bindings/BlockFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/DateTimeFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/DateTimeFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/GeopointFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/KeyValueFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/KeyValueFieldBinding.js +1 -2
- package/dist/form/field_bindings/KeyValueFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/MapFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/MapFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/MarkdownEditorFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/MarkdownEditorFieldBinding.js +1 -1
- package/dist/form/field_bindings/MarkdownEditorFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/MultiSelectFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/MultiSelectFieldBinding.js +1 -1
- package/dist/form/field_bindings/MultiSelectFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/MultipleRelationFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/MultipleRelationFieldBinding.js +2 -2
- package/dist/form/field_bindings/MultipleRelationFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ReferenceFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/ReferenceFieldBinding.js +2 -2
- package/dist/form/field_bindings/ReferenceFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/RelationFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/RelationFieldBinding.js +2 -2
- package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/RepeatFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/RepeatFieldBinding.js +1 -1
- package/dist/form/field_bindings/RepeatFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/SelectFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/SelectFieldBinding.js +1 -1
- package/dist/form/field_bindings/SelectFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/StorageUploadFieldBinding.d.ts +2 -2
- package/dist/form/field_bindings/StorageUploadFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/SwitchFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/SwitchFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/TextFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/UserSelectFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/UserSelectFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/VectorFieldBinding.d.ts +1 -1
- package/dist/form/field_bindings/VectorFieldBinding.js.map +1 -1
- package/dist/form/form_utils.d.ts +3 -3
- package/dist/form/form_utils.js +1 -2
- package/dist/form/form_utils.js.map +1 -1
- package/dist/form/label_placement.d.ts +1 -2
- package/dist/form/label_placement.js.map +1 -1
- package/dist/form/resolve_cell_property.d.ts +1 -2
- package/dist/form/resolve_cell_property.js +1 -1
- package/dist/form/resolve_cell_property.js.map +1 -1
- package/dist/form/resolve_form_properties.d.ts +2 -2
- package/dist/form/resolve_form_properties.js +1 -1
- package/dist/form/resolve_form_properties.js.map +1 -1
- package/dist/form/useClearRestoreValue.d.ts +1 -1
- package/dist/form/useClearRestoreValue.js.map +1 -1
- package/dist/form/validation.d.ts +2 -2
- package/dist/form/validation.js +1 -1
- package/dist/form/validation.js.map +1 -1
- package/dist/hooks/navigation/compose_collections.d.ts +59 -0
- package/dist/hooks/navigation/compose_collections.js +48 -0
- package/dist/hooks/navigation/compose_collections.js.map +1 -0
- package/dist/hooks/navigation/compose_collections_input.d.ts +8 -0
- package/dist/hooks/navigation/compose_collections_input.js +17 -0
- package/dist/hooks/navigation/compose_collections_input.js.map +1 -0
- package/dist/hooks/navigation/contexts/CollectionRegistryContext.d.ts +1 -1
- package/dist/hooks/navigation/contexts/CollectionRegistryContext.js.map +1 -1
- package/dist/hooks/navigation/registered_collection.d.ts +15 -0
- package/dist/hooks/navigation/registered_collection.js +20 -0
- package/dist/hooks/navigation/registered_collection.js.map +1 -0
- package/dist/hooks/navigation/ui_preferences.d.ts +47 -0
- package/dist/hooks/navigation/ui_preferences.js +179 -0
- package/dist/hooks/navigation/ui_preferences.js.map +1 -0
- package/dist/hooks/navigation/useAsyncResolver.d.ts +8 -1
- package/dist/hooks/navigation/useAsyncResolver.js +9 -3
- package/dist/hooks/navigation/useAsyncResolver.js.map +1 -1
- package/dist/hooks/navigation/useBuildCollectionRegistryController.d.ts +1 -3
- package/dist/hooks/navigation/useBuildCollectionRegistryController.js +3 -3
- package/dist/hooks/navigation/useBuildCollectionRegistryController.js.map +1 -1
- package/dist/hooks/navigation/useBuildNavigationStateController.d.ts +9 -5
- package/dist/hooks/navigation/useBuildNavigationStateController.js +2 -1
- package/dist/hooks/navigation/useBuildNavigationStateController.js.map +1 -1
- package/dist/hooks/navigation/useBuildUrlController.d.ts +1 -1
- package/dist/hooks/navigation/useBuildUrlController.js.map +1 -1
- package/dist/hooks/navigation/useNavigationResolution.js +1 -2
- package/dist/hooks/navigation/useNavigationResolution.js.map +1 -1
- package/dist/hooks/navigation/usePanelTables.d.ts +11 -0
- package/dist/hooks/navigation/usePanelTables.js +33 -0
- package/dist/hooks/navigation/usePanelTables.js.map +1 -0
- package/dist/hooks/navigation/useResolvedCollections.d.ts +8 -3
- package/dist/hooks/navigation/useResolvedCollections.js +3 -2
- package/dist/hooks/navigation/useResolvedCollections.js.map +1 -1
- package/dist/hooks/navigation/useResolvedViews.d.ts +1 -2
- package/dist/hooks/navigation/useResolvedViews.js.map +1 -1
- package/dist/hooks/navigation/useTopLevelNavigation.d.ts +1 -2
- package/dist/hooks/navigation/useTopLevelNavigation.js.map +1 -1
- package/dist/hooks/navigation/user_preferences_overlay.d.ts +21 -0
- package/dist/hooks/navigation/user_preferences_overlay.js +101 -0
- package/dist/hooks/navigation/user_preferences_overlay.js.map +1 -0
- package/dist/hooks/navigation/utils.js +1 -1
- package/dist/hooks/navigation/utils.js.map +1 -1
- package/dist/hooks/useAdminContext.d.ts +1 -2
- package/dist/hooks/useAdminContext.js.map +1 -1
- package/dist/hooks/useBuildSidePanel.d.ts +1 -2
- package/dist/hooks/useBuildSidePanel.js +2 -1
- package/dist/hooks/useBuildSidePanel.js.map +1 -1
- package/dist/hooks/useChildViewSource.d.ts +1 -1
- package/dist/hooks/useChildViewSource.js +1 -1
- package/dist/hooks/useChildViewSource.js.map +1 -1
- package/dist/hooks/useEntityDisplay.d.ts +1 -2
- package/dist/hooks/useEntityDisplay.js +1 -1
- package/dist/hooks/useEntityDisplay.js.map +1 -1
- package/dist/hooks/useEntityDisplayTitle.d.ts +2 -2
- package/dist/hooks/useEntityDisplayTitle.js.map +1 -1
- package/dist/hooks/useHistory.js +1 -1
- package/dist/hooks/useHistory.js.map +1 -1
- package/dist/hooks/useRecordActions.d.ts +1 -2
- package/dist/hooks/useRecordActions.js.map +1 -1
- package/dist/hooks/useReferencePaths.d.ts +21 -7
- package/dist/hooks/useReferencePaths.js +23 -6
- package/dist/hooks/useReferencePaths.js.map +1 -1
- package/dist/hooks/useResolvedNavigationFrom.d.ts +3 -3
- package/dist/hooks/useResolvedNavigationFrom.js +1 -1
- package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.js +8 -2
- package/dist/mcp_view/app_modules.d.ts +2 -2
- package/dist/mcp_view/app_modules.js +4 -4
- package/dist/mcp_view/app_modules.js.map +1 -1
- package/dist/mcp_view/index.d.ts +16 -19
- package/dist/mcp_view/index.js +43 -62
- package/dist/mcp_view/index.js.map +1 -1
- package/dist/mcp_view/payload.d.ts +54 -18
- package/dist/mcp_view/payload.js +49 -24
- package/dist/mcp_view/payload.js.map +1 -1
- package/dist/mcp_view/screen.js +11 -11
- package/dist/mcp_view/screen.js.map +1 -1
- package/dist/mcp_view/tool_driver.d.ts +5 -34
- package/dist/mcp_view/tool_driver.js +17 -16
- package/dist/mcp_view/tool_driver.js.map +1 -1
- package/dist/mcp_view/write_review.d.ts +1 -2
- package/dist/mcp_view/write_review.js +1 -1
- package/dist/mcp_view/write_review.js.map +1 -1
- package/dist/preview/PropertyPreview.d.ts +1 -1
- package/dist/preview/PropertyPreview.js +4 -3
- package/dist/preview/PropertyPreview.js.map +1 -1
- package/dist/preview/components/ArrayEnumPreview.d.ts +1 -1
- package/dist/preview/components/ArrayEnumPreview.js.map +1 -1
- package/dist/preview/components/BooleanPreview.d.ts +1 -1
- package/dist/preview/components/BooleanPreview.js.map +1 -1
- package/dist/preview/components/EnumValuesChip.d.ts +1 -1
- package/dist/preview/components/EnumValuesChip.js +1 -1
- package/dist/preview/components/EnumValuesChip.js.map +1 -1
- package/dist/preview/components/ReferencePreview.d.ts +1 -1
- package/dist/preview/components/ReferencePreview.js.map +1 -1
- package/dist/preview/components/RelationPreview.d.ts +1 -1
- package/dist/preview/components/RelationPreview.js.map +1 -1
- package/dist/preview/components/StorageThumbnail.js +2 -1
- package/dist/preview/components/StorageThumbnail.js.map +1 -1
- package/dist/preview/components/UserPreview.d.ts +1 -1
- package/dist/preview/components/UserPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayOfMapsPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayOfMapsPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayOfReferencesPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayOfReferencesPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayOfRelationsPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayOfRelationsPreview.js +2 -1
- package/dist/preview/property_previews/ArrayOfRelationsPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayOfStorageComponentsPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayOfStorageComponentsPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayOfStringsPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayOfStringsPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayOneOfPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayOneOfPreview.js +1 -1
- package/dist/preview/property_previews/ArrayOneOfPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayPropertyEnumPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayPropertyEnumPreview.js +1 -1
- package/dist/preview/property_previews/ArrayPropertyEnumPreview.js.map +1 -1
- package/dist/preview/property_previews/ArrayPropertyPreview.d.ts +1 -1
- package/dist/preview/property_previews/ArrayPropertyPreview.js +1 -1
- package/dist/preview/property_previews/ArrayPropertyPreview.js.map +1 -1
- package/dist/preview/property_previews/MapPropertyPreview.d.ts +1 -1
- package/dist/preview/property_previews/MapPropertyPreview.js.map +1 -1
- package/dist/preview/property_previews/NumberPropertyPreview.d.ts +1 -1
- package/dist/preview/property_previews/NumberPropertyPreview.js +1 -1
- package/dist/preview/property_previews/NumberPropertyPreview.js.map +1 -1
- package/dist/preview/property_previews/SkeletonPropertyComponent.d.ts +1 -1
- package/dist/preview/property_previews/SkeletonPropertyComponent.js.map +1 -1
- package/dist/preview/property_previews/StringPropertyPreview.d.ts +1 -1
- package/dist/preview/property_previews/StringPropertyPreview.js.map +1 -1
- package/dist/preview/util.d.ts +1 -1
- package/dist/preview/util.js.map +1 -1
- package/dist/routes/RebaseRoute.js +2 -2
- package/dist/routes/RebaseRoute.js.map +1 -1
- package/dist/saved_apps/SavedAppsView.d.ts +1 -1
- package/dist/saved_apps/SavedAppsView.js +1 -1
- package/dist/saved_apps/SavedAppsView.js.map +1 -1
- package/dist/selection/SelectionMenu.d.ts +1 -1
- package/dist/selection/SelectionMenu.js.map +1 -1
- package/dist/selection/resolve_selection.d.ts +3 -3
- package/dist/selection/resolve_selection.js +3 -2
- package/dist/selection/resolve_selection.js.map +1 -1
- package/dist/tables/apply_customization.d.ts +65 -0
- package/dist/tables/apply_customization.js +644 -0
- package/dist/tables/apply_customization.js.map +1 -0
- package/dist/tables/column_property.d.ts +64 -0
- package/dist/tables/column_property.js +549 -0
- package/dist/tables/column_property.js.map +1 -0
- package/dist/tables/customize_table.d.ts +39 -0
- package/dist/tables/customize_table.js +247 -0
- package/dist/tables/customize_table.js.map +1 -0
- package/dist/tables/index.d.ts +12 -0
- package/dist/tables/labels.d.ts +18 -0
- package/dist/tables/labels.js +18 -0
- package/dist/tables/labels.js.map +1 -0
- package/dist/tables/project_table.d.ts +79 -0
- package/dist/tables/project_table.js +148 -0
- package/dist/tables/project_table.js.map +1 -0
- package/dist/tables/relations.d.ts +47 -0
- package/dist/tables/relations.js +112 -0
- package/dist/tables/relations.js.map +1 -0
- package/dist/tables/rls.d.ts +39 -0
- package/dist/tables/rls.js +111 -0
- package/dist/tables/rls.js.map +1 -0
- package/dist/tables/update_record.d.ts +32 -0
- package/dist/tables/update_record.js +40 -0
- package/dist/tables/update_record.js.map +1 -0
- package/dist/types/components/EntityFormActionsProps.d.ts +1 -1
- package/dist/types/components/PropertyPreviewProps.d.ts +2 -2
- package/dist/types/fields.d.ts +2 -2
- package/dist/util/dataControllerAdapter.js.map +1 -1
- package/dist/util/entity_pages.d.ts +2 -1
- package/dist/util/entity_pages.js.map +1 -1
- package/dist/util/find_entities_by_ids.d.ts +2 -2
- package/dist/util/find_entities_by_ids.js +1 -1
- package/dist/util/find_entities_by_ids.js.map +1 -1
- package/dist/util/format_collection_date.d.ts +1 -1
- package/dist/util/format_collection_date.js.map +1 -1
- package/dist/util/identity.d.ts +8 -0
- package/dist/util/identity.js +16 -0
- package/dist/util/identity.js.map +1 -0
- package/dist/util/navigation_utils.js +1 -1
- package/dist/util/navigation_utils.js.map +1 -1
- package/dist/util/previews.js +1 -1
- package/dist/util/previews.js.map +1 -1
- package/dist/util/propertyConfigMapper.d.ts +1 -1
- package/dist/util/propertyConfigMapper.js.map +1 -1
- package/dist/util/property_utils.d.ts +1 -3
- package/dist/util/property_utils.js +1 -1
- package/dist/util/property_utils.js.map +1 -1
- package/dist/util/relations.d.ts +18 -0
- package/dist/util/relations.js +32 -0
- package/dist/util/relations.js.map +1 -0
- package/package.json +12 -10
- package/recipes/README.md +4 -4
- package/recipes/my-preferences.tsx +34 -26
- package/recipes/site-settings.tsx +34 -27
- package/dist/collection_editor/collection_wire.d.ts +0 -13
- package/dist/collection_editor/collection_wire.js +0 -49
- package/dist/collection_editor/collection_wire.js.map +0 -1
- package/dist/collection_editor/useJsonCollectionsConfigController.d.ts +0 -37
- package/dist/collection_editor/useJsonCollectionsConfigController.js +0 -191
- package/dist/collection_editor/useJsonCollectionsConfigController.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useLocalCollectionsConfigController.js","names":[],"sources":["../../src/collection_editor/useLocalCollectionsConfigController.tsx"],"sourcesContent":["import { CollectionsConfigController, SaveCollectionParams, UpdateCollectionParams, DeleteCollectionParams, SavePropertyParams, DeletePropertyParams, UpdatePropertiesOrderParams } from \"./types/config_controller\";\nimport { diffCollections, type CollectionPatch } from \"@rebasepro/types\";\nimport { getSubcollections } from \"@rebasepro/common\";\n\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\nimport { DEFAULT_API_PATH } from \"@rebasepro/app\";\nimport { useLiveSchemaEditing } from \"./useLiveSchemaEditing\";\nimport { collectionForWire } from \"./collection_wire\";\n\n/**\n * What the backend said about its schema editor, and how sure we are.\n *\n * `unknown` covers both \"still asking\" and \"could not ask\" — a backend too old\n * to have the endpoint, or one that is unreachable. Those fall back to the\n * build-mode guess below rather than locking the editor for someone whose\n * editor used to work.\n */\ntype SchemaEditorAvailability =\n | { state: \"unknown\" }\n | { state: \"known\", enabled: boolean, reason?: string };\n\n/**\n * The guess this hook used to make on its own.\n *\n * `process.env.NODE_ENV` here is the *frontend bundle's* build mode. Whether\n * the schema editor exists is decided by a different process entirely — the\n * server's own `NODE_ENV`, its `collectionsDir`, whether its collections were\n * introspected, whether `ts-morph` is installed. The two disagree in every\n * ordinary setup: a dev frontend against a deployed API, a `baas` project, a\n * hosted console. When they did, the editor offered itself and every save came\n * back `404 Not Found`. It is kept only as the answer for a backend too old to\n * be asked.\n */\nconst buildModeGuess = (): boolean => process.env.NODE_ENV === \"production\";\n\nexport function useLocalCollectionsConfigController(\n clientOrUrl: any,\n baseCollections: AdminCollection[] = [],\n options?: {\n readOnly?: boolean;\n getAuthToken?: () => Promise<string | null>;\n /**\n * Identity of the signed-in user, if any.\n *\n * Only used to re-ask the backend when it changes: whether the editor\n * will accept a write depends on who is asking, and the answer to an\n * anonymous probe does not survive a sign-in.\n */\n authKey?: string | null;\n /**\n * Whether the signed-in user holds `schema:read`, which both\n * status routes require. `false` asks neither and leaves the editor\n * read-only, because a 403 is the only answer such a user can get.\n * Absent means ask.\n */\n mayReadSchema?: boolean;\n }\n): CollectionsConfigController {\n\n const parsedCollections = baseCollections;\n\n // Store latest options in a ref to prevent stale closures in the `request` function\n // due to useMemo caching the saveCollection function.\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n // `/api` only by default — a backend configured with another `basePath`\n // mounts the schema editor under that instead.\n const clientBaseUrl = typeof clientOrUrl === \"string\"\n ? clientOrUrl\n : (clientOrUrl?.baseUrl ?? \"\");\n const clientApiPath = (typeof clientOrUrl === \"object\" && clientOrUrl !== null && clientOrUrl.apiPath)\n || DEFAULT_API_PATH;\n const editorUrl = `${String(clientBaseUrl).replace(/\\/$/, \"\")}${clientApiPath}/admin/schema-editor`;\n\n const resolveToken = async (): Promise<string | null> => {\n let token = optionsRef.current?.getAuthToken ? await optionsRef.current.getAuthToken() : null;\n if (!token && typeof clientOrUrl === \"object\" && clientOrUrl !== null && clientOrUrl.resolveToken) {\n token = await clientOrUrl.resolveToken();\n }\n return token ?? null;\n };\n\n const request = async (endpoint: string, payload: Record<string, unknown>) => {\n try {\n const token = await resolveToken();\n\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (token) {\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const response = await fetch(`${editorUrl}${endpoint}`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(payload)\n });\n if (!response.ok) {\n const text = await response.text();\n let err: Record<string, unknown> = {};\n try {\n err = JSON.parse(text);\n } catch (e) {\n // ignore json parse error\n }\n\n if (Object.keys(err).length === 0) {\n err = { message: text };\n }\n console.error(\"dev server error payload:\", err);\n const errObj = err.error as Record<string, unknown> | string | undefined;\n const errMessage = typeof errObj === \"object\" && errObj !== null\n ? (errObj.message as string)\n : (typeof errObj === \"string\" ? errObj : (err.message as string | undefined));\n throw new Error(errMessage || \"Error communicating with local dev server\");\n }\n } catch (e) {\n console.error(\"fetch request failed\", e);\n throw e;\n }\n };\n\n // ── Ask the backend whether it will accept an edit ────────────────\n const noSchemaAccess = options?.mayReadSchema === false;\n const forcedReadOnly = noSchemaAccess ? true : options?.readOnly;\n const authKey = options?.authKey ?? null;\n const [availability, setAvailability] = useState<SchemaEditorAvailability>({ state: \"unknown\" });\n\n useEffect(() => {\n // Nothing to ask about: the caller has already decided.\n if (forcedReadOnly === true) return;\n\n let cancelled = false;\n (async () => {\n try {\n const token = await resolveToken();\n const response = await fetch(`${editorUrl}/status`, {\n headers: token ? { Authorization: `Bearer ${token}` } : {}\n });\n if (cancelled) return;\n\n // A backend from before the endpoint existed. Guessing from the\n // bundle's build mode is wrong, but it is what that backend's\n // admin panel has always done, and locking the editor for\n // someone whose editor works would be worse.\n if (response.status === 404) {\n setAvailability({ state: \"unknown\" });\n return;\n }\n\n const body = await response.json().catch(() => ({})) as {\n enabled?: boolean,\n reason?: string,\n error?: { message?: string }\n };\n if (cancelled) return;\n\n if (response.ok) {\n setAvailability({\n state: \"known\",\n enabled: body.enabled === true,\n reason: body.reason\n });\n } else {\n // 401/403 (not an admin) or 501 (no auth configured at all)\n // — all of them mean this session cannot edit collections,\n // and the body says why better than we could.\n setAvailability({\n state: \"known\",\n enabled: false,\n reason: body.error?.message\n ?? `The backend refused to say whether collections are editable (HTTP ${response.status}).`\n });\n }\n } catch {\n if (!cancelled) setAvailability({ state: \"unknown\" });\n }\n })();\n\n return () => { cancelled = true; };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [editorUrl, forcedReadOnly, authKey]);\n\n // ── Live schema editing ───────────────────────────────────────────\n // The same edit, against a backend that can also change the database and\n // commit the result. When it is available, a save is planned and shown\n // before anything happens; when it is not, this is inert and writes go\n // straight to the source-only editor exactly as before.\n const liveSchema = useLiveSchemaEditing({\n baseUrl: `${String(clientBaseUrl).replace(/\\/$/, \"\")}${clientApiPath}/admin/schema`,\n getAuthToken: resolveToken,\n authKey,\n // A read-only editor writes nothing, so there is nothing to ask.\n enabled: forcedReadOnly !== true\n });\n\n /**\n * Perform a write, through the live editor when there is one.\n *\n * `sourceOnly` is the write this controller has always done. It stays the\n * whole behaviour on a backend that cannot edit its schema — a bundle\n * deployment, a non-Postgres driver, a version too old to be asked — so\n * nothing about the editor depends on the feature being there.\n */\n const write = async (\n collectionId: string,\n change: { collection: Record<string, unknown> } | { patch: CollectionPatch }\n ): Promise<void> => {\n // Nothing changed: nothing to plan, commit or write.\n if (\"patch\" in change && change.patch.length === 0) return;\n // `ready()`, not `status` — the rendered status is undefined for one\n // round trip after mount, so reading it here would send a save issued\n // in that window down the source-only path with no confirmation, while\n // the same save a second later would open a dialog. One round trip is\n // cheap; behaviour that depends on how fast somebody clicked is not.\n const available = await liveSchema.ready();\n const proposed = { collectionId, ...change };\n if (!available.enabled) {\n await request(\"/collection/save\", \"patch\" in change\n ? { collectionId, patch: change.patch }\n : { collectionId, collectionData: change.collection });\n return;\n }\n await liveSchema.reviewChange(proposed);\n };\n\n // Live schema editing, when it is on, is where every write goes (`write`\n // above), so the source-only editor's answer does not lock the editor\n // then. That is the case of a bundle with `REBASE_LIVE_SCHEMA_REPOSITORY`:\n // it has no source of its own, so its source-only editor is off, and its\n // writes are committed to the repository instead.\n const liveEditing = liveSchema.status?.enabled === true;\n const readOnly = forcedReadOnly\n ?? (liveEditing ? false : availability.state === \"known\" ? !availability.enabled : buildModeGuess());\n\n // No reason of our own for a user without schema access. Each surface\n // has a generic \"editing is disabled\" for that, and the user's scopes may\n // still be loading, so a specific reason could be wrong.\n const readOnlyReason = noSchemaAccess || liveEditing\n ? undefined\n : availability.state === \"known\" && availability.reason\n ? availability.reason\n : \"Collections can only be edited against a backend running the schema editor, which is off in production.\";\n\n const findCollection = (id: string): AdminCollection | undefined =>\n parsedCollections.find(c => (c as AdminCollection & { id?: string }).id === id || c.slug === id);\n\n /**\n * What to send for a collection that should end up as `saving`.\n *\n * For one that exists: the difference from `loaded` — what the person\n * changed — and nothing else. Both sides are the same view model, through\n * JSON, so whatever JSON cannot carry (a handler, a shared property, an\n * imported enum) is absent from both and never appears as a change; the\n * server writes only the keys the patch names. A collection this does not\n * recognise is a new one — a duplicate among them — and is sent whole,\n * with each relation's target as its slug (see `collectionForWire`).\n */\n const changeFor = (\n id: string,\n saving: Record<string, unknown>,\n loaded?: Record<string, unknown>\n ): { collection: Record<string, unknown> } | { patch: CollectionPatch } => {\n const current = loaded ?? findCollection(id) as Record<string, unknown> | undefined;\n return current\n ? { patch: diffCollections(current, saving) }\n : { collection: collectionForWire(saving) };\n };\n\n /** `findCollection`, as the record a patch is computed from. */\n const currentOf = (id: string): Record<string, unknown> =>\n (findCollection(id) as Record<string, unknown> | undefined) ?? {};\n\n return useMemo(() => ({\n loading: false,\n readOnly,\n readOnlyReason,\n collections: parsedCollections,\n dialog: liveSchema.dialog,\n getCollection: (id: string) => {\n const found = findCollection(id);\n if (found) return found;\n throw Error(`Collection ${id} not found in local mode`);\n },\n\n saveCollection: async ({ id, collectionData, baseline }: SaveCollectionParams) => {\n await write(id, changeFor(\n id,\n collectionData as Record<string, unknown>,\n baseline as Record<string, unknown> | undefined\n ));\n },\n // `collectionData` is a partial: the keys it names, set over the\n // collection as it is.\n updateCollection: async ({ id, collectionData }: UpdateCollectionParams) => {\n const current = findCollection(id) as Record<string, unknown> | undefined;\n await write(id, current\n ? { patch: diffCollections(current, { ...current, ...(collectionData as Record<string, unknown>) }) }\n : { collection: collectionForWire(collectionData as Record<string, unknown>) });\n },\n // Through the live door when there is one: planned (the table and its\n // rows stay, and the plan says so) and committed source-only, with the\n // collection's entry in `index.ts` removed alongside the file. It used\n // to unlink the file and nothing else, which stopped the project from\n // loading its collections and was never committed.\n deleteCollection: async ({ id }: DeleteCollectionParams) => {\n const available = await liveSchema.ready();\n if (!available.enabled) {\n await request(\"/collection/delete\", { collectionId: id });\n return;\n }\n await liveSchema.reviewChange({ collectionId: id, remove: true });\n },\n\n // Every write below is the difference between the collection as it is\n // and as it should end up, through the same door as the editor's own\n // save: planned and confirmed when live editing is on, written as a\n // patch when it is not.\n saveProperty: async ({ path, propertyKey, property, newPropertiesOrder }: SavePropertyParams) => {\n const current = currentOf(path);\n await write(path, { patch: diffCollections(current, {\n ...current,\n properties: { ...(current.properties as Record<string, unknown> | undefined ?? {}), [propertyKey]: property },\n ...(newPropertiesOrder ? { propertiesOrder: newPropertiesOrder } : {})\n }) });\n },\n deleteProperty: async ({ path, propertyKey, newPropertiesOrder }: DeletePropertyParams) => {\n const current = currentOf(path);\n const { [propertyKey]: _removed, ...properties } = (current.properties as Record<string, unknown> | undefined) ?? {};\n await write(path, { patch: diffCollections(current, {\n ...current,\n properties,\n ...(newPropertiesOrder ? { propertiesOrder: newPropertiesOrder } : {})\n }) });\n },\n\n updatePropertiesOrder: async ({ collection, fullPath, newPropertiesOrder }: UpdatePropertiesOrderParams) => {\n const collectionId = (collection as AdminCollection & { id?: string }).id || fullPath.split(\"/\").pop() || \"\";\n const current = currentOf(collectionId);\n await write(collectionId, { patch: diffCollections(current, { ...current, propertiesOrder: newPropertiesOrder }) });\n },\n updateKanbanColumnsOrder: async () => {\n // Kanban order mapping logic can be added later if needed natively.\n },\n\n navigationEntries: [],\n saveNavigationEntries: async () => { }\n // `liveSchema.dialog` and `liveSchema.status` both change as the flow\n // runs — a plan arrives, a dialog opens — and a controller memoised\n // without them would keep handing back a closed dialog and a stale\n // answer about whether the backend can edit its schema at all.\n //\n // `write`, `request`, `findCollection`, `changeFor` and `currentOf` are\n // rebuilt on every render, so listing them would defeat the memo\n // entirely. Each is already covered *transitively* by what is listed:\n // `request` closes over `editorUrl` and a ref, and `editorUrl` derives\n // from `clientOrUrl`; `findCollection`, `changeFor` and `currentOf` close over\n // `parsedCollections`; `write` closes over `liveSchema.status` and\n // `liveSchema.reviewChange`, and the latter is a `useCallback` keyed on\n // a client built from `clientOrUrl`. Every input that can change is in\n // the array under the name it actually varies with.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }), [\n clientOrUrl,\n parsedCollections,\n readOnly,\n readOnlyReason,\n options?.getAuthToken,\n liveSchema.dialog,\n liveSchema.status\n ]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkCA,IAAM,uBAAA,QAAA,IAAA,aAAyD;AAE/D,SAAgB,oCACZ,aACA,kBAAqC,CAAC,GACtC,SAmB2B;CAE3B,MAAM,oBAAoB;CAI1B,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CAIrB,MAAM,gBAAgB,OAAO,gBAAgB,WACvC,cACC,aAAa,WAAW;CAC/B,MAAM,gB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_editor/useLocalCollectionsConfigController.tsx"],"sourcesContent":["import {\n CollectionsConfigController,\n SaveCollectionParams,\n UpdateCollectionParams,\n DeleteCollectionParams,\n SavePropertyParams,\n DeletePropertyParams,\n UpdatePropertiesOrderParams,\n UpdateKanbanColumnsOrderParams,\n TableSourceInfo\n} from \"./types/config_controller\";\nimport type { TableDescriptor, TablePatch, UiTablePreferences, UnmappedTable } from \"@rebasepro/types\";\n\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AdminCollection, AdminPostgresCollection, EnumValues, FirebaseProperty, PostgresProperty, Property } from \"@rebasepro/cms-types\";\nimport { DEFAULT_API_PATH } from \"@rebasepro/app\";\nimport { useLiveSchemaEditing } from \"./useLiveSchemaEditing\";\nimport { LiveSchemaError, type SchemaEditProblem } from \"./liveSchemaClient\";\nimport type { SplitEdit } from \"./split_edit\";\nimport { SplitEditError } from \"./split_edit_error\";\nimport { useDetachRulesConfirmation } from \"./useDetachRulesConfirmation\";\nimport { FIRESTORE_COLLECTION_CALLEE } from \"./firestore_callee\";\n\n/**\n * What the backend said about its schema editor, and how sure we are.\n *\n * `unknown` covers both \"still asking\" and \"could not ask\" — a backend too old\n * to have the endpoint, or one that is unreachable. Those fall back to the\n * build-mode guess below rather than locking the editor for someone whose\n * editor used to work.\n */\ntype SchemaEditorAvailability =\n | { state: \"unknown\" }\n | { state: \"known\", enabled: boolean, reason?: string };\n\n/**\n * The guess this hook used to make on its own.\n *\n * `process.env.NODE_ENV` here is the *frontend bundle's* build mode. Whether\n * the schema editor exists is decided by a different process entirely — the\n * server's own `NODE_ENV`, its `schemaDir`, whether its tables were\n * introspected, whether `ts-morph` is installed. It is kept only as the answer\n * for a backend too old to be asked.\n */\nconst buildModeGuess = (): boolean => process.env.NODE_ENV === \"production\";\n\n/**\n * Where the collection editor's presentation edits go: the UI preferences\n * store (`usePresentationPersistence`). Absent, an edit that changes how a\n * table is presented is refused, never silently dropped.\n */\nexport interface PresentationWriter {\n /** Merge `delta` into the workspace's preferences for `slug`. */\n save: (slug: string, delta: UiTablePreferences) => Promise<void>;\n}\n\n/** The client the controller is built over: a base URL, or the Rebase client. */\nexport interface SchemaEditorTransport {\n baseUrl?: string;\n apiPath?: string;\n resolveToken?: () => Promise<string | null | undefined>;\n}\n\n/** How the server's `GET /schema-editor/tables` describes one table. */\ninterface TableSourceSummary {\n slug: string;\n file: string;\n editedInCode?: string;\n columns?: { key: string; editedInCode?: string }[];\n relations?: { name: string; editedInCode?: string }[];\n rlsEditedInCode?: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** A table description as the wire carries it: checked for the fields the projector and the adoption read. */\nfunction isTableDescriptor(value: unknown): value is TableDescriptor {\n return isRecord(value)\n && typeof value.name === \"string\"\n && typeof value.slug === \"string\"\n && typeof value.table === \"string\"\n && typeof value.schema === \"string\"\n && Array.isArray(value.columns)\n && Array.isArray(value.relations)\n && Array.isArray(value.primaryKey)\n && isRecord(value.rls);\n}\n\n/** One table of `GET …/unmapped-tables`, or of `…/unmapped-tables/:schema/:table` with its description. */\nfunction readUnmappedTable(value: unknown): UnmappedTable | undefined {\n if (!isRecord(value) || typeof value.schema !== \"string\" || typeof value.table !== \"string\") return undefined;\n return {\n schema: value.schema,\n table: value.table,\n rlsEnabled: value.rlsEnabled === true,\n policies: typeof value.policies === \"number\" ? value.policies : 0,\n ...(isTableDescriptor(value.descriptor) ? { descriptor: value.descriptor } : {}),\n ...(typeof value.rlsRaised === \"string\" ? { rlsRaised: value.rlsRaised } : {}),\n ...(typeof value.unimportable === \"string\" ? { unimportable: value.unimportable } : {}),\n notes: Array.isArray(value.notes) ? value.notes.filter((note): note is string => typeof note === \"string\") : []\n };\n}\n\nfunction readSummaries(body: unknown): TableSourceSummary[] {\n if (!isRecord(body) || !Array.isArray(body.tables)) return [];\n return body.tables.flatMap((entry): TableSourceSummary[] => {\n if (!isRecord(entry) || typeof entry.slug !== \"string\" || typeof entry.file !== \"string\") return [];\n const listed = (value: unknown, name: \"key\" | \"name\") => Array.isArray(value)\n ? value.flatMap(item => isRecord(item) && typeof item[name] === \"string\"\n ? [{ id: String(item[name]), reason: typeof item.editedInCode === \"string\" ? item.editedInCode : undefined }]\n : [])\n : [];\n return [{\n slug: entry.slug,\n file: entry.file,\n ...(typeof entry.editedInCode === \"string\" ? { editedInCode: entry.editedInCode } : {}),\n columns: listed(entry.columns, \"key\").map(c => ({ key: c.id, ...(c.reason ? { editedInCode: c.reason } : {}) })),\n relations: listed(entry.relations, \"name\").map(r => ({ name: r.id, ...(r.reason ? { editedInCode: r.reason } : {}) })),\n ...(typeof entry.rlsEditedInCode === \"string\" ? { rlsEditedInCode: entry.rlsEditedInCode } : {})\n }];\n });\n}\n\n/** How the frontend source editor's `GET /frontend/calls` describes one Firestore collection. */\ninterface FrontendCallSummary {\n slug: string;\n file: string;\n version: string;\n info: TableSourceInfo;\n}\n\nfunction readCalls(body: unknown): FrontendCallSummary[] {\n if (!isRecord(body) || !Array.isArray(body.calls)) return [];\n return body.calls.flatMap((entry): FrontendCallSummary[] => {\n if (!isRecord(entry) || typeof entry.value !== \"string\" || typeof entry.file !== \"string\" || typeof entry.version !== \"string\") return [];\n const fields: Record<string, string> = {};\n if (isRecord(entry.members)) {\n for (const [member, reason] of Object.entries(entry.members)) {\n if (typeof reason === \"string\" && member.startsWith(\"fields.\")) fields[member.slice(\"fields.\".length)] = reason;\n }\n }\n return [{\n slug: entry.value,\n file: entry.file,\n version: entry.version,\n info: { file: entry.file, fields, ...(typeof entry.editedInCode === \"string\" ? { editedInCode: entry.editedInCode } : {}) }\n }];\n });\n}\n\n/** `values` in the order of `order` (the ones it does not name last), in the shape they were given in. */\nfunction reorderEnum(values: EnumValues, order: readonly string[]): EnumValues {\n const rank = (id: string) => {\n const at = order.indexOf(id);\n return at === -1 ? order.length : at;\n };\n if (Array.isArray(values)) return [...values].sort((a, b) => rank(String(a.id)) - rank(String(b.id)));\n return Object.fromEntries(Object.entries(values).sort(([a], [b]) => rank(a) - rank(b)));\n}\n\nfunction sourceInfoOf(summary: TableSourceSummary): TableSourceInfo {\n const columns: Record<string, string> = {};\n for (const column of summary.columns ?? []) if (column.editedInCode) columns[column.key] = column.editedInCode;\n for (const relation of summary.relations ?? []) if (relation.editedInCode) columns[relation.name] = relation.editedInCode;\n return {\n file: summary.file,\n ...(summary.editedInCode ? { editedInCode: summary.editedInCode } : {}),\n fields: columns,\n ...(summary.rlsEditedInCode ? { rlsEditedInCode: summary.rlsEditedInCode } : {})\n };\n}\n\n/**\n * An error a save ends with that the editor shows as more than a line:\n * `SCHEMA_EDIT_DOES_NOT_COMPILE` with its problems, a refusal, a file changed\n * on disk since the preview. Carries the server's code and problems.\n */\nexport class SchemaEditRefused extends Error {\n constructor(message: string, readonly code: string | undefined, readonly problems: readonly SchemaEditProblem[] = []) {\n super(message);\n this.name = \"SchemaEditRefused\";\n }\n}\n\n/**\n * The collections config controller the panel builds when the collection\n * editor is on.\n *\n * A save is split ({@link splitEdit}) into the schema edit — `TablePatch`\n * operations for the server's schema editor, through the plan-and-confirm\n * dialog when live schema editing is on, straight to the source-only editor\n * when it is not — and the presentation delta, written to the UI preferences\n * store. A Firestore collection is defined in the frontend: on a development\n * server its save is an edit of its `defineFirestoreCollection` call\n * (`firestoreCollectionPatches`), written by the server's frontend source\n * editor; anywhere else it is read-only here.\n */\nexport function useLocalCollectionsConfigController(\n clientOrUrl: string | SchemaEditorTransport | null | undefined,\n baseCollections: AdminCollection[] = [],\n options?: {\n readOnly?: boolean;\n getAuthToken?: () => Promise<string | null>;\n /**\n * Identity of the signed-in user, if any. Only used to re-ask the\n * backend when it changes.\n */\n authKey?: string | null;\n /**\n * Whether the signed-in user holds `schema:read`, which both status\n * routes require. `false` asks neither and leaves the editor\n * read-only. Absent means ask.\n */\n mayReadSchema?: boolean;\n /**\n * The tables the server serves, as descriptors: what a save keeps from\n * a column the view model cannot fully describe, and which collections\n * are tables at all (the others are external, and read-only here).\n */\n tables?: readonly TableDescriptor[];\n /** Where presentation edits are written. */\n presentation?: PresentationWriter;\n }\n): CollectionsConfigController {\n\n const parsedCollections = baseCollections;\n\n const optionsRef = useRef(options);\n optionsRef.current = options;\n\n const transport: SchemaEditorTransport = typeof clientOrUrl === \"string\" ? { baseUrl: clientOrUrl } : clientOrUrl ?? {};\n const clientBaseUrl = String(transport.baseUrl ?? \"\").replace(/\\/$/, \"\");\n const clientApiPath = transport.apiPath || DEFAULT_API_PATH;\n const editorUrl = `${clientBaseUrl}${clientApiPath}/admin/schema-editor`;\n\n const resolveToken = async (): Promise<string | null> => {\n let token = optionsRef.current?.getAuthToken ? await optionsRef.current.getAuthToken() : null;\n if (!token && transport.resolveToken) token = (await transport.resolveToken()) ?? null;\n return token ?? null;\n };\n\n /** A call to the source-only editor; a refusal becomes {@link SchemaEditRefused} with the server's problems. */\n const request = async (method: \"GET\" | \"POST\", endpoint: string, payload?: object): Promise<unknown> => {\n const token = await resolveToken();\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (token) headers.Authorization = `Bearer ${token}`;\n const response = await fetch(`${editorUrl}${endpoint}`, {\n method,\n headers,\n ...(payload ? { body: JSON.stringify(payload) } : {})\n });\n const text = await response.text();\n let body: unknown;\n try {\n body = text ? JSON.parse(text) : undefined;\n } catch {\n body = undefined;\n }\n if (response.ok) return body;\n const error = isRecord(body) && isRecord(body.error) ? body.error : undefined;\n const details = error && isRecord(error.details) ? error.details : undefined;\n const problems: SchemaEditProblem[] = Array.isArray(details?.problems)\n ? details.problems.flatMap((p): SchemaEditProblem[] => isRecord(p) && typeof p.message === \"string\"\n ? [{ table: typeof p.table === \"string\" ? p.table : \"\", ...(typeof p.key === \"string\" ? { key: p.key } : {}), message: p.message }]\n : [])\n : [];\n throw new SchemaEditRefused(\n (typeof error?.message === \"string\" && error.message) || text || `The schema editor answered ${response.status}.`,\n typeof error?.code === \"string\" ? error.code : undefined,\n problems\n );\n };\n\n // ── Ask the backend whether it will accept an edit ────────────────\n const noSchemaAccess = options?.mayReadSchema === false;\n const forcedReadOnly = noSchemaAccess ? true : options?.readOnly;\n const authKey = options?.authKey ?? null;\n const [availability, setAvailability] = useState<SchemaEditorAvailability>({ state: \"unknown\" });\n const [sources, setSources] = useState<Record<string, TableSourceInfo>>({});\n /** The Firestore collections the frontend source editor found, by slug. */\n const [frontendCalls, setFrontendCalls] = useState<Record<string, FrontendCallSummary>>({});\n\n /** Ask the frontend source editor where each Firestore collection is written, and what in it is code. */\n const refreshFrontendCalls = async (): Promise<void> => {\n const listed = await request(\"GET\", `/frontend/calls?callee=${FIRESTORE_COLLECTION_CALLEE}&key=slug&list=fields`).catch(() => undefined);\n if (listed === undefined) return;\n const next: Record<string, FrontendCallSummary> = {};\n for (const call of readCalls(listed)) next[call.slug] = call;\n setFrontendCalls(next);\n };\n\n useEffect(() => {\n if (forcedReadOnly === true) return;\n\n let cancelled = false;\n (async () => {\n try {\n const token = await resolveToken();\n const response = await fetch(`${editorUrl}/status`, {\n headers: token ? { Authorization: `Bearer ${token}` } : {}\n });\n if (cancelled) return;\n if (response.status === 404) {\n setAvailability({ state: \"unknown\" });\n return;\n }\n const body = await response.json().catch(() => ({})) as {\n enabled?: boolean,\n reason?: string,\n error?: { message?: string }\n };\n if (cancelled) return;\n if (response.ok) {\n setAvailability({ state: \"known\", enabled: body.enabled === true, reason: body.reason });\n if (body.enabled === true) {\n // What is edited in code, so the editor shows it read-only\n // rather than offering an edit the server refuses.\n const listed = await request(\"GET\", \"/tables\").catch(() => undefined);\n if (!cancelled && listed !== undefined) {\n const next: Record<string, TableSourceInfo> = {};\n for (const summary of readSummaries(listed)) next[summary.slug] = sourceInfoOf(summary);\n setSources(next);\n }\n if (!cancelled) await refreshFrontendCalls();\n }\n } else {\n setAvailability({\n state: \"known\",\n enabled: false,\n reason: body.error?.message\n ?? `The backend refused to say whether tables are editable (HTTP ${response.status}).`\n });\n }\n } catch {\n if (!cancelled) setAvailability({ state: \"unknown\" });\n }\n })();\n\n return () => { cancelled = true; };\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `request`, `resolveToken` and `refreshFrontendCalls` are rebuilt every render over the editor URL and the token source, which `editorUrl` and `authKey` stand for; listing them would re-ask on every render\n }, [editorUrl, forcedReadOnly, authKey]);\n\n // A Firestore collection's file is re-read after every save (the dev\n // server reloads the module, and the collections change): its version\n // is what the next save is checked against.\n const sourceEditorEnabled = availability.state === \"known\" && availability.enabled;\n useEffect(() => {\n if (sourceEditorEnabled && forcedReadOnly !== true) void refreshFrontendCalls();\n // eslint-disable-next-line react-hooks/exhaustive-deps -- re-read when the served collections change (the module reloaded); the availability effect does its own first read when the editor turns on\n }, [parsedCollections]);\n\n // ── Live schema editing ───────────────────────────────────────────\n const liveSchema = useLiveSchemaEditing({\n baseUrl: `${clientBaseUrl}${clientApiPath}/admin/schema`,\n getAuthToken: resolveToken,\n authKey,\n enabled: forcedReadOnly !== true\n });\n\n const detach = useDetachRulesConfirmation();\n\n const tablesBySlug = useMemo(() => {\n const map = new Map<string, TableDescriptor>();\n for (const table of options?.tables ?? []) map.set(table.slug, table);\n return map;\n }, [options?.tables]);\n\n /**\n * Send a schema edit: through the live editor (planned, shown, confirmed)\n * when there is one, to the source-only editor when there is not.\n */\n const writeSchema = async (table: string, patches: TablePatch[]): Promise<void> => {\n if (patches.length === 0) return;\n const available = await liveSchema.ready();\n if (available.enabled) {\n await liveSchema.reviewChange({ table, patches });\n return;\n }\n try {\n await request(\"POST\", \"/apply\", { patches });\n } catch (error) {\n if (error instanceof LiveSchemaError) throw new SchemaEditRefused(error.message, error.code, error.problems);\n throw error;\n }\n };\n\n const writePresentation = async (slug: string, delta: UiTablePreferences): Promise<void> => {\n if (Object.keys(delta).length === 0) return;\n const writer = optionsRef.current?.presentation;\n if (!writer) {\n throw new Error(`How \"${slug}\" is presented (labels, columns, view modes) is stored as a UI preference, and this panel has no preferences store. Sign in, or customize the table with customizeTable in the frontend.`);\n }\n await writer.save(slug, delta);\n };\n\n const findCollection = (id: string): AdminCollection | undefined =>\n parsedCollections.find(c => c.slug === id);\n\n /** A collection that is not a served table is defined in the frontend: refuse to edit it here. */\n const assertTable = (collection: AdminCollection | undefined, slug: string): void => {\n if (!collection || tablesBySlug.size === 0 || tablesBySlug.has(slug)) return;\n throw new SplitEditError(\"EXTERNAL_COLLECTION\",\n `\"${slug}\" is not a table of this backend: it is defined in the frontend (frontend/src/cms), which the schema editor does not write. Edit it there.`);\n };\n\n /**\n * Whether Firestore collections can be edited here: the dev server's\n * source editor is on, which writes their `defineFirestoreCollection`\n * calls in frontend/src/cms. Off — production, a deployed API, no\n * `schema:read` — they are read-only, with where to edit them.\n */\n const frontendEditable = forcedReadOnly !== true && sourceEditorEnabled;\n\n /** Save a Firestore collection: the whole edit is an edit of its definition in the frontend. */\n const saveFirestore = async (slug: string, after: AdminCollection, before?: AdminCollection): Promise<void> => {\n if (!frontendEditable) {\n throw new SplitEditError(\"EXTERNAL_COLLECTION\",\n `\"${slug}\" is a Firestore collection: it is defined in the frontend (frontend/src/cms), and only a development server's source editor writes the frontend. Edit it there.`);\n }\n const loaded = before ?? findCollection(slug);\n if (!loaded) throw new Error(`No collection \"${slug}\" is open in the editor.`);\n const { firestoreCollectionPatches, firestoreSourceEdit } = await import(\"./firestore_edit\");\n const patches = firestoreCollectionPatches(loaded, after);\n if (patches.length === 0) return;\n await request(\"POST\", \"/frontend/apply\", firestoreSourceEdit(slug, patches, frontendCalls[slug]?.version));\n await refreshFrontendCalls();\n };\n\n /** A table being imported, projected as the served tables are, its relations resolved among them. */\n const projectedImport = async (descriptor: TableDescriptor): Promise<AdminCollection> => {\n const { collectionFromTable } = await import(\"../tables/project_table\");\n const served = (optionsRef.current?.tables ?? []).filter(table => table.slug !== descriptor.slug);\n return collectionFromTable(descriptor, { tables: [...served, descriptor] });\n };\n\n /** Write one split edit: the schema first, then — once the schema took — the presentation. */\n const commit = async (edit: SplitEdit): Promise<void> => {\n if (edit.detachesInheritedRules) await detach.confirm(edit.table);\n await writeSchema(edit.table, edit.schema);\n await writePresentation(edit.table, edit.presentation);\n };\n\n const save = async (slug: string, after: AdminCollection, before?: AdminCollection, adopting?: TableDescriptor): Promise<void> => {\n // Loaded with the first save: the boot path of every admin session\n // builds this controller, and most sessions never save a table.\n if (adopting) {\n // The person's edits are what changed from the table's projection.\n const { splitEdit } = await import(\"./split_edit\");\n const projected = before ?? await projectedImport(adopting);\n await commit(splitEdit({ before: projected, after, table: adopting, adopt: true }));\n return;\n }\n const loaded = before ?? findCollection(slug);\n if ((loaded ?? after).engine === \"firestore\") {\n await saveFirestore(slug, after, loaded);\n return;\n }\n assertTable(loaded, slug);\n const { splitEdit } = await import(\"./split_edit\");\n await commit(splitEdit({ before: loaded, after, table: tablesBySlug.get(slug) }));\n };\n\n // Live schema editing, when it is on, is where every write goes, so the\n // source-only editor's answer does not lock the editor then.\n const liveEditing = liveSchema.status?.enabled === true;\n const servedRedacted = parsedCollections.some(c => (c.securityRules ?? []).some(rule => isRecord(rule) && rule.redacted === true));\n const readOnly = forcedReadOnly\n ?? (servedRedacted ? true : liveEditing ? false : availability.state === \"known\" ? !availability.enabled : buildModeGuess());\n\n const readOnlyReason = noSchemaAccess\n ? undefined\n : servedRedacted\n ? \"Some of the rules were served to you redacted: only an admin can save schema changes, because saving would write the redacted marker back.\"\n : liveEditing\n ? undefined\n : availability.state === \"known\" && availability.reason\n ? availability.reason\n : \"Tables can only be edited against a backend running the schema editor, which is off in production.\";\n\n const currentOf = (id: string): AdminCollection => {\n const found = findCollection(id);\n if (!found) throw new Error(`No table \"${id}\" is open in the editor.`);\n return found;\n };\n\n /** The collection of a table, or a refusal naming where an external collection is defined. */\n const tableOf = (id: string): AdminPostgresCollection => {\n const found = currentOf(id);\n if (found.engine === \"firestore\") {\n throw new SplitEditError(\"EXTERNAL_COLLECTION\",\n `\"${id}\" is a Firestore collection: it is defined in the frontend (frontend/src/cms), which the schema editor does not write. Edit it there.`);\n }\n return found;\n };\n\n /** A Firestore collection with `properties` replaced, saved. */\n const saveFirestoreProperties = async (current: AdminCollection, properties: Record<string, Property>, order?: string[]): Promise<void> => {\n const firestoreProperties: Record<string, FirebaseProperty> = {};\n for (const [key, property] of Object.entries(properties)) {\n if (property.type === \"relation\" || property.type === \"vector\") {\n throw new SplitEditError(\"NOT_A_COLUMN\", `\"${key}\" is a ${property.type}, which Firestore does not store: that belongs to a Postgres table.`, key);\n }\n firestoreProperties[key] = property;\n }\n await saveFirestore(current.slug, {\n ...current,\n engine: \"firestore\",\n properties: firestoreProperties,\n ...(order ? { propertiesOrder: order } : {})\n }, current);\n };\n\n const columnProperty = (key: string, property: Property): PostgresProperty => {\n if (property.type === \"reference\") {\n throw new SplitEditError(\"NOT_A_COLUMN\",\n `\"${key}\" is a reference, which a table stores as a text column: make it a text field and point it at the other table with \\`referenceTo\\` in its customization.`, key);\n }\n return property;\n };\n\n return useMemo(() => ({\n loading: false,\n readOnly,\n readOnlyReason,\n frontendCollectionsEditable: frontendEditable,\n collections: parsedCollections,\n tableSource: (slug: string) => sources[slug] ?? frontendCalls[slug]?.info,\n dialog: (\n <>\n {liveSchema.dialog}\n {detach.dialog}\n </>\n ),\n getCollection: (id: string) => currentOf(id),\n\n saveCollection: async ({ id, collectionData, baseline, adopting }: SaveCollectionParams) => {\n await save(id, collectionData, baseline, adopting);\n },\n // `collectionData` is a partial: the keys it names, set over the\n // collection as it is.\n updateCollection: async ({ id, collectionData }: UpdateCollectionParams) => {\n const current = currentOf(id);\n if (current.engine === \"firestore\") {\n const edited: AdminCollection = { ...current };\n for (const [key, value] of Object.entries(collectionData)) {\n if (value === undefined) Reflect.deleteProperty(edited, key);\n else Reflect.set(edited, key, value);\n }\n await saveFirestore(id, edited, current);\n return;\n }\n const after: AdminPostgresCollection = { ...tableOf(id) };\n for (const [key, value] of Object.entries(collectionData)) {\n // Absent rather than `undefined` when cleared.\n if (value === undefined) Reflect.deleteProperty(after, key);\n else Reflect.set(after, key, value);\n }\n await save(id, after);\n },\n // The table's definition and its export from the index go; the SQL\n // table and its rows stay, and the plan says so.\n deleteCollection: async ({ id }: DeleteCollectionParams) => {\n if (findCollection(id)?.engine === \"firestore\") {\n throw new SplitEditError(\"EXTERNAL_COLLECTION\",\n `\"${id}\" is a Firestore collection: delete it in code — its file in frontend/src/cms and its entry in \\`externalCollections\\`. Its documents stay in Firestore.`);\n }\n assertTable(findCollection(id), id);\n await writeSchema(id, [{ op: \"deleteTable\", table: id }]);\n },\n applyTablePatches: async (table: string, patches: TablePatch[]) => {\n await writeSchema(table, patches);\n },\n\n listUnmappedTables: async () => {\n const body = await request(\"GET\", \"/unmapped-tables\");\n const listed = isRecord(body) && Array.isArray(body.tables) ? body.tables : [];\n return listed.flatMap(table => readUnmappedTable(table) ?? []);\n },\n\n describeUnmappedTable: async (schema: string, table: string) => {\n const body = await request(\"GET\", `/unmapped-tables/${encodeURIComponent(schema)}/${encodeURIComponent(table)}`);\n const found = isRecord(body) ? readUnmappedTable(body.table) : undefined;\n const descriptor = found?.descriptor;\n if (!found || !descriptor) throw new Error(`The schema editor did not describe \"${schema}\".\"${table}\".`);\n return { table: found, descriptor, collection: await projectedImport(descriptor) };\n },\n\n saveProperty: async ({ path, propertyKey, property, newPropertiesOrder }: SavePropertyParams) => {\n const external = currentOf(path);\n if (external.engine === \"firestore\") {\n await saveFirestoreProperties(external, { ...external.properties, [propertyKey]: property }, newPropertiesOrder);\n return;\n }\n const current = tableOf(path);\n await save(path, {\n ...current,\n properties: { ...current.properties, [propertyKey]: columnProperty(propertyKey, property) },\n ...(newPropertiesOrder ? { propertiesOrder: newPropertiesOrder } : {})\n });\n },\n deleteProperty: async ({ path, propertyKey, newPropertiesOrder }: DeletePropertyParams) => {\n const external = currentOf(path);\n if (external.engine === \"firestore\") {\n const { [propertyKey]: _gone, ...rest } = external.properties;\n void _gone;\n await saveFirestoreProperties(external, rest, newPropertiesOrder);\n return;\n }\n const current = tableOf(path);\n const { [propertyKey]: _removed, ...properties } = current.properties ?? {};\n void _removed;\n await save(path, {\n ...current,\n properties,\n ...(newPropertiesOrder ? { propertiesOrder: newPropertiesOrder } : {})\n });\n },\n\n // Column order is presentation: a preference, never a schema edit.\n // A Firestore collection has no preferences: its order is its definition's.\n updatePropertiesOrder: async ({ collection, newPropertiesOrder }: UpdatePropertiesOrderParams) => {\n const external = findCollection(collection.slug);\n if (external?.engine === \"firestore\") {\n await saveFirestore(collection.slug, { ...external, propertiesOrder: [...newPropertiesOrder] }, external);\n return;\n }\n await writePresentation(collection.slug, { fieldOrder: [...newPropertiesOrder] });\n },\n // The board's column order is the order of the enum's values: presentation too.\n updateKanbanColumnsOrder: async ({ collection, kanbanColumnProperty, newColumnsOrder }: UpdateKanbanColumnsOrderParams) => {\n const external = findCollection(collection.slug);\n if (external?.engine === \"firestore\") {\n const property = external.properties[kanbanColumnProperty];\n if (!property || property.type !== \"string\" || !property.enum) {\n throw new Error(`\"${kanbanColumnProperty}\" of \"${collection.slug}\" is not a string field with values to order.`);\n }\n await saveFirestoreProperties(external, {\n ...external.properties,\n [kanbanColumnProperty]: { ...property, enum: reorderEnum(property.enum, newColumnsOrder) }\n });\n return;\n }\n await writePresentation(collection.slug, { fields: { [kanbanColumnProperty]: { enumOrder: [...newColumnsOrder] } } });\n },\n\n navigationEntries: [],\n saveNavigationEntries: async () => { }\n // Every input that can change is listed under the name it varies with;\n // the helpers rebuilt per render close over exactly these.\n // eslint-disable-next-line react-hooks/exhaustive-deps -- the helpers rebuilt per render close over exactly the inputs listed\n }), [\n clientOrUrl,\n parsedCollections,\n readOnly,\n readOnlyReason,\n sources,\n frontendCalls,\n frontendEditable,\n tablesBySlug,\n options?.getAuthToken,\n liveSchema.dialog,\n liveSchema.status,\n detach.dialog\n ]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA4CA,IAAM,uBAAA,QAAA,IAAA,aAAyD;AA6B/D,IAAM,YAAY,UACd,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;;AAGvE,SAAS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AAsD;GAC9F,MAAM,WAAW,eAAe,WAAW,IAAI;GAC/C,IAAI,UAAU,WAAW,aAAa;IAClC,MAAM,cAAc,WAAW,MAAM;KAAE,GAAG;KAAU,iBAAiB,CAAC,GAAG,kBAAkB;IAAE,GAAG,QAAQ;IACxG;GACJ;GACA,MAAM,kBAAkB,WAAW,MAAM,EAAE,YAAY,CAAC,GAAG,kBAAkB,EAAE,CAAC;EACpF;EAEA,0BAA0B,OAAO,EAAE,YAAY,sBAAsB,sBAAsD;GACvH,MAAM,WAAW,eAAe,WAAW,IAAI;GAC/C,IAAI,UAAU,WAAW,aAAa;IAClC,MAAM,WAAW,SAAS,WAAW;IACrC,IAAI,CAAC,YAAY,SAAS,SAAS,YAAY,CAAC,SAAS,MACrD,MAAM,IAAI,MAAM,IAAI,qBAAqB,QAAQ,WAAW,KAAK,8CAA8C;IAEnH,MAAM,wBAAwB,UAAU;KACpC,GAAG,SAAS;MACX,uBAAuB;MAAE,GAAG;MAAU,MAAM,YAAY,SAAS,MAAM,eAAe;KAAE;IAC7F,CAAC;IACD;GACJ;GACA,MAAM,kBAAkB,WAAW,MAAM,EAAE,QAAQ,GAAG,uBAAuB,EAAE,WAAW,CAAC,GAAG,eAAe,EAAE,EAAE,EAAE,CAAC;EACxH;EAEA,mBAAmB,CAAC;EACpB,uBAAuB,YAAY,CAAE;CAIzC,IAAI;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS;EACT,WAAW;EACX,WAAW;EACX,OAAO;CACX,CAAC;AACL"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validateCollectionJson.js","names":[],"sources":["../../src/collection_editor/validateCollectionJson.ts"],"sourcesContent":["import { DataType } from \"@rebasepro/types\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\n/**\n * Valid dataType values for properties\n */\nconst VALID_DATA_TYPES = [\n \"string\",\n \"number\",\n \"boolean\",\n \"date\",\n \"geopoint\",\n \"reference\",\n \"relation\",\n \"array\",\n \"map\",\n \"vector\",\n \"binary\"\n] as const;\n\n/**\n * Validation error with path and message\n */\nexport interface CollectionValidationError {\n path: string;\n message: string;\n}\n\n/**\n * Result of collection JSON validation\n */\nexport interface CollectionValidationResult {\n valid: boolean;\n errors: CollectionValidationError[];\n collection?: AdminCollection;\n}\n\n/**\n * Validates a property object recursively\n */\nfunction validateProperty(\n property: Record<string, unknown>,\n path: string,\n errors: CollectionValidationError[]\n): void {\n if (typeof property !== \"object\" || property === null) {\n errors.push({\n path,\n message: \"Property must be an object\"\n });\n return;\n }\n\n // Check type\n if (!property.type) {\n errors.push({\n path: `${path}.type`,\n message: \"Required field is missing\"\n });\n } else if (!VALID_DATA_TYPES.includes(property.type as DataType)) {\n errors.push({\n path: `${path}.type`,\n message: `Invalid value \"${property.type}\", expected one of: ${VALID_DATA_TYPES.join(\", \")}`\n });\n }\n\n // Validate name if present\n if (property.name !== undefined && typeof property.name !== \"string\") {\n errors.push({\n path: `${path}.name`,\n message: \"Must be a string\"\n });\n }\n\n // Validate array \"of\" property\n if (property.type === \"array\") {\n if (property.of) {\n if (Array.isArray(property.of)) {\n property.of.forEach((ofProp: Record<string, unknown>, index: number) => {\n validateProperty(ofProp, `${path}.of[${index}]`, errors);\n });\n } else {\n validateProperty(property.of as Record<string, unknown>, `${path}.of`, errors);\n }\n }\n // oneOf validation\n if (property.oneOf) {\n if (typeof property.oneOf !== \"object\") {\n errors.push({\n path: `${path}.oneOf`,\n message: \"Must be an object\"\n });\n } else if ((property.oneOf as Record<string, unknown>).properties) {\n validateProperties((property.oneOf as Record<string, unknown>).properties as Record<string, unknown>, `${path}.oneOf.properties`, errors);\n }\n }\n }\n\n // Validate map properties\n if (property.type === \"map\" && property.properties) {\n validateProperties(property.properties as Record<string, unknown>, `${path}.properties`, errors);\n }\n\n // Validate reference path\n if (property.type === \"reference\") {\n if (property.path !== undefined && typeof property.path !== \"string\") {\n errors.push({\n path: `${path}.path`,\n message: \"Must be a string\"\n });\n }\n }\n\n // Validate relation property\n if (property.type === \"relation\") {\n const link = property.relation as Record<string, unknown> | undefined;\n if (link !== undefined) {\n const KINDS = [\"belongsTo\", \"hasOne\", \"hasMany\", \"manyToMany\", \"via\"];\n if (typeof link.kind !== \"string\" || !KINDS.includes(link.kind)) {\n errors.push({\n path: `${path}.relation.kind`,\n message: `Must be one of ${KINDS.join(\", \")}`\n });\n }\n\n if (link.target !== undefined && typeof link.target !== \"string\" && typeof link.target !== \"function\") {\n errors.push({\n path: `${path}.relation.target`,\n message: \"Must be a collection slug or a thunk returning a collection\"\n });\n }\n\n // Each kind admits exactly one link field. Anything else on it is\n // a leftover from another shape and would previously have been\n // silently honoured by whichever consumer read it first.\n const allowedByKind: Record<string, string[]> = {\n belongsTo: [\"localKey\"],\n hasOne: [\"foreignKeyOnTarget\", \"sourceKey\"],\n hasMany: [\"foreignKeyOnTarget\", \"sourceKey\"],\n manyToMany: [\"through\"],\n via: [\"joinPath\", \"cardinality\"]\n };\n const linkFields = [\"localKey\", \"foreignKeyOnTarget\", \"sourceKey\", \"through\", \"joinPath\", \"cardinality\"];\n const allowed = allowedByKind[String(link.kind)] ?? [];\n for (const field of linkFields) {\n if (link[field] !== undefined && !allowed.includes(field)) {\n errors.push({\n path: `${path}.relation.${field}`,\n message: `Not valid on a \"${String(link.kind)}\" relation`\n });\n }\n }\n\n if (link.kind === \"via\" && !Array.isArray(link.joinPath)) {\n errors.push({\n path: `${path}.relation.joinPath`,\n message: \"A `via` relation requires a joinPath array\"\n });\n }\n }\n }\n\n // Validate vector property\n if (property.type === \"vector\") {\n if (property.dimensions !== undefined && (typeof property.dimensions !== \"number\" || isNaN(property.dimensions) || property.dimensions <= 0)) {\n errors.push({\n path: `${path}.dimensions`,\n message: \"Must be a positive number\"\n });\n }\n }\n\n // Validate storage config for string\n if (property.type === \"string\" && property.storage) {\n if (typeof property.storage !== \"object\") {\n errors.push({\n path: `${path}.storage`,\n message: \"Must be an object\"\n });\n }\n }\n\n // Validate enum if present\n if (property.enum !== undefined) {\n if (!Array.isArray(property.enum) && typeof property.enum !== \"object\") {\n errors.push({\n path: `${path}.enum`,\n message: \"Must be an array or object\"\n });\n }\n }\n}\n\n/**\n * Validates a properties object (collection of property definitions)\n */\nfunction validateProperties(\n properties: Record<string, unknown>,\n path: string,\n errors: CollectionValidationError[]\n): void {\n if (typeof properties !== \"object\" || properties === null) {\n errors.push({\n path,\n message: \"Must be an object\"\n });\n return;\n }\n\n for (const [key, property] of Object.entries(properties)) {\n validateProperty(property as Record<string, unknown>, `${path}.${key}`, errors);\n }\n}\n\n/**\n * Validates optional collection fields\n */\nfunction validateOptionalFields(\n collection: Record<string, unknown>,\n errors: CollectionValidationError[]\n): void {\n // String fields\n const stringFields = [\n \"singularName\",\n \"description\",\n \"group\",\n \"databaseId\"\n ];\n for (const field of stringFields) {\n if (collection[field] !== undefined && typeof collection[field] !== \"string\") {\n errors.push({\n path: field,\n message: \"Must be a string\"\n });\n }\n }\n\n // Boolean fields\n const booleanFields = [\n\n \"selectionEnabled\",\n \"inlineEditing\",\n \"hideFromNavigation\",\n \"hideIdFromForm\",\n \"hideIdFromCollection\",\n \"formAutoSave\",\n \"alwaysApplyDefaultValues\",\n \"includeJsonView\",\n \"history\"\n ];\n for (const field of booleanFields) {\n if (collection[field] !== undefined && typeof collection[field] !== \"boolean\") {\n errors.push({\n path: field,\n message: \"Must be a boolean\"\n });\n }\n }\n\n // Icon can be string or object (React node)\n if (collection.icon !== undefined &&\n typeof collection.icon !== \"string\" &&\n typeof collection.icon !== \"object\") {\n errors.push({\n path: \"icon\",\n message: \"Must be a string (icon key) or object\"\n });\n }\n\n // propertiesOrder must be array of strings\n if (collection.propertiesOrder !== undefined) {\n if (!Array.isArray(collection.propertiesOrder)) {\n errors.push({\n path: \"propertiesOrder\",\n message: \"Must be an array of strings\"\n });\n } else if (!collection.propertiesOrder.every((item: unknown) => typeof item === \"string\")) {\n errors.push({\n path: \"propertiesOrder\",\n message: \"All items must be strings\"\n });\n }\n }\n\n // subcollections must be array\n if (collection.subcollections !== undefined) {\n if (!Array.isArray(collection.subcollections)) {\n errors.push({\n path: \"subcollections\",\n message: \"Must be an array\"\n });\n } else {\n collection.subcollections.forEach((sub: Record<string, unknown>, index: number) => {\n const subErrors: CollectionValidationError[] = [];\n validateCollectionObject(sub, subErrors);\n subErrors.forEach(err => {\n errors.push({\n path: `subcollections[${index}].${err.path}`,\n message: err.message\n });\n });\n });\n }\n }\n\n // defaultViewMode validation\n const validViewModes = [\"table\", \"cards\", \"kanban\"];\n if (collection.defaultViewMode !== undefined) {\n if (!validViewModes.includes(collection.defaultViewMode as string)) {\n errors.push({\n path: \"defaultViewMode\",\n message: `Invalid value, expected one of: ${validViewModes.join(\", \")}`\n });\n }\n }\n\n // kanban config validation\n if (collection.kanban !== undefined) {\n if (typeof collection.kanban !== \"object\" || collection.kanban === null) {\n errors.push({\n path: \"kanban\",\n message: \"Must be an object\"\n });\n } else if ((collection.kanban as Record<string, unknown>).columnProperty !== undefined &&\n typeof (collection.kanban as Record<string, unknown>).columnProperty !== \"string\") {\n errors.push({\n path: \"kanban.columnProperty\",\n message: \"Must be a string\"\n });\n }\n }\n}\n\n/**\n * Validates a collection object\n */\nfunction validateCollectionObject(\n collection: Record<string, unknown>,\n errors: CollectionValidationError[]\n): void {\n // Required fields\n if (!collection.id) {\n errors.push({\n path: \"id\",\n message: \"Required field is missing\"\n });\n } else if (typeof collection.id !== \"string\") {\n errors.push({\n path: \"id\",\n message: \"Must be a string\"\n });\n }\n\n if (!collection.name) {\n errors.push({\n path: \"name\",\n message: \"Required field is missing\"\n });\n } else if (typeof collection.name !== \"string\") {\n errors.push({\n path: \"name\",\n message: \"Must be a string\"\n });\n }\n\n if (!collection.path) {\n errors.push({\n path: \"path\",\n message: \"Required field is missing\"\n });\n } else if (typeof collection.path !== \"string\") {\n errors.push({\n path: \"path\",\n message: \"Must be a string\"\n });\n }\n\n // Properties validation\n if (collection.properties !== undefined) {\n validateProperties(collection.properties as Record<string, unknown>, \"properties\", errors);\n }\n\n // Optional fields\n validateOptionalFields(collection, errors);\n}\n\n/**\n * Validates a JSON string representing a collection configuration.\n * Returns detailed validation errors if the JSON is invalid or doesn't match\n * the expected collection schema.\n */\nexport function validateCollectionJson(jsonString: string): CollectionValidationResult {\n const errors: CollectionValidationError[] = [];\n\n // Try to parse JSON\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(jsonString);\n } catch (e: unknown) {\n // Try to extract line/column info from the error\n const message_ = e instanceof Error ? e.message : String(e);\n const match = message_.match(/position (\\d+)/);\n let message = \"Invalid JSON syntax\";\n if (match) {\n const position = parseInt(match[1], 10);\n const lines = jsonString.substring(0, position).split(\"\\n\");\n const line = lines.length;\n const column = lines[lines.length - 1].length + 1;\n message = `Invalid JSON syntax at line ${line}, column ${column}: ${message_}`;\n } else {\n message = `Invalid JSON syntax: ${message_}`;\n }\n return {\n valid: false,\n errors: [{\n path: \"\",\n message\n }]\n };\n }\n\n // Validate collection structure\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return {\n valid: false,\n errors: [{\n path: \"\",\n message: \"Collection must be an object\"\n }]\n };\n }\n\n validateCollectionObject(parsed as Record<string, unknown>, errors);\n\n return {\n valid: errors.length === 0,\n errors,\n collection: errors.length === 0 ? parsed as AdminCollection : undefined\n };\n}\n"],"mappings":";;;;AAMA,IAAM,mBAAmB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;AAsBA,SAAS,iBACL,UACA,MACA,QACI;CACJ,IAAI,OAAO,aAAa,YAAY,aAAa,MAAM;EACnD,OAAO,KAAK;GACR;GACA,SAAS;EACb,CAAC;EACD;CACJ;CAGA,IAAI,CAAC,SAAS,MACV,OAAO,KAAK;EACR,MAAM,GAAG,KAAK;EACd,SAAS;CACb,CAAC;MACE,IAAI,CAAC,iBAAiB,SAAS,SAAS,IAAgB,GAC3D,OAAO,KAAK;EACR,MAAM,GAAG,KAAK;EACd,SAAS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EAEjB,MAAM,WAAW,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC;EAC1D,MAAM,QAAQ,SAAS,MAAM,gBAAgB;EAC7C,IAAI,UAAU;EACd,IAAI,OAAO;GACP,MAAM,WAAW,SAAS,MAAM,IAAI,EAAE;GACtC,MAAM,QAAQ,WAAW,UAAU,GAAG,QAAQ,CAAC,CAAC,MAAM,IAAI;GAG1D,UAAU,+BAFG,MAAM,OAE2B,WAD/B,MAAM,MAAM,SAAS,EAAE,CAAC,SAAS,EACgB,IAAI;EACxE,OACI,UAAU,wBAAwB;EAEtC,OAAO;GACH,OAAO;GACP,QAAQ,CAAC;IACL,MAAM;IACN;GACJ,CAAC;EACL;CACJ;CAGA,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GACrE,OAAO;EACH,OAAO;EACP,QAAQ,CAAC;GACL,MAAM;GACN,SAAS;EACb,CAAC;CACL;CAGJ,yBAAyB,QAAmC,MAAM;CAElE,OAAO;EACH,OAAO,OAAO,WAAW;EACzB;EACA,YAAY,OAAO,WAAW,IAAI,SAA4B,KAAA;CAClE;AACJ"}
|
|
1
|
+
{"version":3,"file":"validateCollectionJson.js","names":[],"sources":["../../src/collection_editor/validateCollectionJson.ts"],"sourcesContent":["import { DataType } from \"@rebasepro/cms-types\";\nimport type { AdminCollection } from \"@rebasepro/cms-types\";\n\n/**\n * Valid dataType values for properties\n */\nconst VALID_DATA_TYPES = [\n \"string\",\n \"number\",\n \"boolean\",\n \"date\",\n \"geopoint\",\n \"reference\",\n \"relation\",\n \"array\",\n \"map\",\n \"vector\",\n \"binary\"\n] as const;\n\n/**\n * Validation error with path and message\n */\nexport interface CollectionValidationError {\n path: string;\n message: string;\n}\n\n/**\n * Result of collection JSON validation\n */\nexport interface CollectionValidationResult {\n valid: boolean;\n errors: CollectionValidationError[];\n collection?: AdminCollection;\n}\n\n/**\n * Validates a property object recursively\n */\nfunction validateProperty(\n property: Record<string, unknown>,\n path: string,\n errors: CollectionValidationError[]\n): void {\n if (typeof property !== \"object\" || property === null) {\n errors.push({\n path,\n message: \"Property must be an object\"\n });\n return;\n }\n\n // Check type\n if (!property.type) {\n errors.push({\n path: `${path}.type`,\n message: \"Required field is missing\"\n });\n } else if (!VALID_DATA_TYPES.includes(property.type as DataType)) {\n errors.push({\n path: `${path}.type`,\n message: `Invalid value \"${property.type}\", expected one of: ${VALID_DATA_TYPES.join(\", \")}`\n });\n }\n\n // Validate name if present\n if (property.name !== undefined && typeof property.name !== \"string\") {\n errors.push({\n path: `${path}.name`,\n message: \"Must be a string\"\n });\n }\n\n // Validate array \"of\" property\n if (property.type === \"array\") {\n if (property.of) {\n if (Array.isArray(property.of)) {\n property.of.forEach((ofProp: Record<string, unknown>, index: number) => {\n validateProperty(ofProp, `${path}.of[${index}]`, errors);\n });\n } else {\n validateProperty(property.of as Record<string, unknown>, `${path}.of`, errors);\n }\n }\n // oneOf validation\n if (property.oneOf) {\n if (typeof property.oneOf !== \"object\") {\n errors.push({\n path: `${path}.oneOf`,\n message: \"Must be an object\"\n });\n } else if ((property.oneOf as Record<string, unknown>).properties) {\n validateProperties((property.oneOf as Record<string, unknown>).properties as Record<string, unknown>, `${path}.oneOf.properties`, errors);\n }\n }\n }\n\n // Validate map properties\n if (property.type === \"map\" && property.properties) {\n validateProperties(property.properties as Record<string, unknown>, `${path}.properties`, errors);\n }\n\n // Validate reference path\n if (property.type === \"reference\") {\n if (property.path !== undefined && typeof property.path !== \"string\") {\n errors.push({\n path: `${path}.path`,\n message: \"Must be a string\"\n });\n }\n }\n\n // Validate relation property\n if (property.type === \"relation\") {\n const link = property.relation as Record<string, unknown> | undefined;\n if (link !== undefined) {\n const KINDS = [\"belongsTo\", \"hasOne\", \"hasMany\", \"manyToMany\", \"via\"];\n if (typeof link.kind !== \"string\" || !KINDS.includes(link.kind)) {\n errors.push({\n path: `${path}.relation.kind`,\n message: `Must be one of ${KINDS.join(\", \")}`\n });\n }\n\n if (link.target !== undefined && typeof link.target !== \"string\" && typeof link.target !== \"function\") {\n errors.push({\n path: `${path}.relation.target`,\n message: \"Must be a collection slug or a thunk returning a collection\"\n });\n }\n\n // Each kind admits exactly one link field. Anything else on it is\n // a leftover from another shape and would previously have been\n // silently honoured by whichever consumer read it first.\n const allowedByKind: Record<string, string[]> = {\n belongsTo: [\"localKey\"],\n hasOne: [\"foreignKeyOnTarget\", \"sourceKey\"],\n hasMany: [\"foreignKeyOnTarget\", \"sourceKey\"],\n manyToMany: [\"through\"],\n via: [\"joinPath\", \"cardinality\"]\n };\n const linkFields = [\"localKey\", \"foreignKeyOnTarget\", \"sourceKey\", \"through\", \"joinPath\", \"cardinality\"];\n const allowed = allowedByKind[String(link.kind)] ?? [];\n for (const field of linkFields) {\n if (link[field] !== undefined && !allowed.includes(field)) {\n errors.push({\n path: `${path}.relation.${field}`,\n message: `Not valid on a \"${String(link.kind)}\" relation`\n });\n }\n }\n\n if (link.kind === \"via\" && !Array.isArray(link.joinPath)) {\n errors.push({\n path: `${path}.relation.joinPath`,\n message: \"A `via` relation requires a joinPath array\"\n });\n }\n }\n }\n\n // Validate vector property\n if (property.type === \"vector\") {\n if (property.dimensions !== undefined && (typeof property.dimensions !== \"number\" || isNaN(property.dimensions) || property.dimensions <= 0)) {\n errors.push({\n path: `${path}.dimensions`,\n message: \"Must be a positive number\"\n });\n }\n }\n\n // Validate storage config for string\n if (property.type === \"string\" && property.storage) {\n if (typeof property.storage !== \"object\") {\n errors.push({\n path: `${path}.storage`,\n message: \"Must be an object\"\n });\n }\n }\n\n // Validate enum if present\n if (property.enum !== undefined) {\n if (!Array.isArray(property.enum) && typeof property.enum !== \"object\") {\n errors.push({\n path: `${path}.enum`,\n message: \"Must be an array or object\"\n });\n }\n }\n}\n\n/**\n * Validates a properties object (collection of property definitions)\n */\nfunction validateProperties(\n properties: Record<string, unknown>,\n path: string,\n errors: CollectionValidationError[]\n): void {\n if (typeof properties !== \"object\" || properties === null) {\n errors.push({\n path,\n message: \"Must be an object\"\n });\n return;\n }\n\n for (const [key, property] of Object.entries(properties)) {\n validateProperty(property as Record<string, unknown>, `${path}.${key}`, errors);\n }\n}\n\n/**\n * Validates optional collection fields\n */\nfunction validateOptionalFields(\n collection: Record<string, unknown>,\n errors: CollectionValidationError[]\n): void {\n // String fields\n const stringFields = [\n \"singularName\",\n \"description\",\n \"group\",\n \"databaseId\"\n ];\n for (const field of stringFields) {\n if (collection[field] !== undefined && typeof collection[field] !== \"string\") {\n errors.push({\n path: field,\n message: \"Must be a string\"\n });\n }\n }\n\n // Boolean fields\n const booleanFields = [\n\n \"selectionEnabled\",\n \"inlineEditing\",\n \"hideFromNavigation\",\n \"hideIdFromForm\",\n \"hideIdFromCollection\",\n \"formAutoSave\",\n \"alwaysApplyDefaultValues\",\n \"includeJsonView\",\n \"history\"\n ];\n for (const field of booleanFields) {\n if (collection[field] !== undefined && typeof collection[field] !== \"boolean\") {\n errors.push({\n path: field,\n message: \"Must be a boolean\"\n });\n }\n }\n\n // Icon can be string or object (React node)\n if (collection.icon !== undefined &&\n typeof collection.icon !== \"string\" &&\n typeof collection.icon !== \"object\") {\n errors.push({\n path: \"icon\",\n message: \"Must be a string (icon key) or object\"\n });\n }\n\n // propertiesOrder must be array of strings\n if (collection.propertiesOrder !== undefined) {\n if (!Array.isArray(collection.propertiesOrder)) {\n errors.push({\n path: \"propertiesOrder\",\n message: \"Must be an array of strings\"\n });\n } else if (!collection.propertiesOrder.every((item: unknown) => typeof item === \"string\")) {\n errors.push({\n path: \"propertiesOrder\",\n message: \"All items must be strings\"\n });\n }\n }\n\n // subcollections must be array\n if (collection.subcollections !== undefined) {\n if (!Array.isArray(collection.subcollections)) {\n errors.push({\n path: \"subcollections\",\n message: \"Must be an array\"\n });\n } else {\n collection.subcollections.forEach((sub: Record<string, unknown>, index: number) => {\n const subErrors: CollectionValidationError[] = [];\n validateCollectionObject(sub, subErrors);\n subErrors.forEach(err => {\n errors.push({\n path: `subcollections[${index}].${err.path}`,\n message: err.message\n });\n });\n });\n }\n }\n\n // defaultViewMode validation\n const validViewModes = [\"table\", \"cards\", \"kanban\"];\n if (collection.defaultViewMode !== undefined) {\n if (!validViewModes.includes(collection.defaultViewMode as string)) {\n errors.push({\n path: \"defaultViewMode\",\n message: `Invalid value, expected one of: ${validViewModes.join(\", \")}`\n });\n }\n }\n\n // kanban config validation\n if (collection.kanban !== undefined) {\n if (typeof collection.kanban !== \"object\" || collection.kanban === null) {\n errors.push({\n path: \"kanban\",\n message: \"Must be an object\"\n });\n } else if ((collection.kanban as Record<string, unknown>).columnProperty !== undefined &&\n typeof (collection.kanban as Record<string, unknown>).columnProperty !== \"string\") {\n errors.push({\n path: \"kanban.columnProperty\",\n message: \"Must be a string\"\n });\n }\n }\n}\n\n/**\n * Validates a collection object\n */\nfunction validateCollectionObject(\n collection: Record<string, unknown>,\n errors: CollectionValidationError[]\n): void {\n // Required fields\n if (!collection.id) {\n errors.push({\n path: \"id\",\n message: \"Required field is missing\"\n });\n } else if (typeof collection.id !== \"string\") {\n errors.push({\n path: \"id\",\n message: \"Must be a string\"\n });\n }\n\n if (!collection.name) {\n errors.push({\n path: \"name\",\n message: \"Required field is missing\"\n });\n } else if (typeof collection.name !== \"string\") {\n errors.push({\n path: \"name\",\n message: \"Must be a string\"\n });\n }\n\n if (!collection.path) {\n errors.push({\n path: \"path\",\n message: \"Required field is missing\"\n });\n } else if (typeof collection.path !== \"string\") {\n errors.push({\n path: \"path\",\n message: \"Must be a string\"\n });\n }\n\n // Properties validation\n if (collection.properties !== undefined) {\n validateProperties(collection.properties as Record<string, unknown>, \"properties\", errors);\n }\n\n // Optional fields\n validateOptionalFields(collection, errors);\n}\n\n/**\n * Validates a JSON string representing a collection configuration.\n * Returns detailed validation errors if the JSON is invalid or doesn't match\n * the expected collection schema.\n */\nexport function validateCollectionJson(jsonString: string): CollectionValidationResult {\n const errors: CollectionValidationError[] = [];\n\n // Try to parse JSON\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(jsonString);\n } catch (e: unknown) {\n // Try to extract line/column info from the error\n const message_ = e instanceof Error ? e.message : String(e);\n const match = message_.match(/position (\\d+)/);\n let message = \"Invalid JSON syntax\";\n if (match) {\n const position = parseInt(match[1], 10);\n const lines = jsonString.substring(0, position).split(\"\\n\");\n const line = lines.length;\n const column = lines[lines.length - 1].length + 1;\n message = `Invalid JSON syntax at line ${line}, column ${column}: ${message_}`;\n } else {\n message = `Invalid JSON syntax: ${message_}`;\n }\n return {\n valid: false,\n errors: [{\n path: \"\",\n message\n }]\n };\n }\n\n // Validate collection structure\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return {\n valid: false,\n errors: [{\n path: \"\",\n message: \"Collection must be an object\"\n }]\n };\n }\n\n validateCollectionObject(parsed as Record<string, unknown>, errors);\n\n return {\n valid: errors.length === 0,\n errors,\n collection: errors.length === 0 ? parsed as AdminCollection : undefined\n };\n}\n"],"mappings":";;;;AAMA,IAAM,mBAAmB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACJ;;;;AAsBA,SAAS,iBACL,UACA,MACA,QACI;CACJ,IAAI,OAAO,aAAa,YAAY,aAAa,MAAM;EACnD,OAAO,KAAK;GACR;GACA,SAAS;EACb,CAAC;EACD;CACJ;CAGA,IAAI,CAAC,SAAS,MACV,OAAO,KAAK;EACR,MAAM,GAAG,KAAK;EACd,SAAS;CACb,CAAC;MACE,IAAI,CAAC,iBAAiB,SAAS,SAAS,IAAgB,GAC3D,OAAO,KAAK;EACR,MAAM,GAAG,KAAK;EACd,SAAS,kBAAkB,SAAS,KAAK,sBAAsB,iBAAiB,KAAK,IAAI;CAC7F,CAAC;CAIL,IAAI,SAAS,SAAS,KAAA,KAAa,OAAO,SAAS,SAAS,UACxD,OAAO,KAAK;EACR,MAAM,GAAG,KAAK;EACd,SAAS;CACb,CAAC;CAIL,IAAI,SAAS,SAAS,SAAS;EAC3B,IAAI,SAAS,IACT,IAAI,MAAM,QAAQ,SAAS,E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G,MAAM,OAE2B,WAD/B,MAAM,MAAM,SAAS,EAAE,CAAC,SAAS,EACgB,IAAI;EACxE,OACI,UAAU,wBAAwB;EAEtC,OAAO;GACH,OAAO;GACP,QAAQ,CAAC;IACL,MAAM;IACN;GACJ,CAAC;EACL;CACJ;CAGA,IAAI,OAAO,WAAW,YAAY,WAAW,QAAQ,MAAM,QAAQ,MAAM,GACrE,OAAO;EACH,OAAO;EACP,QAAQ,CAAC;GACL,MAAM;GACN,SAAS;EACb,CAAC;CACL;CAGJ,yBAAyB,QAAmC,MAAM;CAElE,OAAO;EACH,OAAO,OAAO,WAAW;EACzB;EACA,YAAY,OAAO,WAAW,IAAI,SAA4B,KAAA;CAClE;AACJ"}
|
|
@@ -20,10 +20,11 @@ export type CollectionPanelProps = CollectionPanelOptions & ({
|
|
|
20
20
|
/**
|
|
21
21
|
* The collection to display: its name (`"orders"`), registered with
|
|
22
22
|
* `<RebaseCMS>` or a {@link CollectionsProvider} above, or the collection
|
|
23
|
-
* as a value — a `
|
|
24
|
-
* Handed over as a value where no CMS
|
|
25
|
-
*
|
|
26
|
-
*
|
|
23
|
+
* as a value — a `defineFirestoreCollection`, or a table's collection you
|
|
24
|
+
* built (`collectionFromTable`). Handed over as a value where no CMS
|
|
25
|
+
* navigation is mounted above, the panel brings its own
|
|
26
|
+
* {@link CollectionsProvider} for it, holding that collection alone, so
|
|
27
|
+
* it works anywhere under `<Rebase>` and a router.
|
|
27
28
|
*/
|
|
28
29
|
collection: AdminCollection | string;
|
|
29
30
|
/**
|
|
@@ -128,11 +129,11 @@ export type CollectionPanelOptions = {
|
|
|
128
129
|
* are filled from, earlier ones first. A place none of them fills
|
|
129
130
|
* stays empty.
|
|
130
131
|
*
|
|
131
|
-
* For this panel it wins over
|
|
132
|
-
* user saved,
|
|
133
|
-
* the user drags still persist; the order is yours,
|
|
134
|
-
* dragged. A
|
|
135
|
-
* custom view is handed the whole collection.
|
|
132
|
+
* For this panel it wins over the table's `fieldOrder` and `listFields`
|
|
133
|
+
* (`customizeTable`), the column order the user saved, and what the cards
|
|
134
|
+
* infer. Column widths the user drags still persist; the order is yours,
|
|
135
|
+
* so columns are not dragged. A field customized `hidden` stays hidden,
|
|
136
|
+
* and a custom view is handed the whole collection.
|
|
136
137
|
*/
|
|
137
138
|
fields?: string[];
|
|
138
139
|
/**
|
|
@@ -13,9 +13,11 @@ import { useContext, useMemo, useRef, useState } from "react";
|
|
|
13
13
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
14
14
|
import { deepEqual } from "fast-equals";
|
|
15
15
|
import { CircularProgressCenter, Typography, cls } from "@rebasepro/ui";
|
|
16
|
-
import { warnDeprecated } from "@rebasepro/common";
|
|
17
16
|
import { CollectionScopeProvider, useComponentOverride } from "@rebasepro/app";
|
|
17
|
+
import { warnDeprecated } from "@rebasepro/common";
|
|
18
18
|
//#region src/components/CollectionPanel.tsx
|
|
19
|
+
/** A collection handed over as a value is shown on its own: no served table beside it. */
|
|
20
|
+
var NO_TABLES = [];
|
|
19
21
|
/**
|
|
20
22
|
* A high-level, reusable wrapper for embedding a Rebase collection view
|
|
21
23
|
* inside custom pages (dashboards, home pages, entity detail views, etc.).
|
|
@@ -113,7 +115,8 @@ function CollectionPanel(rawProps) {
|
|
|
113
115
|
path
|
|
114
116
|
});
|
|
115
117
|
if (needsOwnScope) return /* @__PURE__ */ jsx(CollectionsProvider, {
|
|
116
|
-
|
|
118
|
+
externalCollections: ownCollections,
|
|
119
|
+
tables: NO_TABLES,
|
|
117
120
|
children: /* @__PURE__ */ jsx(CollectionPanelInScope, { ...props })
|
|
118
121
|
});
|
|
119
122
|
return /* @__PURE__ */ jsx(CollectionPanelInScope, { ...props });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CollectionPanel.js","names":[],"sources":["../../src/components/CollectionPanel.tsx"],"sourcesContent":["\nimport type { ViewMode, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { FilterValues } from \"@rebasepro/types\";\nimport React, { useContext, useMemo, useRef, useState } from \"react\";\nimport { deepEqual } from \"fast-equals\";\nimport { CollectionViewBinding } from \"./CollectionViewBinding/CollectionViewBinding\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useNavigationStateController } from \"../hooks/navigation/contexts/NavigationStateContext\";\nimport { useUrlController } from \"../hooks/navigation/contexts/UrlContext\";\nimport { CircularProgressCenter, cls, Typography } from \"@rebasepro/ui\";\nimport { useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { CollectionsScopeContext, isRegistered } from \"./CollectionsScopeContext\";\nimport { CollectionsProvider } from \"./CollectionsProvider\";\nimport { collectionPropOf } from \"./collection_prop\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { ROW_ACTIONS_FIELD, RowActionsContext, type RowActionsRenderer } from \"./CollectionViewBinding/RowActions\";\nimport { ViewTitleReportContext } from \"./CollectionViewBinding/CollectionViewContent\";\nimport {\n CollectionSearchBar,\n CollectionToolbar,\n CollectionViewModeToggle\n} from \"./CollectionViewBinding/CollectionToolbar\";\nimport { CollectionAddButton } from \"./CollectionViewBinding/CollectionAddButton\";\n\n/**\n * Props for the {@link CollectionPanel} component.\n *\n * This is a high-level, consumer-friendly wrapper around {@link CollectionViewBinding}\n * designed for embedding collection views inside custom pages (home pages,\n * dashboards, entity detail views, etc.).\n *\n * Name the collection — `collection=\"orders\"`, one registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above — or hand it over as a\n * value, `collection={ordersCollection}`. All other props are optional overrides that take precedence\n * over the collection's default configuration.\n *\n * @group Components\n */\nexport type CollectionPanelProps = CollectionPanelOptions & ({\n /**\n * The collection to display: its name (`\"orders\"`), registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above, or the collection\n * as a value — a `defineCollection` config or a resolved collection.\n * Handed over as a value where no CMS navigation is mounted above, the\n * panel brings its own {@link CollectionsProvider} for it, so it works\n * anywhere under `<Rebase>` and a router.\n */\n collection: AdminCollection | string;\n /**\n * Where the rows live, where that is not the collection's name: a\n * subcollection's full path, `posts/p1/comments`.\n */\n path?: string;\n} | {\n /**\n * @deprecated Name the collection with `collection`:\n * `<CollectionPanel collection=\"orders\"/>`. It warns once.\n */\n path: string;\n collection?: undefined;\n});\n\n/**\n * The display options of a {@link CollectionPanel}.\n *\n * @group Components\n */\nexport type CollectionPanelOptions = {\n\n /**\n * Optional title displayed above the collection.\n * Set to `false` to hide the title entirely.\n * Defaults to the collection's `name`.\n */\n title?: string | false;\n\n /**\n * The view mode the panel opens in, over the collection's default, the\n * one in the URL and the one the person last picked. They can still\n * switch.\n */\n viewMode?: ViewMode;\n\n /**\n * @deprecated Use {@link orderBy}: `orderBy=\"field:desc\"`. It warns once.\n */\n sort?: [string, \"asc\" | \"desc\"];\n\n /**\n * The order the rows open in, as `\"field:desc\"` or `[\"field\", \"desc\"]`.\n * The person can still sort by another column.\n */\n orderBy?: `${string}:asc` | `${string}:desc` | readonly [string, \"asc\" | \"desc\"];\n\n /**\n * Your own JSX on every row, card and kanban card — an \"Approve\" button,\n * a \"Ship\" — handed the row as the server sends it and its id:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" rowActions={(row, id) =>\n * <Button size=\"small\" onClick={() => update(\"orders\", id, { status: \"shipped\" })}>Ship</Button>}/>\n * ```\n *\n * In the table it is the last column; on a list row, a card and a kanban\n * card it sits beside the collection's own actions. A click on it does\n * not open the record.\n */\n rowActions?: RowActionsRenderer;\n\n /**\n * Maximum number of entities to display.\n */\n limit?: number;\n\n /**\n * Which rows the panel holds, as `useRows`' `where` takes it:\n * `{ status: [\"==\", \"pending\"] }`. The person's own filters on other\n * fields combine with it (AND); these fields cannot be changed or\n * cleared from the toolbar. It follows the prop, so a tab bar or a chart\n * click can drive it from state. Over the collection's `fixedFilter`,\n * field by field.\n */\n where?: FilterValues<string>;\n\n /**\n * Whether to sync filter/sort state with URL query params.\n * Defaults to `false` (embedded panels shouldn't hijack the URL).\n */\n updateUrl?: boolean;\n\n /**\n * Override the entity open mode when clicking a entity.\n */\n openEntityMode?: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n\n /**\n * The ids of the rows drawn as selected — the one a page shows beside\n * the list, say. `[]` draws none. Without it the panel highlights the\n * row last opened. Compared as strings, so an integer key's `5` and\n * `\"5\"` are one row.\n */\n highlightedIds?: (string | number)[];\n\n /**\n * Additional CSS class name for the container.\n */\n className?: string;\n\n /**\n * Any additional collection-level overrides (e.g. `previewProperties`,\n * `enabledViews`, `entityActions`, `defaultFilter`, etc.).\n */\n collectionOverrides?: Partial<AdminCollection>;\n\n /**\n * The properties the panel shows, in this order; the ones it leaves out\n * are not drawn.\n *\n * - Table: the columns.\n * - List, cards, kanban cards: what the row's or card's places — title,\n * image, subtitle, status, date, relation chips, the list's columns —\n * are filled from, earlier ones first. A place none of them fills\n * stays empty.\n *\n * For this panel it wins over `propertiesOrder`, the column order the\n * user saved, `listProperties` and what the cards infer. Column widths\n * the user drags still persist; the order is yours, so columns are not\n * dragged. A property hidden from collections stays hidden, and a\n * custom view is handed the whole collection.\n */\n fields?: string[];\n\n /**\n * The toolbar above the rows.\n *\n * - `\"full\"`, the default: the collection page's own toolbar.\n * - `\"compact\"`: the view-mode switch, search, and New where the person\n * may create.\n * - `\"none\"`: no toolbar.\n *\n * Or compose one from its pieces:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" toolbar={\n * <CollectionToolbar\n * start={<CollectionFiltersButton/>}\n * end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n * }/>\n * ```\n */\n toolbar?: \"full\" | \"compact\" | \"none\" | React.ReactElement;\n\n /**\n * Called with the row and its id when one is clicked, instead of the\n * panel opening it. Without it the record opens as `openEntityMode` says.\n *\n * The row is the one the server sends — the shape `useRows`, `useRow`\n * and `FieldValue` take: ISO date strings (`YYYY-MM-DD` for a date-only\n * column), and a belongsTo relation as its foreign key, under that key's\n * own name. It is exactly the record's columns; the id is the string the\n * admin addresses the record by — its primary key, a composite one's\n * parts joined by `:::` — which `highlightedIds` and\n * `useSidePanel().open` take.\n *\n * ```tsx\n * const [selectedId, setSelectedId] = useState<string>();\n * <CollectionPanel collection=\"orders\"\n * onRowClick={(row, id) => setSelectedId(id)}\n * highlightedIds={selectedId ? [selectedId] : []}/>\n * ```\n */\n onRowClick?: (row: Record<string, unknown>, id: string) => void;\n};\n\n/**\n * A high-level, reusable wrapper for embedding a Rebase collection view\n * inside custom pages (dashboards, home pages, entity detail views, etc.).\n *\n * Usage inside the CMS, by registered slug:\n * ```tsx\n * import { CollectionPanel } from \"@rebasepro/cms\";\n *\n * function MyDashboard() {\n * return (\n * <div>\n * <CollectionPanel collection=\"tasks\" title=\"Pending Tasks\" />\n * <CollectionPanel\n * collection=\"clients\"\n * viewMode=\"table\"\n * collectionOverrides={{\n * defaultFilter: { status: [\"!=\", \"completed\"] }\n * }}\n * />\n * </div>\n * );\n * }\n * ```\n *\n * Usage in a page of your own app, with the collection as a value — no\n * `<RebaseCMS>`, `<RebaseNavigation>` or `<RebaseShell>` needed, and any\n * React Router router will do. Records open in a side panel over the page:\n * ```tsx\n * <Rebase client={client} authController={authController}>\n * <BrowserRouter>\n * <CollectionPanel collection={postsCollection} />\n * </BrowserRouter>\n * </Rebase>\n * ```\n *\n * @group Components\n */\nfunction CollectionPanelInner({\n mergedCollection,\n overrides,\n path,\n title,\n viewMode,\n updateUrl,\n highlightedIds,\n fields,\n toolbar,\n onRowClick,\n rowActions,\n className\n}: ScopedPanelProps & { mergedCollection: AdminCollection; overrides: Partial<AdminCollection> }) {\n const ResolvedCollectionView = useComponentOverride(\"Collection.View\", CollectionViewBinding);\n const toolbarNode = toolbarOf(toolbar);\n const rowActionsScope = useMemo(\n () => rowActions ? { path: path ?? mergedCollection.slug, render: rowActions } : null,\n [path, mergedCollection.slug, rowActions]);\n // The list draws its title as its own heading: there the panel draws none,\n // and hands the view its title instead.\n const [viewDrawsTitle, setViewDrawsTitle] = useState(false);\n const titleReport = useMemo(\n () => ({ path: path ?? mergedCollection.slug, onViewDrawsTitle: setViewDrawsTitle }),\n [path, mergedCollection.slug]);\n\n // A column, so a height or a max-height on the panel reaches the view:\n // it sizes to its rows up to that, then scrolls inside.\n return (\n <div className={cls(\"flex flex-col min-h-0\", className)}>\n {title !== false && !viewDrawsTitle && (\n <Typography\n variant=\"subtitle2\"\n className=\"font-semibold mb-2 text-surface-700 dark:text-surface-300\"\n >\n {title ?? mergedCollection.name}\n </Typography>\n )}\n <RowActionsContext.Provider value={rowActionsScope}>\n <ViewTitleReportContext.Provider value={titleReport}>\n <ResolvedCollectionView\n {...mergedCollection}\n collectionOverrides={overrides}\n {...(highlightedIds !== undefined && { highlightedIds })}\n {...(viewMode && { viewMode })}\n {...(fields && { fields })}\n {...(toolbarNode !== undefined && { toolbar: toolbarNode })}\n {...(onRowClick && { onRowClick })}\n {...(title !== undefined && { title })}\n path={path}\n updateUrl={updateUrl}\n />\n </ViewTitleReportContext.Provider>\n </RowActionsContext.Provider>\n </div>\n );\n}\n\nexport function CollectionPanel(rawProps: CollectionPanelProps) {\n const inScope = useContext(CollectionsScopeContext);\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const { collection, path } = collectionPropOf(rawProps.collection, rawProps.path);\n if (rawProps.collection === undefined) {\n warnDeprecated(\"CollectionPanel.path\", \"`<CollectionPanel path=\\\"…\\\"/>` names its collection with `collection` now: `<CollectionPanel collection=\\\"…\\\"/>`.\");\n }\n const props: ScopedPanelProps = { ...rawProps, collection, path };\n const ownCollections = useMemo(() => collection ? [collection] : [], [collection]);\n\n // A collection handed over as a value brings its own scope where there is\n // none above — or where the one above has settled without it, since a\n // collection the data layer does not know gives its rows no address.\n const needsOwnScope = collection !== undefined && (!inScope\n || (!navigationState.loading && !isRegistered(collectionRegistry.collections, path)));\n // Named by path with no scope above to look it up in: nothing will ever\n // register it, so it is not found rather than loading.\n if (!inScope && collection === undefined) return <CollectionNotFound className={props.className} path={path}/>;\n if (needsOwnScope) {\n return (\n <CollectionsProvider collections={ownCollections}>\n <CollectionPanelInScope {...props}/>\n </CollectionsProvider>\n );\n }\n return <CollectionPanelInScope {...props}/>;\n}\n\n/** A panel's props once its `collection` is a value or absent, and its `path` known. */\ntype ScopedPanelProps = CollectionPanelOptions & { collection?: AdminCollection; path: string };\n\nfunction CollectionPanelInScope(props: ScopedPanelProps) {\n const {\n viewMode,\n sort,\n limit,\n openEntityMode,\n className,\n collectionOverrides,\n where,\n orderBy,\n rowActions,\n collection: collectionProp\n } = props;\n if (sort !== undefined) warnDeprecated(\"CollectionPanel.sort\", \"`CollectionPanel`'s `sort` is `orderBy` now: `orderBy=\\\"field:desc\\\"`.\");\n const order = orderBy ? orderByTuple(orderBy) : sort;\n const orderKey = order ? order.join(\":\") : undefined;\n // Whether, not which: the column reads the renderer through context, so a\n // new function each render leaves the collection alone.\n const hasRowActions = rowActions !== undefined;\n const path = props.path ?? collectionProp?.slug ?? \"\";\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const urlController = useUrlController();\n // The registry's copy, also for a collection handed over as a value: it\n // carries the user's saved overrides and the plugins' changes. Not asked\n // before it has been filled.\n const lookUp = collectionRegistry.initialised || !navigationState.loading;\n const baseCollection = useMemo(\n () => lookUp ? collectionRegistry.getCollection(path) : undefined,\n [lookUp, collectionRegistry, path]);\n const routesMounted = urlController.routesMounted !== false;\n // Compared by value: it is an inline object at most call sites, and a new\n // one on every render would rebuild the overrides each time.\n const whereRef = useRef(where);\n if (!deepEqual(whereRef.current, where)) whereRef.current = where;\n const stableWhere = whereRef.current;\n\n // What this panel changes about the collection: the shorthand props over\n // the explicit overrides. Handed to the view as overrides, which it applies\n // over the registered collection it draws.\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n const merged: Partial<AdminCollection> = {\n ...(collectionOverrides ?? {}),\n ...(viewMode && { defaultViewMode: viewMode }),\n ...(order && { sort: order }),\n ...(limit && { pagination: limit }),\n ...(openEntityMode && { openEntityMode }),\n ...(stableWhere && {\n fixedFilter: { ...(baseCollection?.fixedFilter ?? {}), ...(collectionOverrides?.fixedFilter ?? {}), ...stableWhere }\n }),\n ...(hasRowActions && {\n additionalFields: [...(collectionOverrides?.additionalFields ?? baseCollection?.additionalFields ?? []), ROW_ACTIONS_FIELD]\n })\n };\n // Without CMS routes a record has no page of its own, nor a split\n // beside the list that a URL selects: it opens over the page.\n if (!routesMounted && (merged.openEntityMode ?? baseCollection?.openEntityMode) !== \"dialog\") {\n return { ...merged, openEntityMode: \"side_panel\" };\n }\n return merged;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `order` by its key: `orderBy` is an inline tuple at most call sites.\n }, [baseCollection, collectionOverrides, viewMode, orderKey, limit, openEntityMode, stableWhere, hasRowActions, routesMounted]);\n\n const mergedCollection = useMemo(\n () => baseCollection ? { ...baseCollection, ...overrides } as AdminCollection : undefined,\n [baseCollection, overrides]);\n\n if (!mergedCollection) {\n if (navigationState.loading) {\n return <div className={className}><CircularProgressCenter/></div>;\n }\n return <CollectionNotFound className={className} path={path}/>;\n }\n\n const content = (\n <CollectionPanelInner\n {...props}\n path={path}\n mergedCollection={mergedCollection}\n overrides={overrides}\n />\n );\n\n return (\n <CollectionScopeProvider collection={mergedCollection}>\n {content}\n </CollectionScopeProvider>\n );\n}\n\nfunction CollectionNotFound({ className, path }: { className?: string, path: string }) {\n return (\n <div className={className}>\n <Typography variant=\"body2\" color=\"secondary\">\n Collection "{path}" not found.\n </Typography>\n </div>\n );\n}\n\n/** `\"field:desc\"` or `[\"field\", \"desc\"]`, as the collection's `sort` takes it. */\nfunction orderByTuple(orderBy: NonNullable<CollectionPanelOptions[\"orderBy\"]>): [string, \"asc\" | \"desc\"] {\n if (typeof orderBy !== \"string\") return [orderBy[0], orderBy[1]];\n const at = orderBy.lastIndexOf(\":\");\n return [orderBy.slice(0, at), orderBy.slice(at + 1) as \"asc\" | \"desc\"];\n}\n\n/** The node a `toolbar` keyword stands for; a composed toolbar as it is. */\nfunction toolbarOf(toolbar: CollectionPanelOptions[\"toolbar\"]): React.ReactNode {\n if (toolbar === \"full\") return undefined;\n if (toolbar === \"none\") return null;\n if (toolbar === \"compact\") return COMPACT_TOOLBAR;\n return toolbar;\n}\n\nconst COMPACT_TOOLBAR = (\n <CollectionToolbar\n start={<CollectionViewModeToggle/>}\n end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2PA,SAAS,qBAAqB,EAC1B,kBACA,WACA,MACA,OACA,UACA,WACA,gBACA,QACA,SACA,YACA,YACA,aAC8F;CAC9F,MAAM,yBAAyB,qBAAqB,mBAAmB,qBAAqB;CAC5F,MAAM,cAAc,UAAU,OAAO;CACrC,MAAM,kBAAkB,cACd,aAAa;EAAE,MAAM,QAAQ,iBAAiB;EAAM,QAAQ;CAAW,IAAI,MACjF;EAAC;EAAM,iBAAiB;EAAM;CAAU,CAAC;CAG7C,MAAM,CAAC,gBAAgB,qBAAqB,SAAS,KAAK;CAC1D,MAAM,cAAc,eACT;EAAE,MAAM,QAAQ,iBAAiB;EAAM,kBAAkB;CAAkB,IAClF,CAAC,MAAM,iBAAiB,IAAI,CAAC;CAIjC,OACI,qBAAC,OAAD;EAAK,WAAW,IAAI,yBAAyB,SAAS;YAAtD,CACK,UAAU,SAAS,CAAC,kBACjB,oBAAC,YAAD;GACI,SAAQ;GACR,WAAU;aAET,SAAS,iBAAiB;EACnB,CAAA,GAEhB,oBAAC,kBAAkB,UAAnB;GAA4B,OAAO;aAC/B,oBAAC,uBAAuB,UAAxB;IAAiC,OAAO;cACpC,oBAAC,wBAAD;KACI,GAAI;KACJ,qBAAqB;KACrB,GAAK,mBAAmB,KAAA,KAAa,EAAE,eAAe;KACtD,GAAK,YAAY,EAAE,SAAS;KAC5B,GAAK,UAAU,EAAE,OAAO;KACxB,GAAK,gBAAgB,KAAA,KAAa,EAAE,SAAS,YAAY;KACzD,GAAK,cAAc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AAA;EAAM,CAAA;EAEpE,OAAO,oBAAC,oBAAD;GAA+B;GAAiB;EAAM,CAAA;CACjE;CAWA,OACI,oBAAC,yBAAD;EAAyB,YAAY;YATrC,oBAAC,sBAAD;GACI,GAAI;GACE;GACY;GACP;EACd,CAKI;CACoB,CAAA;AAEjC;AAEA,SAAS,mBAAmB,EAAE,WAAW,QAA8C;CACnF,OACI,oBAAC,OAAD;EAAgB;YACZ,qBAAC,YAAD;GAAY,SAAQ;GAAQ,OAAM;aAAlC;IAA8C;IACxB;IAAK;GACf;;CACX,CAAA;AAEb;;AAGA,SAAS,aAAa,SAAmF;CACrG,IAAI,OAAO,YAAY,UAAU,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE;CAC/D,MAAM,KAAK,QAAQ,YAAY,GAAG;CAClC,OAAO,CAAC,QAAQ,MAAM,GAAG,EAAE,GAAG,QAAQ,MAAM,KAAK,CAAC,CAAmB;AACzE;;AAGA,SAAS,UAAU,SAA6D;CAC5E,IAAI,YAAY,QAAQ,OAAO,KAAA;CAC/B,IAAI,YAAY,QAAQ,OAAO;CAC/B,IAAI,YAAY,WAAW,OAAO;CAClC,OAAO;AACX;AAEA,IAAM,kBACF,oBAAC,mBAAD;CACI,OAAO,oBAAC,0BAAD,CAA0B,CAAA;CACjC,KAAK,qBAAA,UAAA,EAAA,UAAA,CAAE,oBAAC,qBAAD,CAAqB,CAAA,GAAC,oBAAC,qBAAD,CAAqB,CAAA,CAAG,EAAA,CAAA;AAAG,CAAA"}
|
|
1
|
+
{"version":3,"file":"CollectionPanel.js","names":[],"sources":["../../src/components/CollectionPanel.tsx"],"sourcesContent":["\nimport type { ViewMode, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { FilterValues } from \"@rebasepro/types\";\nimport React, { useContext, useMemo, useRef, useState } from \"react\";\nimport { deepEqual } from \"fast-equals\";\nimport { CollectionViewBinding } from \"./CollectionViewBinding/CollectionViewBinding\";\nimport { useCollectionRegistryController } from \"../hooks/navigation/contexts/CollectionRegistryContext\";\nimport { useNavigationStateController } from \"../hooks/navigation/contexts/NavigationStateContext\";\nimport { useUrlController } from \"../hooks/navigation/contexts/UrlContext\";\nimport { CircularProgressCenter, cls, Typography } from \"@rebasepro/ui\";\nimport { useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { CollectionsScopeContext, isRegistered } from \"./CollectionsScopeContext\";\nimport { CollectionsProvider } from \"./CollectionsProvider\";\nimport { collectionPropOf } from \"./collection_prop\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport { ROW_ACTIONS_FIELD, RowActionsContext, type RowActionsRenderer } from \"./CollectionViewBinding/RowActions\";\nimport { ViewTitleReportContext } from \"./CollectionViewBinding/CollectionViewContent\";\nimport {\n CollectionSearchBar,\n CollectionToolbar,\n CollectionViewModeToggle\n} from \"./CollectionViewBinding/CollectionToolbar\";\nimport { CollectionAddButton } from \"./CollectionViewBinding/CollectionAddButton\";\n\nimport type { TableDescriptor } from \"@rebasepro/types\";\n\n/** A collection handed over as a value is shown on its own: no served table beside it. */\nconst NO_TABLES: readonly TableDescriptor[] = [];\n\n/**\n * Props for the {@link CollectionPanel} component.\n *\n * This is a high-level, consumer-friendly wrapper around {@link CollectionViewBinding}\n * designed for embedding collection views inside custom pages (home pages,\n * dashboards, entity detail views, etc.).\n *\n * Name the collection — `collection=\"orders\"`, one registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above — or hand it over as a\n * value, `collection={ordersCollection}`. All other props are optional overrides that take precedence\n * over the collection's default configuration.\n *\n * @group Components\n */\nexport type CollectionPanelProps = CollectionPanelOptions & ({\n /**\n * The collection to display: its name (`\"orders\"`), registered with\n * `<RebaseCMS>` or a {@link CollectionsProvider} above, or the collection\n * as a value — a `defineFirestoreCollection`, or a table's collection you\n * built (`collectionFromTable`). Handed over as a value where no CMS\n * navigation is mounted above, the panel brings its own\n * {@link CollectionsProvider} for it, holding that collection alone, so\n * it works anywhere under `<Rebase>` and a router.\n */\n collection: AdminCollection | string;\n /**\n * Where the rows live, where that is not the collection's name: a\n * subcollection's full path, `posts/p1/comments`.\n */\n path?: string;\n} | {\n /**\n * @deprecated Name the collection with `collection`:\n * `<CollectionPanel collection=\"orders\"/>`. It warns once.\n */\n path: string;\n collection?: undefined;\n});\n\n/**\n * The display options of a {@link CollectionPanel}.\n *\n * @group Components\n */\nexport type CollectionPanelOptions = {\n\n /**\n * Optional title displayed above the collection.\n * Set to `false` to hide the title entirely.\n * Defaults to the collection's `name`.\n */\n title?: string | false;\n\n /**\n * The view mode the panel opens in, over the collection's default, the\n * one in the URL and the one the person last picked. They can still\n * switch.\n */\n viewMode?: ViewMode;\n\n /**\n * @deprecated Use {@link orderBy}: `orderBy=\"field:desc\"`. It warns once.\n */\n sort?: [string, \"asc\" | \"desc\"];\n\n /**\n * The order the rows open in, as `\"field:desc\"` or `[\"field\", \"desc\"]`.\n * The person can still sort by another column.\n */\n orderBy?: `${string}:asc` | `${string}:desc` | readonly [string, \"asc\" | \"desc\"];\n\n /**\n * Your own JSX on every row, card and kanban card — an \"Approve\" button,\n * a \"Ship\" — handed the row as the server sends it and its id:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" rowActions={(row, id) =>\n * <Button size=\"small\" onClick={() => update(\"orders\", id, { status: \"shipped\" })}>Ship</Button>}/>\n * ```\n *\n * In the table it is the last column; on a list row, a card and a kanban\n * card it sits beside the collection's own actions. A click on it does\n * not open the record.\n */\n rowActions?: RowActionsRenderer;\n\n /**\n * Maximum number of entities to display.\n */\n limit?: number;\n\n /**\n * Which rows the panel holds, as `useRows`' `where` takes it:\n * `{ status: [\"==\", \"pending\"] }`. The person's own filters on other\n * fields combine with it (AND); these fields cannot be changed or\n * cleared from the toolbar. It follows the prop, so a tab bar or a chart\n * click can drive it from state. Over the collection's `fixedFilter`,\n * field by field.\n */\n where?: FilterValues<string>;\n\n /**\n * Whether to sync filter/sort state with URL query params.\n * Defaults to `false` (embedded panels shouldn't hijack the URL).\n */\n updateUrl?: boolean;\n\n /**\n * Override the entity open mode when clicking a entity.\n */\n openEntityMode?: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n\n /**\n * The ids of the rows drawn as selected — the one a page shows beside\n * the list, say. `[]` draws none. Without it the panel highlights the\n * row last opened. Compared as strings, so an integer key's `5` and\n * `\"5\"` are one row.\n */\n highlightedIds?: (string | number)[];\n\n /**\n * Additional CSS class name for the container.\n */\n className?: string;\n\n /**\n * Any additional collection-level overrides (e.g. `previewProperties`,\n * `enabledViews`, `entityActions`, `defaultFilter`, etc.).\n */\n collectionOverrides?: Partial<AdminCollection>;\n\n /**\n * The properties the panel shows, in this order; the ones it leaves out\n * are not drawn.\n *\n * - Table: the columns.\n * - List, cards, kanban cards: what the row's or card's places — title,\n * image, subtitle, status, date, relation chips, the list's columns —\n * are filled from, earlier ones first. A place none of them fills\n * stays empty.\n *\n * For this panel it wins over the table's `fieldOrder` and `listFields`\n * (`customizeTable`), the column order the user saved, and what the cards\n * infer. Column widths the user drags still persist; the order is yours,\n * so columns are not dragged. A field customized `hidden` stays hidden,\n * and a custom view is handed the whole collection.\n */\n fields?: string[];\n\n /**\n * The toolbar above the rows.\n *\n * - `\"full\"`, the default: the collection page's own toolbar.\n * - `\"compact\"`: the view-mode switch, search, and New where the person\n * may create.\n * - `\"none\"`: no toolbar.\n *\n * Or compose one from its pieces:\n *\n * ```tsx\n * <CollectionPanel collection=\"orders\" toolbar={\n * <CollectionToolbar\n * start={<CollectionFiltersButton/>}\n * end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n * }/>\n * ```\n */\n toolbar?: \"full\" | \"compact\" | \"none\" | React.ReactElement;\n\n /**\n * Called with the row and its id when one is clicked, instead of the\n * panel opening it. Without it the record opens as `openEntityMode` says.\n *\n * The row is the one the server sends — the shape `useRows`, `useRow`\n * and `FieldValue` take: ISO date strings (`YYYY-MM-DD` for a date-only\n * column), and a belongsTo relation as its foreign key, under that key's\n * own name. It is exactly the record's columns; the id is the string the\n * admin addresses the record by — its primary key, a composite one's\n * parts joined by `:::` — which `highlightedIds` and\n * `useSidePanel().open` take.\n *\n * ```tsx\n * const [selectedId, setSelectedId] = useState<string>();\n * <CollectionPanel collection=\"orders\"\n * onRowClick={(row, id) => setSelectedId(id)}\n * highlightedIds={selectedId ? [selectedId] : []}/>\n * ```\n */\n onRowClick?: (row: Record<string, unknown>, id: string) => void;\n};\n\n/**\n * A high-level, reusable wrapper for embedding a Rebase collection view\n * inside custom pages (dashboards, home pages, entity detail views, etc.).\n *\n * Usage inside the CMS, by registered slug:\n * ```tsx\n * import { CollectionPanel } from \"@rebasepro/cms\";\n *\n * function MyDashboard() {\n * return (\n * <div>\n * <CollectionPanel collection=\"tasks\" title=\"Pending Tasks\" />\n * <CollectionPanel\n * collection=\"clients\"\n * viewMode=\"table\"\n * collectionOverrides={{\n * defaultFilter: { status: [\"!=\", \"completed\"] }\n * }}\n * />\n * </div>\n * );\n * }\n * ```\n *\n * Usage in a page of your own app, with the collection as a value — no\n * `<RebaseCMS>`, `<RebaseNavigation>` or `<RebaseShell>` needed, and any\n * React Router router will do. Records open in a side panel over the page:\n * ```tsx\n * <Rebase client={client} authController={authController}>\n * <BrowserRouter>\n * <CollectionPanel collection={postsCollection} />\n * </BrowserRouter>\n * </Rebase>\n * ```\n *\n * @group Components\n */\nfunction CollectionPanelInner({\n mergedCollection,\n overrides,\n path,\n title,\n viewMode,\n updateUrl,\n highlightedIds,\n fields,\n toolbar,\n onRowClick,\n rowActions,\n className\n}: ScopedPanelProps & { mergedCollection: AdminCollection; overrides: Partial<AdminCollection> }) {\n const ResolvedCollectionView = useComponentOverride(\"Collection.View\", CollectionViewBinding);\n const toolbarNode = toolbarOf(toolbar);\n const rowActionsScope = useMemo(\n () => rowActions ? { path: path ?? mergedCollection.slug, render: rowActions } : null,\n [path, mergedCollection.slug, rowActions]);\n // The list draws its title as its own heading: there the panel draws none,\n // and hands the view its title instead.\n const [viewDrawsTitle, setViewDrawsTitle] = useState(false);\n const titleReport = useMemo(\n () => ({ path: path ?? mergedCollection.slug, onViewDrawsTitle: setViewDrawsTitle }),\n [path, mergedCollection.slug]);\n\n // A column, so a height or a max-height on the panel reaches the view:\n // it sizes to its rows up to that, then scrolls inside.\n return (\n <div className={cls(\"flex flex-col min-h-0\", className)}>\n {title !== false && !viewDrawsTitle && (\n <Typography\n variant=\"subtitle2\"\n className=\"font-semibold mb-2 text-surface-700 dark:text-surface-300\"\n >\n {title ?? mergedCollection.name}\n </Typography>\n )}\n <RowActionsContext.Provider value={rowActionsScope}>\n <ViewTitleReportContext.Provider value={titleReport}>\n <ResolvedCollectionView\n {...mergedCollection}\n collectionOverrides={overrides}\n {...(highlightedIds !== undefined && { highlightedIds })}\n {...(viewMode && { viewMode })}\n {...(fields && { fields })}\n {...(toolbarNode !== undefined && { toolbar: toolbarNode })}\n {...(onRowClick && { onRowClick })}\n {...(title !== undefined && { title })}\n path={path}\n updateUrl={updateUrl}\n />\n </ViewTitleReportContext.Provider>\n </RowActionsContext.Provider>\n </div>\n );\n}\n\nexport function CollectionPanel(rawProps: CollectionPanelProps) {\n const inScope = useContext(CollectionsScopeContext);\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const { collection, path } = collectionPropOf(rawProps.collection, rawProps.path);\n if (rawProps.collection === undefined) {\n warnDeprecated(\"CollectionPanel.path\", \"`<CollectionPanel path=\\\"…\\\"/>` names its collection with `collection` now: `<CollectionPanel collection=\\\"…\\\"/>`.\");\n }\n const props: ScopedPanelProps = { ...rawProps, collection, path };\n const ownCollections = useMemo(() => collection ? [collection] : [], [collection]);\n\n // A collection handed over as a value brings its own scope where there is\n // none above — or where the one above has settled without it, since a\n // collection the data layer does not know gives its rows no address.\n const needsOwnScope = collection !== undefined && (!inScope\n || (!navigationState.loading && !isRegistered(collectionRegistry.collections, path)));\n // Named by path with no scope above to look it up in: nothing will ever\n // register it, so it is not found rather than loading.\n if (!inScope && collection === undefined) return <CollectionNotFound className={props.className} path={path}/>;\n if (needsOwnScope) {\n return (\n <CollectionsProvider externalCollections={ownCollections} tables={NO_TABLES}>\n <CollectionPanelInScope {...props}/>\n </CollectionsProvider>\n );\n }\n return <CollectionPanelInScope {...props}/>;\n}\n\n/** A panel's props once its `collection` is a value or absent, and its `path` known. */\ntype ScopedPanelProps = CollectionPanelOptions & { collection?: AdminCollection; path: string };\n\nfunction CollectionPanelInScope(props: ScopedPanelProps) {\n const {\n viewMode,\n sort,\n limit,\n openEntityMode,\n className,\n collectionOverrides,\n where,\n orderBy,\n rowActions,\n collection: collectionProp\n } = props;\n if (sort !== undefined) warnDeprecated(\"CollectionPanel.sort\", \"`CollectionPanel`'s `sort` is `orderBy` now: `orderBy=\\\"field:desc\\\"`.\");\n const order = orderBy ? orderByTuple(orderBy) : sort;\n const orderKey = order ? order.join(\":\") : undefined;\n // Whether, not which: the column reads the renderer through context, so a\n // new function each render leaves the collection alone.\n const hasRowActions = rowActions !== undefined;\n const path = props.path ?? collectionProp?.slug ?? \"\";\n const collectionRegistry = useCollectionRegistryController();\n const navigationState = useNavigationStateController();\n const urlController = useUrlController();\n // The registry's copy, also for a collection handed over as a value: it\n // carries the user's saved overrides and the plugins' changes. Not asked\n // before it has been filled.\n const lookUp = collectionRegistry.initialised || !navigationState.loading;\n const baseCollection = useMemo(\n () => lookUp ? collectionRegistry.getCollection(path) : undefined,\n [lookUp, collectionRegistry, path]);\n const routesMounted = urlController.routesMounted !== false;\n // Compared by value: it is an inline object at most call sites, and a new\n // one on every render would rebuild the overrides each time.\n const whereRef = useRef(where);\n if (!deepEqual(whereRef.current, where)) whereRef.current = where;\n const stableWhere = whereRef.current;\n\n // What this panel changes about the collection: the shorthand props over\n // the explicit overrides. Handed to the view as overrides, which it applies\n // over the registered collection it draws.\n const overrides = useMemo<Partial<AdminCollection>>(() => {\n const merged: Partial<AdminCollection> = {\n ...(collectionOverrides ?? {}),\n ...(viewMode && { defaultViewMode: viewMode }),\n ...(order && { sort: order }),\n ...(limit && { pagination: limit }),\n ...(openEntityMode && { openEntityMode }),\n ...(stableWhere && {\n fixedFilter: { ...(baseCollection?.fixedFilter ?? {}), ...(collectionOverrides?.fixedFilter ?? {}), ...stableWhere }\n }),\n ...(hasRowActions && {\n additionalFields: [...(collectionOverrides?.additionalFields ?? baseCollection?.additionalFields ?? []), ROW_ACTIONS_FIELD]\n })\n };\n // Without CMS routes a record has no page of its own, nor a split\n // beside the list that a URL selects: it opens over the page.\n if (!routesMounted && (merged.openEntityMode ?? baseCollection?.openEntityMode) !== \"dialog\") {\n return { ...merged, openEntityMode: \"side_panel\" };\n }\n return merged;\n // eslint-disable-next-line react-hooks/exhaustive-deps -- `order` by its key: `orderBy` is an inline tuple at most call sites.\n }, [baseCollection, collectionOverrides, viewMode, orderKey, limit, openEntityMode, stableWhere, hasRowActions, routesMounted]);\n\n const mergedCollection = useMemo(\n () => baseCollection ? { ...baseCollection, ...overrides } as AdminCollection : undefined,\n [baseCollection, overrides]);\n\n if (!mergedCollection) {\n if (navigationState.loading) {\n return <div className={className}><CircularProgressCenter/></div>;\n }\n return <CollectionNotFound className={className} path={path}/>;\n }\n\n const content = (\n <CollectionPanelInner\n {...props}\n path={path}\n mergedCollection={mergedCollection}\n overrides={overrides}\n />\n );\n\n return (\n <CollectionScopeProvider collection={mergedCollection}>\n {content}\n </CollectionScopeProvider>\n );\n}\n\nfunction CollectionNotFound({ className, path }: { className?: string, path: string }) {\n return (\n <div className={className}>\n <Typography variant=\"body2\" color=\"secondary\">\n Collection "{path}" not found.\n </Typography>\n </div>\n );\n}\n\n/** `\"field:desc\"` or `[\"field\", \"desc\"]`, as the collection's `sort` takes it. */\nfunction orderByTuple(orderBy: NonNullable<CollectionPanelOptions[\"orderBy\"]>): [string, \"asc\" | \"desc\"] {\n if (typeof orderBy !== \"string\") return [orderBy[0], orderBy[1]];\n const at = orderBy.lastIndexOf(\":\");\n return [orderBy.slice(0, at), orderBy.slice(at + 1) as \"asc\" | \"desc\"];\n}\n\n/** The node a `toolbar` keyword stands for; a composed toolbar as it is. */\nfunction toolbarOf(toolbar: CollectionPanelOptions[\"toolbar\"]): React.ReactNode {\n if (toolbar === \"full\") return undefined;\n if (toolbar === \"none\") return null;\n if (toolbar === \"compact\") return COMPACT_TOOLBAR;\n return toolbar;\n}\n\nconst COMPACT_TOOLBAR = (\n <CollectionToolbar\n start={<CollectionViewModeToggle/>}\n end={<><CollectionSearchBar/><CollectionAddButton/></>}/>\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2BA,IAAM,YAAwC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsO/C,SAAS,qBAAqB,EAC1B,kBACA,WACA,MACA,OACA,UACA,WACA,gBACA,QACA,SACA,YACA,YACA,aAC8F;CAC9F,MAAM,yBAAyB,qBAAqB,mBAAmB,qBAAqB;CAC5F,MAAM,cAAc,UAAU,OAAO;CACrC,MAAM,kBAAkB,cACd,aAAa;EAAE,MAAM,QAAQ,iBAAiB;EAAM,QAAQ;CAAW,IAAI,MACjF;EAAC;EAAM,iBAAiB;EAAM;CAAU,CAAC;CAG7C,MAAM,CAAC,gBAAgB,qBAAqB,SAAS,KAAK;CAC1D,MAAM,cAAc,eACT;EAAE,MAAM,QAAQ,iBAAiB;EAAM,kBAAkB;CAAkB,IAClF,CAAC,MAAM,iBAAiB,IAAI,CAAC;CAIjC,OACI,qBAAC,OAAD;EAAK,WAAW,IAAI,yBAAyB,SAAS;YAAtD,CACK,UAAU,SAAS,CAAC,kBACjB,oBAAC,YAAD;GACI,SAAQ;GACR,WAAU;aAET,SAAS,iBAAiB;EACnB,CAAA,GAEhB,oBAAC,kBAAkB,UAAnB;GAA4B,OAAO;aAC/B,oBAAC,uBAAuB,UAAxB;IAAiC,OAAO;cACpC,oBAAC,wBAAD;KACI,GAAI;KACJ,qBAAqB;KACrB,GAAK,mBAAmB,KAAA,KAAa,EAAE,eAAe;KACtD,GAAK,YAAY,EAAE,SAAS;KAC5B,GAAK,UAAU,EAAE,OAAO;KACxB,GAA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AAI,gBAAgB,SAChB,OAAO,oBAAC,OAAD;GAAgB;aAAW,oBAAC,wBAAD,CAAwB,CAAA;EAAM,CAAA;EAEpE,OAAO,oBAAC,oBAAD;GAA+B;GAAiB;EAAM,CAAA;CACjE;CAWA,OACI,oBAAC,yBAAD;EAAyB,YAAY;YATrC,oBAAC,sBAAD;GACI,GAAI;GACE;GACY;GACP;EACd,CAKI;CACoB,CAAA;AAEjC;AAEA,SAAS,mBAAmB,EAAE,WAAW,QAA8C;CACnF,OACI,oBAAC,OAAD;EAAgB;YACZ,qBAAC,YAAD;GAAY,SAAQ;GAAQ,OAAM;aAAlC;IAA8C;IACxB;IAAK;GACf;;CACX,CAAA;AAEb;;AAGA,SAAS,aAAa,SAAmF;CACrG,IAAI,OAAO,YAAY,UAAU,OAAO,CAAC,QAAQ,IAAI,QAAQ,EAAE;CAC/D,MAAM,KAAK,QAAQ,YAAY,GAAG;CAClC,OAAO,CAAC,QAAQ,MAAM,GAAG,EAAE,GAAG,QAAQ,MAAM,KAAK,CAAC,CAAmB;AACzE;;AAGA,SAAS,UAAU,SAA6D;CAC5E,IAAI,YAAY,QAAQ,OAAO,KAAA;CAC/B,IAAI,YAAY,QAAQ,OAAO;CAC/B,IAAI,YAAY,WAAW,OAAO;CAClC,OAAO;AACX;AAEA,IAAM,kBACF,oBAAC,mBAAD;CACI,OAAO,oBAAC,0BAAD,CAA0B,CAAA;CACjC,KAAK,qBAAA,UAAA,EAAA,UAAA,CAAE,oBAAC,qBAAD,CAAqB,CAAA,GAAC,oBAAC,qBAAD,CAAqB,CAAA,CAAG,EAAA,CAAA;AAAG,CAAA"}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { EntityAction, AdminCollection } from "@rebasepro/cms-types";
|
|
2
2
|
import React from "react";
|
|
3
|
-
import { Entity } from "@rebasepro/types";
|
|
4
|
-
import { CollectionSize, EntitySelectionController } from "@rebasepro/cms-types";
|
|
3
|
+
import { CollectionSize, EntitySelectionController, Entity } from "@rebasepro/cms-types";
|
|
5
4
|
/**
|
|
6
5
|
*
|
|
7
6
|
* @param entity
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CollectionRowActions.js","names":[],"sources":["../../../src/components/CollectionTableBinding/CollectionRowActions.tsx"],"sourcesContent":["\nimport type { EntityAction, EntityActionClickProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport React, { MouseEvent, useCallback } from \"react\";\n\nimport { Entity } from \"@rebasepro/types\";\nimport { CollectionSize, EntitySelectionController } from \"@rebasepro/cms-types\";\nimport {\n Badge,\n Checkbox,\n cls,\n IconButton,\n Menu,\n MenuItem,\n MoreVerticalIcon,\n Separator,\n Skeleton,\n Tooltip\n} from \"@rebasepro/ui\";\nimport { useTranslation, useSlot } from \"@rebasepro/app\";\nimport { getIcon } from \"@rebasepro/app\";\nimport { getEntityFromCache } from \"@rebasepro/app\";\nimport { getLocalChangesBackup } from \"@rebasepro/app\";\nimport { useAdminContext } from \"../../hooks/useAdminContext\";\nimport { entityActionName, placeEntityActions, resolveEntityActionState } from \"../../util/entity_actions\";\nimport { ActionMenuLabel } from \"../common/ActionMenuLabel\";\nimport { rowOfEntity, selectionControllerOf } from \"@rebasepro/app\";\n\n/**\n *\n * @param entity\n * @param width\n * @param frozen\n * @param isSelected\n * @param selectionEnabled\n * @param size\n * @param toggleEntitySelection\n * @param hideId\n *\n * @group Collection components\n */\nexport const CollectionRowActions = function CollectionRowActions({\n entity,\n collection,\n path,\n width,\n frozen,\n isSelected,\n selectionEnabled,\n size,\n highlightRow,\n onCollectionChange,\n unhighlightRow,\n actions = [],\n hideId,\n selectionController,\n openEntityMode,\n sortableNodeRef,\n sortableStyle,\n sortableAttributes,\n isDragging,\n isDraggable\n}:\n {\n entity: Entity<any>,\n collection?: AdminCollection<any>,\n path?: string,\n width: number,\n frozen?: boolean,\n size: CollectionSize,\n isSelected?: boolean,\n selectionEnabled?: boolean,\n actions?: EntityAction[],\n hideId?: boolean,\n onCollectionChange?: () => void,\n selectionController?: EntitySelectionController;\n highlightRow?: (id: string | number) => void;\n unhighlightRow?: (id: string | number) => void;\n openEntityMode: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n // Sortable props for dnd-kit integration\n sortableNodeRef?: (node: HTMLElement | null) => void;\n sortableStyle?: React.CSSProperties;\n sortableAttributes?: Record<string, any>;\n isDragging?: boolean;\n isDraggable?: boolean;\n }) {\n\n const context = useAdminContext();\n const sidePanelCtrl = context.sidePanelController;\n const { t } = useTranslation();\n\n // Plugin row actions, rendered in the same hover overlay as the built-in\n // ones — beside `edit` and before the collapsed menu, which is where a\n // per-row action goes. `collection`, `path` and `selectionController` are\n // forwarded as they arrive: a relation picker renders rows with no\n // collection path, and a table can be shown with selection off.\n const row = rowOfEntity(entity, collection);\n // The selection as an app's code reads it: rows and ids.\n const rowSelectionController = selectionController\n ? selectionControllerOf(selectionController, collection, path ?? entity.path)\n : undefined;\n const rowSlotProps = React.useMemo(() => ({\n row,\n id: String(entity.id),\n path,\n collection,\n selectionController: rowSelectionController,\n context\n }), [row, entity.id, path, collection, rowSelectionController, context]);\n const slotActions = useSlot(\"entity.row.actions\", rowSlotProps);\n\n const onCheckedChange = useCallback((checked: boolean) => {\n selectionController?.toggleEntitySelection(entity, checked);\n }, [entity, selectionController?.toggleEntitySelection]);\n\n const hasActions = actions.length > 0 || slotActions.length > 0;\n\n // Placed as the record's own bar places them: icons for `collapsed: false`,\n // and a menu of the collection's actions, then Copy, then Delete apart.\n const placed = placeEntityActions(actions);\n const uncollapsedActions = placed.inline;\n const collapsedGroups = [placed.own, placed.generic, placed.destructive].filter(group => group.length > 0);\n const hasCollapsedActions = collapsedGroups.length > 0;\n const enableLocalChangesBackup = collection ? getLocalChangesBackup(collection) : false;\n const hasDraft = enableLocalChangesBackup ? getEntityFromCache(path + \"/\" + entity.id) : false;\n const iconSize = \"small\" as const;\n\n // What every action on this row is called with, and asked `isEnabled`\n // with — the same question the record's own action bar asks, so an action\n // its record does not allow is disabled here too.\n const clickProps: EntityActionClickProps<Record<string, unknown>> = {\n view: \"collection\",\n row,\n id: String(entity.id),\n // The record's own path where the table has none — a picker's rows\n // — so a subcollection record opens and copies where it lives.\n path: path ?? entity.path,\n collection,\n context,\n sidePanelController: sidePanelCtrl,\n selectionController: rowSelectionController,\n highlightRow,\n unhighlightRow,\n onCollectionChange,\n openEntityMode: openEntityMode ?? collection?.openEntityMode\n };\n const actionState = (action: EntityAction) => resolveEntityActionState(action, clickProps);\n\n const content = (\n <div\n className={cls(\n \"h-full flex items-center justify-center flex-col z-10\",\n isSelected\n ? \"bg-surface-raised\"\n : \"bg-surface-card group-hover:bg-surface-card-hover\",\n frozen ? \"sticky left-0\" : \"\"\n )}\n onClick={useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n }, [])}\n style={{\n width,\n position: frozen ? \"sticky\" : \"relative\",\n left: frozen ? 0 : \"initial\",\n contain: \"strict\"\n }}>\n\n {/* The row's resting content is its id. The actions (edit, menu,\n select) cover it while the row is hovered, focused or selected,\n so a 36px row carries one line and the tools still fit. */}\n {(hasActions || selectionEnabled) &&\n <div className={cls(\n \"absolute inset-0 flex items-center justify-center gap-0.5\",\n isSelected\n ? \"bg-surface-raised\"\n : \"bg-surface-card group-hover:bg-surface-card-hover opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity duration-100\"\n )}>\n\n {uncollapsedActions.map((action, index) => {\n const isEditAction = action.key === \"edit\";\n const { enabled, disabledReason } = actionState(action);\n const name = entityActionName(action, t);\n const tooltip = isEditAction && hasDraft\n ? t(\"unsaved_local_changes\")\n : disabledReason ? `${name}: ${disabledReason}` : name;\n\n let iconButton = <IconButton\n aria-label={name}\n disabled={!enabled}\n onClick={(event: MouseEvent) => {\n event.stopPropagation();\n action.onClick(clickProps);\n }}\n size={iconSize}>\n {getIcon(action.icon, undefined, undefined, \"smallest\")}\n </IconButton>;\n if (isEditAction && hasDraft) {\n iconButton = (\n <Badge color={\"warning\"}>\n {iconButton}\n </Badge>\n );\n }\n // A disabled icon takes no pointer events, so as the\n // trigger itself its tooltip — the one place it can\n // say why — never opened. Wrapped, the wrapper hovers.\n return (\n <Tooltip key={index}\n title={tooltip}\n asChild={enabled}>\n {iconButton}\n </Tooltip>\n );\n })}\n\n {slotActions}\n\n {hasCollapsedActions &&\n <Menu\n trigger={<IconButton aria-label={t(\"more_actions\")}\n size={iconSize}>\n <MoreVerticalIcon/>\n </IconButton>}>\n {collapsedGroups.map((group, groupIndex) => (\n <React.Fragment key={groupIndex}>\n {groupIndex > 0 && <Separator orientation={\"horizontal\"}/>}\n {group.map((action, index) => {\n const { enabled, disabledReason } = actionState(action);\n return <MenuItem\n key={action.key ?? index}\n disabled={!enabled}\n onClick={(e) => {\n e.stopPropagation();\n action.onClick(clickProps);\n }}>\n {getIcon(action.icon, undefined, undefined, \"smallest\")}\n <ActionMenuLabel name={entityActionName(action, t)} disabledReason={disabledReason}/>\n </MenuItem>;\n })}\n </React.Fragment>\n ))}\n </Menu>\n }\n\n {selectionEnabled &&\n <Tooltip title={t(\"select_row\", { id: String(entity.id) })}>\n <Checkbox\n aria-label={t(\"select_row\", { id: String(entity.id) })}\n size={\"smallest\"}\n checked={Boolean(isSelected)}\n onCheckedChange={onCheckedChange}\n />\n </Tooltip>}\n\n </div>}\n\n {!hideId && (\n <div\n className=\"w-[138px] overflow-hidden truncate font-mono text-xs text-text-secondary dark:text-text-secondary-dark max-w-full text-ellipsis px-2 align-center justify-center flex items-center gap-1\"\n onClick={(event) => {\n event.stopPropagation();\n }}>\n <span className=\"min-w-0 truncate text-center\">\n {entity\n ? entity.id\n : <Skeleton/>\n }\n </span>\n </div>\n )}\n\n </div>\n );\n\n // Wrap with sortable outer div when sortable props are provided\n // Remove tabIndex from attributes to avoid capturing focus before cell content\n if (sortableNodeRef) {\n const { tabIndex: _tabIndex, ...sortableAttrsWithoutTabIndex } = sortableAttributes ?? {};\n return (\n <div\n ref={sortableNodeRef}\n style={sortableStyle}\n className={cls(\n \"flex-shrink-0\",\n frozen && \"sticky left-0 z-10 bg-surface-card\"\n )}\n {...sortableAttrsWithoutTabIndex}\n >\n {content}\n </div>\n );\n }\n\n return content;\n\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwCA,IAAa,uBAAuB,SAAS,qBAAqB,EAC9D,QACA,YACA,MACA,OACA,QACA,YACA,kBACA,MACA,cACA,oBACA,gBACA,UAAU,CAAC,GACX,QACA,qBACA,gBACA,iBACA,eACA,oBACA,YACA,eAwBG;CAEH,MAAM,UAAU,gBAAgB;CAChC,MAAM,gBAAgB,QAAQ;CAC9B,MAAM,EAAE,MAAM,eAAe;CAO7B,MAAM,MAAM,YAAY,QAAQ,UAAU;CAE1C,MAAM,yBAAyB,sBACzB,sBAAsB,qBAAqB,YAAY,QAAQ,OAAO,IAAI,IAC1E,KAAA;CASN,MAAM,cAAc,QAAQ,sBARP,MAAM,eAAe;EACtC;EACA,IAAI,OAAO,OAAO,EAAE;EACpB;EACA;EACA,qBAAqB;EACrB;CACJ,IAAI;EAAC;EAAK,OAAO;EAAI;EAAM;EAAY;EAAwB;CAAO,CACpB,CAAY;CAE9D,MAAM,kBAAkB,aAAa,YAAqB;EACtD,qBAAqB,sBAAsB,QAAQ,OAAO;CAC9D,GAAG,CAAC,QAAQ,qBAAqB,qBAAqB,CAAC;CAEvD,MAAM,aAAa,QAAQ,SAAS,KAAK,YAAY,SAAS;CAI9D,MAAM,SAAS,mBAAmB,OAAO;CACzC,MAAM,qBAAqB,OAAO;CAClC,MAAM,kBAAkB;EAAC,OAAO;EAAK,OAAO;EAAS,OAAO;CAAW,CAAC,CAAC,QAAO,UAAS,MAAM,SAAS,CAAC;CACzG,MAAM,sBAAsB,gBAAgB,SAAS;CAErD,MAAM,YAD2B,aAAa,sBAAsB,UAAU,IAAI,SACtC,mBAAmB,OAAO,MAAM,OAAO,EAAE,IAAI;CACzF,MAAM,WAAW;CAKjB,MAAM,aAA8D;EAChE,MAAM;EACN;EACA,IAAI,OAAO,OAAO,E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../src/components/CollectionTableBinding/CollectionRowActions.tsx"],"sourcesContent":["\nimport type { EntityAction, EntityActionClickProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport React, { MouseEvent, useCallback } from \"react\";\n\nimport { CollectionSize, EntitySelectionController, Entity } from \"@rebasepro/cms-types\";\nimport {\n Badge,\n Checkbox,\n cls,\n IconButton,\n Menu,\n MenuItem,\n MoreVerticalIcon,\n Separator,\n Skeleton,\n Tooltip\n} from \"@rebasepro/ui\";\nimport { useTranslation, useSlot } from \"@rebasepro/app\";\nimport { getIcon } from \"@rebasepro/app\";\nimport { getEntityFromCache } from \"@rebasepro/app\";\nimport { getLocalChangesBackup } from \"@rebasepro/app\";\nimport { useAdminContext } from \"../../hooks/useAdminContext\";\nimport { entityActionName, placeEntityActions, resolveEntityActionState } from \"../../util/entity_actions\";\nimport { ActionMenuLabel } from \"../common/ActionMenuLabel\";\nimport { rowOfEntity, selectionControllerOf } from \"@rebasepro/app\";\n\n/**\n *\n * @param entity\n * @param width\n * @param frozen\n * @param isSelected\n * @param selectionEnabled\n * @param size\n * @param toggleEntitySelection\n * @param hideId\n *\n * @group Collection components\n */\nexport const CollectionRowActions = function CollectionRowActions({\n entity,\n collection,\n path,\n width,\n frozen,\n isSelected,\n selectionEnabled,\n size,\n highlightRow,\n onCollectionChange,\n unhighlightRow,\n actions = [],\n hideId,\n selectionController,\n openEntityMode,\n sortableNodeRef,\n sortableStyle,\n sortableAttributes,\n isDragging,\n isDraggable\n}:\n {\n entity: Entity<any>,\n collection?: AdminCollection<any>,\n path?: string,\n width: number,\n frozen?: boolean,\n size: CollectionSize,\n isSelected?: boolean,\n selectionEnabled?: boolean,\n actions?: EntityAction[],\n hideId?: boolean,\n onCollectionChange?: () => void,\n selectionController?: EntitySelectionController;\n highlightRow?: (id: string | number) => void;\n unhighlightRow?: (id: string | number) => void;\n openEntityMode: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n // Sortable props for dnd-kit integration\n sortableNodeRef?: (node: HTMLElement | null) => void;\n sortableStyle?: React.CSSProperties;\n sortableAttributes?: Record<string, any>;\n isDragging?: boolean;\n isDraggable?: boolean;\n }) {\n\n const context = useAdminContext();\n const sidePanelCtrl = context.sidePanelController;\n const { t } = useTranslation();\n\n // Plugin row actions, rendered in the same hover overlay as the built-in\n // ones — beside `edit` and before the collapsed menu, which is where a\n // per-row action goes. `collection`, `path` and `selectionController` are\n // forwarded as they arrive: a relation picker renders rows with no\n // collection path, and a table can be shown with selection off.\n const row = rowOfEntity(entity, collection);\n // The selection as an app's code reads it: rows and ids.\n const rowSelectionController = selectionController\n ? selectionControllerOf(selectionController, collection, path ?? entity.path)\n : undefined;\n const rowSlotProps = React.useMemo(() => ({\n row,\n id: String(entity.id),\n path,\n collection,\n selectionController: rowSelectionController,\n context\n }), [row, entity.id, path, collection, rowSelectionController, context]);\n const slotActions = useSlot(\"entity.row.actions\", rowSlotProps);\n\n const onCheckedChange = useCallback((checked: boolean) => {\n selectionController?.toggleEntitySelection(entity, checked);\n }, [entity, selectionController?.toggleEntitySelection]);\n\n const hasActions = actions.length > 0 || slotActions.length > 0;\n\n // Placed as the record's own bar places them: icons for `collapsed: false`,\n // and a menu of the collection's actions, then Copy, then Delete apart.\n const placed = placeEntityActions(actions);\n const uncollapsedActions = placed.inline;\n const collapsedGroups = [placed.own, placed.generic, placed.destructive].filter(group => group.length > 0);\n const hasCollapsedActions = collapsedGroups.length > 0;\n const enableLocalChangesBackup = collection ? getLocalChangesBackup(collection) : false;\n const hasDraft = enableLocalChangesBackup ? getEntityFromCache(path + \"/\" + entity.id) : false;\n const iconSize = \"small\" as const;\n\n // What every action on this row is called with, and asked `isEnabled`\n // with — the same question the record's own action bar asks, so an action\n // its record does not allow is disabled here too.\n const clickProps: EntityActionClickProps<Record<string, unknown>> = {\n view: \"collection\",\n row,\n id: String(entity.id),\n // The record's own path where the table has none — a picker's rows\n // — so a subcollection record opens and copies where it lives.\n path: path ?? entity.path,\n collection,\n context,\n sidePanelController: sidePanelCtrl,\n selectionController: rowSelectionController,\n highlightRow,\n unhighlightRow,\n onCollectionChange,\n openEntityMode: openEntityMode ?? collection?.openEntityMode\n };\n const actionState = (action: EntityAction) => resolveEntityActionState(action, clickProps);\n\n const content = (\n <div\n className={cls(\n \"h-full flex items-center justify-center flex-col z-10\",\n isSelected\n ? \"bg-surface-raised\"\n : \"bg-surface-card group-hover:bg-surface-card-hover\",\n frozen ? \"sticky left-0\" : \"\"\n )}\n onClick={useCallback((event: React.MouseEvent) => {\n event.stopPropagation();\n }, [])}\n style={{\n width,\n position: frozen ? \"sticky\" : \"relative\",\n left: frozen ? 0 : \"initial\",\n contain: \"strict\"\n }}>\n\n {/* The row's resting content is its id. The actions (edit, menu,\n select) cover it while the row is hovered, focused or selected,\n so a 36px row carries one line and the tools still fit. */}\n {(hasActions || selectionEnabled) &&\n <div className={cls(\n \"absolute inset-0 flex items-center justify-center gap-0.5\",\n isSelected\n ? \"bg-surface-raised\"\n : \"bg-surface-card group-hover:bg-surface-card-hover opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity duration-100\"\n )}>\n\n {uncollapsedActions.map((action, index) => {\n const isEditAction = action.key === \"edit\";\n const { enabled, disabledReason } = actionState(action);\n const name = entityActionName(action, t);\n const tooltip = isEditAction && hasDraft\n ? t(\"unsaved_local_changes\")\n : disabledReason ? `${name}: ${disabledReason}` : name;\n\n let iconButton = <IconButton\n aria-label={name}\n disabled={!enabled}\n onClick={(event: MouseEvent) => {\n event.stopPropagation();\n action.onClick(clickProps);\n }}\n size={iconSize}>\n {getIcon(action.icon, undefined, undefined, \"smallest\")}\n </IconButton>;\n if (isEditAction && hasDraft) {\n iconButton = (\n <Badge color={\"warning\"}>\n {iconButton}\n </Badge>\n );\n }\n // A disabled icon takes no pointer events, so as the\n // trigger itself its tooltip — the one place it can\n // say why — never opened. Wrapped, the wrapper hovers.\n return (\n <Tooltip key={index}\n title={tooltip}\n asChild={enabled}>\n {iconButton}\n </Tooltip>\n );\n })}\n\n {slotActions}\n\n {hasCollapsedActions &&\n <Menu\n trigger={<IconButton aria-label={t(\"more_actions\")}\n size={iconSize}>\n <MoreVerticalIcon/>\n </IconButton>}>\n {collapsedGroups.map((group, groupIndex) => (\n <React.Fragment key={groupIndex}>\n {groupIndex > 0 && <Separator orientation={\"horizontal\"}/>}\n {group.map((action, index) => {\n const { enabled, disabledReason } = actionState(action);\n return <MenuItem\n key={action.key ?? index}\n disabled={!enabled}\n onClick={(e) => {\n e.stopPropagation();\n action.onClick(clickProps);\n }}>\n {getIcon(action.icon, undefined, undefined, \"smallest\")}\n <ActionMenuLabel name={entityActionName(action, t)} disabledReason={disabledReason}/>\n </MenuItem>;\n })}\n </React.Fragment>\n ))}\n </Menu>\n }\n\n {selectionEnabled &&\n <Tooltip title={t(\"select_row\", { id: String(entity.id) })}>\n <Checkbox\n aria-label={t(\"select_row\", { id: String(entity.id) })}\n size={\"smallest\"}\n checked={Boolean(isSelected)}\n onCheckedChange={onCheckedChange}\n />\n </Tooltip>}\n\n </div>}\n\n {!hideId && (\n <div\n className=\"w-[138px] overflow-hidden truncate font-mono text-xs text-text-secondary dark:text-text-secondary-dark max-w-full text-ellipsis px-2 align-center justify-center flex items-center gap-1\"\n onClick={(event) => {\n event.stopPropagation();\n }}>\n <span className=\"min-w-0 truncate text-center\">\n {entity\n ? entity.id\n : <Skeleton/>\n }\n </span>\n </div>\n )}\n\n </div>\n );\n\n // Wrap with sortable outer div when sortable props are provided\n // Remove tabIndex from attributes to avoid capturing focus before cell content\n if (sortableNodeRef) {\n const { tabIndex: _tabIndex, ...sortableAttrsWithoutTabIndex } = sortableAttributes ?? {};\n return (\n <div\n ref={sortableNodeRef}\n style={sortableStyle}\n className={cls(\n \"flex-shrink-0\",\n frozen && \"sticky left-0 z-10 bg-surface-card\"\n )}\n {...sortableAttrsWithoutTabIndex}\n >\n {content}\n </div>\n );\n }\n\n return content;\n\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,uB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