Skip to content

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

feat: add branch picker to data studio (#66970)

Edward Pagetf4d51537fa82
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.module.css b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.module.css
index a6f0768ef08..5aa58db671e 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.module.css
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.module.css
@@ -73,3 +73,9 @@
.disablePointer {
cursor: default;
}
+
+.badgeOverlay {
+ position: absolute;
+ top: 0.25rem;
+ right: 0.25rem;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
index 49dffb35b0c..d2e285716fb 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/app/pages/DataStudioLayout/DataStudioLayout.tsx
@@ -10,6 +10,7 @@ import * as Urls from "metabase/lib/urls";
import {
PLUGIN_DEPENDENCIES,
PLUGIN_FEATURE_LEVEL_PERMISSIONS,
+ PLUGIN_REMOTE_SYNC,
PLUGIN_TRANSFORMS,
} from "metabase/plugins";
import { getLocation } from "metabase/selectors/routing";
@@ -74,6 +75,7 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {
const canAccessTransforms = useSelector(
PLUGIN_TRANSFORMS.canAccessTransforms,
);
+ const hasDirtyChanges = PLUGIN_REMOTE_SYNC.useHasLibraryDirtyChanges();
const currentTab = getCurrentTab(pathname);
@@ -90,12 +92,20 @@ function DataStudioNav({ isNavbarOpened, onNavbarToggle }: DataStudioNavProps) {
isNavbarOpened={isNavbarOpened}
onNavbarToggle={onNavbarToggle}
/>
+ {isNavbarOpened && (
+ <PLUGIN_REMOTE_SYNC.GitSyncAppBarControls fullWidth />
+ )}
<DataStudioTab
label={t`Library`}
icon="repository"
to={Urls.dataStudioLibrary()}
isSelected={currentTab === "library"}
showLabel={isNavbarOpened}
+ rightSection={
+ hasDirtyChanges && PLUGIN_REMOTE_SYNC.CollectionSyncStatusBadge ? (
+ <PLUGIN_REMOTE_SYNC.CollectionSyncStatusBadge />
+ ) : null
+ }
/>
{canAccessDataModel && (
@@ -171,6 +181,7 @@ type DataStudioTabProps = {
to: string;
isSelected?: boolean;
showLabel: boolean;
+ rightSection?: ReactNode;
};
const TOOLTIP_OPEN_DELAY = 1000;
@@ -181,6 +192,7 @@ function DataStudioTab({
to,
isSelected,
showLabel,
+ rightSection,
}: DataStudioTabProps) {
return (
<Tooltip
@@ -199,6 +211,14 @@ function DataStudioTab({
>
<FixedSizeIcon name={icon} display="block" className={S.icon} />
{showLabel && <Text lh="sm">{label}</Text>}
+ {rightSection && (
+ <Box
+ className={showLabel ? undefined : S.badgeOverlay}
+ ml={showLabel ? "auto" : undefined}
+ >
+ {rightSection}
+ </Box>
+ )}
</Box>
</Tooltip>
);
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx
index 4eb496bc6c2..a40f96946b3 100644
--- a/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.tsx
@@ -1,4 +1,4 @@
-import { useMemo } from "react";
+import { useCallback, useMemo } from "react";
import { t } from "ttag";
import ErrorBoundary from "metabase/ErrorBoundary";
@@ -12,6 +12,9 @@ import {
SidebarSection,
} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";
import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";
+import { CollectionSyncStatusBadge } from "metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/CollectionSyncStatusBadge";
+import { useGitSyncVisible } from "metabase-enterprise/remote_sync/hooks/use-git-sync-visible";
+import { useRemoteSyncDirtyState } from "metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state";
import type { Collection } from "metabase-types/api";
type LibraryCollectionSectionProps = {
@@ -29,6 +32,9 @@ export function NavbarLibrarySection({
"expand-library-in-nav",
);
+ const { isVisible: isGitSyncVisible } = useGitSyncVisible();
+ const { isCollectionDirty } = useRemoteSyncDirtyState();
+
const libraryTree = useMemo(() => {
const libraryCollection = collections.find(isLibraryCollection);
if (!libraryCollection) {
@@ -43,6 +49,16 @@ export function NavbarLibrarySection({
return tree[0].children || [];
}, [collections]);
+ const showChangesBadge = useCallback(
+ (itemId?: number | string) => {
+ if (!isGitSyncVisible || typeof itemId !== "number") {
+ return false;
+ }
+ return isCollectionDirty(itemId);
+ },
+ [isGitSyncVisible, isCollectionDirty],
+ );
+
if (libraryTree.length === 0) {
return null;
}
@@ -66,6 +82,9 @@ export function NavbarLibrarySection({
TreeNode={SidebarCollectionLink}
role="tree"
aria-label="library-collection-tree"
+ rightSection={(item) =>
+ showChangesBadge(item?.id) && <CollectionSyncStatusBadge />
+ }
/>
</CollapseSection>
</ErrorBoundary>
diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.unit.spec.tsx
new file mode 100644
index 00000000000..7400b6b858f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/nav/components/NavbarLibrarySection/NavbarLibrarySection.unit.spec.tsx
@@ -0,0 +1,221 @@
+import fetchMock from "fetch-mock";
+import { Route } from "react-router";
+
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { Collection } from "metabase-types/api";
+import { createMockCollection } from "metabase-types/api/mocks";
+import { createMockState } from "metabase-types/store/mocks";
+
+// Mock isLibraryCollection to return true for collections with type "library"
+jest.mock("metabase/collections/utils", () => ({
+ ...jest.requireActual("metabase/collections/utils"),
+ isLibraryCollection: (collection: { type: string | null }) =>
+ collection?.type === "library",
+}));
+
+// Mock useGitSyncVisible
+const mockUseGitSyncVisible = jest.fn(() => ({
+ isVisible: true,
+ currentBranch: "main",
+}));
+jest.mock("metabase-enterprise/remote_sync/hooks/use-git-sync-visible", () => ({
+ useGitSyncVisible: () => mockUseGitSyncVisible(),
+}));
+
+// Mock useRemoteSyncDirtyState
+const mockIsCollectionDirty = jest.fn(
+ (_id: number | string | undefined) => false,
+);
+jest.mock(
+ "metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state",
+ () => ({
+ useRemoteSyncDirtyState: () => ({
+ isCollectionDirty: mockIsCollectionDirty,
+ }),
+ }),
+);
+
+import { NavbarLibrarySection } from "./NavbarLibrarySection";
+
+const createChildCollection = (
+ overrides: Partial<Collection> = {},
+): Collection =>
+ createMockCollection({
+ id: 10,
+ name: "Metrics",
+ type: null,
+ location: "/1/",
+ here: ["card"],
+ below: ["card"],
+ ...overrides,
+ } as Partial<Collection>);
+
+const createLibraryCollection = (
+ overrides: Partial<Collection> = {},
+): Collection =>
+ createMockCollection({
+ id: 1,
+ name: "Library",
+ type: "library",
+ location: "/",
+ here: ["card"],
+ below: ["card"],
+ ...overrides,
+ } as Partial<Collection>);
+
+const setup = ({
+ collections = [createLibraryCollection()],
+ dirtyCollectionIds = [] as number[],
+ isGitSyncVisible = true,
+}: {
+ collections?: Collection[];
+ dirtyCollectionIds?: number[];
+ isGitSyncVisible?: boolean;
+} = {}) => {
+ mockUseGitSyncVisible.mockReturnValue({
+ isVisible: isGitSyncVisible,
+ currentBranch: "main",
+ });
+ mockIsCollectionDirty.mockImplementation(
+ (id: number | string | undefined) =>
+ typeof id === "number" && dirtyCollectionIds.includes(id),
+ );
+
+ return renderWithProviders(
+ <Route
+ path="/"
+ component={() => (
+ <NavbarLibrarySection
+ collections={collections}
+ selectedId={undefined}
+ onItemSelect={jest.fn()}
+ />
+ )}
+ />,
+ {
+ storeInitialState: createMockState({
+ settings: mockSettings({
+ "expand-library-in-nav": true,
+ }),
+ }),
+ withRouter: true,
+ withDND: true,
+ },
+ );
+};
+
+describe("NavbarLibrarySection", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ });
+
+ describe("rendering", () => {
+ it("should render library subcollections", async () => {
+ const libraryCollection = createLibraryCollection({
+ children: [createChildCollection({ name: "Metrics" })],
+ });
+ setup({ collections: [libraryCollection] });
+
+ await waitFor(() => {
+ expect(screen.getByText("Metrics")).toBeInTheDocument();
+ });
+ });
+
+ it("should not render when no library collection exists", () => {
+ const regularCollection = createMockCollection({
+ id: 2,
+ name: "Regular",
+ type: null,
+ });
+ setup({ collections: [regularCollection] });
+
+ expect(screen.queryByText("Library")).not.toBeInTheDocument();
+ });
+ });
+
+ describe("dirty state badges", () => {
+ it("should not show badge when git sync is not visible", async () => {
+ const libraryCollection = createLibraryCollection({
+ children: [createChildCollection({ id: 10, name: "Metrics" })],
+ });
+ setup({
+ collections: [libraryCollection],
+ dirtyCollectionIds: [10],
+ isGitSyncVisible: false,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Metrics")).toBeInTheDocument();
+ });
+
+ expect(
+ screen.queryByTestId("remote-sync-status"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should not show badge when collection has no dirty changes", async () => {
+ const libraryCollection = createLibraryCollection({
+ children: [createChildCollection({ id: 10, name: "Metrics" })],
+ });
+ setup({
+ collections: [libraryCollection],
+ dirtyCollectionIds: [],
+ isGitSyncVisible: true,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Metrics")).toBeInTheDocument();
+ });
+
+ expect(
+ screen.queryByTestId("remote-sync-status"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("should show badge when collection has dirty changes and git sync is visible", async () => {
+ const libraryCollection = createLibraryCollection({
+ children: [createChildCollection({ id: 10, name: "Metrics" })],
+ });
+ setup({
+ collections: [libraryCollection],
+ dirtyCollectionIds: [10],
+ isGitSyncVisible: true,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Metrics")).toBeInTheDocument();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("remote-sync-status")).toBeInTheDocument();
+ });
+ });
+
+ it("should show badge only for collections with changes", async () => {
+ const libraryCollection = createLibraryCollection({
+ children: [
+ createChildCollection({ id: 10, name: "Dirty Collection" }),
+ createChildCollection({ id: 11, name: "Clean Collection" }),
+ ],
+ });
+ setup({
+ collections: [libraryCollection],
+ dirtyCollectionIds: [10],
+ isGitSyncVisible: true,
+ });
+
+ await waitFor(() => {
+ expect(screen.getByText("Dirty Collection")).toBeInTheDocument();
+ });
+ expect(screen.getByText("Clean Collection")).toBeInTheDocument();
+
+ await waitFor(() => {
+ const badges = screen.getAllByTestId("remote-sync-status");
+ expect(badges).toHaveLength(1);
+ });
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsx
index dc1a183ee5d..e24c85528a3 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.tsx
@@ -5,8 +5,8 @@ import { Tree } from "metabase/common/components/tree";
import type { ITreeNodeItem } from "metabase/common/components/tree/types";
import type { CollectionTreeItem } from "metabase/entities/collections";
import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";
-import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";
+import { useRemoteSyncDirtyState } from "../../hooks/use-remote-sync-dirty-state";
import { CollectionSyncStatusBadge } from "../SyncedCollectionsSidebarSection/CollectionSyncStatusBadge";
interface CollectionsNavTreeProps {
@@ -30,28 +30,16 @@ export const CollectionsNavTree = ({
[collectionsList],
);
- const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {
- skip: !hasRemoteSyncedCollections,
- refetchOnFocus: true,
- });
-
- const changedCollections = useMemo(
- () => dirtyData?.changedCollections ?? {},
- [dirtyData?.changedCollections],
- );
+ const { isCollectionDirty } = useRemoteSyncDirtyState();
const showChangesBadge = useCallback(
(itemId?: number | string) => {
- if (
- !hasRemoteSyncedCollections ||
- !changedCollections ||
- typeof itemId !== "number"
- ) {
+ if (!hasRemoteSyncedCollections) {
return false;
}
- return !!changedCollections[itemId];
+ return isCollectionDirty(itemId);
},
- [hasRemoteSyncedCollections, changedCollections],
+ [hasRemoteSyncedCollections, isCollectionDirty],
);
return (
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsx
index fc4d251ca5b..d6fbea8ffe7 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/CollectionsNavTree/CollectionsNavTree.unit.spec.tsx
@@ -1,19 +1,22 @@
import fetchMock from "fetch-mock";
import { Route } from "react-router";
-import {
- setupPropertiesEndpoints,
- setupSettingsEndpoints,
-} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import type { Collection } from "metabase-types/api";
-import {
- createMockCollection,
- createMockSettings,
-} from "metabase-types/api/mocks";
+import { createMockCollection } from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
+// Mock useRemoteSyncDirtyState
+const mockIsCollectionDirty = jest.fn(
+ (_id: number | string | undefined) => false,
+);
+jest.mock("../../hooks/use-remote-sync-dirty-state", () => ({
+ useRemoteSyncDirtyState: () => ({
+ isCollectionDirty: mockIsCollectionDirty,
+ }),
+}));
+
import { CollectionsNavTree } from "./CollectionsNavTree";
const createMockCollectionTreeItem = (
@@ -29,34 +32,28 @@ const createMockCollectionTreeItem = (
const setupEndpoints = ({
collections = [createMockCollectionTreeItem()],
- dirty = [],
- changedCollections = {},
}: {
collections?: Collection[];
- dirty?: { id: number; name: string; model: string; collection_id: number }[];
- changedCollections?: Record<number, boolean>;
} = {}) => {
fetchMock.get("path:/api/collection", collections);
- fetchMock.get("path:/api/ee/remote-sync/dirty", {
- dirty,
- changedCollections,
- });
- setupPropertiesEndpoints(createMockSettings());
- setupSettingsEndpoints([]);
};
const setup = ({
collections = [createMockCollectionTreeItem()],
collectionsList = [createMockCollectionTreeItem()],
- dirty = [],
- changedCollections = {},
+ dirtyCollectionIds = [] as number[],
}: {
collections?: Collection[];
collectionsList?: Collection[];
- dirty?: { id: number; name: string; model: string; collection_id: number }[];
- changedCollections?: Record<number, boolean>;
+ dirtyCollectionIds?: number[];
} = {}) => {
- setupEndpoints({ collections: collectionsList, dirty, changedCollections });
+ setupEndpoints({ collections: collectionsList });
+
+ // Configure mock to return true for dirty collection IDs
+ mockIsCollectionDirty.mockImplementation(
+ (id: number | string | undefined) =>
+ typeof id === "number" && dirtyCollectionIds.includes(id),
+ );
return renderWithProviders(
<Route
@@ -82,6 +79,9 @@ const setup = ({
describe("CollectionsNavTree", () => {
beforeEach(() => {
jest.clearAllMocks();
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ mockIsCollectionDirty.mockReturnValue(false);
});
describe("rendering", () => {
@@ -124,8 +124,7 @@ describe("CollectionsNavTree", () => {
setup({
collections: [collection],
collectionsList: [collection],
- dirty: [{ id: 1, name: "Card", model: "card", collection_id: 1 }],
- changedCollections: { 1: true },
+ dirtyCollectionIds: [1],
});
await waitFor(() => {
@@ -147,8 +146,7 @@ describe("CollectionsNavTree", () => {
setup({
collections: [collection],
collectionsList: [collection],
- dirty: [{ id: 1, name: "Card", model: "card", collection_id: 1 }],
- changedCollections: { 1: true },
+ dirtyCollectionIds: [1],
});
await waitFor(() => {
@@ -169,8 +167,7 @@ describe("CollectionsNavTree", () => {
setup({
collections: [syncedCollection],
collectionsList: [syncedCollection],
- dirty: [],
- changedCollections: {},
+ dirtyCollectionIds: [],
});
await waitFor(() => {
@@ -197,8 +194,7 @@ describe("CollectionsNavTree", () => {
setup({
collections: [dirtyCollection, cleanCollection],
collectionsList: [dirtyCollection, cleanCollection],
- dirty: [{ id: 1, name: "Card", model: "card", collection_id: 1 }],
- changedCollections: { 1: true },
+ dirtyCollectionIds: [1],
});
await waitFor(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsx
index f1b63a51c13..394dc3ead14 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/BranchPicker.tsx
@@ -117,6 +117,8 @@ export const BranchPicker = ({
py="1rem"
size="compact-sm"
variant="default"
+ justify="left"
+ flex={1}
disabled={disabled || isLoading || isCreating}
onClick={() => combobox.toggleDropdown()}
leftSection={<Icon name="git_branch" c="text-medium" size={14} />}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx
index 967cb2fbcc0..dd8e4eba5bb 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.tsx
@@ -1,18 +1,13 @@
import { useCallback, useState } from "react";
import { t } from "ttag";
-import { useAdminSetting } from "metabase/api/utils";
import { useToast } from "metabase/common/hooks";
-import { useSelector } from "metabase/lib/redux";
-import { getUserIsAdmin } from "metabase/selectors/user";
import { Button, Icon, Loader, Tooltip } from "metabase/ui";
-import {
- useGetRemoteSyncChangesQuery,
- useImportChangesMutation,
-} from "metabase-enterprise/api";
+import { useImportChangesMutation } from "metabase-enterprise/api";
import { trackBranchSwitched, trackPullChanges } from "../../analytics";
-import { BRANCH_KEY, REMOTE_SYNC_KEY, TYPE_KEY } from "../../constants";
+import { useGitSyncVisible } from "../../hooks/use-git-sync-visible";
+import { useRemoteSyncDirtyState } from "../../hooks/use-remote-sync-dirty-state";
import { useSyncStatus } from "../../hooks/use-sync-status";
import { type SyncError, parseSyncError } from "../../utils";
import { PushChangesModal } from "../PushChangesModal";
@@ -23,11 +18,14 @@ import {
import { BranchPicker } from "./BranchPicker";
-export const GitSyncControls = () => {
- const isAdmin = useSelector(getUserIsAdmin);
- const { value: isRemoteSyncEnabled } = useAdminSetting(REMOTE_SYNC_KEY);
- const { value: currentBranch } = useAdminSetting(BRANCH_KEY);
- const { value: syncType } = useAdminSetting(TYPE_KEY);
+interface GitSyncControlsProps {
+ fullWidth?: boolean;
+}
+
+export const GitSyncControls = ({
+ fullWidth = false,
+}: GitSyncControlsProps) => {
+ const { isVisible, currentBranch } = useGitSyncVisible();
const [importChanges, { isLoading: isImporting }] =
useImportChangesMutation();
@@ -39,14 +37,9 @@ export const GitSyncControls = () => {
const [showPushModal, setShowPushModal] = useState(false);
const [sendToast] = useToast();
- const { data: dirtyData, refetch: refetchDirty } =
- useGetRemoteSyncChangesQuery(undefined, {
- skip: !isRemoteSyncEnabled,
- refetchOnFocus: true,
- });
+ const { isDirty, refetch: refetchDirty } = useRemoteSyncDirtyState();
const isSwitchingBranch = !!nextBranch;
- const isDirty = !!(dirtyData?.dirty && dirtyData.dirty.length > 0);
const isLoading = isSyncTaskRunning || isSwitchingBranch || isImporting;
const changeBranch = useCallback(
@@ -144,19 +137,17 @@ export const GitSyncControls = () => {
setNextBranch(null);
}, []);
- // Don't render if remote sync is not enabled, user is not admin, or not in read-write mode
- if (
- !isRemoteSyncEnabled ||
- !isAdmin ||
- !currentBranch ||
- syncType !== "read-write"
- ) {
+ if (!isVisible || !currentBranch) {
return null;
}
return (
<>
- <Button.Group data-testid="git-sync-controls" mr="2rem">
+ <Button.Group
+ data-testid="git-sync-controls"
+ mr={fullWidth ? undefined : "2rem"}
+ w={fullWidth ? "100%" : "13.5rem"}
+ >
<BranchPicker
isLoading={isLoading}
value={currentBranch}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx
index a1f92d9ebc4..aa0e65b37d2 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/GitSyncControls/GitSyncControls.unit.spec.tsx
@@ -19,6 +19,7 @@ const setup = ({
syncType = "read-write",
dirty = [],
branches = ["main", "develop"],
+ fullWidth = false,
}: {
isAdmin?: boolean;
remoteSyncEnabled?: boolean;
@@ -26,12 +27,13 @@ const setup = ({
syncType?: "read-only" | "read-write";
dirty?: ReturnType<typeof createMockDirtyEntity>[];
branches?: string[];
+ fullWidth?: boolean;
} = {}) => {
setupRemoteSyncEndpoints({ branches, dirty });
setupCollectionEndpoints();
setupSessionEndpoints({ remoteSyncEnabled, currentBranch, syncType });
- return renderWithProviders(<GitSyncControls />, {
+ return renderWithProviders(<GitSyncControls fullWidth={fullWidth} />, {
storeInitialState: createRemoteSyncStoreState({
isAdmin,
remoteSyncEnabled,
@@ -247,4 +249,29 @@ describe("GitSyncControls", () => {
});
});
});
+
+ describe("fullWidth prop", () => {
+ it("should render with default styling when fullWidth is false", async () => {
+ setup({ fullWidth: false });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("git-sync-controls")).toBeInTheDocument();
+ });
+
+ const controls = screen.getByTestId("git-sync-controls");
+ expect(controls).toHaveStyle({ width: "13.5rem" });
+ });
+
+ it("should render with full width when fullWidth is true", async () => {
+ setup({ fullWidth: true });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("git-sync-controls")).toBeInTheDocument();
+ });
+
+ const controls = screen.getByTestId("git-sync-controls");
+ expect(controls).toHaveStyle({ width: "100%" });
+ expect(controls).not.toHaveStyle({ maxWidth: "13.5rem" });
+ });
+ });
});
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 4b47e00c006..63c5e1ef551 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
@@ -1,7 +1,7 @@
+import { useMemo } from "react";
import { t } from "ttag";
import ErrorBoundary from "metabase/ErrorBoundary";
-import { useAdminSetting } from "metabase/api/utils";
import { Tree } from "metabase/common/components/tree";
import {
SidebarHeading,
@@ -10,9 +10,9 @@ import {
import { SidebarCollectionLink } from "metabase/nav/containers/MainNavbar/SidebarItems";
import type { SyncedCollectionsSidebarSectionProps } from "metabase/plugins/types";
import { Box, Flex, Group, Text } from "metabase/ui";
-import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";
-import { REMOTE_SYNC_KEY } from "../../constants";
+import { useGitSyncVisible } from "../../hooks/use-git-sync-visible";
+import { useRemoteSyncDirtyState } from "../../hooks/use-remote-sync-dirty-state";
import { CollectionSyncStatusBadge } from "./CollectionSyncStatusBadge";
@@ -23,24 +23,20 @@ export const SyncedCollectionsSidebarSection = ({
}: SyncedCollectionsSidebarSectionProps) => {
const hasSyncedCollections = syncedCollections.length > 0;
- const { value: isRemoteSyncEnabled } = useAdminSetting(REMOTE_SYNC_KEY);
+ const { isVisible: isGitSyncVisible } = useGitSyncVisible();
+ const { dirty, isCollectionDirty } = useRemoteSyncDirtyState();
- const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {
- skip: !isRemoteSyncEnabled,
- refetchOnFocus: true,
- });
-
- const changedCollections = dirtyData?.changedCollections ?? {};
- const hasEntityRemoved = dirtyData?.dirty?.some(
- (entity) => entity.sync_status === "removed",
+ const hasEntityRemoved = useMemo(
+ () => dirty.some((entity) => entity.sync_status === "removed"),
+ [dirty],
);
const showChangesBadge = (itemId?: number | string) => {
- if (!changedCollections || typeof itemId !== "number") {
+ if (typeof itemId !== "number") {
return false;
}
- const collectionIsUpdated = !!changedCollections[itemId];
+ const collectionIsUpdated = isCollectionDirty(itemId);
const hasSingleRootCollection = syncedCollections.length === 1;
return (
@@ -53,7 +49,7 @@ export const SyncedCollectionsSidebarSection = ({
);
};
- if (!isRemoteSyncEnabled) {
+ if (!isGitSyncVisible) {
return null;
}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/index.ts
index f2223e379f3..1eb23e243e0 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/SyncedCollectionsSidebarSection/index.ts
@@ -1 +1,2 @@
export { SyncedCollectionsSidebarSection } from "./SyncedCollectionsSidebarSection";
+export { CollectionSyncStatusBadge } from "./CollectionSyncStatusBadge";
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-git-sync-visible.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-git-sync-visible.ts
new file mode 100644
index 00000000000..bf3374e13ca
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-git-sync-visible.ts
@@ -0,0 +1,30 @@
+import { useAdminSetting } from "metabase/api/utils";
+import { useSelector } from "metabase/lib/redux";
+import { getUserIsAdmin } from "metabase/selectors/user";
+
+import { BRANCH_KEY, REMOTE_SYNC_KEY, TYPE_KEY } from "../constants";
+
+export interface GitSyncVisibleState {
+ isVisible: boolean;
+ currentBranch: string | null | undefined;
+}
+
+/**
+ * Hook to check if the GitSyncControls would be visible and get the current branch.
+ * This centralizes the visibility logic used by GitSyncControls and other components.
+ */
+export const useGitSyncVisible = (): GitSyncVisibleState => {
+ const isAdmin = useSelector(getUserIsAdmin);
+ const { value: isRemoteSyncEnabled } = useAdminSetting(REMOTE_SYNC_KEY);
+ const { value: currentBranch } = useAdminSetting(BRANCH_KEY);
+ const { value: syncType } = useAdminSetting(TYPE_KEY);
+
+ const isVisible = !!(
+ isRemoteSyncEnabled &&
+ isAdmin &&
+ currentBranch &&
+ syncType === "read-write"
+ );
+
+ return { isVisible, currentBranch };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-git-sync-visible.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-git-sync-visible.unit.spec.ts
new file mode 100644
index 00000000000..2e46967b21c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-git-sync-visible.unit.spec.ts
@@ -0,0 +1,112 @@
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import { createMockSettings, createMockUser } from "metabase-types/api/mocks";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { useGitSyncVisible } from "./use-git-sync-visible";
+
+const setup = ({
+ isAdmin = true,
+ remoteSyncEnabled = true,
+ currentBranch = "main",
+ syncType = "read-write",
+}: {
+ isAdmin?: boolean;
+ remoteSyncEnabled?: boolean;
+ currentBranch?: string | null;
+ syncType?: "read-only" | "read-write";
+} = {}) => {
+ setupPropertiesEndpoints(
+ createMockSettings({
+ "remote-sync-enabled": remoteSyncEnabled,
+ "remote-sync-branch": currentBranch,
+ "remote-sync-type": syncType,
+ }),
+ );
+ setupSettingsEndpoints([]);
+
+ const storeInitialState = createMockState({
+ currentUser: createMockUser({ is_superuser: isAdmin }),
+ settings: mockSettings({
+ "remote-sync-enabled": remoteSyncEnabled,
+ "remote-sync-branch": currentBranch,
+ "remote-sync-type": syncType,
+ }),
+ });
+
+ return renderHookWithProviders(() => useGitSyncVisible(), {
+ storeInitialState,
+ });
+};
+
+describe("useGitSyncVisible", () => {
+ it("should return isVisible: true when all conditions are met", async () => {
+ const { result } = setup({
+ isAdmin: true,
+ remoteSyncEnabled: true,
+ currentBranch: "main",
+ syncType: "read-write",
+ });
+
+ await waitFor(() => {
+ expect(result.current.isVisible).toBe(true);
+ });
+ expect(result.current.currentBranch).toBe("main");
+ });
+
+ it("should return isVisible: false when remote sync is disabled", async () => {
+ const { result } = setup({
+ remoteSyncEnabled: false,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isVisible).toBe(false);
+ });
+ });
+
+ it("should return isVisible: false when user is not admin", async () => {
+ const { result } = setup({
+ isAdmin: false,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isVisible).toBe(false);
+ });
+ });
+
+ it("should return isVisible: false when currentBranch is null", async () => {
+ const { result } = setup({
+ currentBranch: null,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isVisible).toBe(false);
+ });
+ expect(result.current.currentBranch).toBe(null);
+ });
+
+ it("should return isVisible: false when sync type is read-only", async () => {
+ const { result } = setup({
+ syncType: "read-only",
+ });
+
+ await waitFor(() => {
+ expect(result.current.isVisible).toBe(false);
+ });
+ });
+
+ it("should return isVisible: false when multiple conditions fail", async () => {
+ const { result } = setup({
+ isAdmin: false,
+ remoteSyncEnabled: false,
+ });
+
+ await waitFor(() => {
+ expect(result.current.isVisible).toBe(false);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-has-library-dirty-changes.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-has-library-dirty-changes.ts
new file mode 100644
index 00000000000..10597a470cb
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-has-library-dirty-changes.ts
@@ -0,0 +1,47 @@
+import { useMemo } from "react";
+
+import { useListCollectionsTreeQuery } from "metabase/api";
+import { isLibraryCollection } from "metabase/collections/utils";
+import { getAllDescendantIds } from "metabase/common/components/tree/utils";
+import { buildCollectionTree } from "metabase/entities/collections";
+
+import { useGitSyncVisible } from "./use-git-sync-visible";
+import { useRemoteSyncDirtyState } from "./use-remote-sync-dirty-state";
+
+export function useHasLibraryDirtyChanges(): boolean {
+ const { isVisible: isGitSyncVisible } = useGitSyncVisible();
+ const { hasDirtyInCollectionTree, isDirty } = useRemoteSyncDirtyState();
+
+ const { data: collections = [] } = useListCollectionsTreeQuery(
+ {
+ "exclude-other-user-collections": true,
+ "exclude-archived": true,
+ "include-library": true,
+ },
+ { skip: !isGitSyncVisible },
+ );
+
+ return useMemo(() => {
+ if (!isDirty) {
+ return false;
+ }
+
+ const libraryCollection = collections.find(isLibraryCollection);
+ if (!libraryCollection) {
+ return false;
+ }
+
+ // Build tree and get all descendant IDs (including Library itself)
+ const libraryTree = buildCollectionTree([libraryCollection]);
+ const libraryCollectionIds = getAllDescendantIds(libraryTree);
+
+ // Filter to only numeric IDs for the dirty check
+ const numericIds = new Set(
+ [...libraryCollectionIds].filter(
+ (id): id is number => typeof id === "number",
+ ),
+ );
+
+ return hasDirtyInCollectionTree(numericIds);
+ }, [collections, isDirty, hasDirtyInCollectionTree]);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-has-library-dirty-changes.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-has-library-dirty-changes.unit.spec.ts
new file mode 100644
index 00000000000..3432be6bf1c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-has-library-dirty-changes.unit.spec.ts
@@ -0,0 +1,167 @@
+import fetchMock from "fetch-mock";
+
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import type { Collection } from "metabase-types/api";
+import { createMockCollection } from "metabase-types/api/mocks";
+
+// Mock isLibraryCollection to return true for collections with type "library"
+jest.mock("metabase/collections/utils", () => ({
+ ...jest.requireActual("metabase/collections/utils"),
+ isLibraryCollection: (collection: { type: string | null }) =>
+ collection?.type === "library",
+}));
+
+// Mock useRemoteSyncDirtyState
+const mockHasDirtyInCollectionTree = jest.fn(
+ (_collectionIds: Set<number>) => false,
+);
+const mockIsDirty = jest.fn(() => false);
+jest.mock("./use-remote-sync-dirty-state", () => ({
+ useRemoteSyncDirtyState: () => ({
+ hasDirtyInCollectionTree: mockHasDirtyInCollectionTree,
+ isDirty: mockIsDirty(),
+ }),
+}));
+
+// Mock useGitSyncVisible
+const mockUseGitSyncVisible = jest.fn<
+ { isVisible: boolean; currentBranch: string | null },
+ []
+>(() => ({
+ isVisible: true,
+ currentBranch: "main",
+}));
+jest.mock("./use-git-sync-visible", () => ({
+ useGitSyncVisible: () => mockUseGitSyncVisible(),
+}));
+
+import { useHasLibraryDirtyChanges } from "./use-has-library-dirty-changes";
+
+const createLibraryCollection = (
+ overrides: Partial<Collection> = {},
+): Collection =>
+ createMockCollection({
+ id: 1,
+ name: "Library",
+ type: "library",
+ ...overrides,
+ });
+
+const createRegularCollection = (
+ overrides: Partial<Collection> = {},
+): Collection =>
+ createMockCollection({
+ id: 2,
+ name: "Regular Collection",
+ type: null,
+ ...overrides,
+ });
+
+const setupCollectionsEndpoint = (collections: Collection[]) => {
+ fetchMock.get("path:/api/collection/tree", collections);
+};
+
+const setup = () => {
+ return renderHookWithProviders(() => useHasLibraryDirtyChanges(), {});
+};
+
+describe("useHasLibraryDirtyChanges", () => {
+ beforeEach(() => {
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ mockUseGitSyncVisible.mockReturnValue({
+ isVisible: true,
+ currentBranch: "main",
+ });
+ mockIsDirty.mockReturnValue(false);
+ mockHasDirtyInCollectionTree.mockReturnValue(false);
+ });
+
+ it("returns false when no dirty changes exist", async () => {
+ setupCollectionsEndpoint([createLibraryCollection()]);
+ mockIsDirty.mockReturnValue(false);
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current).toBe(false);
+ });
+ });
+
+ it("returns false when dirty changes exist but not in Library collections", async () => {
+ setupCollectionsEndpoint([
+ createLibraryCollection({ id: 1 }),
+ createRegularCollection({ id: 2 }),
+ ]);
+ mockIsDirty.mockReturnValue(true);
+ mockHasDirtyInCollectionTree.mockReturnValue(false);
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current).toBe(false);
+ });
+ });
+
+ it("returns true when Library collection has dirty items", async () => {
+ setupCollectionsEndpoint([createLibraryCollection({ id: 1 })]);
+ mockIsDirty.mockReturnValue(true);
+ // When hasDirtyInCollectionTree is called with the library IDs, return true
+ mockHasDirtyInCollectionTree.mockReturnValue(true);
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current).toBe(true);
+ });
+ });
+
+ it("calls hasDirtyInCollectionTree when Library exists and isDirty", async () => {
+ setupCollectionsEndpoint([createLibraryCollection({ id: 42 })]);
+ mockIsDirty.mockReturnValue(true);
+ mockHasDirtyInCollectionTree.mockReturnValue(false);
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current).toBe(false);
+ });
+
+ // Verify hasDirtyInCollectionTree was called with a Set
+ expect(mockHasDirtyInCollectionTree).toHaveBeenCalled();
+ const calledWith = mockHasDirtyInCollectionTree.mock.calls[0]?.[0];
+ expect(calledWith).toBeInstanceOf(Set);
+ // The Set should contain numeric IDs (exact IDs depend on buildCollectionTree transformation)
+ expect(calledWith?.size).toBeGreaterThan(0);
+ });
+
+ it("returns false when no Library collection exists", async () => {
+ setupCollectionsEndpoint([createRegularCollection()]);
+ mockIsDirty.mockReturnValue(true);
+ mockHasDirtyInCollectionTree.mockReturnValue(true);
+
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current).toBe(false);
+ });
+ });
+
+ it("returns false when git sync is not visible", async () => {
+ setupCollectionsEndpoint([createLibraryCollection()]);
+ mockUseGitSyncVisible.mockReturnValue({
+ isVisible: false,
+ currentBranch: null,
+ });
+ mockIsDirty.mockReturnValue(true);
+ mockHasDirtyInCollectionTree.mockReturnValue(true);
+
+ const { result } = setup();
+
+ // When git sync is not visible, collections query is skipped,
+ // so no library collection will be found
+ await waitFor(() => {
+ expect(result.current).toBe(false);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state.ts
new file mode 100644
index 00000000000..2b317d5ea0d
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state.ts
@@ -0,0 +1,102 @@
+import { useCallback, useMemo } from "react";
+
+import type { RemoteSyncEntity } from "metabase-types/api";
+
+import { useGetRemoteSyncChangesQuery } from "../../api";
+
+import { useGitSyncVisible } from "./use-git-sync-visible";
+
+export interface RemoteSyncDirtyState {
+ /** Array of all dirty entities */
+ dirty: RemoteSyncEntity[];
+ /** Map of collection IDs that have dirty child entities */
+ changedCollections: Record<number, boolean>;
+ /** Whether any dirty changes exist globally */
+ isDirty: boolean;
+ /** Whether data is loading */
+ isLoading: boolean;
+ /** Check if a specific collection has dirty items */
+ isCollectionDirty: (collectionId: number | string | undefined) => boolean;
+ /** Check if any collection in a set has dirty items */
+ hasAnyCollectionDirty: (collectionIds: Set<number> | number[]) => boolean;
+ /** Check if any dirty entity (including collections) is in the given set of IDs */
+ hasDirtyInCollectionTree: (collectionIds: Set<number>) => boolean;
+ /** Refetch the dirty state data */
+ refetch: () => ReturnType<
+ ReturnType<typeof useGetRemoteSyncChangesQuery>["refetch"]
+ >;
+}
+
+export function useRemoteSyncDirtyState(): RemoteSyncDirtyState {
+ const { isVisible: isGitSyncVisible } = useGitSyncVisible();
+
+ const {
+ data: dirtyData,
+ isLoading,
+ refetch,
+ } = useGetRemoteSyncChangesQuery(undefined, {
+ skip: !isGitSyncVisible,
+ refetchOnFocus: true,
+ });
+
+ const dirty = useMemo(() => dirtyData?.dirty ?? [], [dirtyData?.dirty]);
+ const changedCollections = useMemo(
+ () => dirtyData?.changedCollections ?? {},
+ [dirtyData?.changedCollections],
+ );
+ const isDirty = dirty.length > 0;
+
+ const isCollectionDirty = useCallback(
+ (collectionId: number | string | undefined) => {
+ if (typeof collectionId !== "number") {
+ return false;
+ }
+ return !!changedCollections[collectionId];
+ },
+ [changedCollections],
+ );
+
+ const hasAnyCollectionDirty = useCallback(
+ (collectionIds: Set<number> | number[]) => {
+ const ids =
+ collectionIds instanceof Set ? collectionIds : new Set(collectionIds);
+ for (const id of Object.keys(changedCollections)) {
+ if (ids.has(Number(id))) {
+ return true;
+ }
+ }
+ return false;
+ },
+ [changedCollections],
+ );
+
+ const hasDirtyInCollectionTree = useCallback(
+ (collectionIds: Set<number>) => {
+ // Check changedCollections map (collections with dirty child entities)
+ for (const id of Object.keys(changedCollections)) {
+ if (collectionIds.has(Number(id))) {
+ return true;
+ }
+ }
+ // Check if any dirty collection itself is in the tree
+ for (const entity of dirty) {
+ if (entity.model === "collection" && collectionIds.has(entity.id)) {
+ return true;
+ }
+ }
+ return false;
+ },
+ [changedCollections, dirty],
+ );
+
+ return {
+ dirty,
+ changedCollections,
+ isDirty,
+ isLoading,
+ isCollectionDirty,
+ hasAnyCollectionDirty,
+ hasDirtyInCollectionTree,
+ refetch,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state.unit.spec.ts
new file mode 100644
index 00000000000..6eea6d98a06
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-dirty-state.unit.spec.ts
@@ -0,0 +1,263 @@
+import fetchMock from "fetch-mock";
+
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+
+// Mock the useGitSyncVisible hook before importing useRemoteSyncDirtyState
+const mockUseGitSyncVisible = jest.fn(() => ({
+ isVisible: true,
+ currentBranch: "main",
+}));
+jest.mock("./use-git-sync-visible", () => ({
+ useGitSyncVisible: () => mockUseGitSyncVisible(),
+}));
+
+import { useRemoteSyncDirtyState } from "./use-remote-sync-dirty-state";
+
+const createMockDirtyEntity = (overrides: Record<string, unknown> = {}) => ({
+ id: 1,
+ name: "Test Entity",
+ description: null,
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: null,
+ model: "card" as const,
+ sync_status: "update" as const,
+ collection_id: 1,
+ ...overrides,
+});
+
+const setupEndpoints = ({
+ dirty = [],
+ changedCollections = {},
+}: {
+ dirty?: Array<ReturnType<typeof createMockDirtyEntity>>;
+ changedCollections?: Record<number, boolean>;
+} = {}) => {
+ fetchMock.get("path:/api/ee/remote-sync/dirty", {
+ dirty,
+ changedCollections,
+ });
+};
+
+const setup = ({
+ isGitSyncVisible = true,
+ dirty = [],
+ changedCollections = {},
+}: {
+ isGitSyncVisible?: boolean;
+ dirty?: Array<ReturnType<typeof createMockDirtyEntity>>;
+ changedCollections?: Record<number, boolean>;
+} = {}) => {
+ mockUseGitSyncVisible.mockReturnValue({
+ isVisible: isGitSyncVisible,
+ currentBranch: "main",
+ });
+ setupEndpoints({ dirty, changedCollections });
+
+ return renderHookWithProviders(() => useRemoteSyncDirtyState(), {});
+};
+
+describe("useRemoteSyncDirtyState", () => {
+ beforeEach(() => {
+ fetchMock.removeRoutes();
+ fetchMock.clearHistory();
+ });
+
+ describe("isDirty", () => {
+ it("returns false when no dirty entities exist", async () => {
+ const { result } = setup({ dirty: [] });
+
+ await waitFor(() => {
+ expect(result.current.isDirty).toBe(false);
+ });
+ });
+
+ it("returns true when dirty entities exist", async () => {
+ const { result } = setup({
+ dirty: [createMockDirtyEntity()],
+ });
+
+ await waitFor(() => {
+ expect(result.current.isDirty).toBe(true);
+ });
+ });
+ });
+
+ describe("isCollectionDirty", () => {
+ it("returns false for collection without dirty items", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 1 })],
+ });
+
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.isCollectionDirty(2)).toBe(false);
+ });
+
+ it("returns true for collection with dirty items", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 1 })],
+ });
+
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.isCollectionDirty(1)).toBe(true);
+ });
+
+ it("returns false for non-numeric collection id", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 1 })],
+ });
+
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.isCollectionDirty("root")).toBe(false);
+ expect(result.current.isCollectionDirty(undefined)).toBe(false);
+ });
+ });
+
+ describe("hasAnyCollectionDirty", () => {
+ it("returns false when no collections in set are dirty", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 1 })],
+ });
+
+ // Wait for data to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasAnyCollectionDirty(new Set([2, 3]))).toBe(false);
+ });
+
+ it("returns true when any collection in set is dirty", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [
+ createMockDirtyEntity({ id: 1, collection_id: 1 }),
+ createMockDirtyEntity({ id: 2, collection_id: 3 }),
+ ],
+ });
+
+ // Wait for data to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasAnyCollectionDirty(new Set([2, 3]))).toBe(true);
+ });
+
+ it("works with array input", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 1 })],
+ });
+
+ // Wait for data to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasAnyCollectionDirty([1, 2])).toBe(true);
+ });
+ });
+
+ describe("hasDirtyInCollectionTree", () => {
+ it("returns false when no collections in tree are dirty", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 100 })],
+ });
+
+ // Wait for data to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasDirtyInCollectionTree(new Set([1, 2, 3]))).toBe(
+ false,
+ );
+ });
+
+ it("returns true when a collection in tree has dirty children", async () => {
+ // changedCollections is built from dirty entities' collection_id
+ const { result } = setup({
+ dirty: [createMockDirtyEntity({ collection_id: 2 })],
+ });
+
+ // Wait for data to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasDirtyInCollectionTree(new Set([1, 2, 3]))).toBe(
+ true,
+ );
+ });
+
+ it("returns true when a collection in tree is itself dirty", async () => {
+ const { result } = setup({
+ dirty: [
+ createMockDirtyEntity({
+ id: 2,
+ model: "collection",
+ collection_id: null,
+ }),
+ ],
+ });
+
+ // Wait for dirty to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasDirtyInCollectionTree(new Set([1, 2, 3]))).toBe(
+ true,
+ );
+ });
+
+ it("returns false when dirty collection is not in tree", async () => {
+ const { result } = setup({
+ dirty: [
+ createMockDirtyEntity({
+ id: 100,
+ model: "collection",
+ collection_id: null,
+ }),
+ ],
+ });
+
+ // Wait for dirty to be populated
+ await waitFor(() => {
+ expect(result.current.dirty.length).toBeGreaterThan(0);
+ });
+
+ expect(result.current.hasDirtyInCollectionTree(new Set([1, 2, 3]))).toBe(
+ false,
+ );
+ });
+ });
+
+ describe("when git sync is not visible", () => {
+ it("returns empty dirty state", async () => {
+ const { result } = setup({
+ isGitSyncVisible: false,
+ dirty: [createMockDirtyEntity()],
+ });
+
+ await waitFor(() => {
+ expect(result.current.dirty).toEqual([]);
+ });
+ expect(result.current.isDirty).toBe(false);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts
index 25244e23809..7a2ca16fbbd 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/index.ts
@@ -9,8 +9,13 @@ import { LibraryNav } from "./LibraryNav";
import { CollectionsNavTree } from "./components/CollectionsNavTree";
import { GitSyncControls } from "./components/GitSyncControls";
import { RemoteSyncAdminSettings } from "./components/RemoteSyncAdminSettings/RemoteSyncAdminSettings";
-import { SyncedCollectionsSidebarSection } from "./components/SyncedCollectionsSidebarSection/SyncedCollectionsSidebarSection";
+import {
+ CollectionSyncStatusBadge,
+ SyncedCollectionsSidebarSection,
+} from "./components/SyncedCollectionsSidebarSection";
import { REMOTE_SYNC_INVALIDATION_TAGS } from "./constants";
+import { useGitSyncVisible } from "./hooks/use-git-sync-visible";
+import { useHasLibraryDirtyChanges } from "./hooks/use-has-library-dirty-changes";
import { useSyncStatus } from "./hooks/use-sync-status";
import { remoteSyncListenerMiddleware } from "./middleware/remote-sync-listener-middleware";
import { remoteSyncReducer } from "./sync-task-slice";
@@ -26,9 +31,12 @@ export function initializePlugin() {
SyncedCollectionsSidebarSection;
PLUGIN_REMOTE_SYNC.GitSyncAppBarControls = GitSyncControls;
PLUGIN_REMOTE_SYNC.CollectionsNavTree = CollectionsNavTree;
+ PLUGIN_REMOTE_SYNC.CollectionSyncStatusBadge = CollectionSyncStatusBadge;
PLUGIN_REMOTE_SYNC.REMOTE_SYNC_INVALIDATION_TAGS =
REMOTE_SYNC_INVALIDATION_TAGS;
PLUGIN_REMOTE_SYNC.useSyncStatus = useSyncStatus;
+ PLUGIN_REMOTE_SYNC.useGitSyncVisible = useGitSyncVisible;
+ PLUGIN_REMOTE_SYNC.useHasLibraryDirtyChanges = useHasLibraryDirtyChanges;
PLUGIN_REDUX_MIDDLEWARES.push(remoteSyncListenerMiddleware.middleware);
PLUGIN_REDUCERS.remoteSyncPlugin = remoteSyncReducer;
diff --git a/frontend/src/metabase/common/components/tree/utils.tsx b/frontend/src/metabase/common/components/tree/utils.tsx
index 9e368409642..b0d453cdcb2 100644
--- a/frontend/src/metabase/common/components/tree/utils.tsx
+++ b/frontend/src/metabase/common/components/tree/utils.tsx
@@ -36,3 +36,25 @@ export const getAllExpandableIds = (
traverse(nodes);
return ids;
};
+
+/**
+ * Recursively collects all IDs from tree nodes and their descendants.
+ * Unlike getAllExpandableIds, this includes ALL nodes (not just those with children).
+ */
+export const getAllDescendantIds = (
+ nodes: ITreeNodeItem[],
+): Set<ITreeNodeItem["id"]> => {
+ const ids = new Set<ITreeNodeItem["id"]>();
+
+ const traverse = (items: ITreeNodeItem[]) => {
+ for (const item of items) {
+ ids.add(item.id);
+ if (item.children && item.children.length > 0) {
+ traverse(item.children);
+ }
+ }
+ };
+
+ traverse(nodes);
+ return ids;
+};
diff --git a/frontend/src/metabase/common/components/tree/utils.unit.spec.tsx b/frontend/src/metabase/common/components/tree/utils.unit.spec.tsx
new file mode 100644
index 00000000000..ff6b96c0cbb
--- /dev/null
+++ b/frontend/src/metabase/common/components/tree/utils.unit.spec.tsx
@@ -0,0 +1,146 @@
+import type { ITreeNodeItem } from "./types";
+import {
+ getAllDescendantIds,
+ getAllExpandableIds,
+ getInitialExpandedIds,
+} from "./utils";
+
+const createTreeNode = (
+ id: number | string,
+ children: ITreeNodeItem[] = [],
+): ITreeNodeItem => ({
+ id,
+ name: `Node ${id}`,
+ icon: "folder",
+ children,
+});
+
+describe("tree/utils", () => {
+ describe("getAllDescendantIds", () => {
+ it("returns empty set for empty tree", () => {
+ const result = getAllDescendantIds([]);
+ expect(result.size).toBe(0);
+ });
+
+ it("returns single id for single node without children", () => {
+ const tree = [createTreeNode(1)];
+ const result = getAllDescendantIds(tree);
+ expect(result.size).toBe(1);
+ expect(result.has(1)).toBe(true);
+ });
+
+ it("returns all ids for flat tree", () => {
+ const tree = [createTreeNode(1), createTreeNode(2), createTreeNode(3)];
+ const result = getAllDescendantIds(tree);
+ expect(result.size).toBe(3);
+ expect(result.has(1)).toBe(true);
+ expect(result.has(2)).toBe(true);
+ expect(result.has(3)).toBe(true);
+ });
+
+ it("returns all ids including nested children", () => {
+ const tree = [
+ createTreeNode(1, [
+ createTreeNode(2, [createTreeNode(3)]),
+ createTreeNode(4),
+ ]),
+ createTreeNode(5),
+ ];
+ const result = getAllDescendantIds(tree);
+ expect(result.size).toBe(5);
+ expect(result.has(1)).toBe(true);
+ expect(result.has(2)).toBe(true);
+ expect(result.has(3)).toBe(true);
+ expect(result.has(4)).toBe(true);
+ expect(result.has(5)).toBe(true);
+ });
+
+ it("handles deeply nested trees", () => {
+ const tree = [
+ createTreeNode(1, [
+ createTreeNode(2, [
+ createTreeNode(3, [createTreeNode(4, [createTreeNode(5)])]),
+ ]),
+ ]),
+ ];
+ const result = getAllDescendantIds(tree);
+ expect(result.size).toBe(5);
+ [1, 2, 3, 4, 5].forEach((id) => {
+ expect(result.has(id)).toBe(true);
+ });
+ });
+
+ it("handles string ids", () => {
+ const tree = [
+ createTreeNode("a", [createTreeNode("b")]),
+ createTreeNode("c"),
+ ];
+ const result = getAllDescendantIds(tree);
+ expect(result.size).toBe(3);
+ expect(result.has("a")).toBe(true);
+ expect(result.has("b")).toBe(true);
+ expect(result.has("c")).toBe(true);
+ });
+
+ it("returns a Set for O(1) lookup", () => {
+ const tree = [createTreeNode(1)];
+ const result = getAllDescendantIds(tree);
+ expect(result instanceof Set).toBe(true);
+ });
+ });
+
+ describe("getAllExpandableIds", () => {
+ it("returns empty array for empty tree", () => {
+ const result = getAllExpandableIds([]);
+ expect(result).toEqual([]);
+ });
+
+ it("returns empty array for nodes without children", () => {
+ const tree = [createTreeNode(1), createTreeNode(2)];
+ const result = getAllExpandableIds(tree);
+ expect(result).toEqual([]);
+ });
+
+ it("returns ids of nodes with children", () => {
+ const tree = [createTreeNode(1, [createTreeNode(2)]), createTreeNode(3)];
+ const result = getAllExpandableIds(tree);
+ expect(result).toEqual([1]);
+ });
+
+ it("returns all expandable ids in nested tree", () => {
+ const tree = [
+ createTreeNode(1, [
+ createTreeNode(2, [createTreeNode(3)]),
+ createTreeNode(4),
+ ]),
+ ];
+ const result = getAllExpandableIds(tree);
+ expect(result).toContain(1);
+ expect(result).toContain(2);
+ expect(result).not.toContain(3);
+ expect(result).not.toContain(4);
+ });
+ });
+
+ describe("getInitialExpandedIds", () => {
+ it("returns empty array when selected id is not in tree", () => {
+ const tree = [createTreeNode(1), createTreeNode(2)];
+ const result = getInitialExpandedIds(999, tree);
+ expect(result).toEqual([]);
+ });
+
+ it("returns single id when selected id is at root level", () => {
+ const tree = [createTreeNode(1), createTreeNode(2)];
+ const result = getInitialExpandedIds(1, tree);
+ expect(result).toEqual([1]);
+ });
+
+ it("returns path to nested selected id", () => {
+ const tree = [
+ createTreeNode(1, [createTreeNode(2, [createTreeNode(3)])]),
+ ];
+ const result = getInitialExpandedIds(3, tree);
+ expect(result).toEqual([1, 2, 3]);
+ });
+ });
+});
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
index ff74a587ee2..a40fbd8646c 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
@@ -54,6 +54,8 @@ const AppBarLarge = ({
onToggleNavbar,
}: AppBarLargeProps): JSX.Element => {
const isNavBarVisible = isNavBarOpen && isNavBarEnabled;
+ const { isVisible: isGitSyncVisible } =
+ PLUGIN_REMOTE_SYNC.useGitSyncVisible();
return (
<AppBarRoot
@@ -73,6 +75,7 @@ const AppBarLarge = ({
<AppBarLogo
isLogoVisible={isLogoVisible}
isNavBarEnabled={isNavBarEnabled}
+ isGitSyncVisible={isGitSyncVisible}
/>
<PLUGIN_REMOTE_SYNC.GitSyncAppBarControls />
<AppBarInfoContainer
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLogo.styled.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLogo.styled.tsx
index e795f4320ff..fd0eff0e4e1 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarLogo.styled.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLogo.styled.tsx
@@ -6,8 +6,12 @@ import styled from "@emotion/styled";
import Link from "metabase/common/components/Link";
import { doNotForwardProps } from "metabase/common/utils/doNotForwardProps";
-export const LogoLink = styled(Link, doNotForwardProps("isSmallAppBar"))<{
+export const LogoLink = styled(
+ Link,
+ doNotForwardProps("isSmallAppBar", "isGitSyncVisible"),
+)<{
isSmallAppBar: boolean;
+ isGitSyncVisible: boolean;
}>`
cursor: pointer;
display: flex;
@@ -22,6 +26,6 @@ export const LogoLink = styled(Link, doNotForwardProps("isSmallAppBar"))<{
${(props) =>
!props.isSmallAppBar &&
css`
- margin-inline-end: 2rem;
+ margin-inline-end: ${props.isGitSyncVisible ? "1rem" : "2rem"};
`}
`;
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLogo.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLogo.tsx
index 59f793cf0ea..48539e3fde7 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarLogo.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLogo.tsx
@@ -9,6 +9,7 @@ export interface AppBarLogoProps {
isSmallAppBar?: boolean;
isLogoVisible?: boolean;
isNavBarEnabled?: boolean;
+ isGitSyncVisible?: boolean;
onLogoClick?: () => void;
}
@@ -16,6 +17,7 @@ export function AppBarLogo({
isLogoVisible,
isSmallAppBar,
isNavBarEnabled,
+ isGitSyncVisible,
onLogoClick,
}: AppBarLogoProps): JSX.Element | null {
const isAtHomepageDashboard = useIsAtHomepageDashboard();
@@ -37,6 +39,7 @@ export function AppBarLogo({
<LogoLink
to="/"
isSmallAppBar={Boolean(isSmallAppBar)}
+ isGitSyncVisible={Boolean(isGitSyncVisible)}
onClick={handleClick}
disabled={!isNavBarEnabled}
data-testid="main-logo-link"
diff --git a/frontend/src/metabase/plugins/oss/remote-sync.ts b/frontend/src/metabase/plugins/oss/remote-sync.ts
index 11689894172..ea818c9b3a6 100644
--- a/frontend/src/metabase/plugins/oss/remote-sync.ts
+++ b/frontend/src/metabase/plugins/oss/remote-sync.ts
@@ -16,12 +16,18 @@ export type CollectionsNavTreeProps = {
onSelect?: (item: ITreeNodeItem) => void;
};
+export interface GitSyncAppBarControlsProps {
+ fullWidth?: boolean;
+}
+
const getDefaultPluginRemoteSync = () => ({
LibraryNav: PluginPlaceholder,
RemoteSyncSettings: NotFoundPlaceholder,
SyncedCollectionsSidebarSection: PluginPlaceholder,
- GitSyncAppBarControls: PluginPlaceholder,
+ GitSyncAppBarControls:
+ PluginPlaceholder as ComponentType<GitSyncAppBarControlsProps>,
CollectionsNavTree: null as ComponentType<CollectionsNavTreeProps> | null,
+ CollectionSyncStatusBadge: null as ComponentType | null,
REMOTE_SYNC_INVALIDATION_TAGS: null,
useSyncStatus: () => ({
isIdle: true,
@@ -30,14 +36,17 @@ const getDefaultPluginRemoteSync = () => ({
message: "",
progressModal: null,
}),
+ useGitSyncVisible: () => ({ isVisible: false, currentBranch: null }),
+ useHasLibraryDirtyChanges: () => false,
});
export const PLUGIN_REMOTE_SYNC: {
LibraryNav: ComponentType;
RemoteSyncSettings: ComponentType;
SyncedCollectionsSidebarSection: ComponentType<SyncedCollectionsSidebarSectionProps>;
- GitSyncAppBarControls: ComponentType;
+ GitSyncAppBarControls: ComponentType<GitSyncAppBarControlsProps>;
CollectionsNavTree: ComponentType<CollectionsNavTreeProps> | null;
+ CollectionSyncStatusBadge: ComponentType | null;
REMOTE_SYNC_INVALIDATION_TAGS: TagDescription<any>[] | null;
useSyncStatus: () => {
isIdle: boolean;
@@ -46,6 +55,11 @@ export const PLUGIN_REMOTE_SYNC: {
message: string;
progressModal: ReactNode;
};
+ useGitSyncVisible: () => {
+ isVisible: boolean;
+ currentBranch: string | null | undefined;
+ };
+ useHasLibraryDirtyChanges: () => boolean;
} = getDefaultPluginRemoteSync();
/**