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
feat: Move Caching tab into the overflow menu (UXW-4236) (#74563)
Andrei Chernykh520fece1d027
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.styled.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.styled.tsxdeleted file mode 100644index 53dd9aa48aa..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.styled.tsx+++ /dev/null@@ -1,10 +0,0 @@-import styled from "@emotion/styled";--import { FormSubmitButton } from "metabase/forms";--export const StyledInvalidateNowButton = styled(FormSubmitButton)`- align-self: flex-start;- padding: 0.75rem;- min-width: 40px;- height: 40px;-`;diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsxindex 8c151725880..1be2f8666f8 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/InvalidateNowButton.tsx@@ -3,17 +3,14 @@ import { useCallback, useMemo } from "react";import { match } from "ts-pattern";import { c, t } from "ttag";-import { IconInButton } from "metabase/admin/performance/components/StrategyForm.styled";import { useInvalidateTarget } from "metabase/admin/performance/hooks/useInvalidateTarget";import { useIsFormPending } from "metabase/admin/performance/hooks/useIsFormPending";import type { ModelWithClearableCache } from "metabase/admin/performance/types";import { useConfirmation } from "metabase/common/hooks/use-confirmation";-import { Form, FormProvider } from "metabase/forms";+import { FormProvider, FormSubmitButton } from "metabase/forms";import type { InvalidateNowButtonProps } from "metabase/plugins";import { Group, Icon, Loader, Text } from "metabase/ui";-import { StyledInvalidateNowButton } from "./InvalidateNowButton.styled";-/** Button that clears the cache of a particular object (the "target") */export const InvalidateNowButton = ({targetId,@@ -67,42 +64,41 @@ const InvalidateNowFormBody = ({[targetModel],);+ // Nested `<form>` would be invalid HTML; the parent `StrategyForm` owns the form element.return (<>- <Form>- <StyledInvalidateNowButton- onClick={(e) => {- confirmInvalidation();- e.preventDefault();- return false;- }}- disabled={wasFormRecentlyPending}- label={- <Group gap="sm">- <Icon c="danger" name="trash" />- <Text>{buttonText}</Text>- </Group>- }- activeLabel={- <Group gap="sm">- <Loader size="1rem" />- <Text>{c("Shown when a cache is being cleared")- .t`Clearing cache… `}</Text>- </Group>- }- successLabel={- <Group gap="sm">- <IconInButton name="check" c={"success"} />- <Text>{t`Cache cleared`}</Text>- </Group>- }- failedLabel={- <Text fw="bold" lh="1">- {t`Error`}- </Text>- }- />- </Form>+ <FormSubmitButton+ onClick={(e) => {+ confirmInvalidation();+ e.preventDefault();+ return false;+ }}+ disabled={wasFormRecentlyPending}+ variant="subtle"+ c="error"+ px="sm"+ leftSection={<Icon name="trash" />}+ label={buttonText}+ activeLabel={+ <Group gap="sm" align="center">+ <Loader size="1rem" />+ <Text>{c("Shown when a cache is being cleared")+ .t`Clearing cache… `}</Text>+ </Group>+ }+ successLabel={+ <Group gap="sm" align="center">+ <Icon name="check" c="success" />+ <Text>{t`Cache cleared`}</Text>+ </Group>+ }+ failedLabel={+ <Text fw="bold" lh="1">+ {t`Error`}+ </Text>+ }+ />+{confirmationModal}</>);diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.cssnew file mode 100644index 00000000000..4ec32533aae--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.module.css@@ -0,0 +1,12 @@+.content {+ height: min(38rem, 85vh);+ display: flex;+ flex-direction: column;+}++.body {+ display: flex;+ flex-direction: column;+ flex: 1;+ min-height: 0;+}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsxnew file mode 100644index 00000000000..cb6d960fe78--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsx@@ -0,0 +1,83 @@+import { useCallback } from "react";+import { t } from "ttag";++import { StrategyForm } from "metabase/admin/performance/components/StrategyForm";+import { useCacheConfigs } from "metabase/admin/performance/hooks/useCacheConfigs";+import { useConfirmIfFormIsDirty } from "metabase/admin/performance/hooks/useConfirmIfFormIsDirty";+import { useSaveStrategy } from "metabase/admin/performance/hooks/useSaveStrategy";+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";+import type { MetricCachingModalProps } from "metabase/plugins";+import { Modal } from "metabase/ui";+import type { CacheStrategy, CacheableModel } from "metabase-types/api";++import S from "./MetricCachingModal.module.css";++const QUESTION_MODELS: CacheableModel[] = ["question"];++export function MetricCachingModal({+ cardId,+ cardName,+ onClose,+}: MetricCachingModalProps) {+ // Metric cache configs live under the `question` model on the API.+ const { configs, isLoading, error } = useCacheConfigs({+ model: QUESTION_MODELS,+ id: cardId,+ });++ const savedStrategy = configs?.find(+ (config) => config.model_id === cardId,+ )?.strategy;++ const saveStrategy = useSaveStrategy(cardId, "metric");++ const {+ confirmationModal,+ setIsStrategyFormDirty,+ isStrategyFormDirty,+ askBeforeDiscardingChanges,+ } = useConfirmIfFormIsDirty();++ const handleClose = useCallback(() => {+ if (isStrategyFormDirty) {+ askBeforeDiscardingChanges(onClose);+ } else {+ onClose();+ }+ }, [isStrategyFormDirty, askBeforeDiscardingChanges, onClose]);++ const handleSaveAndClose = useCallback(+ async (values: CacheStrategy) => {+ await saveStrategy(values);+ onClose();+ },+ [saveStrategy, onClose],+ );++ return (+ <Modal+ opened+ onClose={handleClose}+ title={t`Caching`}+ size="lg"+ padding="lg"+ classNames={{ content: S.content, body: S.body }}+ >+ <DelayedLoadingAndErrorWrapper loading={isLoading} error={error}>+ <StrategyForm+ targetId={cardId}+ targetModel="metric"+ targetName={cardName}+ setIsDirty={setIsStrategyFormDirty}+ saveStrategy={handleSaveAndClose}+ savedStrategy={savedStrategy}+ shouldAllowInvalidation+ shouldShowName={false}+ onReset={handleClose}+ layout="modal"+ />+ </DelayedLoadingAndErrorWrapper>+ {confirmationModal}+ </Modal>+ );+}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.tsxnew file mode 100644index 00000000000..861a6bfd523--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.unit.spec.tsx@@ -0,0 +1,162 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import { Route } from "react-router";++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 { createMockState } from "metabase/redux/store/mocks";+import {+ createMockSettings,+ createMockTokenFeatures,+} from "metabase-types/api/mocks";++import { MetricCachingModal } from "./MetricCachingModal";++interface SetupOpts {+ cardId?: number;+ cardName?: string;+}++function setup({ cardId = 19, cardName = "Number of Orders" }: SetupOpts = {}) {+ const settings = mockSettings(+ createMockSettings({+ "token-features": createMockTokenFeatures({+ cache_granular_controls: true,+ }),+ }),+ );++ setupEnterprisePlugins();+ setupPerformanceEndpoints([]);+ fetchMock.post("glob:*/api/cache/invalidate*", {});++ const onClose = jest.fn();+ const storeInitialState = createMockState({ settings });++ // `useConfirmIfFormIsDirty` needs router context.+ renderWithProviders(+ <Route+ path="/"+ component={() => (+ <MetricCachingModal+ cardId={cardId}+ cardName={cardName}+ onClose={onClose}+ />+ )}+ />,+ { storeInitialState, withRouter: true, initialRoute: "/" },+ );++ return { cardId, cardName, onClose };+}++describe("MetricCachingModal", () => {+ it("renders the five strategy radio options with Default preselected", async () => {+ setup();++ expect(+ await screen.findByRole("radio", { name: /^Default$/i }),+ ).toBeChecked();+ expect(+ await screen.findByRole("radio", { name: /^Duration$/i }),+ ).toBeInTheDocument();+ expect(+ await screen.findByRole("radio", { name: /^Schedule$/i }),+ ).toBeInTheDocument();+ expect(+ await screen.findByRole("radio", { name: /^Adaptive$/i }),+ ).toBeInTheDocument();+ expect(+ await screen.findByRole("radio", { 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 userEvent.click(screen.getByTestId("strategy-form-submit-button"));++ await waitFor(() => {+ expect(+ fetchMock.callHistory.called("path:/api/cache", { method: "PUT" }),+ ).toBe(true);+ });+ await waitFor(() => expect(onClose).toHaveBeenCalled());+ });++ it("closes the modal on Cancel without writing to the cache config", async () => {+ const { onClose } = setup();++ await userEvent.click(+ await screen.findByRole("button", { name: "Cancel" }),+ );++ expect(onClose).toHaveBeenCalled();+ expect(+ fetchMock.callHistory.called("path:/api/cache", { method: "PUT" }),+ ).toBe(false);+ });++ it.each([+ ["close button", /close/i],+ ["Cancel button", /^Cancel$/i],+ ])(+ "prompts before discarding when the %s is pressed with a dirty form",+ async (_label, name) => {+ const { onClose } = setup();++ await userEvent.click(+ await screen.findByRole("radio", { name: /^Duration$/i }),+ );+ await userEvent.click(screen.getByRole("button", { name }));++ expect(+ await screen.findByRole("heading", {+ name: /Discard your changes\?/i,+ }),+ ).toBeInTheDocument();+ expect(onClose).not.toHaveBeenCalled();+ },+ );++ 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 userEvent.click(screen.getByRole("button", { name: /^Cancel$/i }));++ // Dismiss the discard prompt by clicking its Cancel button (not Discard).+ const discardDialog = await screen.findByRole("dialog", {+ name: /Discard your changes\?/i,+ });+ await userEvent.click(+ within(discardDialog).getByRole("button", { name: /^Cancel$/i }),+ );++ // Form should still be dirty (Duration still selected).+ expect(screen.getByRole("radio", { name: /^Duration$/i })).toBeChecked();++ // Pressing Cancel again should re-show the discard confirmation.+ await userEvent.click(screen.getByRole("button", { name: /^Cancel$/i }));+ expect(+ await screen.findByRole("heading", { name: /Discard your changes\?/i }),+ ).toBeInTheDocument();+ expect(onClose).not.toHaveBeenCalled();+ });++ it("renders the Clear cache button labelled for the metric", async () => {+ setup();++ expect(+ await screen.findByText("Clear cache for this metric"),+ ).toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.module.cssnew file mode 100644index 00000000000..19d20623dfc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.module.css@@ -0,0 +1,4 @@+/* Doubled class beats Mantine's transparent-on-hover rule for subtle buttons without `!important`. */+.highlightOnHover.highlightOnHover[data-variant="subtle"]:hover {+ background-color: var(--mb-color-background-error);+}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.styled.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.styled.tsxdeleted file mode 100644index eef49c170ae..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.styled.tsx+++ /dev/null@@ -1,22 +0,0 @@-import { css } from "@emotion/react";-import styled from "@emotion/styled";--import type { FormSubmitButtonProps } from "metabase/forms";-import { FormSubmitButton } from "metabase/forms";--export const ResetAllFormSubmitButton = styled(FormSubmitButton, {- shouldForwardProp: (prop) => prop !== "highlightOnHover",-})<FormSubmitButtonProps & { highlightOnHover?: boolean }>`- ${({ highlightOnHover }) =>- highlightOnHover- ? css`- :hover {- background-color: color-mix(- in srgb,- var(--mb-color-error),- transparent 85%- );- }- `- : ""}-`;diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsxindex b951ae37338..c42a277a132 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsx@@ -2,18 +2,14 @@ import { useFormikContext } from "formik";import { t } from "ttag";import { useConfirmation } from "metabase/common/hooks/use-confirmation";-import { Form, useFormContext } from "metabase/forms";+import { Form, FormSubmitButton, useFormContext } from "metabase/forms";import { Box, Flex, Group, Icon, Loader, Text } from "metabase/ui";-import { ResetAllFormSubmitButton } from "./ResetButtonContainer.styled";+import S from "./ResetButtonContainer.module.css";export const ResetButtonContainer = () => {return (- <Box- pb="1rem"- mt="auto"- style={{ marginInlineStart: "auto", marginInlineEnd: "1.5rem" }}- >+ <Box pb="md" mt="auto" ms="auto" me="lg"><ResetAllToDefaultButtonFormBody /></Box>);@@ -38,8 +34,8 @@ const ResetAllToDefaultButtonFormBody = () => {<><Form><Flex justify="flex-end">- <ResetAllFormSubmitButton- px="1rem"+ <FormSubmitButton+ px="md"py=".75rem"lh="1"onClick={(e) => {@@ -65,7 +61,7 @@ const ResetAllToDefaultButtonFormBody = () => {</Text>}variant="subtle"- highlightOnHover={status === "idle"}+ className={status === "idle" ? S.highlightOnHover : undefined}/></Flex></Form>diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsxindex b4ac9acedc9..c41a076d94d 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx@@ -85,9 +85,13 @@ export const SidebarCacheForm = ({savedStrategy={savedStrategy}shouldAllowInvalidationshouldShowName={false}- onReset={onBack}+ onReset={() =>+ isStrategyFormDirty+ ? askBeforeDiscardingChanges(onBack)+ : onBack()+ }buttonLabels={{ save: t`Save`, discard: t`Cancel` }}- isInSidebar+ layout="sidebar"/></DelayedLoadingAndErrorWrapper>{confirmationModal}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.module.cssnew file mode 100644index 00000000000..70c52e2e769--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.module.css@@ -0,0 +1,4 @@+.formLauncher:hover,+.formLauncher:focus-visible {+ color: var(--mb-color-brand);+}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.styled.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.styled.tsxdeleted file mode 100644index 46a65ba1dda..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.styled.tsx+++ /dev/null@@ -1,17 +0,0 @@-import styled from "@emotion/styled";-import type { AnchorHTMLAttributes } from "react";--import type { AnchorProps } from "metabase/ui";-import { Anchor } from "metabase/ui";--export const FormLauncher = styled(Anchor)<- AnchorProps & AnchorHTMLAttributes<HTMLAnchorElement>->`- font-weight: bold;-- &:hover,- &:active {- color: var(--mb-color-brand);- text-decoration: none;- }-`;diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.tsxindex c19966cf426..fdf5e09632e 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheSection.tsx@@ -6,9 +6,9 @@ import { useCacheConfigs } from "metabase/admin/performance/hooks/useCacheConfigimport { getShortStrategyLabel } from "metabase/admin/performance/utils";import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";import type { SidebarCacheSectionProps } from "metabase/plugins";-import { Flex } from "metabase/ui";+import { Flex, UnstyledButton } from "metabase/ui";-import { FormLauncher } from "./SidebarCacheSection.styled";+import S from "./SidebarCacheSection.module.css";import { getItemId } from "./utils";/** Displays the current cache invalidation strategy and provides a button that opens the cache configuration form */@@ -32,20 +32,21 @@ export const SidebarCacheSection = ({const savedStrategy = targetConfig?.strategy;const shortStrategyLabel =- getShortStrategyLabel(savedStrategy, model) || t`Use default`;+ getShortStrategyLabel(savedStrategy, model) || t`Default`;const labelId = "question-caching-policy-label";return (<DelayedLoadingAndErrorWrapper delay={0} loading={isLoading} error={error}><Flex align="center" justify="space-between"><span id={labelId}>{t`When to get new results`}</span>- <FormLauncher- role="button"+ <UnstyledButton+ fw="bold"+ className={S.formLauncher}onClick={() => setPage("caching")}aria-labelledby={labelId}>{shortStrategyLabel}- </FormLauncher>+ </UnstyledButton></Flex></DelayedLoadingAndErrorWrapper>);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 4856011d5cf..6857e8c438a 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@@ -38,13 +38,13 @@ describe("StrategyEditorForDatabases", () => {expect(await screen.findAllByRole("radio")).toHaveLength(4);});- it("shows five policy options for a database (adds 'Use default')", async () => {+ 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);expect(- screen.getByRole("radio", { name: /Use default/i }),+ screen.getByRole("radio", { name: /^Default$/i }),).toBeInTheDocument();});@@ -91,7 +91,7 @@ describe("StrategyEditorForDatabases", () => {).not.toBeInTheDocument();const durationStrategyRadioButton = await screen.findByRole("radio", {- name: /keep the cache for a number of hours/i,+ name: /^Duration$/i,});expect(durationStrategyRadioButton).toBeChecked();@@ -152,7 +152,7 @@ describe("StrategyEditorForDatabases", () => {).toBeInTheDocument();});- it("lets user change policy for Database 1 from 'Adaptive' to 'Duration' to 'Don't cache to 'Use default'", async () => {+ it("lets user change policy for Database 1 from 'Adaptive' to 'Duration' to 'Don't cache to 'Default'", async () => {const editButton = await screen.findByLabelText(`Edit policy for database 'Database 1' (currently: Adaptive)`,);@@ -180,7 +180,7 @@ describe("StrategyEditorForDatabases", () => {).toBeInTheDocument();const durationStrategyRadioButton = await screen.findByRole("radio", {- name: /keep the cache for a number of hours/i,+ name: /^Duration$/i,});await userEvent.click(durationStrategyRadioButton);diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsxindex 3c54a90b81c..33e9334f9ab 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx@@ -246,7 +246,8 @@ export const StrategyEditorForQuestionsAndDashboards = () => {savedStrategy={savedStrategy}shouldAllowInvalidation={true}shouldShowName={false}- isInSidebar+ onReset={closeForm}+ layout="sidebar"/>)}</Sidesheet>diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.module.cssnew file mode 100644index 00000000000..35e42f9b4aa--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.module.css@@ -0,0 +1,49 @@+.launcher {+ display: flex;+ flex-direction: row;+ flex-wrap: nowrap;+ align-items: center;+ justify-content: space-between;+ gap: var(--mantine-spacing-sm);+ width: 100%;+ padding: var(--mantine-spacing-md);+ border-radius: var(--mantine-radius-md);+ border: 1px solid var(--mb-color-border);+ background-color: var(--mb-color-background-primary);+ font-weight: bold;+ cursor: pointer;+}++.launcher[data-for-root="true"] {+ background-color: var(--mb-color-background-tertiary);+ font-weight: normal;+}++.launcher[data-inherits-root="true"] {+ font-weight: normal;+}++.token {+ border-width: 1px;+ border-style: solid;+}++.token[data-variant="filled"],+.token[data-variant="outline"] {+ border-color: var(--mb-color-brand);+}++.token :global(.mantine-Button-inner) {+ gap: var(--mantine-spacing-sm);+}++@media (max-width: 40em) {+ .launcher {+ flex-direction: column;+ align-items: stretch;+ }++ .token {+ flex: 1;+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.styled.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.styled.tsxdeleted file mode 100644index 04f06a23242..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.styled.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { css } from "@emotion/react";-import styled from "@emotion/styled";-import type { HTMLAttributes, MutableRefObject } from "react";--import { breakpointMaxSmall } from "metabase/styled-components/theme";-import type { ButtonProps as BaseButtonProps } from "metabase/ui";-import { Button } from "metabase/ui";--type ButtonProps = BaseButtonProps & HTMLAttributes<HTMLButtonElement>;-export const PolicyToken = styled((props: ButtonProps) => (- <Button {...props} radius={props.radius ?? "sm"} />-))<- { variant?: string; ref?: MutableRefObject<HTMLButtonElement> } & ButtonProps->`- cursor: pointer;- display: flex;- flex-flow: row nowrap;- padding: 1rem;- border-width: 1px;- border-style: solid;- justify-content: center;-- ${({ variant }) => css`- border-color: ${["filled", "outline"].includes(variant || "")- ? "var(--mb-color-brand)"- : "var(--mb-color-border)"} !important;- `};- span {- gap: 0.5rem;- }- ${breakpointMaxSmall} {- flex: 1;- }-` as unknown as typeof Button;--export const StyledLauncher = styled.div<- {- forRoot?: boolean;- inheritsRootStrategy?: boolean;- variant?: string;- ref?: MutableRefObject<HTMLDivElement>;- } & ButtonProps->`- border-radius: 0.5rem;- cursor: pointer;- display: flex;- flex-flow: row nowrap;- padding: 1rem;- border-width: 1px;- border-style: solid;- justify-content: space-between;- gap: 0.5rem;- width: 100%;- ${({ variant }) => css`- border-color: ${["filled", "outline"].includes(variant || "")- ? "var(--mb-color-brand)"- : "var(--mb-color-border)"} !important;- `};- font-weight: ${({ forRoot, inheritsRootStrategy }) =>- forRoot || inheritsRootStrategy ? "normal" : "bold"};- background-color: ${({ forRoot }) =>- forRoot- ? "var(--mb-color-background-tertiary)"- : "var(--mb-color-background-primary)"};- ${({ forRoot }) =>- !forRoot &&- css`- border: 1px solid var(--mb-color-border);- `};- flex-direction: row;- align-items: center;- ${breakpointMaxSmall} {- flex-direction: column;- align-items: stretch;- gap: 0.5rem;- }-`; // FIXME, make this into CSS modulesdiff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.tsxindex 6b0b9b8551c..734b13afae5 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.tsx@@ -4,10 +4,18 @@ import { findWhere } from "underscore";import { rootId } from "metabase/admin/performance/constants/simple";import type { UpdateTargetId } from "metabase/admin/performance/types";import { getShortStrategyLabel } from "metabase/admin/performance/utils";-import { FixedSizeIcon, Flex, Title, Tooltip, useHover } from "metabase/ui";+import {+ Box,+ Button,+ FixedSizeIcon,+ Flex,+ Title,+ Tooltip,+ useHover,+} from "metabase/ui";import type { CacheConfig } from "metabase-types/api";-import { PolicyToken, StyledLauncher } from "./StrategyFormLauncher.styled";+import S from "./StrategyFormLauncher.module.css";export type StrategyFormLauncherProps = {forId: number;@@ -38,7 +46,7 @@ export const StrategyFormLauncher = ({const strategy = savedStrategy ?? rootStrategy;const isBeingEdited = targetId === forId;- const { hovered, ref: hoveredRef } = useHover<HTMLDivElement>();+ const { hovered, ref: hoveredRef } = useHover<HTMLElement>();const buttonVariant =isBeingEdited || hovered@@ -66,29 +74,31 @@ export const StrategyFormLauncher = ({const shouldDisableTooltip = !inheritsRootStrategy;return (- <StyledLauncher- ref={hoveredRef as any}+ <Box+ ref={hoveredRef}+ className={S.launcher}+ data-for-root={forRoot}+ data-inherits-root={inheritsRootStrategy}aria-label={ariaLabel}onClick={launchForm}- forRoot={forRoot}- inheritsRootStrategy={inheritsRootStrategy}data-testid={`strategy-form-launcher${shouldDisableTooltip ? "" : "-with-tooltip"}`}>- <Flex gap="0.5rem" c="text-secondary" align="center">+ <Flex gap="sm" c="text-secondary" align="center"><FixedSizeIcon name={forRoot ? "star" : "database"} c="inherit" /><Title c="inherit" order={6}>{title}</Title></Flex>- <Flex wrap="nowrap" lh="1.5rem" gap=".5rem">+ <Flex wrap="nowrap" lh="1.5rem" gap="sm"><Tooltipposition="bottom"disabled={shouldDisableTooltip}label={t`Using default policy`}>- <PolicyToken+ <Button+ className={S.token}onClick={launchForm}variant={buttonVariant}fw={forRoot || inheritsRootStrategy ? "normal" : "bold"}@@ -98,9 +108,9 @@ export const StrategyFormLauncher = ({radius="7rem">{shortStrategyLabel}- </PolicyToken>+ </Button></Tooltip></Flex>- </StyledLauncher>+ </Box>);};diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.module.cssnew file mode 100644index 00000000000..44e4a010802--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.module.css@@ -0,0 +1,25 @@+.root {+ overflow-y: auto;+}++.section {+ padding: var(--mantine-spacing-lg);+}++.divided {+ border-bottom: 1px solid var(--mb-color-border);+}++.stack {+ gap: var(--mantine-spacing-md);+}++@media screen and (max-width: 40em) {+ .section {+ padding: 0.75rem;+ }++ .stack {+ gap: var(--mantine-spacing-sm);+ }+}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.styled.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.styled.tsxdeleted file mode 100644index fef644da488..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.styled.tsx+++ /dev/null@@ -1,27 +0,0 @@-import { css } from "@emotion/react";-import styled from "@emotion/styled";--import { breakpointMaxSmall } from "metabase/styled-components/theme";-import { Box, Stack } from "metabase/ui";--const sectionStyle = css`- padding: 1.5rem;- ${breakpointMaxSmall} {- padding: 0.75rem;- }-`;--export const StrategyFormLauncherPanelBox = styled(Box)<- React.PropsWithChildren<any>->`- ${sectionStyle}- border-bottom: 1px solid var(--mb-color-border);-` as unknown as typeof Box;--export const StrategyFormLauncherPanelStack = styled(Stack)`- ${sectionStyle}- gap: 1rem;- ${breakpointMaxSmall} {- gap: 0.5rem;- }-`;diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.tsxindex 9170a72ed07..194af551bfc 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.tsx@@ -1,10 +1,11 @@+import cx from "classnames";import { useMemo } from "react";import { t } from "ttag";-import { Panel } from "metabase/admin/performance/components/StrategyEditorForDatabases.styled";import { rootId } from "metabase/admin/performance/constants/simple";import type { UpdateTargetId } from "metabase/admin/performance/types";import { FormProvider } from "metabase/forms";+import { Box, Stack } from "metabase/ui";import type Database from "metabase-lib/v1/metadata/Database";import type { CacheConfig } from "metabase-types/api";@@ -12,10 +13,7 @@ import { useResetToDefaultForm } from "../hooks/useResetToDefaultForm";import { ResetButtonContainer } from "./ResetButtonContainer";import { StrategyFormLauncher } from "./StrategyFormLauncher";-import {- StrategyFormLauncherPanelBox,- StrategyFormLauncherPanelStack,-} from "./StrategyFormLauncherPanel.styled";+import S from "./StrategyFormLauncherPanel.module.css";export const StrategyFormLauncherPanel = ({configs,@@ -43,11 +41,14 @@ export const StrategyFormLauncherPanel = ({});return (- <Panel+ <Box+ component="section"role="group"- style={{ backgroundColor: "var(--mb-color-background-secondary)" }}+ h="100%"+ bg="background-secondary"+ className={S.root}>- <StrategyFormLauncherPanelBox>+ <Box className={cx(S.section, S.divided)}><StrategyFormLauncherforId={rootId}title={t`Default policy`}@@ -56,8 +57,8 @@ export const StrategyFormLauncherPanel = ({updateTargetId={updateTargetId}isFormDirty={isStrategyFormDirty}/>- </StrategyFormLauncherPanelBox>- <StrategyFormLauncherPanelStack>+ </Box>+ <Stack className={cx(S.section, S.stack)}>{databases?.map((db) => (<StrategyFormLauncherforId={db.id}@@ -69,7 +70,7 @@ export const StrategyFormLauncherPanel = ({key={`database_${db.id}`}/>))}- </StrategyFormLauncherPanelStack>+ </Stack><FormProviderinitialValues={{}}onSubmit={resetAllToDefault}@@ -77,6 +78,6 @@ export const StrategyFormLauncherPanel = ({>{shouldShowResetButton && <ResetButtonContainer />}</FormProvider>- </Panel>+ </Box>);};diff --git a/enterprise/frontend/src/metabase-enterprise/caching/constants.ts b/enterprise/frontend/src/metabase-enterprise/caching/constants.tsindex fb9855fdcac..467a7808e90 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/constants.ts+++ b/enterprise/frontend/src/metabase-enterprise/caching/constants.ts@@ -17,41 +17,41 @@ export const durationUnits = new Set(Object.values(CacheDurationUnit).map(String),);-const scheduleStrategyValidationSchema = Yup.object({- type: Yup.string().equals(["schedule"]),- schedule: Yup.string()- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045- .required(t`A cron expression is required`)- .default(defaultCron),- refresh_automatically: Yup.boolean().nullable().default(false),-});+const getScheduleStrategyValidationSchema = () =>+ Yup.object({+ type: Yup.string().equals(["schedule"]),+ schedule: Yup.string()+ .required(t`A cron expression is required`)+ .default(defaultCron),+ refresh_automatically: Yup.boolean().nullable().default(false),+ });-const durationStrategyValidationSchema = Yup.object({- type: Yup.string().equals(["duration"]),- duration: getPositiveIntegerSchema().default(24),- unit: Yup.string().test(- "is-duration-unit",- "${path} is not a valid duration",- (value) => !!value && durationUnits.has(value),- ),- refresh_automatically: Yup.boolean().nullable().default(false),-});+const getDurationStrategyValidationSchema = () =>+ Yup.object({+ type: Yup.string().equals(["duration"]),+ duration: getPositiveIntegerSchema().default(24),+ unit: Yup.string().test(+ "is-duration-unit",+ "${path} is not a valid duration",+ (value) => !!value && durationUnits.has(value),+ ),+ refresh_automatically: Yup.boolean().nullable().default(false),+ });-/** Caching strategies available on EE only */+/** Caching strategies available on EE only. Labels are functions so ttag+ * runs after the locale is set (see `StrategyLabel`). */export const enterpriseOnlyCachingStrategies: Record<string, StrategyData> = {schedule: {- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045- label: t`Schedule: pick when to regularly invalidate the cache`,- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045- shortLabel: t`Scheduled`,- validationSchema: scheduleStrategyValidationSchema,+ label: () => t`Schedule`,+ description: () => t`Pick when to regularly invalidate the cache`,+ shortLabel: () => t`Scheduled`,+ validationSchema: getScheduleStrategyValidationSchema,},duration: {- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045- label: t`Duration: keep the cache for a number of hours`,- validationSchema: durationStrategyValidationSchema,- // eslint-disable-next-line ttag/no-module-declaration -- see metabase#55045- shortLabel: t`Duration`,+ label: () => t`Duration`,+ description: () => t`Keep the cache for a number of hours`,+ validationSchema: getDurationStrategyValidationSchema,+ shortLabel: () => t`Duration`,},};diff --git a/enterprise/frontend/src/metabase-enterprise/caching/index.tsx b/enterprise/frontend/src/metabase-enterprise/caching/index.tsxindex a86482f2904..52e6d951ae4 100644--- a/enterprise/frontend/src/metabase-enterprise/caching/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/caching/index.tsx@@ -4,6 +4,7 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";import { DashboardAndQuestionCachingTab } from "./components/DashboardAndQuestionCachingTab";import { GranularControlsExplanation } from "./components/GranularControlsExplanation";import { InvalidateNowButton } from "./components/InvalidateNowButton";+import { MetricCachingModal } from "./components/MetricCachingModal";import { PreemptiveCachingSwitch } from "./components/PreemptiveCachingSwitch";import { SidebarCacheForm } from "./components/SidebarCacheForm";import { SidebarCacheSection } from "./components/SidebarCacheSection";@@ -13,7 +14,6 @@ import {enterpriseOnlyCachingStrategies,getEnterprisePerformanceTabMetadata,} from "./constants";-import { MetricCachingPage } from "./pages/MetricCachingPage";import { hasQuestionCacheSection } from "./utils";/**@@ -41,7 +41,7 @@ export function initializePlugin() {PLUGIN_CACHING.StrategyEditorForQuestionsAndDashboards =StrategyEditorForQuestionsAndDashboards;PLUGIN_CACHING.getTabMetadata = getEnterprisePerformanceTabMetadata;- PLUGIN_CACHING.MetricCachingPage = MetricCachingPage;+ PLUGIN_CACHING.MetricCachingModal = MetricCachingModal;}if (hasPremiumFeature("cache_preemptive")) {diff --git a/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsx b/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsxdeleted file mode 100644index 6284fe865e0..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/MetricCachingPage.tsx+++ /dev/null@@ -1,98 +0,0 @@-import { useMemo } from "react";-import { t } from "ttag";-import _ from "underscore";--import { StrategyForm } from "metabase/admin/performance/components/StrategyForm";-import { useCacheConfigs } from "metabase/admin/performance/hooks/useCacheConfigs";-import { useConfirmIfFormIsDirty } from "metabase/admin/performance/hooks/useConfirmIfFormIsDirty";-import { useSaveStrategy } from "metabase/admin/performance/hooks/useSaveStrategy";-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import CS from "metabase/css/core/index.css";-import { PageContainer } from "metabase/data-studio/common/components/PageContainer";-import { useLoadCardWithMetadata } from "metabase/data-studio/common/hooks/use-load-card-with-metadata";-import { MetricPageShell } from "metabase/metrics/components/MetricPageShell";-import { metricUrls as defaultUrls } from "metabase/metrics/urls";-import type { MetricSettingsPageProps } from "metabase/plugins/oss/caching";-import { Card, Center } from "metabase/ui";-import * as Urls from "metabase/urls";-import { getItemName } from "metabase-enterprise/caching/components/utils";-import Question from "metabase-lib/v1/Question";-import type { CacheableModel } from "metabase-types/api";--const cachingModel: CacheableModel[] = ["question"];--export function MetricCachingPage({- params,- urls = defaultUrls,- renderBreadcrumbs,- showAppSwitcher,- showDataStudioLink = true,-}: MetricSettingsPageProps) {- const cardId = Urls.extractEntityId(params.cardId);- const {- card,- isLoading: isLoadingCard,- error: cardError,- } = useLoadCardWithMetadata(cardId);- const question = useMemo(() => card && new Question(card), [card]);-- const {- configs,- isLoading: isLoadingConfigs,- error: configsError,- } = useCacheConfigs({- model: cachingModel,- id: cardId,- });-- const { savedStrategy } = useMemo(() => {- const targetConfig = _.findWhere(configs ?? [], { model_id: cardId });- const savedStrategy = targetConfig?.strategy;- return { savedStrategy };- }, [configs, cardId]);-- const saveStrategy = useSaveStrategy(cardId ?? null, "metric");-- const { confirmationModal, setIsStrategyFormDirty } =- useConfirmIfFormIsDirty();-- const isLoading = isLoadingCard || isLoadingConfigs;- const error = cardError || configsError;-- if (isLoading || error != null || card == null) {- return (- <Center h="100%">- <LoadingAndErrorWrapper loading={isLoading} error={error} />- </Center>- );- }-- return (- <PageContainer pos="relative" data-testid="metric-caching" gap="xl">- <MetricPageShell- card={card}- urls={urls}- renderBreadcrumbs={renderBreadcrumbs}- showAppSwitcher={showAppSwitcher}- showDataStudioLink={showDataStudioLink}- />- {question ? (- <Card withBorder flex={1} p={0}>- <StrategyForm- targetId={question.id()}- targetModel="metric"- targetName={getItemName("question", question)}- setIsDirty={setIsStrategyFormDirty}- saveStrategy={saveStrategy}- savedStrategy={savedStrategy}- shouldAllowInvalidation- shouldShowName={false}- buttonLabels={{ save: t`Save`, discard: t`Cancel` }}- classNames={{ formBox: CS.pt4 }}- />- {confirmationModal}- </Card>- ) : null}- </PageContainer>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/index.ts b/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/index.tsdeleted file mode 100644index d0da7e1096b..00000000000--- a/enterprise/frontend/src/metabase-enterprise/caching/pages/MetricCachingPage/index.ts+++ /dev/null@@ -1 +0,0 @@-export { MetricCachingPage } from "./MetricCachingPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricCachingPage/DataStudioMetricCachingPage.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricCachingPage/DataStudioMetricCachingPage.tsxdeleted file mode 100644index 064c62ff324..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricCachingPage/DataStudioMetricCachingPage.tsx+++ /dev/null@@ -1,24 +0,0 @@-import type { MetricPageParams } from "metabase/metrics/types";-import { PLUGIN_CACHING } from "metabase/plugins";--import { DataStudioMetricBreadcrumbs } from "../../components/DataStudioMetricBreadcrumbs";-import { dataStudioMetricUrls } from "../../urls";--interface DataStudioMetricCachingPageProps {- params: MetricPageParams;-}--export function DataStudioMetricCachingPage({- params,-}: DataStudioMetricCachingPageProps) {- const CachingPage = PLUGIN_CACHING.MetricCachingPage;- return (- <CachingPage- params={params}- urls={dataStudioMetricUrls}- showAppSwitcher- showDataStudioLink={false}- renderBreadcrumbs={(card) => <DataStudioMetricBreadcrumbs card={card} />}- />- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricCachingPage/index.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricCachingPage/index.tsdeleted file mode 100644index ddc713cfc57..00000000000--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/pages/DataStudioMetricCachingPage/index.ts+++ /dev/null@@ -1 +0,0 @@-export { DataStudioMetricCachingPage } from "./DataStudioMetricCachingPage";diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsxindex 4ed2eadcc38..e3bd3a4d6ef 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/routes.tsx@@ -1,9 +1,8 @@import { IndexRoute, Route } from "react-router";-import { PLUGIN_CACHING, PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";import { DataStudioMetricAboutPage } from "./pages/DataStudioMetricAboutPage";-import { DataStudioMetricCachingPage } from "./pages/DataStudioMetricCachingPage";import { DataStudioMetricDependenciesPage } from "./pages/DataStudioMetricDependenciesPage";import { DataStudioMetricHistoryPage } from "./pages/DataStudioMetricHistoryPage";import { DataStudioMetricOverviewPage } from "./pages/DataStudioMetricOverviewPage";@@ -26,9 +25,6 @@ export function getDataStudioMetricRoutes() {</Route>)}<Route path=":cardId/history" component={DataStudioMetricHistoryPage} />- {PLUGIN_CACHING.isGranularCachingEnabled() && (- <Route path=":cardId/caching" component={DataStudioMetricCachingPage} />- )}</Route>);}diff --git a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.tsindex bf745b3318a..7301cc9c8ae 100644--- a/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts+++ b/enterprise/frontend/src/metabase-enterprise/data-studio/library/metrics/urls.ts@@ -6,7 +6,6 @@ export const dataStudioMetricUrls: MetricUrls = {overview: Urls.dataStudioMetricOverview,query: Urls.dataStudioMetricQuery,dependencies: Urls.dataStudioMetricDependencies,- caching: Urls.dataStudioMetricCaching,history: Urls.dataStudioMetricHistory,database: (databaseId) => Urls.dataStudioData({ databaseId }),};diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.css b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.cssnew file mode 100644index 00000000000..2fb3ec41b79--- /dev/null+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.css@@ -0,0 +1,22 @@+.scrollableLayout {+ overflow: hidden;+}++.roundedBox {+ display: grid;+ grid-template-columns: minmax(5rem, 30rem);+ overflow: hidden;+ border-radius: 1rem;+}++.roundedBoxTwoColumns {+ grid-template-columns: minmax(5rem, 30rem) minmax(5rem, auto);+}++.formPanel {+ overflow-y: auto;+}++.formPanelWithLeftBorder {+ border-left: 1px solid var(--mb-color-border);+}diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.styled.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.styled.tsxdeleted file mode 100644index cbb0a4582a2..00000000000--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.styled.tsx+++ /dev/null@@ -1,28 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import { css } from "@emotion/react";-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--export const Panel = styled.section<{ hasLeftBorder?: boolean }>`- overflow-y: auto;- background-color: var(--mb-color-background-primary);- height: 100%;-- ${(props) =>- props.hasLeftBorder &&- css`- border-left: 1px solid var(--mb-color-border);- `}-`;--export const RoundedBox = styled.div<{ twoColumns?: boolean }>`- margin-bottom: 1rem;- width: 100%;- display: grid;- grid-template-columns: minmax(5rem, 30rem) ${(props) =>- props.twoColumns ? "minmax(5rem, auto)" : ""};- max-width: ${(props) => (props.twoColumns ? "100%" : "30rem")};- overflow: hidden;- border-radius: 1rem;- border: 2px solid var(--mb-color-border);-`;diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsxindex d8ec55e5b8f..f98939bce7e 100644--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx@@ -1,3 +1,5 @@+import cx from "classnames";+import type { ReactNode } from "react";import { useEffect, useMemo, useState } from "react";import { t } from "ttag";import { findWhere } from "underscore";@@ -7,7 +9,7 @@ import { UpsellCacheConfig } from "metabase/admin/upsells";import { useListDatabasesQuery } from "metabase/api";import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";import { PLUGIN_CACHING } from "metabase/plugins";-import { Flex } from "metabase/ui";+import { Box, Flex } from "metabase/ui";import type { CacheableModel } from "metabase-types/api";import { CacheDurationUnit } from "metabase-types/api";@@ -17,9 +19,29 @@ import { useConfirmIfFormIsDirty } from "../hooks/useConfirmIfFormIsDirty";import { useSaveStrategy } from "../hooks/useSaveStrategy";import type { UpdateTargetId } from "../types";-import { Panel, RoundedBox } from "./StrategyEditorForDatabases.styled";+import S from "./StrategyEditorForDatabases.module.css";import { StrategyForm } from "./StrategyForm";+/** Rounded outer container for the two-column launcher + form layout. */+function RoundedBox({+ children,+ twoColumns,+}: {+ children: ReactNode;+ twoColumns?: boolean;+}) {+ return (+ <Box+ w="100%"+ maw={twoColumns ? "100%" : "30rem"}+ bd="2px solid var(--mb-color-border)"+ className={cx(S.roundedBox, { [S.roundedBoxTwoColumns]: twoColumns })}+ >+ {children}+ </Box>+ );+}+export const StrategyEditorForDatabases: React.FC = () => {const { canOverrideRootStrategy } = PLUGIN_CACHING;@@ -132,7 +154,7 @@ export const StrategyEditorForDatabases: React.FC = () => {h="calc(100vh - 7rem)">{confirmationModal}- <Flex gap="xl" style={{ overflow: "hidden" }}>+ <Flex gap="xl" className={S.scrollableLayout}><RoundedBox twoColumns={canOverrideRootStrategy}>{canOverrideRootStrategy && (<PLUGIN_CACHING.StrategyFormLauncherPanel@@ -144,7 +166,14 @@ export const StrategyEditorForDatabases: React.FC = () => {shouldShowResetButton={shouldShowResetButton}/>)}- <Panel hasLeftBorder={canOverrideRootStrategy}>+ <Box+ component="section"+ bg="background-primary"+ h="100%"+ className={cx(S.formPanel, {+ [S.formPanelWithLeftBorder]: canOverrideRootStrategy,+ })}+ >{targetId !== null && (<StrategyFormtargetId={targetId}@@ -157,7 +186,7 @@ export const StrategyEditorForDatabases: React.FC = () => {shouldShowName={targetId !== rootId}/>)}- </Panel>+ </Box></RoundedBox><UpsellCacheConfig location="performance-data_cache" /></Flex>diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.module.css b/frontend/src/metabase/admin/performance/components/StrategyForm.module.cssnew file mode 100644index 00000000000..c6a17d1fe73--- /dev/null+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.module.css@@ -0,0 +1,27 @@+.strategyOption label {+ cursor: pointer;+}++.radioDescription {+ font-size: var(--mantine-font-size-md);+ line-height: 1.25rem;+ color: var(--mb-color-text-secondary);+}++.form {+ flex-direction: column;+ flex-grow: 1;+ min-height: 0;+ overflow: auto;+}++.formFixedHeight {+ overflow: hidden;+}++.modalBody {+ flex: 1;+ overflow-y: auto;+ min-height: 0;+ margin-top: var(--mantine-spacing-xl);+}diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.styled.tsx b/frontend/src/metabase/admin/performance/components/StrategyForm.styled.tsxdeleted file mode 100644index f837c1dc9c9..00000000000--- a/frontend/src/metabase/admin/performance/components/StrategyForm.styled.tsx+++ /dev/null@@ -1,37 +0,0 @@-// eslint-disable-next-line no-restricted-imports-import styled from "@emotion/styled";--import { FixedSizeIcon, Group, Loader } from "metabase/ui";--export const LoaderInButton = styled(Loader)`- position: relative;- top: 1px;-`;--export const IconInButton = styled(FixedSizeIcon)`- position: relative;- top: 1px;-`;--export const FormWrapper = styled.div`- height: 100%;- display: flex;- flex-direction: column;-`;--export const StyledFormButtonsGroup = styled(Group)<{ isInSidebar?: boolean }>`- padding-block: 1rem;- gap: 1rem;- ${({ isInSidebar }) =>- isInSidebar- ? `- justify-content: flex-end;- padding-inline: 1rem;- padding-bottom: 0;- `- : `- background-color: var(--mb-color-background-primary);- border-top: 1px solid var(--mb-color-border);- padding-inline: 2.5rem;- `}-`;diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx b/frontend/src/metabase/admin/performance/components/StrategyForm.tsxindex 16aef5169e5..1d6139554b0 100644--- a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx@@ -24,8 +24,10 @@ import {Box,Button,FixedSizeIcon,+ Flex,Group,Icon,+ Loader,Radio,Stack,Text,@@ -47,18 +49,34 @@ import { useIsFormPending } from "../hooks/useIsFormPending";import { isModelWithClearableCache } from "../types";import { getDefaultValueForField, getLabelString } from "../utils";-import Styles from "./PerformanceApp.module.css";-import {- FormWrapper,- LoaderInButton,- StyledFormButtonsGroup,-} from "./StrategyForm.styled";+import PerformanceAppStyles from "./PerformanceApp.module.css";+import S from "./StrategyForm.module.css";interface ButtonLabels {save: string;discard: string;}+export type StrategyFormLayout = "default" | "sidebar" | "modal";++// Module-level so initialValues stay reference-stable across renders.+const ROOT_DEFAULT_STRATEGY: CacheStrategy = { type: "nocache" };+const INHERIT_DEFAULT_STRATEGY: CacheStrategy = { type: "inherit" };++interface StrategyFormProps {+ targetId: number | null;+ targetModel: CacheableModel;+ targetName: string;+ setIsDirty: (isDirty: boolean) => void;+ saveStrategy: (values: CacheStrategy) => Promise<void>;+ savedStrategy?: CacheStrategy;+ shouldAllowInvalidation?: boolean;+ shouldShowName?: boolean;+ onReset?: () => void;+ buttonLabels?: ButtonLabels;+ layout?: StrategyFormLayout;+}+export const StrategyForm = ({targetId,targetModel,@@ -69,37 +87,19 @@ export const StrategyForm = ({shouldAllowInvalidation = false,shouldShowName = true,onReset,- isInSidebar = false,- classNames,- buttonLabels = isInSidebar+ layout = "default",+ buttonLabels = layout === "default"? {- save: t`Save`,- discard: t`Cancel`,- }- : {save: t`Save changes`,discard: t`Discard changes`,+ }+ : {+ save: t`Save`,+ discard: t`Cancel`,},-}: {- targetId: number | null;- targetModel: CacheableModel;- targetName: string;- setIsDirty: (isDirty: boolean) => void;- saveStrategy: (values: CacheStrategy) => Promise<void>;- savedStrategy?: CacheStrategy;- shouldAllowInvalidation?: boolean;- shouldShowName?: boolean;- onReset?: () => void;- buttonLabels?: ButtonLabels;- isInSidebar?: boolean;- classNames?: { formBox?: string };-}) => {- const defaultStrategy: CacheStrategy = useMemo(- () => ({- type: targetId === rootId ? "nocache" : "inherit",- }),- [targetId],- );+}: StrategyFormProps) => {+ const defaultStrategy =+ targetId === rootId ? ROOT_DEFAULT_STRATEGY : INHERIT_DEFAULT_STRATEGY;const initialValues = savedStrategy ?? defaultStrategy;@@ -120,9 +120,9 @@ export const StrategyForm = ({shouldAllowInvalidation={shouldAllowInvalidation}shouldShowName={shouldShowName}buttonLabels={buttonLabels}- isInSidebar={isInSidebar}+ layout={layout}strategyType={initialValues.type}- classNames={classNames}+ onDiscard={onReset}/></FormProvider>);@@ -131,8 +131,8 @@ export const StrategyForm = ({/** Don't count the addition/deletion of a default value as a reason to consider the form dirty */const isFormDirty = (values: CacheStrategy, initialValues: CacheStrategy) => {const fieldNames = [...Object.keys(values), ...Object.keys(initialValues)];- const defaultValues = _.object(- _.map(fieldNames, (fieldName) => [+ const defaultValues = Object.fromEntries(+ fieldNames.map((fieldName) => [fieldName,getDefaultValueForField(values.type, fieldName),]),@@ -140,17 +140,15 @@ const isFormDirty = (values: CacheStrategy, initialValues: CacheStrategy) => {const initialValuesWithDefaults = { ...defaultValues, ...initialValues };const valuesWithDefaults = { ...defaultValues, ...values };// If the default value is a number and the value is a string, coerce the value to a number- const coercedValuesWithDefaults = _.chain(valuesWithDefaults)- .pairs()- .map(([key, value]) => [+ const coercedValuesWithDefaults = Object.fromEntries(+ Object.entries(valuesWithDefaults).map(([key, value]) => [key,typeof getDefaultValueForField(values.type, key) === "number" &&typeof value === "string"? Number(value): value,- ])- .object()- .value();+ ]),+ );return !_.isEqual(initialValuesWithDefaults, coercedValuesWithDefaults);};@@ -162,8 +160,8 @@ const StrategyFormBody = ({shouldAllowInvalidation,shouldShowName = true,buttonLabels,- isInSidebar,- classNames,+ layout,+ onDiscard,}: {targetId: number | null;targetModel: CacheableModel;@@ -173,8 +171,8 @@ const StrategyFormBody = ({shouldAllowInvalidation: boolean;shouldShowName?: boolean;buttonLabels: ButtonLabels;- isInSidebar?: boolean;- classNames?: { formBox?: string };+ layout: StrategyFormLayout;+ onDiscard?: () => void;}) => {const { values, initialValues, setFieldValue } =useFormikContext<CacheStrategy>();@@ -219,29 +217,32 @@ const StrategyFormBody = ({}, [values, setFieldValue, setStatus]);return (- <FormWrapper>+ <Flex direction="column" h="100%" mih={0}><Formdisplay="flex"- style={{- overflow: isInSidebar ? undefined : "auto",- flexDirection: "column",- flexGrow: 1,- }}+ className={cx(S.form, { [S.formFixedHeight]: layout !== "default" })}aria-labelledby={headingId}data-testid={`strategy-form-for-${targetModel}-${targetId}`}>+ {layout === "modal" && (+ <Box pt="md">+ <StrategySelectorHeading headingId={headingId} />+ </Box>+ )}<Box- className={cx(Styles.FormBox, classNames?.formBox, {- [Styles.FormBoxSidebar]: isInSidebar,+ className={cx({+ [PerformanceAppStyles.FormBox]: layout !== "modal",+ [PerformanceAppStyles.FormBoxSidebar]: layout === "sidebar",+ [S.modalBody]: layout === "modal",})}>{shouldShowName && (- <Box lh="1rem" pt="md" color="text-secondary">+ <Box lh="1rem" pt="md" c="text-secondary"><Group gap="sm">{targetModel === "database" && (<FixedSizeIcon name="database" c="inherit" />)}- <Text fw="bold" py="1rem">+ <Text fw="bold" py="md">{targetName}</Text></Group>@@ -252,6 +253,7 @@ const StrategyFormBody = ({targetId={targetId}model={targetModel}headingId={headingId}+ showHeading={layout !== "modal"}/>{selectedStrategyType === "ttl" && (<>@@ -310,25 +312,38 @@ const StrategyFormBody = ({targetName={targetName}shouldAllowInvalidation={shouldAllowInvalidation}buttonLabels={buttonLabels}- isInSidebar={isInSidebar}+ layout={layout}dirty={dirty}+ onDiscard={onDiscard}/></Form>- </FormWrapper>+ </Flex>);};const FormButtonsGroup = ({children,- isInSidebar,+ layout,}: {children: ReactNode;- isInSidebar?: boolean;+ layout: StrategyFormLayout;}) => {return (- <StyledFormButtonsGroup isInSidebar={isInSidebar}>+ <Group+ py="md"+ gap="md"+ justify={layout === "sidebar" ? "flex-end" : undefined}+ px={layout === "sidebar" ? "md" : "2.5rem"}+ pb={layout === "sidebar" ? 0 : undefined}+ bg={layout === "sidebar" ? undefined : "background-primary"}+ style={+ layout === "sidebar"+ ? undefined+ : { borderTop: "1px solid var(--mb-color-border)" }+ }+ >{children}- </StyledFormButtonsGroup>+ </Group>);};@@ -338,8 +353,9 @@ type FormButtonsProps = {shouldAllowInvalidation: boolean;targetName?: string;buttonLabels: ButtonLabels;- isInSidebar?: boolean;+ layout: StrategyFormLayout;dirty: boolean;+ onDiscard?: () => void;};const FormButtons = ({@@ -348,38 +364,69 @@ const FormButtons = ({shouldAllowInvalidation,targetName,buttonLabels,- isInSidebar,+ layout,dirty,+ onDiscard,}: FormButtonsProps) => {if (targetId === rootId) {shouldAllowInvalidation = false;}+ const canInvalidate =+ shouldAllowInvalidation &&+ isModelWithClearableCache(targetModel) &&+ targetId !== null &&+ !!targetName;+const { isFormPending, wasFormRecentlyPending } = useIsFormPending();+ if (layout === "modal") {+ return (+ <Group+ justify={canInvalidate ? "space-between" : "flex-end"}+ wrap="nowrap"+ mt="xl"+ gap="md"+ >+ {canInvalidate && (+ <PLUGIN_CACHING.InvalidateNowButton+ targetId={targetId}+ targetModel={targetModel}+ targetName={targetName}+ />+ )}+ <Group gap="md" wrap="nowrap">+ <Button onClick={onDiscard}>{buttonLabels.discard}</Button>+ <FormSubmitButton+ h="2.5rem"+ label={buttonLabels.save}+ variant="filled"+ data-testid="strategy-form-submit-button"+ />+ </Group>+ </Group>+ );+ }+const isSavingPossible = dirty || isFormPending || wasFormRecentlyPending;if (isSavingPossible) {return (- <FormButtonsGroup isInSidebar={isInSidebar}>+ <FormButtonsGroup layout={layout}><SaveAndDiscardButtonsdirty={dirty}isFormPending={isFormPending}buttonLabels={buttonLabels}- isInSidebar={isInSidebar}+ layout={layout}+ onDiscard={onDiscard}/></FormButtonsGroup>);}- if (- shouldAllowInvalidation &&- isModelWithClearableCache(targetModel) &&- targetId &&- targetName- ) {+ if (canInvalidate) {return (- <FormButtonsGroup isInSidebar={isInSidebar}>+ <FormButtonsGroup layout={layout}><PLUGIN_CACHING.InvalidateNowButtontargetId={targetId}targetModel={targetModel}@@ -431,44 +478,92 @@ const SaveAndDiscardButtons = ({dirty,isFormPending,buttonLabels,- isInSidebar,+ layout,+ onDiscard,}: {dirty: boolean;isFormPending: boolean;buttonLabels: ButtonLabels;- isInSidebar?: boolean;+ layout: StrategyFormLayout;+ onDiscard?: () => void;}) => {return (<>- <Button disabled={!dirty || isFormPending} type="reset">- {buttonLabels.discard}- </Button>+ {layout === "sidebar" ? (+ // Sidebar Cancel closes the sidesheet; consumer wraps the dirty-confirm.+ <Button onClick={onDiscard}>{buttonLabels.discard}</Button>+ ) : (+ <Button disabled={!dirty || isFormPending} type="reset">+ {buttonLabels.discard}+ </Button>+ )}<FormSubmitButton- miw={isInSidebar ? undefined : "10rem"}- h="40px"+ miw={layout === "sidebar" ? undefined : "10rem"}+ h="2.5rem"label={buttonLabels.save}successLabel={<Group gap="xs"><Icon name="check" /> {t`Saved`}</Group>}- activeLabel={<LoaderInButton size="1rem" />}+ activeLabel={<Loader size="1rem" pos="relative" top={1} />}variant="filled"data-testid="strategy-form-submit-button"- className="strategy-form-submit-button"/></>);};+export const StrategySelectorHeading = ({+ headingId,+}: {+ headingId: string;+}) => (+ <Stack gap="xs">+ <Text lh="1.25rem" fw="bold" fz="md" id={headingId}>+ {t`Select the cache invalidation policy`}+ </Text>+ <Text lh="1.25rem" fw="normal" fz="md" c="text-secondary">+ {t`This determines how long cached results will be stored.`}+ </Text>+ </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,headingId,+ showHeading = true,}: {targetId: number | null;model?: CacheableModel;headingId: string;+ showHeading?: boolean;}) => {const { strategies } = PLUGIN_CACHING;@@ -479,53 +574,29 @@ const StrategySelector = ({}, [targetId, strategies]);return (- <section>+ <section aria-labelledby={headingId}><FormRadioGrouplabel={- <Stack gap="xs">- <Text lh="1rem" color="text-secondary" id={headingId}>- {t`Select the cache invalidation policy`}- </Text>- <Text lh="1rem" fw="normal" size="sm" color="text-secondary">- {t`This determines how long cached results will be stored.`}- </Text>- </Stack>+ showHeading ? (+ <StrategySelectorHeading headingId={headingId} />+ ) : undefined}name="type">- <Stack mt="md" gap="md">- {_.map(availableStrategies, (option, name) => {- const labelString = getLabelString(option.label, model);- /** Special colon sometimes used in Asian languages */- const wideColon = ":";- const colon = labelString.includes(wideColon) ? wideColon : ":";- const optionLabelParts = labelString.split(colon);- const optionLabelFormatted = (- <>- <strong>{optionLabelParts[0]}</strong>- {optionLabelParts[1] ? (- <>- {colon} {optionLabelParts[1]}- </>- ) : null}- </>- );- return (- <Radio- value={name}- key={name}- label={optionLabelFormatted}- autoFocus={values.type === name}- role="radio"- styles={{- label: {- paddingLeft: undefined,- paddingInlineStart: ".5rem",- },- }}- />- );- })}+ <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></section>diff --git a/frontend/src/metabase/admin/performance/constants/complex.ts b/frontend/src/metabase/admin/performance/constants/complex.tsindex 0c10783bb1d..461fd7e09a0 100644--- a/frontend/src/metabase/admin/performance/constants/complex.ts+++ b/frontend/src/metabase/admin/performance/constants/complex.ts@@ -72,24 +72,29 @@ export const strategyValidationSchema = Yup.object().test(export const strategies = {inherit: {- label: (model?: CacheableModel) => {+ // NOTE: We use functions for labels because otherwise t doesn't work properly+ label: () => t`Default`,+ description: (model?: CacheableModel) => {switch (model) {+ case "database":+ return t`Use the default policy`;case "dashboard":- return t`Use default: each question will use its own policy or the database policy`;+ return t`Each question will use its own policy or the database policy`;case "question":- return t`Use default: use the database or dashboard policy`;+ case "metric":+ return t`Use the database or dashboard policy`;default:- return t`Use default`;+ return undefined;}},- // NOTE: We use functions for labels because otherwise t doesn't work properly- shortLabel: () => t`Use default`,+ shortLabel: () => t`Default`,validationSchema: inheritStrategyValidationSchema,},// NOTE: The strategy is called 'ttl' in the BE, but we've renamed it 'Adaptive' in the FEttl: {- label: () =>- t`Adaptive: use a query’s average execution time to determine how long to cache its results`,+ label: () => t`Adaptive`,+ description: () =>+ t`Use a query’s average execution time to determine how long to cache its results`,shortLabel: () => t`Adaptive`,validationSchema: getAdaptiveStrategyValidationSchema,},diff --git a/frontend/src/metabase/admin/performance/types.ts b/frontend/src/metabase/admin/performance/types.tsindex 85e22d90346..7b5648f411c 100644--- a/frontend/src/metabase/admin/performance/types.ts+++ b/frontend/src/metabase/admin/performance/types.ts@@ -7,12 +7,13 @@ export type UpdateTargetId = (isFormDirty: boolean,) => void;-export type StrategyLabel = string | ((model?: CacheableModel) => string);+export type StrategyLabel =+ | string+ | ((model?: CacheableModel) => string | undefined);export type StrategyData = {- /**- * The human-readable label for the strategy, which can be a string or a function that takes a model and returns a string */label: StrategyLabel;+ description?: StrategyLabel;shortLabel?: StrategyLabel;/** Schema used to validate the value. This field can optionally be set to a function that returns a schema. This helps ensure that calls to ttag functions do not run until after the locale is set */validationSchema: AnySchema | (() => AnySchema);diff --git a/frontend/src/metabase/admin/performance/utils.unit.spec.ts b/frontend/src/metabase/admin/performance/utils.unit.spec.tsindex 11e8a2e3355..2f380918a83 100644--- a/frontend/src/metabase/admin/performance/utils.unit.spec.ts+++ b/frontend/src/metabase/admin/performance/utils.unit.spec.ts@@ -18,11 +18,11 @@ describe("getShortStrategyLabel", () => {expect(result).toBe("Adaptive");});- it("can abbreviate a 'Use default' aka inherit strategy", () => {+ it("can abbreviate a 'Default' aka inherit strategy", () => {const strategy: InheritStrategy = {type: "inherit",};const result = getShortStrategyLabel(strategy);- expect(result).toBe("Use default");+ expect(result).toBe("Default");});});diff --git a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.ts b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.tsindex b09407b5c26..a982a2e934a 100644--- a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.ts+++ b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/tests/premium.unit.spec.ts@@ -50,7 +50,7 @@ describe("DashboardSettingsSidebar > premium enterprise", () => {enterprisePlugins: ["audit_app", "caching"],});- await userEvent.click(await screen.findByText("Use default"));+ await userEvent.click(await screen.findByText("Default"));expect(await screen.findByText("Caching settings")).toBeInTheDocument();});diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsxindex 1de834b25a9..3d8a103b948 100644--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.tsx@@ -7,11 +7,10 @@ import {PaneHeaderTabs,} from "metabase/data-studio/common/components/PaneHeader";import { isNumericMetric } from "metabase/metrics/utils/validation";-import { PLUGIN_CACHING, PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";import { useSelector } from "metabase/redux";import { getMetadata } from "metabase/selectors/metadata";import * as Lib from "metabase-lib";-import Question from "metabase-lib/v1/Question";import type Metadata from "metabase-lib/v1/metadata/Metadata";import type { Card } from "metabase-types/api";@@ -71,18 +70,6 @@ function getTabs(});}- const isCacheableQuestion =- card.can_write &&- PLUGIN_CACHING.isGranularCachingEnabled() &&- PLUGIN_CACHING.hasQuestionCacheSection(new Question(card));-- if (isCacheableQuestion) {- tabs.push({- label: t`Caching`,- to: urls.caching(card.id),- });- }-tabs.push({label: t`History`,to: urls.history(card.id),diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsxindex 5517d8ec536..306b43091f9 100644--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricTabs/MetricTabs.unit.spec.tsx@@ -25,7 +25,6 @@ const urls: MetricUrls = {overview: (id) => `/metric/${id}/overview`,query: (id) => `/metric/${id}/query`,dependencies: (id) => `/metric/${id}/dependencies`,- caching: (id) => `/metric/${id}/caching`,history: (id) => `/metric/${id}/history`,};@@ -81,20 +80,19 @@ describe("MetricTabs", () => {).map((element) => element.textContent);}- it("should show the caching tab when the user has write access", async () => {+ it("does not show the caching tab in the tabs row regardless of write access", async () => {setup({ card: { can_write: true } });await waitFor(() => {expect(getTabLabels()).toEqual(["About","Overview","Definition",- "Caching","History",]);});});- it("should not show the caching tab when the user has no write access", async () => {+ it("does not show the caching tab when the user has no write access", async () => {setup({ card: { can_write: false } });await waitFor(() => {expect(getTabLabels()).toEqual([@@ -109,12 +107,7 @@ describe("MetricTabs", () => {it("should hide the overview tab when metric has no dimensions", async () => {setup({ hasDimensions: false });await waitFor(() => {- expect(getTabLabels()).toEqual([- "About",- "Definition",- "Caching",- "History",- ]);+ expect(getTabLabels()).toEqual(["About", "Definition", "History"]);});});diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.module.css b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.module.cssnew file mode 100644index 00000000000..6c77bc9bfe9--- /dev/null+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.module.css@@ -0,0 +1,3 @@+.moreOptionsButton {+ border: 1px solid var(--mb-color-border);+}diff --git a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsxindex 015c2c1d8e8..83e232ed6d4 100644--- a/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx+++ b/frontend/src/metabase/metrics/components/MetricHeader/MetricToolbar/MetricToolbar.tsx@@ -10,12 +10,12 @@ import {} from "metabase/api";import { ForwardRefLink } from "metabase/common/components/Link";import { AddToDashSelectDashModal } from "metabase/common/components/Pickers/AddToDashSelectDashModal";-import { ToolbarButton } from "metabase/common/components/ToolbarButton";import { canAccessDataStudio as canAccessDataStudioSelector } from "metabase/data-studio/selectors";import { isNumericMetric } from "metabase/metrics/utils/validation";import { QuestionAlertListModal } from "metabase/notifications/modals/QuestionAlertListModal";import {PLUGIN_AUDIT,+ PLUGIN_CACHING,PLUGIN_LIBRARY,PLUGIN_MODERATION,} from "metabase/plugins";@@ -26,7 +26,7 @@ import { useDispatch, useSelector } from "metabase/redux";import { openUrl } from "metabase/redux/app";import { getMetadata } from "metabase/selectors/metadata";import { canManageSubscriptions as canManageSubscriptionsSelector } from "metabase/selectors/user";-import { Button, Group, Icon, Menu } from "metabase/ui";+import { ActionIcon, Button, Group, Icon, Menu } from "metabase/ui";import * as Urls from "metabase/urls";import * as Lib from "metabase-lib";import Question from "metabase-lib/v1/Question";@@ -34,12 +34,15 @@ import type { Card } from "metabase-types/api";import type { MetricUrls } from "../../../types";+import S from "./MetricToolbar.module.css";+type MetricModalType =| "move"| "copy"| "archive"| "add-to-dashboard"- | "alert";+ | "alert"+ | "caching";interface MetricToolbarProps {card: Card;@@ -111,6 +114,11 @@ function MetricToolbarButtons({PLUGIN_LIBRARY.isLibraryCollectionType(card.collection?.type) &&canAccessDataStudio;+ const isCacheableQuestion =+ card.can_write &&+ PLUGIN_CACHING.isGranularCachingEnabled() &&+ PLUGIN_CACHING.hasQuestionCacheSection(new Question(card));+return (<Group wrap="nowrap" gap="sm">{isNumericMetric(card) && (@@ -125,7 +133,14 @@ function MetricToolbarButtons({)}<Menu position="bottom-end"><Menu.Target>- <ToolbarButton icon="ellipsis" aria-label={t`More options`} />+ <ActionIcon+ variant="default"+ size="lg"+ className={S.moreOptionsButton}+ aria-label={t`More options`}+ >+ <Icon name="ellipsis" />+ </ActionIcon></Menu.Target><Menu.Dropdown><Menu.Item@@ -178,6 +193,18 @@ function MetricToolbarButtons({</Menu.Item>)}+ {isCacheableQuestion && (+ <>+ <Menu.Divider role="separator" />+ <Menu.Item+ leftSection={<Icon name="sync" />}+ onClick={() => onOpenModal("caching")}+ >+ {t`Caching`}+ </Menu.Item>+ </>+ )}+{(PLUGIN_AUDIT.isEnabled || showDataStudioLink) && (<Menu.Divider role="separator" />)}@@ -251,6 +278,14 @@ function MetricModal({ card, urls, modalType, onClose }: MetricModalProps) {onClose={onClose}/>);+ case "caching":+ return (+ <PLUGIN_CACHING.MetricCachingModal+ cardId={card.id}+ cardName={card.name}+ onClose={onClose}+ />+ );default:return null;}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 b6d5d784200..5075a9610b5 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@@ -1,8 +1,13 @@import userEvent from "@testing-library/user-event";+import { Route } from "react-router";-import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";+import {+ setupEnterpriseOnlyPlugin,+ setupEnterprisePlugins,+} from "__support__/enterprise";import { setupBookmarksEndpoints } from "__support__/server-mocks/bookmark";import { setupListNotificationEndpoints } from "__support__/server-mocks/notification";+import { setupPerformanceEndpoints } from "__support__/server-mocks/performance";import { mockSettings } from "__support__/settings";import { renderWithProviders, screen, within } from "__support__/ui";import { createMockState } from "metabase/redux/store/mocks";@@ -32,7 +37,6 @@ const mockUrls = {overview: (id: number) => `/metric/${id}/overview`,query: (id: number) => `/metric/${id}/query`,dependencies: (id: number) => `/metric/${id}/dependencies`,- caching: (id: number) => `/metric/${id}/caching`,history: (id: number) => `/metric/${id}/history`,};@@ -42,6 +46,7 @@ interface SetupOpts {isAdmin?: boolean;showDataStudioLink?: boolean;collectionType?: CollectionType | null;+ withModal?: boolean;}function setup({@@ -50,6 +55,7 @@ function setup({isAdmin = false,showDataStudioLink = false,collectionType = null,+ withModal = false,}: SetupOpts = {}) {setupEnterpriseOnlyPlugin("library");@@ -59,6 +65,7 @@ function setup({const card = createMockCard({can_write: canWrite,collection: createMockCollection({ type: collectionType }),+ last_query_start: "2024-01-01T00:00:00Z",type: "metric",});@@ -67,7 +74,10 @@ function setup({});const settingValues = createMockSettings({- "token-features": createMockTokenFeatures({ library: true }),+ "token-features": createMockTokenFeatures({+ library: true,+ cache_granular_controls: true,+ }),});const state = createMockState({@@ -77,14 +87,23 @@ function setup({setupBookmarksEndpoints([]);setupListNotificationEndpoints({ card_id: card.id }, []);+ if (withModal) {+ setupPerformanceEndpoints([]);+ }- renderWithProviders(+ const toolbar = (<MetricToolbarcard={card}urls={mockUrls}showDataStudioLink={showDataStudioLink}- />,- { storeInitialState: state },+ />+ );++ renderWithProviders(+ withModal ? <Route path="/" component={() => toolbar} /> : toolbar,+ withModal+ ? { storeInitialState: state, withRouter: true, initialRoute: "/" }+ : { storeInitialState: state },);return { card };@@ -113,6 +132,16 @@ describe("MetricToolbar", () => {// Note: In OSS, canManageSubscriptions always returns true via the// PLUGIN_APPLICATION_PERMISSIONS default, so the alert item is always visible.+ beforeAll(() => {+ mockSettings({+ "token-features": createMockTokenFeatures({+ library: true,+ cache_granular_controls: true,+ }),+ });+ setupEnterprisePlugins();+ });+describe("menu items", () => {it("should show bookmark, move, duplicate, add-to-dashboard, alert, and trash for writable metric", async () => {setup({ canWrite: true });@@ -124,7 +153,8 @@ describe("MetricToolbar", () => {expect(screen.getByText("Add to a dashboard")).toBeInTheDocument();expect(screen.getByText("Create an alert")).toBeInTheDocument();expect(screen.getByText("Move to trash")).toBeInTheDocument();- expect(getDividers()).toHaveLength(2);+ // Bookmark/Move/Duplicate ─ Add-to-dash/Alert ─ Caching ─ Trash+ expect(getDividers()).toHaveLength(3);expectNoConsecutiveOrTrailingDividers();});@@ -146,7 +176,7 @@ describe("MetricToolbar", () => {await openMenu();expect(screen.queryByText("Duplicate")).not.toBeInTheDocument();- expect(getDividers()).toHaveLength(2);+ expect(getDividers()).toHaveLength(3);expectNoConsecutiveOrTrailingDividers();});@@ -159,7 +189,8 @@ describe("MetricToolbar", () => {await openMenu();expect(screen.getByText("Open in Data Studio")).toBeInTheDocument();- expect(getDividers()).toHaveLength(3);+ // Bookmark/Move/Duplicate ─ Add-to-dash/Alert ─ Caching ─ DataStudio/Insights ─ Trash+ expect(getDividers()).toHaveLength(4);expectNoConsecutiveOrTrailingDividers();});@@ -168,7 +199,7 @@ describe("MetricToolbar", () => {await openMenu();expect(screen.queryByText("Open in Data Studio")).not.toBeInTheDocument();- expect(getDividers()).toHaveLength(2);+ expect(getDividers()).toHaveLength(3);expectNoConsecutiveOrTrailingDividers();});@@ -181,7 +212,7 @@ describe("MetricToolbar", () => {await openMenu();expect(screen.queryByText("Open in Data Studio")).not.toBeInTheDocument();- expect(getDividers()).toHaveLength(2);+ expect(getDividers()).toHaveLength(3);expectNoConsecutiveOrTrailingDividers();});@@ -190,8 +221,38 @@ describe("MetricToolbar", () => {await openMenu();expect(screen.queryByText("Open in Data Studio")).not.toBeInTheDocument();- expect(getDividers()).toHaveLength(2);+ expect(getDividers()).toHaveLength(3);expectNoConsecutiveOrTrailingDividers();});++ it("should show 'Caching' as a menu item when the metric is cacheable", async () => {+ setup({ canWrite: true });+ await openMenu();++ expect(screen.getByText("Caching")).toBeInTheDocument();+ expectNoConsecutiveOrTrailingDividers();+ });++ it("should hide 'Caching' when the user cannot write the metric", async () => {+ setup({ canWrite: false });+ await openMenu();++ expect(screen.queryByText("Caching")).not.toBeInTheDocument();+ });+ });++ describe("Caching menu interaction", () => {+ it("opens the Caching modal when the Caching menu item is clicked", async () => {+ setup({ withModal: true });+ await openMenu();+ await userEvent.click(screen.getByText("Caching"));++ expect(+ await screen.findByRole("dialog", { name: /Caching/i }),+ ).toBeInTheDocument();+ expect(+ await screen.findByRole("radio", { name: /^Default$/i }),+ ).toBeInTheDocument();+ });});});diff --git a/frontend/src/metabase/metrics/routes.tsx b/frontend/src/metabase/metrics/routes.tsxindex a14ecb17828..99470b4c3d1 100644--- a/frontend/src/metabase/metrics/routes.tsx+++ b/frontend/src/metabase/metrics/routes.tsx@@ -1,6 +1,6 @@import { IndexRoute, Route } from "react-router";-import { PLUGIN_CACHING, PLUGIN_DEPENDENCIES } from "metabase/plugins";+import { PLUGIN_DEPENDENCIES } from "metabase/plugins";import { MetricAboutPage } from "./pages/MetricAboutPage";import { MetricDependenciesPage } from "./pages/MetricDependenciesPage";@@ -22,12 +22,6 @@ export function getMetricRoutes() {</Route>)}<Route path=":cardId/history" component={MetricHistoryPage} />- {PLUGIN_CACHING.isGranularCachingEnabled() && (- <Route- path=":cardId/caching"- component={PLUGIN_CACHING.MetricCachingPage}- />- )}</Route>);}diff --git a/frontend/src/metabase/metrics/types.ts b/frontend/src/metabase/metrics/types.tsindex 4c27b6f785f..7cb27b72c7e 100644--- a/frontend/src/metabase/metrics/types.ts+++ b/frontend/src/metabase/metrics/types.ts@@ -13,7 +13,6 @@ export interface MetricUrls {overview: (cardId: CardId) => string;query: (cardId: CardId) => string;dependencies: (cardId: CardId) => string;- caching: (cardId: CardId) => string;history: (cardId: CardId) => string;database?: (databaseId: DatabaseId) => string;}diff --git a/frontend/src/metabase/metrics/urls.ts b/frontend/src/metabase/metrics/urls.tsindex 0ac3fb4f303..82102b9a8d1 100644--- a/frontend/src/metabase/metrics/urls.ts+++ b/frontend/src/metabase/metrics/urls.ts@@ -7,6 +7,5 @@ export const metricUrls: MetricUrls = {overview: Urls.metricOverview,query: Urls.metricQuery,dependencies: Urls.metricDependencies,- caching: Urls.metricCaching,history: Urls.metricHistory,};diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.tsindex 980c9d6d159..b8f288d8a90 100644--- a/frontend/src/metabase/plugins/index.ts+++ b/frontend/src/metabase/plugins/index.ts@@ -16,6 +16,7 @@ export {export {PLUGIN_CACHING,type InvalidateNowButtonProps,+ type MetricCachingModalProps,type SidebarCacheSectionProps,type SidebarCacheFormProps,type PreemptiveCachingSwitchProps,diff --git a/frontend/src/metabase/plugins/oss/caching.ts b/frontend/src/metabase/plugins/oss/caching.tsindex 03ebaf50cbc..301030eb8bb 100644--- a/frontend/src/metabase/plugins/oss/caching.ts+++ b/frontend/src/metabase/plugins/oss/caching.ts@@ -1,18 +1,17 @@-import type { ComponentType, Dispatch, ReactNode, SetStateAction } from "react";+import type { ComponentType, Dispatch, SetStateAction } from "react";import {getPerformanceTabMetadata,strategies,} from "metabase/admin/performance/constants/complex";import type { ModelWithClearableCache } from "metabase/admin/performance/types";-import type { MetricPageParams, MetricUrls } from "metabase/metrics/types";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";import type { ModalOverlayProps, StackProps } from "metabase/ui";import type Question from "metabase-lib/v1/Question";import type {CacheableDashboard,CacheableModel,- Card,+ CardId,} from "metabase-types/api";// Types@@ -42,12 +41,10 @@ export type PreemptiveCachingSwitchProps = {handleSwitchToggle: () => void;};-export interface MetricSettingsPageProps {- params: MetricPageParams;- urls?: MetricUrls;- renderBreadcrumbs?: (card: Card) => ReactNode;- showAppSwitcher?: boolean;- showDataStudioLink?: boolean;+export interface MetricCachingModalProps {+ cardId: CardId;+ cardName: string;+ onClose: () => void;}const getDefaultPluginCaching = () => ({@@ -67,8 +64,8 @@ const getDefaultPluginCaching = () => ({getTabMetadata: getPerformanceTabMetadata,PreemptiveCachingSwitch:PluginPlaceholder as ComponentType<PreemptiveCachingSwitchProps>,- MetricCachingPage:- PluginPlaceholder as ComponentType<MetricSettingsPageProps>,+ MetricCachingModal:+ PluginPlaceholder as ComponentType<MetricCachingModalProps>,});export const PLUGIN_CACHING = getDefaultPluginCaching();diff --git a/frontend/src/metabase/urls/data-studio.ts b/frontend/src/metabase/urls/data-studio.tsindex 32602f2f8e0..1f14b977fca 100644--- a/frontend/src/metabase/urls/data-studio.ts+++ b/frontend/src/metabase/urls/data-studio.ts@@ -266,10 +266,6 @@ export function dataStudioMetricDependencies(cardId: CardId) {return `${dataStudioMetric(cardId)}/dependencies`;}-export function dataStudioMetricCaching(cardId: CardId) {- return `${dataStudioMetric(cardId)}/caching`;-}-export function dataStudioMetricHistory(cardId: CardId) {return `${dataStudioMetric(cardId)}/history`;}diff --git a/frontend/src/metabase/urls/metrics.ts b/frontend/src/metabase/urls/metrics.tsindex e43a726a12f..0373cd4ce49 100644--- a/frontend/src/metabase/urls/metrics.ts+++ b/frontend/src/metabase/urls/metrics.ts@@ -75,10 +75,6 @@ export function metricDependencies(cardId: CardId): string {return `/metric/${cardId}/dependencies`;}-export function metricCaching(cardId: CardId): string {- return `/metric/${cardId}/caching`;-}-export function metricHistory(cardId: CardId): string {return `/metric/${cardId}/history`;}