Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Make sure /dirty is called when moving an entity out of the library (#65259)

Anderson60c65add21cd
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge.tsx
index ec4c5975c27..f4414e49750 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge.tsx
@@ -1,36 +1,16 @@
import { t } from "ttag";
import { Box, Tooltip } from "metabase/ui";
-import type { Collection } from "metabase-types/api";
-interface CollectionSyncStatusBadgeProps {
- collection: Pick<Collection, "id">;
- changedCollections?: Record<number, boolean>;
-}
-
-export const CollectionSyncStatusBadge = ({
- collection,
- changedCollections,
-}: CollectionSyncStatusBadgeProps) => {
- const isDirty =
- changedCollections != null &&
- typeof collection?.id === "number" &&
- changedCollections[collection.id];
-
- if (!isDirty) {
- return null;
- }
-
- return (
- <Tooltip label={t`Unsynced changes`}>
- <Box
- bdrs="50%"
- bg="warning"
- h="0.5rem"
- w="0.5rem"
- mr="xs"
- data-testid="remote-sync-status"
- />
- </Tooltip>
- );
-};
+export const CollectionSyncStatusBadge = () => (
+ <Tooltip label={t`Unsynced changes`}>
+ <Box
+ bdrs="50%"
+ bg="warning"
+ h="0.5rem"
+ w="0.5rem"
+ mr="xs"
+ data-testid="remote-sync-status"
+ />
+ </Tooltip>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsx
index 23c6d18b5ee..0edfbc63a8f 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/PushChangesButton.tsx
@@ -1,7 +1,7 @@
import { useDisclosure } from "@mantine/hooks";
import { t } from "ttag";
-import type { CollectionTreeItem } from "metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView";
+import type { CollectionTreeItem } from "metabase/entities/collections";
import { ActionIcon, Icon } from "metabase/ui";
import { PushChangesModal } from "../PushChangesModal";
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx
index 289302f67f2..a553ab2eb1a 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection.tsx
@@ -10,8 +10,8 @@ import {
SidebarHeading,
SidebarSection,
} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";
-import type { CollectionTreeItem } from "metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView";
import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";
+import type { SyncedCollectionsSidebarSectionProps } from "metabase/plugins/types";
import { getUserIsAdmin } from "metabase/selectors/user";
import { Box, Flex, Group, Text } from "metabase/ui";
import {
@@ -32,16 +32,10 @@ import { CollectionSyncStatusBadge } from "./CollectionSyncStatusBadge";
import { PullFromRemoteButton } from "./PullFromRemoteButton";
import { PushChangesButton } from "./PushChangesButton";
-interface SyncedCollectionsSidebarSectionProps {
- syncedCollections: CollectionTreeItem[];
- collectionItem: CollectionTreeItem | null;
- onItemSelect: VoidFunction;
-}
-
export const SyncedCollectionsSidebarSection = ({
- syncedCollections,
- collectionItem,
onItemSelect,
+ selectedId,
+ syncedCollections,
}: SyncedCollectionsSidebarSectionProps) => {
const hasSyncedCollections = syncedCollections.length > 0;
const isAdmin = useSelector(getUserIsAdmin);
@@ -61,7 +55,11 @@ export const SyncedCollectionsSidebarSection = ({
refetchOnFocus: true,
});
+ const isSwitchingBranch = !!nextBranch;
const isDirty = !!(dirtyData?.dirty && dirtyData.dirty.length > 0);
+ const hasEntityRemoved = dirtyData?.dirty?.some(
+ (entity) => entity.sync_status === "removed",
+ );
const changeBranch = useCallback(
async (branch: string | null, isNewBranch?: boolean) => {
@@ -112,8 +110,23 @@ export const SyncedCollectionsSidebarSection = ({
},
[currentBranch, changeBranch, refetchDirty, sendToast],
);
-
- const isSwitchingBranch = !!nextBranch;
+ const showChangesBadge = (itemId?: number | string) => {
+ if (!dirtyData?.changedCollections || typeof itemId !== "number") {
+ return false;
+ }
+
+ const collectionIsUpdated = !!dirtyData?.changedCollections[itemId];
+ const hasSingleRootCollection = syncedCollections.length === 1;
+
+ return (
+ // Collection was updated
+ collectionIsUpdated ||
+ // An item was removed and this is the root synced collection (TODO: this is a workaround before we do UXW-2181)
+ (hasEntityRemoved &&
+ hasSingleRootCollection &&
+ syncedCollections[0].id === itemId)
+ );
+ };
if (!isRemoteSyncEnabled) {
return null;
@@ -165,17 +178,14 @@ export const SyncedCollectionsSidebarSection = ({
<Box>
<Tree
data={syncedCollections}
- selectedId={collectionItem?.id}
+ selectedId={selectedId}
onSelect={onItemSelect}
TreeNode={SidebarCollectionLink}
role="tree"
aria-label="collection-tree"
- rightSection={(item) => (
- <CollectionSyncStatusBadge
- collection={item}
- changedCollections={dirtyData?.changedCollections}
- />
- )}
+ rightSection={(item) =>
+ showChangesBadge(item?.id) && <CollectionSyncStatusBadge />
+ }
/>
</Box>
</ErrorBoundary>
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts
index 8d9c6e9def1..b305ae9d088 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts
@@ -8,17 +8,21 @@ import { dashboardApi } from "metabase/api/dashboard";
import { tag } from "metabase/api/tags";
import { timelineApi } from "metabase/api/timeline";
import { timelineEventApi } from "metabase/api/timeline-event";
+import { getCollectionFromCollectionsTree } from "metabase/selectors/collection";
+import { documentApi } from "metabase-enterprise/api/document";
+import { remoteSyncApi } from "metabase-enterprise/api/remote-sync";
import type {
Card,
+ CardId,
Collection,
+ CollectionId,
Dashboard,
+ DashboardId,
Document,
RemoteSyncTaskStatus,
} from "metabase-types/api";
import type { State } from "metabase-types/store";
-import { documentApi } from "../../api/document";
-import { remoteSyncApi } from "../../api/remote-sync";
import { REMOTE_SYNC_INVALIDATION_TAGS } from "../constants";
import {
modalDismissed,
@@ -92,6 +96,34 @@ function shouldInvalidateForCollection(
return oldType === "remote-synced" || newType === "remote-synced";
}
+function getOriginalDocument(originalState: State, id: number) {
+ return (
+ documentApi.endpoints.getDocument.select({ id })(originalState as any)
+ ?.data || originalState.entities.documents[id]
+ );
+}
+
+function getOriginalDashboard(originalState: State, id: DashboardId) {
+ return (
+ dashboardApi.endpoints.getDashboard.select({ id })(originalState as any)
+ ?.data || originalState.entities.dashboards[id]
+ );
+}
+
+function getOriginalCard(originalState: State, id: CardId) {
+ return (
+ cardApi.endpoints.getCard.select({ id })(originalState as any)?.data ||
+ originalState.entities.questions[id]
+ );
+}
+
+function getOriginalCollection(originalState: State, id: CollectionId) {
+ return (
+ collectionApi.endpoints.getCollection.select({ id })(originalState)?.data ||
+ getCollectionFromCollectionsTree(originalState, id)
+ );
+}
+
remoteSyncListenerMiddleware.startListening({
matcher: isAnyOf(
cardApi.endpoints.createCard.matchFulfilled,
@@ -117,11 +149,7 @@ remoteSyncListenerMiddleware.startListening({
{ getOriginalState, dispatch },
) => {
const newCard = action.payload;
- const originalState = getOriginalState();
-
- const oldCard = cardApi.endpoints.getCard.select({ id: newCard.id })(
- originalState,
- )?.data;
+ const oldCard = getOriginalCard(getOriginalState(), newCard.id);
if (shouldInvalidateForEntity(oldCard, newCard)) {
invalidateRemoteSyncTags(dispatch);
@@ -136,11 +164,10 @@ remoteSyncListenerMiddleware.startListening({
{ getOriginalState, dispatch },
) => {
const newDashboard = action.payload;
- const originalState = getOriginalState();
-
- const oldDashboard = dashboardApi.endpoints.getDashboard.select({
- id: newDashboard.id,
- })(originalState)?.data;
+ const oldDashboard = getOriginalDashboard(
+ getOriginalState(),
+ newDashboard.id,
+ );
if (shouldInvalidateForEntity(oldDashboard, newDashboard)) {
invalidateRemoteSyncTags(dispatch);
@@ -155,11 +182,7 @@ remoteSyncListenerMiddleware.startListening({
{ getOriginalState, dispatch },
) => {
const newDocument = action.payload;
- const originalState = getOriginalState();
-
- const oldDocument = documentApi.endpoints.getDocument.select({
- id: newDocument.id,
- })(originalState as any)?.data;
+ const oldDocument = getOriginalDocument(getOriginalState(), newDocument.id);
if (shouldInvalidateForEntity(oldDocument, newDocument)) {
invalidateRemoteSyncTags(dispatch);
@@ -170,13 +193,10 @@ remoteSyncListenerMiddleware.startListening({
remoteSyncListenerMiddleware.startListening({
matcher: cardApi.endpoints.deleteCard.matchFulfilled,
effect: async (action, { getOriginalState, dispatch }) => {
- const originalState = getOriginalState();
const id = (action.meta as any).arg.originalArgs as number;
if (id) {
- const card = cardApi.endpoints.getCard.select({ id })(
- originalState,
- )?.data;
+ const card = getOriginalCard(getOriginalState(), id);
if (card?.is_remote_synced) {
invalidateRemoteSyncTags(dispatch);
@@ -188,13 +208,10 @@ remoteSyncListenerMiddleware.startListening({
remoteSyncListenerMiddleware.startListening({
matcher: dashboardApi.endpoints.deleteDashboard.matchFulfilled,
effect: async (action, { getOriginalState, dispatch }) => {
- const originalState = getOriginalState();
const id = (action.meta as any).arg.originalArgs as number;
if (id) {
- const dashboard = dashboardApi.endpoints.getDashboard.select({ id })(
- originalState,
- )?.data;
+ const dashboard = getOriginalDashboard(getOriginalState(), id);
if (dashboard?.is_remote_synced) {
invalidateRemoteSyncTags(dispatch);
@@ -206,13 +223,10 @@ remoteSyncListenerMiddleware.startListening({
remoteSyncListenerMiddleware.startListening({
matcher: documentApi.endpoints.deleteDocument.matchFulfilled,
effect: async (action, { getOriginalState, dispatch }) => {
- const originalState = getOriginalState();
const id = (action.meta as any).arg.originalArgs as number;
if (id) {
- const document = documentApi.endpoints.getDocument.select({ id })(
- originalState as any,
- )?.data;
+ const document = getOriginalDocument(getOriginalState(), id);
if (document?.is_remote_synced) {
invalidateRemoteSyncTags(dispatch);
@@ -239,11 +253,10 @@ remoteSyncListenerMiddleware.startListening({
{ getOriginalState, dispatch },
) => {
const newCollection = action.payload;
- const originalState = getOriginalState();
-
- const oldCollection = collectionApi.endpoints.getCollection.select({
- id: newCollection.id,
- })(originalState)?.data;
+ const oldCollection = getOriginalCollection(
+ getOriginalState(),
+ newCollection.id,
+ );
if (shouldInvalidateForCollection(oldCollection, newCollection)) {
invalidateRemoteSyncTags(dispatch);
@@ -254,15 +267,15 @@ remoteSyncListenerMiddleware.startListening({
remoteSyncListenerMiddleware.startListening({
matcher: collectionApi.endpoints.deleteCollection.matchFulfilled,
effect: async (action, { getOriginalState, dispatch }) => {
- const originalState = getOriginalState();
const deleteRequest = (action.meta as any).arg.originalArgs as {
id: number;
};
if (deleteRequest?.id) {
- const collection = collectionApi.endpoints.getCollection.select({
- id: deleteRequest.id,
- })(originalState)?.data;
+ const collection = getOriginalCollection(
+ getOriginalState(),
+ deleteRequest.id,
+ );
if (collection?.type === "remote-synced") {
invalidateRemoteSyncTags(dispatch);
diff --git a/frontend/src/metabase-types/api/schema.ts b/frontend/src/metabase-types/api/schema.ts
index d99fa38b9a8..f71e16f73c6 100644
--- a/frontend/src/metabase-types/api/schema.ts
+++ b/frontend/src/metabase-types/api/schema.ts
@@ -3,6 +3,7 @@ import type { Card, CardId } from "./card";
import type { Collection, CollectionId, CollectionItemId } from "./collection";
import type { Dashboard } from "./dashboard";
import type { Database, DatabaseId } from "./database";
+import type { Document } from "./document";
import type { Field, FieldDimension, FieldId } from "./field";
import type { Segment, SegmentId } from "./segment";
import type { NativeQuerySnippet } from "./snippets";
@@ -18,6 +19,7 @@ import type { Timeline, TimelineEventId } from "./timeline";
export type NormalizedWritebackAction = WritebackAction;
export type NormalizedDashboard = Dashboard;
+export type NormalizedDocument = Document;
export type NormalizedCard = Card;
export type NormalizedNativeQuerySnippet = NativeQuerySnippet;
diff --git a/frontend/src/metabase-types/store/entities.ts b/frontend/src/metabase-types/store/entities.ts
index c97028a7fe0..b1b70fbeeb7 100644
--- a/frontend/src/metabase-types/store/entities.ts
+++ b/frontend/src/metabase-types/store/entities.ts
@@ -3,6 +3,7 @@ import type {
NormalizedCollection,
NormalizedDashboard,
NormalizedDatabase,
+ NormalizedDocument,
NormalizedField,
NormalizedIndexedEntity,
NormalizedNativeQuerySnippet,
@@ -16,6 +17,7 @@ export interface EntitiesState {
actions: Record<string, NormalizedWritebackAction>;
collections: Record<string, NormalizedCollection>;
dashboards: Record<string, NormalizedDashboard>;
+ documents: Record<string, NormalizedDocument>;
databases: Record<string, NormalizedDatabase>;
schemas: Record<string, NormalizedSchema>;
tables: Record<string, NormalizedTable>;
diff --git a/frontend/src/metabase-types/store/mocks/entities.ts b/frontend/src/metabase-types/store/mocks/entities.ts
index 16a68609046..0fbfb23a62e 100644
--- a/frontend/src/metabase-types/store/mocks/entities.ts
+++ b/frontend/src/metabase-types/store/mocks/entities.ts
@@ -7,6 +7,7 @@ export const createMockNormalizedEntitiesState = (): EntitiesState => ({
collections: {},
dashboards: {},
databases: {},
+ documents: {},
schemas: {},
tables: {},
fields: {},
diff --git a/frontend/src/metabase/common/utils/collections.ts b/frontend/src/metabase/common/utils/collections.ts
new file mode 100644
index 00000000000..a8f8cf22e1f
--- /dev/null
+++ b/frontend/src/metabase/common/utils/collections.ts
@@ -0,0 +1,21 @@
+import type { Collection, CollectionId } from "metabase-types/api";
+
+export const findCollectionById = (
+ collectionsTree?: Collection[],
+ collectionId?: CollectionId,
+): Collection | null => {
+ if (!collectionsTree?.length || !collectionId) {
+ return null;
+ }
+
+ const collection = collectionsTree.find((c) => c.id === collectionId);
+
+ if (collection) {
+ return collection;
+ }
+
+ return findCollectionById(
+ collectionsTree.map((c) => c.children || []).flat(),
+ collectionId,
+ );
+};
diff --git a/frontend/src/metabase/common/utils/collections.unit.spec.ts b/frontend/src/metabase/common/utils/collections.unit.spec.ts
new file mode 100644
index 00000000000..00032da7551
--- /dev/null
+++ b/frontend/src/metabase/common/utils/collections.unit.spec.ts
@@ -0,0 +1,57 @@
+import type { Collection } from "metabase-types/api";
+import { createMockCollection } from "metabase-types/api/mocks";
+
+import { findCollectionById } from "./collections";
+
+describe("findCollectionById", () => {
+ it("should return null when collections array is empty or undefined", () => {
+ expect(findCollectionById([], 1)).toBeNull();
+ expect(findCollectionById(undefined, 1)).toBeNull();
+ });
+
+ it("should return null when collectionId is undefined", () => {
+ const collections = [createMockCollection({ id: 1 })];
+ expect(findCollectionById(collections, undefined)).toBeNull();
+ });
+
+ it("should find collection at top level", () => {
+ const targetCollection = createMockCollection({ id: 2, name: "Target" });
+ const collections = [
+ createMockCollection({ id: 1, name: "First" }),
+ targetCollection,
+ createMockCollection({ id: 3, name: "Third" }),
+ ];
+
+ const result = findCollectionById(collections, 2);
+ expect(result).toEqual(targetCollection);
+ });
+
+ it("should recursively search nested children collections", () => {
+ const deeplyNestedCollection = createMockCollection({
+ id: 5,
+ name: "Deeply Nested",
+ });
+
+ const collections: Collection[] = [
+ createMockCollection({
+ id: 1,
+ name: "Parent 1",
+ children: [
+ createMockCollection({
+ id: 2,
+ name: "Child 1-1",
+ children: [deeplyNestedCollection],
+ }),
+ createMockCollection({ id: 3, name: "Child 1-2" }),
+ ],
+ }),
+ createMockCollection({
+ id: 4,
+ name: "Parent 2",
+ }),
+ ];
+
+ const result = findCollectionById(collections, 5);
+ expect(result).toEqual(deeplyNestedCollection);
+ });
+});
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
index a1fa386a90a..0d0b5984d03 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
@@ -13,6 +13,7 @@ import {
import { Tree } from "metabase/common/components/tree";
import { useSetting, useUserSetting } from "metabase/common/hooks";
import { useIsAtHomepageDashboard } from "metabase/common/hooks/use-is-at-homepage-dashboard";
+import type { CollectionTreeItem } from "metabase/entities/collections";
import {
getCanAccessOnboardingPage,
getIsNewInstance,
@@ -22,15 +23,8 @@ import { useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { WhatsNewNotification } from "metabase/nav/components/WhatsNewNotification";
import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
-import {
- ActionIcon,
- Flex,
- Icon,
- type IconName,
- type IconProps,
- Tooltip,
-} from "metabase/ui";
-import type { Bookmark, Collection } from "metabase-types/api";
+import { ActionIcon, Flex, Icon, Tooltip } from "metabase/ui";
+import type { Bookmark } from "metabase-types/api";
import {
PaddedSidebarLink,
@@ -51,10 +45,6 @@ import BookmarkList from "./BookmarkList";
import { BrowseNavSection } from "./BrowseNavSection";
import { GettingStartedSection } from "./GettingStartedSection";
-export interface CollectionTreeItem extends Collection {
- icon: IconName | IconProps;
- children: CollectionTreeItem[];
-}
type Props = {
isAdmin: boolean;
isOpen: boolean;
@@ -221,9 +211,9 @@ export function MainNavbarView({
{showSyncGroup && (
<PLUGIN_REMOTE_SYNC.SyncedCollectionsSidebarSection
- syncedCollections={syncedCollections}
- collectionItem={collectionItem}
onItemSelect={onItemSelect}
+ selectedId={collectionItem?.id}
+ syncedCollections={syncedCollections}
/>
)}
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index fadf21d1a8b..7054d66ac27 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -103,7 +103,11 @@ import type {
} from "metabase-types/store";
import type { EmbeddingEntityType } from "metabase-types/store/embedding-data-picker";
-import type { GetAuthProviders, PluginGroupManagersType } from "./types";
+import type {
+ GetAuthProviders,
+ PluginGroupManagersType,
+ SyncedCollectionsSidebarSectionProps,
+} from "./types";
// functions called when the application is started
export const PLUGIN_APP_INIT_FUNCTIONS: (() => void)[] = [];
@@ -913,11 +917,7 @@ export const PLUGIN_TRANSFORMS: TransformsPlugin = {
export const PLUGIN_REMOTE_SYNC: {
LibraryNav: ComponentType;
RemoteSyncSettings: ComponentType;
- SyncedCollectionsSidebarSection: ComponentType<{
- syncedCollections: any[];
- collectionItem: any;
- onItemSelect: () => void;
- }>;
+ SyncedCollectionsSidebarSection: ComponentType<SyncedCollectionsSidebarSectionProps>;
REMOTE_SYNC_INVALIDATION_TAGS: TagDescription<any>[] | null;
useSyncStatus: () => {
isIdle: boolean;
diff --git a/frontend/src/metabase/plugins/types.ts b/frontend/src/metabase/plugins/types.ts
index bdd61258a54..5903b8b969a 100644
--- a/frontend/src/metabase/plugins/types.ts
+++ b/frontend/src/metabase/plugins/types.ts
@@ -1,6 +1,7 @@
import type { ComponentType } from "react";
import type { ConfirmationState } from "metabase/common/hooks/use-confirmation";
+import type { CollectionTreeItem } from "metabase/entities/collections";
import type { Member, Membership, User } from "metabase-types/api";
export interface AuthProvider {
@@ -47,3 +48,9 @@ export type PluginGroupManagersType = {
confirmDeleteMembershipAction: any;
confirmUpdateMembershipAction: any;
};
+
+export type SyncedCollectionsSidebarSectionProps = {
+ onItemSelect: VoidFunction;
+ selectedId?: number | string;
+ syncedCollections: CollectionTreeItem[];
+};
diff --git a/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityPicker.jsx b/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityPicker.jsx
index 253f2bd9fde..abff0b80cd1 100644
--- a/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityPicker.jsx
+++ b/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/SavedEntityPicker.jsx
@@ -8,6 +8,7 @@ import {
nonPersonalOrArchivedCollection,
} from "metabase/collections/utils";
import { Tree } from "metabase/common/components/tree";
+import { findCollectionById } from "metabase/common/utils/collections";
import CS from "metabase/css/core/index.css";
import Collections, {
PERSONAL_COLLECTIONS,
@@ -19,7 +20,6 @@ import { Box, Icon } from "metabase/ui";
import SavedEntityList from "./SavedEntityList";
import SavedEntityPickerS from "./SavedEntityPicker.module.css";
import { CARD_INFO } from "./constants";
-import { findCollectionById } from "./utils";
const propTypes = {
type: PropTypes.string,
diff --git a/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/utils.js b/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/utils.js
deleted file mode 100644
index 63b2bc3cc18..00000000000
--- a/frontend/src/metabase/query_builder/components/DataSelector/saved-entity-picker/utils.js
+++ /dev/null
@@ -1,19 +0,0 @@
-export const findCollectionById = (collections, collectionId) => {
- if (!collections || collections.length === 0) {
- return null;
- }
-
- const collection = collections.find((c) => c.id === collectionId);
-
- if (collection) {
- return collection;
- }
-
- return findCollectionById(
- collections
- .map((c) => c.children)
- .filter(Boolean)
- .flat(),
- collectionId,
- );
-};
diff --git a/frontend/src/metabase/selectors/collection.ts b/frontend/src/metabase/selectors/collection.ts
new file mode 100644
index 00000000000..3678c8fe586
--- /dev/null
+++ b/frontend/src/metabase/selectors/collection.ts
@@ -0,0 +1,35 @@
+import { collectionApi } from "metabase/api";
+import { findCollectionById } from "metabase/common/utils/collections";
+import type { Collection, CollectionId } from "metabase-types/api";
+import type { State } from "metabase-types/store";
+
+export const getCollectionFromCollectionsTree = (
+ state: State,
+ collectionId: CollectionId,
+): Collection | undefined => {
+ const queriesCache = state[collectionApi.reducerPath]?.queries || {};
+ let collection: Collection | undefined;
+ let latestQueryTimestamp = 0;
+
+ for (const [queryName, queryState] of Object.entries(queriesCache)) {
+ if (
+ queryName.startsWith(collectionApi.endpoints.listCollectionsTree.name) &&
+ queryState?.status === "fulfilled" &&
+ queryState?.data
+ ) {
+ if (queryState.fulfilledTimeStamp < latestQueryTimestamp) {
+ continue;
+ }
+
+ const collectionsTree = queryState.data as Collection[];
+ const foundCollection = findCollectionById(collectionsTree, collectionId);
+
+ if (foundCollection) {
+ latestQueryTimestamp = queryState.fulfilledTimeStamp;
+ collection = foundCollection;
+ }
+ }
+ }
+
+ return collection;
+};
diff --git a/frontend/src/metabase/selectors/collection.unit.spec.ts b/frontend/src/metabase/selectors/collection.unit.spec.ts
new file mode 100644
index 00000000000..530a04d26fa
--- /dev/null
+++ b/frontend/src/metabase/selectors/collection.unit.spec.ts
@@ -0,0 +1,84 @@
+import { QueryStatus } from "@reduxjs/toolkit/query";
+
+import type { Collection } from "metabase-types/api";
+import { createMockCollection } from "metabase-types/api/mocks";
+import type { State } from "metabase-types/store";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { getCollectionFromCollectionsTree } from "./collection";
+
+const createMockStateWithCollectionsTree = (collections: Collection[]) => {
+ return createMockState({
+ "metabase-api": {
+ queries: {
+ "listCollectionsTree(undefined)": {
+ status: QueryStatus.fulfilled,
+ data: collections,
+ error: undefined,
+ originalArgs: undefined,
+ requestId: "test-request-1",
+ endpointName: "listCollectionsTree",
+ startedTimeStamp: Date.now(),
+ fulfilledTimeStamp: Date.now(),
+ },
+ },
+ },
+ } as unknown as Partial<State>);
+};
+
+describe("getCollectionFromCollectionsTree", () => {
+ it("should return undefined when no collections tree is cached", () => {
+ const state = createMockStateWithCollectionsTree([]);
+ const result = getCollectionFromCollectionsTree(state, 1);
+ expect(result).toBeUndefined();
+ });
+
+ it("should return undefined when collection is not found in tree", () => {
+ const collections = [
+ createMockCollection({ id: 1, name: "Collection 1" }),
+ createMockCollection({ id: 2, name: "Collection 2" }),
+ ];
+
+ const state = createMockStateWithCollectionsTree(collections);
+
+ const result = getCollectionFromCollectionsTree(state, 999);
+ expect(result).toBeUndefined();
+ });
+
+ it("should find collection at top level of tree", () => {
+ const targetCollection = createMockCollection({ id: 2, name: "Target" });
+ const collections = [
+ createMockCollection({ id: 1, name: "Collection 1" }),
+ targetCollection,
+ createMockCollection({ id: 3, name: "Collection 3" }),
+ ];
+
+ const state = createMockStateWithCollectionsTree(collections);
+
+ const result = getCollectionFromCollectionsTree(state, 2);
+ expect(result).toEqual(targetCollection);
+ });
+
+ it("should find collection nested in children", () => {
+ const nestedCollection = createMockCollection({
+ id: 3,
+ name: "Nested Collection",
+ });
+
+ const collections: Collection[] = [
+ createMockCollection({
+ id: 1,
+ name: "Parent",
+ children: [
+ createMockCollection({ id: 2, name: "Child" }),
+ nestedCollection,
+ ],
+ }),
+ ];
+
+ const state = createMockStateWithCollectionsTree(collections);
+
+ const result = getCollectionFromCollectionsTree(state, 3);
+ expect(result).toEqual(nestedCollection);
+ });
+});
diff --git a/frontend/test/__support__/store.ts b/frontend/test/__support__/store.ts
index 154e56d73b7..3a314f76d4e 100644
--- a/frontend/test/__support__/store.ts
+++ b/frontend/test/__support__/store.ts
@@ -6,6 +6,7 @@ import {
CollectionSchema,
DashboardSchema,
DatabaseSchema,
+ DocumentSchema,
FieldSchema,
IndexedEntitySchema,
QuestionSchema,
@@ -50,6 +51,7 @@ const EntitiesSchema: Record<keyof EntitiesState, NormalizrSchema<any>> = {
collections: [CollectionSchema],
dashboards: [DashboardSchema],
databases: [DatabaseSchema],
+ documents: [DocumentSchema],
schemas: [SchemaSchema],
tables: [TableSchema],
fields: [FieldSchema],