Skip to content

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

Improve database form dirty state awareness (#66684)

Andersonf504e2871475
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx b/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx
index 48d25547271..fc93216fecb 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseEditConnectionForm.tsx
@@ -98,7 +98,7 @@ export const DatabaseEditConnectionForm = withRouter(
config={{ isAdvanced: true, ...config }}
onCancel={onCancel}
onSubmit={handleSubmit}
- setIsDirty={setIsDirty}
+ onDirtyStateChange={setIsDirty}
location={formLocation}
onEngineChange={onEngineChange}
/>
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/DatabaseForm.tsx b/frontend/src/metabase/databases/components/DatabaseForm/DatabaseForm.tsx
index 635acdb4769..84062a1ff44 100644
--- a/frontend/src/metabase/databases/components/DatabaseForm/DatabaseForm.tsx
+++ b/frontend/src/metabase/databases/components/DatabaseForm/DatabaseForm.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import { Form, FormProvider } from "metabase/forms";
import { useSelector } from "metabase/lib/redux";
@@ -10,6 +10,7 @@ import { getSubmitValues, getValidationSchema } from "../../utils/schema";
import { DatabaseFormBody } from "./DatabaseFormBody";
import { DatabaseFormFooter } from "./DatabaseFormFooter";
+import { FormDirtyStateProvider } from "./context";
import { getEngine, getEngineKey } from "./utils";
export type EngineFieldState = "default" | "hidden" | "disabled";
@@ -37,7 +38,7 @@ interface DatabaseFormProps {
onSubmit?: (values: DatabaseData) => void;
onEngineChange?: (engineKey: string | undefined) => void;
onCancel?: () => void;
- setIsDirty?: (isDirty: boolean) => void;
+ onDirtyStateChange?: (isDirty: boolean) => void;
config?: DatabaseFormConfig;
location: FormLocation;
/**
@@ -54,7 +55,7 @@ export const DatabaseForm = ({
onSubmit,
onCancel,
onEngineChange,
- setIsDirty,
+ onDirtyStateChange,
location,
showSampleDatabase = false,
ContinueWithoutDataSlot,
@@ -64,7 +65,9 @@ export const DatabaseForm = ({
const engineFieldState = config.engine?.fieldState;
const engines = useSelector(getEngines);
- const initialEngineKey = getEngineKey(engines, initialData, isAdvanced);
+ const initialEngineKey = useMemo(() => {
+ return getEngineKey(engines, initialData, isAdvanced);
+ }, [engines, initialData, isAdvanced]);
const [engineKey, setEngineKey] = useState(initialEngineKey);
const engine = getEngine(engines, engineKey);
@@ -79,6 +82,11 @@ export const DatabaseForm = ({
);
}, [initialData, engineKey, validationSchema]);
+ useEffect(() => {
+ // during page load, if initialData changes, initialEngineKey will also change
+ setEngineKey(initialEngineKey);
+ }, [initialEngineKey]);
+
const handleSubmit = useCallback(
(values: DatabaseData) => {
return onSubmit?.(getSubmitValues(engine, values, isAdvanced));
@@ -105,27 +113,28 @@ export const DatabaseForm = ({
data-testid="database-form"
pt={location === "full-page" ? undefined : "md"}
>
- <DatabaseFormBody
- engine={engine}
- // casting won't be needed after migrating all usages of engineKey
- engineKey={engineKey as EngineKey}
- engines={engines}
- engineFieldState={engineFieldState}
- autofocusFieldName={autofocusFieldName}
- isAdvanced={isAdvanced}
- onEngineChange={handleEngineChange}
- setIsDirty={setIsDirty}
- config={config}
- showSampleDatabase={showSampleDatabase}
- location={location}
- />
- <DatabaseFormFooter
- ContinueWithoutDataSlot={ContinueWithoutDataSlot}
- isAdvanced={isAdvanced}
- location={location}
- onCancel={onCancel}
- showSampleDatabase={showSampleDatabase}
- />
+ <FormDirtyStateProvider onDirtyStateChange={onDirtyStateChange}>
+ <DatabaseFormBody
+ engine={engine}
+ // casting won't be needed after migrating all usages of engineKey
+ engineKey={engineKey as EngineKey}
+ engines={engines}
+ engineFieldState={engineFieldState}
+ autofocusFieldName={autofocusFieldName}
+ isAdvanced={isAdvanced}
+ onEngineChange={handleEngineChange}
+ config={config}
+ showSampleDatabase={showSampleDatabase}
+ location={location}
+ />
+ <DatabaseFormFooter
+ ContinueWithoutDataSlot={ContinueWithoutDataSlot}
+ isAdvanced={isAdvanced}
+ location={location}
+ onCancel={onCancel}
+ showSampleDatabase={showSampleDatabase}
+ />
+ </FormDirtyStateProvider>
</Form>
</FormProvider>
);
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormBody.tsx b/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormBody.tsx
index f1a9791756a..64a2841e7f3 100644
--- a/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormBody.tsx
+++ b/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormBody.tsx
@@ -1,5 +1,5 @@
import { useFormikContext } from "formik";
-import { type JSX, useEffect, useMemo } from "react";
+import { type JSX, useMemo } from "react";
import { match } from "ts-pattern";
import type {
@@ -27,7 +27,6 @@ interface DatabaseFormBodyProps {
autofocusFieldName?: string;
isAdvanced: boolean;
onEngineChange: (engineKey: string | undefined) => void;
- setIsDirty?: (isDirty: boolean) => void;
config: DatabaseFormConfig;
showSampleDatabase?: boolean;
location: FormLocation;
@@ -41,18 +40,13 @@ export const DatabaseFormBody = ({
autofocusFieldName,
isAdvanced,
onEngineChange,
- setIsDirty,
config,
showSampleDatabase = false,
location,
}: DatabaseFormBodyProps): JSX.Element => {
- const { values, dirty, setValues } = useFormikContext<DatabaseData>();
+ const { values, setValues } = useFormikContext<DatabaseData>();
const hasConnectionError = useHasConnectionError();
- useEffect(() => {
- setIsDirty?.(dirty);
- }, [dirty, setIsDirty]);
-
const fields = useMemo(() => {
return engine ? getVisibleFields(engine, values, isAdvanced) : [];
}, [engine, values, isAdvanced]);
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormFooter.tsx b/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormFooter.tsx
index bcc8cf2fcdb..e59c1849a1d 100644
--- a/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormFooter.tsx
+++ b/frontend/src/metabase/databases/components/DatabaseForm/DatabaseFormFooter.tsx
@@ -14,7 +14,7 @@ import type { DatabaseData } from "metabase-types/api";
import { DatabaseFormError } from "../DatabaseFormError";
-import { useHasConnectionError } from "./utils";
+import { useHasConnectionError, useIsFormDirty } from "./utils";
interface DatabaseFormFooterProps {
isAdvanced: boolean;
@@ -31,9 +31,10 @@ export const DatabaseFormFooter = ({
ContinueWithoutDataSlot,
location,
}: DatabaseFormFooterProps) => {
- const { values, dirty } = useFormikContext<DatabaseData>();
+ const { values } = useFormikContext<DatabaseData>();
const isNew = values.id == null;
const hasConnectionError = useHasConnectionError();
+ const isDirty = useIsFormDirty();
// eslint-disable-next-line no-unconditional-metabase-links-render -- Metabase setup + admin pages only
const { url: docsUrl } = useDocsUrl("databases/connecting");
@@ -62,7 +63,7 @@ export const DatabaseFormFooter = ({
<Flex gap="sm">
<Button onClick={onCancel}>{t`Cancel`}</Button>
<FormSubmitButton
- disabled={!dirty}
+ disabled={!isDirty}
label={isNew ? t`Save` : t`Save changes`}
variant="filled"
/>
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/context/FormDirtyStateContext.tsx b/frontend/src/metabase/databases/components/DatabaseForm/context/FormDirtyStateContext.tsx
new file mode 100644
index 00000000000..ee7e73efb8c
--- /dev/null
+++ b/frontend/src/metabase/databases/components/DatabaseForm/context/FormDirtyStateContext.tsx
@@ -0,0 +1,45 @@
+import { useFormikContext } from "formik";
+import {
+ type PropsWithChildren,
+ createContext,
+ useEffect,
+ useState,
+} from "react";
+
+import type { DatabaseData } from "metabase-types/api";
+
+import { checkFormIsDirty } from "./utils";
+
+export const FormDirtyStateContext = createContext<boolean>(false);
+
+type ProviderProps = PropsWithChildren<{
+ onDirtyStateChange?: (isDirty: boolean) => void;
+}>;
+
+/**
+ * Custom definition for form dirty state.
+ * This is needed because Formik's `dirty` value is not accurate to track actual field updates on our database form (#65988).
+ *
+ * This should be wrapped in a FormProvider.
+ */
+export const FormDirtyStateProvider = ({
+ children,
+ onDirtyStateChange,
+}: ProviderProps) => {
+ const [isDirty, setIsDirty] = useState<boolean>(false);
+ const { initialValues, values } = useFormikContext<DatabaseData>();
+
+ useEffect(() => {
+ setIsDirty(checkFormIsDirty(initialValues, values));
+ }, [initialValues, values]);
+
+ useEffect(() => {
+ onDirtyStateChange?.(isDirty);
+ }, [isDirty, onDirtyStateChange]);
+
+ return (
+ <FormDirtyStateContext.Provider value={isDirty}>
+ {children}
+ </FormDirtyStateContext.Provider>
+ );
+};
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/context/index.ts b/frontend/src/metabase/databases/components/DatabaseForm/context/index.ts
new file mode 100644
index 00000000000..7c628e8b533
--- /dev/null
+++ b/frontend/src/metabase/databases/components/DatabaseForm/context/index.ts
@@ -0,0 +1,4 @@
+export {
+ FormDirtyStateProvider,
+ FormDirtyStateContext,
+} from "./FormDirtyStateContext";
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/context/utils.ts b/frontend/src/metabase/databases/components/DatabaseForm/context/utils.ts
new file mode 100644
index 00000000000..95f1e58673c
--- /dev/null
+++ b/frontend/src/metabase/databases/components/DatabaseForm/context/utils.ts
@@ -0,0 +1,24 @@
+import _ from "underscore";
+
+import type { DatabaseData } from "metabase-types/api";
+
+export const checkFormIsDirty = (
+ initialValues: DatabaseData,
+ currentValues: DatabaseData,
+) => {
+ const sanitizeValues = (values: DatabaseData) => {
+ return {
+ ...values,
+ // Ignore "advanced-options" when checking if the form is dirty. It is not an actual field.
+ details: _.omit(values.details, ["advanced-options"]),
+ // These boolean fields are nullable. When null, they are treated as false in the form.
+ refingerprint: values.refingerprint || false,
+ auto_run_queries: values.auto_run_queries || false,
+ };
+ };
+
+ return !_.isEqual(
+ sanitizeValues(initialValues),
+ sanitizeValues(currentValues),
+ );
+};
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/context/utils.unit.spec.ts b/frontend/src/metabase/databases/components/DatabaseForm/context/utils.unit.spec.ts
new file mode 100644
index 00000000000..22b69e858b0
--- /dev/null
+++ b/frontend/src/metabase/databases/components/DatabaseForm/context/utils.unit.spec.ts
@@ -0,0 +1,54 @@
+import { createMockDatabaseData } from "metabase-types/api/mocks";
+
+import { checkFormIsDirty } from "./utils";
+
+describe("checkFormIsDirty", () => {
+ it("should return false when values are equal", () => {
+ const initialValues = createMockDatabaseData();
+ const currentValues = createMockDatabaseData();
+
+ // Everything is the same
+ expect(checkFormIsDirty(initialValues, currentValues)).toBe(false);
+
+ // Name changed
+ expect(
+ checkFormIsDirty(initialValues, {
+ ...currentValues,
+ name: "another name",
+ }),
+ ).toBe(true);
+ });
+
+ it("should ignore advanced-options field when checking dirty state", () => {
+ const initialValues = createMockDatabaseData({
+ details: {
+ "advanced-options": false,
+ },
+ });
+ const currentValues = createMockDatabaseData({
+ details: {
+ "advanced-options": true,
+ },
+ });
+
+ expect(checkFormIsDirty(initialValues, currentValues)).toBe(false);
+ });
+
+ it("should treat null refingerprint as false", () => {
+ const initialValues = createMockDatabaseData({
+ refingerprint: null as any,
+ });
+ const currentValues = createMockDatabaseData({ refingerprint: false });
+
+ expect(checkFormIsDirty(initialValues, currentValues)).toBe(false);
+ });
+
+ it("should treat null auto_run_queries as false", () => {
+ const initialValues = createMockDatabaseData({
+ auto_run_queries: null as any,
+ });
+ const currentValues = createMockDatabaseData({ auto_run_queries: false });
+
+ expect(checkFormIsDirty(initialValues, currentValues)).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/tests/common.unit.spec.tsx b/frontend/src/metabase/databases/components/DatabaseForm/tests/common.unit.spec.tsx
index b7cf14e3a40..bee7d8d81a6 100644
--- a/frontend/src/metabase/databases/components/DatabaseForm/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/databases/components/DatabaseForm/tests/common.unit.spec.tsx
@@ -106,6 +106,45 @@ describe("DatabaseForm", () => {
expect(screen.getByPlaceholderText("Our H2")).toBeInTheDocument();
});
+
+ describe("updating existing database", () => {
+ it("should mark form as dirty only when actual fields are changed (#66684)", async () => {
+ setup({
+ initialValues: {
+ id: 1,
+ name: "My Original H2 Database name",
+ details: {
+ db: "file:/somewhere",
+ },
+ },
+ });
+ const getSaveButton = () =>
+ screen.getByRole("button", { name: "Save changes" });
+ const getNameInput = () => screen.getByLabelText("Display name");
+ const getRefingerprintToggle = () =>
+ screen.getByLabelText(/Periodically refingerprint tables/);
+
+ expect(getSaveButton()).toBeDisabled();
+ await userEvent.click(screen.getByText("Show advanced options"));
+ // Still disabled after opening up advanced options
+ await waitFor(() => expect(getSaveButton()).toBeDisabled());
+
+ // Button gets enabled when a field is changed, and disabled again when it is reset
+ await userEvent.clear(getNameInput());
+ await userEvent.type(getNameInput(), "My updated name");
+ await waitFor(() => expect(getSaveButton()).toBeEnabled());
+
+ await userEvent.clear(getNameInput());
+ await userEvent.type(getNameInput(), "My Original H2 Database name");
+ await waitFor(() => expect(getSaveButton()).toBeDisabled());
+
+ // Check also for a toggle field in advanced options
+ await userEvent.click(getRefingerprintToggle());
+ await waitFor(() => expect(getSaveButton()).toBeEnabled());
+ await userEvent.click(getRefingerprintToggle());
+ await waitFor(() => expect(getSaveButton()).toBeDisabled());
+ });
+ });
});
describe("DatabaseForm with provider name", () => {
diff --git a/frontend/src/metabase/databases/components/DatabaseForm/utils.ts b/frontend/src/metabase/databases/components/DatabaseForm/utils.ts
index 7e357e181a5..998a3451403 100644
--- a/frontend/src/metabase/databases/components/DatabaseForm/utils.ts
+++ b/frontend/src/metabase/databases/components/DatabaseForm/utils.ts
@@ -1,7 +1,11 @@
+import { useContext } from "react";
+
import { getDefaultEngineKey } from "metabase/databases/utils/engine";
import { useFormErrorMessage } from "metabase/forms";
import type { DatabaseData, Engine } from "metabase-types/api";
+import { FormDirtyStateContext } from "./context";
+
export const useHasConnectionError = () => {
const errorMessage = useFormErrorMessage();
return !!errorMessage;
@@ -25,3 +29,7 @@ export const getEngineKey = (
return getDefaultEngineKey(engines);
}
};
+
+export const useIsFormDirty = () => {
+ return useContext(FormDirtyStateContext);
+};