@rebasepro/cms 0.28.2 → 0.29.0-canary.g0e3a0e7
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 +3 -3
- package/dist/collection_editor/_cms_internals.d.ts +0 -1
- package/dist/collection_editor/ui/EditorCollectionAction.d.ts +2 -2
- package/dist/collection_editor/ui/EditorCollectionAction.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/import/CollectionEditorImportDataPreview.js +2 -2
- package/dist/collection_editor/ui/collection_editor/import/CollectionEditorImportDataPreview.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/MarkdownPropertyField.js +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/MarkdownPropertyField.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/StoragePropertyField.js +1 -1
- package/dist/collection_editor/ui/collection_editor/properties/StoragePropertyField.js.map +1 -1
- package/dist/components/AdditionalFieldValue.d.ts +9 -3
- package/dist/components/AdditionalFieldValue.js +7 -4
- package/dist/components/AdditionalFieldValue.js.map +1 -1
- package/dist/components/CollectionPanel.d.ts +117 -18
- package/dist/components/CollectionPanel.js +115 -37
- package/dist/components/CollectionPanel.js.map +1 -1
- package/dist/components/CollectionTableBinding/CollectionRowActions.d.ts +5 -5
- package/dist/components/CollectionTableBinding/CollectionRowActions.js +16 -12
- package/dist/components/CollectionTableBinding/CollectionRowActions.js.map +1 -1
- package/dist/components/CollectionTableBinding/CollectionTableBinding.js +33 -8
- package/dist/components/CollectionTableBinding/CollectionTableBinding.js.map +1 -1
- package/dist/components/CollectionTableBinding/CollectionTableBindingProps.d.ts +8 -3
- package/dist/components/CollectionTableBinding/PropertyTableCell.js +2 -2
- package/dist/components/CollectionTableBinding/PropertyTableCell.js.map +1 -1
- package/dist/components/CollectionTableBinding/column_utils.d.ts +9 -1
- package/dist/components/CollectionTableBinding/column_utils.js +6 -3
- package/dist/components/CollectionTableBinding/column_utils.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableMultipleRelationField.js +2 -2
- package/dist/components/CollectionTableBinding/fields/TableMultipleRelationField.js.map +1 -1
- 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.js +2 -2
- package/dist/components/CollectionTableBinding/fields/TableRelationField.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.d.ts +3 -2
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js +9 -7
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/common.d.ts +26 -2
- package/dist/components/CollectionTableBinding/internal/common.js +88 -4
- package/dist/components/CollectionTableBinding/internal/common.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js +4 -3
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
- package/dist/components/CollectionViewBinding/BoardCardBinding.d.ts +7 -1
- package/dist/components/CollectionViewBinding/BoardCardBinding.js +19 -14
- package/dist/components/CollectionViewBinding/BoardCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionAddButton.d.ts +28 -0
- package/dist/components/CollectionViewBinding/CollectionAddButton.js +50 -0
- package/dist/components/CollectionViewBinding/CollectionAddButton.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionBoardViewBinding.d.ts +11 -3
- package/dist/components/CollectionViewBinding/CollectionBoardViewBinding.js +9 -4
- package/dist/components/CollectionViewBinding/CollectionBoardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.d.ts +5 -3
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js +5 -3
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionEntityActions.d.ts +29 -0
- package/dist/components/CollectionViewBinding/CollectionEntityActions.js +112 -0
- package/dist/components/CollectionViewBinding/CollectionEntityActions.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.d.ts +2 -2
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +58 -16
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionToolbar.d.ts +57 -0
- package/dist/components/CollectionViewBinding/CollectionToolbar.js +146 -0
- package/dist/components/CollectionViewBinding/CollectionToolbar.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionViewActions.d.ts +2 -2
- package/dist/components/CollectionViewBinding/CollectionViewActions.js +22 -26
- package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewBinding.d.ts +58 -22
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js +81 -1089
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +9 -0
- package/dist/components/CollectionViewBinding/CollectionViewContent.js +152 -0
- package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionViewDialogs.d.ts +9 -0
- package/dist/components/CollectionViewBinding/CollectionViewDialogs.js +38 -0
- package/dist/components/CollectionViewBinding/CollectionViewDialogs.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionViewFrame.d.ts +13 -0
- package/dist/components/CollectionViewBinding/CollectionViewFrame.js +32 -0
- package/dist/components/CollectionViewBinding/CollectionViewFrame.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionViewScope.d.ts +14 -0
- package/dist/components/CollectionViewBinding/CollectionViewScope.js +22 -0
- package/dist/components/CollectionViewBinding/CollectionViewScope.js.map +1 -0
- package/dist/components/CollectionViewBinding/CollectionViewStartActions.d.ts +2 -2
- package/dist/components/CollectionViewBinding/CollectionViewStartActions.js +39 -67
- package/dist/components/CollectionViewBinding/CollectionViewStartActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CustomViewHost.d.ts +28 -0
- package/dist/components/CollectionViewBinding/CustomViewHost.js +54 -0
- package/dist/components/CollectionViewBinding/CustomViewHost.js.map +1 -0
- package/dist/components/CollectionViewBinding/EntitiesCount.d.ts +24 -0
- package/dist/components/CollectionViewBinding/EntitiesCount.js +69 -0
- package/dist/components/CollectionViewBinding/EntitiesCount.js.map +1 -0
- package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +7 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js +34 -23
- package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntityIdHeaderWidget.d.ts +17 -0
- package/dist/components/CollectionViewBinding/EntityIdHeaderWidget.js +107 -0
- package/dist/components/CollectionViewBinding/EntityIdHeaderWidget.js.map +1 -0
- package/dist/components/CollectionViewBinding/FiltersButton.d.ts +15 -0
- package/dist/components/CollectionViewBinding/FiltersButton.js +49 -0
- package/dist/components/CollectionViewBinding/FiltersButton.js.map +1 -0
- package/dist/components/CollectionViewBinding/PluginColumnSlots.d.ts +35 -0
- package/dist/components/CollectionViewBinding/PluginColumnSlots.js +45 -0
- package/dist/components/CollectionViewBinding/PluginColumnSlots.js.map +1 -0
- package/dist/components/CollectionViewBinding/RowActions.d.ts +40 -0
- package/dist/components/CollectionViewBinding/RowActions.js +60 -0
- package/dist/components/CollectionViewBinding/RowActions.js.map +1 -0
- package/dist/components/CollectionViewBinding/SplitListView.d.ts +7 -4
- package/dist/components/CollectionViewBinding/SplitListView.js +20 -21
- package/dist/components/CollectionViewBinding/SplitListView.js.map +1 -1
- package/dist/components/CollectionViewBinding/builtin_action_props.d.ts +13 -0
- package/dist/components/CollectionViewBinding/fields.d.ts +22 -0
- package/dist/components/CollectionViewBinding/fields.js +47 -0
- package/dist/components/CollectionViewBinding/fields.js.map +1 -0
- package/dist/components/CollectionViewBinding/useBoardDataController.js +6 -7
- package/dist/components/CollectionViewBinding/useBoardDataController.js.map +1 -1
- package/dist/components/CollectionViewBinding/useCollectionLargeLayout.d.ts +19 -0
- package/dist/components/CollectionViewBinding/useCollectionLargeLayout.js +28 -0
- package/dist/components/CollectionViewBinding/useCollectionLargeLayout.js.map +1 -0
- package/dist/components/CollectionViewBinding/useCollectionViewState.d.ts +125 -0
- package/dist/components/CollectionViewBinding/useCollectionViewState.js +844 -0
- package/dist/components/CollectionViewBinding/useCollectionViewState.js.map +1 -0
- package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +20 -0
- package/dist/components/CollectionViewBinding/usePreviewSlots.js +23 -2
- package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
- package/dist/components/CollectionViewBinding/useSelectionController.d.ts +21 -3
- package/dist/components/CollectionViewBinding/useSelectionController.js +37 -6
- package/dist/components/CollectionViewBinding/useSelectionController.js.map +1 -1
- package/dist/components/CollectionsProvider.d.ts +3 -3
- package/dist/components/CollectionsProvider.js +4 -4
- package/dist/components/CollectionsProvider.js.map +1 -1
- package/dist/components/CollectionsScopeContext.d.ts +1 -1
- package/dist/components/CollectionsScopeContext.js +1 -1
- package/dist/components/CollectionsScopeContext.js.map +1 -1
- package/dist/components/DeleteEntityDialog.d.ts +1 -1
- package/dist/components/DeleteEntityDialog.js +2 -2
- package/dist/components/DeleteEntityDialog.js.map +1 -1
- package/dist/components/DetailViewBinding.js +32 -68
- package/dist/components/DetailViewBinding.js.map +1 -1
- package/dist/components/EditFormActions.js +5 -4
- package/dist/components/EditFormActions.js.map +1 -1
- package/dist/components/EditViewBinding.d.ts +2 -2
- package/dist/components/EditViewBinding.js +25 -15
- package/dist/components/EditViewBinding.js.map +1 -1
- package/dist/components/EntityDisplayHeader.js +8 -5
- package/dist/components/EntityDisplayHeader.js.map +1 -1
- package/dist/components/EntityPreviewBinding.js +1 -1
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/components/EntityViewBinding.d.ts +8 -1
- package/dist/components/EntityViewBinding.js +43 -14
- package/dist/components/EntityViewBinding.js.map +1 -1
- package/dist/components/EntityViewBody.d.ts +40 -0
- package/dist/components/EntityViewBody.js +90 -0
- package/dist/components/EntityViewBody.js.map +1 -0
- package/dist/components/FieldValue.d.ts +50 -0
- package/dist/components/FieldValue.js +81 -0
- package/dist/components/FieldValue.js.map +1 -0
- package/dist/components/InlineEntityPreview.js +1 -1
- package/dist/components/InlineEntityPreview.js.map +1 -1
- package/dist/components/PanelNotFound.d.ts +5 -0
- package/dist/components/PanelNotFound.js +21 -0
- package/dist/components/PanelNotFound.js.map +1 -0
- package/dist/components/RebaseCMS.d.ts +1 -1
- package/dist/components/RebaseCMS.js +11 -3
- package/dist/components/RebaseCMS.js.map +1 -1
- package/dist/components/RebaseNavigation.js +9 -3
- package/dist/components/RebaseNavigation.js.map +1 -1
- package/dist/components/RebaseShell.js +10 -5
- package/dist/components/RebaseShell.js.map +1 -1
- package/dist/components/RecordDetail.d.ts +61 -0
- package/dist/components/RecordDetail.js +123 -0
- package/dist/components/RecordDetail.js.map +1 -0
- package/dist/components/RecordForm.d.ts +126 -0
- package/dist/components/{EntityFormPanel.js → RecordForm.js} +64 -36
- package/dist/components/RecordForm.js.map +1 -0
- package/dist/components/ReferenceTable/SelectionTableBinding.d.ts +47 -17
- package/dist/components/ReferenceTable/SelectionTableBinding.js +89 -53
- package/dist/components/ReferenceTable/SelectionTableBinding.js.map +1 -1
- package/dist/components/ReferenceWidget.d.ts +5 -3
- package/dist/components/ReferenceWidget.js +10 -7
- package/dist/components/ReferenceWidget.js.map +1 -1
- package/dist/components/RelationSelector.js +4 -4
- package/dist/components/RelationSelector.js.map +1 -1
- package/dist/components/SelectableTable/SelectableTable.js +2 -3
- package/dist/components/SelectableTable/SelectableTable.js.map +1 -1
- package/dist/components/SelectableTable/SelectionStore.d.ts +1 -1
- package/dist/components/SelectableTable/SelectionStore.js +1 -1
- package/dist/components/SelectableTable/SelectionStore.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/SidePanelBinding.js +13 -12
- package/dist/components/SidePanelBinding.js.map +1 -1
- package/dist/components/collection_prop.d.ts +18 -0
- package/dist/components/collection_prop.js +23 -0
- package/dist/components/collection_prop.js.map +1 -0
- package/dist/components/common/default_entity_actions.js +54 -54
- package/dist/components/common/default_entity_actions.js.map +1 -1
- package/dist/components/history/EntityHistoryView.d.ts +4 -1
- package/dist/components/history/EntityHistoryView.js +1 -1
- package/dist/components/history/EntityHistoryView.js.map +1 -1
- package/dist/components/history/LastEditedByFormAction.d.ts +1 -1
- package/dist/components/index.d.ts +4 -2
- package/dist/data_export/export/ExportCollectionAction.d.ts +3 -2
- package/dist/data_export/export/ExportCollectionAction.js +4 -3
- package/dist/data_export/export/ExportCollectionAction.js.map +1 -1
- package/dist/data_export/export/additional_fields.d.ts +6 -3
- package/dist/data_export/export/additional_fields.js +8 -4
- package/dist/data_export/export/additional_fields.js.map +1 -1
- package/dist/data_import/import/ImportCollectionAction.js +2 -2
- package/dist/data_import/import/ImportCollectionAction.js.map +1 -1
- package/dist/form/EntityForm.d.ts +1 -1
- package/dist/form/EntityForm.js +252 -150
- package/dist/form/EntityForm.js.map +1 -1
- package/dist/form/EntityFormActions.js +3 -2
- package/dist/form/EntityFormActions.js.map +1 -1
- package/dist/form/EntityFormBinding.d.ts +1 -1
- package/dist/form/EntityFormBinding.js +22 -11
- package/dist/form/EntityFormBinding.js.map +1 -1
- package/dist/form/FormField.d.ts +36 -0
- package/dist/form/FormField.js +41 -0
- package/dist/form/FormField.js.map +1 -0
- package/dist/form/FormFieldsContext.d.ts +69 -0
- package/dist/form/FormFieldsContext.js +143 -0
- package/dist/form/FormFieldsContext.js.map +1 -0
- package/dist/form/PropertyFieldBinding.js +4 -4
- package/dist/form/PropertyFieldBinding.js.map +1 -1
- package/dist/form/collection_showing.d.ts +8 -0
- package/dist/form/collection_showing.js +29 -0
- package/dist/form/collection_showing.js.map +1 -0
- package/dist/form/components/ErrorFocus.js +2 -1
- package/dist/form/components/ErrorFocus.js.map +1 -1
- package/dist/form/components/FieldBlock.js +3 -1
- package/dist/form/components/FieldBlock.js.map +1 -1
- package/dist/form/components/FormRail.d.ts +5 -1
- package/dist/form/components/FormRail.js +5 -1
- package/dist/form/components/FormRail.js.map +1 -1
- package/dist/form/components/FormSections.d.ts +5 -1
- package/dist/form/components/FormSections.js +11 -4
- package/dist/form/components/FormSections.js.map +1 -1
- package/dist/form/field_bindings/ArrayOfReferencesFieldBinding.js +2 -2
- package/dist/form/field_bindings/ArrayOfReferencesFieldBinding.js.map +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/MultipleRelationFieldBinding.js +2 -2
- package/dist/form/field_bindings/MultipleRelationFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +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.js +2 -2
- package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/StorageUploadFieldBinding.js +1 -1
- package/dist/form/field_bindings/StorageUploadFieldBinding.js.map +1 -1
- package/dist/form/form_dom_ids.d.ts +25 -0
- package/dist/form/form_dom_ids.js +42 -0
- package/dist/form/form_dom_ids.js.map +1 -0
- package/dist/form/index.d.ts +3 -1
- package/dist/form/resolve_cell_property.d.ts +5 -0
- package/dist/form/resolve_cell_property.js +22 -1
- package/dist/form/resolve_cell_property.js.map +1 -1
- package/dist/hooks/index.d.ts +1 -1
- package/dist/hooks/navigation/useBuildNavigationStateController.d.ts +2 -2
- package/dist/hooks/navigation/useBuildNavigationStateController.js.map +1 -1
- package/dist/hooks/navigation/useNavigationResolution.d.ts +3 -3
- package/dist/hooks/navigation/useNavigationResolution.js.map +1 -1
- package/dist/hooks/navigation/useResolvedCollections.d.ts +2 -2
- package/dist/hooks/navigation/useResolvedCollections.js.map +1 -1
- package/dist/hooks/navigation/useResolvedViews.d.ts +2 -2
- package/dist/hooks/navigation/useResolvedViews.js.map +1 -1
- package/dist/hooks/useBuildSidePanel.js +9 -9
- package/dist/hooks/useBuildSidePanel.js.map +1 -1
- package/dist/hooks/useEntityDisplay.js +6 -4
- package/dist/hooks/useEntityDisplay.js.map +1 -1
- package/dist/hooks/useRecordActions.js +2 -2
- package/dist/hooks/useRecordActions.js.map +1 -1
- package/dist/hooks/useSelectionDialog.d.ts +20 -7
- package/dist/hooks/useSelectionDialog.js +29 -8
- package/dist/hooks/useSelectionDialog.js.map +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.js +15 -9
- package/dist/mcp-view.d.ts +9 -0
- package/dist/mcp-view.js +2 -0
- package/dist/mcp_view/app_modules.d.ts +29 -0
- package/dist/mcp_view/app_modules.js +163 -0
- package/dist/mcp_view/app_modules.js.map +1 -0
- package/dist/mcp_view/bridge.d.ts +90 -0
- package/dist/mcp_view/bridge.js +205 -0
- package/dist/mcp_view/bridge.js.map +1 -0
- package/dist/mcp_view/code_app.d.ts +65 -0
- package/dist/mcp_view/code_app.js +139 -0
- package/dist/mcp_view/code_app.js.map +1 -0
- package/dist/mcp_view/index.d.ts +48 -0
- package/dist/mcp_view/index.js +235 -0
- package/dist/mcp_view/index.js.map +1 -0
- package/dist/mcp_view/payload.d.ts +78 -0
- package/dist/mcp_view/payload.js +155 -0
- package/dist/mcp_view/payload.js.map +1 -0
- package/dist/mcp_view/screen.d.ts +28 -0
- package/dist/mcp_view/screen.js +223 -0
- package/dist/mcp_view/screen.js.map +1 -0
- package/dist/mcp_view/storage_source.d.ts +14 -0
- package/dist/mcp_view/storage_source.js +29 -0
- package/dist/mcp_view/storage_source.js.map +1 -0
- package/dist/mcp_view/store.d.ts +9 -0
- package/dist/mcp_view/store.js +27 -0
- package/dist/mcp_view/store.js.map +1 -0
- package/dist/mcp_view/tool_driver.d.ts +135 -0
- package/dist/mcp_view/tool_driver.js +527 -0
- package/dist/mcp_view/tool_driver.js.map +1 -0
- package/dist/preview/components/DatePreview.d.ts +34 -1
- package/dist/preview/components/DatePreview.js +72 -37
- package/dist/preview/components/DatePreview.js.map +1 -1
- package/dist/routes/RebaseRoute.js +1 -1
- package/dist/routes/RebaseRoute.js.map +1 -1
- package/dist/selection/SelectionMenu.d.ts +5 -3
- package/dist/selection/SelectionMenu.js +16 -9
- package/dist/selection/SelectionMenu.js.map +1 -1
- package/dist/selection/index.d.ts +2 -1
- package/dist/selection/resolve_selection.d.ts +61 -7
- package/dist/selection/resolve_selection.js +93 -11
- package/dist/selection/resolve_selection.js.map +1 -1
- package/dist/types/components/EntityFormProps.d.ts +60 -10
- package/dist/types/fields.d.ts +2 -65
- package/dist/util/dataControllerAdapter.d.ts +8 -0
- package/dist/util/dataControllerAdapter.js +11 -0
- package/dist/util/dataControllerAdapter.js.map +1 -1
- package/dist/util/navigation_utils.d.ts +5 -4
- package/dist/util/navigation_utils.js +6 -6
- package/dist/util/navigation_utils.js.map +1 -1
- package/dist/util/propertyConfigMapper.d.ts +8 -0
- package/dist/util/propertyConfigMapper.js +16 -2
- package/dist/util/propertyConfigMapper.js.map +1 -1
- package/package.json +15 -9
- package/recipes/README.md +79 -26
- package/recipes/approval-queue.tsx +79 -0
- package/recipes/bulk-set-status.tsx +23 -17
- package/recipes/calendar-view.tsx +28 -23
- package/recipes/master-detail.tsx +75 -0
- package/recipes/my-preferences.tsx +3 -3
- package/recipes/orders-dashboard.tsx +58 -84
- package/recipes/site-settings.tsx +4 -4
- package/dist/components/EntityFormPanel.d.ts +0 -63
- package/dist/components/EntityFormPanel.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useNavigationResolution.js","names":[],"sources":["../../../src/hooks/navigation/useNavigationResolution.ts"],"sourcesContent":["import type { AuthCollectionConfig, CollectionCallbacks } from \"@rebasepro/types\";\nimport type { AppView, AppViewsBuilder, EntityAction, CollectionConfigsBuilder, RebaseContext, RebasePlugin, UserCreationResult, AdminCollection } from \"@rebasepro/cms-types\";\nimport { type User, type RebaseData } from \"@rebasepro/types\";\nimport { type AuthController, resolveAdminCollection } from \"@rebasepro/cms-types\";\nimport { canReadCollection } from \"@rebasepro/common\";\nimport { accountAccessAction, resetMfaAction, resetPasswordAction } from \"../../components/common/default_entity_actions\";\nimport { CreationResultDialog } from \"../../components/admin/CreationResultDialog\";\nimport React from \"react\";\n\n/**\n * Check whether a `RebaseCallContext` is actually the full frontend\n * `RebaseContext` (which carries `dialogsController`).\n */\nfunction isRebaseContext(ctx: unknown): ctx is RebaseContext {\n return typeof ctx === \"object\" && ctx !== null && \"dialogsController\" in ctx;\n}\n\nexport function filterOutNotAllowedCollections(resolvedCollections: AdminCollection[], authController: AuthController): AdminCollection[] {\n return resolvedCollections\n .filter((c) => canReadCollection(c, authController))\n .map((c) => {\n if (!c.childCollections) return c;\n return {\n ...c,\n childCollections: () => filterOutNotAllowedCollections(c.childCollections!() ?? [], authController)\n };\n });\n}\n\nexport function applyPluginModifyCollection(resolvedCollections: AdminCollection[], modifyCollection: (collection: AdminCollection) => AdminCollection): AdminCollection[] {\n return resolvedCollections.map((collection): AdminCollection => {\n const modifiedCollection = modifyCollection(collection);\n if (modifiedCollection.childCollections) {\n return {\n ...modifiedCollection,\n childCollections: () => applyPluginModifyCollection(modifiedCollection.childCollections!() ?? [], modifyCollection)\n };\n }\n return modifiedCollection;\n });\n}\n\n/**\n * Auto-inject auth-specific entity actions and callbacks for collections\n * with `auth: true` or `auth: { enabled: true }`.\n *\n * Injections:\n * 1. **resetPasswordAction** — adds the entity action unless explicitly disabled,\n * or unless the auth adapter reports no `adminPasswordReset` support. Custom\n * adapters mount their own admin routes and may not implement\n * `POST /admin/users/:userId/reset-password`; injecting the action anyway\n * would show a button that can only ever 404.\n * 2. **browserCallbacks.afterSave** — shows the `CreationResultDialog` when a\n * new user is created with `invitationSent` or `temporaryPassword` in the\n * response\n *\n * Skips injection if the collection already has the action/callback present.\n */\nfunction injectAuthCollectionConfig(\n collections: AdminCollection[],\n adminPasswordResetSupported: boolean\n): AdminCollection[] {\n return collections.map((collection) => {\n const authProp = collection.auth;\n if (!authProp) return collection;\n\n const isAuth = authProp === true || (typeof authProp === \"object\" && authProp.enabled === true);\n if (!isAuth) return collection;\n\n const authConfig: AuthCollectionConfig | undefined = typeof authProp === \"object\" ? authProp : undefined;\n\n let result = collection;\n\n // ─── Entity Action injection (resetPassword) ─────────────────────\n const resetPref = authConfig?.actions?.resetPassword;\n let actionToInject: EntityAction | undefined;\n\n if (resetPref === false) {\n actionToInject = undefined;\n } else if (typeof resetPref === \"object\") {\n // An explicitly supplied action is the collection author's own; they\n // own its backend, so the adapter capability doesn't apply.\n // `auth.actions.resetPassword`'s object form is an EntityAction; core\n // types it as `object` because a server never renders one.\n actionToInject = resetPref as EntityAction;\n } else if (!adminPasswordResetSupported) {\n actionToInject = undefined;\n } else {\n actionToInject = resetPasswordAction;\n }\n\n if (actionToInject) {\n const injectedAction = actionToInject;\n const existing = result.entityActions ?? [];\n // An entry is either the action or the key of an app-level one, and a\n // collection that names `\"reset_password\"` already has this action — so\n // the string form has to count here too, or the reset action is injected\n // a second time and the user gets two identical buttons.\n const alreadyHas = existing.some((a) =>\n typeof a === \"string\"\n ? a === injectedAction.key\n : a.key != null && a.key === injectedAction.key\n );\n if (!alreadyHas) {\n result = {\n ...result,\n entityActions: [...existing, injectedAction]\n };\n }\n }\n\n // ─── The other admin user actions ───────────────────────────────\n //\n // Resetting a user's second factors and switching an account off are\n // mounted by the same admin user routes as the password reset, so the\n // same capability says whether they exist. Each action is offered only\n // to a caller holding `users:write`, which is what the routes demand.\n if (adminPasswordResetSupported) {\n const present = result.entityActions ?? [];\n const missing = [resetMfaAction, accountAccessAction].filter((action) => !present.some((a) =>\n typeof a === \"string\" ? a === action.key : a.key != null && a.key === action.key));\n if (missing.length > 0) {\n result = { ...result, entityActions: [...present, ...missing] };\n }\n }\n\n // ─── afterSave callback (creation result dialog) ─────────────────\n //\n // `browserCallbacks`, not `callbacks`. This injection has always been a\n // panel behaviour — it opens a dialog — but it was installed on the\n // server's block, which nothing in the browser runs and which the Vite\n // plugin strips on the way into the bundle. So it never fired, and\n // creating a user through the panel never showed the temporary password\n // the server had just minted and will not repeat.\n const existingAfterSave = result.browserCallbacks?.afterSave;\n const injectedAfterSave = {\n ...result.browserCallbacks,\n afterSave: (async (props) => {\n await existingAfterSave?.(props);\n\n const { values, status, context } = props;\n if (status !== \"new\" && status !== \"copy\") return;\n\n const hasCreationInfo = values.invitationSent !== undefined || values.temporaryPassword !== undefined;\n if (!hasCreationInfo || !isRebaseContext(context) || !context.dialogsController) return;\n\n const { dialogsController } = context;\n\n const creationResult: UserCreationResult = {\n user: {\n uid: String(props.id),\n email: typeof values.email === \"string\" ? values.email : \"\",\n displayName: typeof values.displayName === \"string\" ? values.displayName : \"\",\n roles: Array.isArray(values.roles) ? values.roles as string[] : [],\n photoURL: typeof values.photoURL === \"string\"\n ? values.photoURL\n : typeof values.photoUrl === \"string\"\n ? values.photoUrl\n : null,\n providerId: \"password\",\n isAnonymous: false\n },\n invitationSent: !!values.invitationSent,\n temporaryPassword: typeof values.temporaryPassword === \"string\" ? values.temporaryPassword : undefined,\n emailDeliveryFailed: !!values.emailDeliveryFailed\n };\n\n const { closeDialog } = dialogsController.open({\n key: \"user_creation_result\",\n Component: () => (\n React.createElement(CreationResultDialog, {\n result: creationResult,\n onClose: () => closeDialog()\n })\n )\n });\n }) as NonNullable<CollectionCallbacks[\"afterSave\"]>\n };\n\n // Written to both the flat key and the block. This injection runs after\n // `resolveAdminCollection` has flattened `admin` onto the top level, and\n // that flattening spreads the block *over* the top level — so anything\n // put only up here is undone the next time a collection is re-resolved,\n // which the registry controller does on every lookup. Writing both keeps\n // re-flattening the no-op its callers already believe it is.\n result = {\n ...result,\n browserCallbacks: injectedAfterSave,\n admin: {\n ...result.admin,\n browserCallbacks: injectedAfterSave\n }\n };\n\n return result;\n });\n}\n\nexport async function resolveCollections(\n collections: undefined | AdminCollection[] | CollectionConfigsBuilder,\n authController: AuthController,\n data: RebaseData,\n plugins: RebasePlugin[] | undefined\n): Promise<AdminCollection[]> {\n let resolvedCollections: AdminCollection[] = [];\n if (typeof collections === \"function\") {\n resolvedCollections = await collections({\n user: authController.user,\n authController,\n data\n });\n } else if (Array.isArray(collections)) {\n resolvedCollections = collections;\n }\n\n // Collections arrive in the authoring shape, with presentation nested under\n // `admin`. Everything downstream — plugins, navigation, the drawer — reads the\n // panel's flat view model, so `admin.group` or `admin.hideFromNavigation`\n // would otherwise be silently ignored.\n resolvedCollections = resolvedCollections.map(resolveAdminCollection);\n\n if (plugins) {\n for (const plugin of plugins) {\n if (plugin.hooks?.modifyCollection) {\n resolvedCollections = applyPluginModifyCollection(resolvedCollections, plugin.hooks.modifyCollection);\n }\n\n if (plugin.hooks?.injectCollections) {\n // A plugin may return collections in the authoring shape too; the\n // flattening is idempotent, so re-running it is safe.\n resolvedCollections = plugin.hooks.injectCollections(resolvedCollections).map(resolveAdminCollection);\n }\n }\n }\n\n // Auto-inject auth entity actions and callbacks (resetPassword, creation dialog, etc.)\n resolvedCollections = injectAuthCollectionConfig(\n resolvedCollections,\n authController.capabilities?.adminPasswordReset ?? true\n );\n\n resolvedCollections = filterOutNotAllowedCollections(resolvedCollections, authController);\n return resolvedCollections;\n}\n\nexport async function resolveAppViews(\n baseViews: AppView[] | AppViewsBuilder | undefined,\n authController: AuthController,\n data: RebaseData,\n plugins?: RebasePlugin[]\n): Promise<AppView[]> {\n let resolvedViews: AppView[] = [];\n if (typeof baseViews === \"function\") {\n resolvedViews = await baseViews({\n user: authController.user,\n authController,\n data\n }) ?? [];\n } else if (Array.isArray(baseViews)) {\n resolvedViews = baseViews;\n }\n\n // Inject views from plugins\n if (plugins) {\n for (const plugin of plugins) {\n if (plugin.views && plugin.views.length > 0) {\n resolvedViews = [...resolvedViews, ...plugin.views];\n }\n }\n }\n\n // Detect duplicate view slugs (dev warning)\n if (process.env.NODE_ENV !== 'production') {\n const slugCounts = new Map<string, number>();\n resolvedViews.forEach(v => {\n slugCounts.set(v.slug, (slugCounts.get(v.slug) ?? 0) + 1);\n });\n slugCounts.forEach((count, slug) => {\n if (count > 1) {\n console.warn(\n `[Rebase] Duplicate view slug \"${slug}\" detected (${count} views). ` +\n `Last-write-wins. Ensure unique slugs across admin views and plugins.`\n );\n }\n });\n }\n\n // Filter by roles — applies to admin, plugin, and builder-returned views\n resolvedViews = filterViewsByRole(resolvedViews, authController);\n\n return resolvedViews;\n}\n\n/**\n * Filter views by the `roles` field on AppView.\n * When `roles` is set, the view is only included if the current user\n * has at least one of the listed roles. Views without `roles` (or with\n * an empty array) are always included.\n */\nfunction filterViewsByRole(views: AppView[], authController: AuthController): AppView[] {\n const userRoles = authController.user?.roles ?? [];\n return views.filter(view => {\n if (!view.roles || view.roles.length === 0) return true;\n return view.roles.some(role => userRoles.includes(role));\n });\n}\n"],"mappings":";;;;;;;;;;AAaA,SAAS,gBAAgB,KAAoC;CACzD,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,uBAAuB;AAC7E;AAEA,SAAgB,+BAA+B,qBAAwC,gBAAmD;CACtI,OAAO,oBACF,QAAQ,MAAM,kBAAkB,GAAG,cAAc,CAAC,CAAC,CACnD,KAAK,MAAM;EACR,IAAI,CAAC,EAAE,kBAAkB,OAAO;EAChC,OAAO;GACH,GAAG;GACH,wBAAwB,+BAA+B,EAAE,iBAAkB,KAAK,CAAC,GAAG,cAAc;EACtG;CACJ,CAAC;AACT;AAEA,SAAgB,4BAA4B,qBAAwC,kBAAuF;CACvK,OAAO,oBAAoB,KAAK,eAAgC;EAC5D,MAAM,qBAAqB,iBAAiB,UAAU;EACtD,IAAI,mBAAmB,kBACnB,OAAO;GACH,GAAG;GACH,wBAAwB,4BAA4B,mBAAmB,iBAAkB,KAAK,C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Q,UAAU,SAAS,IAAI,CAAC;CAC3D,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"useNavigationResolution.js","names":[],"sources":["../../../src/hooks/navigation/useNavigationResolution.ts"],"sourcesContent":["import type { AuthCollectionConfig, CollectionCallbacks } from \"@rebasepro/types\";\nimport type { AppView, AppViewsBuilder, EntityAction, CollectionConfigsBuilder, RebaseContext, RebasePlugin, UserCreationResult, AdminCollection } from \"@rebasepro/cms-types\";\nimport { type User, type RebaseSdkData } from \"@rebasepro/types\";\nimport { type AuthController, resolveAdminCollection } from \"@rebasepro/cms-types\";\nimport { canReadCollection } from \"@rebasepro/common\";\nimport { accountAccessAction, resetMfaAction, resetPasswordAction } from \"../../components/common/default_entity_actions\";\nimport { CreationResultDialog } from \"../../components/admin/CreationResultDialog\";\nimport React from \"react\";\n\n/**\n * Check whether a `RebaseCallContext` is actually the full frontend\n * `RebaseContext` (which carries `dialogsController`).\n */\nfunction isRebaseContext(ctx: unknown): ctx is RebaseContext {\n return typeof ctx === \"object\" && ctx !== null && \"dialogsController\" in ctx;\n}\n\nexport function filterOutNotAllowedCollections(resolvedCollections: AdminCollection[], authController: AuthController): AdminCollection[] {\n return resolvedCollections\n .filter((c) => canReadCollection(c, authController))\n .map((c) => {\n if (!c.childCollections) return c;\n return {\n ...c,\n childCollections: () => filterOutNotAllowedCollections(c.childCollections!() ?? [], authController)\n };\n });\n}\n\nexport function applyPluginModifyCollection(resolvedCollections: AdminCollection[], modifyCollection: (collection: AdminCollection) => AdminCollection): AdminCollection[] {\n return resolvedCollections.map((collection): AdminCollection => {\n const modifiedCollection = modifyCollection(collection);\n if (modifiedCollection.childCollections) {\n return {\n ...modifiedCollection,\n childCollections: () => applyPluginModifyCollection(modifiedCollection.childCollections!() ?? [], modifyCollection)\n };\n }\n return modifiedCollection;\n });\n}\n\n/**\n * Auto-inject auth-specific entity actions and callbacks for collections\n * with `auth: true` or `auth: { enabled: true }`.\n *\n * Injections:\n * 1. **resetPasswordAction** — adds the entity action unless explicitly disabled,\n * or unless the auth adapter reports no `adminPasswordReset` support. Custom\n * adapters mount their own admin routes and may not implement\n * `POST /admin/users/:userId/reset-password`; injecting the action anyway\n * would show a button that can only ever 404.\n * 2. **browserCallbacks.afterSave** — shows the `CreationResultDialog` when a\n * new user is created with `invitationSent` or `temporaryPassword` in the\n * response\n *\n * Skips injection if the collection already has the action/callback present.\n */\nfunction injectAuthCollectionConfig(\n collections: AdminCollection[],\n adminPasswordResetSupported: boolean\n): AdminCollection[] {\n return collections.map((collection) => {\n const authProp = collection.auth;\n if (!authProp) return collection;\n\n const isAuth = authProp === true || (typeof authProp === \"object\" && authProp.enabled === true);\n if (!isAuth) return collection;\n\n const authConfig: AuthCollectionConfig | undefined = typeof authProp === \"object\" ? authProp : undefined;\n\n let result = collection;\n\n // ─── Entity Action injection (resetPassword) ─────────────────────\n const resetPref = authConfig?.actions?.resetPassword;\n let actionToInject: EntityAction | undefined;\n\n if (resetPref === false) {\n actionToInject = undefined;\n } else if (typeof resetPref === \"object\") {\n // An explicitly supplied action is the collection author's own; they\n // own its backend, so the adapter capability doesn't apply.\n // `auth.actions.resetPassword`'s object form is an EntityAction; core\n // types it as `object` because a server never renders one.\n actionToInject = resetPref as EntityAction;\n } else if (!adminPasswordResetSupported) {\n actionToInject = undefined;\n } else {\n actionToInject = resetPasswordAction;\n }\n\n if (actionToInject) {\n const injectedAction = actionToInject;\n const existing = result.entityActions ?? [];\n // An entry is either the action or the key of an app-level one, and a\n // collection that names `\"reset_password\"` already has this action — so\n // the string form has to count here too, or the reset action is injected\n // a second time and the user gets two identical buttons.\n const alreadyHas = existing.some((a) =>\n typeof a === \"string\"\n ? a === injectedAction.key\n : a.key != null && a.key === injectedAction.key\n );\n if (!alreadyHas) {\n result = {\n ...result,\n entityActions: [...existing, injectedAction]\n };\n }\n }\n\n // ─── The other admin user actions ───────────────────────────────\n //\n // Resetting a user's second factors and switching an account off are\n // mounted by the same admin user routes as the password reset, so the\n // same capability says whether they exist. Each action is offered only\n // to a caller holding `users:write`, which is what the routes demand.\n if (adminPasswordResetSupported) {\n const present = result.entityActions ?? [];\n const missing = [resetMfaAction, accountAccessAction].filter((action) => !present.some((a) =>\n typeof a === \"string\" ? a === action.key : a.key != null && a.key === action.key));\n if (missing.length > 0) {\n result = { ...result, entityActions: [...present, ...missing] };\n }\n }\n\n // ─── afterSave callback (creation result dialog) ─────────────────\n //\n // `browserCallbacks`, not `callbacks`. This injection has always been a\n // panel behaviour — it opens a dialog — but it was installed on the\n // server's block, which nothing in the browser runs and which the Vite\n // plugin strips on the way into the bundle. So it never fired, and\n // creating a user through the panel never showed the temporary password\n // the server had just minted and will not repeat.\n const existingAfterSave = result.browserCallbacks?.afterSave;\n const injectedAfterSave = {\n ...result.browserCallbacks,\n afterSave: (async (props) => {\n await existingAfterSave?.(props);\n\n const { values, status, context } = props;\n if (status !== \"new\" && status !== \"copy\") return;\n\n const hasCreationInfo = values.invitationSent !== undefined || values.temporaryPassword !== undefined;\n if (!hasCreationInfo || !isRebaseContext(context) || !context.dialogsController) return;\n\n const { dialogsController } = context;\n\n const creationResult: UserCreationResult = {\n user: {\n uid: String(props.id),\n email: typeof values.email === \"string\" ? values.email : \"\",\n displayName: typeof values.displayName === \"string\" ? values.displayName : \"\",\n roles: Array.isArray(values.roles) ? values.roles as string[] : [],\n photoURL: typeof values.photoURL === \"string\"\n ? values.photoURL\n : typeof values.photoUrl === \"string\"\n ? values.photoUrl\n : null,\n providerId: \"password\",\n isAnonymous: false\n },\n invitationSent: !!values.invitationSent,\n temporaryPassword: typeof values.temporaryPassword === \"string\" ? values.temporaryPassword : undefined,\n emailDeliveryFailed: !!values.emailDeliveryFailed\n };\n\n const { closeDialog } = dialogsController.open({\n key: \"user_creation_result\",\n Component: () => (\n React.createElement(CreationResultDialog, {\n result: creationResult,\n onClose: () => closeDialog()\n })\n )\n });\n }) as NonNullable<CollectionCallbacks[\"afterSave\"]>\n };\n\n // Written to both the flat key and the block. This injection runs after\n // `resolveAdminCollection` has flattened `admin` onto the top level, and\n // that flattening spreads the block *over* the top level — so anything\n // put only up here is undone the next time a collection is re-resolved,\n // which the registry controller does on every lookup. Writing both keeps\n // re-flattening the no-op its callers already believe it is.\n result = {\n ...result,\n browserCallbacks: injectedAfterSave,\n admin: {\n ...result.admin,\n browserCallbacks: injectedAfterSave\n }\n };\n\n return result;\n });\n}\n\nexport async function resolveCollections(\n collections: undefined | AdminCollection[] | CollectionConfigsBuilder,\n authController: AuthController,\n data: RebaseSdkData,\n plugins: RebasePlugin[] | undefined\n): Promise<AdminCollection[]> {\n let resolvedCollections: AdminCollection[] = [];\n if (typeof collections === \"function\") {\n resolvedCollections = await collections({\n user: authController.user,\n authController,\n data\n });\n } else if (Array.isArray(collections)) {\n resolvedCollections = collections;\n }\n\n // Collections arrive in the authoring shape, with presentation nested under\n // `admin`. Everything downstream — plugins, navigation, the drawer — reads the\n // panel's flat view model, so `admin.group` or `admin.hideFromNavigation`\n // would otherwise be silently ignored.\n resolvedCollections = resolvedCollections.map(resolveAdminCollection);\n\n if (plugins) {\n for (const plugin of plugins) {\n if (plugin.hooks?.modifyCollection) {\n resolvedCollections = applyPluginModifyCollection(resolvedCollections, plugin.hooks.modifyCollection);\n }\n\n if (plugin.hooks?.injectCollections) {\n // A plugin may return collections in the authoring shape too; the\n // flattening is idempotent, so re-running it is safe.\n resolvedCollections = plugin.hooks.injectCollections(resolvedCollections).map(resolveAdminCollection);\n }\n }\n }\n\n // Auto-inject auth entity actions and callbacks (resetPassword, creation dialog, etc.)\n resolvedCollections = injectAuthCollectionConfig(\n resolvedCollections,\n authController.capabilities?.adminPasswordReset ?? true\n );\n\n resolvedCollections = filterOutNotAllowedCollections(resolvedCollections, authController);\n return resolvedCollections;\n}\n\nexport async function resolveAppViews(\n baseViews: AppView[] | AppViewsBuilder | undefined,\n authController: AuthController,\n data: RebaseSdkData,\n plugins?: RebasePlugin[]\n): Promise<AppView[]> {\n let resolvedViews: AppView[] = [];\n if (typeof baseViews === \"function\") {\n resolvedViews = await baseViews({\n user: authController.user,\n authController,\n data\n }) ?? [];\n } else if (Array.isArray(baseViews)) {\n resolvedViews = baseViews;\n }\n\n // Inject views from plugins\n if (plugins) {\n for (const plugin of plugins) {\n if (plugin.views && plugin.views.length > 0) {\n resolvedViews = [...resolvedViews, ...plugin.views];\n }\n }\n }\n\n // Detect duplicate view slugs (dev warning)\n if (process.env.NODE_ENV !== 'production') {\n const slugCounts = new Map<string, number>();\n resolvedViews.forEach(v => {\n slugCounts.set(v.slug, (slugCounts.get(v.slug) ?? 0) + 1);\n });\n slugCounts.forEach((count, slug) => {\n if (count > 1) {\n console.warn(\n `[Rebase] Duplicate view slug \"${slug}\" detected (${count} views). ` +\n `Last-write-wins. Ensure unique slugs across admin views and plugins.`\n );\n }\n });\n }\n\n // Filter by roles — applies to admin, plugin, and builder-returned views\n resolvedViews = filterViewsByRole(resolvedViews, authController);\n\n return resolvedViews;\n}\n\n/**\n * Filter views by the `roles` field on AppView.\n * When `roles` is set, the view is only included if the current user\n * has at least one of the listed roles. Views without `roles` (or with\n * an empty array) are always included.\n */\nfunction filterViewsByRole(views: AppView[], authController: AuthController): AppView[] {\n const userRoles = authController.user?.roles ?? [];\n return views.filter(view => {\n if (!view.roles || view.roles.length === 0) return true;\n return view.roles.some(role => userRoles.includes(role));\n });\n}\n"],"mappings":";;;;;;;;;;AAaA,SAAS,gBAAgB,KAAoC;CACzD,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,uBAAuB;AAC7E;AAEA,SAAgB,+BAA+B,qBAAwC,gBAAmD;CACtI,OAAO,oBACF,QAAQ,MAAM,kBAAkB,GAAG,cAAc,CAAC,CAAC,CACnD,KAAK,MAAM;EACR,IAAI,CAAC,EAAE,kBAAkB,OAAO;EAChC,OAAO;GACH,GAAG;GACH,wBAAwB,+BAA+B,EAAE,iBAAkB,KAAK,CAAC,GAAG,cAAc;EACtG;CACJ,CAAC;AACT;AAEA,SAAgB,4BAA4B,qBAAwC,kBA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pF,MAAM,YAAY,eAAe,MAAM,SAAS,CAAC;CACjD,OAAO,MAAM,QAAO,SAAQ;EACxB,IAAI,CAAC,KAAK,SAAS,KAAK,MAAM,WAAW,GAAG,OAAO;EACnD,OAAO,KAAK,MAAM,MAAK,SAAQ,UAAU,SAAS,IAAI,CAAC;CAC3D,CAAC;AACL"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { RebasePlugin, AdminCollection } from "@rebasepro/cms-types";
|
|
2
|
-
import { CollectionRegistryController,
|
|
2
|
+
import { CollectionRegistryController, RebaseSdkData, User } from "@rebasepro/types";
|
|
3
3
|
import { AuthController } from "@rebasepro/cms-types";
|
|
4
4
|
import type { CollectionConfigsBuilder } from "@rebasepro/cms-types";
|
|
5
5
|
import { CollectionRegistry } from "@rebasepro/common";
|
|
6
6
|
export type UseResolvedCollectionsProps<EC extends AdminCollection, USER extends User> = {
|
|
7
7
|
authController: AuthController<USER>;
|
|
8
8
|
collections?: EC[] | CollectionConfigsBuilder<EC>;
|
|
9
|
-
data:
|
|
9
|
+
data: RebaseSdkData;
|
|
10
10
|
plugins?: RebasePlugin[];
|
|
11
11
|
disabled?: boolean;
|
|
12
12
|
collectionRegistryController: CollectionRegistryController<EC> & {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useResolvedCollections.js","names":[],"sources":["../../../src/hooks/navigation/useResolvedCollections.ts"],"sourcesContent":["\nimport type { RebasePlugin, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useRef, useMemo } from \"react\";\n\nimport { CollectionRegistryController,
|
|
1
|
+
{"version":3,"file":"useResolvedCollections.js","names":[],"sources":["../../../src/hooks/navigation/useResolvedCollections.ts"],"sourcesContent":["\nimport type { RebasePlugin, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useRef, useMemo } from \"react\";\n\nimport { CollectionRegistryController, RebaseSdkData, User } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport type { CollectionConfigsBuilder } from \"@rebasepro/cms-types\";\nimport { CollectionRegistry } from \"@rebasepro/common\";\n\nimport { resolveCollections } from \"./useNavigationResolution\";\nimport { areCollectionListsEqual } from \"./utils\";\nimport { useAsyncResolver } from \"./useAsyncResolver\";\n\nexport type UseResolvedCollectionsProps<EC extends AdminCollection, USER extends User> = {\n authController: AuthController<USER>;\n collections?: EC[] | CollectionConfigsBuilder<EC>;\n data: RebaseSdkData;\n plugins?: RebasePlugin[];\n disabled?: boolean;\n collectionRegistryController: CollectionRegistryController<EC> & { collectionRegistryRef: React.MutableRefObject<CollectionRegistry> };\n\n};\n\nexport type UseResolvedCollectionsResult = {\n collections: AdminCollection[];\n loading: boolean;\n error: Error | undefined;\n refresh: () => void;\n};\n\n/**\n * Hook that resolves collection props (which may be async builders or arrays)\n * into concrete AdminCollection[], and registers them with the CollectionRegistry.\n *\n * When userManagement is provided, the default users collection is always\n * prepended. Developer collections override via generic slug-based dedup\n * (Map keyed by slug, last-write-wins). No hardcoded string checks.\n *\n * Uses refs for potentially-unstable dependencies (driver, authController,\n * plugins) to avoid re-triggering effects when their object identity changes.\n */\nexport function useResolvedCollections<EC extends AdminCollection, USER extends User>(\n props: UseResolvedCollectionsProps<EC, USER>\n): UseResolvedCollectionsResult {\n\n const {\n authController,\n collections: collectionsProp,\n data,\n plugins,\n disabled,\n collectionRegistryController\n } = props;\n\n // Stable identity string for the user — avoids re-triggering when the\n // authController object reference changes but uid/roles are the same.\n const userIdentity = authController.user\n ? `${authController.user.uid}:${(authController.user.roles ?? []).sort().join(',')}`\n : null;\n\n // Use refs for values that may be new objects each render but shouldn't\n // re-trigger the effect. The effect reads them at execution time.\n const dataRef = useRef(data);\n dataRef.current = data;\n const authControllerRef = useRef(authController);\n authControllerRef.current = authController;\n const pluginsRef = useRef(plugins);\n pluginsRef.current = plugins;\n\n const { data: collections, loading, error, refresh } = useAsyncResolver<AdminCollection[]>({\n resolver: async () => {\n const resolved = await resolveCollections(\n collectionsProp,\n authControllerRef.current,\n dataRef.current,\n pluginsRef.current\n );\n\n const deduped = [...resolved];\n\n // Register with the CollectionRegistry; returns true if changed\n const changed = collectionRegistryController.collectionRegistryRef.current.registerMultiple(deduped);\n\n if (changed) {\n console.debug(\"Collections have changed\", deduped);\n }\n\n return deduped;\n },\n initialValue: [],\n isEqual: areCollectionListsEqual,\n deps: [collectionsProp, userIdentity, disabled],\n disabled: disabled || authController.initialLoading,\n });\n\n return useMemo(() => ({\n collections,\n loading,\n error,\n refresh\n }), [collections, loading, error, refresh]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,SAAgB,uBACZ,OAC4B;CAE5B,MAAM,EACF,gBACA,aAAa,iBACb,MACA,SACA,UACA,iCACA;CAIJ,MAAM,eAAe,eAAe,OAC9B,GAAG,eAAe,KAAK,IAAI,IAAI,eAAe,KAAK,SAAS,CAAC,EAAA,CAAG,KAAK,CAAC,CAAC,KAAK,GAAG,MAC/E;CAIN,MAAM,UAAU,OAAO,IAAI;CAC3B,QAAQ,UAAU;CAClB,MAAM,oBAAoB,OAAO,cAAc;CAC/C,kBAAkB,UAAU;CAC5B,MAAM,aAAa,OAAO,OAAO;CACjC,WAAW,UAAU;CAErB,MAAM,EAAE,MAAM,aAAa,SAAS,OAAO,YAAY,iBAAoC;EACvF,UAAU,YAAY;GAQlB,MAAM,UAAU,CAAC,GAAG,MAPG,mBACnB,iBACA,kBAAkB,SAClB,QAAQ,SACR,WAAW,OACf,CAE4B;GAK5B,IAFgB,6BAA6B,sBAAsB,QAAQ,iBAAiB,OAExF,GACA,QAAQ,MAAM,4BAA4B,OAAO;GAGrD,OAAO;EACX;EACA,cAAc,CAAC;EACf,SAAS;EACT,MAAM;GAAC;GAAiB;GAAc;EAAQ;EAC9C,UAAU,YAAY,eAAe;CACzC,CAAC;CAED,OAAO,eAAe;EAClB;EACA;EACA;EACA;CACJ,IAAI;EAAC;EAAa;EAAS;EAAO;CAAO,CAAC;AAC9C"}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import type { EffectiveRoleController } from "@rebasepro/types";
|
|
2
2
|
import type { AppView, AppViewsBuilder, RebasePlugin } from "@rebasepro/cms-types";
|
|
3
|
-
import type {
|
|
3
|
+
import type { RebaseSdkData, User } from "@rebasepro/types";
|
|
4
4
|
import type { AuthController } from "@rebasepro/cms-types";
|
|
5
5
|
export type UseResolvedViewsProps<USER extends User> = {
|
|
6
6
|
authController: AuthController<USER>;
|
|
7
7
|
views?: AppView[] | AppViewsBuilder;
|
|
8
8
|
adminViews?: AppView[] | AppViewsBuilder;
|
|
9
|
-
data:
|
|
9
|
+
data: RebaseSdkData;
|
|
10
10
|
plugins?: RebasePlugin[];
|
|
11
11
|
adminMode?: "cms" | "studio";
|
|
12
12
|
effectiveRoleController?: EffectiveRoleController;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useResolvedViews.js","names":[],"sources":["../../../src/hooks/navigation/useResolvedViews.tsx"],"sourcesContent":["\nimport type { EffectiveRoleController } from \"@rebasepro/types\";\nimport type { AppView, AppViewsBuilder, RebasePlugin } from \"@rebasepro/cms-types\";\nimport { useMemo, useRef } from \"react\";\n\n/**\n * Compare two view arrays by their slug identity.\n * Returns true when the sets of slugs are identical (same order, same values).\n * This avoids deepEqual on React elements, which have unstable internal refs.\n */\nfunction viewSlugsEqual(a: AppView[] | undefined, b: AppView[] | undefined): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].slug !== b[i].slug) return false;\n }\n return true;\n}\n\nimport type {
|
|
1
|
+
{"version":3,"file":"useResolvedViews.js","names":[],"sources":["../../../src/hooks/navigation/useResolvedViews.tsx"],"sourcesContent":["\nimport type { EffectiveRoleController } from \"@rebasepro/types\";\nimport type { AppView, AppViewsBuilder, RebasePlugin } from \"@rebasepro/cms-types\";\nimport { useMemo, useRef } from \"react\";\n\n/**\n * Compare two view arrays by their slug identity.\n * Returns true when the sets of slugs are identical (same order, same values).\n * This avoids deepEqual on React elements, which have unstable internal refs.\n */\nfunction viewSlugsEqual(a: AppView[] | undefined, b: AppView[] | undefined): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i].slug !== b[i].slug) return false;\n }\n return true;\n}\n\nimport type { RebaseSdkData, User } from \"@rebasepro/types\";\nimport type { AuthController } from \"@rebasepro/cms-types\";\n\nimport { resolveAppViews } from \"./useNavigationResolution\";\nimport { useAsyncResolver } from \"./useAsyncResolver\";\n\nexport type UseResolvedViewsProps<USER extends User> = {\n authController: AuthController<USER>;\n views?: AppView[] | AppViewsBuilder;\n adminViews?: AppView[] | AppViewsBuilder;\n data: RebaseSdkData;\n plugins?: RebasePlugin[];\n adminMode?: \"cms\" | \"studio\";\n effectiveRoleController?: EffectiveRoleController;\n};\n\nexport type UseResolvedViewsResult = {\n views: AppView[] | undefined;\n adminViews: AppView[] | undefined;\n loading: boolean;\n error: Error | undefined;\n refresh: () => void;\n};\n\n/**\n * Combined result type for the async resolver — holds both views and\n * adminViews so they can be resolved together in a single async call.\n */\ntype ResolvedViewsData = {\n views: AppView[] | undefined;\n adminViews: AppView[] | undefined;\n};\n\n/**\n * Equality check for the combined views data.\n * Compares both views and adminViews by slug identity.\n */\nfunction areResolvedViewsEqual(a: ResolvedViewsData, b: ResolvedViewsData): boolean {\n return viewSlugsEqual(a.views, b.views) && viewSlugsEqual(a.adminViews, b.adminViews);\n}\n\n/**\n * Hook that resolves view and admin view props (which may be async builders or arrays)\n * into concrete AppView[].\n *\n * Uses refs for potentially-unstable dependencies (driver, authController,\n * plugins) to avoid re-triggering effects when their object identity changes.\n */\nexport function useResolvedViews<USER extends User>(\n props: UseResolvedViewsProps<USER>\n): UseResolvedViewsResult {\n\n const {\n authController,\n views: viewsProp,\n adminViews: adminViewsProp,\n data,\n plugins,\n adminMode = \"cms\",\n effectiveRoleController\n } = props;\n\n // Stable identity string for the user — avoids re-triggering when the\n // authController object reference changes but uid/roles are the same.\n const userIdentity = authController.user\n ? `${authController.user.uid}:${(authController.user.roles ?? []).sort().join(',')}`\n : null;\n\n // Use refs for values that may be new objects each render but shouldn't\n // re-trigger the effect. The effect reads them at execution time.\n const dataRef = useRef(data);\n dataRef.current = data;\n const authControllerRef = useRef(authController);\n authControllerRef.current = authController;\n const pluginsRef = useRef(plugins);\n pluginsRef.current = plugins;\n\n // Build the resolved auth controller (with effective role override for studio mode)\n const resolvedAuthController = useMemo(() => {\n if (adminMode === \"studio\" && effectiveRoleController?.effectiveRole && authController.user) {\n return {\n ...authController,\n user: {\n ...authController.user,\n roles: [effectiveRoleController.effectiveRole]\n }\n };\n }\n return authController;\n }, [adminMode, effectiveRoleController?.effectiveRole, authController]);\n\n // Store resolvedAuthController in a ref for effect access without re-triggering\n const resolvedAuthControllerRef = useRef(resolvedAuthController);\n resolvedAuthControllerRef.current = resolvedAuthController;\n\n const initialLoading = resolvedAuthController.initialLoading;\n\n const { data: resolvedData, loading, error, refresh } = useAsyncResolver<ResolvedViewsData>({\n resolver: async () => {\n const [newViews, newAdminViews] = await Promise.all([\n resolveAppViews(viewsProp, resolvedAuthControllerRef.current, dataRef.current, pluginsRef.current),\n resolveAppViews(adminViewsProp, resolvedAuthControllerRef.current, dataRef.current)\n ]);\n return { views: newViews, adminViews: newAdminViews };\n },\n initialValue: { views: undefined, adminViews: undefined },\n isEqual: areResolvedViewsEqual,\n deps: [viewsProp, adminViewsProp, adminMode, userIdentity],\n disabled: initialLoading,\n });\n\n return useMemo(() => ({\n views: resolvedData.views,\n adminViews: resolvedData.adminViews,\n loading,\n error,\n refresh\n }), [resolvedData, loading, error, refresh]);\n}\n"],"mappings":";;;;;;;;;AAUA,SAAS,eAAe,GAA0B,GAAmC;CACjF,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,CAAC,KAAK,CAAC,GAAG,OAAO;CACrB,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAA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AY;GAAc;EACxD;EACA,cAAc;GAAE,OAAO,KAAA;GAAW,YAAY,KAAA;EAAU;EACxD,SAAS;EACT,MAAM;GAAC;GAAW;GAAgB;GAAW;EAAY;EACzD,UAAU;CACd,CAAC;CAED,OAAO,eAAe;EAClB,OAAO,aAAa;EACpB,YAAY,aAAa;EACzB;EACA;EACA;CACJ,IAAI;EAAC;EAAc;EAAS;EAAO;CAAO,CAAC;AAC/C"}
|
|
@@ -107,10 +107,10 @@ var useBuildSidePanel = (collectionRegistryController, urlController, navigation
|
|
|
107
107
|
updateUrl: false,
|
|
108
108
|
allowFullScreen: false
|
|
109
109
|
};
|
|
110
|
-
if (props.copy && !hasEntityId(props.
|
|
110
|
+
if (props.copy && !hasEntityId(props.id)) throw Error("To open a copy, pass the id of the record to copy");
|
|
111
111
|
const defaultSelectedView = resolveDefaultSelectedView(props.collection ? props.collection.defaultSelectedView : void 0, {
|
|
112
|
-
status: props.copy ? "copy" : hasEntityId(props.
|
|
113
|
-
|
|
112
|
+
status: props.copy ? "copy" : hasEntityId(props.id) ? "existing" : "new",
|
|
113
|
+
id: props.id
|
|
114
114
|
});
|
|
115
115
|
sideDialogsController.open(propsToSidePanel({
|
|
116
116
|
...props,
|
|
@@ -130,7 +130,7 @@ var useBuildSidePanel = (collectionRegistryController, urlController, navigation
|
|
|
130
130
|
updateUrl: false,
|
|
131
131
|
allowFullScreen: false
|
|
132
132
|
};
|
|
133
|
-
if (props.copy && !hasEntityId(props.
|
|
133
|
+
if (props.copy && !hasEntityId(props.id)) throw Error("To open a copy, pass the id of the record to copy");
|
|
134
134
|
sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));
|
|
135
135
|
}, [
|
|
136
136
|
urlController.buildUrlCollectionPath,
|
|
@@ -166,7 +166,7 @@ function buildSidePanelsFromUrl(path, collections, newFlag) {
|
|
|
166
166
|
const previousEntry = navigationViewsForPath[i - 1];
|
|
167
167
|
if (navigationEntry.type === "entity") sidePanel = {
|
|
168
168
|
path: navigationEntry.slug,
|
|
169
|
-
|
|
169
|
+
id: navigationEntry.entityId,
|
|
170
170
|
copy: false,
|
|
171
171
|
collection: navigationEntry.parentCollection,
|
|
172
172
|
width: navigationEntry.parentCollection?.sideDialogWidth
|
|
@@ -184,8 +184,8 @@ function buildSidePanelsFromUrl(path, collections, newFlag) {
|
|
|
184
184
|
if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith("/edit")) sidePanel.selectedTab = "edit";
|
|
185
185
|
if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {
|
|
186
186
|
const defaultView = resolveDefaultSelectedView(sidePanel.collection.defaultSelectedView, {
|
|
187
|
-
status: sidePanel.copy ? "copy" : hasEntityId(sidePanel.
|
|
188
|
-
|
|
187
|
+
status: sidePanel.copy ? "copy" : hasEntityId(sidePanel.id) ? "existing" : "new",
|
|
188
|
+
id: sidePanel.id
|
|
189
189
|
});
|
|
190
190
|
if (defaultView) sidePanel.selectedTab = defaultView;
|
|
191
191
|
}
|
|
@@ -199,7 +199,7 @@ var propsToSidePanel = (props, buildUrlCollectionPath, resolveIdsFrom, smallLayo
|
|
|
199
199
|
const collectionPath = removeInitialAndTrailingSlashes(props.path);
|
|
200
200
|
const locationSearch = typeof window !== "undefined" ? window.location.search : "";
|
|
201
201
|
const shouldUpdateUrl = props.updateUrl !== false;
|
|
202
|
-
const urlPath = shouldUpdateUrl ? hasEntityId(props.
|
|
202
|
+
const urlPath = shouldUpdateUrl ? hasEntityId(props.id) ? `${buildUrlCollectionPath(`${collectionPath}/${props.id}${props.selectedTab ? "/" + props.selectedTab : ""}`)}${locationSearch}#${SIDE_URL_HASH}` : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}` : void 0;
|
|
203
203
|
const parentUrlPath = shouldUpdateUrl ? buildUrlCollectionPath(collectionPath) : void 0;
|
|
204
204
|
const resolvedPanelProps = {
|
|
205
205
|
...props,
|
|
@@ -207,7 +207,7 @@ var propsToSidePanel = (props, buildUrlCollectionPath, resolveIdsFrom, smallLayo
|
|
|
207
207
|
};
|
|
208
208
|
const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);
|
|
209
209
|
return {
|
|
210
|
-
key: `${props.path}/${props.
|
|
210
|
+
key: `${props.path}/${props.id}`,
|
|
211
211
|
component: /* @__PURE__ */ jsx(ResolvedSidePanelBinding, { ...resolvedPanelProps }),
|
|
212
212
|
urlPath,
|
|
213
213
|
parentUrlPath,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useBuildSidePanel.js","names":[],"sources":["../../src/hooks/useBuildSidePanel.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport type { CustomizationController, SidePanelBindingProps, SideDialogPanelProps, SideDialogsController, SidePanelController, UrlController, NavigationStateController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport { useLocation } from \"react-router\";\nimport { NavigationViewInternal } from \"@rebasepro/app\";\nimport { getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView } from \"@rebasepro/app\";\nimport { resolvedSelectedEntityView } from \"../util/resolutions\";\nimport { CONTAINER_FULL_WIDTH, SIDE_PANEL_DEFAULT_WIDTH } from \"@rebasepro/app\";\nimport { useCustomizationController, useLargeLayout, useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { JSON_TAB_VALUE, HISTORY_TAB_VALUE } from \"../util/view_constants\";\nimport React, { Suspense } from \"react\";\nimport { CircularProgressCenter } from \"@rebasepro/ui\";\n// Lazy: this hook runs on every page (the side-panel provider is mounted by\n// RebaseNavigation), and the panel's form stack is not needed until one opens.\nimport { LazySidePanelBinding as SidePanelBinding } from \"../components/lazy_record_views\";\n\n/**\n * Thin wrapper that resolves the Entity.SidePanel component override.\n * Because the JSX is created inside `propsToSidePanel` (a plain function,\n * not a React component), we need this wrapper so the hook is called at the\n * top level of a React component per the Rules of Hooks.\n */\nfunction ResolvedSidePanelBindingInner(props: SidePanelBindingProps) {\n const Resolved = useComponentOverride<SidePanelBindingProps>(\"Entity.SidePanel\", SidePanelBinding);\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Resolved {...props}/>\n </Suspense>;\n}\n\nfunction ResolvedSidePanelBinding(props: SidePanelBindingProps) {\n if (props.collection) {\n return (\n <CollectionScopeProvider collection={props.collection}>\n <ResolvedSidePanelBindingInner {...props}/>\n </CollectionScopeProvider>\n );\n }\n return <ResolvedSidePanelBindingInner {...props}/>;\n}\n\nconst NEW_URL_HASH = \"new_side\";\nconst SIDE_URL_HASH = \"side\";\n\n/**\n * How wide the side panel opens.\n *\n * One width for the whole panel, whatever tab is showing. It used to depend on\n * the selected tab — the form got one width and a subcollection or custom view\n * got `calc(55vw + 768px)` — so the panel physically resized under the cursor\n * every time you switched tabs. And the \"form\" width was derived from how\n * deeply nested the collection's *properties* were, which is not a thing anyone\n * can predict from looking at the panel.\n *\n * Now: `width` prop, then the collection's `sideDialogWidth`, then a default\n * sized for the content the panel actually has to hold — the form column plus\n * its metadata rail — capped so it never eats the whole window.\n */\nexport function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string {\n if (small) return CONTAINER_FULL_WIDTH;\n\n if (props.width) {\n return typeof props.width === \"number\" ? `${props.width}px` : props.width;\n }\n if (props.collection?.sideDialogWidth) {\n return typeof props.collection.sideDialogWidth === \"number\"\n ? `${props.collection.sideDialogWidth}px`\n : props.collection.sideDialogWidth;\n }\n return SIDE_PANEL_DEFAULT_WIDTH;\n}\n\nexport const useBuildSidePanel = (collectionRegistryController: CollectionRegistryController,\n urlController: UrlController,\n navigationStateController: NavigationStateController,\n sideDialogsController: SideDialogsController,\n authController: AuthController\n): SidePanelController => {\n\n const location = useLocation();\n const initialised = useRef<boolean>(false);\n const currentPanelKeysRef = useRef<string[]>([]);\n const customizationController = useCustomizationController();\n\n const smallLayout = !useLargeLayout();\n\n useEffect(() => {\n\n const newFlag = location.hash === `#${NEW_URL_HASH}`;\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n\n if (!navigationStateController.loading) {\n if ((newFlag || sideFlag) && urlController.isUrlCollectionPath(location.pathname)) {\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], newFlag);\n for (let i = 0; i < panelsFromUrl.length; i++) {\n const props = panelsFromUrl[i];\n if (i === 0)\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n else\n sideDialogsController.open(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController))\n }\n }\n initialised.current = true;\n }\n }, [navigationStateController.loading]);\n\n // sync panels if URL changes with #side\n // Use a ref for currentPanelKeys so this effect only fires on URL changes,\n // not on panel state changes. This prevents a race condition with React Router 7\n // where close() clears panels before the URL updates, causing the effect to\n // re-open the panel from the stale #side hash.\n currentPanelKeysRef.current = sideDialogsController.sidePanels.map(p => p.key);\n useEffect(() => {\n if (initialised.current) {\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n if (sideFlag) {\n const currentKeys = currentPanelKeysRef.current;\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], false);\n // if we have more panels than determined by the url, we ignore the url. We might have references open\n if (panelsFromUrl.length <= currentKeys.length) {\n return;\n }\n const lastPanel = panelsFromUrl[panelsFromUrl.length - 1];\n const panelProps = propsToSidePanel(lastPanel, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController);\n const lastCurrentPanel = currentKeys.length > 0 ? currentKeys[currentKeys.length - 1] : undefined;\n if (!lastCurrentPanel || lastCurrentPanel !== panelProps.key) {\n sideDialogsController.replace(panelProps);\n }\n }\n }\n }, [location.pathname, location.hash]);\n\n // update side panels to match browser size\n // Only update panel widths on layout change — don't recreate components.\n // Recreating components would unmount/remount SidePanelBinding, losing\n // scroll position, unsaved form state, and triggering unnecessary data fetches.\n useEffect(() => {\n const updatedSidePanels = sideDialogsController.sidePanels.map(sidePanelProps => {\n if (sidePanelProps.additional) {\n const entityProps = sidePanelProps.additional as SidePanelBindingProps;\n const newWidth = getEntityViewWidth(entityProps, smallLayout, customizationController);\n if (sidePanelProps.width !== newWidth) {\n return { ...sidePanelProps,\nwidth: newWidth };\n }\n }\n return sidePanelProps;\n });\n sideDialogsController.setSidePanels(updatedSidePanels);\n }, [smallLayout]);\n\n const close = useCallback(() => {\n sideDialogsController.close();\n }, [sideDialogsController]);\n\n // Where no CMS route serves the page, a panel is an overlay and nothing\n // more: it writes no URL (one would lead nowhere) and offers no way to a\n // full-screen route that does not exist.\n const routesMounted = urlController.routesMounted !== false;\n\n const open = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.entityId)) {\n throw Error(\"If you want to copy a entity you need to provide a entityId\");\n }\n\n const defaultSelectedView = resolveDefaultSelectedView(\n props.collection ? props.collection.defaultSelectedView : undefined,\n {\n status: props.copy ? \"copy\" : (hasEntityId(props.entityId) ? \"existing\" : \"new\"),\n entityId: props.entityId\n }\n );\n\n sideDialogsController.open(\n propsToSidePanel({\n ...props,\n selectedTab: props.selectedTab ?? defaultSelectedView\n },\n urlController.buildUrlCollectionPath,\n urlController.resolveDatabasePathsFrom,\n smallLayout,\n customizationController,\n authController\n ));\n\n }, [sideDialogsController, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, authController.user, routesMounted]);\n\n const replace = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.entityId)) {\n throw Error(\"If you want to copy a entity you need to provide a entityId\");\n }\n\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n\n }, [urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, sideDialogsController, smallLayout, authController.user, routesMounted]);\n\n return useMemo(() => ({\n close,\n open,\n replace\n }), [close, open, replace]);\n};\n\nexport function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[] {\n\n const navigationViewsForPath: NavigationViewInternal<any>[] = getNavigationEntriesFromPath({\n path,\n collections\n });\n\n let sidePanel: SidePanelBindingProps<any> | undefined = undefined;\n let lastCollectionPath = \"\";\n let lastCollectionId: string | undefined = undefined;\n for (let i = 0; i < navigationViewsForPath.length; i++) {\n const navigationEntry = navigationViewsForPath[i];\n\n if (navigationEntry.type === \"collection\") {\n lastCollectionPath = navigationEntry.slug;\n lastCollectionId = navigationEntry.collection.slug;\n }\n\n const previousEntry = navigationViewsForPath[i - 1];\n if (navigationEntry.type === \"entity\") {\n sidePanel = {\n path: navigationEntry.slug,\n entityId: navigationEntry.entityId,\n copy: false,\n collection: navigationEntry.parentCollection,\n width: navigationEntry.parentCollection?.sideDialogWidth\n };\n } else if (navigationEntry.type === \"custom_view\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.view.key;\n }\n } else if (navigationEntry.type === \"collection\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.collection.slug;\n }\n }\n\n }\n\n // `edit` is not a registered view, so the navigation parser skips it. Pick it\n // up from the raw path so that reloading an edit URL reopens the edit form\n // rather than silently dropping the user back on the detail view.\n if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith(\"/edit\")) {\n sidePanel.selectedTab = \"edit\";\n }\n\n // When the URL doesn't contain a tab segment but the collection has a\n // defaultSelectedView, resolve it so the panel opens with the correct\n // width and the URL is updated on the next replace() cycle.\n if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {\n const defaultView = resolveDefaultSelectedView(\n sidePanel.collection.defaultSelectedView,\n {\n status: sidePanel.copy ? \"copy\" : (hasEntityId(sidePanel.entityId) ? \"existing\" : \"new\"),\n entityId: sidePanel.entityId\n }\n );\n if (defaultView) {\n sidePanel.selectedTab = defaultView;\n }\n }\n\n if (newFlag) {\n sidePanel = {\n path: lastCollectionPath,\n copy: false\n }\n }\n\n return sidePanel ? [sidePanel] : [];\n}\n\nconst propsToSidePanel = (props: SidePanelBindingProps,\n buildUrlCollectionPath: (path: string) => string,\n resolveIdsFrom: (pathWithAliases: string) => string,\n smallLayout: boolean,\n customizationController: CustomizationController,\n authController: AuthController\n): SideDialogPanelProps => {\n\n const collectionPath = removeInitialAndTrailingSlashes(props.path);\n\n // The list's state — search, filters, sort, view mode — read from the\n // address bar at the moment the panel opens. Not react-router's\n // `location.search`: the list writes its state with `replaceState`, which\n // the router does not observe, so that value is whatever the view mounted\n // with, and the list reads a panel URL built from it back as its state.\n const locationSearch = typeof window !== \"undefined\" ? window.location.search : \"\";\n\n // When updateUrl is explicitly false, don't generate URL paths — the dialog\n // opens as an overlay without affecting the browser URL / router.\n const shouldUpdateUrl = props.updateUrl !== false;\n\n // `buildUrlCollectionPath` encodes every segment of the data path it is\n // given, the record id among them, so the query and the hash go after it.\n const urlPath = shouldUpdateUrl\n ? (hasEntityId(props.entityId)\n ? `${buildUrlCollectionPath(`${collectionPath}/${props.entityId}${props.selectedTab ? \"/\" + props.selectedTab : \"\"}`)}${locationSearch}#${SIDE_URL_HASH}`\n : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}`)\n : undefined;\n\n const parentUrlPath = shouldUpdateUrl\n ? buildUrlCollectionPath(collectionPath)\n : undefined;\n\n const resolvedPanelProps: SidePanelBindingProps<any> = {\n ...props,\n formProps: props.formProps\n };\n\n const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);\n return {\n key: `${props.path}/${props.entityId}`,\n component: <ResolvedSidePanelBinding {...resolvedPanelProps}/>,\n urlPath: urlPath,\n parentUrlPath: parentUrlPath,\n width: entityViewWidth,\n onClose: props.onClose,\n additional: resolvedPanelProps\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAS,8BAA8B,OAA8B;CACjE,MAAM,WAAW,qBAA4C,oBAAoB,oBAAgB;CACjG,OAAO,oBAAC,UAAD;EAAU,UAAU,oBAAC,wBAAD,CAAwB,CAAA;YAC/C,oBAAC,UAAD,EAAU,GAAI,MAAO,CAAA;CACf,CAAA;AACd;AAEA,SAAS,yBAAyB,OAA8B;CAC5D,IAAI,MAAM,YACN,OACI,oBAAC,yBAAD;EAAyB,YAAY,MAAM;YACvC,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;CACrB,CAAA;CAGjC,OAAO,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;AACrD;AAEA,IAAM,eAAe;AACrB,IAAM,gBAAgB;;;;;;;;;;;;;;;AAgBtB,SAAgB,mBAAmB,OAAmC,OAAgB,yBAA0D;CAC5I,IAAI,OAAO,OAAO;CAElB,IAAI,MAAM,OACN,OAAO,OAAO,MAAM,UAAU,WAAW,GAAG,MAAM,MAAM,MAAM,MAAM;CAExE,IAAI,MAAM,YAAY,iBAClB,OAAO,OAAO,MAAM,WAAW,oBAAoB,WAC7C,GAAG,MAAM,WAAW,gBAAgB,MACpC,MAAM,WAAW;CAE3B,OAAO;AACX;AAEA,IAAa,qBAAqB,8BAC9B,eACA,2BACA,uBACA,mBACsB;CAEtB,MAAM,WAAW,YAAY;CAC7B,MAAM,cAAc,OAAgB,KAAK;CACzC,MAAM,sBAAsB,OAAi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UAAU;EACxB,CACJ;EACA,IAAI,aACA,UAAU,cAAc;CAEhC;CAEA,IAAI,SACA,YAAY;EACR,MAAM;EACN,MAAM;CACV;CAGJ,OAAO,YAAY,CAAC,SAAS,IAAI,CAAC;AACtC;AAEA,IAAM,oBAAoB,OACtB,wBACA,gBACA,aACA,yBACA,mBACuB;CAEvB,MAAM,iBAAiB,gCAAgC,MAAM,IAAI;CAOjE,MAAM,iBAAiB,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;CAIhF,MAAM,kBAAkB,MAAM,cAAc;CAI5C,MAAM,UAAU,kBACT,YAAY,MAAM,QAAQ,IACvB,GAAG,uBAAuB,GAAG,eAAe,GAAG,MAAM,WAAW,MAAM,cAAc,MAAM,MAAM,cAAc,IAAI,IAAI,eAAe,GAAG,kBACxI,GAAG,uBAAuB,cAAc,IAAI,eAAe,GAAG,iBAClE,KAAA;CAEN,MAAM,gBAAgB,kBAChB,uBAAuB,cAAc,IACrC,KAAA;CAEN,MAAM,qBAAiD;EACnD,GAAG;EACH,WAAW,MAAM;CACrB;CAEA,MAAM,kBAAkB,mBAAmB,OAAO,aAAa,uBAAuB;CACtF,OAAO;EACH,KAAK,GAAG,MAAM,KAAK,GAAG,MAAM;EAC5B,WAAW,oBAAC,0BAAD,EAA0B,GAAI,mBAAoB,CAAA;EACpD;EACM;EACf,OAAO;EACP,SAAS,MAAM;EACf,YAAY;CAChB;AACJ"}
|
|
1
|
+
{"version":3,"file":"useBuildSidePanel.js","names":[],"sources":["../../src/hooks/useBuildSidePanel.tsx"],"sourcesContent":["\nimport type { Property } from \"@rebasepro/types\";\nimport { hasEntityId } from \"@rebasepro/common\";\nimport type { CustomizationController, SidePanelBindingProps, SideDialogPanelProps, SideDialogsController, SidePanelController, UrlController, NavigationStateController, AdminCollection } from \"@rebasepro/cms-types\";\nimport { useCallback, useEffect, useRef, useMemo } from \"react\";\nimport { CollectionRegistryController } from \"@rebasepro/types\";\nimport { AuthController } from \"@rebasepro/cms-types\";\nimport { useLocation } from \"react-router\";\nimport { NavigationViewInternal } from \"@rebasepro/app\";\nimport { getNavigationEntriesFromPath, removeInitialAndTrailingSlashes, removeTrailingSlash, resolveDefaultSelectedView } from \"@rebasepro/app\";\nimport { resolvedSelectedEntityView } from \"../util/resolutions\";\nimport { CONTAINER_FULL_WIDTH, SIDE_PANEL_DEFAULT_WIDTH } from \"@rebasepro/app\";\nimport { useCustomizationController, useLargeLayout, useComponentOverride, CollectionScopeProvider } from \"@rebasepro/app\";\nimport { JSON_TAB_VALUE, HISTORY_TAB_VALUE } from \"../util/view_constants\";\nimport React, { Suspense } from \"react\";\nimport { CircularProgressCenter } from \"@rebasepro/ui\";\n// Lazy: this hook runs on every page (the side-panel provider is mounted by\n// RebaseNavigation), and the panel's form stack is not needed until one opens.\nimport { LazySidePanelBinding as SidePanelBinding } from \"../components/lazy_record_views\";\n\n/**\n * Thin wrapper that resolves the Entity.SidePanel component override.\n * Because the JSX is created inside `propsToSidePanel` (a plain function,\n * not a React component), we need this wrapper so the hook is called at the\n * top level of a React component per the Rules of Hooks.\n */\nfunction ResolvedSidePanelBindingInner(props: SidePanelBindingProps) {\n const Resolved = useComponentOverride<SidePanelBindingProps>(\"Entity.SidePanel\", SidePanelBinding);\n return <Suspense fallback={<CircularProgressCenter/>}>\n <Resolved {...props}/>\n </Suspense>;\n}\n\nfunction ResolvedSidePanelBinding(props: SidePanelBindingProps) {\n if (props.collection) {\n return (\n <CollectionScopeProvider collection={props.collection}>\n <ResolvedSidePanelBindingInner {...props}/>\n </CollectionScopeProvider>\n );\n }\n return <ResolvedSidePanelBindingInner {...props}/>;\n}\n\nconst NEW_URL_HASH = \"new_side\";\nconst SIDE_URL_HASH = \"side\";\n\n/**\n * How wide the side panel opens.\n *\n * One width for the whole panel, whatever tab is showing. It used to depend on\n * the selected tab — the form got one width and a subcollection or custom view\n * got `calc(55vw + 768px)` — so the panel physically resized under the cursor\n * every time you switched tabs. And the \"form\" width was derived from how\n * deeply nested the collection's *properties* were, which is not a thing anyone\n * can predict from looking at the panel.\n *\n * Now: `width` prop, then the collection's `sideDialogWidth`, then a default\n * sized for the content the panel actually has to hold — the form column plus\n * its metadata rail — capped so it never eats the whole window.\n */\nexport function getEntityViewWidth(props: SidePanelBindingProps<any>, small: boolean, customizationController: CustomizationController): string {\n if (small) return CONTAINER_FULL_WIDTH;\n\n if (props.width) {\n return typeof props.width === \"number\" ? `${props.width}px` : props.width;\n }\n if (props.collection?.sideDialogWidth) {\n return typeof props.collection.sideDialogWidth === \"number\"\n ? `${props.collection.sideDialogWidth}px`\n : props.collection.sideDialogWidth;\n }\n return SIDE_PANEL_DEFAULT_WIDTH;\n}\n\nexport const useBuildSidePanel = (collectionRegistryController: CollectionRegistryController,\n urlController: UrlController,\n navigationStateController: NavigationStateController,\n sideDialogsController: SideDialogsController,\n authController: AuthController\n): SidePanelController => {\n\n const location = useLocation();\n const initialised = useRef<boolean>(false);\n const currentPanelKeysRef = useRef<string[]>([]);\n const customizationController = useCustomizationController();\n\n const smallLayout = !useLargeLayout();\n\n useEffect(() => {\n\n const newFlag = location.hash === `#${NEW_URL_HASH}`;\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n\n if (!navigationStateController.loading) {\n if ((newFlag || sideFlag) && urlController.isUrlCollectionPath(location.pathname)) {\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], newFlag);\n for (let i = 0; i < panelsFromUrl.length; i++) {\n const props = panelsFromUrl[i];\n if (i === 0)\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n else\n sideDialogsController.open(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController))\n }\n }\n initialised.current = true;\n }\n }, [navigationStateController.loading]);\n\n // sync panels if URL changes with #side\n // Use a ref for currentPanelKeys so this effect only fires on URL changes,\n // not on panel state changes. This prevents a race condition with React Router 7\n // where close() clears panels before the URL updates, causing the effect to\n // re-open the panel from the stale #side hash.\n currentPanelKeysRef.current = sideDialogsController.sidePanels.map(p => p.key);\n useEffect(() => {\n if (initialised.current) {\n const sideFlag = location.hash === `#${SIDE_URL_HASH}`;\n if (sideFlag) {\n const currentKeys = currentPanelKeysRef.current;\n const entityOrCollectionPath = urlController.urlPathToDataPath(location.pathname);\n const panelsFromUrl = buildSidePanelsFromUrl(entityOrCollectionPath, collectionRegistryController.collections ?? [], false);\n // if we have more panels than determined by the url, we ignore the url. We might have references open\n if (panelsFromUrl.length <= currentKeys.length) {\n return;\n }\n const lastPanel = panelsFromUrl[panelsFromUrl.length - 1];\n const panelProps = propsToSidePanel(lastPanel, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController);\n const lastCurrentPanel = currentKeys.length > 0 ? currentKeys[currentKeys.length - 1] : undefined;\n if (!lastCurrentPanel || lastCurrentPanel !== panelProps.key) {\n sideDialogsController.replace(panelProps);\n }\n }\n }\n }, [location.pathname, location.hash]);\n\n // update side panels to match browser size\n // Only update panel widths on layout change — don't recreate components.\n // Recreating components would unmount/remount SidePanelBinding, losing\n // scroll position, unsaved form state, and triggering unnecessary data fetches.\n useEffect(() => {\n const updatedSidePanels = sideDialogsController.sidePanels.map(sidePanelProps => {\n if (sidePanelProps.additional) {\n const entityProps = sidePanelProps.additional as SidePanelBindingProps;\n const newWidth = getEntityViewWidth(entityProps, smallLayout, customizationController);\n if (sidePanelProps.width !== newWidth) {\n return { ...sidePanelProps,\nwidth: newWidth };\n }\n }\n return sidePanelProps;\n });\n sideDialogsController.setSidePanels(updatedSidePanels);\n }, [smallLayout]);\n\n const close = useCallback(() => {\n sideDialogsController.close();\n }, [sideDialogsController]);\n\n // Where no CMS route serves the page, a panel is an overlay and nothing\n // more: it writes no URL (one would lead nowhere) and offers no way to a\n // full-screen route that does not exist.\n const routesMounted = urlController.routesMounted !== false;\n\n const open = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.id)) {\n throw Error(\"To open a copy, pass the id of the record to copy\");\n }\n\n const defaultSelectedView = resolveDefaultSelectedView(\n props.collection ? props.collection.defaultSelectedView : undefined,\n {\n status: props.copy ? \"copy\" : (hasEntityId(props.id) ? \"existing\" : \"new\"),\n id: props.id\n }\n );\n\n sideDialogsController.open(\n propsToSidePanel({\n ...props,\n selectedTab: props.selectedTab ?? defaultSelectedView\n },\n urlController.buildUrlCollectionPath,\n urlController.resolveDatabasePathsFrom,\n smallLayout,\n customizationController,\n authController\n ));\n\n }, [sideDialogsController, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, authController.user, routesMounted]);\n\n const replace = useCallback((propsIn: SidePanelBindingProps<any>) => {\n const props = routesMounted ? propsIn : { ...propsIn, updateUrl: false, allowFullScreen: false };\n\n if (props.copy && !hasEntityId(props.id)) {\n throw Error(\"To open a copy, pass the id of the record to copy\");\n }\n\n sideDialogsController.replace(propsToSidePanel(props, urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, smallLayout, customizationController, authController));\n\n }, [urlController.buildUrlCollectionPath, urlController.resolveDatabasePathsFrom, sideDialogsController, smallLayout, authController.user, routesMounted]);\n\n return useMemo(() => ({\n close,\n open,\n replace\n }), [close, open, replace]);\n};\n\nexport function buildSidePanelsFromUrl(path: string, collections: AdminCollection[], newFlag: boolean): SidePanelBindingProps<any>[] {\n\n const navigationViewsForPath: NavigationViewInternal<any>[] = getNavigationEntriesFromPath({\n path,\n collections\n });\n\n let sidePanel: SidePanelBindingProps<any> | undefined = undefined;\n let lastCollectionPath = \"\";\n let lastCollectionId: string | undefined = undefined;\n for (let i = 0; i < navigationViewsForPath.length; i++) {\n const navigationEntry = navigationViewsForPath[i];\n\n if (navigationEntry.type === \"collection\") {\n lastCollectionPath = navigationEntry.slug;\n lastCollectionId = navigationEntry.collection.slug;\n }\n\n const previousEntry = navigationViewsForPath[i - 1];\n if (navigationEntry.type === \"entity\") {\n sidePanel = {\n path: navigationEntry.slug,\n id: navigationEntry.entityId,\n copy: false,\n collection: navigationEntry.parentCollection,\n width: navigationEntry.parentCollection?.sideDialogWidth\n };\n } else if (navigationEntry.type === \"custom_view\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.view.key;\n }\n } else if (navigationEntry.type === \"collection\") {\n if (previousEntry?.type === \"entity\") {\n if (sidePanel)\n sidePanel.selectedTab = navigationEntry.collection.slug;\n }\n }\n\n }\n\n // `edit` is not a registered view, so the navigation parser skips it. Pick it\n // up from the raw path so that reloading an edit URL reopens the edit form\n // rather than silently dropping the user back on the detail view.\n if (sidePanel && !sidePanel.selectedTab && removeTrailingSlash(path).endsWith(\"/edit\")) {\n sidePanel.selectedTab = \"edit\";\n }\n\n // When the URL doesn't contain a tab segment but the collection has a\n // defaultSelectedView, resolve it so the panel opens with the correct\n // width and the URL is updated on the next replace() cycle.\n if (sidePanel && !sidePanel.selectedTab && sidePanel.collection) {\n const defaultView = resolveDefaultSelectedView(\n sidePanel.collection.defaultSelectedView,\n {\n status: sidePanel.copy ? \"copy\" : (hasEntityId(sidePanel.id) ? \"existing\" : \"new\"),\n id: sidePanel.id\n }\n );\n if (defaultView) {\n sidePanel.selectedTab = defaultView;\n }\n }\n\n if (newFlag) {\n sidePanel = {\n path: lastCollectionPath,\n copy: false\n }\n }\n\n return sidePanel ? [sidePanel] : [];\n}\n\nconst propsToSidePanel = (props: SidePanelBindingProps,\n buildUrlCollectionPath: (path: string) => string,\n resolveIdsFrom: (pathWithAliases: string) => string,\n smallLayout: boolean,\n customizationController: CustomizationController,\n authController: AuthController\n): SideDialogPanelProps => {\n\n const collectionPath = removeInitialAndTrailingSlashes(props.path);\n\n // The list's state — search, filters, sort, view mode — read from the\n // address bar at the moment the panel opens. Not react-router's\n // `location.search`: the list writes its state with `replaceState`, which\n // the router does not observe, so that value is whatever the view mounted\n // with, and the list reads a panel URL built from it back as its state.\n const locationSearch = typeof window !== \"undefined\" ? window.location.search : \"\";\n\n // When updateUrl is explicitly false, don't generate URL paths — the dialog\n // opens as an overlay without affecting the browser URL / router.\n const shouldUpdateUrl = props.updateUrl !== false;\n\n // `buildUrlCollectionPath` encodes every segment of the data path it is\n // given, the record id among them, so the query and the hash go after it.\n const urlPath = shouldUpdateUrl\n ? (hasEntityId(props.id)\n ? `${buildUrlCollectionPath(`${collectionPath}/${props.id}${props.selectedTab ? \"/\" + props.selectedTab : \"\"}`)}${locationSearch}#${SIDE_URL_HASH}`\n : `${buildUrlCollectionPath(collectionPath)}${locationSearch}#${NEW_URL_HASH}`)\n : undefined;\n\n const parentUrlPath = shouldUpdateUrl\n ? buildUrlCollectionPath(collectionPath)\n : undefined;\n\n const resolvedPanelProps: SidePanelBindingProps<any> = {\n ...props,\n formProps: props.formProps\n };\n\n const entityViewWidth = getEntityViewWidth(props, smallLayout, customizationController);\n return {\n key: `${props.path}/${props.id}`,\n component: <ResolvedSidePanelBinding {...resolvedPanelProps}/>,\n urlPath: urlPath,\n parentUrlPath: parentUrlPath,\n width: entityViewWidth,\n onClose: props.onClose,\n additional: resolvedPanelProps\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,SAAS,8BAA8B,OAA8B;CACjE,MAAM,WAAW,qBAA4C,oBAAoB,oBAAgB;CACjG,OAAO,oBAAC,UAAD;EAAU,UAAU,oBAAC,wBAAD,CAAwB,CAAA;YAC/C,oBAAC,UAAD,EAAU,GAAI,MAAO,CAAA;CACf,CAAA;AACd;AAEA,SAAS,yBAAyB,OAA8B;CAC5D,IAAI,MAAM,YACN,OACI,oBAAC,yBAAD;EAAyB,YAAY,MAAM;YACvC,oBAAC,+BAAD,EAA+B,GAAI,MAAO,CAAA;CACrB,CAAA;CAGjC,OAAO,oBAAC,+BAAD,EAA+B,GAAI,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,KAAK,GAAG,MAAM;EAC5B,WAAW,oBAAC,0BAAD,EAA0B,GAAI,mBAAoB,CAAA;EACpD;EACM;EACf,OAAO;EACP,SAAS,MAAM;EACf,YAAY;CAChB;AACJ"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getEntityTitlePropertyKeyForEntity, isUserSelectProperty, resolveTitleToString } from "../util/previews.js";
|
|
2
2
|
import { getUserLabel, useResolvedUser } from "./useResolvedUsers.js";
|
|
3
3
|
import { useEffect, useMemo, useSyncExternalStore } from "react";
|
|
4
|
-
import { entityDisplayKey, getDisplayPropertyKey, getDisplayResolver, getPropertyInPath, getSharedEntityDisplayCache, useRebaseContext } from "@rebasepro/app";
|
|
4
|
+
import { entityDisplayKey, getDisplayPropertyKey, getDisplayResolver, getPropertyInPath, getSharedEntityDisplayCache, rowOfEntity, useRebaseContext } from "@rebasepro/app";
|
|
5
5
|
import { getValueInPath } from "@rebasepro/utils";
|
|
6
6
|
import "@rebasepro/cms-types";
|
|
7
7
|
//#region src/hooks/useEntityDisplay.tsx
|
|
@@ -60,17 +60,19 @@ function useEntityDisplay(role, { collection, entity, values: valuesProp, enable
|
|
|
60
60
|
const loading = Boolean(canResolve && key && resolved === void 0);
|
|
61
61
|
useEffect(() => {
|
|
62
62
|
if (!canResolve || !key || !resolver || !entity) return;
|
|
63
|
-
|
|
63
|
+
const row = rowOfEntity(entity, collection);
|
|
64
64
|
cache.resolve(key, () => resolver({
|
|
65
|
-
|
|
65
|
+
row,
|
|
66
|
+
id: String(entity.id),
|
|
66
67
|
context
|
|
67
|
-
})).catch(() => {});
|
|
68
|
+
}), row).catch(() => {});
|
|
68
69
|
}, [
|
|
69
70
|
cache,
|
|
70
71
|
canResolve,
|
|
71
72
|
key,
|
|
72
73
|
resolver,
|
|
73
74
|
entity,
|
|
75
|
+
collection,
|
|
74
76
|
context,
|
|
75
77
|
role
|
|
76
78
|
]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useEntityDisplay.js","names":[],"sources":["../../src/hooks/useEntityDisplay.tsx"],"sourcesContent":["import type { AdminCollection, EntityDisplayRole } from \"@rebasepro/cms-types\";\nimport type { Entity, Property } from \"@rebasepro/types\";\nimport { ENTITY_DISPLAY_ROLES } from \"@rebasepro/cms-types\";\nimport { useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport {\n type EntityDisplayCache,\n entityDisplayKey,\n getSharedEntityDisplayCache,\n getDisplayPropertyKey,\n getDisplayResolver,\n getPropertyInPath,\n useRebaseContext\n} from \"@rebasepro/app\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nimport { getEntityTitlePropertyKeyForEntity, isUserSelectProperty, resolveTitleToString } from \"../util/previews\";\nimport { getUserLabel, useResolvedUser } from \"./useResolvedUsers\";\n\n/**\n * What fills one display role for one record.\n *\n * `value` is `undefined` rather than a placeholder when nothing resolved,\n * because the substitute differs by surface and each one knows its own better\n * than this hook does: a page heading wants the singular collection name, a link\n * wants the id, a draft wants \"New customer\". A single baked-in fallback is\n * exactly what produced three different ones scattered across the consumers.\n */\nexport interface ResolvedDisplayValue<T = unknown> {\n /** What goes in the slot. `undefined` when the record has nothing for it. */\n value: T | undefined;\n /**\n * A resolver is in flight, and `value` currently holds the derived answer or\n * nothing. Surfaces that can show a skeleton may; none has to.\n */\n loading: boolean;\n /**\n * Set only when the value came from a property of this collection. Carries\n * what a rich renderer needs — a status shows as its enum's coloured chip,\n * an image as a storage thumbnail — which a bare resolved string cannot\n * describe.\n */\n source?: {\n key: string;\n property: Property | undefined;\n value: unknown;\n };\n}\n\n/**\n * The store behind {@link useEntityDisplay}, for invalidating after a write.\n *\n * The app's one shared store, so every surface agrees on a record and resolves\n * it once, and so it is emptied with the rest of the session's caches when the\n * user signs out.\n */\nexport function useEntityDisplayCache(): EntityDisplayCache {\n return getSharedEntityDisplayCache();\n}\n\nexport interface UseEntityDisplayParams<M extends Record<string, unknown>> {\n /**\n * Optional because several callers look the collection up in the registry by\n * path and may not find it — a relation into a collection the panel does not\n * register. A hook that could not be called until that succeeded would have\n * to sit below an early return, which is not where hooks go.\n */\n collection?: AdminCollection<M>;\n /**\n * The record. A resolver is handed the whole entity — its id and path are\n * how it reaches anything the record does not carry — so a computed value is\n * only available once there is an entity to compute it from.\n */\n entity?: Entity<M>;\n /**\n * Values to read a declared path from when they are newer than the entity:\n * the live form values while editing. Falls back to `entity.values`.\n */\n values?: Record<string, unknown>;\n /** Set false to skip resolver work entirely — a draft has nothing to show. */\n enabled?: boolean;\n}\n\n/**\n * What fills one display role of one record.\n *\n * This is the only implementation. Before it there were seven for the title\n * alone — the identity bar, the detail header, inline previews, reference cards,\n * list slots, relation chips and the headless view — each re-deriving it from\n * `collection.properties` and disagreeing about the answer.\n *\n * Resolution order, per role:\n *\n * 1. `admin.display[role]` as a **resolver** — awaited, cached per record and\n * role, with the derived value showing meanwhile so nothing flickers empty.\n * 2. `admin.display[role]` as a **property path** (or, for the title, the\n * deprecated `titleProperty`).\n * 3. The **derived** answer: for the title, the best-ranked property carrying a\n * readable value; for the rest, today's per-role heuristics.\n *\n * A user-picker title resolves to the person behind the id, as it always did —\n * that path is now here rather than in two of the seven.\n */\nexport function useEntityDisplay<T = unknown, M extends Record<string, unknown> = Record<string, unknown>>(\n role: EntityDisplayRole,\n {\n collection,\n entity,\n values: valuesProp,\n enabled = true\n }: UseEntityDisplayParams<M>\n): ResolvedDisplayValue<T> {\n\n const context = useRebaseContext();\n const cache = useEntityDisplayCache();\n\n const values = valuesProp ?? entity?.values;\n\n /* ---- the declared or derived key ------------------------------------- */\n\n // The title is the one role with a ranking behind it: several candidates,\n // best first, skipping the ones that hold nothing for *this* record. The\n // others are a single declared or derived key.\n const declaredKey = collection ? getDisplayPropertyKey(collection, role) : undefined;\n const propertyKey = collection && role === \"title\" && !declaredKey\n ? getEntityTitlePropertyKeyForEntity(collection, values, entity?.id)\n : declaredKey;\n\n const rawValue = values && propertyKey ? getValueInPath(values, propertyKey) : undefined;\n\n // A user picker stores an auth id and renders the person: resolved like a\n // relation, and hooked unconditionally so the hook order never changes.\n const titleUser = useResolvedUser(\n collection && role === \"title\" && isUserSelectProperty(collection, propertyKey) && typeof rawValue === \"string\"\n ? rawValue\n : undefined\n );\n\n const derived = useMemo<T | undefined>(() => {\n if (titleUser) return getUserLabel(titleUser) as T;\n if (rawValue === undefined || rawValue === null) return undefined;\n // Only text roles get flattened to a string; a date stays a date and an\n // image stays whatever the storage property holds, so the renderer can\n // still format them.\n if (role === \"title\" || role === \"subtitle\" || role === \"status\") {\n return (resolveTitleToString(rawValue) || undefined) as T | undefined;\n }\n return rawValue as T;\n }, [titleUser, rawValue, role]);\n\n /* ---- the computed answer --------------------------------------------- */\n\n const resolver = collection ? getDisplayResolver(collection, role) : undefined;\n const canResolve = Boolean(enabled && resolver && entity);\n const key = entity ? entityDisplayKey(entity.path, entity.id, role) : undefined;\n\n const resolved = useSyncExternalStore<unknown>(\n // Subscribing unconditionally keeps the hook order stable. The store\n // only notifies when an entry changes, so a collection with no resolver\n // never re-renders from it.\n cb => cache.subscribe(cb),\n () => (canResolve && key ? cache.peek(key) : undefined),\n // Server render: nothing is resolved, so every slot starts at its\n // fallback and hydration does not disagree with the markup.\n () => undefined\n );\n\n const loading = Boolean(canResolve && key && resolved === undefined);\n\n useEffect(() => {\n if (!canResolve || !key || !resolver || !entity) return;\n if (cache.peek(key) !== undefined) return;\n cache.resolve(key, () => resolver({\n entity,\n context\n })).catch(() => {\n // Unreachable, and kept only so it stays that way: `resolve` records a\n // failure as \"nothing\" and returns a RESOLVED promise, which is why\n // the warning that used to live here could never run — see the note on\n // `EntityDisplayCache.resolve`. The cache reports the failure itself\n // now, once per key. This exists so that if `resolve` ever starts\n // rejecting, it surfaces as a caught no-op rather than an unhandled\n // rejection during render.\n });\n }, [cache, canResolve, key, resolver, entity, context, role]);\n\n /* ---- the answer ------------------------------------------------------ */\n\n // A resolver that produced nothing falls back to the derived value rather\n // than to blank: it said this record has no computed answer for the role,\n // not that the role should be empty.\n const computed = canResolve && resolved !== null ? resolved as T | undefined : undefined;\n const value = computed ?? derived;\n\n return useMemo(() => ({\n value,\n loading,\n source: collection && propertyKey && value === derived && derived !== undefined\n ? {\n key: propertyKey,\n property: getPropertyInPath(collection.properties, propertyKey),\n value: rawValue\n }\n : undefined\n }), [value, loading, propertyKey, derived, collection, rawValue]);\n}\n\n/**\n * Every display role of a record at once — what a list row, a card or a board\n * card needs, in one call rather than six.\n *\n * The role list is iterated from {@link ENTITY_DISPLAY_ROLES} so the hook order\n * is fixed and adding a role does not mean editing every caller.\n */\nexport function useEntityDisplayValues<M extends Record<string, unknown>>(\n params: UseEntityDisplayParams<M>\n): Record<EntityDisplayRole, ResolvedDisplayValue> & { loading: boolean } {\n\n // Not a loop over `useEntityDisplay`: the number of hooks a component calls\n // has to be fixed at compile time, and a role added to the array later would\n // silently change it. Written out, it is checked by the return type.\n const title = useEntityDisplay<string, M>(\"title\", params);\n const subtitle = useEntityDisplay<string, M>(\"subtitle\", params);\n const image = useEntityDisplay<string, M>(\"image\", params);\n const status = useEntityDisplay<string, M>(\"status\", params);\n const date = useEntityDisplay<Date | string | number, M>(\"date\", params);\n const tags = useEntityDisplay<string[] | string, M>(\"tags\", params);\n\n return useMemo(() => ({\n title,\n subtitle,\n image,\n status,\n date,\n tags,\n loading: title.loading || subtitle.loading || image.loading\n || status.loading || date.loading || tags.loading\n }), [title, subtitle, image, status, date, tags]);\n}\n\n/**\n * What the record is called — the one role asked for often enough on its own to\n * deserve a name.\n */\nexport function useEntityTitle<M extends Record<string, unknown>>(\n params: UseEntityDisplayParams<M>\n): ResolvedDisplayValue<string> {\n return useEntityDisplay<string, M>(\"title\", params);\n}\n\n/** Re-exported so a caller can iterate roles without reaching into types. */\nexport { ENTITY_DISPLAY_ROLES };\n"],"mappings":";;;;;;;;;;;;;;AAuDA,SAAgB,wBAA4C;CACxD,OAAO,4BAA4B;AACvC;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iBACZ,MACA,EACI,YAC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YAAY,CAQhB,CAAC;CACL,GAAG;EAAC;EAAO;EAAY;EAAK;EAAU;EAAQ;EAAS;CAAI,CAAC;CAQ5D,MAAM,SADW,cAAc,aAAa,OAAO,WAA4B,KAAA,MACrD;CAE1B,OAAO,eAAe;EAClB;EACA;EACA,QAAQ,cAAc,eAAe,UAAU,WAAW,YAAY,KAAA,IAChE;GACE,KAAK;GACL,UAAU,kBAAkB,WAAW,YAAY,WAAW;GAC9D,OAAO;EACX,IACE,KAAA;CACV,IAAI;EAAC;EAAO;EAAS;EAAa;EAAS;EAAY;CAAQ,CAAC;AACpE;;;;;;;;AASA,SAAgB,uBACZ,QACsE;CAKtE,MAAM,QAAQ,iBAA4B,SAAS,MAAM;CACzD,MAAM,WAAW,iBAA4B,YAAY,MAAM;CAC/D,MAAM,QAAQ,iBAA4B,SAAS,MAAM;CACzD,MAAM,SAAS,iBAA4B,UAAU,MAAM;CAC3D,MAAM,OAAO,iBAA4C,QAAQ,MAAM;CACvE,MAAM,OAAO,iBAAuC,QAAQ,MAAM;CAElE,OAAO,eAAe;EAClB;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,MAAM,WAAW,SAAS,WAAW,MAAM,WAC7C,OAAO,WAAW,KAAK,WAAW,KAAK;CAClD,IAAI;EAAC;EAAO;EAAU;EAAO;EAAQ;EAAM;CAAI,CAAC;AACpD;;;;;AAMA,SAAgB,eACZ,QAC4B;CAC5B,OAAO,iBAA4B,SAAS,MAAM;AACtD"}
|
|
1
|
+
{"version":3,"file":"useEntityDisplay.js","names":[],"sources":["../../src/hooks/useEntityDisplay.tsx"],"sourcesContent":["import type { AdminCollection, EntityDisplayRole } from \"@rebasepro/cms-types\";\nimport type { Entity, Property } from \"@rebasepro/types\";\nimport { ENTITY_DISPLAY_ROLES } from \"@rebasepro/cms-types\";\nimport { useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport {\n type EntityDisplayCache,\n entityDisplayKey,\n getSharedEntityDisplayCache,\n getDisplayPropertyKey,\n getDisplayResolver,\n getPropertyInPath,\n useRebaseContext\n} from \"@rebasepro/app\";\nimport { getValueInPath } from \"@rebasepro/utils\";\n\nimport { getEntityTitlePropertyKeyForEntity, isUserSelectProperty, resolveTitleToString } from \"../util/previews\";\nimport { getUserLabel, useResolvedUser } from \"./useResolvedUsers\";\nimport { rowOfEntity } from \"@rebasepro/app\";\n\n/**\n * What fills one display role for one record.\n *\n * `value` is `undefined` rather than a placeholder when nothing resolved,\n * because the substitute differs by surface and each one knows its own better\n * than this hook does: a page heading wants the singular collection name, a link\n * wants the id, a draft wants \"New customer\". A single baked-in fallback is\n * exactly what produced three different ones scattered across the consumers.\n */\nexport interface ResolvedDisplayValue<T = unknown> {\n /** What goes in the slot. `undefined` when the record has nothing for it. */\n value: T | undefined;\n /**\n * A resolver is in flight, and `value` currently holds the derived answer or\n * nothing. Surfaces that can show a skeleton may; none has to.\n */\n loading: boolean;\n /**\n * Set only when the value came from a property of this collection. Carries\n * what a rich renderer needs — a status shows as its enum's coloured chip,\n * an image as a storage thumbnail — which a bare resolved string cannot\n * describe.\n */\n source?: {\n key: string;\n property: Property | undefined;\n value: unknown;\n };\n}\n\n/**\n * The store behind {@link useEntityDisplay}, for invalidating after a write.\n *\n * The app's one shared store, so every surface agrees on a record and resolves\n * it once, and so it is emptied with the rest of the session's caches when the\n * user signs out.\n */\nexport function useEntityDisplayCache(): EntityDisplayCache {\n return getSharedEntityDisplayCache();\n}\n\nexport interface UseEntityDisplayParams<M extends Record<string, unknown>> {\n /**\n * Optional because several callers look the collection up in the registry by\n * path and may not find it — a relation into a collection the panel does not\n * register. A hook that could not be called until that succeeded would have\n * to sit below an early return, which is not where hooks go.\n */\n collection?: AdminCollection<M>;\n /**\n * The record. A resolver is handed the whole entity — its id and path are\n * how it reaches anything the record does not carry — so a computed value is\n * only available once there is an entity to compute it from.\n */\n entity?: Entity<M>;\n /**\n * Values to read a declared path from when they are newer than the entity:\n * the live form values while editing. Falls back to `entity.values`.\n */\n values?: Record<string, unknown>;\n /** Set false to skip resolver work entirely — a draft has nothing to show. */\n enabled?: boolean;\n}\n\n/**\n * What fills one display role of one record.\n *\n * This is the only implementation. Before it there were seven for the title\n * alone — the identity bar, the detail header, inline previews, reference cards,\n * list slots, relation chips and the headless view — each re-deriving it from\n * `collection.properties` and disagreeing about the answer.\n *\n * Resolution order, per role:\n *\n * 1. `admin.display[role]` as a **resolver** — awaited, cached per record and\n * role, with the derived value showing meanwhile so nothing flickers empty.\n * 2. `admin.display[role]` as a **property path** (or, for the title, the\n * deprecated `titleProperty`).\n * 3. The **derived** answer: for the title, the best-ranked property carrying a\n * readable value; for the rest, today's per-role heuristics.\n *\n * A user-picker title resolves to the person behind the id, as it always did —\n * that path is now here rather than in two of the seven.\n */\nexport function useEntityDisplay<T = unknown, M extends Record<string, unknown> = Record<string, unknown>>(\n role: EntityDisplayRole,\n {\n collection,\n entity,\n values: valuesProp,\n enabled = true\n }: UseEntityDisplayParams<M>\n): ResolvedDisplayValue<T> {\n\n const context = useRebaseContext();\n const cache = useEntityDisplayCache();\n\n const values = valuesProp ?? entity?.values;\n\n /* ---- the declared or derived key ------------------------------------- */\n\n // The title is the one role with a ranking behind it: several candidates,\n // best first, skipping the ones that hold nothing for *this* record. The\n // others are a single declared or derived key.\n const declaredKey = collection ? getDisplayPropertyKey(collection, role) : undefined;\n const propertyKey = collection && role === \"title\" && !declaredKey\n ? getEntityTitlePropertyKeyForEntity(collection, values, entity?.id)\n : declaredKey;\n\n const rawValue = values && propertyKey ? getValueInPath(values, propertyKey) : undefined;\n\n // A user picker stores an auth id and renders the person: resolved like a\n // relation, and hooked unconditionally so the hook order never changes.\n const titleUser = useResolvedUser(\n collection && role === \"title\" && isUserSelectProperty(collection, propertyKey) && typeof rawValue === \"string\"\n ? rawValue\n : undefined\n );\n\n const derived = useMemo<T | undefined>(() => {\n if (titleUser) return getUserLabel(titleUser) as T;\n if (rawValue === undefined || rawValue === null) return undefined;\n // Only text roles get flattened to a string; a date stays a date and an\n // image stays whatever the storage property holds, so the renderer can\n // still format them.\n if (role === \"title\" || role === \"subtitle\" || role === \"status\") {\n return (resolveTitleToString(rawValue) || undefined) as T | undefined;\n }\n return rawValue as T;\n }, [titleUser, rawValue, role]);\n\n /* ---- the computed answer --------------------------------------------- */\n\n const resolver = collection ? getDisplayResolver(collection, role) : undefined;\n const canResolve = Boolean(enabled && resolver && entity);\n const key = entity ? entityDisplayKey(entity.path, entity.id, role) : undefined;\n\n const resolved = useSyncExternalStore<unknown>(\n // Subscribing unconditionally keeps the hook order stable. The store\n // only notifies when an entry changes, so a collection with no resolver\n // never re-renders from it.\n cb => cache.subscribe(cb),\n () => (canResolve && key ? cache.peek(key) : undefined),\n // Server render: nothing is resolved, so every slot starts at its\n // fallback and hydration does not disagree with the markup.\n () => undefined\n );\n\n const loading = Boolean(canResolve && key && resolved === undefined);\n\n useEffect(() => {\n if (!canResolve || !key || !resolver || !entity) return;\n // Asked every time the record changes, with the row the resolver is\n // handed: the cache answers from what it holds while that row is the\n // one it was computed from, and resolves again once it is not.\n const row = rowOfEntity(entity, collection);\n cache.resolve(key, () => resolver({\n row,\n id: String(entity.id),\n context\n }), row).catch(() => {\n // Unreachable, and kept only so it stays that way: `resolve` records a\n // failure as \"nothing\" and returns a RESOLVED promise, which is why\n // the warning that used to live here could never run — see the note on\n // `EntityDisplayCache.resolve`. The cache reports the failure itself\n // now, once per key. This exists so that if `resolve` ever starts\n // rejecting, it surfaces as a caught no-op rather than an unhandled\n // rejection during render.\n });\n }, [cache, canResolve, key, resolver, entity, collection, context, role]);\n\n /* ---- the answer ------------------------------------------------------ */\n\n // A resolver that produced nothing falls back to the derived value rather\n // than to blank: it said this record has no computed answer for the role,\n // not that the role should be empty.\n const computed = canResolve && resolved !== null ? resolved as T | undefined : undefined;\n const value = computed ?? derived;\n\n return useMemo(() => ({\n value,\n loading,\n source: collection && propertyKey && value === derived && derived !== undefined\n ? {\n key: propertyKey,\n property: getPropertyInPath(collection.properties, propertyKey),\n value: rawValue\n }\n : undefined\n }), [value, loading, propertyKey, derived, collection, rawValue]);\n}\n\n/**\n * Every display role of a record at once — what a list row, a card or a board\n * card needs, in one call rather than six.\n *\n * The role list is iterated from {@link ENTITY_DISPLAY_ROLES} so the hook order\n * is fixed and adding a role does not mean editing every caller.\n */\nexport function useEntityDisplayValues<M extends Record<string, unknown>>(\n params: UseEntityDisplayParams<M>\n): Record<EntityDisplayRole, ResolvedDisplayValue> & { loading: boolean } {\n\n // Not a loop over `useEntityDisplay`: the number of hooks a component calls\n // has to be fixed at compile time, and a role added to the array later would\n // silently change it. Written out, it is checked by the return type.\n const title = useEntityDisplay<string, M>(\"title\", params);\n const subtitle = useEntityDisplay<string, M>(\"subtitle\", params);\n const image = useEntityDisplay<string, M>(\"image\", params);\n const status = useEntityDisplay<string, M>(\"status\", params);\n const date = useEntityDisplay<Date | string | number, M>(\"date\", params);\n const tags = useEntityDisplay<string[] | string, M>(\"tags\", params);\n\n return useMemo(() => ({\n title,\n subtitle,\n image,\n status,\n date,\n tags,\n loading: title.loading || subtitle.loading || image.loading\n || status.loading || date.loading || tags.loading\n }), [title, subtitle, image, status, date, tags]);\n}\n\n/**\n * What the record is called — the one role asked for often enough on its own to\n * deserve a name.\n */\nexport function useEntityTitle<M extends Record<string, unknown>>(\n params: UseEntityDisplayParams<M>\n): ResolvedDisplayValue<string> {\n return useEntityDisplay<string, M>(\"title\", params);\n}\n\n/** Re-exported so a caller can iterate roles without reaching into types. */\nexport { ENTITY_DISPLAY_ROLES };\n"],"mappings":";;;;;;;;;;;;;;AAwDA,SAAgB,wBAA4C;CACxD,OAAO,4BAA4B;AACvC;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iBACZ,MACA,EACI,YACA,QACA,QAAQ,YACR,UAAU,QAES;CAEvB,MAAM,UAAU,iBAAiB;CACjC,MAAM,QAAQ,sBAAsB;CAEpC,MAAM,SAAS,cAAc,QAAQ;CAOrC,MAAM,cAAc,aAAa,sBAAsB,YAAY,IAAI,IAAI,K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rD;CAE1B,OAAO,eAAe;EAClB;EACA;EACA,QAAQ,cAAc,eAAe,UAAU,WAAW,YAAY,KAAA,IAChE;GACE,KAAK;GACL,UAAU,kBAAkB,WAAW,YAAY,WAAW;GAC9D,OAAO;EACX,IACE,KAAA;CACV,IAAI;EAAC;EAAO;EAAS;EAAa;EAAS;EAAY;CAAQ,CAAC;AACpE;;;;;;;;AASA,SAAgB,uBACZ,QACsE;CAKtE,MAAM,QAAQ,iBAA4B,SAAS,MAAM;CACzD,MAAM,WAAW,iBAA4B,YAAY,MAAM;CAC/D,MAAM,QAAQ,iBAA4B,SAAS,MAAM;CACzD,MAAM,SAAS,iBAA4B,UAAU,MAAM;CAC3D,MAAM,OAAO,iBAA4C,QAAQ,MAAM;CACvE,MAAM,OAAO,iBAAuC,QAAQ,MAAM;CAElE,OAAO,eAAe;EAClB;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,MAAM,WAAW,SAAS,WAAW,MAAM,WAC7C,OAAO,WAAW,KAAK,WAAW,KAAK;CAClD,IAAI;EAAC;EAAO;EAAU;EAAO;EAAQ;EAAM;CAAI,CAAC;AACpD;;;;;AAMA,SAAgB,eACZ,QAC4B;CAC5B,OAAO,iBAA4B,SAAS,MAAM;AACtD"}
|
|
@@ -29,7 +29,7 @@ function useRecordActions({ collection, path, entity, clickProps }) {
|
|
|
29
29
|
const actions = useMemo(() => {
|
|
30
30
|
const customEntityActions = (collection.entityActions ?? []).map((action) => resolveEntityAction(action, customizationController.entityActions)).filter(Boolean);
|
|
31
31
|
const createEnabled = canCreate(collection, path);
|
|
32
|
-
const deleteEnabled = entity ? canDelete(collection, path, entity) : false;
|
|
32
|
+
const deleteEnabled = entity ? canDelete(collection, path, entity.values) : false;
|
|
33
33
|
const disableActions = collection.disableDefaultActions ?? [];
|
|
34
34
|
const defaults = [];
|
|
35
35
|
if (createEnabled && !disableActions.includes("copy")) defaults.push(copyEntityAction);
|
|
@@ -46,7 +46,7 @@ function useRecordActions({ collection, path, entity, clickProps }) {
|
|
|
46
46
|
isLinkedChildView
|
|
47
47
|
]);
|
|
48
48
|
return useMemo(() => {
|
|
49
|
-
if (!clickProps?.
|
|
49
|
+
if (!clickProps?.row || !actions.length) return void 0;
|
|
50
50
|
const report = (action, error) => {
|
|
51
51
|
console.error("Error executing action", action.key ?? action.name, error);
|
|
52
52
|
snackbarController.open({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRecordActions.js","names":[],"sources":["../../src/hooks/useRecordActions.tsx"],"sourcesContent":["import type { EntityAction, EntityActionClickProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { Entity } from \"@rebasepro/types\";\nimport { useCallback, useMemo } from \"react\";\nimport { useNavigate } from \"react-router\";\nimport { getIcon, useCustomizationController, usePermissions, useSnackbarController, useTranslation } from \"@rebasepro/app\";\nimport { copyEntityAction, deleteEntityAction, unlinkEntityAction } from \"../components/common/default_entity_actions\";\nimport { entityActionName, mergeEntityActions, placeEntityActions, resolveEntityActionState, type PlacedEntityActions } from \"../util/entity_actions\";\nimport { resolveEntityAction } from \"../util/resolutions\";\nimport { useChildViewSource } from \"./useChildViewSource\";\nimport { useUrlController } from \"./navigation/contexts/UrlContext\";\nimport { withListState } from \"../util/view_mode\";\nimport type { RecordActionItem } from \"../components/EntityIdentityBar\";\nimport { useSideDialogContext } from \"../components/SideDialogs\";\n\nexport interface UseRecordActionsParams<M extends Record<string, unknown>> {\n collection: AdminCollection<M>;\n path: string;\n entity?: Entity<M>;\n /**\n * What every action is called with — and asked `isEnabled` with. Undefined\n * until there is a record to act on.\n */\n clickProps?: EntityActionClickProps<Record<string, unknown>>;\n}\n\n/**\n * The actions you can perform *on* a record — copy, delete, and whatever the\n * collection adds — resolved against the current user's permissions, and\n * placed for the record's identity bar: buttons for the ones declared\n * `collapsed: false`, menu groups for the rest.\n *\n * Extracted from the form's footer so the identity bar can own them. They are\n * not ways to leave the form, so they never belonged next to Save's footer;\n * the bar carries them on the edit view and the read-only view alike.\n */\nexport function useRecordActions<M extends Record<string, unknown>>({\n collection,\n path,\n entity,\n clickProps\n}: UseRecordActionsParams<M>): PlacedEntityActions<RecordActionItem> | undefined {\n\n const { canCreate, canDelete } = usePermissions();\n const customizationController = useCustomizationController();\n const snackbarController = useSnackbarController();\n const { t } = useTranslation();\n\n // Rows shared through a junction: the delete action here removes the link,\n // because that is what the server does for this path.\n const childViewSource = useChildViewSource(path);\n const isLinkedChildView = childViewSource?.kind === \"relation\" && childViewSource.mode === \"linked\";\n\n const actions = useMemo((): EntityAction[] => {\n const customEntityActions = (collection.entityActions ?? [])\n .map(action => resolveEntityAction(action, customizationController.entityActions))\n .filter(Boolean) as EntityAction[];\n\n const createEnabled = canCreate(collection, path);\n const deleteEnabled = entity ? canDelete(collection, path, entity) : false;\n const disableActions = collection.disableDefaultActions ?? [];\n\n const defaults: EntityAction[] = [];\n if (createEnabled && !disableActions.includes(\"copy\"))\n defaults.push(copyEntityAction);\n if (deleteEnabled && !disableActions.includes(\"delete\"))\n defaults.push(isLinkedChildView ? unlinkEntityAction : deleteEntityAction);\n\n const merged = customEntityActions.length\n ? mergeEntityActions(defaults, customEntityActions)\n : defaults;\n\n return merged.filter(a => a.includeInForm === undefined || a.includeInForm);\n }, [\n canCreate,\n canDelete,\n collection,\n path,\n customizationController.entityActions?.length,\n entity,\n collection.disableDefaultActions,\n isLinkedChildView\n ]);\n\n return useMemo(() => {\n if (!clickProps?.
|
|
1
|
+
{"version":3,"file":"useRecordActions.js","names":[],"sources":["../../src/hooks/useRecordActions.tsx"],"sourcesContent":["import type { EntityAction, EntityActionClickProps, AdminCollection } from \"@rebasepro/cms-types\";\nimport type { Entity } from \"@rebasepro/types\";\nimport { useCallback, useMemo } from \"react\";\nimport { useNavigate } from \"react-router\";\nimport { getIcon, useCustomizationController, usePermissions, useSnackbarController, useTranslation } from \"@rebasepro/app\";\nimport { copyEntityAction, deleteEntityAction, unlinkEntityAction } from \"../components/common/default_entity_actions\";\nimport { entityActionName, mergeEntityActions, placeEntityActions, resolveEntityActionState, type PlacedEntityActions } from \"../util/entity_actions\";\nimport { resolveEntityAction } from \"../util/resolutions\";\nimport { useChildViewSource } from \"./useChildViewSource\";\nimport { useUrlController } from \"./navigation/contexts/UrlContext\";\nimport { withListState } from \"../util/view_mode\";\nimport type { RecordActionItem } from \"../components/EntityIdentityBar\";\nimport { useSideDialogContext } from \"../components/SideDialogs\";\n\nexport interface UseRecordActionsParams<M extends Record<string, unknown>> {\n collection: AdminCollection<M>;\n path: string;\n entity?: Entity<M>;\n /**\n * What every action is called with — and asked `isEnabled` with. Undefined\n * until there is a record to act on.\n */\n clickProps?: EntityActionClickProps<Record<string, unknown>>;\n}\n\n/**\n * The actions you can perform *on* a record — copy, delete, and whatever the\n * collection adds — resolved against the current user's permissions, and\n * placed for the record's identity bar: buttons for the ones declared\n * `collapsed: false`, menu groups for the rest.\n *\n * Extracted from the form's footer so the identity bar can own them. They are\n * not ways to leave the form, so they never belonged next to Save's footer;\n * the bar carries them on the edit view and the read-only view alike.\n */\nexport function useRecordActions<M extends Record<string, unknown>>({\n collection,\n path,\n entity,\n clickProps\n}: UseRecordActionsParams<M>): PlacedEntityActions<RecordActionItem> | undefined {\n\n const { canCreate, canDelete } = usePermissions();\n const customizationController = useCustomizationController();\n const snackbarController = useSnackbarController();\n const { t } = useTranslation();\n\n // Rows shared through a junction: the delete action here removes the link,\n // because that is what the server does for this path.\n const childViewSource = useChildViewSource(path);\n const isLinkedChildView = childViewSource?.kind === \"relation\" && childViewSource.mode === \"linked\";\n\n const actions = useMemo((): EntityAction[] => {\n const customEntityActions = (collection.entityActions ?? [])\n .map(action => resolveEntityAction(action, customizationController.entityActions))\n .filter(Boolean) as EntityAction[];\n\n const createEnabled = canCreate(collection, path);\n const deleteEnabled = entity ? canDelete(collection, path, entity.values) : false;\n const disableActions = collection.disableDefaultActions ?? [];\n\n const defaults: EntityAction[] = [];\n if (createEnabled && !disableActions.includes(\"copy\"))\n defaults.push(copyEntityAction);\n if (deleteEnabled && !disableActions.includes(\"delete\"))\n defaults.push(isLinkedChildView ? unlinkEntityAction : deleteEntityAction);\n\n const merged = customEntityActions.length\n ? mergeEntityActions(defaults, customEntityActions)\n : defaults;\n\n return merged.filter(a => a.includeInForm === undefined || a.includeInForm);\n }, [\n canCreate,\n canDelete,\n collection,\n path,\n customizationController.entityActions?.length,\n entity,\n collection.disableDefaultActions,\n isLinkedChildView\n ]);\n\n return useMemo(() => {\n if (!clickProps?.row || !actions.length) return undefined;\n\n const report = (action: EntityAction, error: unknown) => {\n console.error(\"Error executing action\", action.key ?? action.name, error);\n snackbarController.open({\n type: \"error\",\n message: `${entityActionName(action, t)}: ${error instanceof Error ? error.message : String(error)}`\n });\n };\n\n const items = actions.map((action, index): RecordActionItem & Pick<EntityAction, \"collapsed\"> => ({\n key: action.key ?? `${action.name}_${index}`,\n name: entityActionName(action, t),\n icon: getIcon(action.icon, undefined, undefined, \"smallest\"),\n collapsed: action.collapsed,\n ...resolveEntityActionState(action, clickProps),\n // A failure reaches the user rather than the console alone, wherever\n // the action was clicked from. A promise is handed back only when the\n // action returned one, so a button shows a spinner for work that is\n // actually running and never flashes one for a synchronous call.\n run: () => {\n try {\n const result = action.onClick(clickProps);\n if (result instanceof Promise) return result.catch(error => report(action, error));\n } catch (error: unknown) {\n report(action, error);\n }\n return undefined;\n }\n }));\n\n return placeEntityActions(items);\n }, [actions, clickProps, snackbarController, t]);\n}\n\n/**\n * What a record's own actions mean by `navigateBack`: leave the record. The\n * delete action calls it once the row is gone.\n *\n * It is not the edit view's `navigateBack` prop, which every layout wires to\n * \"leave the edit view for the record's detail view\" — after a delete that is a\n * record that no longer exists, and the split, the side panel and the dialog\n * stayed open on it.\n */\nexport function useLeaveRecord({\n layout,\n path,\n onCloseRequest\n}: {\n layout: \"side_panel\" | \"full_screen\" | \"split\" | \"dialog\";\n path: string;\n onCloseRequest?: () => void;\n}): () => void {\n const sideDialogContext = useSideDialogContext();\n const navigate = useNavigate();\n const urlController = useUrlController();\n return useCallback(() => {\n if (layout === \"side_panel\" || layout === \"dialog\") {\n sideDialogContext.close(true);\n } else if (onCloseRequest) {\n onCloseRequest();\n } else {\n navigate(withListState(urlController.buildUrlCollectionPath(path)), { replace: true });\n }\n }, [layout, sideDialogContext, onCloseRequest, navigate, urlController, path]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,iBAAoD,EAChE,YACA,MACA,QACA,cAC6E;CAE7E,MAAM,EAAE,WAAW,cAAc,eAAe;CAChD,MAAM,0BAA0B,2BAA2B;CAC3D,MAAM,qBAAqB,sBAAsB;CACjD,MAAM,EAAE,MAAM,eAAe;CAI7B,MAAM,kBAAkB,mBAAmB,IAAI;CAC/C,MAAM,oBAAoB,iBAAiB,SAAS,cAAc,gBAAgB,SAAS;CAE3F,MAAM,UAAU,cAA8B;EAC1C,MAAM,uBAAuB,WAAW,iBAAiB,CAAC,EAAA,CACrD,KAAI,WAAU,oBAAoB,QAAQ,wBAAwB,aAAa,CAAC,CAAC,CACjF,OAAO,OAAO;EAEnB,MAAM,gBAAgB,UAAU,YAAY,IAAI;EAChD,MAAM,gBAAgB,SAAS,UAAU,YAAY,MAAM,OAAO,MAAM,IAAI;EAC5E,MAAM,iBAAiB,WAAW,yBAAyB,CAAC;EAE5D,MAAM,WAA2B,CAAC;EAClC,IAAI,iBAAiB,CAAC,eAAe,SAAS,MAAM,GAChD,SAAS,KAAK,gBAAgB;EAClC,IAAI,iBAAiB,CAAC,eAAe,SAAS,QAAQ,GAClD,SAAS,KAAK,oBAAoB,qBAAqB,kBAAkB;EAM7E,QAJe,oBAAoB,SAC7B,mBAAmB,UAAU,mBAAmB,IAChD,SAAA,CAEQ,QAAO,MAAK,EAAE,kBAAkB,KAAA,KAAa,EAAE,aAAa;CAC9E,GAAG;EACC;EACA;EACA;EACA;EACA,wBAAwB,eAAe;EACvC;EACA,WAAW;EACX;CACJ,CAAC;CAED,OAAO,cAAc;EACjB,IAAI,CAAC,YAAY,OAAO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SelectionTableBinding.js";
|
|
1
|
+
import { EntitySelectionProps, SelectionProps } from "../components/ReferenceTable/SelectionTableBinding.js";
|
|
2
|
+
type DialogOptions = {
|
|
3
|
+
path?: string | false;
|
|
4
|
+
onClose?: () => void;
|
|
5
|
+
};
|
|
2
6
|
/**
|
|
3
7
|
* This hook is used to open a side dialog that allows the selection
|
|
4
|
-
* of
|
|
5
|
-
* You can use it in custom views for selecting
|
|
8
|
+
* of rows under a given path.
|
|
9
|
+
* You can use it in custom views for selecting rows; the callbacks are handed
|
|
10
|
+
* them as the server sends them, and their ids beside them.
|
|
6
11
|
* You need to specify the path of the target collection at least.
|
|
7
12
|
* If your collection is not defined in your top collection configuration
|
|
8
13
|
* (in your `Rebase` component), you need to specify explicitly.
|
|
9
14
|
* This is the same hook used internally when a reference property is defined.
|
|
10
15
|
* @group Hooks and utilities
|
|
11
16
|
*/
|
|
12
|
-
export declare function useSelectionDialog<M extends Record<string, unknown>>(
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
}
|
|
17
|
+
export declare function useSelectionDialog<M extends Record<string, unknown>>(selectionProps: Omit<SelectionProps<M>, "path"> & DialogOptions): {
|
|
18
|
+
open: () => void;
|
|
19
|
+
close: () => void;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* {@link useSelectionDialog} over the admin's `Entity` view model, for its own
|
|
23
|
+
* reference and relation fields.
|
|
24
|
+
*
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
export declare function useEntitySelectionDialog<M extends Record<string, unknown>>(referenceDialogProps: Omit<EntitySelectionProps<M>, "path"> & DialogOptions): {
|
|
16
28
|
open: () => void;
|
|
17
29
|
close: () => void;
|
|
18
30
|
};
|
|
31
|
+
export {};
|