Skip to content

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

UXW-5034 New UI for database caching settings (#80034)

Denis Berezin11e969a6190d
diff --git a/e2e/support/helpers/e2e-caching-helpers.ts b/e2e/support/helpers/e2e-caching-helpers.ts
index 1d64c3786c3..20a829ae691 100644
--- a/e2e/support/helpers/e2e-caching-helpers.ts
+++ b/e2e/support/helpers/e2e-caching-helpers.ts
@@ -3,7 +3,7 @@ export const cacheStrategySidesheet = () =>
export const cacheStrategySelect = () =>
cy
- .findByRole("form", { name: "Select the cache invalidation policy" })
+ .findByRole("form", { name: "Cache invalidation policy" })
.findByTestId("cache-strategy-select");
/** Open the strategy dropdown and pick an option by its title (e.g. /Duration/).
@@ -13,3 +13,8 @@ export const selectCacheStrategy = (name: RegExp) => {
cacheStrategySelect().click();
cy.findByRole("option", { name }).click();
};
+
+/** Selecting the Duration strategy leaves the duration field empty, and the
+ * form cannot be saved until it is filled. */
+export const fillCacheDuration = (value: number) =>
+ cy.findByRole("spinbutton", { name: /Cache duration/ }).type(String(value));
diff --git a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js
index 51a28a6cc78..1adc24409f5 100644
--- a/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js
+++ b/e2e/test/scenarios/admin/admin-reproductions.cy.spec.js
@@ -256,21 +256,33 @@ describe("issue 45890", () => {
cy.visit("/admin/performance/databases");
H.main()
.findByLabelText(/Edit policy for database 'Sample Database'/)
- .findByText("No caching")
.click();
- // The strategy picker is a dropdown; its options render in a portal.
- H.main().findByTestId("cache-strategy-select").click();
+ // The strategy form opens in a side panel; the picker options render in a portal.
+ cy.findByTestId("cache-policy-panel")
+ .findByTestId("cache-strategy-select")
+ .click();
cy.findByRole("option", { name: /Schedule/ }).click();
- H.main().button("Save changes").click();
+ cy.intercept("PUT", "/api/cache").as("putCacheConfig");
+ cy.findByTestId("cache-policy-panel").button("Save").click();
+ cy.wait("@putCacheConfig");
});
it("should correctly reset caching schedule form when discarding changes", () => {
- H.main().findByLabelText("Frequency").click();
+ cy.findByTestId("cache-policy-panel").findByLabelText("Frequency").click();
H.popover().findByText("weekly").click();
- H.main().button("Discard changes").click();
- H.main().findByLabelText("Frequency").should("have.value", "hourly");
+ cy.log("Cancel the dirty form and confirm discarding the changes");
+ cy.findByTestId("cache-policy-panel").button("Cancel").click();
+ cy.findByTestId("confirm-modal").button("Discard").click();
+
+ cy.log("Reopening the form shows the saved schedule, not the draft");
+ H.main()
+ .findByLabelText(/Edit policy for database 'Sample Database'/)
+ .click();
+ cy.findByTestId("cache-policy-panel")
+ .findByLabelText("Frequency")
+ .should("have.value", "hourly");
});
});
diff --git a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts
index 1e101b1710c..6c2463b09f1 100644
--- a/e2e/test/scenarios/admin/performance/caching.cy.spec.ts
+++ b/e2e/test/scenarios/admin/performance/caching.cy.spec.ts
@@ -10,7 +10,7 @@ const preemptiveCachingSwitch = () =>
const saveCacheStrategyForm = () => {
cy.intercept("PUT", "/api/cache").as("putCacheConfig");
- cy.findByRole("form", { name: "Select the cache invalidation policy" })
+ cy.findByRole("form", { name: "Cache invalidation policy" })
.button(/Save/)
.click();
cy.wait("@putCacheConfig");
@@ -57,7 +57,7 @@ const cancelConfirmationModal = () =>
* frontend/.../Schedule/{cron,Schedule}.unit.spec.{ts,tsx}.
* - Strategy form input binding (typing into Min Duration / Multiplier),
* strategy-switch flows (Adaptive <-> Duration <-> No caching),
- * strategy -> launcher-label mapping, policy-options counts,
+ * strategy -> row-label mapping, policy-options counts,
* preemptive caching switch availability for root/database targets:
* frontend/.../StrategyEditorForDatabases.unit.spec.tsx and
* enterprise/.../caching/components/StrategyEditorForDatabases.unit.spec.tsx.
@@ -72,6 +72,10 @@ describe("scenarios > admin > performance > caching", () => {
it("saves the default-policy strategy and reflects the saved state", () => {
cy.visit("/admin/performance");
H.selectCacheStrategy(/Adaptive/);
+ cy.findByRole("spinbutton", { name: /minimum query duration/i }).type(
+ "1",
+ );
+ cy.findByRole("spinbutton", { name: /multiplier/i }).type("10");
saveCacheStrategyForm();
H.cacheStrategySelect().should("have.value", "Adaptive");
});
@@ -95,6 +99,7 @@ describe("scenarios > admin > performance > caching", () => {
cy.log("Set Sample Database to Duration and save");
H.selectCacheStrategy(/Duration/);
+ H.fillCacheDuration(24);
saveCacheStrategyForm();
cy.findByTestId("admin-layout-content").findByLabelText(
/Edit.*Sample Database.*currently.*Duration/,
@@ -109,7 +114,7 @@ describe("scenarios > admin > performance > caching", () => {
cy.button(/Clear cache for this database/).click();
cy.log("Confirm in the dialog");
- cy.findByRole("dialog")
+ cy.findByTestId("confirm-modal")
.button(/Clear cache/)
.click();
cy.wait("@invalidateCacheForSampleDatabase");
@@ -122,6 +127,8 @@ describe("scenarios > admin > performance > caching", () => {
H.visitQuestion(ORDERS_QUESTION_ID);
openSidebarCacheStrategyForm("question");
H.selectCacheStrategy(/Duration/);
+ // 24 keeps the "Duration: 24h" admin-tab assertion below true
+ H.fillCacheDuration(24);
preemptiveCachingSwitch().within(() => {
cy.findByRole("switch").should("not.be.checked");
cy.findByRole("switch").parent("label").click();
@@ -216,6 +223,10 @@ describe("scenarios > admin > performance > caching", () => {
H.visitQuestion(ORDERS_COUNT_QUESTION_ID);
openSidebarCacheStrategyForm("question");
H.selectCacheStrategy(/Adaptive/);
+ cy.findByRole("spinbutton", { name: /minimum query duration/i }).type(
+ "1",
+ );
+ cy.findByRole("spinbutton", { name: /multiplier/i }).type("10");
saveCacheStrategyForm();
cy.log("Both entries are visible on the admin tab");
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.ts
index e78e55d672b..0d25335b6d5 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
@@ -407,6 +407,7 @@ describe("scenarios > data studio > library > metrics", () => {
H.selectDropdown()
.findByRole("option", { name: /Duration/ })
.click();
+ H.fillCacheDuration(24);
H.modal().findByTestId("strategy-form-submit-button").click();
cy.wait("@updateCacheConfig");
diff --git a/e2e/test/scenarios/permissions/impersonated.cy.spec.js b/e2e/test/scenarios/permissions/impersonated.cy.spec.js
index 897d814e6af..79a0e72e0c9 100644
--- a/e2e/test/scenarios/permissions/impersonated.cy.spec.js
+++ b/e2e/test/scenarios/permissions/impersonated.cy.spec.js
@@ -117,6 +117,7 @@ describe("impersonated permission", { tags: "@external" }, () => {
.findByText(/Caching settings/)
.should("be.visible");
H.selectCacheStrategy(/Duration/);
+ H.fillCacheDuration(24);
H.cacheStrategySidesheet()
.findByRole("button", { name: /Save/ })
.click();
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/DatabaseCachingEditor.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/DatabaseCachingEditor.tsx
new file mode 100644
index 00000000000..72afb2d6ada
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/DatabaseCachingEditor.tsx
@@ -0,0 +1,335 @@
+import type { SortingState } from "@tanstack/react-table";
+import { useCallback, useMemo, useState } from "react";
+import { t } from "ttag";
+import { findWhere } from "underscore";
+
+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
+import { PerformancePageContent } from "metabase/admin/performance/components/PerformancePageContent";
+import { StrategyForm } from "metabase/admin/performance/components/StrategyForm";
+import {
+ defaultRootStrategy,
+ rootId,
+} from "metabase/admin/performance/constants/simple";
+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 type { UpdateTargetId } from "metabase/admin/performance/types";
+import { getShortStrategyLabel } from "metabase/admin/performance/utils";
+import {
+ useDeleteCacheConfigsMutation,
+ useListDatabasesQuery,
+} from "metabase/api";
+import { DebouncedSearchInput } from "metabase/common/components/DebouncedSearchInput";
+import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
+import { useConfirmation } from "metabase/common/hooks/use-confirmation";
+import { useDispatch } from "metabase/redux";
+import { addUndo } from "metabase/redux/undo";
+import { ActionIcon, Center, Flex, Icon, Text, Tooltip } from "metabase/ui";
+import type { Database } from "metabase-types/api";
+
+import { PolicySidePanel } from "./PolicySidePanel";
+import {
+ DEFAULT_POLICY_TABLE_SORTING,
+ PolicyTable,
+ type PolicyTableRowBase,
+ getAdjacentRows,
+ sortPolicyRows,
+} from "./PolicyTable";
+
+type DatabaseRow = PolicyTableRowBase & {
+ targetId: number;
+ ariaLabel: string;
+};
+
+const emptyDatabaseList: Database[] = [];
+const MIN_ITEMS_TO_SHOW_SEARCH = 11;
+
+export const DatabaseCachingEditor = () => {
+ const dispatch = useDispatch();
+
+ const [
+ // The targetId is the id of the model that is currently being edited
+ targetId,
+ setTargetId,
+ ] = useState<number | null>(null);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [sorting, setSorting] = useState<SortingState>(
+ DEFAULT_POLICY_TABLE_SORTING,
+ );
+
+ const {
+ configs,
+ error: configsError,
+ isLoading: areConfigsLoading,
+ } = useCacheConfigs({ model: ["root", "database"] });
+
+ const databasesResult = useListDatabasesQuery();
+ const databases = databasesResult.data?.data ?? emptyDatabaseList;
+
+ const rootStrategy =
+ findWhere(configs ?? [], { model_id: rootId })?.strategy ??
+ defaultRootStrategy;
+
+ const allRows: DatabaseRow[] = useMemo(() => {
+ const rootPolicyLabel = getShortStrategyLabel(rootStrategy);
+ const databaseRows = databases.map((database) => {
+ const config = findWhere(configs ?? [], {
+ model: "database",
+ model_id: database.id,
+ });
+ const policyLabel =
+ getShortStrategyLabel(config?.strategy ?? rootStrategy) ?? null;
+ return {
+ id: `database:${database.id}`,
+ targetId: database.id,
+ name: database.name,
+ icon: "database" as const,
+ policyLabel,
+ usesDefaultPolicy: config === undefined, // "Uses the default policy" here means inheritance: no config of its own
+ ariaLabel:
+ config === undefined
+ ? t`Edit policy for database '${database.name}' (currently inheriting the default policy, ${rootPolicyLabel})`
+ : t`Edit policy for database '${database.name}' (currently: ${policyLabel})`,
+ };
+ });
+ const defaultPolicyRow: DatabaseRow = {
+ id: "root",
+ targetId: rootId,
+ name: t`Default policy`,
+ icon: "star",
+ policyLabel: rootPolicyLabel ?? null,
+ usesDefaultPolicy: false,
+ ariaLabel: t`Edit default policy (currently: ${rootPolicyLabel})`,
+ };
+ // The default policy row stays pinned at the top regardless of sorting
+ return [defaultPolicyRow, ...sortPolicyRows(databaseRows, sorting)];
+ }, [databases, configs, rootStrategy, sorting]);
+
+ const query = searchQuery.trim().toLowerCase();
+ const visibleRows =
+ query === ""
+ ? allRows
+ : allRows.filter(
+ (row) =>
+ row.name.toLowerCase().includes(query) ||
+ row.policyLabel?.toLowerCase().includes(query),
+ );
+
+ const shouldShowSearch = databases.length >= MIN_ITEMS_TO_SHOW_SEARCH;
+
+ const {
+ askBeforeDiscardingChanges,
+ confirmationModal,
+ isStrategyFormDirty,
+ setIsStrategyFormDirty,
+ } = useConfirmIfFormIsDirty();
+
+ const updateTargetId: UpdateTargetId = useCallback(
+ (newTargetId, isFormDirty) => {
+ if (targetId !== newTargetId) {
+ const update = () => {
+ setTargetId(newTargetId);
+ // Closing the sidesheet unmounts the form, so nothing else would
+ // clear the dirty flag after the user discards their changes
+ setIsStrategyFormDirty(false);
+ };
+ if (isFormDirty) {
+ askBeforeDiscardingChanges(update);
+ } else {
+ update();
+ }
+ }
+ },
+ [targetId, askBeforeDiscardingChanges, setIsStrategyFormDirty],
+ );
+
+ const targetDatabase = databases.find((db) => db.id === targetId);
+ const targetConfig = findWhere(configs ?? [], {
+ model_id: targetId ?? undefined,
+ });
+ const savedStrategy = targetConfig?.strategy;
+
+ const shouldAllowInvalidation = useMemo(() => {
+ if (
+ targetId === null ||
+ targetId === rootId ||
+ savedStrategy?.type === "nocache"
+ ) {
+ return false;
+ }
+ const inheritingRootStrategy = ["inherit", undefined].includes(
+ savedStrategy?.type,
+ );
+ const rootConfig = findWhere(configs ?? [], { model_id: rootId });
+ const inheritingDoNotCache =
+ inheritingRootStrategy && !rootConfig?.strategy;
+ return !inheritingDoNotCache;
+ }, [configs, savedStrategy?.type, targetId]);
+
+ const saveStrategy = useSaveStrategy(targetId, "database");
+
+ const overriddenDatabaseIds = useMemo(
+ () =>
+ (configs ?? [])
+ .filter((config) => config.model === "database")
+ .map((config) => config.model_id),
+ [configs],
+ );
+
+ const [deleteCacheConfigs] = useDeleteCacheConfigsMutation();
+ const { show: showResetConfirmation, modalContent: resetConfirmationModal } =
+ useConfirmation();
+
+ const showResetAllConfirmation = useCallback(() => {
+ showResetConfirmation({
+ title: t`Reset all to default?`,
+ message: t`This will reset all database caching policies to their default values.`,
+ confirmButtonText: t`Reset all to default`,
+ onConfirm: async () => {
+ try {
+ await deleteCacheConfigs({
+ model: "database",
+ model_id: overriddenDatabaseIds,
+ }).unwrap();
+ } catch {
+ dispatch(
+ addUndo({
+ icon: "warning",
+ message: t`Could not reset the caching policies.`,
+ }),
+ );
+ }
+ },
+ });
+ }, [
+ showResetConfirmation,
+ deleteCacheConfigs,
+ overriddenDatabaseIds,
+ dispatch,
+ ]);
+
+ const handleResetAllToDefault = useCallback(() => {
+ if (isStrategyFormDirty) {
+ askBeforeDiscardingChanges(() => {
+ setIsStrategyFormDirty(false);
+ showResetAllConfirmation();
+ });
+ } else {
+ showResetAllConfirmation();
+ }
+ }, [
+ isStrategyFormDirty,
+ askBeforeDiscardingChanges,
+ setIsStrategyFormDirty,
+ showResetAllConfirmation,
+ ]);
+
+ const targetRowIndex = visibleRows.findIndex(
+ (row) => row.targetId === targetId,
+ );
+ const { previousRow, nextRow } = getAdjacentRows(visibleRows, targetRowIndex);
+
+ const closePanel = useCallback(() => {
+ updateTargetId(null, isStrategyFormDirty);
+ }, [updateTargetId, isStrategyFormDirty]);
+
+ const error = configsError || databasesResult.error;
+ const loading = areConfigsLoading || databasesResult.isLoading;
+ if (error || loading) {
+ return <DelayedLoadingAndErrorWrapper error={error} loading={loading} />;
+ }
+
+ return (
+ <Flex h="100%" wrap="nowrap">
+ <PerformancePageContent>
+ <SettingsPageWrapper
+ title={
+ <Flex flex={1} justify="space-between" align="center">
+ {t`Database caching`}
+ {overriddenDatabaseIds.length > 0 && (
+ <Tooltip label={t`Reset all to default`}>
+ <ActionIcon
+ size="lg"
+ c="icon-primary"
+ bd="1px solid var(--mb-color-border-neutral)"
+ aria-label={t`Reset all to default`}
+ onClick={handleResetAllToDefault}
+ >
+ <Icon name="revert" />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </Flex>
+ }
+ aria-label={t`Data caching settings`}
+ description={t`Speed up queries by caching results with a global policy or database-specific policies.`}
+ descriptionProps={{ maw: "100%" }}
+ h="calc(100vh - 9rem)"
+ >
+ {confirmationModal}
+ {resetConfirmationModal}
+ {shouldShowSearch && (
+ <DebouncedSearchInput
+ flex={0}
+ value={searchQuery}
+ placeholder={t`Search by name or policy…`}
+ onChange={setSearchQuery}
+ />
+ )}
+ <PolicyTable
+ rows={visibleRows}
+ sorting={sorting}
+ onSortingChange={setSorting}
+ selectedRowId={visibleRows[targetRowIndex]?.id ?? null}
+ onRowClick={(row) =>
+ updateTargetId(row.targetId, isStrategyFormDirty)
+ }
+ getRowProps={(row) => ({
+ "aria-label": row.original.ariaLabel,
+ "data-testid": `policy-row-${row.original.targetId}`,
+ })}
+ emptyState={
+ <Center p="xl">
+ <Text fw="bold" c="text-secondary">{t`No results`}</Text>
+ </Center>
+ }
+ data-testid="database-caching-table"
+ />
+ </SettingsPageWrapper>
+ </PerformancePageContent>
+ {targetId !== null && (
+ <PolicySidePanel
+ title={
+ targetId === rootId
+ ? t`Default policy`
+ : targetDatabase?.name || t`Untitled database`
+ }
+ onPrevious={
+ previousRow
+ ? () => updateTargetId(previousRow.targetId, isStrategyFormDirty)
+ : undefined
+ }
+ onNext={
+ nextRow
+ ? () => updateTargetId(nextRow.targetId, isStrategyFormDirty)
+ : undefined
+ }
+ onClose={closePanel}
+ >
+ <StrategyForm
+ targetId={targetId}
+ targetModel={targetId === rootId ? "root" : "database"}
+ targetName={targetDatabase?.name || t`Untitled database`}
+ setIsDirty={setIsStrategyFormDirty}
+ saveStrategy={saveStrategy}
+ savedStrategy={savedStrategy}
+ shouldAllowInvalidation={shouldAllowInvalidation}
+ shouldShowName={false}
+ onCancel={closePanel}
+ layout="sidebar"
+ />
+ </PolicySidePanel>
+ )}
+ </Flex>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/GranularControlsExplanation.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/GranularControlsExplanation.tsx
deleted file mode 100644
index 388a51b5dd7..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/GranularControlsExplanation.tsx
+++ /dev/null
@@ -1,8 +0,0 @@
-import { t } from "ttag";
-
-export const GranularControlsExplanation = () => (
- <>
- &nbsp;
- {t`You can set up one caching policy for all your databases, or set up caching policies specific to each database.`}
- </>
-);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsx
index cb6d960fe78..6002a9d8008 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/MetricCachingModal.tsx
@@ -73,7 +73,7 @@ export function MetricCachingModal({
savedStrategy={savedStrategy}
shouldAllowInvalidation
shouldShowName={false}
- onReset={handleClose}
+ onCancel={handleClose}
layout="modal"
/>
</DelayedLoadingAndErrorWrapper>
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.tsx
index 16466e70b67..da7aa198fe8 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,7 @@ import { setupPerformanceEndpoints } from "__support__/server-mocks/performance"
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import {
+ changeInput,
getCacheStrategySelect,
selectCacheStrategy,
} from "metabase/admin/performance/components/test-utils";
@@ -85,6 +86,7 @@ describe("MetricCachingModal", () => {
const { onClose } = setup();
await selectCacheStrategy(/^Duration/i);
+ await changeInput(/Cache duration/, 0, 24);
await userEvent.click(screen.getByTestId("strategy-form-submit-button"));
await waitFor(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/PolicySidePanel.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/PolicySidePanel.module.css
new file mode 100644
index 00000000000..10608af4d30
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/PolicySidePanel.module.css
@@ -0,0 +1,16 @@
+.panel {
+ flex-shrink: 0;
+ border-left: 1px solid var(--mb-color-border-neutral);
+}
+
+.navButton:not([data-specificity-hack]) {
+ color: var(--mb-color-icon-primary);
+ border: 1px solid var(--mb-color-border-neutral);
+
+ &:disabled,
+ &[data-disabled] {
+ color: var(--mb-color-icon-disabled);
+ border-color: var(--mb-color-border-neutral-subtle);
+ background-color: transparent;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/PolicySidePanel.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/PolicySidePanel.tsx
new file mode 100644
index 00000000000..e4a14799a80
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/PolicySidePanel.tsx
@@ -0,0 +1,84 @@
+import type { ReactNode } from "react";
+import { t } from "ttag";
+
+import { ActionIcon, Flex, Group, Icon, Stack, Text, Title } from "metabase/ui";
+
+import S from "./PolicySidePanel.module.css";
+
+type Props = {
+ title: string;
+ subtitle?: string;
+ onPrevious?: () => void;
+ onNext?: () => void;
+ onClose: () => void;
+ children: ReactNode;
+};
+
+export const PolicySidePanel = ({
+ title,
+ subtitle,
+ onPrevious,
+ onNext,
+ onClose,
+ children,
+}: Props) => (
+ <Flex
+ component="aside"
+ direction="column"
+ className={S.panel}
+ w="28.75rem"
+ maw="50%"
+ h="100%"
+ bg="background_page-primary"
+ aria-label={title}
+ data-testid="cache-policy-panel"
+ >
+ <Group justify="space-between" px="2rem" pt="2rem">
+ {(onPrevious !== undefined || onNext !== undefined) && (
+ <Group gap="sm">
+ <ActionIcon
+ size="lg"
+ className={S.navButton}
+ disabled={onPrevious === undefined}
+ aria-label={t`Previous item`}
+ onClick={onPrevious}
+ >
+ <Icon name="chevronup" />
+ </ActionIcon>
+ <ActionIcon
+ size="lg"
+ className={S.navButton}
+ disabled={onNext === undefined}
+ aria-label={t`Next item`}
+ onClick={onNext}
+ >
+ <Icon name="chevrondown" />
+ </ActionIcon>
+ </Group>
+ )}
+ <ActionIcon
+ variant="subtle"
+ c="icon-primary"
+ size="lg"
+ ml="auto"
+ aria-label={t`Close`}
+ onClick={onClose}
+ >
+ <Icon name="close" />
+ </ActionIcon>
+ </Group>
+ <Stack gap={0} px="2rem" pt="xl" pb="xl">
+ {subtitle && (
+ <Text size="md" lh="1rem" fw="bold" c="text-secondary" mb="xs">
+ {subtitle}
+ </Text>
+ )}
+ <Title order={3} c="text-primary">
+ {title}
+ </Title>
+ </Stack>
+ <Flex direction="column" mih={0} px="2rem" pb="lg" flex="1">
+ {children}
+ </Flex>
+ </Flex>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/index.ts b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/index.ts
new file mode 100644
index 00000000000..4174a6504bf
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicySidePanel/index.ts
@@ -0,0 +1 @@
+export { PolicySidePanel } from "./PolicySidePanel";
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/PolicyTable.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/PolicyTable.tsx
new file mode 100644
index 00000000000..df42b07c1a2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/PolicyTable.tsx
@@ -0,0 +1,175 @@
+import type { Row, SortingState, Updater } from "@tanstack/react-table";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { t } from "ttag";
+
+import { getCollectionPathAsString } from "metabase/common/collections/utils";
+import type { TreeTableColumnDef } from "metabase/ui";
+import {
+ Card,
+ Ellipsified,
+ FixedSizeIcon,
+ Flex,
+ Text,
+ TreeTable,
+ useTreeTableInstance,
+} from "metabase/ui";
+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";
+import type { CollectionEssentials, IconName } from "metabase-types/api";
+
+export type PolicyTableRowBase = {
+ id: string;
+ name: string;
+ icon: IconName;
+ collection?: CollectionEssentials | null;
+ policyLabel: string | null;
+ usesDefaultPolicy: boolean;
+};
+
+type Props<TRow extends PolicyTableRowBase> = {
+ rows: TRow[];
+ withCollectionColumn?: boolean;
+ sorting: SortingState;
+ onSortingChange: (sorting: SortingState) => void;
+ selectedRowId: string | null;
+ onRowClick: (row: TRow) => void;
+ getRowProps?: (row: Row<TRow>) => Record<string, unknown>;
+ emptyState: React.ReactNode;
+ "data-testid"?: string;
+};
+
+export function PolicyTable<TRow extends PolicyTableRowBase>({
+ rows,
+ withCollectionColumn = false,
+ sorting,
+ onSortingChange,
+ selectedRowId,
+ onRowClick,
+ getRowProps,
+ emptyState,
+ "data-testid": dataTestId,
+}: Props<TRow>) {
+ const handleSortingChange = useCallback(
+ (updater: Updater<SortingState>) => {
+ const next = typeof updater === "function" ? updater(sorting) : updater;
+ if (next.length === 0 && sorting[0] !== undefined) {
+ onSortingChange([{ id: sorting[0].id, desc: false }]);
+ return;
+ }
+ onSortingChange(next);
+ },
+ [sorting, onSortingChange],
+ );
+
+ const columns = useMemo<TreeTableColumnDef<TRow>[]>(() => {
+ const nameColumn: TreeTableColumnDef<TRow> = {
+ id: "name",
+ header: t`Name`,
+ width: "auto",
+ minWidth: 200,
+ enableSorting: true,
+ accessorFn: (row) => row.name,
+ cell: ({ row }) => (
+ <Flex gap="sm" align="center" miw={0}>
+ <FixedSizeIcon name={row.original.icon} c="text-secondary" />
+ <Ellipsified tooltip={row.original.name}>
+ {row.original.name}
+ </Ellipsified>
+ </Flex>
+ ),
+ };
+ const collectionColumn: TreeTableColumnDef<TRow> = {
+ id: "collection",
+ header: t`Collection`,
+ width: "auto",
+ minWidth: 200,
+ enableSorting: true,
+ accessorFn: (row) =>
+ row.collection ? getCollectionPathAsString(row.collection) : "",
+ cell: ({ row }) => {
+ const { collection } = row.original;
+ if (!collection) {
+ return null;
+ }
+ const path = getCollectionPathAsString(collection);
+ return <Ellipsified tooltip={path}>{path}</Ellipsified>;
+ },
+ };
+ const policyColumn: TreeTableColumnDef<TRow> = {
+ id: "policy",
+ header: t`Policy`,
+ width: "auto",
+ minWidth: 140,
+ enableSorting: true,
+ // Sorting is manual (see sortPolicyRows), but getCanSort requires an accessorFn
+ accessorFn: (row) => row.policyLabel ?? "",
+ cell: ({ row }) => (
+ <Text
+ size="md"
+ c={row.original.usesDefaultPolicy ? "text-disabled" : "text-primary"}
+ data-uses-default-policy={row.original.usesDefaultPolicy}
+ >
+ {row.original.policyLabel ?? EMPTY_CELL_PLACEHOLDER}
+ </Text>
+ ),
+ };
+ return withCollectionColumn
+ ? [nameColumn, collectionColumn, policyColumn]
+ : [nameColumn, policyColumn];
+ }, [withCollectionColumn]);
+
+ const instanceRef = useRef<{
+ setActiveRowId: (id: string | null) => void;
+ } | null>(null);
+
+ const handleRowActivate = useCallback(
+ (row: Row<TRow>) => {
+ onRowClick(row.original);
+ // TreeTable focuses any activated row right away, but the parent may
+ // park the selection change behind a dirty-form confirmation; keep the
+ // highlight on the selected row until the selection actually moves
+ // (the effect below follows it when it does)
+ instanceRef.current?.setActiveRowId(selectedRowId);
+ },
+ [onRowClick, selectedRowId],
+ );
+
+ const instance = useTreeTableInstance<TRow>({
+ data: rows,
+ columns,
+ getNodeId: (row) => row.id,
+ sorting,
+ manualSorting: true,
+ onSortingChange: handleSortingChange,
+ onRowActivate: handleRowActivate,
+ selectedRowId,
+ });
+ instanceRef.current = instance;
+
+ // Keyboard focus stays on the last clicked row unless synced; when the
+ // panel's prev/next buttons move the selection, that row would also keep
+ // rendering as active
+ const { setActiveRowId } = instance;
+ useEffect(() => {
+ setActiveRowId(selectedRowId);
+ }, [selectedRowId, setActiveRowId]);
+
+ return (
+ <Card
+ flex="0 1 auto"
+ mih={0}
+ p={0}
+ pos="relative"
+ withBorder
+ data-testid={dataTestId}
+ >
+ <TreeTable
+ instance={instance}
+ hierarchical={false}
+ ariaLabel={t`Caching policies`}
+ onRowClick={handleRowActivate}
+ getRowProps={getRowProps}
+ emptyState={emptyState}
+ />
+ </Card>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/index.ts b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/index.ts
new file mode 100644
index 00000000000..5c361f65d81
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/index.ts
@@ -0,0 +1,6 @@
+export { PolicyTable, type PolicyTableRowBase } from "./PolicyTable";
+export {
+ DEFAULT_POLICY_TABLE_SORTING,
+ getAdjacentRows,
+ sortPolicyRows,
+} from "./utils";
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/utils.ts b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/utils.ts
new file mode 100644
index 00000000000..edca357f108
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/PolicyTable/utils.ts
@@ -0,0 +1,40 @@
+import type { SortingState } from "@tanstack/react-table";
+
+import type { PolicyTableRowBase } from "./PolicyTable";
+
+export const DEFAULT_POLICY_TABLE_SORTING: SortingState = [
+ { id: "name", desc: false },
+];
+
+const getSortValue = <TRow extends PolicyTableRowBase>(
+ row: TRow,
+ columnId: string,
+) => {
+ switch (columnId) {
+ case "collection":
+ return row.collection?.name ?? "";
+ case "policy":
+ return row.policyLabel ?? "";
+ default:
+ return row.name;
+ }
+};
+
+export const sortPolicyRows = <TRow extends PolicyTableRowBase>(
+ rows: TRow[],
+ sorting: SortingState,
+): TRow[] => {
+ const { id: columnId = "name", desc = false } = sorting[0] ?? {};
+
+ return [...rows].sort(
+ (rowA, rowB) =>
+ getSortValue(rowA, columnId).localeCompare(getSortValue(rowB, columnId)) *
+ (desc ? -1 : 1),
+ );
+};
+
+export const getAdjacentRows = <TRow>(rows: TRow[], index: number) => ({
+ previousRow: index > 0 ? rows[index - 1] : undefined,
+ nextRow:
+ index !== -1 && index < rows.length - 1 ? rows[index + 1] : undefined,
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.module.css
deleted file mode 100644
index 4f300e2878e..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.module.css
+++ /dev/null
@@ -1,4 +0,0 @@
-/* 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_surface-error);
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsx
deleted file mode 100644
index 92a72022a98..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/ResetButtonContainer.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { useFormikContext } from "formik";
-import { t } from "ttag";
-
-import { useConfirmation } from "metabase/common/hooks/use-confirmation";
-import { Form, FormSubmitButton, useFormContext } from "metabase/forms";
-import { Box, Flex, Group, Icon, Loader, Text } from "metabase/ui";
-
-import S from "./ResetButtonContainer.module.css";
-
-export const ResetButtonContainer = () => {
- return (
- <Box pb="md" mt="auto" ms="auto" me="lg">
- <ResetAllToDefaultButtonFormBody />
- </Box>
- );
-};
-
-const ResetAllToDefaultButtonFormBody = () => {
- const { submitForm } = useFormikContext();
- const { show: askConfirmation, modalContent: confirmationModal } =
- useConfirmation();
- const { status } = useFormContext();
-
- const confirmResetAllToDefault = () => {
- askConfirmation({
- title: t`Reset all database caching policies to the default?`,
- message: "",
- confirmButtonText: t`Reset`,
- onConfirm: submitForm,
- });
- };
-
- return (
- <>
- <Form>
- <Flex justify="flex-end">
- <FormSubmitButton
- px="md"
- py=".75rem"
- lh="1"
- onClick={(e) => {
- confirmResetAllToDefault();
- e.preventDefault();
- return false;
- }}
- label={
- <Text
- // Prevents the label from getting cut off vertically
- h="1rem"
- lh="1"
- fw="normal"
- color="feedback-negative"
- >{t`Reset all to default`}</Text>
- }
- activeLabel={<Loader size="xs" />}
- successLabel={
- <Text fw="bold" lh="1" color="feedback-positive">
- <Group gap="xs">
- <Icon name="check" /> {t`Success`}
- </Group>
- </Text>
- }
- variant="subtle"
- className={status === "idle" ? S.highlightOnHover : undefined}
- />
- </Flex>
- </Form>
- {confirmationModal}
- </>
- );
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx
index c41a076d94d..ee402fe5c0d 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/SidebarCacheForm.tsx
@@ -85,7 +85,7 @@ export const SidebarCacheForm = ({
savedStrategy={savedStrategy}
shouldAllowInvalidation
shouldShowName={false}
- onReset={() =>
+ onCancel={() =>
isStrategyFormDirty
? askBeforeDiscardingChanges(onBack)
: onBack()
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.tsx
index a3b406013a3..47b4097d1c9 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
@@ -1,7 +1,7 @@
import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
-import { act, screen, within } from "__support__/ui";
+import { act, screen, waitFor, within } from "__support__/ui";
import type { SetupOpts } from "metabase/admin/performance/components/test-utils";
import {
setupStrategyEditorForDatabases as baseSetup,
@@ -56,7 +56,7 @@ describe("StrategyEditorForDatabases", () => {
).toBeInTheDocument();
});
- it("should show strategy form launchers", async () => {
+ it("should show the default policy and database rows", async () => {
const rootStrategyHeading = await screen.findByText("Default policy");
expect(rootStrategyHeading).toBeInTheDocument();
expect(
@@ -215,8 +215,8 @@ describe("StrategyEditorForDatabases", () => {
// Schedule.unit.spec.tsx. This case is the integration: picking a
// frequency/day/time in the Schedule fields must flow through Formik's
// `setFieldValue("schedule", ...)` and end up in the saved strategy, which
- // the launcher label then reads back.
- it("saves a weekly Monday 8 AM schedule and round-trips it through the launcher label", async () => {
+ // the row label then reads back.
+ it("saves a weekly Monday 8 AM schedule and round-trips it through the row label", async () => {
await userEvent.click(
await screen.findByLabelText(
`Edit policy for database 'Database 1' (currently: Adaptive)`,
@@ -273,6 +273,32 @@ describe("StrategyEditorForDatabases", () => {
expect(getShortStrategyLabel(strategy)).toBe(expected);
});
+ it("does not silently save default values when saving right after switching strategies", async () => {
+ // Database 4 inherits the default policy
+ await userEvent.click(
+ await screen.findByLabelText(/Edit policy for database 'Database 4'/),
+ );
+
+ await selectCacheStrategy(/^Duration/i);
+ const saveButton = await screen.findByTestId("strategy-form-submit-button");
+ await waitFor(() => expect(saveButton).toBeDisabled());
+ await userEvent.click(saveButton);
+ expect(
+ fetchMock.callHistory.calls("path:/api/cache", { method: "PUT" }),
+ ).toHaveLength(0);
+
+ await selectCacheStrategy(/Adaptive/i);
+ await waitFor(() =>
+ expect(screen.getByTestId("strategy-form-submit-button")).toBeDisabled(),
+ );
+
+ await changeInput(/minimum query duration/i, 1, 5);
+ await changeInput(/multiplier/i, 10, 3);
+ await waitFor(() =>
+ expect(screen.getByTestId("strategy-form-submit-button")).toBeEnabled(),
+ );
+ });
+
it("does not allow saving an empty cache duration", async () => {
await userEvent.click(
await screen.findByLabelText(
@@ -338,6 +364,193 @@ describe("StrategyEditorForDatabases", () => {
});
});
+describe("StrategyEditorForDatabases (table behaviors)", () => {
+ it("keeps the default policy row pinned at the top", async () => {
+ setup();
+ const rows = await screen.findAllByTestId(/^policy-row-/);
+ expect(rows[0]).toHaveAccessibleName(/Edit default policy/);
+ });
+
+ it("shows the policy in a lighter color for databases using the default policy", async () => {
+ setup();
+ // Database 4 has no config of its own, so it inherits the default policy
+ const inheritingRow = await screen.findByTestId("policy-row-4");
+ expect(within(inheritingRow).getByText("Duration: 1h")).toHaveAttribute(
+ "data-uses-default-policy",
+ "true",
+ );
+ const overriddenRow = await screen.findByTestId("policy-row-1");
+ expect(within(overriddenRow).getByText("Adaptive")).toHaveAttribute(
+ "data-uses-default-policy",
+ "false",
+ );
+ });
+
+ it("does not ask to discard again after changes were already discarded", async () => {
+ setup();
+ await userEvent.click(await screen.findByLabelText(/Edit default policy/));
+ await changeInput(/Cache duration/, 0, 48);
+
+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ const dialog = await screen.findByRole("dialog", {
+ name: "Discard your changes?",
+ });
+ await userEvent.click(
+ within(dialog).getByRole("button", { name: "Discard" }),
+ );
+
+ await userEvent.click(
+ await screen.findByLabelText(/Edit policy for database 'Database 1'/),
+ );
+ expect(
+ await screen.findByTestId("cache-strategy-select"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Discard your changes?")).not.toBeInTheDocument();
+ });
+
+ it("navigates between rows with the sidesheet chevrons", async () => {
+ setup();
+ await userEvent.click(await screen.findByLabelText(/Edit default policy/));
+
+ const previousButton = await screen.findByLabelText("Previous item");
+ expect(previousButton).toBeDisabled();
+
+ await userEvent.click(screen.getByLabelText("Next item"));
+
+ const sidesheet = await screen.findByTestId("cache-policy-panel");
+ expect(
+ await within(sidesheet).findByText("Database 1"),
+ ).toBeInTheDocument();
+ });
+
+ it("keeps the row highlight while a discard confirmation is open", async () => {
+ setup();
+ await userEvent.click(await screen.findByLabelText(/Edit default policy/));
+ await changeInput(/Cache duration/, 0, 48);
+
+ await userEvent.click(
+ await screen.findByLabelText(/Edit policy for database 'Database 1'/),
+ );
+ await screen.findByText("Discard your changes?");
+
+ expect(screen.getByTestId("policy-row-0")).toHaveAttribute(
+ "data-keyboard-active",
+ "true",
+ );
+ expect(screen.getByTestId("policy-row-1")).not.toHaveAttribute(
+ "data-keyboard-active",
+ );
+ });
+
+ it("moves the row highlight when navigating with the chevrons", async () => {
+ setup();
+ await userEvent.click(await screen.findByLabelText(/Edit default policy/));
+ await userEvent.click(await screen.findByLabelText("Next item"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("policy-row-1")).toHaveAttribute(
+ "data-keyboard-active",
+ "true",
+ );
+ });
+ expect(screen.getByTestId("policy-row-0")).not.toHaveAttribute(
+ "data-keyboard-active",
+ );
+ });
+});
+
+describe("StrategyEditorForDatabases (search)", () => {
+ it("does not show search with 10 or fewer items", async () => {
+ setup();
+ await screen.findByLabelText(/Edit default policy/);
+ expect(
+ screen.queryByPlaceholderText("Search by name or policy…"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows search with more than 10 items and filters rows, including the default policy row", async () => {
+ setup({ databaseCount: 12 });
+ const searchInput = await screen.findByPlaceholderText(
+ "Search by name or policy…",
+ );
+ expect(
+ await screen.findByLabelText(/Edit default policy/),
+ ).toBeInTheDocument();
+
+ await userEvent.type(searchInput, "Database 10");
+
+ await waitFor(() => {
+ expect(
+ screen.queryByLabelText(/Edit default policy/),
+ ).not.toBeInTheDocument();
+ });
+ expect(
+ screen.getByLabelText(/Edit policy for database 'Database 10'/),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByLabelText(/Edit policy for database 'Database 11'/),
+ ).not.toBeInTheDocument();
+ });
+});
+
+describe("StrategyEditorForDatabases (reset all to default)", () => {
+ it("hides the reset-all button when no database has its own policy", async () => {
+ setup({
+ cacheConfigs: [
+ createMockCacheConfig({
+ model: "root",
+ model_id: 0,
+ strategy: {
+ type: "duration",
+ duration: 1,
+ unit: CacheDurationUnit.Hours,
+ refresh_automatically: false,
+ },
+ }),
+ ],
+ });
+ await screen.findByLabelText(/Edit default policy/);
+ expect(
+ screen.queryByLabelText("Reset all to default"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("resets all database policies after confirmation", async () => {
+ setup();
+ await userEvent.click(await screen.findByLabelText("Reset all to default"));
+
+ const dialog = await screen.findByRole("dialog", {
+ name: "Reset all to default?",
+ });
+ expect(
+ within(dialog).getByText(
+ "This will reset all database caching policies to their default values.",
+ ),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ within(dialog).getByRole("button", { name: "Reset all to default" }),
+ );
+
+ await waitFor(() => {
+ expect(
+ fetchMock.callHistory.calls("path:/api/cache", { method: "DELETE" }),
+ ).toHaveLength(1);
+ });
+
+ expect(
+ await screen.findByLabelText(
+ /Edit policy for database 'Database 1' \(currently inheriting the default policy/,
+ ),
+ ).toBeInTheDocument();
+ await waitFor(() => {
+ expect(
+ screen.queryByLabelText("Reset all to default"),
+ ).not.toBeInTheDocument();
+ });
+ });
+});
+
describe("StrategyEditorForDatabases (sub-hour duration policy)", () => {
beforeEach(() => {
setup({
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/CachingPoliciesFilters.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/CachingPoliciesFilters.tsx
new file mode 100644
index 00000000000..5e199228373
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/CachingPoliciesFilters.tsx
@@ -0,0 +1,84 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import {
+ FilterPill,
+ FilterSection,
+ ListFilterPopover,
+} from "metabase/common/components/ListFilterPopover";
+import { useGetIcon } from "metabase/hooks/use-icon";
+
+export type CachingPolicyFilter = "default" | "custom";
+export type CachingTypeFilter = "dashboard" | "question";
+
+export type CachingFilters = {
+ policy: CachingPolicyFilter | null;
+ type: CachingTypeFilter | null;
+};
+
+export const EMPTY_CACHING_FILTERS: CachingFilters = {
+ policy: null,
+ type: null,
+};
+
+type Props = {
+ filters: CachingFilters;
+ onChange: (filters: CachingFilters) => void;
+};
+
+export const CachingPoliciesFilters = ({ filters, onChange }: Props) => {
+ const getIcon = useGetIcon();
+ const [draft, setDraft] = useState<CachingFilters>(filters);
+ const hasActiveFilters = filters.policy !== null || filters.type !== null;
+
+ const togglePolicy = (policy: CachingPolicyFilter) => {
+ setDraft((prev) => ({
+ ...prev,
+ policy: prev.policy === policy ? null : policy,
+ }));
+ };
+
+ const toggleType = (type: CachingTypeFilter) => {
+ setDraft((prev) => ({
+ ...prev,
+ type: prev.type === type ? null : type,
+ }));
+ };
+
+ return (
+ <ListFilterPopover
+ hasActiveFilters={hasActiveFilters}
+ onOpen={() => setDraft(filters)}
+ onApply={() => onChange(draft)}
+ onClear={() => onChange(EMPTY_CACHING_FILTERS)}
+ >
+ <FilterSection label={t`Caching policy`}>
+ <FilterPill
+ label={t`Default`}
+ selected={draft.policy === "default"}
+ onClick={() => togglePolicy("default")}
+ />
+ <FilterPill
+ label={t`Custom`}
+ selected={draft.policy === "custom"}
+ onClick={() => togglePolicy("custom")}
+ />
+ </FilterSection>
+
+ <FilterSection label={t`Type`}>
+ <FilterPill
+ icon={getIcon({ model: "dashboard" }).name}
+ label={t`Dashboard`}
+ selected={draft.type === "dashboard"}
+ onClick={() => toggleType("dashboard")}
+ />
+ <FilterPill
+ icon={getIcon({ model: "card" }).name}
+ label={t`Question`}
+ selected={draft.type === "question"}
+ onClick={() => toggleType("question")}
+ />
+ </FilterSection>
+ </ListFilterPopover>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.module.css
deleted file mode 100644
index fcfb990c2d8..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.module.css
+++ /dev/null
@@ -1,47 +0,0 @@
-.SkeletonTableRow {
- height: 3rem;
-
- td {
- width: 20rem;
- }
-
- &:hover {
- background-color: transparent !important;
- }
-}
-
-.CacheableItemTable {
- table-layout: fixed;
- background-color: var(--mb-color-text-primary-inverse);
-
- col {
- width: 30%;
- }
-
- td {
- padding: 0.75rem !important;
- }
-
- tbody > tr:hover {
- background-color: var(--mb-color-background_surface-hover) !important;
- }
-
- tbody > tr.currentTarget {
- background-color: var(--mb-color-background_page-highlighted) !important;
- }
-}
-
-.StrategyFormPanel {
- border-left: 1px solid var(--mb-color-border-neutral);
- position: relative;
- max-width: 30rem;
-
- @media screen and (--breakpoint-max-lg) {
- max-width: 25rem;
- }
-}
-
-.ItemLink:hover,
-.CollectionLink :hover {
- color: var(--mb-color-core-brand);
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx
index e0a55db6d7d..700ff15771b 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.tsx
@@ -1,96 +1,146 @@
+import type { SortingState } from "@tanstack/react-table";
import { useCallback, useEffect, useMemo, useState } from "react";
import { t } from "ttag";
import _ from "underscore";
import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
+import { PerformancePageContent } from "metabase/admin/performance/components/PerformancePageContent";
import { StrategyForm } from "metabase/admin/performance/components/StrategyForm";
+import {
+ defaultRootStrategy,
+ rootId,
+} from "metabase/admin/performance/constants/simple";
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 { getShortStrategyLabel } from "metabase/admin/performance/utils";
+import { DebouncedSearchInput } from "metabase/common/components/DebouncedSearchInput";
import { DelayedLoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/DelayedLoadingAndErrorWrapper";
-import { Sidesheet } from "metabase/common/components/Sidesheet";
-import { Table } from "metabase/common/components/Table";
-import type { ColumnItem } from "metabase/common/components/Table/types";
+import { PaginationControls } from "metabase/common/components/PaginationControls";
import { usePagination } from "metabase/common/hooks/use-pagination";
-import { Center, Flex, Repeat, Skeleton, Stack } from "metabase/ui";
-import type { CacheSortColumn, CacheableModel } from "metabase-types/api";
-import type { SortDirection } from "metabase-types/api/sorting";
+import { useGetIcon } from "metabase/hooks/use-icon";
+import { Center, Flex, Text } from "metabase/ui";
+import type { CacheableModel } from "metabase-types/api";
-import type { CacheableItem, UpdateTarget } from "../types";
+import { PolicySidePanel } from "../PolicySidePanel";
+import {
+ DEFAULT_POLICY_TABLE_SORTING,
+ PolicyTable,
+ type PolicyTableRowBase,
+ getAdjacentRows,
+ sortPolicyRows,
+} from "../PolicyTable";
+import type { UpdateTarget } from "../types";
-import Styles from "./StrategyEditorForQuestionsAndDashboards.module.css";
-import { TableRowForCacheableItem } from "./TableRowForCacheableItem";
-import { getConstants } from "./constants";
+import {
+ type CachingFilters,
+ CachingPoliciesFilters,
+ EMPTY_CACHING_FILTERS,
+} from "./CachingPoliciesFilters";
const PAGE_SIZE = 25;
+const MIN_ITEMS_TO_SHOW_SEARCH = 11;
+
+type ItemRow = PolicyTableRowBase & {
+ itemId: number;
+ model: CacheableModel;
+};
export const StrategyEditorForQuestionsAndDashboards = () => {
+ const getIcon = useGetIcon();
+
const [
// The targetId is the id of the object that is currently being edited
targetId,
setTargetId,
] = useState<number | null>(null);
-
- const { tableColumns } = useMemo(() => getConstants(), []);
-
const [targetModel, setTargetModel] = useState<CacheableModel | null>(null);
-
+ const [searchQuery, setSearchQuery] = useState("");
+ const [filters, setFilters] = useState<CachingFilters>(EMPTY_CACHING_FILTERS);
+ const [sorting, setSorting] = useState<SortingState>(
+ DEFAULT_POLICY_TABLE_SORTING,
+ );
const { page, setPage, resetPage } = usePagination();
- const [sortColumn, setSortColumn] = useState<CacheSortColumn>("name");
- const [sortDirection, setSortDirection] = useState<SortDirection>("asc");
-
- const { configs, total, error, isLoading } = useCacheConfigs({
- model: ["dashboard", "question"],
- limit: PAGE_SIZE,
- offset: page * PAGE_SIZE,
- sort_column: sortColumn,
- sort_direction: sortDirection,
+ // Fetched without a limit so search/filter/sort/pagination can run client
+ // side: the list only holds items with their own policies, so it stays small
+ const { configs, error, isLoading } = useCacheConfigs({
+ model: ["root", "dashboard", "question"],
});
- // Handle sort column click
- const handleSort = useCallback(
- (columnName: string, direction: SortDirection) => {
- // Unjustified type cast. FIXME
- setSortColumn(columnName as CacheSortColumn);
- setSortDirection(direction);
- resetPage();
- },
- [resetPage],
- );
+ const rootStrategy =
+ _.findWhere(configs ?? [], { model_id: rootId })?.strategy ??
+ defaultRootStrategy;
- const cacheableItems: CacheableItem[] = useMemo(() => {
- if (configs === undefined) {
- return [];
- }
- return configs
- .filter((config) => config.name !== undefined)
+ const allRows: ItemRow[] = useMemo(() => {
+ return (configs ?? [])
+ .filter((config) => config.model !== "root" && config.name !== undefined)
.map((config) => ({
- id: config.model_id,
+ id: `${config.model}:${config.model_id}`,
+ itemId: config.model_id,
model: config.model,
- strategy: config.strategy,
- name: config.name,
- collection: config.collection ?? undefined,
- iconModel: config.model === "question" ? "card" : "dashboard",
+ name: config.name ?? "",
+ icon: getIcon({
+ model: config.model === "question" ? "card" : "dashboard",
+ }).name,
+ collection: config.collection ?? null,
+ policyLabel: getShortStrategyLabel(config.strategy) ?? null,
+ usesDefaultPolicy: _.isEqual(config.strategy, rootStrategy),
}));
- }, [configs]);
+ }, [configs, rootStrategy, getIcon]);
+
+ const filteredRows = useMemo(() => {
+ const query = searchQuery.trim().toLowerCase();
+ return allRows.filter((row) => {
+ const matchesSearch =
+ query === "" ||
+ row.name.toLowerCase().includes(query) ||
+ row.collection?.name?.toLowerCase().includes(query);
+ const matchesPolicy =
+ filters.policy === null ||
+ (filters.policy === "default") === row.usesDefaultPolicy;
+ const matchesType = filters.type === null || filters.type === row.model;
+ return matchesSearch && matchesPolicy && matchesType;
+ });
+ }, [allRows, searchQuery, filters]);
+
+ const sortedRows = useMemo(
+ () => sortPolicyRows(filteredRows, sorting),
+ [filteredRows, sorting],
+ );
+
+ const paginatedRows = useMemo(
+ () => sortedRows.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE),
+ [sortedRows, page],
+ );
+
+ const shouldShowControls = allRows.length >= MIN_ITEMS_TO_SHOW_SEARCH;
+
+ const {
+ askBeforeDiscardingChanges,
+ confirmationModal,
+ isStrategyFormDirty,
+ setIsStrategyFormDirty,
+ } = useConfirmIfFormIsDirty();
useEffect(
/** When the user configures an item to 'Use default' and that item
* disappears from the table, it should no longer be the target */
function removeTargetIfNoLongerInTable() {
- const isTargetIdInTable = cacheableItems.some(
- (item) => item.id === targetId,
+ const isTargetInTable = allRows.some(
+ (row) => row.itemId === targetId && row.model === targetModel,
);
- if (targetId !== null && !isTargetIdInTable) {
+ if (targetId !== null && !isTargetInTable) {
setTargetId(null);
setTargetModel(null);
+ // The form unmounts mid-save with its values still differing from the
+ // deleted config, so nothing else would clear the dirty flag
+ setIsStrategyFormDirty(false);
}
},
- [targetId, cacheableItems],
+ [targetId, targetModel, allRows, setIsStrategyFormDirty],
);
- /** The config for the object currently being edited */
const targetConfig =
configs && targetModel
? _.findWhere(configs, {
@@ -101,25 +151,14 @@ export const StrategyEditorForQuestionsAndDashboards = () => {
const savedStrategy = targetConfig?.strategy;
- const targetName = useMemo(() => {
- if (targetId === null || targetModel === null) {
- return;
- }
- const item = _.findWhere(cacheableItems, {
- id: targetId,
- model: targetModel,
- });
- return item?.name;
- }, [targetId, targetModel, cacheableItems]);
-
- const {
- askBeforeDiscardingChanges,
- confirmationModal,
- isStrategyFormDirty,
- setIsStrategyFormDirty,
- } = useConfirmIfFormIsDirty();
+ const targetRow = useMemo(
+ () =>
+ allRows.find(
+ (row) => row.itemId === targetId && row.model === targetModel,
+ ),
+ [allRows, targetId, targetModel],
+ );
- /** Change the target, but first confirm if the form is unsaved */
const updateTarget: UpdateTarget = useCallback(
({ id: newTargetId, model: newTargetModel }, isFormDirty) => {
if (targetId !== newTargetId || targetModel !== newTargetModel) {
@@ -147,87 +186,123 @@ export const StrategyEditorForQuestionsAndDashboards = () => {
const saveStrategy = useSaveStrategy(targetId, targetModel);
- const hasPagination = (total ?? 0) > PAGE_SIZE;
-
- const rowRenderer = useCallback(
- (item: CacheableItem) => (
- <TableRowForCacheableItem
- updateTarget={updateTarget}
- currentTargetId={targetId}
- currentTargetModel={targetModel}
- forId={item.id}
- item={item}
- isFormDirty={isStrategyFormDirty}
- />
- ),
- [updateTarget, targetId, targetModel, isStrategyFormDirty],
+ const targetRowIndex = paginatedRows.findIndex(
+ (row) => row.itemId === targetId && row.model === targetModel,
+ );
+ const { previousRow, nextRow } = getAdjacentRows(
+ paginatedRows,
+ targetRowIndex,
);
- const explanatoryAsideId = "mb-explanatory-aside";
+ const navigateToRow = useCallback(
+ (row: ItemRow) =>
+ updateTarget({ id: row.itemId, model: row.model }, isStrategyFormDirty),
+ [updateTarget, isStrategyFormDirty],
+ );
const closeForm = useCallback(() => {
updateTarget({ id: null, model: null }, isStrategyFormDirty);
}, [updateTarget, isStrategyFormDirty]);
- return (
- <SettingsPageWrapper
- title={t`Caching for dashboards and questions`}
- description={t`Here are the dashboards and questions that have their own caching policies, which override any default or database policies you’ve set.`}
- >
- <Stack
- gap="xl"
- style={{
- flex: 1,
- overflowY: "auto",
- }}
- >
- {confirmationModal}
- <Flex>
- <DelayedLoadingAndErrorWrapper
- error={error}
- loading={isLoading}
- loader={<TableSkeleton columns={tableColumns} />}
- >
- <Table<CacheableItem>
- className={Styles.CacheableItemTable}
- columns={tableColumns}
- data-testid="cache-config-table"
- rows={cacheableItems}
- rowRenderer={rowRenderer}
- emptyBody={<NoResultsTableRow />}
- aria-labelledby={explanatoryAsideId}
- sortColumnName={sortColumn}
- sortDirection={sortDirection}
- onSort={handleSort}
- cols={
- <>
- <col />
- <col />
- <col />
- </>
- }
- paginationProps={
- hasPagination
- ? {
- page,
- pageSize: PAGE_SIZE,
- total,
- showTotal: true,
- onPageChange: setPage,
- }
- : undefined
- }
- />
- </DelayedLoadingAndErrorWrapper>
- </Flex>
- </Stack>
+ const handleSearchChange = useCallback(
+ (query: string) => {
+ setSearchQuery(query);
+ resetPage();
+ },
+ [resetPage],
+ );
- <Sidesheet
- isOpen={targetId !== null && targetModel !== null}
- onClose={closeForm}
- title={targetName ?? `Untitled ${targetModel}`}
- >
- {targetModel && (
+ const handleFiltersChange = useCallback(
+ (nextFilters: CachingFilters) => {
+ setFilters(nextFilters);
+ resetPage();
+ },
+ [resetPage],
+ );
+
+ const handleSortingChange = useCallback(
+ (nextSorting: SortingState) => {
+ setSorting(nextSorting);
+ resetPage();
+ },
+ [resetPage],
+ );
+
+ if (error || isLoading) {
+ return <DelayedLoadingAndErrorWrapper error={error} loading={isLoading} />;
+ }
+
+ return (
+ <Flex h="100%" wrap="nowrap">
+ <PerformancePageContent>
+ <SettingsPageWrapper
+ title={t`Dashboard and question caching`}
+ description={t`These dashboards and questions have custom caching policies that override default or database-level policies.`}
+ descriptionProps={{ maw: "100%" }}
+ h="calc(100vh - 9rem)"
+ >
+ {confirmationModal}
+ {shouldShowControls && (
+ <Flex gap="md" align="center">
+ <DebouncedSearchInput
+ value={searchQuery}
+ placeholder={t`Search by name or collection…`}
+ onChange={handleSearchChange}
+ />
+ <CachingPoliciesFilters
+ filters={filters}
+ onChange={handleFiltersChange}
+ />
+ </Flex>
+ )}
+ <PolicyTable
+ rows={paginatedRows}
+ withCollectionColumn
+ sorting={sorting}
+ onSortingChange={handleSortingChange}
+ selectedRowId={targetRow?.id ?? null}
+ onRowClick={navigateToRow}
+ emptyState={
+ <Center p="xl">
+ <Text fw="bold" c="text-secondary">
+ {allRows.length === 0
+ ? t`No dashboards or questions have their own caching policies yet.`
+ : t`No results`}
+ </Text>
+ </Center>
+ }
+ data-testid="cache-config-table"
+ />
+ {sortedRows.length > PAGE_SIZE && (
+ <Flex justify="end">
+ <PaginationControls
+ page={page}
+ pageSize={PAGE_SIZE}
+ itemsLength={paginatedRows.length}
+ total={sortedRows.length}
+ showTotal
+ onPreviousPage={() => setPage(page - 1)}
+ onNextPage={() => setPage(page + 1)}
+ />
+ </Flex>
+ )}
+ </SettingsPageWrapper>
+ </PerformancePageContent>
+ {targetId !== null && targetModel !== null && (
+ <PolicySidePanel
+ title={
+ targetRow?.name ??
+ (targetModel === "dashboard"
+ ? t`Untitled dashboard`
+ : t`Untitled question`)
+ }
+ subtitle={targetRow?.collection?.name}
+ onPrevious={
+ previousRow ? () => navigateToRow(previousRow) : undefined
+ }
+ onNext={nextRow ? () => navigateToRow(nextRow) : undefined}
+ onClose={closeForm}
+ >
<StrategyForm
targetId={targetId}
targetModel={targetModel}
@@ -237,34 +312,11 @@ export const StrategyEditorForQuestionsAndDashboards = () => {
savedStrategy={savedStrategy}
shouldAllowInvalidation={true}
shouldShowName={false}
- onReset={closeForm}
+ onCancel={closeForm}
layout="sidebar"
/>
- )}
- </Sidesheet>
- </SettingsPageWrapper>
+ </PolicySidePanel>
+ )}
+ </Flex>
);
};
-
-const TableSkeleton = ({ columns }: { columns: ColumnItem[] }) => (
- <Table<{ id: number }>
- columns={columns}
- rows={[{ id: 0 }, { id: 1 }, { id: 2 }]}
- rowRenderer={() => (
- <tr className={Styles.SkeletonTableRow}>
- <Repeat times={3}>
- <td>
- <Skeleton h="1rem" natural />
- </td>
- </Repeat>
- </tr>
- )}
- className={Styles.CacheableItemTable}
- />
-);
-
-const NoResultsTableRow = () => (
- <Center fw="bold" c="text-disabled">
- {t`No dashboards or questions have their own caching policies yet.`}
- </Center>
-);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.unit.spec.tsx
new file mode 100644
index 00000000000..9affa93cfdd
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards.unit.spec.tsx
@@ -0,0 +1,276 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupEnterprisePlugins } from "__support__/enterprise";
+import { setupTokenStatusEndpoint } from "__support__/server-mocks";
+import { setupPerformanceEndpoints } from "__support__/server-mocks/performance";
+import { mockSettings } from "__support__/settings";
+import { createMockEntitiesState } from "__support__/store";
+import {
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import { createMockState } from "metabase/redux/store/mocks";
+import { Route } from "metabase/router";
+import type {
+ CacheConfig,
+ CacheConfigWithDetails,
+ CacheStrategy,
+ CacheableModel,
+} from "metabase-types/api";
+import { CacheDurationUnit } from "metabase-types/api";
+import {
+ createMockCacheConfig,
+ createMockCollection,
+ createMockSettings,
+ createMockTokenFeatures,
+} from "metabase-types/api/mocks";
+
+import { StrategyEditorForQuestionsAndDashboards } from "./StrategyEditorForQuestionsAndDashboards";
+
+const ROOT_STRATEGY: CacheStrategy = {
+ type: "duration",
+ duration: 1,
+ unit: CacheDurationUnit.Hours,
+ refresh_automatically: false,
+};
+
+const NO_CACHE_STRATEGY: CacheStrategy = { type: "nocache" };
+
+const createItemConfig = ({
+ model,
+ id,
+ name,
+ collectionName,
+ strategy,
+}: {
+ model: CacheableModel;
+ id: number;
+ name: string;
+ collectionName: string;
+ strategy: CacheStrategy;
+}): CacheConfigWithDetails => ({
+ ...createMockCacheConfig({ model, model_id: id, strategy }),
+ name,
+ collection: createMockCollection({ id: 1, name: collectionName }),
+});
+
+const getDefaultConfigs = (): CacheConfig[] => [
+ createMockCacheConfig({
+ model: "root",
+ model_id: 0,
+ strategy: ROOT_STRATEGY,
+ }),
+ createItemConfig({
+ model: "dashboard",
+ id: 1,
+ name: "Sales dashboard",
+ collectionName: "Product",
+ // Matches the root strategy, so it counts as the default policy
+ strategy: ROOT_STRATEGY,
+ }),
+ createItemConfig({
+ model: "question",
+ id: 1,
+ name: "Revenue question",
+ collectionName: "Finance",
+ strategy: NO_CACHE_STRATEGY,
+ }),
+];
+
+const getManyConfigs = (itemCount: number): CacheConfig[] => [
+ createMockCacheConfig({
+ model: "root",
+ model_id: 0,
+ strategy: ROOT_STRATEGY,
+ }),
+ ...Array.from({ length: itemCount }, (_, i) =>
+ createItemConfig({
+ model: i % 2 === 0 ? "dashboard" : "question",
+ id: i + 1,
+ name: `Item ${i + 1}`,
+ collectionName: i % 2 === 0 ? "Collection Apples" : "Collection Bananas",
+ strategy: NO_CACHE_STRATEGY,
+ }),
+ ),
+];
+
+const setup = ({
+ configs = getDefaultConfigs(),
+}: { configs?: CacheConfig[] } = {}) => {
+ mockGetBoundingClientRect({ height: 800, width: 1000 });
+ setupEnterprisePlugins();
+ setupTokenStatusEndpoint({ valid: true });
+ setupPerformanceEndpoints(configs);
+
+ const storeInitialState = createMockState({
+ entities: createMockEntitiesState({}),
+ settings: mockSettings(
+ createMockSettings({
+ "token-features": createMockTokenFeatures({
+ cache_granular_controls: true,
+ }),
+ }),
+ ),
+ });
+
+ renderWithProviders(
+ <Route path="*" element={<StrategyEditorForQuestionsAndDashboards />} />,
+ { storeInitialState, withRouter: true },
+ );
+};
+
+describe("StrategyEditorForQuestionsAndDashboards", () => {
+ it("shows rows with name, collection and policy", async () => {
+ setup();
+ expect(await screen.findByText("Sales dashboard")).toBeInTheDocument();
+ expect(screen.getByText("Revenue question")).toBeInTheDocument();
+ expect(screen.getByText("Product")).toBeInTheDocument();
+ expect(screen.getByText("Finance")).toBeInTheDocument();
+ });
+
+ it("shows the policy in a lighter color when it matches the default policy", async () => {
+ setup();
+ expect(await screen.findByText("Duration: 1h")).toHaveAttribute(
+ "data-uses-default-policy",
+ "true",
+ );
+ expect(screen.getByText("No caching")).toHaveAttribute(
+ "data-uses-default-policy",
+ "false",
+ );
+ });
+
+ it("shows an empty state when nothing has its own caching policy", async () => {
+ setup({
+ configs: [
+ createMockCacheConfig({
+ model: "root",
+ model_id: 0,
+ strategy: ROOT_STRATEGY,
+ }),
+ ],
+ });
+ expect(
+ await screen.findByText(
+ "No dashboards or questions have their own caching policies yet.",
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it("hides search and filter with 10 or fewer items", async () => {
+ setup();
+ await screen.findByText("Sales dashboard");
+ expect(
+ screen.queryByPlaceholderText("Search by name or collection…"),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("Show filters")).not.toBeInTheDocument();
+ });
+
+ it("searches by name or collection with more than 10 items", async () => {
+ setup({ configs: getManyConfigs(12) });
+ const searchInput = await screen.findByPlaceholderText(
+ "Search by name or collection…",
+ );
+
+ await userEvent.type(searchInput, "Item 3");
+ await waitFor(() => {
+ expect(screen.queryByText("Item 1")).not.toBeInTheDocument();
+ });
+ expect(screen.getByText("Item 3")).toBeInTheDocument();
+
+ await userEvent.clear(searchInput);
+ await userEvent.type(searchInput, "Bananas");
+ // Even-numbered items live in "Collection Bananas"
+ expect(await screen.findByText("Item 2")).toBeInTheDocument();
+ expect(screen.getByText("Item 4")).toBeInTheDocument();
+ expect(screen.queryByText("Item 1")).not.toBeInTheDocument();
+ });
+
+ it("filters by caching policy and type", async () => {
+ const configs = getManyConfigs(12);
+ // Give one dashboard a policy matching the default
+ configs[1] = createItemConfig({
+ model: "dashboard",
+ id: 1,
+ name: "Item 1",
+ collectionName: "Collection Apples",
+ strategy: ROOT_STRATEGY,
+ });
+ setup({ configs });
+ await screen.findByText("Item 1");
+
+ await userEvent.click(screen.getByLabelText("Show filters"));
+ await userEvent.click(await screen.findByText("Default"));
+ await userEvent.click(screen.getByRole("button", { name: "Apply" }));
+ await waitFor(() => {
+ expect(screen.queryByText("Item 2")).not.toBeInTheDocument();
+ });
+ expect(screen.getByText("Item 1")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByLabelText("Show filters"));
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Clear filters" }),
+ );
+ expect(await screen.findByText("Item 2")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByLabelText("Show filters"));
+ await userEvent.click(await screen.findByText("Question"));
+ await userEvent.click(screen.getByRole("button", { name: "Apply" }));
+ await waitFor(() => {
+ // Odd-numbered items are dashboards
+ expect(screen.queryByText("Item 1")).not.toBeInTheDocument();
+ });
+ expect(screen.getByText("Item 2")).toBeInTheDocument();
+ });
+
+ it("opens the policy form in a sidesheet on row click", async () => {
+ setup();
+ await userEvent.click(await screen.findByText("Revenue question"));
+
+ const sidesheet = await screen.findByTestId("cache-policy-panel");
+ expect(
+ await within(sidesheet).findByText("Revenue question"),
+ ).toBeInTheDocument();
+ expect(within(sidesheet).getByText("Finance")).toBeInTheDocument();
+ expect(
+ within(sidesheet).getByTestId("cache-strategy-select"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not ask to discard after saving an item back to the default policy", async () => {
+ setup();
+ await userEvent.click(await screen.findByText("Revenue question"));
+ await userEvent.click(await screen.findByTestId("cache-strategy-select"));
+ await userEvent.click(
+ await screen.findByRole("option", { name: /^Default/ }),
+ );
+ await userEvent.click(screen.getByTestId("strategy-form-submit-button"));
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("cache-policy-panel"),
+ ).not.toBeInTheDocument();
+ });
+
+ await userEvent.click(screen.getByText("Sales dashboard"));
+ expect(
+ await screen.findByTestId("cache-strategy-select"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText("Discard your changes?")).not.toBeInTheDocument();
+ });
+
+ it("paginates when there are more than 25 items", async () => {
+ setup({ configs: getManyConfigs(26) });
+ await screen.findByText("Item 1");
+
+ expect(screen.getByTestId("pagination-total")).toHaveTextContent("26");
+ // Sorted by name: "Item 1", "Item 10" ... "Item 9" occupy the first page
+ expect(screen.queryByText("Item 9")).not.toBeInTheDocument();
+
+ await userEvent.click(screen.getByTestId("next-page-btn"));
+ expect(await screen.findByText("Item 9")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/TableRowForCacheableItem.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/TableRowForCacheableItem.tsx
deleted file mode 100644
index b4a17eadff9..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/TableRowForCacheableItem.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-import { useMemo } from "react";
-
-import { getShortStrategyLabel } from "metabase/admin/performance/utils";
-import { EllipsifiedCollectionPath } from "metabase/common/components/EllipsifiedPath/EllipsifiedCollectionPath";
-import { Link } from "metabase/common/components/Link";
-import { useGetIcon } from "metabase/hooks/use-icon";
-import { Box, Button, Ellipsified, FixedSizeIcon, Flex } from "metabase/ui";
-import * as Urls from "metabase/urls";
-import type { CacheableModel } from "metabase-types/api";
-
-import type { CacheableItem, UpdateTarget } from "../types";
-import { getItemUrl } from "../utils";
-
-import StrategyEditorForQuestionsAndDashboardsS from "./StrategyEditorForQuestionsAndDashboards.module.css";
-
-export const TableRowForCacheableItem = ({
- item,
- forId,
- currentTargetId,
- currentTargetModel,
- updateTarget,
- isFormDirty,
-}: {
- item: CacheableItem;
- forId: number;
- currentTargetId: number | null;
- currentTargetModel: CacheableModel | null;
- updateTarget: UpdateTarget;
- isFormDirty: boolean;
-}) => {
- const getIcon = useGetIcon();
- const { name, id, collection, model, strategy, iconModel } = item;
-
- const iconName = iconModel
- ? getIcon({ model: iconModel || "card" }).name
- : null;
-
- const url = useMemo(
- // Unjustified type cast. FIXME
- () => getItemUrl(model, item as { id: number; name: string }) || undefined,
- [model, item],
- );
-
- const launchForm = () => {
- if (currentTargetId !== item.id || currentTargetModel !== item.model) {
- updateTarget({ id, model }, isFormDirty);
- }
- };
-
- const cellContent = (
- <Flex
- className={StrategyEditorForQuestionsAndDashboardsS.ItemLink}
- align="center"
- wrap="nowrap"
- gap="sm"
- fw={700}
- style={{ overflow: "hidden" }}
- >
- {iconName ? <FixedSizeIcon name={iconName} /> : <Box h="sm" w="md" />}
- <Ellipsified>{name}</Ellipsified>
- </Flex>
- );
-
- return (
- <tr
- className={
- currentTargetId !== null && currentTargetId === forId
- ? StrategyEditorForQuestionsAndDashboardsS.currentTarget
- : undefined
- }
- >
- <td>{url ? <Link to={url}>{cellContent}</Link> : cellContent}</td>
- <td>
- {collection && (
- <Link
- className={StrategyEditorForQuestionsAndDashboardsS.CollectionLink}
- to={Urls.collection(collection)}
- >
- <EllipsifiedCollectionPath collection={collection} />
- </Link>
- )}
- </td>
- <td>
- <Button variant="subtle" onClick={() => launchForm()} p={0} fw="bold">
- {getShortStrategyLabel(strategy)}
- </Button>
- </td>
- </tr>
- );
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/constants.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/constants.tsx
deleted file mode 100644
index 9a0d3be9144..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyEditorForQuestionsAndDashboards/constants.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { t } from "ttag";
-
-import type { ColumnItem } from "metabase/common/components/Table/types";
-
-/** Retrieve constants for the dashboard and question caching table
- *
- * Some constants need to be defined within the component's scope so that ttag.t knows the current locale */
-export const getConstants = () => {
- const tableColumns: ColumnItem[] = [
- { key: "name", name: t`Name`, sortable: true },
- { key: "collection", name: t`Collection`, sortable: true },
- { key: "policy", name: t`Policy`, sortable: true },
- ];
- return { tableColumns };
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.module.css
deleted file mode 100644
index ba9e167e4d7..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.module.css
+++ /dev/null
@@ -1,49 +0,0 @@
-.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-neutral);
- background-color: var(--mb-color-background_page-primary);
- font-weight: bold;
- cursor: pointer;
-}
-
-.launcher[data-for-root="true"] {
- background-color: var(--mb-color-background_page-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-core-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.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.tsx
deleted file mode 100644
index 734b13afae5..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-import { t } from "ttag";
-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 {
- Box,
- Button,
- FixedSizeIcon,
- Flex,
- Title,
- Tooltip,
- useHover,
-} from "metabase/ui";
-import type { CacheConfig } from "metabase-types/api";
-
-import S from "./StrategyFormLauncher.module.css";
-
-export type StrategyFormLauncherProps = {
- forId: number;
- targetId: number | null;
- title: string;
- updateTargetId: UpdateTargetId;
- configs: CacheConfig[];
- isFormDirty: boolean;
-};
-
-export const StrategyFormLauncher = ({
- forId,
- targetId,
- title,
- updateTargetId,
- configs,
- isFormDirty,
-}: StrategyFormLauncherProps) => {
- const forRoot = forId === rootId;
-
- const config = findWhere(configs, { model_id: forId });
- const rootConfig = findWhere(configs, { model: "root" });
-
- const rootStrategy = rootConfig?.strategy ?? { type: "nocache" };
- const savedStrategy = config?.strategy;
-
- const inheritsRootStrategy = !forRoot && savedStrategy === undefined;
- const strategy = savedStrategy ?? rootStrategy;
- const isBeingEdited = targetId === forId;
-
- const { hovered, ref: hoveredRef } = useHover<HTMLElement>();
-
- const buttonVariant =
- isBeingEdited || hovered
- ? "filled"
- : inheritsRootStrategy || forRoot
- ? "default"
- : "outline";
- const shortStrategyLabel = getShortStrategyLabel(
- inheritsRootStrategy ? rootStrategy : strategy,
- );
-
- const ariaLabel = forRoot
- ? t`Edit default policy (currently: ${shortStrategyLabel})`
- : inheritsRootStrategy
- ? t`Edit policy for database '${title}' (currently inheriting the default policy, ${getShortStrategyLabel(
- rootStrategy,
- )})`
- : t`Edit policy for database '${title}' (currently: ${shortStrategyLabel})`;
-
- const launchForm = () => {
- if (targetId !== forId) {
- updateTargetId(forId, isFormDirty);
- }
- };
- const shouldDisableTooltip = !inheritsRootStrategy;
-
- return (
- <Box
- ref={hoveredRef}
- className={S.launcher}
- data-for-root={forRoot}
- data-inherits-root={inheritsRootStrategy}
- aria-label={ariaLabel}
- onClick={launchForm}
- data-testid={`strategy-form-launcher${
- shouldDisableTooltip ? "" : "-with-tooltip"
- }`}
- >
- <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="sm">
- <Tooltip
- position="bottom"
- disabled={shouldDisableTooltip}
- label={t`Using default policy`}
- >
- <Button
- className={S.token}
- onClick={launchForm}
- variant={buttonVariant}
- fw={forRoot || inheritsRootStrategy ? "normal" : "bold"}
- lh="1.5rem"
- p="0.25rem .75rem"
- mah="3rem"
- radius="7rem"
- >
- {shortStrategyLabel}
- </Button>
- </Tooltip>
- </Flex>
- </Box>
- );
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.unit.spec.tsx
deleted file mode 100644
index b5139468910..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncher.unit.spec.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import _ from "underscore";
-
-import { setupEnterprisePlugins } from "__support__/enterprise";
-import { mockSettings } from "__support__/settings";
-import { createMockEntitiesState } from "__support__/store";
-import { renderWithProviders, screen } from "__support__/ui";
-import { rootId } from "metabase/admin/performance/constants/simple";
-import { createMockState } from "metabase/redux/store/mocks";
-import { CacheDurationUnit } from "metabase-types/api";
-import {
- createMockSettings,
- createMockTokenFeatures,
-} from "metabase-types/api/mocks";
-
-import {
- StrategyFormLauncher,
- type StrategyFormLauncherProps,
-} from "./StrategyFormLauncher";
-
-const defaultProps: Pick<
- StrategyFormLauncherProps,
- "configs" | "isFormDirty" | "updateTargetId"
-> = {
- configs: [
- {
- model: "root",
- model_id: 0,
- strategy: {
- type: "duration",
- duration: 96,
- unit: CacheDurationUnit.Hours,
- refresh_automatically: false,
- },
- },
- { model: "database", model_id: 1, strategy: { type: "nocache" } },
- ],
- isFormDirty: false,
- updateTargetId: _.noop,
-};
-
-const renderStrategyFormLauncher = (props: StrategyFormLauncherProps) => {
- const storeInitialState = createMockState({
- entities: createMockEntitiesState({}),
- settings: mockSettings(
- createMockSettings({
- "token-features": createMockTokenFeatures({
- cache_granular_controls: true,
- }),
- }),
- ),
- });
-
- setupEnterprisePlugins();
-
- return renderWithProviders(<StrategyFormLauncher {...props} />, {
- storeInitialState,
- });
-};
-
-describe("StrategyFormLauncher", () => {
- it("can render a button representing the default policy", async () => {
- renderStrategyFormLauncher({
- forId: rootId,
- targetId: null,
- title: "Default policy",
- ...defaultProps,
- });
- const launcher = await screen.findByLabelText(
- "Edit default policy (currently: Duration: 96h)",
- );
- expect(launcher).toHaveTextContent("Default policy");
- expect(launcher).toHaveAttribute("data-testid", "strategy-form-launcher");
- });
-
- it("can render a button representing a database with a Don't cache policy", async () => {
- renderStrategyFormLauncher({
- forId: 1,
- targetId: null,
- title: "Database 1",
- ...defaultProps,
- });
- const launcher = await screen.findByLabelText(
- "Edit policy for database 'Database 1' (currently: No caching)",
- );
- expect(launcher).toHaveTextContent("Database 1");
- expect(launcher).toHaveAttribute("data-testid", "strategy-form-launcher");
- });
-
- it("can render a button representing a database that inherits root policy", async () => {
- renderStrategyFormLauncher({
- forId: 2,
- targetId: null,
- title: "Database 2",
- ...defaultProps,
- });
- const launcher = await screen.findByLabelText(
- "Edit policy for database 'Database 2' (currently inheriting the default policy, Duration: 96h)",
- );
- expect(launcher).toHaveTextContent("Database 2");
- expect(launcher).toHaveAttribute(
- "data-testid",
- "strategy-form-launcher-with-tooltip",
- );
- });
-});
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.module.css b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.module.css
deleted file mode 100644
index 649e4422165..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.module.css
+++ /dev/null
@@ -1,25 +0,0 @@
-.root {
- overflow-y: auto;
-}
-
-.section {
- padding: var(--mantine-spacing-lg);
-}
-
-.divided {
- border-bottom: 1px solid var(--mb-color-border-neutral);
-}
-
-.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.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.tsx
deleted file mode 100644
index 8aab7d688b2..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/StrategyFormLauncherPanel.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import cx from "classnames";
-import { useMemo } from "react";
-import { t } from "ttag";
-
-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";
-
-import { useResetToDefaultForm } from "../hooks/useResetToDefaultForm";
-
-import { ResetButtonContainer } from "./ResetButtonContainer";
-import { StrategyFormLauncher } from "./StrategyFormLauncher";
-import S from "./StrategyFormLauncherPanel.module.css";
-
-export const StrategyFormLauncherPanel = ({
- configs,
- targetId,
- updateTargetId,
- databases,
- isStrategyFormDirty,
- shouldShowResetButton,
-}: {
- configs: CacheConfig[];
- targetId: number | null;
- updateTargetId: UpdateTargetId;
- databases: Database[];
- isStrategyFormDirty: boolean;
- shouldShowResetButton: boolean;
-}) => {
- const databaseIds = useMemo(() => databases.map((db) => db.id), [databases]);
-
- const {
- handleSubmit: resetAllToDefault,
- versionNumber: resetFormVersionNumber,
- } = useResetToDefaultForm({
- databaseIds,
- isFormVisible: targetId !== null,
- });
-
- return (
- <Box
- component="section"
- role="group"
- h="100%"
- bg="background_page-secondary"
- className={S.root}
- >
- <Box className={cx(S.section, S.divided)}>
- <StrategyFormLauncher
- forId={rootId}
- title={t`Default policy`}
- configs={configs}
- targetId={targetId}
- updateTargetId={updateTargetId}
- isFormDirty={isStrategyFormDirty}
- />
- </Box>
- <Stack className={cx(S.section, S.stack)}>
- {databases?.map((db) => (
- <StrategyFormLauncher
- forId={db.id}
- title={db.name}
- configs={configs}
- targetId={targetId}
- updateTargetId={updateTargetId}
- isFormDirty={isStrategyFormDirty}
- key={`database_${db.id}`}
- />
- ))}
- </Stack>
- <FormProvider
- initialValues={{}}
- onSubmit={resetAllToDefault}
- key={resetFormVersionNumber} // To avoid using stale context
- >
- {shouldShowResetButton && <ResetButtonContainer />}
- </FormProvider>
- </Box>
- );
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/components/utils.tsx b/enterprise/frontend/src/metabase-enterprise/caching/components/utils.tsx
index 3cd89c42922..023624d2e38 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/components/utils.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/components/utils.tsx
@@ -1,7 +1,5 @@
-import { match } from "ts-pattern";
import { t } from "ttag";
-import * as Urls from "metabase/urls";
import type Question from "metabase-lib/v1/Question";
import type { CacheableDashboard, CacheableModel } from "metabase-types/api";
@@ -24,12 +22,3 @@ export const getItemName = (
(item as CacheableDashboard).name
: // Unjustified type cast. FIXME
((item as Question).displayName() ?? t`Untitled question`);
-
-export const getItemUrl = (
- model: CacheableModel,
- item: { id: number; name: string },
-) =>
- match(model)
- .with("dashboard", () => Urls.dashboard(item))
- .with("question", () => Urls.card(item))
- .otherwise(() => null);
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/hooks/useResetToDefaultForm.tsx b/enterprise/frontend/src/metabase-enterprise/caching/hooks/useResetToDefaultForm.tsx
deleted file mode 100644
index a8daf28677d..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/caching/hooks/useResetToDefaultForm.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import { useCallback, useEffect, useState } from "react";
-
-import { useDeleteCacheConfigsMutation } from "metabase/api";
-
-export const useResetToDefaultForm = ({
- databaseIds,
- isFormVisible,
-}: {
- databaseIds: number[];
- isFormVisible: boolean;
-}) => {
- const [versionNumber, setVersionNumber] = useState(0);
- const [deleteCacheConfigs] = useDeleteCacheConfigsMutation();
-
- useEffect(() => {
- // Avoid stale context in the form
- if (!isFormVisible) {
- setVersionNumber((n) => n + 1);
- }
- }, [isFormVisible]);
-
- const handleSubmit = useCallback(async () => {
- if (databaseIds.length === 0) {
- return;
- }
- await deleteCacheConfigs({
- model: "database",
- model_id: databaseIds,
- }).unwrap();
- }, [databaseIds, deleteCacheConfigs]);
-
- return { handleSubmit, versionNumber };
-};
diff --git a/enterprise/frontend/src/metabase-enterprise/caching/index.tsx b/enterprise/frontend/src/metabase-enterprise/caching/index.tsx
index 52e6d951ae4..548e5968a3f 100644
--- a/enterprise/frontend/src/metabase-enterprise/caching/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/caching/index.tsx
@@ -2,14 +2,13 @@ import { PLUGIN_CACHING } from "metabase/plugins";
import { hasPremiumFeature } from "metabase-enterprise/settings";
import { DashboardAndQuestionCachingTab } from "./components/DashboardAndQuestionCachingTab";
-import { GranularControlsExplanation } from "./components/GranularControlsExplanation";
+import { DatabaseCachingEditor } from "./components/DatabaseCachingEditor";
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";
import { StrategyEditorForQuestionsAndDashboards } from "./components/StrategyEditorForQuestionsAndDashboards/StrategyEditorForQuestionsAndDashboards";
-import { StrategyFormLauncherPanel } from "./components/StrategyFormLauncherPanel";
import {
enterpriseOnlyCachingStrategies,
getEnterprisePerformanceTabMetadata,
@@ -22,10 +21,9 @@ import { hasQuestionCacheSection } from "./utils";
export function initializePlugin() {
if (hasPremiumFeature("cache_granular_controls")) {
PLUGIN_CACHING.isGranularCachingEnabled = () => true;
- PLUGIN_CACHING.StrategyFormLauncherPanel = StrategyFormLauncherPanel;
+ PLUGIN_CACHING.DatabaseCachingEditor = DatabaseCachingEditor;
PLUGIN_CACHING.hasQuestionCacheSection = hasQuestionCacheSection;
PLUGIN_CACHING.canOverrideRootStrategy = true;
- PLUGIN_CACHING.GranularControlsExplanation = GranularControlsExplanation;
PLUGIN_CACHING.InvalidateNowButton = InvalidateNowButton;
PLUGIN_CACHING.SidebarCacheSection = SidebarCacheSection;
PLUGIN_CACHING.SidebarCacheForm = SidebarCacheForm;
diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
index d87c0e752b0..9b2b046036b 100644
--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
@@ -1,11 +1,13 @@
import type React from "react";
+import CS from "metabase/css/core/index.css";
import {
Box,
type BoxProps,
Stack,
type StackProps,
Text,
+ type TextProps,
Title,
type TitleProps,
} from "metabase/ui";
@@ -52,28 +54,30 @@ export function SettingsSection({
export function SettingsPageWrapper({
title,
description,
+ descriptionProps,
children,
...stackProps
}: {
title?: React.ReactNode;
description?: React.ReactNode;
+ descriptionProps?: TextProps;
children: React.ReactNode;
} & Omit<StackProps, "title">) {
return (
<Stack gap="lg" {...stackProps}>
{(title || description) && (
- <Box>
+ <Stack gap="sm">
{title && (
- <Title order={1} display="flex" style={{ alignItems: "center" }}>
+ <Title order={1} display="flex" className={CS.alignCenter}>
{title}
</Title>
)}
{description && (
- <Text c="text-secondary" maw="40rem">
+ <Text c="text-secondary" lh={1.5} maw="40rem" {...descriptionProps}>
{description}
</Text>
)}
- </Box>
+ </Stack>
)}
{children}
</Stack>
diff --git a/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.tsx b/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.tsx
index c39a89c33e2..e04d2747678 100644
--- a/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.tsx
+++ b/frontend/src/metabase/admin/performance/components/ModelPersistenceConfiguration.tsx
@@ -25,6 +25,7 @@ import { useSetting } from "metabase/settings";
import { Switch, Text } from "metabase/ui";
import ModelPersistenceConfigurationS from "./ModelPersistenceConfiguration.module.css";
+import { PerformancePageContent } from "./PerformancePageContent";
const modelCachingOptions = [
{
@@ -121,59 +122,61 @@ export const ModelPersistenceConfiguration = () => {
const { url: docsUrl } = useDocsUrl("data-modeling/model-persistence");
return (
- <SettingsPageWrapper
- title={t`Model persistence`}
- description={t`Enable model persistence to make your models (and the queries that use them) load faster.`}
- >
- <SettingsSection
- className={ModelPersistenceConfigurationS.Explanation}
- maw="40rem"
+ <PerformancePageContent>
+ <SettingsPageWrapper
+ title={t`Model persistence`}
+ description={t`Enable model persistence to make your models (and the queries that use them) load faster.`}
>
- <Text>
- {c(
- '{0} is either "Metabase" or the customized name of the application.',
- )
- .t`This will create a table for each of your models in a dedicated schema. ${applicationName} will refresh them on a schedule. Questions and queries that use your models will query these tables.`}
- {showMetabaseLinks && (
- <>
- {" "}
- <ExternalLink
- key="model-caching-link"
- href={docsUrl}
- >{t`Learn more`}</ExternalLink>
- </>
- )}
- </Text>
- <DelayedLoadingAndErrorWrapper
- error={null}
- loading={modelPersistenceEnabled === undefined}
+ <SettingsSection
+ className={ModelPersistenceConfigurationS.Explanation}
+ maw="40rem"
>
- <Switch
- label={
- <Text fw="bold">
- {modelPersistenceEnabled ? t`Enabled` : t`Disabled`}
- </Text>
- }
- onChange={onSwitchChanged}
- checked={modelPersistenceEnabled}
- />
- </DelayedLoadingAndErrorWrapper>
-
- {/* modelCachingSchedule is sometimes undefined but TS thinks it is always a string */}
- {modelPersistenceEnabled && modelCachingSchedule && (
- <div>
- <ModelCachingScheduleWidget
- value={modelCachingSchedule}
- options={modelCachingOptions}
- onChange={async (value: string) => {
- await resolveWithToasts([
- setRefreshSchedule({ cron: value }).unwrap(),
- ]);
- }}
+ <Text>
+ {c(
+ '{0} is either "Metabase" or the customized name of the application.',
+ )
+ .t`This will create a table for each of your models in a dedicated schema. ${applicationName} will refresh them on a schedule. Questions and queries that use your models will query these tables.`}
+ {showMetabaseLinks && (
+ <>
+ {" "}
+ <ExternalLink
+ key="model-caching-link"
+ href={docsUrl}
+ >{t`Learn more`}</ExternalLink>
+ </>
+ )}
+ </Text>
+ <DelayedLoadingAndErrorWrapper
+ error={null}
+ loading={modelPersistenceEnabled === undefined}
+ >
+ <Switch
+ label={
+ <Text fw="bold">
+ {modelPersistenceEnabled ? t`Enabled` : t`Disabled`}
+ </Text>
+ }
+ onChange={onSwitchChanged}
+ checked={modelPersistenceEnabled}
/>
- </div>
- )}
- </SettingsSection>
- </SettingsPageWrapper>
+ </DelayedLoadingAndErrorWrapper>
+
+ {/* modelCachingSchedule is sometimes undefined but TS thinks it is always a string */}
+ {modelPersistenceEnabled && modelCachingSchedule && (
+ <div>
+ <ModelCachingScheduleWidget
+ value={modelCachingSchedule}
+ options={modelCachingOptions}
+ onChange={async (value: string) => {
+ await resolveWithToasts([
+ setRefreshSchedule({ cron: value }).unwrap(),
+ ]);
+ }}
+ />
+ </div>
+ )}
+ </SettingsSection>
+ </SettingsPageWrapper>
+ </PerformancePageContent>
);
};
diff --git a/frontend/src/metabase/admin/performance/components/PerformanceApp.module.css b/frontend/src/metabase/admin/performance/components/PerformanceApp.module.css
index 638de400de5..95fbb35088f 100644
--- a/frontend/src/metabase/admin/performance/components/PerformanceApp.module.css
+++ b/frontend/src/metabase/admin/performance/components/PerformanceApp.module.css
@@ -53,6 +53,6 @@
padding-inline: 2.5rem;
&.FormBoxSidebar {
- padding-inline: 1rem;
+ padding-inline: 0;
}
}
diff --git a/frontend/src/metabase/admin/performance/components/PerformanceApp.tsx b/frontend/src/metabase/admin/performance/components/PerformanceApp.tsx
index 1e586878b59..c0577c06c22 100644
--- a/frontend/src/metabase/admin/performance/components/PerformanceApp.tsx
+++ b/frontend/src/metabase/admin/performance/components/PerformanceApp.tsx
@@ -10,7 +10,7 @@ import { getPerformanceTabName } from "../utils";
export const PerformanceApp = () => (
<AdminSettingsLayout
- maw="60rem"
+ fullWidth
sidebar={
<AdminNavWrapper>
<AdminNavItem
diff --git a/frontend/src/metabase/admin/performance/components/PerformancePageContent.tsx b/frontend/src/metabase/admin/performance/components/PerformancePageContent.tsx
new file mode 100644
index 00000000000..1606d249f3f
--- /dev/null
+++ b/frontend/src/metabase/admin/performance/components/PerformancePageContent.tsx
@@ -0,0 +1,16 @@
+import type { ReactNode } from "react";
+
+import CS from "metabase/css/core/index.css";
+import { Box } from "metabase/ui";
+
+export const PerformancePageContent = ({
+ children,
+}: {
+ children: ReactNode;
+}) => (
+ <Box p="2rem" h="100%" flex={1} miw={0} className={CS.overflowYAuto}>
+ <Box maw="60rem" w="100%" mx="auto">
+ {children}
+ </Box>
+ </Box>
+);
diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.css b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.css
index a22c8d5c2e5..a33c630fd2a 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.css
+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.module.css
@@ -9,14 +9,6 @@
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-neutral);
-}
diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx
index e5cd5257469..e1657f2c82d 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx
+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.tsx
@@ -1,76 +1,41 @@
-import cx from "classnames";
-import type { ReactNode } from "react";
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import { t } from "ttag";
import { findWhere } from "underscore";
import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
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 { Box, Flex } from "metabase/ui";
-import type { CacheableModel } from "metabase-types/api";
import { rootId } from "../constants/simple";
import { useCacheConfigs } from "../hooks/useCacheConfigs";
import { useConfirmIfFormIsDirty } from "../hooks/useConfirmIfFormIsDirty";
import { useSaveStrategy } from "../hooks/useSaveStrategy";
-import type { UpdateTargetId } from "../types";
+import { PerformancePageContent } from "./PerformancePageContent";
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-neutral)"
- className={cx(S.roundedBox, { [S.roundedBoxTwoColumns]: twoColumns })}
- >
- {children}
- </Box>
- );
-}
-
-export const StrategyEditorForDatabases: React.FC = () => {
- const { canOverrideRootStrategy } = PLUGIN_CACHING;
+export const StrategyEditorForDatabases = () => {
+ if (PLUGIN_CACHING.canOverrideRootStrategy) {
+ return <PLUGIN_CACHING.DatabaseCachingEditor />;
+ }
+ return <RootCachingStrategyEditor />;
+};
+const RootCachingStrategyEditor = () => {
const [
// The targetId is the id of the model that is currently being edited
targetId,
setTargetId,
] = useState<number | null>(null);
- const model: CacheableModel[] = useMemo(() => {
- const ret: CacheableModel[] = ["root"];
- if (canOverrideRootStrategy) {
- ret.push("database");
- }
- return ret;
- }, [canOverrideRootStrategy]);
-
const {
configs,
- rootStrategyOverriddenOnce,
- rootStrategyRecentlyOverridden,
error: configsError,
isLoading: areConfigsLoading,
- } = useCacheConfigs({ model });
-
- const databasesResult = useListDatabasesQuery();
- const databases = databasesResult.data?.data ?? [];
-
- const shouldShowResetButton =
- rootStrategyOverriddenOnce || rootStrategyRecentlyOverridden;
+ } = useCacheConfigs({ model: ["root"] });
/** The config for the model currently being edited */
const targetConfig = findWhere(configs ?? [], {
@@ -79,107 +44,65 @@ export const StrategyEditorForDatabases: React.FC = () => {
const savedStrategy = targetConfig?.strategy;
- const {
- askBeforeDiscardingChanges,
- confirmationModal,
- isStrategyFormDirty,
- setIsStrategyFormDirty,
- } = useConfirmIfFormIsDirty();
-
- /** Update the targetId (the id of the currently edited model) but confirm if the form is unsaved */
- const updateTargetId: UpdateTargetId = (newTargetId, isFormDirty) => {
- if (targetId !== newTargetId) {
- const update = () => setTargetId(newTargetId);
- if (isFormDirty) {
- askBeforeDiscardingChanges(update);
- } else {
- update();
- }
- }
- };
+ const { confirmationModal, setIsStrategyFormDirty } =
+ useConfirmIfFormIsDirty();
useEffect(() => {
- if (!canOverrideRootStrategy && targetId === null) {
+ if (targetId === null) {
setTargetId(rootId);
}
- }, [canOverrideRootStrategy, targetId]);
-
- const targetDatabase = databases.find((db) => db.id === targetId);
-
- const shouldAllowInvalidation = useMemo(() => {
- if (
- targetId === null ||
- targetId === rootId ||
- savedStrategy?.type === "nocache"
- ) {
- return false;
- }
- const inheritingRootStrategy = ["inherit", undefined].includes(
- savedStrategy?.type,
- );
- const rootConfig = findWhere(configs ?? [], { model_id: rootId });
- const inheritingDoNotCache =
- inheritingRootStrategy && !rootConfig?.strategy;
- return !inheritingDoNotCache;
- }, [configs, savedStrategy?.type, targetId]);
+ }, [targetId]);
const saveStrategy = useSaveStrategy(targetId, "database");
- const error = configsError || databasesResult.error;
- const loading = areConfigsLoading || databasesResult.isLoading;
- if (error || loading) {
- return <DelayedLoadingAndErrorWrapper error={error} loading={loading} />;
+ if (configsError || areConfigsLoading) {
+ return (
+ <DelayedLoadingAndErrorWrapper
+ error={configsError}
+ loading={areConfigsLoading}
+ />
+ );
}
return (
- <SettingsPageWrapper
- title={t`Database caching`}
- aria-label={t`Data caching settings`}
- description={
- <>
- {t`Speed up queries by caching their results.`}
- <PLUGIN_CACHING.GranularControlsExplanation />
- </>
- }
- h="calc(100vh - 7rem)"
- >
- {confirmationModal}
- <Flex gap="xl" className={S.scrollableLayout}>
- <RoundedBox twoColumns={canOverrideRootStrategy}>
- {canOverrideRootStrategy && (
- <PLUGIN_CACHING.StrategyFormLauncherPanel
- configs={configs ?? []}
- targetId={targetId}
- updateTargetId={updateTargetId}
- databases={databases}
- isStrategyFormDirty={isStrategyFormDirty}
- shouldShowResetButton={shouldShowResetButton}
- />
- )}
+ <PerformancePageContent>
+ <SettingsPageWrapper
+ title={t`Database caching`}
+ aria-label={t`Data caching settings`}
+ description={t`Speed up queries by caching their results.`}
+ h="calc(100vh - 9rem)"
+ >
+ {confirmationModal}
+ <Flex gap="xl" className={S.scrollableLayout}>
<Box
- component="section"
- bg="background_page-primary"
- h="100%"
- className={cx(S.formPanel, {
- [S.formPanelWithLeftBorder]: canOverrideRootStrategy,
- })}
+ w="100%"
+ maw="30rem"
+ bd="2px solid var(--mb-color-border-neutral)"
+ className={S.roundedBox}
>
- {targetId !== null && (
- <StrategyForm
- targetId={targetId}
- targetModel={targetId === rootId ? "root" : "database"}
- targetName={targetDatabase?.name || t`Untitled database`}
- setIsDirty={setIsStrategyFormDirty}
- saveStrategy={saveStrategy}
- savedStrategy={savedStrategy}
- shouldAllowInvalidation={shouldAllowInvalidation}
- shouldShowName={targetId !== rootId}
- />
- )}
+ <Box
+ component="section"
+ bg="background_page-primary"
+ h="100%"
+ className={S.formPanel}
+ >
+ {targetId !== null && (
+ <StrategyForm
+ targetId={targetId}
+ targetModel="root"
+ targetName={t`Default policy`}
+ setIsDirty={setIsStrategyFormDirty}
+ saveStrategy={saveStrategy}
+ savedStrategy={savedStrategy}
+ shouldAllowInvalidation={false}
+ shouldShowName={false}
+ />
+ )}
+ </Box>
</Box>
- </RoundedBox>
- <UpsellCacheConfig location="performance-data_cache" />
- </Flex>
- </SettingsPageWrapper>
+ <UpsellCacheConfig location="performance-data_cache" />
+ </Flex>
+ </SettingsPageWrapper>
+ </PerformancePageContent>
);
};
diff --git a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx
index f4a14602057..03156d2feb3 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx
+++ b/frontend/src/metabase/admin/performance/components/StrategyEditorForDatabases.unit.spec.tsx
@@ -54,9 +54,12 @@ describe("StrategyEditorForDatabases (OSS)", () => {
it("does not regard form as dirty when a default value is entered into an input (metabase#42974)", async () => {
await selectCacheStrategy(/Adaptive/i);
+ await changeInput(/minimum query duration/i, 1, 1);
+ await changeInput(/multiplier/i, 10, 10);
await userEvent.click(await getSaveButton());
+ // Re-entering the value it was saved with does not make the form dirty,
+ // so the save button is not present
await changeInput(/multiplier/i, 10, 10);
- // The form is not considered dirty, so the save button is not present
expect(
screen.queryByTestId("strategy-form-submit-button"),
).not.toBeInTheDocument();
diff --git a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx
index e283b61899b..377d8676605 100644
--- a/frontend/src/metabase/admin/performance/components/StrategyForm.tsx
+++ b/frontend/src/metabase/admin/performance/components/StrategyForm.tsx
@@ -42,7 +42,7 @@ import type {
} from "metabase-types/api";
import { CacheDurationUnit } from "metabase-types/api";
-import { rootId } from "../constants/simple";
+import { defaultRootStrategy, rootId } from "../constants/simple";
import { useIsFormPending } from "../hooks/useIsFormPending";
import {
getDefaultValueForField,
@@ -61,7 +61,6 @@ interface ButtonLabels {
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 {
@@ -73,7 +72,7 @@ interface StrategyFormProps {
savedStrategy?: CacheStrategy;
shouldAllowInvalidation?: boolean;
shouldShowName?: boolean;
- onReset?: () => void;
+ onCancel?: () => void;
buttonLabels?: ButtonLabels;
layout?: StrategyFormLayout;
}
@@ -87,7 +86,7 @@ export const StrategyForm = ({
savedStrategy,
shouldAllowInvalidation = false,
shouldShowName = true,
- onReset,
+ onCancel,
layout = "default",
buttonLabels = layout === "default"
? {
@@ -100,7 +99,7 @@ export const StrategyForm = ({
},
}: StrategyFormProps) => {
const defaultStrategy =
- targetId === rootId ? ROOT_DEFAULT_STRATEGY : INHERIT_DEFAULT_STRATEGY;
+ targetId === rootId ? defaultRootStrategy : INHERIT_DEFAULT_STRATEGY;
const initialValues = savedStrategy ?? defaultStrategy;
@@ -110,7 +109,6 @@ export const StrategyForm = ({
initialValues={initialValues}
validationSchema={strategyValidationSchema}
onSubmit={saveStrategy}
- onReset={onReset}
enableReinitialize
>
<StrategyFormBody
@@ -123,7 +121,7 @@ export const StrategyForm = ({
buttonLabels={buttonLabels}
layout={layout}
strategyType={initialValues.type}
- onDiscard={onReset}
+ onDiscard={onCancel}
/>
</FormProvider>
);
@@ -242,7 +240,7 @@ const StrategyFormBody = ({
</Group>
</Box>
)}
- <Stack maw="35rem" pt={targetId === rootId ? "xl" : 0} gap="xl">
+ <Stack maw="35rem" gap="xl">
<StrategySelector
targetId={targetId}
model={targetModel}
@@ -254,12 +252,14 @@ const StrategyFormBody = ({
<DurationStrategyFormFields
targetModel={targetModel}
onSwitchToggle={handleSwitchToggle}
+ fullWidthFields={layout === "sidebar"}
/>
)}
{selectedStrategyType === "schedule" && (
<ScheduleStrategyFormFields
targetModel={targetModel}
onSwitchToggle={handleSwitchToggle}
+ fullWidthFields={layout === "sidebar"}
/>
)}
</Stack>
@@ -291,7 +291,7 @@ const FormButtonsGroup = ({
py="md"
gap="md"
justify={layout === "sidebar" ? "flex-end" : undefined}
- px={layout === "sidebar" ? "md" : "2.5rem"}
+ px={layout === "sidebar" ? 0 : "2.5rem"}
pb={layout === "sidebar" ? 0 : undefined}
bg={layout === "sidebar" ? undefined : "background_page-primary"}
style={
@@ -400,9 +400,11 @@ const FormButtons = ({
const ScheduleStrategyFormFields = ({
targetModel,
onSwitchToggle,
+ fullWidthFields = false,
}: {
targetModel: CacheableModel;
onSwitchToggle: () => void;
+ fullWidthFields?: boolean;
}) => {
const { values, setFieldValue } = useFormikContext<ScheduleStrategy>();
const { schedule: scheduleInCronFormat } = values;
@@ -447,6 +449,7 @@ const ScheduleStrategyFormFields = ({
onScheduleChange={onScheduleChange}
verb={c("A verb in the imperative mood").t`Invalidate`}
layout="horizontal"
+ fullWidthSelects={fullWidthFields}
timezone={timezone}
aria-label={t`Describe how often the cache should be invalidated`}
/>
@@ -507,7 +510,7 @@ export const StrategySelectorHeading = ({
}) => (
<Stack gap="xs">
<Text lh="1.25rem" fw="bold" fz="md" id={headingId}>
- {t`Select the cache invalidation policy`}
+ {t`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.`}
@@ -515,6 +518,11 @@ export const StrategySelectorHeading = ({
</Stack>
);
+const EMPTY_FIELDS_BY_STRATEGY: Partial<Record<string, string[]>> = {
+ duration: ["duration"],
+ ttl: ["min_duration_seconds", "multiplier"],
+};
+
const StrategySelector = ({
targetId,
model,
@@ -547,10 +555,20 @@ const StrategySelector = ({
<section aria-labelledby={headingId}>
{showHeading && <StrategySelectorHeading headingId={headingId} />}
<Select
- mt={showHeading ? "xl" : 0}
+ mt={showHeading ? "sm" : 0}
data={data}
value={values.type}
- onChange={(value) => value && setFieldValue("type", value)}
+ onChange={(value) => {
+ if (!value) {
+ return;
+ }
+ setFieldValue("type", value);
+ for (const fieldName of EMPTY_FIELDS_BY_STRATEGY[value] ?? []) {
+ if (!(fieldName in values)) {
+ setFieldValue(fieldName, null);
+ }
+ }
+ }}
allowDeselect={false}
aria-labelledby={headingId}
data-testid="cache-strategy-select"
@@ -642,9 +660,11 @@ const getDurationUnitOptions = (duration: number) => {
const DurationStrategyFormFields = ({
targetModel,
onSwitchToggle,
+ fullWidthFields = false,
}: {
targetModel: CacheableModel;
onSwitchToggle: () => void;
+ fullWidthFields?: boolean;
}) => {
const { values, setFieldValue } = useFormikContext<CacheStrategy>();
const unit = values.type === "duration" ? values.unit : undefined;
@@ -667,7 +687,11 @@ const DurationStrategyFormFields = ({
</Text>
}
>
- <Flex align="flex-start" gap="sm">
+ <Flex
+ align="flex-start"
+ gap="sm"
+ w={fullWidthFields ? "100%" : undefined}
+ >
<PositiveNumberInput
strategyType="duration"
name="duration"
@@ -676,7 +700,8 @@ const DurationStrategyFormFields = ({
<FormSelect
name="unit"
data={getDurationUnitOptions(duration)}
- w="8rem"
+ w={fullWidthFields ? undefined : "8rem"}
+ style={fullWidthFields ? { flexGrow: 1 } : undefined}
allowDeselect={false}
aria-label={t`Cache duration unit`}
data-testid="duration-unit-select"
diff --git a/frontend/src/metabase/admin/performance/components/test-utils.tsx b/frontend/src/metabase/admin/performance/components/test-utils.tsx
index 854468dd14a..6036ede8c4a 100644
--- a/frontend/src/metabase/admin/performance/components/test-utils.tsx
+++ b/frontend/src/metabase/admin/performance/components/test-utils.tsx
@@ -11,7 +11,13 @@ import {
import { setupPerformanceEndpoints } from "__support__/server-mocks/performance";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
-import { act, fireEvent, renderWithProviders, screen } from "__support__/ui";
+import {
+ act,
+ fireEvent,
+ mockGetBoundingClientRect,
+ renderWithProviders,
+ screen,
+} from "__support__/ui";
import { createMockState } from "metabase/redux/store/mocks";
import { Route } from "metabase/router";
import type { CacheConfig, TokenFeatures } from "metabase-types/api";
@@ -32,6 +38,7 @@ export interface SetupOpts {
enterprisePlugins?: Parameters<typeof setupEnterpriseOnlyPlugin>[0][] | "*";
tokenFeatures?: Partial<TokenFeatures>;
cacheConfigs?: CacheConfig[];
+ databaseCount?: number;
}
const getDefaultCacheConfigs = (): CacheConfig[] => [
@@ -54,7 +61,11 @@ export const setupStrategyEditorForDatabases = ({
enterprisePlugins,
tokenFeatures = {},
cacheConfigs = getDefaultCacheConfigs(),
+ databaseCount = 4,
}: SetupOpts = {}) => {
+ // TreeTable is virtualized; without measured sizes jsdom would render no rows
+ mockGetBoundingClientRect({ height: 800, width: 1000 });
+
const storeInitialState = createMockState({
entities: createMockEntitiesState({}),
settings: mockSettings(
@@ -75,7 +86,7 @@ export const setupStrategyEditorForDatabases = ({
setupPerformanceEndpoints(cacheConfigs);
- const databases = Array.from({ length: 4 }, (_, i) =>
+ const databases = Array.from({ length: databaseCount }, (_, i) =>
createSampleDatabase({ id: i + 1, name: `Database ${i + 1}`, tables: [] }),
);
setupDatabasesEndpoints(databases);
diff --git a/frontend/src/metabase/admin/performance/constants/simple.ts b/frontend/src/metabase/admin/performance/constants/simple.ts
index 4aec65a9e38..5499773f6f8 100644
--- a/frontend/src/metabase/admin/performance/constants/simple.ts
+++ b/frontend/src/metabase/admin/performance/constants/simple.ts
@@ -1 +1,6 @@
+import type { CacheStrategy } from "metabase-types/api";
+
export const rootId = 0;
+
+/** The implicit instance-wide policy when no root cache config exists */
+export const defaultRootStrategy: CacheStrategy = { type: "nocache" };
diff --git a/frontend/src/metabase/admin/performance/hooks/useCacheConfigs.tsx b/frontend/src/metabase/admin/performance/hooks/useCacheConfigs.tsx
index 03317c26bb4..0ad2ae66eed 100644
--- a/frontend/src/metabase/admin/performance/hooks/useCacheConfigs.tsx
+++ b/frontend/src/metabase/admin/performance/hooks/useCacheConfigs.tsx
@@ -1,11 +1,8 @@
import { useListCacheConfigsQuery } from "metabase/api";
import type { ListCacheConfigsRequest } from "metabase-types/api";
-import { rootId } from "../constants/simple";
import { translateConfigFromAPI } from "../utils";
-import { useRecentlyTrue } from "./useRecentlyTrue";
-
export const useCacheConfigs = (
listCacheConfigsRequest: ListCacheConfigsRequest,
) => {
@@ -17,21 +14,9 @@ export const useCacheConfigs = (
const configs = listCacheConfigsResponse?.data.map(translateConfigFromAPI);
- const rootStrategyOverriddenOnce =
- configs !== undefined &&
- configs.some((config) => config.model_id !== rootId);
-
- const [rootStrategyRecentlyOverridden] = useRecentlyTrue(
- rootStrategyOverriddenOnce,
- 3000,
- );
-
return {
error,
isLoading,
configs,
- total: listCacheConfigsResponse?.total,
- rootStrategyOverriddenOnce,
- rootStrategyRecentlyOverridden,
};
};
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsSearchInput/NotificationsSearchInput.tsx b/frontend/src/metabase/common/components/DebouncedSearchInput/DebouncedSearchInput.tsx
similarity index 85%
rename from frontend/src/metabase/monitor/tools/notifications/NotificationsSearchInput/NotificationsSearchInput.tsx
rename to frontend/src/metabase/common/components/DebouncedSearchInput/DebouncedSearchInput.tsx
index 1dc0e00ce89..a5024a9ade7 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsSearchInput/NotificationsSearchInput.tsx
+++ b/frontend/src/metabase/common/components/DebouncedSearchInput/DebouncedSearchInput.tsx
@@ -1,17 +1,20 @@
import { useEffect, useRef, useState } from "react";
import { useLatest } from "react-use";
-import { t } from "ttag";
import { useDebouncedValue } from "metabase/common/hooks/use-debounced-value";
-import { Icon, Input, TextInput } from "metabase/ui";
+import { Icon, Input, TextInput, type TextInputProps } from "metabase/ui";
import { SEARCH_DEBOUNCE_DURATION } from "metabase/utils/constants";
type Props = {
value: string;
onChange: (value: string) => void;
-};
+} & Omit<TextInputProps, "value" | "onChange">;
-export const NotificationsSearchInput = ({ value, onChange }: Props) => {
+export const DebouncedSearchInput = ({
+ value,
+ onChange,
+ ...textInputProps
+}: Props) => {
const [query, setQuery] = useState(value);
const debounced = useDebouncedValue(query, SEARCH_DEBOUNCE_DURATION);
const onChangeRef = useLatest(onChange);
@@ -47,13 +50,13 @@ export const NotificationsSearchInput = ({ value, onChange }: Props) => {
return (
<TextInput
flex={1}
- placeholder={t`Search by question or owner…`}
value={query}
radius="md"
onChange={(event) => setQuery(event.currentTarget.value)}
leftSection={<Icon c="text-secondary" name="search" size={16} />}
rightSectionPointerEvents="all"
rightSection={renderRightSection()}
+ {...textInputProps}
/>
);
};
diff --git a/frontend/src/metabase/common/components/DebouncedSearchInput/index.ts b/frontend/src/metabase/common/components/DebouncedSearchInput/index.ts
new file mode 100644
index 00000000000..5fadfb933a5
--- /dev/null
+++ b/frontend/src/metabase/common/components/DebouncedSearchInput/index.ts
@@ -0,0 +1 @@
+export { DebouncedSearchInput } from "./DebouncedSearchInput";
diff --git a/frontend/src/metabase/common/components/ListFilterPopover/ListFilterPopover.tsx b/frontend/src/metabase/common/components/ListFilterPopover/ListFilterPopover.tsx
new file mode 100644
index 00000000000..6289eaf741d
--- /dev/null
+++ b/frontend/src/metabase/common/components/ListFilterPopover/ListFilterPopover.tsx
@@ -0,0 +1,135 @@
+import { type ReactNode, useState } from "react";
+import { t } from "ttag";
+
+import {
+ Button,
+ Flex,
+ Group,
+ Icon,
+ Indicator,
+ Popover,
+ Stack,
+ Text,
+ UnstyledButton,
+} from "metabase/ui";
+import type { IconName } from "metabase-types/api";
+
+type ListFilterPopoverProps = {
+ hasActiveFilters: boolean;
+ /** Called when the popover opens; sync the draft with the applied filters here */
+ onOpen: () => void;
+ onApply: () => void;
+ onClear: () => void;
+ children: ReactNode;
+};
+
+/** Filter button + popover shell for list pages: an Indicator-dotted trigger,
+ * filter sections as children, and a Clear filters / Apply footer. */
+export const ListFilterPopover = ({
+ hasActiveFilters,
+ onOpen,
+ onApply,
+ onClear,
+ children,
+}: ListFilterPopoverProps) => {
+ const [opened, setOpened] = useState(false);
+
+ const handleTriggerClick = () => {
+ if (!opened) {
+ onOpen();
+ }
+ setOpened(!opened);
+ };
+
+ const handleApply = () => {
+ onApply();
+ setOpened(false);
+ };
+
+ const handleClear = () => {
+ onClear();
+ setOpened(false);
+ };
+
+ return (
+ <Popover
+ position="bottom-end"
+ shadow="md"
+ withinPortal
+ opened={opened}
+ onChange={setOpened}
+ >
+ <Popover.Target>
+ <Indicator disabled={!hasActiveFilters} size={8} offset={8}>
+ <Button
+ variant="default"
+ leftSection={<Icon name="filter" />}
+ aria-label={t`Show filters`}
+ onClick={handleTriggerClick}
+ >
+ {t`Filter`}
+ </Button>
+ </Indicator>
+ </Popover.Target>
+ <Popover.Dropdown p="lg">
+ <Stack gap="xl" w={300}>
+ {children}
+ <Group gap="md" grow>
+ <Button variant="default" onClick={handleClear}>
+ {t`Clear filters`}
+ </Button>
+ <Button variant="filled" onClick={handleApply}>
+ {t`Apply`}
+ </Button>
+ </Group>
+ </Stack>
+ </Popover.Dropdown>
+ </Popover>
+ );
+};
+
+type FilterSectionProps = {
+ label: string;
+ children: ReactNode;
+};
+
+export const FilterSection = ({ label, children }: FilterSectionProps) => (
+ <Stack gap="sm">
+ <Text fw="bold" fz="md" c="text-primary">
+ {label}
+ </Text>
+ <Flex gap="sm" wrap="wrap">
+ {children}
+ </Flex>
+ </Stack>
+);
+
+type FilterPillProps = {
+ icon?: IconName;
+ label: string;
+ selected: boolean;
+ onClick: () => void;
+};
+
+export const FilterPill = ({
+ icon,
+ label,
+ selected,
+ onClick,
+}: FilterPillProps) => (
+ <UnstyledButton
+ onClick={onClick}
+ bg={selected ? "background_surface-selected" : "background_page-primary"}
+ bd="1px solid var(--mb-color-border-neutral)"
+ px={12}
+ py="sm"
+ bdrs="xl"
+ >
+ <Flex gap="sm" align="center">
+ {icon && <Icon name={icon} size={16} c="text-secondary" />}
+ <Text fz="md" c="text-primary" lh="sm">
+ {label}
+ </Text>
+ </Flex>
+ </UnstyledButton>
+);
diff --git a/frontend/src/metabase/common/components/ListFilterPopover/index.ts b/frontend/src/metabase/common/components/ListFilterPopover/index.ts
new file mode 100644
index 00000000000..45bd854df7c
--- /dev/null
+++ b/frontend/src/metabase/common/components/ListFilterPopover/index.ts
@@ -0,0 +1,5 @@
+export {
+ FilterPill,
+ FilterSection,
+ ListFilterPopover,
+} from "./ListFilterPopover";
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.module.css b/frontend/src/metabase/common/components/Schedule/Schedule.module.css
index 97c7dabd9c9..1fee9b605e3 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.module.css
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.module.css
@@ -50,3 +50,21 @@
.Horizontal .TextInSecondColumn {
grid-column: unset;
}
+
+.FullWidthSelects {
+ width: 100%;
+
+ & .ControlGroup {
+ flex-grow: 1;
+ }
+
+ & .ControlGroup > * {
+ flex-grow: 1;
+ }
+
+ /* AutoWidthSelect sets an inline width on the input wrapper;
+ !important lets the stretched width win over it */
+ & .ControlGroup :global(.mb-mantine-Input-wrapper) {
+ width: 100% !important;
+ }
+}
diff --git a/frontend/src/metabase/common/components/Schedule/Schedule.tsx b/frontend/src/metabase/common/components/Schedule/Schedule.tsx
index 0b2022e0db1..081e90195c3 100644
--- a/frontend/src/metabase/common/components/Schedule/Schedule.tsx
+++ b/frontend/src/metabase/common/components/Schedule/Schedule.tsx
@@ -51,6 +51,7 @@ export interface ScheduleProps {
getDefaults?: GetScheduleDefaults;
labelAlignment?: "compact" | "left";
layout?: "vertical" | "horizontal";
+ fullWidthSelects?: boolean;
renderScheduleDescription?: (
value: ScheduleValue,
cronInputValue: string,
@@ -68,6 +69,7 @@ export const Schedule = ({
onScheduleChange,
labelAlignment = "compact",
layout = "vertical",
+ fullWidthSelects = false,
renderScheduleDescription,
...flexProps
}: ScheduleProps & FlexProps & HTMLAttributes<HTMLDivElement>) => {
@@ -286,6 +288,7 @@ export const Schedule = ({
{
[S.CompactLabels]: labelAlignment === "compact",
[S.Horizontal]: layout === "horizontal",
+ [S.FullWidthSelects]: fullWidthSelects,
},
className,
)}
diff --git a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx
index 38548631aa2..3d79f077b42 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSettingsSidebar/DashboardSettingsSidebar.tsx
@@ -41,7 +41,6 @@ export function DashboardSettingsSidebar() {
isOpen={state.caching}
onClose={closeSidebar}
onBack={() => close("caching")}
- pt="md"
/>
);
}
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
index d2cfd88b862..f164f6d6456 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationsAdminPage/NotificationsAdminPage.tsx
@@ -12,6 +12,7 @@ import {
BulkActionBar,
BulkActionButton,
} from "metabase/common/components/BulkActionBar";
+import { DebouncedSearchInput } from "metabase/common/components/DebouncedSearchInput";
import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
import { PaginationControls } from "metabase/common/components/PaginationControls";
import { useAbortableQuery } from "metabase/common/hooks/use-abortable-query";
@@ -31,7 +32,6 @@ import { ChangeOwnerModal } from "../ChangeOwnerModal";
import { NotificationDetailSidebar } from "../NotificationDetailSidebar";
import { SIDEBAR_WIDTH } from "../NotificationDetailSidebar/constants";
import { NotificationsFilters } from "../NotificationsFilters";
-import { NotificationsSearchInput } from "../NotificationsSearchInput";
import { NotificationsTable } from "../NotificationsTable";
import { NotificationsTabs } from "../NotificationsTabs";
import {
@@ -335,8 +335,9 @@ export const NotificationsAdminPage = () => {
/>
<Flex gap="md" align="center">
- <NotificationsSearchInput
+ <DebouncedSearchInput
value={urlState.query}
+ placeholder={t`Search by question or owner…`}
onChange={handleSearchChange}
/>
<NotificationsFilters state={urlState} onChange={patchUrlState} />
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsFilters/NotificationsFilters.tsx b/frontend/src/metabase/monitor/tools/notifications/NotificationsFilters/NotificationsFilters.tsx
index cd6e1458ac1..048a1b8d1a3 100644
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsFilters/NotificationsFilters.tsx
+++ b/frontend/src/metabase/monitor/tools/notifications/NotificationsFilters/NotificationsFilters.tsx
@@ -1,21 +1,13 @@
-import type { ReactNode } from "react";
-import { useEffect, useState } from "react";
+import { useState } from "react";
import { t } from "ttag";
import {
- Button,
- Flex,
- Group,
- Icon,
- Indicator,
- Popover,
- Stack,
- Text,
- TextInput,
- UnstyledButton,
-} from "metabase/ui";
+ FilterPill,
+ FilterSection,
+ ListFilterPopover,
+} from "metabase/common/components/ListFilterPopover";
+import { TextInput } from "metabase/ui";
import type {
- IconName,
NotificationChannelType,
NotificationRunStatus,
} from "metabase-types/api";
@@ -39,18 +31,10 @@ type Props = {
};
export const NotificationsFilters = ({ state, onChange }: Props) => {
- const [opened, setOpened] = useState(false);
const [draft, setDraft] = useState<FilterDraft>(() => stateToDraft(state));
- const hasActive = hasActiveFilters(state);
const isFailingTab = state.tab === "failing";
const isOwnerlessTab = state.tab === "ownerless";
- useEffect(() => {
- if (opened) {
- setDraft(stateToDraft(state));
- }
- }, [opened, state]);
-
const handleApply = () => {
trackAlertsManagementFiltersApplied();
onChange({
@@ -60,7 +44,6 @@ export const NotificationsFilters = ({ state, onChange }: Props) => {
recipient_email: draft.recipient_email.trim(),
page: 0,
});
- setOpened(false);
};
const handleClear = () => {
@@ -71,7 +54,6 @@ export const NotificationsFilters = ({ state, onChange }: Props) => {
recipient_email: "",
page: 0,
});
- setOpened(false);
};
const toggleChannel = (channel: NotificationChannelType) => {
@@ -99,139 +81,72 @@ export const NotificationsFilters = ({ state, onChange }: Props) => {
};
return (
- <Popover
- position="bottom-end"
- shadow="md"
- withinPortal
- opened={opened}
- onChange={setOpened}
+ <ListFilterPopover
+ hasActiveFilters={hasActiveFilters(state)}
+ onOpen={() => setDraft(stateToDraft(state))}
+ onApply={handleApply}
+ onClear={handleClear}
>
- <Popover.Target>
- <Indicator disabled={!hasActive} size={8} offset={8}>
- <Button
- variant="default"
- leftSection={<Icon name="filter" />}
- aria-label={t`Show filters`}
- onClick={() => setOpened((value) => !value)}
- >
- {t`Filter`}
- </Button>
- </Indicator>
- </Popover.Target>
- <Popover.Dropdown p="lg">
- <Stack gap="xl" w={300}>
- <FilterSection label={t`Channel`}>
- {CHANNEL_VALUES.map((channel) => (
- <FilterPill
- key={channel}
- icon={getChannelIconName(channel)}
- label={getChannelLabel(channel)}
- selected={draft.channel.includes(channel)}
- onClick={() => toggleChannel(channel)}
- />
- ))}
- </FilterSection>
-
- {!isFailingTab && (
- <FilterSection label={t`Last send attempt`}>
- <FilterPill
- icon="verified_round"
- label={t`Successful`}
- selected={draft.last_send_status === "successful"}
- onClick={() => toggleLastSendStatus("successful")}
- />
- <FilterPill
- icon="warning_round"
- label={t`Failed`}
- selected={draft.last_send_status === "failing"}
- onClick={() => toggleLastSendStatus("failing")}
- />
- </FilterSection>
- )}
-
- {!isOwnerlessTab && (
- <FilterSection label={t`Owner`}>
- <FilterPill
- icon="person"
- label={t`Active`}
- selected={draft.creator_active === true}
- onClick={() => toggleCreatorActive(true)}
- />
- <FilterPill
- icon="ghost"
- label={t`Deactivated`}
- selected={draft.creator_active === false}
- onClick={() => toggleCreatorActive(false)}
- />
- </FilterSection>
- )}
-
- <FilterSection label={t`Email recipient`}>
- <TextInput
- w="100%"
- placeholder={t`[email protected]`}
- value={draft.recipient_email}
- onChange={(event) => {
- const value = event.currentTarget.value;
- setDraft((prev) => ({
- ...prev,
- recipient_email: value,
- }));
- }}
- />
- </FilterSection>
-
- <Group gap="md" grow>
- <Button variant="default" onClick={handleClear}>
- {t`Clear filters`}
- </Button>
- <Button variant="filled" onClick={handleApply}>
- {t`Apply`}
- </Button>
- </Group>
- </Stack>
- </Popover.Dropdown>
- </Popover>
+ <FilterSection label={t`Channel`}>
+ {CHANNEL_VALUES.map((channel) => (
+ <FilterPill
+ key={channel}
+ icon={getChannelIconName(channel)}
+ label={getChannelLabel(channel)}
+ selected={draft.channel.includes(channel)}
+ onClick={() => toggleChannel(channel)}
+ />
+ ))}
+ </FilterSection>
+
+ {!isFailingTab && (
+ <FilterSection label={t`Last send attempt`}>
+ <FilterPill
+ icon="verified_round"
+ label={t`Successful`}
+ selected={draft.last_send_status === "successful"}
+ onClick={() => toggleLastSendStatus("successful")}
+ />
+ <FilterPill
+ icon="warning_round"
+ label={t`Failed`}
+ selected={draft.last_send_status === "failing"}
+ onClick={() => toggleLastSendStatus("failing")}
+ />
+ </FilterSection>
+ )}
+
+ {!isOwnerlessTab && (
+ <FilterSection label={t`Owner`}>
+ <FilterPill
+ icon="person"
+ label={t`Active`}
+ selected={draft.creator_active === true}
+ onClick={() => toggleCreatorActive(true)}
+ />
+ <FilterPill
+ icon="ghost"
+ label={t`Deactivated`}
+ selected={draft.creator_active === false}
+ onClick={() => toggleCreatorActive(false)}
+ />
+ </FilterSection>
+ )}
+
+ <FilterSection label={t`Email recipient`}>
+ <TextInput
+ w="100%"
+ placeholder={t`[email protected]`}
+ value={draft.recipient_email}
+ onChange={(event) => {
+ const value = event.currentTarget.value;
+ setDraft((prev) => ({
+ ...prev,
+ recipient_email: value,
+ }));
+ }}
+ />
+ </FilterSection>
+ </ListFilterPopover>
);
};
-
-type FilterSectionProps = {
- label: string;
- children: ReactNode;
-};
-
-const FilterSection = ({ label, children }: FilterSectionProps) => (
- <Stack gap="sm">
- <Text fw="bold" fz="md" c="text-primary">
- {label}
- </Text>
- <Flex gap="sm" wrap="wrap">
- {children}
- </Flex>
- </Stack>
-);
-
-type FilterPillProps = {
- icon: IconName;
- label: string;
- selected: boolean;
- onClick: () => void;
-};
-
-const FilterPill = ({ icon, label, selected, onClick }: FilterPillProps) => (
- <UnstyledButton
- onClick={onClick}
- bg={selected ? "background_surface-selected" : "background_page-primary"}
- bd="1px solid var(--mb-color-border-neutral)"
- px={12}
- py="sm"
- bdrs="xl"
- >
- <Flex gap="sm" align="center">
- <Icon name={icon} size={16} c="text-secondary" />
- <Text fz="md" c="text-primary" lh="sm">
- {label}
- </Text>
- </Flex>
- </UnstyledButton>
-);
diff --git a/frontend/src/metabase/monitor/tools/notifications/NotificationsSearchInput/index.ts b/frontend/src/metabase/monitor/tools/notifications/NotificationsSearchInput/index.ts
deleted file mode 100644
index 64db929edc2..00000000000
--- a/frontend/src/metabase/monitor/tools/notifications/NotificationsSearchInput/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { NotificationsSearchInput } from "./NotificationsSearchInput";
diff --git a/frontend/src/metabase/plugins/oss/caching.ts b/frontend/src/metabase/plugins/oss/caching.ts
index b3cacacaa34..c76663af7cf 100644
--- a/frontend/src/metabase/plugins/oss/caching.ts
+++ b/frontend/src/metabase/plugins/oss/caching.ts
@@ -165,10 +165,8 @@ export const getPerformanceTabMetadata = () =>
const getDefaultPluginCaching = () => ({
isGranularCachingEnabled: () => false,
- // Unjustified type cast. FIXME
- StrategyFormLauncherPanel: PluginPlaceholder as any,
- // Unjustified type cast. FIXME
- GranularControlsExplanation: PluginPlaceholder as any,
+ // The placeholder renders nothing and accepts the EE page component's (empty) props
+ DatabaseCachingEditor: PluginPlaceholder as ComponentType,
SidebarCacheSection:
// Unjustified type cast. FIXME
PluginPlaceholder as ComponentType<SidebarCacheSectionProps>,
diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx
index c42fcb17d91..0a57b73baab 100644
--- a/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx
+++ b/frontend/src/metabase/query_builder/components/view/sidebars/QuestionSettingsSidebar/QuestionSettingsSidebar.tsx
@@ -80,7 +80,6 @@ export const QuestionSettingsSidebar = ({
onClose={handleClose}
overlayProps={{ bg: "transparent" }}
onBack={() => close("caching")}
- pt="md"
/>
)}
</>
diff --git a/frontend/src/metabase/ui/components/buttons/ActionIcon/ActionIcon.module.css b/frontend/src/metabase/ui/components/buttons/ActionIcon/ActionIcon.module.css
index 2e4f0855acb..19877cda0bc 100644
--- a/frontend/src/metabase/ui/components/buttons/ActionIcon/ActionIcon.module.css
+++ b/frontend/src/metabase/ui/components/buttons/ActionIcon/ActionIcon.module.css
@@ -1,6 +1,6 @@
.root {
&[data-disabled] {
- color: var(--mb-color-text-disabled);
+ color: var(--mb-color-icon-disabled);
pointer-events: all;
}
diff --git a/frontend/test/__support__/server-mocks/performance.ts b/frontend/test/__support__/server-mocks/performance.ts
index 725f645700c..60238057e3b 100644
--- a/frontend/test/__support__/server-mocks/performance.ts
+++ b/frontend/test/__support__/server-mocks/performance.ts
@@ -11,8 +11,13 @@ export function setupPerformanceEndpoints(cacheConfigs: CacheConfig[]) {
fetchMock.put("path:/api/cache", ({ options }) => {
// Unjustified type cast. FIXME
const body = JSON.parse(options.body as string);
+ // Configs are keyed on model + model_id: a question and a dashboard can
+ // share the same model_id
configs = [
- ...configs.filter((config) => config.model_id !== body.model_id),
+ ...configs.filter(
+ (config) =>
+ config.model !== body.model || config.model_id !== body.model_id,
+ ),
body,
];
return {};
@@ -21,7 +26,13 @@ export function setupPerformanceEndpoints(cacheConfigs: CacheConfig[]) {
fetchMock.delete("path:/api/cache", ({ options }) => {
// Unjustified type cast. FIXME
const body = JSON.parse(options.body as string);
- configs = configs.filter((config) => config.model_id !== body.model_id);
+ const modelIds = Array.isArray(body.model_id)
+ ? body.model_id
+ : [body.model_id];
+ configs = configs.filter(
+ (config) =>
+ config.model !== body.model || !modelIds.includes(config.model_id),
+ );
return {};
});
}