Skip to content

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

Break out RemoteSyncSettingsForm component into smaller chunks (#79379)

Nick Fitzpatrick8d598a796de3
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/LibrarySyncRow/LibrarySyncRow.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/LibrarySyncRow/LibrarySyncRow.tsx
index 612d8eb3ae6..e610bb7d820 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/LibrarySyncRow/LibrarySyncRow.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/LibrarySyncRow/LibrarySyncRow.tsx
@@ -3,20 +3,17 @@ import { t } from "ttag";
import CS from "metabase/css/core/bordered.module.css";
import { Box, Flex, Icon, Switch, Text } from "metabase/ui";
-import type { RemoteSyncConfigurationSettings } from "metabase-types/api";
import { SYNC_LIBRARY_PENDING_KEY } from "../../constants";
-
-type FormValues = RemoteSyncConfigurationSettings & {
- [SYNC_LIBRARY_PENDING_KEY]?: boolean;
-};
+import type { RemoteSyncSettingsFormState } from "../../types";
interface LibrarySyncRowProps {
isReadOnly: boolean;
}
export const LibrarySyncRow = ({ isReadOnly }: LibrarySyncRowProps) => {
- const { values, setFieldValue } = useFormikContext<FormValues>();
+ const { values, setFieldValue } =
+ useFormikContext<RemoteSyncSettingsFormState>();
const isChecked = values[SYNC_LIBRARY_PENDING_KEY] ?? false;
const handleToggle = (checked: boolean) => {
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcherSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcherSection.tsx
new file mode 100644
index 00000000000..952ca917b71
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/BranchSwitcherSection.tsx
@@ -0,0 +1,38 @@
+import { t } from "ttag";
+
+import { useGetAdminSettingsDetailsQuery } from "metabase/settings";
+import type { RemoteSyncEntity } from "metabase-types/api";
+
+import { BRANCH_KEY } from "../../constants";
+import { useGitSyncVisible } from "../../hooks/use-git-sync-visible";
+
+import { BranchSwitcher } from "./BranchSwitcher";
+import { RemoteSyncSettingsSection } from "./RemoteSyncSettingsSection";
+
+type BranchSwitcherSectionProps = {
+ dirty: RemoteSyncEntity[];
+};
+
+export const BranchSwitcherSection = ({
+ dirty,
+}: BranchSwitcherSectionProps) => {
+ const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
+ const { currentBranch } = useGitSyncVisible();
+
+ const branchDetails = settingDetails?.[BRANCH_KEY];
+ const isSetByEnv = !!branchDetails?.is_env_setting;
+
+ return (
+ <RemoteSyncSettingsSection
+ title={t`Sync branch`}
+ description={t`Choose which branch to sync with git.`}
+ >
+ <BranchSwitcher
+ currentBranch={currentBranch}
+ dirty={dirty}
+ disabled={isSetByEnv}
+ envVarName={isSetByEnv ? branchDetails.env_name : undefined}
+ />
+ </RemoteSyncSettingsSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/CollectionsToSyncSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/CollectionsToSyncSection.tsx
new file mode 100644
index 00000000000..92312e280a6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/CollectionsToSyncSection.tsx
@@ -0,0 +1,32 @@
+import { t } from "ttag";
+
+import { useSetting } from "metabase/settings";
+import { Stack, Text } from "metabase/ui";
+
+import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";
+import { TopLevelCollectionsList } from "../TopLevelCollectionsList";
+
+import { RemoteSyncSettingsSection } from "./RemoteSyncSettingsSection";
+
+export const CollectionsToSyncSection = () => {
+ const useTenants = useSetting("use-tenants");
+
+ return (
+ <RemoteSyncSettingsSection
+ title={t`Collections to sync`}
+ description={t`Choose which collections to sync with git.`}
+ >
+ <Stack gap="lg">
+ <TopLevelCollectionsList />
+ {useTenants && (
+ <>
+ <Text fw={700} size="md" lh="1rem">
+ {t`Shared collections`}
+ </Text>
+ <SharedTenantCollectionsList />
+ </>
+ )}
+ </Stack>
+ </RemoteSyncSettingsSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/GitSettingsSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/GitSettingsSection.tsx
new file mode 100644
index 00000000000..d9c238aa19f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/GitSettingsSection.tsx
@@ -0,0 +1,46 @@
+import { useFormikContext } from "formik";
+import { t } from "ttag";
+
+import { FormTextInput } from "metabase/forms";
+import { useGetAdminSettingsDetailsQuery } from "metabase/settings";
+import { Box, Text } from "metabase/ui";
+
+import { TOKEN_KEY, URL_KEY } from "../../constants";
+import type { RemoteSyncSettingsFormState } from "../../types";
+import { getEnvSettingProps } from "../../utils";
+
+import { RemoteSyncSettingsSection } from "./RemoteSyncSettingsSection";
+import { TestConnectionButton } from "./TestConnectionButton";
+
+export const GitSettingsSection = () => {
+ const { values } = useFormikContext<RemoteSyncSettingsFormState>();
+ const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
+
+ return (
+ <RemoteSyncSettingsSection title={t`Git settings`}>
+ <FormTextInput
+ name={URL_KEY}
+ label={t`Repository URL`}
+ placeholder="https://git-host.example.com/yourcompany/repo.git"
+ labelProps={{ mb: "0.75rem" }}
+ {...getEnvSettingProps(settingDetails?.[URL_KEY])}
+ />
+ <FormTextInput
+ name={TOKEN_KEY}
+ label={t`Access Token`}
+ description={
+ <Text c="text-disabled" size="sm" lh="md" component="span">
+ {t`Personal access token with write permissions`}
+ </Text>
+ }
+ type="password"
+ {...getEnvSettingProps(settingDetails?.[TOKEN_KEY], {
+ inputWrapperOrder: ["label", "description", "error"],
+ })}
+ />
+ <Box>
+ <TestConnectionButton values={values} />
+ </Box>
+ </RemoteSyncSettingsSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/ReadOnlyBranchSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/ReadOnlyBranchSection.tsx
new file mode 100644
index 00000000000..8bc83c0f3f7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/ReadOnlyBranchSection.tsx
@@ -0,0 +1,54 @@
+import { useFormikContext } from "formik";
+import { t } from "ttag";
+
+import { FormSwitch, FormTextInput } from "metabase/forms";
+import { useGetAdminSettingsDetailsQuery, useSetting } from "metabase/settings";
+import { Box, Stack } from "metabase/ui";
+
+import { AUTO_IMPORT_KEY, BRANCH_KEY, REMOTE_SYNC_KEY } from "../../constants";
+import type { RemoteSyncSettingsFormState } from "../../types";
+import { getEnvSettingProps } from "../../utils";
+
+import { PullChangesButton } from "./PullChangesButton";
+import { RemoteSyncSettingsSection } from "./RemoteSyncSettingsSection";
+
+export const ReadOnlyBranchSection = () => {
+ const { dirty, values } = useFormikContext<RemoteSyncSettingsFormState>();
+ const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
+ const isRemoteSyncEnabled = !!useSetting(REMOTE_SYNC_KEY);
+
+ return (
+ <RemoteSyncSettingsSection title={t`Branch to sync with`}>
+ <Stack gap="md">
+ <Box style={{ flex: 1 }}>
+ <FormTextInput
+ name={BRANCH_KEY}
+ placeholder="main"
+ label={t`Sync branch`}
+ labelProps={{ mb: "0.75rem" }}
+ {...getEnvSettingProps(settingDetails?.[BRANCH_KEY])}
+ />
+ </Box>
+ <FormSwitch
+ label={t`Auto-sync with git`}
+ description={t`Periodically import changes from the sync branch. When auto-sync is off, you'll need to pull changes from the sync branch manually.`}
+ mb="0.6125rem"
+ name={AUTO_IMPORT_KEY}
+ size="sm"
+ {...getEnvSettingProps(settingDetails?.[AUTO_IMPORT_KEY], {
+ disabled: true,
+ })}
+ />
+ </Stack>
+ {isRemoteSyncEnabled && (
+ <Box>
+ <PullChangesButton
+ branch={values?.[BRANCH_KEY] || "main"}
+ dirty={dirty}
+ forcePull
+ />
+ </Box>
+ )}
+ </RemoteSyncSettingsSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncConflictModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncConflictModal.tsx
new file mode 100644
index 00000000000..bd658330e90
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncConflictModal.tsx
@@ -0,0 +1,26 @@
+import { useDispatch, useSelector } from "metabase/redux";
+
+import { useGitSyncVisible } from "../../hooks/use-git-sync-visible";
+import { getSyncConflictVariant } from "../../selectors";
+import { syncConflictVariantUpdated } from "../../sync-task-slice";
+import { SyncConflictModal } from "../SyncConflictModal";
+
+export const RemoteSyncConflictModal = () => {
+ const dispatch = useDispatch();
+ const conflictVariant = useSelector(getSyncConflictVariant);
+ const { currentBranch } = useGitSyncVisible();
+
+ if (!conflictVariant || !currentBranch) {
+ return null;
+ }
+
+ return (
+ <SyncConflictModal
+ currentBranch={currentBranch}
+ onClose={() => {
+ dispatch(syncConflictVariantUpdated(null));
+ }}
+ variant={conflictVariant}
+ />
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx
index a3c153217eb..aa0806e6694 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx
@@ -1,369 +1,80 @@
-import { type ComponentProps, useCallback, useMemo, useRef } from "react";
import { jt, t } from "ttag";
-import { SettingsSection } from "metabase/admin/components/SettingsSection";
-import { useListCollectionItemsQuery } from "metabase/api";
-import { getErrorMessage } from "metabase/api/utils";
import { ExternalLink } from "metabase/common/components/ExternalLink";
-import { useDocsUrl, useToast } from "metabase/common/hooks";
-import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { useDocsUrl } from "metabase/common/hooks";
import {
Form,
FormErrorMessage,
FormProvider,
- FormRadioGroup,
FormSubmitButton,
- FormSwitch,
- FormTextInput,
} from "metabase/forms";
-import { PLUGIN_TRANSFORMS } from "metabase/plugins";
-import { useDispatch, useSelector } from "metabase/redux";
-import { getApplicationName } from "metabase/selectors/whitelabel";
import {
useGetAdminSettingsDetailsQuery,
useGetSettingsQuery,
useSetting,
} from "metabase/settings";
-import {
- Box,
- Button,
- Flex,
- Icon,
- Radio,
- Stack,
- Text,
- Tooltip,
-} from "metabase/ui";
-import {
- useCreateLibraryMutation,
- useGetLibraryCollectionQuery,
-} from "metabase-enterprise/api";
-import {
- useGetRemoteSyncChangesQuery,
- useUpdateRemoteSyncSettingsMutation,
-} from "metabase-enterprise/api/remote-sync";
-import { useGitSyncVisible } from "metabase-enterprise/remote_sync/hooks/use-git-sync-visible";
-import { getSyncConflictVariant } from "metabase-enterprise/remote_sync/selectors";
-import { syncConflictVariantUpdated } from "metabase-enterprise/remote_sync/sync-task-slice";
-import type {
- RemoteSyncConfigurationSettings,
- SettingDefinition,
-} from "metabase-types/api";
+import { Box, Button, Flex, Icon, Stack, Text } from "metabase/ui";
+import { useGetRemoteSyncChangesQuery } from "metabase-enterprise/api";
import {
- trackBranchSwitched,
- trackRemoteSyncDeactivated,
- trackRemoteSyncSettingsChanged,
-} from "../../analytics";
-import {
- AUTO_IMPORT_KEY,
- BRANCH_KEY,
- COLLECTIONS_KEY,
REMOTE_SYNC_KEY,
REMOTE_SYNC_SCHEMA,
- SYNC_LIBRARY_PENDING_KEY,
- TOKEN_KEY,
- TRANSFORMS_KEY,
TYPE_KEY,
URL_KEY,
} from "../../constants";
-import { SharedTenantCollectionsList } from "../SharedTenantCollectionsList";
-import { SyncConflictModal } from "../SyncConflictModal";
+import { useDisableRemoteSync } from "../../hooks/use-disable-remote-sync";
+import { useRemoteSyncInitialValues } from "../../hooks/use-remote-sync-initial-values";
+import { useRemoteSyncSubmit } from "../../hooks/use-remote-sync-submit";
+import type { RemoteSyncSettingsVariant } from "../../types";
import { TopLevelCollectionsList } from "../TopLevelCollectionsList";
-import { BranchSwitcher } from "./BranchSwitcher";
-import { DevInstanceUpsell } from "./DevInstanceUpsell";
-import { PullChangesButton } from "./PullChangesButton";
-import { TestConnectionButton } from "./TestConnectionButton";
+import { BranchSwitcherSection } from "./BranchSwitcherSection";
+import { CollectionsToSyncSection } from "./CollectionsToSyncSection";
+import { GitSettingsSection } from "./GitSettingsSection";
+import { ReadOnlyBranchSection } from "./ReadOnlyBranchSection";
+import { RemoteSyncConflictModal } from "./RemoteSyncConflictModal";
+import {
+ RemoteSyncSettingsSection,
+ RemoteSyncSettingsVariantProvider,
+} from "./RemoteSyncSettingsSection";
+import { SyncModeSection } from "./SyncModeSection";
export type RemoteSyncSettingsFormProps = {
onCancel?: VoidFunction;
onSaveSuccess?: VoidFunction;
- variant?: "admin" | "settings-modal";
+ variant?: RemoteSyncSettingsVariant;
};
-type RemoteSyncSettingsFormState = RemoteSyncConfigurationSettings & {
- [SYNC_LIBRARY_PENDING_KEY]?: boolean;
-};
-
-export const RemoteSyncSettingsForm = (props: RemoteSyncSettingsFormProps) => {
- const { onCancel, onSaveSuccess, variant = "admin" } = props;
+export const RemoteSyncSettingsForm = ({
+ onCancel,
+ onSaveSuccess,
+ variant = "admin",
+}: RemoteSyncSettingsFormProps) => {
const { data: settingValues } = useGetSettingsQuery();
const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
- const [
- updateRemoteSyncSettings,
- { isLoading: isUpdatingRemoteSyncSettings },
- ] = useUpdateRemoteSyncSettingsMutation();
- const [createLibrary, { isLoading: isCreatingLibrary }] =
- useCreateLibraryMutation();
+ const isRemoteSyncEnabled = !!useSetting(REMOTE_SYNC_KEY);
const { data: dirtyData } = useGetRemoteSyncChangesQuery(undefined, {
- refetchOnFocus: true,
refetchOnMountOrArgChange: true,
});
- const pendingConfirmationSettingsRef =
- useRef<RemoteSyncConfigurationSettings | null>(null);
-
- const isRemoteSyncEnabled = !!useSetting(REMOTE_SYNC_KEY);
- const useTenants = useSetting("use-tenants");
- const isDevInstance = useSetting("development-mode?");
- const applicationName = useSelector(getApplicationName);
-
- // Fetch top-level collections to build initial sync state
- const { data: topLevelCollectionsData } = useListCollectionItemsQuery(
- { id: "root", models: ["collection"] },
- { skip: !isRemoteSyncEnabled },
- );
-
- const isModalVariant = variant === "settings-modal";
-
- // Fetch library collection to build initial sync state
- // For modal variant, always fetch to enable default-checked toggles
- const { data: libraryCollectionData } = useGetLibraryCollectionQuery(
- undefined,
- { skip: !isRemoteSyncEnabled && !isModalVariant },
- );
- // Library collection endpoint returns { data: null } when not found
- const libraryCollection =
- libraryCollectionData && "name" in libraryCollectionData
- ? libraryCollectionData
- : undefined;
- const dispatch = useDispatch();
- const conflictVariant = useSelector(getSyncConflictVariant);
- const { currentBranch } = useGitSyncVisible();
-
- // Fetch tenant collections to build initial sync state
- const { data: tenantCollectionsData } = useListCollectionItemsQuery(
- {
- id: "root",
- namespace: "shared-tenant-collection",
- },
- { skip: !isRemoteSyncEnabled || !useTenants },
- );
-
- const {
- show: showChangeBranchConfirmation,
- modalContent: changeBranchConfirmationModal,
- } = useConfirmation();
- const [sendToast] = useToast();
-
- const {
- show: showDisableConfirmation,
- modalContent: disableConfirmationModal,
- } = useConfirmation();
-
- const initialValues = useMemo(() => {
- const values = REMOTE_SYNC_SCHEMA.cast(settingValues, {
- stripUnknown: true,
- });
- const tokenValue =
- settingDetails?.[TOKEN_KEY]?.value ?? settingValues?.[TOKEN_KEY];
-
- // Build initial collection sync map from server data
- const collectionSyncMap: Record<number, boolean> = {};
-
- // For modal variant during first-time setup, default library to checked
- const shouldDefaultToChecked = isModalVariant && !isRemoteSyncEnabled;
-
- // Add library collection
- if (libraryCollection) {
- collectionSyncMap[libraryCollection.id] = shouldDefaultToChecked
- ? true
- : (libraryCollection.is_remote_synced ?? false);
- }
-
- // Add top-level collections (excluding personal)
- topLevelCollectionsData?.data
- ?.filter((c) => !c.personal_owner_id)
- .forEach((collection) => {
- collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;
- });
-
- // Add tenant collections
- tenantCollectionsData?.data?.forEach((collection) => {
- collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;
- });
-
- return {
- ...values,
- [TOKEN_KEY]: tokenValue,
- [COLLECTIONS_KEY]: collectionSyncMap,
- // For modal variant during first-time setup, default transforms to checked (if enabled)
- [TRANSFORMS_KEY]:
- shouldDefaultToChecked && PLUGIN_TRANSFORMS.isEnabled
- ? true
- : values[TRANSFORMS_KEY],
- // For modal variant when library doesn't exist, default to wanting to create and sync it
- [SYNC_LIBRARY_PENDING_KEY]: shouldDefaultToChecked && !libraryCollection,
- };
- }, [
- settingValues,
- settingDetails,
- libraryCollection,
- topLevelCollectionsData,
- tenantCollectionsData,
- isModalVariant,
- isRemoteSyncEnabled,
- ]);
-
- const handleSubmit = useCallback(
- async (values: RemoteSyncSettingsFormState) => {
- const didBranchChange =
- values[BRANCH_KEY] !== settingValues?.[BRANCH_KEY];
-
- const collectionsMap: Record<number, boolean> = {
- ...values[COLLECTIONS_KEY],
- };
-
- // If user wants to sync library but it doesn't exist yet, create it first
- const wantsSyncLibrary = values[SYNC_LIBRARY_PENDING_KEY];
- if (isModalVariant && !libraryCollection && wantsSyncLibrary) {
- try {
- const newLibrary = await createLibrary().unwrap();
- // Cast to number since the newly created library will have a numeric ID
- collectionsMap[newLibrary.id as number] = true;
- } catch (error) {
- sendToast({
- message: t`Failed to create Library`,
- icon: "warning",
- });
- throw error;
- }
- }
-
- // Only include collections whose sync state actually changed
- const initialCollections = initialValues[COLLECTIONS_KEY] ?? {};
- const changedCollections: Record<number, boolean> = {};
- for (const [idStr, desired] of Object.entries(collectionsMap)) {
- const id = Number(idStr);
- if (initialCollections[id] !== desired) {
- changedCollections[id] = desired;
- }
- }
- const hasCollectionChanges = Object.keys(changedCollections).length > 0;
-
- // Don't send collections when in read-only mode or when nothing changed
- // Also filter out the sync-library-pending key as it's not a real setting
- const isReadOnly = values[TYPE_KEY] === "read-only";
- const settingsToSave: RemoteSyncConfigurationSettings = {
- [REMOTE_SYNC_KEY]: values[REMOTE_SYNC_KEY],
- [URL_KEY]: values[URL_KEY],
- [TOKEN_KEY]: values[TOKEN_KEY],
- [TYPE_KEY]: values[TYPE_KEY],
- [BRANCH_KEY]: values[BRANCH_KEY],
- [AUTO_IMPORT_KEY]: values[AUTO_IMPORT_KEY],
- [TRANSFORMS_KEY]: values[TRANSFORMS_KEY],
- ...(isReadOnly || !hasCollectionChanges
- ? {}
- : {
- [COLLECTIONS_KEY]: changedCollections,
- }),
- };
-
- const saveSettings = async (
- settings: RemoteSyncConfigurationSettings,
- ) => {
- try {
- await updateRemoteSyncSettings(settings).unwrap();
-
- trackRemoteSyncSettingsChanged({
- triggeredFrom: isModalVariant ? "data-studio" : "admin-settings",
- });
-
- if (
- didBranchChange &&
- settingValues?.[BRANCH_KEY] &&
- values[BRANCH_KEY]
- ) {
- trackBranchSwitched({
- triggeredFrom: "admin-settings",
- });
- }
-
- sendToast({ message: t`Settings saved successfully`, icon: "check" });
- onSaveSuccess?.();
- } catch (error) {
- sendToast({
- message: getErrorMessage(error, t`Settings could not be saved`),
- icon: "warning",
- });
- throw error;
- }
- };
-
- if (didBranchChange) {
- pendingConfirmationSettingsRef.current = settingsToSave;
- showChangeBranchConfirmation({
- title: t`Switch branches?`,
- message: t`The synced collection will update to match the new branch. Questions that exist in the current branch but not the new one will be removed from any dashboards or content that reference them permanently, even if you switch back.`,
- confirmButtonText: t`Continue`,
- confirmButtonProps: {
- variant: "filled",
- color: "feedback-negative",
- },
- onConfirm: async () => {
- if (pendingConfirmationSettingsRef.current) {
- await saveSettings(pendingConfirmationSettingsRef.current);
- pendingConfirmationSettingsRef.current = null;
- }
- },
- onCancel: () => {
- pendingConfirmationSettingsRef.current = null;
- },
- });
- return;
- }
- await saveSettings(settingsToSave);
- },
- [
- settingValues,
+ const { initialValues, libraryCollection } =
+ useRemoteSyncInitialValues(variant);
+ const { handleSubmit, branchChangeModal, isUpdating, isCreatingLibrary } =
+ useRemoteSyncSubmit({
initialValues,
- updateRemoteSyncSettings,
- isModalVariant,
libraryCollection,
- createLibrary,
- sendToast,
onSaveSuccess,
- showChangeBranchConfirmation,
- ],
- );
-
- const handleDisable = useCallback(async () => {
- showDisableConfirmation({
- title: t`Disable Remote Sync?`,
- message: t`This will clear all remote sync settings. Any changes made to the Library collection after disabling can be overwritten if you enable sync again.`,
- confirmButtonText: t`Disable`,
- confirmButtonProps: {
- variant: "filled",
- color: "feedback-negative",
- },
- onConfirm: async () => {
- try {
- await updateRemoteSyncSettings({ [URL_KEY]: "" }).unwrap();
- trackRemoteSyncDeactivated();
- sendToast({ message: t`Remote Sync disabled`, icon: "check" });
- } catch (error) {
- console.error(error);
- sendToast({
- message: t`Failed to disable Remote Sync`,
- icon: "warning",
- });
- }
- },
+ variant,
});
- }, [updateRemoteSyncSettings, sendToast, showDisableConfirmation]);
+ const { handleDisable, disableModal, isDisabling } = useDisableRemoteSync();
- // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- This links only shows for admins.
- const { url: docsUrl } = useDocsUrl(
- "installation-and-operation/remote-sync",
- {
- anchor: "remote-sync",
- },
- );
-
- const hasUnsyncedChanges = !!dirtyData?.dirty?.length && isRemoteSyncEnabled;
+ const dirtyEntities = dirtyData?.dirty ?? [];
+ const isModalVariant = variant === "settings-modal";
+ const isSaving = isUpdating || isDisabling;
+ const canDisable =
+ isRemoteSyncEnabled && !settingDetails?.[REMOTE_SYNC_KEY]?.is_env_setting;
return (
- <>
+ <RemoteSyncSettingsVariantProvider value={variant}>
<FormProvider
initialValues={initialValues}
enableReinitialize
@@ -371,215 +82,34 @@ export const RemoteSyncSettingsForm = (props: RemoteSyncSettingsFormProps) => {
validationContext={settingValues}
onSubmit={handleSubmit}
>
- {({ dirty, values }) => (
- <Form disabled={!dirty}>
- <Stack gap="xl" maw="52rem">
- {!isModalVariant && !isRemoteSyncEnabled && (
- <Text c="text-secondary" size="sm">
- {jt`Need help setting this up? Check out our ${(
- <ExternalLink key="link" href={docsUrl}>
- {t`setup guide`}
- </ExternalLink>
- )}.`}
- </Text>
- )}
+ {({ dirty, values }) => {
+ const isReadOnly = values?.[TYPE_KEY] === "read-only";
+ const isReadWrite = values?.[TYPE_KEY] === "read-write";
- {/* Section 1: Git settings */}
- <RemoteSyncSettingsSection
- title={t`Git settings`}
- variant={variant}
- >
- <FormTextInput
- name={URL_KEY}
- label={t`Repository URL`}
- placeholder="https://git-host.example.com/yourcompany/repo.git"
- labelProps={{ mb: "0.75rem" }}
- {...getEnvSettingProps(settingDetails?.[URL_KEY])}
- />
- <FormTextInput
- name={TOKEN_KEY}
- label={t`Access Token`}
- description={
- <Text c="text-disabled" size="sm" lh="md" component="span">
- {t`Personal access token with write permissions`}
- </Text>
- }
- type="password"
- {...getEnvSettingProps(settingDetails?.[TOKEN_KEY], {
- inputWrapperOrder: ["label", "description", "erorr"],
- })}
- />
- <Box>
- <TestConnectionButton values={values} />
- </Box>
- </RemoteSyncSettingsSection>
+ return (
+ <Form disabled={!dirty}>
+ <Stack gap="xl" maw="52rem">
+ {!isModalVariant && !isRemoteSyncEnabled && <SetupGuideLink />}
- {/* Section 2: Sync mode for this instance */}
- <RemoteSyncSettingsSection
- title={t`Sync mode for this instance`}
- description={
- settingDetails?.[TYPE_KEY]?.is_env_setting
- ? t`Using ${settingDetails[TYPE_KEY].env_name}`
- : undefined
- }
- variant={variant}
- >
- <FormRadioGroup name={TYPE_KEY}>
- <Stack>
- <Tooltip
- disabled={!hasUnsyncedChanges}
- label={t`You can't switch to Read-only as you have unpublished changes.`}
- position="bottom-start"
- >
- <Box>
- <Radio
- description={
- <Text
- c="text-secondary"
- lh="1.25rem"
- component="span"
- >
- {t`Usually you should use this for your production ${applicationName} instance. All synced collections are read-only, and will automatically sync with the specified branch (we'd recommend syncing with main).`}
- </Text>
- }
- disabled={
- hasUnsyncedChanges ||
- !!settingDetails?.[TYPE_KEY]?.is_env_setting
- }
- label={
- <Text fw={700} lh="1.25rem" mb="xs">
- {t`Read-only`}
- </Text>
- }
- value="read-only"
- />
- </Box>
- </Tooltip>
- <Radio
- value="read-write"
- disabled={!!settingDetails?.[TYPE_KEY]?.is_env_setting}
- label={
- <Text fw={700} lh="1.25rem" mb="xs">
- {t`Read-write`}
- </Text>
- }
- description={
- <Text c="text-secondary" lh="1.25rem" component="span">
- {t`This mode is generally for development or local instances of ${applicationName}. Changes you make to content in synced collections can be pushed and pulled from any git branch.`}
- </Text>
- }
- />
- </Stack>
- </FormRadioGroup>
- {!isDevInstance && (
- <DevInstanceUpsell
- campaign="remote-sync-dev-instance"
- dismissible
- />
- )}
- </RemoteSyncSettingsSection>
+ <GitSettingsSection />
+ <SyncModeSection dirty={dirtyEntities} />
- {/* Branch switching (read-write): a rare, destructive operation kept out of the everyday sync
- controls and behind guard rails. Read-only mode changes the branch via the Sync branch
- field below, which triggers a reconciling import. */}
- {isRemoteSyncEnabled &&
- values?.[TYPE_KEY] === "read-write" &&
- !isModalVariant && (
- <RemoteSyncSettingsSection
- title={t`Sync branch`}
- description={t`Choose which branch to sync with git.`}
- variant={variant}
- >
- <BranchSwitcher
- currentBranch={currentBranch}
- dirty={dirtyData?.dirty ?? []}
- disabled={settingDetails?.[BRANCH_KEY]?.is_env_setting}
- envVarName={
- settingDetails?.[BRANCH_KEY]?.is_env_setting
- ? settingDetails?.[BRANCH_KEY]?.env_name
- : undefined
- }
- />
- </RemoteSyncSettingsSection>
+ {isRemoteSyncEnabled && isReadWrite && !isModalVariant && (
+ <BranchSwitcherSection dirty={dirtyEntities} />
)}
-
- {/* Section 3: Branch to sync with (read-only only) */}
- {values?.[TYPE_KEY] === "read-only" && (
- <RemoteSyncSettingsSection
- title={t`Branch to sync with`}
- variant={variant}
- >
- <Stack gap="md">
- <Box style={{ flex: 1 }}>
- <FormTextInput
- name={BRANCH_KEY}
- placeholder="main"
- label={t`Sync branch`}
- labelProps={{ mb: "0.75rem" }}
- {...getEnvSettingProps(settingDetails?.[BRANCH_KEY])}
- />
- </Box>
- <FormSwitch
- label={t`Auto-sync with git`}
- description={t`Periodically import changes from the sync branch. When auto-sync is off, you'll need to pull changes from the sync branch manually.`}
- mb="0.6125rem"
- name={AUTO_IMPORT_KEY}
- size="sm"
- {...getEnvSettingProps(
- settingDetails?.[AUTO_IMPORT_KEY],
- { disabled: true },
- )}
- />
- </Stack>
- {isRemoteSyncEnabled && (
- <Box>
- <PullChangesButton
- branch={values?.[BRANCH_KEY] || "main"}
- dirty={dirty}
- forcePull
- />
- </Box>
- )}
- </RemoteSyncSettingsSection>
- )}
-
- {/* Section 4: Collections to sync */}
- {(isRemoteSyncEnabled || values?.[TYPE_KEY] === "read-write") &&
- !isModalVariant && (
- <RemoteSyncSettingsSection
- description={t`Choose which collections to sync with git.`}
- title={t`Collections to sync`}
- variant={variant}
- >
- <Stack gap="lg">
- <TopLevelCollectionsList />
- {useTenants && (
- <>
- <Text fw={700} size="md" lh="1rem">
- {t`Shared collections`}
- </Text>
- <SharedTenantCollectionsList />
- </>
- )}
- </Stack>
+ {isReadOnly && <ReadOnlyBranchSection />}
+ {(isRemoteSyncEnabled || isReadWrite) && !isModalVariant && (
+ <CollectionsToSyncSection />
+ )}
+ {isModalVariant && isReadWrite && (
+ <RemoteSyncSettingsSection title={t`Content to sync`}>
+ <TopLevelCollectionsList skipCollections />
</RemoteSyncSettingsSection>
)}
- {/* Content to sync section for modal variant */}
- {isModalVariant && values?.[TYPE_KEY] === "read-write" && (
- <RemoteSyncSettingsSection
- title={t`Content to sync`}
- variant={variant}
- >
- <TopLevelCollectionsList skipCollections />
- </RemoteSyncSettingsSection>
- )}
-
- {/* Footer Actions - Outside Sections */}
- <Flex justify="space-between" align="center">
- <Box>
- {isRemoteSyncEnabled &&
- !settingDetails?.[REMOTE_SYNC_KEY]?.is_env_setting && (
+ <Flex justify="space-between" align="center">
+ <Box>
+ {canDisable && (
<Button
c="feedback-negative"
variant="subtle"
@@ -591,83 +121,65 @@ export const RemoteSyncSettingsForm = (props: RemoteSyncSettingsFormProps) => {
{t`Disable remote sync`}
</Button>
)}
- </Box>
+ </Box>
- <Flex align="center" gap="md">
- <FormErrorMessage />
- {onCancel && (
- <Button
- variant="default"
- onClick={onCancel}
- disabled={isUpdatingRemoteSyncSettings}
- >
- {t`Cancel`}
- </Button>
- )}
- <FormSubmitButton
- data-testid="remote-sync-submit-button"
- size="md"
- label={
- isRemoteSyncEnabled
- ? t`Save changes`
- : t`Set up remote sync`
- }
- variant="filled"
- disabled={isRemoteSyncEnabled ? !dirty : !values?.[URL_KEY]}
- loading={isUpdatingRemoteSyncSettings || isCreatingLibrary}
- />
+ <Flex align="center" gap="md">
+ <FormErrorMessage />
+ {onCancel && (
+ <Button
+ variant="default"
+ onClick={onCancel}
+ disabled={isSaving}
+ >
+ {t`Cancel`}
+ </Button>
+ )}
+ <FormSubmitButton
+ data-testid="remote-sync-submit-button"
+ size="md"
+ label={
+ isRemoteSyncEnabled
+ ? t`Save changes`
+ : t`Set up remote sync`
+ }
+ variant="filled"
+ disabled={
+ isRemoteSyncEnabled ? !dirty : !values?.[URL_KEY]
+ }
+ loading={isSaving || isCreatingLibrary}
+ />
+ </Flex>
</Flex>
- </Flex>
- </Stack>
- </Form>
- )}
+ </Stack>
+ </Form>
+ );
+ }}
</FormProvider>
- {changeBranchConfirmationModal}
- {disableConfirmationModal}
+ {branchChangeModal}
+ {disableModal}
- {!!conflictVariant && !!currentBranch && (
- <SyncConflictModal
- currentBranch={currentBranch}
- onClose={() => {
- dispatch(syncConflictVariantUpdated(null));
- }}
- variant={conflictVariant}
- />
- )}
- </>
+ <RemoteSyncConflictModal />
+ </RemoteSyncSettingsVariantProvider>
);
};
-const RemoteSyncSettingsSection = ({
- children,
- title,
- variant,
- ...props
-}: ComponentProps<typeof SettingsSection> & {
- title: string;
- variant: RemoteSyncSettingsFormProps["variant"];
-}) => {
- return (
- <SettingsSection
- {...props}
- title={title}
- titleProps={{
- order: variant === "settings-modal" ? 3 : 2,
- }}
- >
- {children}
- </SettingsSection>
+const SetupGuideLink = () => {
+ // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- This links only shows for admins.
+ const { url: docsUrl } = useDocsUrl(
+ "installation-and-operation/remote-sync",
+ {
+ anchor: "remote-sync",
+ },
);
-};
-const getEnvSettingProps = <T,>(setting?: SettingDefinition, extras?: T) => {
- if (setting?.is_env_setting) {
- return {
- description: t`Using ${setting.env_name}`,
- readOnly: true,
- ...extras,
- };
- }
- return {};
+ return (
+ <Text c="text-secondary" size="sm">
+ {jt`Need help setting this up? Check out our ${(
+ <ExternalLink key="link" href={docsUrl}>
+ {t`setup guide`}
+ </ExternalLink>
+ )}.`}
+ </Text>
+ );
};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsSection.tsx
new file mode 100644
index 00000000000..bdd45a47c44
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsSection.tsx
@@ -0,0 +1,34 @@
+import { type ComponentProps, createContext, useContext } from "react";
+
+import { SettingsSection } from "metabase/admin/components/SettingsSection";
+
+import type { RemoteSyncSettingsVariant } from "../../types";
+
+const RemoteSyncSettingsVariantContext =
+ createContext<RemoteSyncSettingsVariant>("admin");
+
+export const RemoteSyncSettingsVariantProvider =
+ RemoteSyncSettingsVariantContext.Provider;
+
+export const useRemoteSyncSettingsVariant = () =>
+ useContext(RemoteSyncSettingsVariantContext);
+
+export const RemoteSyncSettingsSection = ({
+ children,
+ title,
+ ...props
+}: ComponentProps<typeof SettingsSection> & { title: string }) => {
+ const variant = useRemoteSyncSettingsVariant();
+
+ return (
+ <SettingsSection
+ {...props}
+ title={title}
+ titleProps={{
+ order: variant === "settings-modal" ? 3 : 2,
+ }}
+ >
+ {children}
+ </SettingsSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/SyncModeSection.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/SyncModeSection.tsx
new file mode 100644
index 00000000000..ebbca829848
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/SyncModeSection.tsx
@@ -0,0 +1,79 @@
+import { t } from "ttag";
+
+import { FormRadioGroup } from "metabase/forms";
+import { useSelector } from "metabase/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
+import { useGetAdminSettingsDetailsQuery, useSetting } from "metabase/settings";
+import { Box, Radio, Stack, Text, Tooltip } from "metabase/ui";
+import type { RemoteSyncEntity } from "metabase-types/api";
+
+import { REMOTE_SYNC_KEY, TYPE_KEY } from "../../constants";
+
+import { DevInstanceUpsell } from "./DevInstanceUpsell";
+import { RemoteSyncSettingsSection } from "./RemoteSyncSettingsSection";
+
+type SyncModeSectionProps = {
+ dirty: RemoteSyncEntity[];
+};
+
+export const SyncModeSection = ({ dirty }: SyncModeSectionProps) => {
+ const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
+ const applicationName = useSelector(getApplicationName);
+ const isRemoteSyncEnabled = !!useSetting(REMOTE_SYNC_KEY);
+ const isDevInstance = useSetting("development-mode?");
+
+ const typeDetails = settingDetails?.[TYPE_KEY];
+ const isSetByEnv = !!typeDetails?.is_env_setting;
+ const hasUnsyncedChanges = dirty.length > 0 && isRemoteSyncEnabled;
+
+ return (
+ <RemoteSyncSettingsSection
+ title={t`Sync mode for this instance`}
+ description={isSetByEnv ? t`Using ${typeDetails.env_name}` : undefined}
+ >
+ <FormRadioGroup name={TYPE_KEY}>
+ <Stack>
+ <Tooltip
+ disabled={!hasUnsyncedChanges}
+ label={t`You can't switch to Read-only as you have unpublished changes.`}
+ position="bottom-start"
+ >
+ <Box>
+ <Radio
+ description={
+ <Text c="text-secondary" lh="1.25rem" component="span">
+ {t`Usually you should use this for your production ${applicationName} instance. All synced collections are read-only, and will automatically sync with the specified branch (we'd recommend syncing with main).`}
+ </Text>
+ }
+ disabled={hasUnsyncedChanges || isSetByEnv}
+ label={
+ <Text fw={700} lh="1.25rem" mb="xs">
+ {t`Read-only`}
+ </Text>
+ }
+ value="read-only"
+ />
+ </Box>
+ </Tooltip>
+ <Radio
+ value="read-write"
+ disabled={isSetByEnv}
+ label={
+ <Text fw={700} lh="1.25rem" mb="xs">
+ {t`Read-write`}
+ </Text>
+ }
+ description={
+ <Text c="text-secondary" lh="1.25rem" component="span">
+ {t`This mode is generally for development or local instances of ${applicationName}. Changes you make to content in synced collections can be pushed and pulled from any git branch.`}
+ </Text>
+ }
+ />
+ </Stack>
+ </FormRadioGroup>
+ {!isDevInstance && (
+ <DevInstanceUpsell campaign="remote-sync-dev-instance" dismissible />
+ )}
+ </RemoteSyncSettingsSection>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-disable-remote-sync.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-disable-remote-sync.ts
new file mode 100644
index 00000000000..bf7aa0adf47
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-disable-remote-sync.ts
@@ -0,0 +1,44 @@
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import { useToast } from "metabase/common/hooks";
+import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { useUpdateRemoteSyncSettingsMutation } from "metabase-enterprise/api/remote-sync";
+
+import { trackRemoteSyncDeactivated } from "../analytics";
+import { URL_KEY } from "../constants";
+
+export const useDisableRemoteSync = () => {
+ const [updateRemoteSyncSettings, { isLoading: isDisabling }] =
+ useUpdateRemoteSyncSettingsMutation();
+ const [sendToast] = useToast();
+ const { show: showDisableConfirmation, modalContent: disableModal } =
+ useConfirmation();
+
+ const handleDisable = useCallback(async () => {
+ showDisableConfirmation({
+ title: t`Disable Remote Sync?`,
+ message: t`This will clear all remote sync settings. Any changes made to the Library collection after disabling can be overwritten if you enable sync again.`,
+ confirmButtonText: t`Disable`,
+ confirmButtonProps: {
+ variant: "filled",
+ color: "feedback-negative",
+ },
+ onConfirm: async () => {
+ try {
+ await updateRemoteSyncSettings({ [URL_KEY]: "" }).unwrap();
+ trackRemoteSyncDeactivated();
+ sendToast({ message: t`Remote Sync disabled`, icon: "check" });
+ } catch (error) {
+ console.error(error);
+ sendToast({
+ message: t`Failed to disable Remote Sync`,
+ icon: "warning",
+ });
+ }
+ },
+ });
+ }, [updateRemoteSyncSettings, sendToast, showDisableConfirmation]);
+
+ return { handleDisable, disableModal, isDisabling };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-initial-values.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-initial-values.ts
new file mode 100644
index 00000000000..74adbd6fd83
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-initial-values.ts
@@ -0,0 +1,104 @@
+import { useMemo } from "react";
+
+import { useListCollectionItemsQuery } from "metabase/api";
+import { PLUGIN_TRANSFORMS } from "metabase/plugins";
+import {
+ useGetAdminSettingsDetailsQuery,
+ useGetSettingsQuery,
+ useSetting,
+} from "metabase/settings";
+import { useGetLibraryCollectionQuery } from "metabase-enterprise/api";
+import type { LibraryCollection } from "metabase-types/api";
+
+import {
+ COLLECTIONS_KEY,
+ REMOTE_SYNC_KEY,
+ REMOTE_SYNC_SCHEMA,
+ SYNC_LIBRARY_PENDING_KEY,
+ TOKEN_KEY,
+ TRANSFORMS_KEY,
+} from "../constants";
+import type {
+ RemoteSyncSettingsFormState,
+ RemoteSyncSettingsVariant,
+} from "../types";
+
+export const useRemoteSyncInitialValues = (
+ variant: RemoteSyncSettingsVariant,
+) => {
+ const isModalVariant = variant === "settings-modal";
+ const { data: settingValues } = useGetSettingsQuery();
+ const { data: settingDetails } = useGetAdminSettingsDetailsQuery();
+ const isRemoteSyncEnabled = !!useSetting(REMOTE_SYNC_KEY);
+ const useTenants = useSetting("use-tenants");
+
+ const { data: topLevelCollectionsData } = useListCollectionItemsQuery(
+ { id: "root", models: ["collection"] },
+ { skip: !isRemoteSyncEnabled },
+ );
+
+ // The modal always fetches so its toggles can default to checked.
+ const { data: libraryCollectionData } = useGetLibraryCollectionQuery(
+ undefined,
+ { skip: !isRemoteSyncEnabled && !isModalVariant },
+ );
+
+ // Library collection endpoint returns { data: null } when not found
+ const libraryCollection: LibraryCollection | undefined =
+ libraryCollectionData && "name" in libraryCollectionData
+ ? libraryCollectionData
+ : undefined;
+
+ const { data: tenantCollectionsData } = useListCollectionItemsQuery(
+ { id: "root", namespace: "shared-tenant-collection" },
+ { skip: !isRemoteSyncEnabled || !useTenants },
+ );
+
+ const initialValues: RemoteSyncSettingsFormState = useMemo(() => {
+ const values = REMOTE_SYNC_SCHEMA.cast(settingValues, {
+ stripUnknown: true,
+ });
+ const tokenValue =
+ settingDetails?.[TOKEN_KEY]?.value ?? settingValues?.[TOKEN_KEY];
+
+ const collectionSyncMap: Record<number, boolean> = {};
+ const shouldDefaultToChecked = isModalVariant && !isRemoteSyncEnabled;
+
+ if (libraryCollection) {
+ collectionSyncMap[libraryCollection.id] = shouldDefaultToChecked
+ ? true
+ : (libraryCollection.is_remote_synced ?? false);
+ }
+
+ topLevelCollectionsData?.data
+ ?.filter((collection) => !collection.personal_owner_id)
+ .forEach((collection) => {
+ collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;
+ });
+
+ tenantCollectionsData?.data?.forEach((collection) => {
+ collectionSyncMap[collection.id] = collection.is_remote_synced ?? false;
+ });
+
+ return {
+ ...values,
+ [TOKEN_KEY]: tokenValue,
+ [COLLECTIONS_KEY]: collectionSyncMap,
+ [TRANSFORMS_KEY]:
+ shouldDefaultToChecked && PLUGIN_TRANSFORMS.isEnabled
+ ? true
+ : values[TRANSFORMS_KEY],
+ [SYNC_LIBRARY_PENDING_KEY]: shouldDefaultToChecked && !libraryCollection,
+ };
+ }, [
+ settingValues,
+ settingDetails,
+ libraryCollection,
+ topLevelCollectionsData,
+ tenantCollectionsData,
+ isModalVariant,
+ isRemoteSyncEnabled,
+ ]);
+
+ return { initialValues, libraryCollection };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts
new file mode 100644
index 00000000000..2b41d915ec5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts
@@ -0,0 +1,182 @@
+import { useCallback, useRef } from "react";
+import { t } from "ttag";
+
+import { getErrorMessage } from "metabase/api/utils";
+import { useToast } from "metabase/common/hooks";
+import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { useGetSettingsQuery } from "metabase/settings";
+import { useCreateLibraryMutation } from "metabase-enterprise/api";
+import { useUpdateRemoteSyncSettingsMutation } from "metabase-enterprise/api/remote-sync";
+import type {
+ LibraryCollection,
+ RemoteSyncConfigurationSettings,
+} from "metabase-types/api";
+
+import {
+ trackBranchSwitched,
+ trackRemoteSyncSettingsChanged,
+} from "../analytics";
+import {
+ AUTO_IMPORT_KEY,
+ BRANCH_KEY,
+ COLLECTIONS_KEY,
+ REMOTE_SYNC_KEY,
+ SYNC_LIBRARY_PENDING_KEY,
+ TOKEN_KEY,
+ TRANSFORMS_KEY,
+ TYPE_KEY,
+ URL_KEY,
+} from "../constants";
+import type {
+ RemoteSyncSettingsFormState,
+ RemoteSyncSettingsVariant,
+} from "../types";
+
+interface UseRemoteSyncSubmitProps {
+ initialValues: RemoteSyncSettingsFormState;
+ libraryCollection?: LibraryCollection;
+ onSaveSuccess?: VoidFunction;
+ variant: RemoteSyncSettingsVariant;
+}
+
+export const useRemoteSyncSubmit = ({
+ initialValues,
+ libraryCollection,
+ onSaveSuccess,
+ variant,
+}: UseRemoteSyncSubmitProps) => {
+ const isModalVariant = variant === "settings-modal";
+ const { data: settingValues } = useGetSettingsQuery();
+ const [updateRemoteSyncSettings, { isLoading: isUpdating }] =
+ useUpdateRemoteSyncSettingsMutation();
+ const [createLibrary, { isLoading: isCreatingLibrary }] =
+ useCreateLibraryMutation();
+ const [sendToast] = useToast();
+ const {
+ show: showBranchChangeConfirmation,
+ modalContent: branchChangeModal,
+ } = useConfirmation();
+ const pendingConfirmationSettingsRef =
+ useRef<RemoteSyncConfigurationSettings | null>(null);
+
+ const handleSubmit = useCallback(
+ async (values: RemoteSyncSettingsFormState) => {
+ const didBranchChange =
+ values[BRANCH_KEY] !== settingValues?.[BRANCH_KEY];
+
+ const collectionsMap: Record<number, boolean> = {
+ ...values[COLLECTIONS_KEY],
+ };
+
+ const wantsSyncLibrary = values[SYNC_LIBRARY_PENDING_KEY];
+ if (isModalVariant && !libraryCollection && wantsSyncLibrary) {
+ try {
+ const newLibrary = await createLibrary().unwrap();
+ // A freshly created library always has a numeric id; only seeded collections use string ids.
+ collectionsMap[newLibrary.id as number] = true;
+ } catch (error) {
+ sendToast({
+ message: t`Failed to create Library`,
+ icon: "warning",
+ });
+ throw error;
+ }
+ }
+
+ const initialCollections = initialValues[COLLECTIONS_KEY] ?? {};
+ const changedCollections: Record<number, boolean> = {};
+ for (const [idStr, desired] of Object.entries(collectionsMap)) {
+ const id = Number(idStr);
+ if (initialCollections[id] !== desired) {
+ changedCollections[id] = desired;
+ }
+ }
+ const hasCollectionChanges = Object.keys(changedCollections).length > 0;
+
+ // Listed key by key so the sync-library-pending form field, which is not a setting, stays out.
+ const isReadOnly = values[TYPE_KEY] === "read-only";
+ const settingsToSave: RemoteSyncConfigurationSettings = {
+ [REMOTE_SYNC_KEY]: values[REMOTE_SYNC_KEY],
+ [URL_KEY]: values[URL_KEY],
+ [TOKEN_KEY]: values[TOKEN_KEY],
+ [TYPE_KEY]: values[TYPE_KEY],
+ [BRANCH_KEY]: values[BRANCH_KEY],
+ [AUTO_IMPORT_KEY]: values[AUTO_IMPORT_KEY],
+ [TRANSFORMS_KEY]: values[TRANSFORMS_KEY],
+ ...(isReadOnly || !hasCollectionChanges
+ ? {}
+ : {
+ [COLLECTIONS_KEY]: changedCollections,
+ }),
+ };
+
+ const saveSettings = async (
+ settings: RemoteSyncConfigurationSettings,
+ ) => {
+ try {
+ await updateRemoteSyncSettings(settings).unwrap();
+
+ trackRemoteSyncSettingsChanged({
+ triggeredFrom: isModalVariant ? "data-studio" : "admin-settings",
+ });
+
+ if (
+ didBranchChange &&
+ settingValues?.[BRANCH_KEY] &&
+ values[BRANCH_KEY]
+ ) {
+ trackBranchSwitched({
+ triggeredFrom: "admin-settings",
+ });
+ }
+
+ sendToast({ message: t`Settings saved successfully`, icon: "check" });
+ onSaveSuccess?.();
+ } catch (error) {
+ sendToast({
+ message: getErrorMessage(error, t`Settings could not be saved`),
+ icon: "warning",
+ });
+ throw error;
+ }
+ };
+
+ if (didBranchChange) {
+ pendingConfirmationSettingsRef.current = settingsToSave;
+ showBranchChangeConfirmation({
+ title: t`Switch branches?`,
+ message: t`The synced collection will update to match the new branch. Questions that exist in the current branch but not the new one will be removed from any dashboards or content that reference them permanently, even if you switch back.`,
+ confirmButtonText: t`Continue`,
+ confirmButtonProps: {
+ variant: "filled",
+ color: "feedback-negative",
+ },
+ onConfirm: async () => {
+ if (pendingConfirmationSettingsRef.current) {
+ await saveSettings(pendingConfirmationSettingsRef.current);
+ pendingConfirmationSettingsRef.current = null;
+ }
+ },
+ onCancel: () => {
+ pendingConfirmationSettingsRef.current = null;
+ },
+ });
+ return;
+ }
+ await saveSettings(settingsToSave);
+ },
+ [
+ settingValues,
+ initialValues,
+ updateRemoteSyncSettings,
+ isModalVariant,
+ libraryCollection,
+ createLibrary,
+ sendToast,
+ onSaveSuccess,
+ showBranchChangeConfirmation,
+ ],
+ );
+
+ return { handleSubmit, branchChangeModal, isUpdating, isCreatingLibrary };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/types.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/types.ts
index 985ba11eeae..4201275dcf1 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/types.ts
@@ -1,5 +1,7 @@
import type { State } from "metabase/redux/store";
+import type { RemoteSyncConfigurationSettings } from "metabase-types/api";
+import type { SYNC_LIBRARY_PENDING_KEY } from "./constants";
import type { SyncTaskState } from "./sync-task-slice";
export interface RemoteSyncStoreState extends State {
@@ -7,3 +9,9 @@ export interface RemoteSyncStoreState extends State {
remoteSyncPlugin?: SyncTaskState;
};
}
+
+export type RemoteSyncSettingsVariant = "admin" | "settings-modal";
+
+export type RemoteSyncSettingsFormState = RemoteSyncConfigurationSettings & {
+ [Key in typeof SYNC_LIBRARY_PENDING_KEY]?: boolean;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts
index a93adf2e765..8dd987bc35f 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts
@@ -5,6 +5,7 @@ import type {
Collection,
IconName,
RemoteSyncEntityStatus,
+ SettingDefinition,
} from "metabase-types/api";
import type { CollectionPathSegment } from "./displayGroups";
@@ -39,6 +40,21 @@ type ParsedError = {
currentBranch: string | null;
};
+// TODO: Should merge with getExtraFormFieldProps from admin/settings/utils.ts
+export const getEnvSettingProps = <T>(
+ setting?: SettingDefinition,
+ extras?: T,
+) => {
+ if (setting?.is_env_setting) {
+ return {
+ description: t`Using ${setting.env_name}`,
+ readOnly: true,
+ ...extras,
+ };
+ }
+ return {};
+};
+
export const getSyncStatusIcon = (status: RemoteSyncEntityStatus): IconName => {
switch (status) {
case "create":