The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Replace caching strategy picker radios with a dropdown (#74948)
Andrei Chernykh16d2f6509e5d
diff --git a/e2e/support/helpers/e2e-caching-helpers.ts b/e2e/support/helpers/e2e-caching-helpers.tsindex 211e5753da8..1d64c3786c3 100644--- a/e2e/support/helpers/e2e-caching-helpers.ts+++ b/e2e/support/helpers/e2e-caching-helpers.ts@@ -1,7 +1,15 @@export const cacheStrategySidesheet = () =>cy.findByRole("dialog", { name: /Caching settings/ }).should("be.visible");-export const durationRadioButton = () =>+export const cacheStrategySelect = () =>cy.findByRole("form", { name: "Select the cache invalidation policy" })- .findByRole("radio", { name: /Duration/ });+ .findByTestId("cache-strategy-select");++/** Open the strategy dropdown and pick an option by its title (e.g. /Duration/).+ * Options render in a portal at the document root, so this must not run inside+ * a `.within()` scoped to the form/sidesheet. */+export const selectCacheStrategy = (name: RegExp) => {+ cacheStrategySelect().click();+ cy.findByRole("option", { name }).click();+};diff --git a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.jsindex 9e9b0ae952d..51a28a6cc78 100644--- a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js+++ b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js@@ -254,15 +254,16 @@ describe("issue 45890", () => {H.activateToken("pro-self-hosted");cy.visit("/admin/performance/databases");- H.main().within(() => {- cy.findByLabelText(/Edit policy for database 'Sample Database'/)- .findByText("No caching")- .click();+ H.main()+ .findByLabelText(/Edit policy for database 'Sample Database'/)+ .findByText("No caching")+ .click();- cy.findByText("Schedule").click();+ // The strategy picker is a dropdown; its options render in a portal.+ H.main().findByTestId("cache-strategy-select").click();+ cy.findByRole("option", { name: /Schedule/ }).click();- cy.button("Save changes").click();- });+ H.main().button("Save changes").click();});it("should correctly reset caching schedule form when discarding changes", () => {diff --git a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts b/e2e/test/scenarios/admin/performance/caching.cy.spec.tsindex e79297db8fc..d865b86652d 100644--- a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts+++ b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts@@ -5,11 +5,6 @@ import {const { H } = cy;-const adaptiveRadioButton = () =>- cy- .findByRole("form", { name: "Select the cache invalidation policy" })- .findByRole("radio", { name: /Adaptive/ });-const preemptiveCachingSwitch = () =>cy.findByTestId("preemptive-caching-switch");@@ -76,9 +71,9 @@ describe("scenarios > admin > performance > caching", () => {it("saves the default-policy strategy and reflects the saved state", () => {cy.visit("/admin/performance");- adaptiveRadioButton().click();+ H.selectCacheStrategy(/Adaptive/);saveCacheStrategyForm();- adaptiveRadioButton().should("be.checked");+ H.cacheStrategySelect().should("have.value", "Adaptive");});});@@ -99,7 +94,7 @@ describe("scenarios > admin > performance > caching", () => {cy.button(/Clear cache/).should("not.exist");cy.log("Set Sample Database to Duration and save");- H.durationRadioButton().click();+ H.selectCacheStrategy(/Duration/);saveCacheStrategyForm();cy.findByTestId("admin-layout-content").findByLabelText(/Edit.*Sample Database.*currently.*Duration/,@@ -126,7 +121,7 @@ describe("scenarios > admin > performance > caching", () => {cy.log("Enable preemptive caching from the question sidebar");H.visitQuestion(ORDERS_QUESTION_ID);openSidebarCacheStrategyForm("question");- H.durationRadioButton().click();+ H.selectCacheStrategy(/Duration/);preemptiveCachingSwitch().within(() => {cy.findByRole("switch").should("not.be.checked");cy.findByRole("switch").parent("label").click();@@ -175,10 +170,10 @@ describe("scenarios > admin > performance > caching", () => {cy.findByTestId("collection-table").findByText("Orders").click();openSidebarCacheStrategyForm("question");- H.cacheStrategySidesheet().within(() => {- cy.findByText(/Caching settings/).should("be.visible");- H.durationRadioButton().click();- });+ H.cacheStrategySidesheet()+ .findByText(/Caching settings/)+ .should("be.visible");+ H.selectCacheStrategy(/Duration/);cy.log("Action 1 — click the close (×) button");H.cacheStrategySidesheet()@@ -213,14 +208,14 @@ describe("scenarios > admin > performance > caching", () => {cy.log("Configure Orders with Duration: 99h");H.visitQuestion(ORDERS_QUESTION_ID);openSidebarCacheStrategyForm("question");- H.durationRadioButton().click();- cy.findByLabelText(/Cache results for this many hours/).type("99");+ H.selectCacheStrategy(/Duration/);+ cy.findByLabelText(/Cache duration/).type("99");saveCacheStrategyForm();cy.log("Configure Orders, Count with Adaptive");H.visitQuestion(ORDERS_COUNT_QUESTION_ID);openSidebarCacheStrategyForm("question");- adaptiveRadioButton().click();+ H.selectCacheStrategy(/Adaptive/);saveCacheStrategyForm();cy.log("Both entries are visible on the admin tab");@@ -231,18 +226,15 @@ describe("scenarios > admin > performance > caching", () => {cy.log("Clicking Duration: 99h opens its form with duration selected");cy.findByTestId("cache-config-table").contains("Duration: 99h").click();- H.durationRadioButton().should("be.checked");- cy.findByLabelText(/Cache results for this many hours/).should(- "have.value",- "99",- );+ H.cacheStrategySelect().should("have.value", "Duration");+ cy.findByLabelText(/Cache duration/).should("have.value", "99");cy.log("Close the sidesheet via ESC");cy.get("body").type("{esc}");cy.log("Clicking Adaptive opens its form with adaptive selected");cy.findByTestId("cache-config-table").contains("Adaptive").click();- adaptiveRadioButton().should("be.checked");+ H.cacheStrategySelect().should("have.value", "Adaptive");});});});diff --git a/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts b/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.tsindex 374572245c8..34761272c1a 100644--- a/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts+++ b/e2e/test/scenarios/data-studio/data-studio-metrics.cy.spec.ts@@ -428,8 +428,9 @@ describe("scenarios > data studio > library > metrics", () => {H.DataStudio.Metrics.cachingTab().click();cy.log("Change the setting and save");- cy.findByRole("radio", { name: /Use default/ }).should("be.checked");- cy.findByRole("radio", { name: /Duration/ }).click();+ cy.findByTestId("cache-strategy-select").should("have.value", "Default");+ cy.findByTestId("cache-strategy-select").click();+ cy.findByRole("option", { name: /Duration/ }).click();cy.findByRole("button", { name: "Save" }).click();cy.findByRole("button", { name: /Saved/ }).should("exist");@@ -440,7 +441,7 @@ describe("scenarios > data studio > library > metrics", () => {cy.log("Navigate away and come back to verify the change is persisted");H.DataStudio.Metrics.overviewTab().click();H.DataStudio.Metrics.cachingTab().click();- cy.findByRole("radio", { name: /Duration/ }).should("be.checked");+ cy.findByTestId("cache-strategy-select").should("have.value", "Duration");});});});diff --git a/e2e/test/scenarios/permissions/impersonated.cy.spec.js b/e2e/test/scenarios/permissions/impersonated.cy.spec.jsindex 0617fbde9af..18cdad41f23 100644--- a/e2e/test/scenarios/permissions/impersonated.cy.spec.js+++ b/e2e/test/scenarios/permissions/impersonated.cy.spec.js@@ -113,12 +113,13 @@ describe("impersonated permission", { tags: "@external" }, () => {cy.log("configure caching");H.openQuestionActions("Edit settings");cy.findByLabelText("When to get new results").click();- H.cacheStrategySidesheet().within(() => {- cy.findByText(/Default/).click();- cy.findByText(/Caching settings/).should("be.visible");- H.durationRadioButton().click();- cy.findByRole("button", { name: /Save/ }).click();- });+ H.cacheStrategySidesheet()+ .findByText(/Caching settings/)+ .should("be.visible");+ H.selectCacheStrategy(/Duration/);+ H.cacheStrategySidesheet()+ .findByRole("button", { name: /Save/ })+ .click();cy.log("prime and assert results are cached");cy.intercept("POST", "/api/card/*/query").as("query");diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.cssindex 4ec32533aae..de1f787f92f 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.css+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.css@@ -1,5 +1,7 @@+/* Size to content (no empty space for short strategies); cap at the viewport+ and let the body scroll only when the content would overflow. */.content {- height: min(38rem, 85vh);+ max-height: 85vh;display: flex;flex-direction: column;}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.unit.spec.tsxindex 861a6bfd523..a9883f8dae3 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.unit.spec.tsx@@ -6,6 +6,10 @@ import { setupEnterprisePlugins } from "__support__/enterprise";import { setupPerformanceEndpoints } from "__support__/server-mocks/performance";import { mockSettings } from "__support__/settings";import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import {+ getCacheStrategySelect,+ selectCacheStrategy,+} from "metabase/admin/performance/components/test-utils";import { createMockState } from "metabase/redux/store/mocks";import {createMockSettings,@@ -54,32 +58,33 @@ function setup({ cardId = 19, cardName = "Number of Orders" }: SetupOpts = {}) {}describe("MetricCachingModal", () => {- it("renders the five strategy radio options with Default preselected", async () => {+ it("renders the five strategy options with Default preselected", async () => {setup();+ expect(await screen.findByTestId("cache-strategy-select")).toHaveValue(+ "Default",+ );++ await userEvent.click(getCacheStrategySelect());+ expect(await screen.findAllByRole("option")).toHaveLength(5);expect(- await screen.findByRole("radio", { name: /^Default$/i }),- ).toBeChecked();- expect(- await screen.findByRole("radio", { name: /^Duration$/i }),+ screen.getByRole("option", { name: /^Duration/i }),).toBeInTheDocument();expect(- await screen.findByRole("radio", { name: /^Schedule$/i }),+ screen.getByRole("option", { name: /^Schedule/i }),).toBeInTheDocument();expect(- await screen.findByRole("radio", { name: /^Adaptive$/i }),+ screen.getByRole("option", { name: /^Adaptive/i }),).toBeInTheDocument();expect(- await screen.findByRole("radio", { name: /Don.t cache/i }),+ screen.getByRole("option", { name: /Don.t cache/i }),).toBeInTheDocument();});it("persists the selected strategy and closes the modal on Save", async () => {const { onClose } = setup();- await userEvent.click(- await screen.findByRole("radio", { name: /^Duration$/i }),- );+ await selectCacheStrategy(/^Duration/i);await userEvent.click(screen.getByTestId("strategy-form-submit-button"));await waitFor(() => {@@ -111,9 +116,7 @@ describe("MetricCachingModal", () => {async (_label, name) => {const { onClose } = setup();- await userEvent.click(- await screen.findByRole("radio", { name: /^Duration$/i }),- );+ await selectCacheStrategy(/^Duration/i);await userEvent.click(screen.getByRole("button", { name }));expect(@@ -128,9 +131,7 @@ describe("MetricCachingModal", () => {it("re-prompts on Cancel after the discard confirmation is dismissed (form stays dirty)", async () => {const { onClose } = setup();- await userEvent.click(- await screen.findByRole("radio", { name: /^Duration$/i }),- );+ await selectCacheStrategy(/^Duration/i);await userEvent.click(screen.getByRole("button", { name: /^Cancel$/i }));// Dismiss the discard prompt by clicking its Cancel button (not Discard).@@ -142,7 +143,7 @@ describe("MetricCachingModal", () => {);// Form should still be dirty (Duration still selected).- expect(screen.getByRole("radio", { name: /^Duration$/i })).toBeChecked();+ expect(getCacheStrategySelect()).toHaveValue("Duration");// Pressing Cancel again should re-show the discard confirmation.await userEvent.click(screen.getByRole("button", { name: /^Cancel$/i }));diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsxindex 6857e8c438a..63f58da139c 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForDatabases.unit.spec.tsx@@ -5,7 +5,9 @@ import type { SetupOpts } from "metabase/admin/performance/components/test-utilsimport {setupStrategyEditorForDatabases as baseSetup,changeInput,+ getCacheStrategySelect,getSaveButton,+ selectCacheStrategy,} from "metabase/admin/performance/components/test-utils";import { getShortStrategyLabel } from "metabase/admin/performance/utils";import { PLUGIN_CACHING } from "metabase/plugins";@@ -35,16 +37,18 @@ describe("StrategyEditorForDatabases", () => {it("shows four policy options for the default policy", async () => {await userEvent.click(await screen.findByLabelText(/Edit default policy/));- expect(await screen.findAllByRole("radio")).toHaveLength(4);+ await userEvent.click(getCacheStrategySelect());+ expect(await screen.findAllByRole("option")).toHaveLength(4);});it("shows five policy options for a database (adds 'Default')", async () => {await userEvent.click(await screen.findByLabelText(/Edit policy for database 'Database 1'/),);- expect(await screen.findAllByRole("radio")).toHaveLength(5);+ await userEvent.click(getCacheStrategySelect());+ expect(await screen.findAllByRole("option")).toHaveLength(5);expect(- screen.getByRole("radio", { name: /^Default$/i }),+ screen.getByRole("option", { name: /^Default/i }),).toBeInTheDocument();});@@ -90,14 +94,11 @@ describe("StrategyEditorForDatabases", () => {screen.queryByRole("button", { name: "Save changes" }),).not.toBeInTheDocument();- const durationStrategyRadioButton = await screen.findByRole("radio", {- name: /^Duration$/i,- });- expect(durationStrategyRadioButton).toBeChecked();+ expect(await getCacheStrategySelect()).toHaveValue("Duration");expect((await screen.findAllByRole("spinbutton")).length).toBe(1);- await changeInput(/Cache results for this many hours/, 24, 48);+ await changeInput(/Cache duration/, 24, 48);await userEvent.click(await screen.findByTestId("strategy-form-submit-button"),@@ -109,10 +110,7 @@ describe("StrategyEditorForDatabases", () => {),).toBeInTheDocument();- const noCacheStrategyRadioButton = await screen.findByRole("radio", {- name: /Don.t cache/i,- });- await userEvent.click(noCacheStrategyRadioButton);+ await selectCacheStrategy(/Don.t cache/i);expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();@@ -131,10 +129,7 @@ describe("StrategyEditorForDatabases", () => {"Edit default policy (currently: No caching)",);- const adaptiveStrategyRadioButton = await screen.findByRole("radio", {- name: /Adaptive/i,- });- await userEvent.click(adaptiveStrategyRadioButton);+ await selectCacheStrategy(/Adaptive/i);expect((await screen.findAllByRole("spinbutton")).length).toBe(2);@@ -162,10 +157,7 @@ describe("StrategyEditorForDatabases", () => {screen.queryByRole("button", { name: "Save changes" }),).not.toBeInTheDocument();- const noCacheStrategyRadioButton = await screen.findByRole("radio", {- name: /Don.t cache/i,- });- await userEvent.click(noCacheStrategyRadioButton);+ await selectCacheStrategy(/Don.t cache/i);expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();@@ -179,14 +171,11 @@ describe("StrategyEditorForDatabases", () => {),).toBeInTheDocument();- const durationStrategyRadioButton = await screen.findByRole("radio", {- name: /^Duration$/i,- });- await userEvent.click(durationStrategyRadioButton);+ await selectCacheStrategy(/^Duration/i);expect((await screen.findAllByRole("spinbutton")).length).toBe(1);- await changeInput(/Cache results for this many hours/, 24, 48);+ await changeInput(/Cache duration/, 24, 48);await userEvent.click(await screen.findByTestId("strategy-form-submit-button"),@@ -205,10 +194,7 @@ describe("StrategyEditorForDatabases", () => {);// Switch to Adaptive strategy- const multiplierStrategyRadioButton = await screen.findByRole("radio", {- name: /Adaptive/i,- });- await userEvent.click(multiplierStrategyRadioButton);+ await selectCacheStrategy(/Adaptive/i);expect((await screen.findAllByRole("spinbutton")).length).toBe(2);@@ -240,9 +226,7 @@ describe("StrategyEditorForDatabases", () => {),);- await userEvent.click(- await screen.findByRole("radio", { name: /Schedule/i }),- );+ await selectCacheStrategy(/^Schedule/i);const pickOption = async (testId: string, optionName: string) => {await userEvent.click(screen.getByTestId(testId));@@ -302,17 +286,15 @@ describe("StrategyEditorForDatabases (cache_preemptive enabled)", () => {// The preemptive caching switch only renders for question/dashboard targets.// Root and database forms must not show it, regardless of strategy.it.each([- ["default policy", /Edit default policy/, /Duration/i],- ["default policy", /Edit default policy/, /Schedule/i],- ["a database", /Edit policy for database 'Database 1'/, /Duration/i],- ["a database", /Edit policy for database 'Database 1'/, /Schedule/i],+ ["default policy", /Edit default policy/, /^Duration/i],+ ["default policy", /Edit default policy/, /^Schedule/i],+ ["a database", /Edit policy for database 'Database 1'/, /^Duration/i],+ ["a database", /Edit policy for database 'Database 1'/, /^Schedule/i],])("does not show the preemptive caching switch for %s with %p strategy",async (_label, launcherLabel, strategyName) => {await userEvent.click(await screen.findByLabelText(launcherLabel));- await userEvent.click(- await screen.findByRole("radio", { name: strategyName }),- );+ await selectCacheStrategy(strategyName);expect(screen.queryByTestId("preemptive-caching-switch"),).not.toBeInTheDocument();diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsxindex e3e7baa0e67..f4a14602057 100644--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx@@ -5,6 +5,7 @@ import { screen } from "__support__/ui";import {changeInput,getSaveButton,+ selectCacheStrategy,setupStrategyEditorForDatabases as setup,} from "./test-utils";@@ -14,13 +15,13 @@ describe("StrategyEditorForDatabases (OSS)", () => {});it("shows two policy options for the default policy: Adaptive and Don't cache", async () => {- const radios = await screen.findAllByRole("radio");- expect(radios).toHaveLength(2);+ await userEvent.click(await screen.findByTestId("cache-strategy-select"));+ expect(await screen.findAllByRole("option")).toHaveLength(2);expect(- screen.getByRole("radio", { name: /Adaptive/i }),+ screen.getByRole("option", { name: /Adaptive/i }),).toBeInTheDocument();expect(- screen.getByRole("radio", { name: /Don.t cache/i }),+ screen.getByRole("option", { name: /Don.t cache/i }),).toBeInTheDocument();});@@ -29,11 +30,7 @@ describe("StrategyEditorForDatabases (OSS)", () => {screen.queryByRole("button", { name: "Save changes" }),).not.toBeInTheDocument();- const ttlStrategyRadioButton = await screen.findByRole("radio", {- name: /Adaptive/i,- });-- await userEvent.click(ttlStrategyRadioButton);+ await selectCacheStrategy(/Adaptive/i);expect((await screen.findAllByRole("spinbutton")).length).toBe(2);@@ -49,20 +46,14 @@ describe("StrategyEditorForDatabases (OSS)", () => {// NOTE: There is no need to check that the submission of the form was successful.// It doesn't meaningfully change the state of the component on OSS- const noCacheStrategyRadioButton = await screen.findByRole("radio", {- name: /Don.t cache/i,- });- noCacheStrategyRadioButton.click();+ await selectCacheStrategy(/Don.t cache/i);expect(screen.queryByRole("spinbutton")).not.toBeInTheDocument();(await screen.findByTestId("strategy-form-submit-button")).click();});it("does not regard form as dirty when a default value is entered into an input (metabase#42974)", async () => {- const adaptiveStrategyRadioButton = await screen.findByRole("radio", {- name: /Adaptive/i,- });- await userEvent.click(adaptiveStrategyRadioButton);+ await selectCacheStrategy(/Adaptive/i);await userEvent.click(await getSaveButton());await changeInput(/multiplier/i, 10, 10);// The form is not considered dirty, so the save button is not presentdiff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.module.css b/frontend/src/metabase/admin/performance/components/StrategyForm.module.cssindex c6a17d1fe73..69b812efe1b 100644--- a/frontend/src/metabase/admin/performance/components/StrategyForm.module.css+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.module.css@@ -1,11 +1,9 @@-.strategyOption label {- cursor: pointer;+.option {+ padding: var(--mantine-spacing-sm) var(--mantine-spacing-md);}-.radioDescription {- font-size: var(--mantine-font-size-md);- line-height: 1.25rem;- color: var(--mb-color-text-secondary);+.option[data-combobox-selected] {+ background-color: var(--mb-color-background-selected);}.form {diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx b/frontend/src/metabase/admin/performance/components/StrategyForm.tsxindex 1d6139554b0..b4efb1eedb9 100644--- a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx@@ -12,7 +12,6 @@ import type { FormTextInputProps } from "metabase/forms";import {Form,FormProvider,- FormRadioGroup,FormSubmitButton,FormTextInput,useFormContext,@@ -28,10 +27,9 @@ import {Group,Icon,Loader,- Radio,+ Select,Stack,Text,- Title,Tooltip,} from "metabase/ui";import type {@@ -255,54 +253,18 @@ const StrategyFormBody = ({headingId={headingId}showHeading={layout !== "modal"}/>- {selectedStrategyType === "ttl" && (- <>- <Field- title={t`Minimum query duration`}- subtitle={- <Text size="sm">- {t`Metabase will cache all saved questions with an average query execution time greater than this many seconds.`}- </Text>- }- >- <PositiveNumberInput- strategyType="ttl"- name="min_duration_seconds"- />- </Field>- <Field- title={t`Multiplier`}- subtitle={<MultiplierFieldSubtitle />}- >- <PositiveNumberInput strategyType="ttl" name="multiplier" />- </Field>- </>- )}+ {selectedStrategyType === "ttl" && <TtlStrategyFormFields />}{selectedStrategyType === "duration" && (- <>- <Field title={t`Cache results for this many hours`}>- <PositiveNumberInput- strategyType="duration"- name="duration"- />- </Field>- <input type="hidden" name="unit" />- {["question", "dashboard"].includes(targetModel) && (- <PLUGIN_CACHING.PreemptiveCachingSwitch- handleSwitchToggle={handleSwitchToggle}- />- )}- </>+ <DurationStrategyFormFields+ targetModel={targetModel}+ onSwitchToggle={handleSwitchToggle}+ />)}{selectedStrategyType === "schedule" && (- <>- <ScheduleStrategyFormFields />- {["question", "dashboard"].includes(targetModel) && (- <PLUGIN_CACHING.PreemptiveCachingSwitch- handleSwitchToggle={handleSwitchToggle}- />- )}- </>+ <ScheduleStrategyFormFields+ targetModel={targetModel}+ onSwitchToggle={handleSwitchToggle}+ />)}</Stack></Box>@@ -439,7 +401,13 @@ const FormButtons = ({return null;};-const ScheduleStrategyFormFields = () => {+const ScheduleStrategyFormFields = ({+ targetModel,+ onSwitchToggle,+}: {+ targetModel: CacheableModel;+ onSwitchToggle: () => void;+}) => {const { values, setFieldValue } = useFormikContext<ScheduleStrategy>();const { schedule: scheduleInCronFormat } = values;const initialSchedule = cronToScheduleSettings(scheduleInCronFormat);@@ -452,6 +420,8 @@ const ScheduleStrategyFormFields = () => {},[setFieldValue],);++ // A malformed cron can't drive the Schedule UI, so show only the error.if (!initialSchedule) {return (<LoadingAndErrorWrapper@@ -462,14 +432,32 @@ const ScheduleStrategyFormFields = () => {return (<>- <Schedule- cronString={scheduleInCronFormat || defaultCronSchedule}- scheduleOptions={["hourly", "daily", "weekly", "monthly"]}- onScheduleChange={onScheduleChange}- verb={c("A verb in the imperative mood").t`Invalidate`}- timezone={timezone}- aria-label={t`Describe how often the cache should be invalidated`}- />+ {/* Not a StrategyFormField: its <label> would redirect title/subtitle+ clicks to the first Select inside Schedule. */}+ <Stack gap="sm">+ <Stack gap="xs">+ <Text fw="bold" fz="md" lh="1.25rem">+ {t`Cache invalidation schedule`}+ </Text>+ <Text fz="md" lh="1.25rem" c="text-secondary">+ {t`How often to invalidate cached results.`}+ </Text>+ </Stack>+ <Schedule+ cronString={scheduleInCronFormat || defaultCronSchedule}+ scheduleOptions={["hourly", "daily", "weekly", "monthly"]}+ onScheduleChange={onScheduleChange}+ verb={c("A verb in the imperative mood").t`Invalidate`}+ layout="horizontal"+ timezone={timezone}+ aria-label={t`Describe how often the cache should be invalidated`}+ />+ </Stack>+ {["question", "dashboard"].includes(targetModel) && (+ <PLUGIN_CACHING.PreemptiveCachingSwitch+ handleSwitchToggle={onSwitchToggle}+ />+ )}</>);};@@ -529,31 +517,6 @@ export const StrategySelectorHeading = ({</Stack>);-const StrategyOption = ({- value,- title,- description,- autoFocus,-}: {- value: string;- title?: string;- description?: string;- autoFocus?: boolean;-}) => (- <Radio- value={value}- className={S.strategyOption}- classNames={{ description: S.radioDescription }}- label={- <Text component="strong" fw="bold" lh="1.25rem">- {title}- </Text>- }- description={description}- autoFocus={autoFocus}- />-);-const StrategySelector = ({targetId,model,@@ -566,43 +529,124 @@ const StrategySelector = ({showHeading?: boolean;}) => {const { strategies } = PLUGIN_CACHING;+ const { values, setFieldValue } = useFormikContext<CacheStrategy>();- const { values } = useFormikContext<CacheStrategy>();+ const availableStrategies = useMemo(+ () => (targetId === rootId ? _.omit(strategies, "inherit") : strategies),+ [targetId, strategies],+ );- const availableStrategies = useMemo(() => {- return targetId === rootId ? _.omit(strategies, "inherit") : strategies;- }, [targetId, strategies]);+ const data = useMemo(+ () =>+ Object.entries(availableStrategies).map(([name, option]) => ({+ value: name,+ label: getLabelString(option.label, model) ?? name,+ })),+ [availableStrategies, model],+ );return (<section aria-labelledby={headingId}>- <FormRadioGroup- label={- showHeading ? (- <StrategySelectorHeading headingId={headingId} />- ) : undefined- }- name="type"- >- <Stack mt={showHeading ? "xl" : 0} gap="md">- {Object.entries(availableStrategies).map(([name, option]) => (- <StrategyOption- key={name}- value={name}- title={getLabelString(option.label, model)}- description={- option.description- ? getLabelString(option.description, model)- : undefined- }- autoFocus={values.type === name}- />- ))}- </Stack>- </FormRadioGroup>+ {showHeading && <StrategySelectorHeading headingId={headingId} />}+ <Select+ mt={showHeading ? "xl" : 0}+ data={data}+ value={values.type}+ onChange={(value) => value && setFieldValue("type", value)}+ allowDeselect={false}+ aria-labelledby={headingId}+ data-testid="cache-strategy-select"+ classNames={{ option: S.option }}+ renderOption={({ option }) => {+ const strategy = availableStrategies[option.value];+ if (!strategy) {+ return option.label;+ }+ return (+ <Stack gap="xs">+ <Text fw="bold">{getLabelString(strategy.label, model)}</Text>+ {strategy.description && (+ <Text size="sm" c="text-secondary">+ {getLabelString(strategy.description, model)}+ </Text>+ )}+ </Stack>+ );+ }}+ /></section>);};+const TtlStrategyFormFields = () => (+ <>+ <StrategyFormField+ title={t`Minimum query duration`}+ subtitle={+ <Text fz="md" lh="1.25rem" c="text-secondary">+ {t`Skip caching for queries that run faster than this.`}+ </Text>+ }+ unit={c("Unit suffix shown after the minimum query duration input")+ .t`seconds`}+ >+ <PositiveNumberInput strategyType="ttl" name="min_duration_seconds" />+ </StrategyFormField>+ <StrategyFormField+ title={t`Multiplier`}+ subtitle={<MultiplierFieldSubtitle />}+ unit={c("Unit suffix shown after the cache multiplier input").t`times`}+ >+ <PositiveNumberInput strategyType="ttl" name="multiplier" />+ </StrategyFormField>+ </>+);++const MultiplierFieldSubtitle = () => (+ <Text fz="md" lh="1.25rem" c="text-secondary">+ {t`Cached results last this many times the query's average run time.`}{" "}+ <Tooltip+ multiline+ inline={true}+ position="bottom"+ label={t`If a query takes on average 120 seconds (2 minutes) to run, and you input 10 for your multiplier, its cache entry will persist for 1,200 seconds (20 minutes).`}+ maw="20rem"+ >+ <Text tabIndex={0} fz="md" lh="1.25rem" display="inline" c="brand">+ {t`Example`}+ </Text>+ </Tooltip>+ </Text>+);++const DurationStrategyFormFields = ({+ targetModel,+ onSwitchToggle,+}: {+ targetModel: CacheableModel;+ onSwitchToggle: () => void;+}) => (+ <>+ <StrategyFormField+ title={t`Cache duration`}+ subtitle={+ <Text fz="md" lh="1.25rem" c="text-secondary">+ {t`Cached results are refreshed after this period.`}+ </Text>+ }+ unit={c("Unit suffix shown after the cache duration input").t`hours`}+ >+ <PositiveNumberInput strategyType="duration" name="duration" />+ </StrategyFormField>+ <input type="hidden" name="unit" />+ {["question", "dashboard"].includes(targetModel) && (+ <PLUGIN_CACHING.PreemptiveCachingSwitch+ handleSwitchToggle={onSwitchToggle}+ />+ )}+ </>+);+export const PositiveNumberInput = ({strategyType,...props@@ -628,41 +672,38 @@ export const PositiveNumberInput = ({);};-const Field = ({+const StrategyFormField = ({title,subtitle,+ unit,children,}: {title: ReactNode;subtitle?: ReactNode;+ unit?: ReactNode;children: ReactNode;}) => {+ const control = unit ? (+ <Flex align="center" gap="sm">+ {children}+ <Text c="text-secondary" fz="md" lh="1.25rem">+ {unit}+ </Text>+ </Flex>+ ) : (+ children+ );return (<label>- <Stack gap="xs">- <div>- <Title order={4}>{title}</Title>+ <Stack gap="sm">+ <Stack gap="xs">+ <Text fw="bold" fz="md" lh="1.25rem">+ {title}+ </Text>{subtitle}- </div>- {children}+ </Stack>+ {control}</Stack></label>);};--const MultiplierFieldSubtitle = () => (- <Text size="sm">- {t`To determine how long each cached result should stick around, we take that query's average execution time and multiply that by what you input here. The result is how many seconds the cache should remain valid for.`}{" "}- <Tooltip- multiline- inline={true}- position="bottom"- label={t`If a query takes on average 120 seconds (2 minutes) to run, and you input 10 for your multiplier, its cache entry will persist for 1,200 seconds (20 minutes).`}- maw="20rem"- >- <Text tabIndex={0} size="sm" lh="1" display="inline" c="brand">- {t`Example`}- </Text>- </Tooltip>- </Text>-);diff --git a/frontend/src/metabase/admin/performance/components/test-utils.tsx b/frontend/src/metabase/admin/performance/components/test-utils.tsxindex 5dc002afa4c..7581b7883da 100644--- a/frontend/src/metabase/admin/performance/components/test-utils.tsx+++ b/frontend/src/metabase/admin/performance/components/test-utils.tsx@@ -1,3 +1,4 @@+import userEvent from "@testing-library/user-event";import { Route } from "react-router";import {@@ -90,6 +91,16 @@ export const setupStrategyEditorForDatabases = ({export const getSaveButton = async () =>await screen.findByTestId("strategy-form-submit-button");+/** The strategy picker is a Mantine Select; its options stack a bold title+ * over a description, so match `name` against the title prefix (e.g. `/^Duration/i`). */+export const selectCacheStrategy = async (name: RegExp) => {+ await userEvent.click(await screen.findByTestId("cache-strategy-select"));+ await userEvent.click(await screen.findByRole("option", { name }));+};++export const getCacheStrategySelect = () =>+ screen.getByTestId("cache-strategy-select");+export const changeInput = async (label: RegExp,expectedPlaceholder: number,diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsxindex b7d24a3bc44..dd445818074 100644--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.unit.spec.tsx@@ -250,9 +250,9 @@ describe("MetricToolbar", () => {expect(await screen.findByRole("dialog", { name: /Caching/i }),).toBeInTheDocument();- expect(- await screen.findByRole("radio", { name: /^Default$/i }),- ).toBeInTheDocument();+ expect(await screen.findByTestId("cache-strategy-select")).toHaveValue(+ "Default",+ );});});