The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
GDGT-2796 Namespacing custom viz settings (#81181)
Kamil Mielnik12e5f1691812
diff --git a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.tsindex f3a2a7182d7..f8d9f6dd446 100644--- a/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts+++ b/e2e/test/scenarios/visualizations-charts/custom-viz.cy.spec.ts@@ -621,6 +621,17 @@ describe("admin > custom visualizations", () => {H.saveSavedQuestion();+ cy.log("plugin settings are stored under the plugin's namespace");+ cy.get("@questionId").then((id) => {+ cy.request("GET", `/api/card/${id}`).then(({ body }) => {+ expect(body.visualization_settings).to.have.property(+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:threshold`,+ 42,+ );+ expect(body.visualization_settings).not.to.have.property("threshold");+ });+ });+H.interceptPluginBundle();cy.reload();cy.wait("@pluginBundle");@@ -631,6 +642,100 @@ describe("admin > custom visualizations", () => {H.main().findByText("Threshold: 42").should("be.visible");});+ it("reads and migrates plugin settings saved before namespacing", () => {+ H.createQuestion(+ {+ name: "Legacy Custom Viz Settings",+ query: {+ "source-table": SAMPLE_DB_TABLES.STATIC_ORDERS_ID,+ aggregation: [["count"]],+ },+ display: H.CUSTOM_VIZ_DISPLAY,+ visualization_settings: { threshold: 42 },+ },+ { visitQuestion: true, wrapId: true, idAlias: "legacyQuestionId" },+ );+ H.main().findByText("Threshold: 42").should("be.visible");++ cy.findByTestId("viz-settings-button").click();+ cy.findByTestId("chartsettings-sidebar")+ .findByPlaceholderText("Set threshold")+ .clear()+ .type("43")+ .blur();+ H.main().findByText("Threshold: 43").should("be.visible");+ H.saveSavedQuestion();++ cy.log("the first edit moves the bare key under the plugin's namespace");+ cy.get("@legacyQuestionId").then((id) => {+ cy.request("GET", `/api/card/${id}`).then(({ body }) => {+ expect(body.visualization_settings).to.have.property(+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:threshold`,+ 43,+ );+ expect(body.visualization_settings).not.to.have.property("threshold");+ });+ });+ });++ it("keeps plugin writes to Metabase settings inside the plugin's namespace", () => {+ H.visitQuestion("@questionId");+ switchToDemoViz();++ cy.findByTestId("viz-settings-button").click();+ cy.findByTestId("chartsettings-sidebar")+ .findByRole("button", { name: "Rename question from plugin" })+ .click();+ H.main().findByText("Threshold: 7").should("be.visible");+ H.saveSavedQuestion();++ cy.get("@questionId").then((id) => {+ cy.request("GET", `/api/card/${id}`).then(({ body }) => {+ expect(body.visualization_settings).to.have.property(+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:threshold`,+ 7,+ );+ expect(body.visualization_settings).to.have.property(+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:card.title`,+ "Plugin title",+ );+ expect(body.visualization_settings).not.to.have.property(+ "card.title",+ );+ });+ });+ });++ it("hands the plugin its own array-valued settings, including edits made in the session", () => {+ H.visitQuestion("@questionId");+ switchToDemoViz();++ cy.log("the default the plugin computes is an array");+ cy.findByTestId("demo-viz-columns").should("have.text", "Columns: count");++ cy.findByTestId("viz-settings-button").click();+ cy.findByTestId("chartsettings-sidebar")+ .findByRole("button", { name: "Add column from plugin" })+ .click();+ cy.findByTestId("demo-viz-columns").should(+ "have.text",+ "Columns: count, extra",+ );+ cy.findByTestId("chartsettings-sidebar")+ .findByRole("button", { name: "Add column from plugin" })+ .should("be.visible");+ H.saveSavedQuestion();++ cy.get("@questionId").then((id) => {+ cy.request("GET", `/api/card/${id}`).then(({ body }) => {+ expect(body.visualization_settings).to.have.deep.property(+ `custom:${H.CUSTOM_VIZ_IDENTIFIER}:columns`,+ ["count", "extra"],+ );+ });+ });+ });+it("keeps an unsaved question's custom viz after a browser reload (metabase#76065)", () => {H.visitQuestionAdhoc({dataset_query: {@@ -2427,7 +2532,7 @@ describe("sandbox", () => {cy.get("@consoleLog").should("have.been.calledWith","plugin treewalker(document) saw non-empty nodes:",- 25,+ 27,);});diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.cljindex 9886e32d93d..d6257fd0848 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/api.clj@@ -214,7 +214,7 @@plugins (custom-viz-plugin.db/active-enabled-non-blob-plugins)](->> plugins(remove #(and (not dev-mode?) (dev-only-plugin? %)))- ;; An identifier containing ":" would collide with another plugin's `custom-viz:<id>:`+ ;; An identifier containing ":" would collide with another plugin's `custom:<id>:`;; settings prefix on the frontend. Colons are rejected at registration now; skip any;; legacy row that predates that check instead of serving it.(remove #(manifest/identifier-error (:identifier %)))diff --git a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/manifest.clj b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/manifest.cljindex 39a9a83fc52..88479092a16 100644--- a/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/manifest.clj+++ b/enterprise/backend/src/metabase_enterprise/custom_viz_plugin/manifest.clj@@ -46,7 +46,7 @@(some-> (mr/explain ManifestFieldTypes manifest) me/humanize))(defn identifier-error- "Why `identifier` can't name a plugin, or nil. `:` separates the parts of `custom-viz:<identifier>:<setting id>`+ "Why `identifier` can't name a plugin, or nil. `:` separates the parts of `custom:<identifier>:<setting id>`viz-settings keys, so an identifier containing it could read another plugin's settings."[identifier](when (and (string? identifier) (str/includes? identifier ":"))diff --git a/enterprise/frontend/src/custom-viz/CHANGELOG.md b/enterprise/frontend/src/custom-viz/CHANGELOG.mdindex e079fcf2440..3d9146a32f6 100644--- a/enterprise/frontend/src/custom-viz/CHANGELOG.md+++ b/enterprise/frontend/src/custom-viz/CHANGELOG.md@@ -7,6 +7,9 @@ This changelog covers the `@metabase/custom-viz` npm package — the API and CLI### ⚠ BREAKING CHANGES- `column` and `column_settings` are now reserved setting ids, contributed to every visualization by Metabase to power the built-in per-column formatting popover. Plugins that declared their own settings under these ids must rename them — the `Settings` type now rejects those keys with a type error ([#78128](https://github.com/metabase/metabase/pull/78128)).+- Plugin settings are now stored under `custom:<plugin name>:<setting id>` keys in a question's `visualization_settings`, so a plugin can never write one of Metabase's own settings. Plugins keep using their own ids: `settings`, `onChangeSettings`, `readDependencies`, `writeDependencies`, and `eraseDependencies` are translated by Metabase and refer to the plugin's own settings only ([#81181](https://github.com/metabase/metabase/pull/81181)).+- `onChangeSettings` and the dependency lists are typed to the plugin's own setting ids. Writes to Metabase settings such as `card.title` or `click_behavior` no longer take effect ([#81181](https://github.com/metabase/metabase/pull/81181)).+- Plugin settings saved by earlier plugin versions are adopted under the new keys automatically. Metabase settings an earlier plugin version already wrote, including `click_behavior`, stay stored and keep taking effect until removed, so review click behavior on existing custom visualization cards ([#81181](https://github.com/metabase/metabase/pull/81181)).- `ClickObject` is no longer generic and no longer has a `settings` field. Metabase attaches the visualization's current settings to every click itself and ignores anything passed under `settings`, so a click can't redirect dashboard click behavior. A `click_behavior` saved by an earlier plugin version stays in effect until removed ([#81181](https://github.com/metabase/metabase/pull/81181)).- The top-level `colorScheme` visualization prop moved into the new `renderingContext` prop (see Features below). Read `props.renderingContext.colorScheme` instead of `props.colorScheme` ([#78429](https://github.com/metabase/metabase/pull/78429)).- The `id` field of the visualization definition is removed. It was never read — Metabase identifies a visualization by `name` in `metabase-plugin.json`. Delete it from your `defineConfig` call.diff --git a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/Visualization.tsx b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/Visualization.tsxindex e07bbaacf4e..a4b548e27e2 100644--- a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/Visualization.tsx+++ b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/Visualization.tsx@@ -1,14 +1,18 @@-import { useState } from "react";import type { MouseEvent } from "react";+import { useState } from "react";import { type CustomVisualizationProps, formatValue } from "../../../src/index";-import type { Settings } from "./types";++type Settings = {+ columns?: string[];+ threshold?: number;+};export const Visualization = (props: CustomVisualizationProps<Settings> & { locale: string },) => {const { series, settings, renderingContext, onClick, onHover, locale } =props;- const { threshold } = settings;+ const { columns, threshold } = settings;const { cols, rows } = series[0].data;const value = rows[0][0];@@ -58,6 +62,9 @@ export const Visualization = (<div><h1>Custom viz rendered successfully</h1><div>Threshold: {threshold}</div>+ <div data-testid="demo-viz-columns">+ Columns: {columns?.join(", ") ?? "none"}+ </div><div>Value: {value}</div><div data-testid="demo-viz-formatted-value">Formatted: {formatValue(value, settings.column?.(cols[0]))}diff --git a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index-widget-security.tsx b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index-widget-security.tsxindex 3888109535c..44654b88993 100644--- a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index-widget-security.tsx+++ b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index-widget-security.tsx@@ -1,7 +1,11 @@import { defineConfig } from "../../../src/index";import type { CreateCustomVisualization } from "../../../src/types/viz";import { Visualization } from "./Visualization";-import { Settings } from "./types";++type Settings = {+ customWidget?: string | null;+ threshold?: number;+};// A custom React component used as a setting widget. It renders a forbidden// element (`<form>`) — rendering it makes React call@@ -29,6 +33,14 @@ const createVisualization: CreateCustomVisualization<Settings> = ({}},settings: {+ customWidget: defineSetting({+ id: "customWidget",+ title: "Custom widget",+ widget: ForbiddenSettingWidget,+ getDefault() {+ return null;+ },+ }),threshold: defineSetting({id: "threshold",title: "Threshold",@@ -47,14 +59,6 @@ const createVisualization: CreateCustomVisualization<Settings> = ({};},}),- customWidget: defineSetting({- id: "customWidget",- title: "Custom widget",- widget: ForbiddenSettingWidget,- getDefault() {- return null;- },- }),},VisualizationComponent: (props) => (<Visualization {...props} locale={locale} />diff --git a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index.tsx b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index.tsxindex c8e0b791608..292be5f3104 100644--- a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index.tsx+++ b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/index.tsx@@ -1,12 +1,47 @@import { defineConfig } from "../../../src/index";-import type { CreateCustomVisualization } from "../../../src/types/viz";+import type {+ BaseWidgetProps,+ CreateCustomVisualization,+} from "../../../src/types/viz";import { Visualization } from "./Visualization";type Settings = {threshold?: number;metricColumn?: string | null;+ renameQuestion?: null;+ columns?: string[];};+function ColumnsWidget({+ value,+ onChange,+}: BaseWidgetProps<string[], Settings>) {+ return (+ <button type="button" onClick={() => onChange([...(value ?? []), "extra"])}>+ Add column from plugin+ </button>+ );+}++function RenameQuestionWidget({+ onChangeSettings,+}: BaseWidgetProps<null, Settings>) {+ return (+ <button+ type="button"+ onClick={() =>+ onChangeSettings({+ // @ts-expect-error -- the SDK type rejects internal Metabase setting ids on purpose+ "card.title": "Plugin title",+ threshold: 7,+ })+ }+ >+ Rename question from plugin+ </button>+ );+}+const createVisualization: CreateCustomVisualization<Settings> = ({defineSetting,locale,@@ -77,6 +112,22 @@ const createVisualization: CreateCustomVisualization<Settings> = ({};},}),+ renameQuestion: defineSetting({+ id: "renameQuestion",+ title: "Rename question",+ widget: RenameQuestionWidget,+ getDefault() {+ return null;+ },+ }),+ columns: defineSetting({+ id: "columns",+ title: "Columns",+ widget: ColumnsWidget,+ getDefault(series) {+ return series[0].data.cols.map((col) => col.name);+ },+ }),},VisualizationComponent: (props) => (<Visualization {...props} locale={locale} />diff --git a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/types.ts b/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/types.tsdeleted file mode 100644index 45b959348c7..00000000000--- a/enterprise/frontend/src/custom-viz/fixtures/example_custom_viz_plugin/src/types.ts+++ /dev/null@@ -1,4 +0,0 @@-export type Settings = {- threshold?: number;- customWidget?: string | null;-};diff --git a/enterprise/frontend/src/custom-viz/src/templates/README.md b/enterprise/frontend/src/custom-viz/src/templates/README.mdindex 180b2dce3bf..84ea0a6b08c 100644--- a/enterprise/frontend/src/custom-viz/src/templates/README.md+++ b/enterprise/frontend/src/custom-viz/src/templates/README.md@@ -191,9 +191,9 @@ settings: {| `getValue(series, settings)` | Always-computed value — overrides stored value on every render. || `getProps(series, settings)` | Returns widget-specific props. || `isValid(series, settings)` | Return `false` to discard a stored value and fall back to `getDefault`. |-| `readDependencies` | Setting IDs that must resolve before this one. |-| `writeDependencies` | Setting IDs whose current values are persisted when this setting changes. |-| `eraseDependencies` | Setting IDs reset to `null` when this setting changes. |+| `readDependencies` | Ids of your settings that must resolve before this one. |+| `writeDependencies` | Ids of your settings whose current values are persisted when this setting changes. |+| `eraseDependencies` | Ids of your settings reset to `null` when this setting changes. || `persistDefault` | When `true`, writes the computed default to stored settings on first render. |> **Note:** The setting ids `column_settings` and `column` are reserved by Metabase@@ -201,6 +201,11 @@ settings: {> `Settings` type, and Metabase ignores setting definitions that use them. To apply> the formatting people pick in the popover, pass the result of `settings.column?.(col)`> to `formatValue`.+>+> Metabase stores your settings under `custom:<plugin name>:<setting id>` keys.+> You never see the prefix: `settings`, `onChangeSettings`, and the dependency lists+> use your own ids and can only refer to your own settings. If one of your ids collides+> with a Metabase setting id, your setting shadows Metabase's in `settings`.### Built-in widgetsdiff --git a/enterprise/frontend/src/custom-viz/src/types/viz-settings.ts b/enterprise/frontend/src/custom-viz/src/types/viz-settings.tsindex aa6a0f91394..1ad39db44ee 100644--- a/enterprise/frontend/src/custom-viz/src/types/viz-settings.ts+++ b/enterprise/frontend/src/custom-viz/src/types/viz-settings.ts@@ -167,192 +167,202 @@ export type CreateDefineSetting<TSettings extends BaseVisualizationSettings> =() => <W extends WidgetName | ComponentType<any>,Key extends keyof TSettings,- >(settingDefinition: {- /**- * Unique key that identifies this setting. Must match the key used in your- * `CustomVisualizationSettings` type and in the `settings` map passed to- * `createCustomVisualization`.- */- id: Key;-- /**- * Returns the top-level section this setting appears under in the settings- * sidebar (e.g. `"Data"`, `"Display"`, `"Axes"`). Implemented as a getter so- * the label can be localized at call time.- *- * @returns Section to put this setting into.- */- getSection?: () => string;-- /** Human-readable label rendered above the widget in the sidebar. */- title?: string;-- /**- * Sub-heading within a `section` used to cluster related settings- * visually (e.g. `"X-axis"`, `"Y-axis"`). Settings sharing the same- * `group` within a section are rendered under a common sub-heading.- */- group?: string;-- /**- * Controls the display order of settings when they're placed in the same group.- */- index?: number;-- /**- * When `true`, the widget is rendered on the same line as its `title`- * label rather than below it. Best suited for compact widgets like- * `"toggle"`.- */- inline?: boolean;-- /**- * When `true`, the computed default value (from `getDefault`) is written- * into the card's stored `visualization_settings` the first time the query- * runs, even though the user never explicitly changed the setting.- *- * Use this for settings whose default depends on the query result and must- * survive subsequent renders without re-running `getDefault`. For example,- * auto-selected axis columns are persisted so that manually- * reordering series does not lose the original- * auto-selection when the question is saved and reopened.- *- * Without `persistDefault`, `getDefault` re-runs on every render and any- * derived state (e.g. user-applied series order) built on top of the- * default can be silently reset when data or column order changes.- */- persistDefault?: boolean;-- /**- * Setting IDs that must be computed before this setting.- *- * The settings engine resolves each listed ID first so their values are- * available in the `settings` argument passed to `getDefault`, `getValue`,- * `isValid`, and `getProps`. Required because computed settings are memoized —- * without an explicit ordering a dependency may still be `undefined` when- * this setting tries to read it.- */- readDependencies?: string[];-- /**- * Setting IDs whose current computed values are persisted alongside this- * setting whenever it changes.- *- * On change, the engine snapshots each listed setting's current computed- * value into the write payload. Use this to "lock in" dynamic defaults of- * related settings so they aren't silently recalculated under the new- * context and lose user intent.- */- writeDependencies?: string[];-- /**- * Setting IDs that are reset to `null` whenever this setting changes.- *- * On change, each listed setting is set to `null` in the persisted payload,- * forcing it to recompute from scratch on the next render. Use this to- * invalidate derived settings whose stored value becomes stale or meaningless- * after the change.- */- eraseDependencies?: string[];-- /**- * Widget to render for this setting: either a built-in widget name- * (`WidgetName`) or a custom React component (`React.ComponentType<P>`).- *- * When using a custom component, `getProps` should return only the- * non-base props; base widget props are provided by the settings- * renderer.- *- * Custom-component widgets are rewritten internally to a `WidgetMount`- * before the definition leaves the plugin sandbox, so the host never- * receives a plain React component reference.- */- widget: W;-- /**- * Determines whether the stored value for this setting is still valid given- * the current data and resolved settings. Called during the settings- * resolution pass before the visualization renders.- *- * When `isValid` returns `false`, the stored value is discarded and- * `getDefault` is used instead. This keeps settings coherent when the- * underlying query changes — for example, when a saved column reference no- * longer exists in the result set.- *- * @param series - The current query result (rows + column metadata).- * @param settings - All settings resolved so far, respecting `readDependencies` ordering.- * @returns `true` to keep the stored value, `false` to fall back to`getDefault`.- */- isValid?: (- series: Series,- settings: CustomVisualizationSettings<TSettings>,- ) => boolean;-- /**- * Computes the default value for this setting when no stored value exists,- * or when `isValid` returns `false` for the stored value.- *- * Called during the settings resolution pass before the visualization renders.- * The returned value is used transiently unless `persistDefault` is `true`,- * in which case it is written into the card's stored `visualization_settings`- * on the first query run.- *- * @param series - The current query result (rows + column metadata).- * @param settings - All settings resolved so far, respecting `readDependencies` ordering.- * @returns The default value for this setting.- */- getDefault?: (- series: Series,- settings: CustomVisualizationSettings<TSettings>,- ) => TSettings[Key];-- /**- * Returns additional props passed to the setting's `widget` component,- * beyond the base props the engine always provides.- *- * Called on every render. Use it to derive widget configuration from the- * current query result or resolved settings — for example, populating a- * dropdown's `options` list from the available columns.- *- * The return type is inferred from the `widget` value: props of the named- * built-in widget when `widget` is a `WidgetName`, or the component's own- * props (minus the base props the engine injects) when `widget` is a custom- * React component. Omit `getProps` entirely when the widget has no- * configurable props (`ToggleProps` is `never`).- *- * @param series - The current query result (rows + column metadata).- * @param vizSettings - All settings resolved so far, respecting `readDependencies` ordering.- * @returns Props object merged into the widget component's props.- */- getProps?: PropsFromWidget<W> extends never- ? never- : (- series: Series,- vizSettings: CustomVisualizationSettings<TSettings>,- ) => PropsFromWidget<W>;-- /**- * Computes a derived value for this setting on every render, overriding both- * the stored value and the result of `getDefault`.- *- * Use this when the setting's effective value must always be derived from the- * current query result or other resolved settings, and storing a user-chosen- * value makes no sense. Unlike `getDefault`, `getValue` is always called —- * the stored value is never used.- *- * @param series - The current query result (rows + column metadata).- * @param settings - All settings resolved so far, respecting `readDependencies` ordering.- * @returns The computed value for this setting.- *- * @example- * // Always reflect the number of series currently in the result- * getValue: (series, _settings) => series.length,- */- getValue?: (- series: Series,- settings: CustomVisualizationSettings<TSettings>,- ) => TSettings[Key];- }) => CustomVisualizationSettingDefinition<TSettings>;+ >(+ settingDefinition: SettingDefinition<TSettings, W, Key>,+ ) => CustomVisualizationSettingDefinition<TSettings>;++type SettingDefinition<+ TSettings extends BaseVisualizationSettings,+ W extends WidgetName | ComponentType<any>,+ Key extends keyof TSettings,+> = {+ /**+ * Unique key that identifies this setting. Must match the key used in your+ * `CustomVisualizationSettings` type and in the `settings` map passed to+ * `createCustomVisualization`.+ */+ id: Key;++ /**+ * Returns the top-level section this setting appears under in the settings+ * sidebar (e.g. `"Data"`, `"Display"`, `"Axes"`). Implemented as a getter so+ * the label can be localized at call time.+ *+ * @returns Section to put this setting into.+ */+ getSection?: () => string;++ /** Human-readable label rendered above the widget in the sidebar. */+ title?: string;++ /**+ * Sub-heading within a `section` used to cluster related settings+ * visually (e.g. `"X-axis"`, `"Y-axis"`). Settings sharing the same+ * `group` within a section are rendered under a common sub-heading.+ */+ group?: string;++ /**+ * Controls the display order of settings when they're placed in the same group.+ */+ index?: number;++ /**+ * When `true`, the widget is rendered on the same line as its `title`+ * label rather than below it. Best suited for compact widgets like+ * `"toggle"`.+ */+ inline?: boolean;++ /**+ * When `true`, the computed default value (from `getDefault`) is written+ * into the card's stored `visualization_settings` the first time the query+ * runs, even though the user never explicitly changed the setting.+ *+ * Use this for settings whose default depends on the query result and must+ * survive subsequent renders without re-running `getDefault`. For example,+ * auto-selected axis columns are persisted so that manually+ * reordering series does not lose the original+ * auto-selection when the question is saved and reopened.+ *+ * Without `persistDefault`, `getDefault` re-runs on every render and any+ * derived state (e.g. user-applied series order) built on top of the+ * default can be silently reset when data or column order changes.+ */+ persistDefault?: boolean;++ /**+ * Ids of your own settings that must be computed before this setting.+ * Metabase's settings are always available and can't be listed here.+ *+ * The settings engine resolves each listed id first so their values are+ * available in the `settings` argument passed to `getDefault`, `getValue`,+ * `isValid`, and `getProps`. Required because computed settings are memoized —+ * without an explicit ordering a dependency may still be `undefined` when+ * this setting tries to read it.+ */+ readDependencies?: (keyof TSettings & string)[];++ /**+ * Ids of your own settings whose current computed values are persisted+ * alongside this setting whenever it changes.+ *+ * On change, the engine snapshots each listed setting's current computed+ * value into the write payload. Use this to "lock in" dynamic defaults of+ * related settings so they aren't silently recalculated under the new+ * context and lose user intent.+ */+ writeDependencies?: (keyof TSettings & string)[];++ /**+ * Ids of your own settings that are reset to `null` whenever this setting+ * changes.+ *+ * On change, each listed setting is set to `null` in the persisted payload,+ * forcing it to recompute from scratch on the next render. Use this to+ * invalidate derived settings whose stored value becomes stale or meaningless+ * after the change.+ */+ eraseDependencies?: (keyof TSettings & string)[];++ /**+ * Widget to render for this setting: either a built-in widget name+ * (`WidgetName`) or a custom React component (`React.ComponentType<P>`).+ *+ * When using a custom component, `getProps` should return only the+ * non-base props; base widget props are provided by the settings+ * renderer.+ *+ * Custom-component widgets are rewritten internally to a `WidgetMount`+ * before the definition leaves the plugin sandbox, so the host never+ * receives a plain React component reference.+ */+ widget: W;++ /**+ * Determines whether the stored value for this setting is still valid given+ * the current data and resolved settings. Called during the settings+ * resolution pass before the visualization renders.+ *+ * When `isValid` returns `false`, the stored value is discarded and+ * `getDefault` is used instead. This keeps settings coherent when the+ * underlying query changes — for example, when a saved column reference no+ * longer exists in the result set.+ *+ * @param series - The current query result (rows + column metadata).+ * @param settings - All settings resolved so far, respecting `readDependencies` ordering.+ * @returns `true` to keep the stored value, `false` to fall back to`getDefault`.+ */+ isValid?: (+ series: Series,+ settings: CustomVisualizationSettings<TSettings>,+ ) => boolean;++ /**+ * Computes the default value for this setting when no stored value exists,+ * or when `isValid` returns `false` for the stored value.+ *+ * Called during the settings resolution pass before the visualization renders.+ * The returned value is used transiently unless `persistDefault` is `true`,+ * in which case it is written into the card's stored `visualization_settings`+ * on the first query run.+ *+ * @param series - The current query result (rows + column metadata).+ * @param settings - All settings resolved so far, respecting `readDependencies` ordering.+ * @returns The default value for this setting.+ */+ getDefault?: (+ series: Series,+ settings: CustomVisualizationSettings<TSettings>,+ ) => TSettings[Key];++ /**+ * Returns additional props passed to the setting's `widget` component,+ * beyond the base props the engine always provides.+ *+ * Called on every render. Use it to derive widget configuration from the+ * current query result or resolved settings — for example, populating a+ * dropdown's `options` list from the available columns.+ *+ * The return type is inferred from the `widget` value: props of the named+ * built-in widget when `widget` is a `WidgetName`, or the component's own+ * props (minus the base props the engine injects) when `widget` is a custom+ * React component. Omit `getProps` entirely when the widget has no+ * configurable props (`ToggleProps` is `never`).+ *+ * @param series - The current query result (rows + column metadata).+ * @param vizSettings - All settings resolved so far, respecting `readDependencies` ordering.+ * @returns Props object merged into the widget component's props.+ */+ getProps?: PropsFromWidget<W> extends never+ ? never+ : (+ series: Series,+ vizSettings: CustomVisualizationSettings<TSettings>,+ ) => PropsFromWidget<W>;++ /**+ * Computes a derived value for this setting on every render, overriding both+ * the stored value and the result of `getDefault`.+ *+ * Use this when the setting's effective value must always be derived from the+ * current query result or other resolved settings, and storing a user-chosen+ * value makes no sense. Unlike `getDefault`, `getValue` is always called —+ * the stored value is never used.+ *+ * @param series - The current query result (rows + column metadata).+ * @param settings - All settings resolved so far, respecting `readDependencies` ordering.+ * @returns The computed value for this setting.+ *+ * @example+ * // Always reflect the number of series currently in the result+ * getValue: (series, _settings) => series.length,+ */+ getValue?: (+ series: Series,+ settings: CustomVisualizationSettings<TSettings>,+ ) => TSettings[Key];+};declare const SettingDefinitionSymbol: unique symbol;diff --git a/enterprise/frontend/src/custom-viz/src/types/viz.ts b/enterprise/frontend/src/custom-viz/src/types/viz.tsindex ca5a391a3d9..fdb9daa8ad3 100644--- a/enterprise/frontend/src/custom-viz/src/types/viz.ts+++ b/enterprise/frontend/src/custom-viz/src/types/viz.ts@@ -279,10 +279,12 @@ export type BaseWidgetProps<TValue,TSettings extends BaseVisualizationSettings,> = {+ /**+ * Form-only id for the widget's control (e.g. a label's `htmlFor`).+ * The value is arbitrary - don't interpret it.+ */id: string;value: TValue | undefined;onChange: (value?: TValue | null) => void;- onChangeSettings: (- settings: Partial<CustomVisualizationSettings<TSettings>>,- ) => void;+ onChangeSettings: (settings: Partial<TSettings>) => void;};diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.tsx b/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.tsxindex 1d0adae0e3b..e4426b0c8ec 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.tsx+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.tsx@@ -1,13 +1,14 @@import type { WidgetMount } from "custom-viz";import { checkNotNull } from "metabase/utils/types";+import type { CustomVizSettingWidgetProps } from "metabase/viz-core";import { usePluginMount } from "../use-plugin-mount";import { getWidgetMountPlugin } from "../widget-mount";type Props = {- mount: WidgetMount<Record<string, unknown>>;- widgetProps: Record<string, unknown>;+ mount: WidgetMount<CustomVizSettingWidgetProps>;+ widgetProps: CustomVizSettingWidgetProps;};/**diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.unit.spec.tsxindex 1399399ebd9..d012c9c2fb4 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/components/CustomVizSettingWidget.unit.spec.tsx@@ -3,13 +3,21 @@ import type { WidgetMount } from "custom-viz";import type { ComponentType } from "react";import { createRoot } from "react-dom/client";+import type { CustomVizSettingWidgetProps } from "metabase/viz-core";import { createMockCustomVizPluginRuntime } from "metabase-types/api/mocks";-import { wrapPluginWidget } from "../widget-mount";+import { type PluginWidgetProps, wrapPluginWidget } from "../widget-mount";import { CustomVizSettingWidget } from "./CustomVizSettingWidget";-type TestWidgetProps = { title?: string; value?: number };+type TestWidgetProps = PluginWidgetProps & { title?: string };++const WIDGET_PROPS: CustomVizSettingWidgetProps = {+ id: "custom:demo-viz:setting",+ value: 1,+ onChange: jest.fn(),+ onChangeSettings: jest.fn(),+};function TestWidget({ title }: TestWidgetProps) {return (@@ -53,6 +61,7 @@ function prepareWidget(pluginId = 1) {const mount = wrapPluginWidget(widgetMount,createMockCustomVizPluginRuntime({ id: pluginId }),+ "custom:demo-viz:",);return {mount,@@ -63,15 +72,18 @@ function prepareWidget(pluginId = 1) {function setup({pluginId = 1,- widgetProps = { title: "Setting 1" },+ widgetProps,}: {- widgetProps?: TestWidgetProps;+ widgetProps?: Partial<CustomVizSettingWidgetProps>;pluginId?: number;}) {const { mount, getMountCalls, getWidgetContainer } = prepareWidget(pluginId);const { rerender, unmount } = render(- <CustomVizSettingWidget mount={mount} widgetProps={widgetProps} />,+ <CustomVizSettingWidget+ mount={mount}+ widgetProps={{ ...WIDGET_PROPS, title: "Setting 1", ...widgetProps }}+ />,);return {@@ -99,7 +111,7 @@ describe("CustomVizSettingWidget", () => {rerender(<CustomVizSettingWidgetmount={mount}- widgetProps={{ title: "Settings 2" }}+ widgetProps={{ ...WIDGET_PROPS, title: "Settings 2" }}/>,);diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/copy-plugin-value.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/copy-plugin-value.tsnew file mode 100644index 00000000000..a6cda97c2c4--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/copy-plugin-value.ts@@ -0,0 +1,59 @@+import {+ isDate,+ isFunction,+ isMap,+ isObject,+ isSet,+} from "metabase-types/guards";++// Values a plugin hands the host arrive as membrane proxies+export function copyPluginValue<T>(value: T): T {+ // Same shape as the input, like structuredClone.+ return copy(value) as T;+}++function copy(value: unknown): unknown {+ if (isFunction(value)) {+ throw new TypeError("Functions can't be copied");+ }++ // A symbol-tagged object (e.g. `$$typeof`) could pass for a React element in the host.+ if (typeof value === "symbol") {+ throw new TypeError("Symbols can't be copied");+ }++ if (!isObject(value)) {+ return value;+ }++ if (Array.isArray(value)) {+ return Array.from(value, copy);+ }++ if (isMap(value)) {+ return new Map(+ [...value].map(([key, entry]): [unknown, unknown] => [+ copy(key),+ copy(entry),+ ]),+ );+ }++ if (isSet(value)) {+ return new Set([...value].map(copy));+ }++ if (isDate(value)) {+ return new Date(value.getTime());+ }++ const tag = Object.prototype.toString.call(value);++ if (tag !== "[object Object]") {+ throw new TypeError(`${tag} can't be copied`);+ }++ return Object.fromEntries(+ Object.entries(value).map(([key, entry]) => [key, copy(entry)]),+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/copy-plugin-value.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/copy-plugin-value.unit.spec.tsnew file mode 100644index 00000000000..413abaff4f7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/copy-plugin-value.unit.spec.ts@@ -0,0 +1,68 @@+import { runInNewContext } from "vm";++import { copyPluginValue } from "./copy-plugin-value";++describe("copyPluginValue", () => {+ it("copies through a proxy, which structuredClone rejects", () => {+ const original = {+ list: [1, { deep: true }],+ lookup: new Map([["a", [1]]]),+ tags: new Set(["x"]),+ when: new Date(0),+ none: null,+ big: 10n,+ };++ const copied = copyPluginValue(new Proxy(original, {}));++ expect(copied).toEqual(original);+ expect(copied.list).not.toBe(original.list);+ expect(copied.list[1]).not.toBe(original.list[1]);+ expect(copied.lookup).not.toBe(original.lookup);+ expect(() => structuredClone(copied)).not.toThrow();+ });++ it("copies through a proxied array", () => {+ const original = ["count", { name: "extra" }];++ const copied = copyPluginValue(new Proxy(original, {}));++ expect(copied).toEqual(original);+ expect(Array.isArray(copied)).toBe(true);+ expect(copied[1]).not.toBe(original[1]);+ });++ it("builds the copy in the host realm even when the value's methods belong to another realm", () => {+ const foreign: { list: unknown[]; lookup: Map<unknown, unknown> } =+ runInNewContext(+ '({ list: ["count", [1]], lookup: new Map([["a", 1]]) })',+ );++ const copied = copyPluginValue(new Proxy(foreign, {}));++ expect(copied).toEqual({+ list: ["count", [1]],+ lookup: new Map([["a", 1]]),+ });+ expect(Object.getPrototypeOf(copied)).toBe(Object.prototype);+ expect(Object.getPrototypeOf(copied.list)).toBe(Array.prototype);+ expect(Object.getPrototypeOf(copied.list[1])).toBe(Array.prototype);+ expect(copied.lookup).toBeInstanceOf(Map);+ });++ it("passes primitives through", () => {+ expect(copyPluginValue(7)).toBe(7);+ expect(copyPluginValue(null)).toBeNull();+ expect(copyPluginValue(undefined)).toBeUndefined();+ });++ it.each([+ ["a function", () => 1],+ ["a symbol", Symbol.for("react.element")],+ ["an Intl formatter", new Intl.NumberFormat()],+ ])("rejects a value holding %s", (_name, value) => {+ expect(() => copyPluginValue(new Proxy({ value }, {}))).toThrow(+ /can't be copied/,+ );+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.tsindex 2b101eca1e4..e3f7e133beb 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.ts@@ -8,13 +8,14 @@ import type {} from "metabase/visualizations/types/visualization";import { columnSettings } from "metabase/viz-core";import type {+ CustomVizDisplayType,CustomVizPluginRuntime,Series,- VisualizationDisplay,VisualizationSettings,} from "metabase-types/api";import { sanitizePluginSettings } from "./custom-viz-settings";+import { toPluginSeries, toPluginSettings } from "./plugin-view";/*** Assign properties derived from a vizDef onto a Visualization component@@ -32,22 +33,30 @@ export function applyDefaultVisualizationProps(Component: ComponentType<VisualizationProps & VisualizationPassThroughProps>,vizDef: CustomVisualization<Record<string, unknown>>,settings: {- identifier: VisualizationDisplay;+ identifier: CustomVizDisplayType;plugin: CustomVizPluginRuntime;+ prefix: string;iconUrl?: string | undefined;isDev?: boolean;},): Visualization {- const { plugin, ...componentSettings } = settings;+ const { plugin, prefix, ...componentSettings } = settings;const uiName = resolveUiName(vizDef, plugin);return Object.assign(Component, {settings: {...columnSettings({ getHidden: () => true }),- ...sanitizePluginSettings(vizDef.settings, vizDef.mount, plugin),+ ...sanitizePluginSettings(vizDef.settings, {+ prefix,+ mount: vizDef.mount,+ plugin,+ }),},checkRenderable: (series: Series, vizSettings: VisualizationSettings) => {if (typeof vizDef.checkRenderable === "function") {- vizDef.checkRenderable(series, vizSettings);+ vizDef.checkRenderable(+ toPluginSeries(series, prefix),+ toPluginSettings(vizSettings, prefix),+ );}},noHeader: vizDef.noHeader ?? false,diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.unit.spec.tsindex 11b497b2f85..4339b16d30f 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-common.unit.spec.ts@@ -23,6 +23,7 @@ describe("applyDefaultVisualizationProps", () => {applyDefaultVisualizationProps(COMPONENT, vizDef, {identifier: "custom:demo-viz",plugin: PLUGIN,+ prefix: "custom:demo-viz:",}).checkRenderable?.([], {});expect(checkRenderable).toHaveBeenCalledTimes(1);@@ -37,6 +38,7 @@ describe("applyDefaultVisualizationProps", () => {{identifier: "custom:demo-viz",plugin: PLUGIN,+ prefix: "custom:demo-viz:",},);@@ -49,6 +51,7 @@ describe("applyDefaultVisualizationProps", () => {const { getUiName } = applyDefaultVisualizationProps(COMPONENT, vizDef, {identifier: "custom:demo-viz",plugin: PLUGIN,+ prefix: "custom:demo-viz:",});expect(getUiName()).toBe("Localized demo");@@ -63,6 +66,7 @@ describe("applyDefaultVisualizationProps", () => {const { getUiName } = applyDefaultVisualizationProps(COMPONENT, vizDef, {identifier: "custom:demo-viz",plugin,+ prefix: "custom:demo-viz:",});expect(getUiName()).toBe("Manifest name");@@ -78,6 +82,7 @@ describe("applyDefaultVisualizationProps", () => {const { getUiName } = applyDefaultVisualizationProps(COMPONENT, vizDef, {identifier: "custom:demo-viz",plugin,+ prefix: "custom:demo-viz:",});expect(getUiName()).toBe("Manifest name");@@ -92,6 +97,7 @@ describe("applyDefaultVisualizationProps", () => {const { getUiName } = applyDefaultVisualizationProps(COMPONENT, vizDef, {identifier: "custom:demo-viz",plugin,+ prefix: "custom:demo-viz:",});expect(getUiName()).toBe("Manifest name");@@ -107,6 +113,7 @@ describe("applyDefaultVisualizationProps", () => {applyDefaultVisualizationProps(COMPONENT, vizDef, {identifier: "custom:demo-viz",plugin: PLUGIN,+ prefix: "custom:demo-viz:",}),).toThrow("boom");expect(getName).toHaveBeenCalledTimes(1);diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsxindex 0523e4aa328..ec7e3947ddf 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-plugins.tsx@@ -26,7 +26,11 @@ import {} from "metabase/visualizations/custom-visualizations/custom-viz-utils";import { useBrowserRenderingContext } from "metabase/visualizations/hooks/use-browser-rendering-context";import type { VisualizationProps } from "metabase/visualizations/types/visualization";-import { registerVisualization, visualizations } from "metabase/viz-core";+import {+ getCustomVizSettingKeyPrefix,+ registerVisualization,+ visualizations,+} from "metabase/viz-core";import { useListCustomVizPluginsQuery } from "metabase-enterprise/api";import { customVizPluginApi } from "metabase-enterprise/api/custom-viz-plugin";import type {@@ -41,6 +45,7 @@ import { type PluginClickObject, toHostClickObject } from "./click-object";import { applyDefaultVisualizationProps } from "./custom-viz-common";import { ensureVizApi } from "./custom-viz-globals";import { type PluginHoverObject, toHostHoverObject } from "./hover-object";+import { toPluginSeries, toPluginSettings } from "./plugin-view";import type { SandboxMode } from "./sandbox";import { usePluginMount } from "./use-plugin-mount";import { reportUnavailableCustomVizPlugin } from "./utils/unavailable-toast";@@ -423,11 +428,13 @@ async function fetchAndRegisterCustomVizPlugin(// Build a Metabase-compatible identifier, prefixed to avoid collisionsconst identifier = getCustomPluginIdentifier(plugin);+ const prefix = getCustomVizSettingKeyPrefix(identifier);const Wrapper = createCustomVizWrapper(vizDef.mount,vizDef.VisualizationComponent,plugin,+ prefix,);// core app resolves these to a plain same-origin url like@@ -445,6 +452,7 @@ async function fetchAndRegisterCustomVizPlugin({identifier,plugin,+ prefix,iconUrl: resolvedIconUrl,isDev: Boolean(plugin.dev_bundle_url),},@@ -582,6 +590,7 @@ function createCustomVizWrapper(mount: GenericVizMount,VisualizationComponent: GenericVizDefinition["VisualizationComponent"],plugin: CustomVizPluginRuntime,+ prefix: string,) {return function CustomVizWrapper({width,@@ -621,12 +630,8 @@ function createCustomVizWrapper(const pluginProps: GenericVizPluginProps = {width,height,- // Unjustified type cast. FIXME- series: series as unknown as GenericVizPluginProps["series"],- // The plugin API mirrors host types with looser public shapes (e.g.- // the `column` resolver returns plain strings instead of internal- // unions); the runtime value is the host's computed settings.- settings: settings as unknown as GenericVizPluginProps["settings"],+ series: toPluginSeries(series, prefix),+ settings: toPluginSettings(settings, prefix),renderingContext,onClick: handleClick,onHover: handleHover,diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.tsindex d5be2bc93ce..5ae777edd76 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.ts@@ -1,16 +1,23 @@import type {+ CreateDefineSetting,CustomVisualization,CustomVisualizationMount,- CustomVisualizationSettingDefinition,ReservedVisualizationSettingId,Widgets,} from "custom-viz";import type { ComponentType } from "react";import { t } from "ttag";-import type { CustomVizPluginRuntime } from "metabase-types/api";+import type {+ ComputedVisualizationSettings,+ VisualizationSettingDefinition,+ VisualizationSettingsDefinitions,+} from "metabase/viz-core";+import type { CustomVizPluginRuntime, Series } from "metabase-types/api";import { isObject } from "metabase-types/guards";+import { copyPluginValue } from "./copy-plugin-value";+import { toPluginSeries, toPluginSettings } from "./plugin-view";import { wrapPluginWidget } from "./widget-mount";const RESERVED_SETTING_IDS: ReadonlySet<string> = new Set(@@ -20,60 +27,172 @@ const RESERVED_SETTING_IDS: ReadonlySet<string> = new Set(} satisfies Record<ReservedVisualizationSettingId, true>),);+type PluginSettingDefinitions = CustomVisualization<+ Record<string, unknown>+>["settings"];++type PluginSettingDefinition = Parameters<+ ReturnType<CreateDefineSetting<Record<string, unknown>>>+>[0];++export type HostContext = {+ prefix: string;+ mount: CustomVisualizationMount;+ plugin: CustomVizPluginRuntime;+};+/**- * Walk a plugin's `vizDef.settings` and rewrite every Component-shaped- * `widget` into a host-trusted `WidgetMount` whose body delegates to the- * plugin's shared `mount` function (i.e., its sandbox-side `createRoot`- * render path). Built-in `WidgetName` strings pass through unchanged.+ * Turns plugin's `vizDef.settings` into host definitions. Setting ids and+ * dependency ids get the plugin's namespace, every callback sees the plugin's+ * view of the series and settings, the values `getDefault` and `getValue` return+ * are copied into the host, and custom setting widgets are rewrapped into+ * host-side `WidgetMount`s.*/export function sanitizePluginSettings(- settings:- | CustomVisualization<Record<string, unknown>>["settings"]- | undefined,- mount: CustomVisualizationMount,- plugin: CustomVizPluginRuntime,-): CustomVisualization<Record<string, unknown>>["settings"] {+ settings: PluginSettingDefinitions | undefined,+ context: HostContext,+): VisualizationSettingsDefinitions {if (!settings) {- return settings;+ return {};}- assertValidSettingWidgets(settings);+ const objectDefinitions = Object.entries(settings).flatMap(+ ([settingId, definition]): [string, PluginSettingDefinition][] => {+ if (!isObject(definition)) {+ return [];+ }+ // Definitions leave the sandbox as opaque branded values.+ return [[settingId, definition as unknown as PluginSettingDefinition]];+ },+ );- const sanitizedSettings: CustomVisualization<- Record<string, unknown>- >["settings"] = {};+ assertValidSettingWidgets(objectDefinitions);- for (const [settingId, value] of Object.entries(settings)) {- if (RESERVED_SETTING_IDS.has(settingId)) {- console.warn(- `Custom viz setting "${settingId}" uses a reserved id and was ignored.`,- );- continue;- }+ const definitions = objectDefinitions.flatMap(+ ([settingId, definition]): [string, PluginSettingDefinition][] => {+ if (RESERVED_SETTING_IDS.has(settingId)) {+ console.warn(+ `Custom viz setting "${settingId}" uses a reserved id and was ignored.`,+ );+ return [];+ }+ return [[settingId, definition]];+ },+ );- if (!isObject(value)) {- // settings definitions should be objects- continue;- }+ const declaredIds = new Set(definitions.map(([settingId]) => settingId));++ return Object.fromEntries(+ definitions.map(([settingId, definition]) => [+ `${context.prefix}${settingId}`,+ toHostDefinition(definition, context, declaredIds),+ ]),+ );+}- if ("widget" in value && typeof value.widget === "function") {- // Unjustified type cast. FIXME- const Widget = value.widget as ComponentType<Record<string, unknown>>;- // Unjustified type cast. FIXME- sanitizedSettings[settingId] = {- ...value,- widget: wrapPluginWidget(- (container, initialProps) => mount(Widget, container, initialProps),+function toHostDefinition(+ definition: PluginSettingDefinition,+ { prefix, mount, plugin }: HostContext,+ declaredIds: ReadonlySet<string>,+): VisualizationSettingDefinition<Series> {+ const {+ title,+ group,+ index,+ inline,+ persistDefault,+ getSection,+ widget,+ readDependencies,+ writeDependencies,+ eraseDependencies,+ isValid,+ getDefault,+ getProps,+ getValue,+ } = definition;+ const pluginArgs = (+ series: Series,+ settings: ComputedVisualizationSettings,+ ) =>+ [+ toPluginSeries(series, prefix),+ toPluginSettings(settings, prefix),+ ] as const;++ return {+ title: asString(title),+ group: asString(group),+ index,+ inline,+ persistDefault,+ getSection: getSection && (() => asString(getSection())),+ readDependencies: prefixSettingIds(readDependencies, prefix, declaredIds),+ writeDependencies: prefixSettingIds(writeDependencies, prefix, declaredIds),+ eraseDependencies: prefixSettingIds(eraseDependencies, prefix, declaredIds),+ isValid:+ isValid &&+ ((series, settings) => isValid(...pluginArgs(series, settings))),+ getDefault:+ getDefault &&+ ((series, settings) =>+ copyPluginValue(getDefault(...pluginArgs(series, settings)))),+ getValue:+ getValue &&+ ((series, settings) =>+ copyPluginValue(getValue(...pluginArgs(series, settings)))),+ getProps:+ getProps &&+ ((series, settings) => {+ const props = getProps(...pluginArgs(series, settings));+ // A built-in widget renders these in the host, so no sandbox object may reach it.+ return isComponentWidget(widget) ? props : copyPluginProps(props);+ }),+ widget: isComponentWidget(widget)+ ? wrapPluginWidget(+ (container, initialProps) => mount(widget, container, initialProps),plugin,- ),- } as unknown as CustomVisualizationSettingDefinition<- Record<string, unknown>- >;- } else {- sanitizedSettings[settingId] = value;- }+ prefix,+ )+ : widget,+ };+}++function prefixSettingIds(+ ids: string[] | undefined,+ prefix: string,+ declaredIds: ReadonlySet<string>,+): string[] | undefined {+ if (!Array.isArray(ids)) {+ return undefined;}- return sanitizedSettings;++ // Dependencies may only reference the plugin's own settings - drop anything else.+ return ids.flatMap((id) => {+ return typeof id === "string" && declaredIds.has(id)+ ? [`${prefix}${id}`]+ : [];+ });+}++// Labels end up as React children, so anything but a string is dropped.+function asString(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined;+}++function copyPluginProps(props: unknown): Record<string, unknown> {+ try {+ return isObject(props) ? copyPluginValue(props) : {};+ } catch (error) {+ console.warn("Custom viz widget props were ignored", error);+ return {};+ }+}++function isComponentWidget(+ widget: unknown,+): widget is ComponentType<Record<string, unknown>> {+ return typeof widget === "function";}const ALLOWED_WIDGET_NAMES: Array<keyof Widgets> = [@@ -90,20 +209,18 @@ const ALLOWED_WIDGET_NAMES: Array<keyof Widgets> = [] as const;function assertValidSettingWidgets(- settings: CustomVisualization<Record<string, unknown>>["settings"],+ definitions: [string, PluginSettingDefinition][],): void {- if (!settings) {- return;- }- for (const [settingId, def] of Object.entries(settings)) {- // Unjustified type cast. FIXME- const widget = (def as { widget?: unknown }).widget;- if (- typeof widget === "string" &&- !ALLOWED_WIDGET_NAMES.some((w) => w === widget)- ) {+ for (const [settingId, { widget }] of definitions) {+ if (typeof widget === "string") {+ if (!ALLOWED_WIDGET_NAMES.some((name) => name === widget)) {+ throw new Error(+ t`Setting "${settingId}" has unsupported widget ${widget}. Use one of: ${ALLOWED_WIDGET_NAMES.join(", ")}.`,+ );+ }+ } else if (widget && !isComponentWidget(widget)) {throw new Error(- t`Setting "${settingId}" has unsupported widget ${widget}. Use one of: ${ALLOWED_WIDGET_NAMES.join(", ")}.`,+ t`Setting "${settingId}" has an unsupported widget. Use a component or one of: ${ALLOWED_WIDGET_NAMES.join(", ")}.`,);}}diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.unit.spec.tsindex 2020bbdb9a5..81f68f2a4b2 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.unit.spec.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/custom-viz-settings.unit.spec.ts@@ -6,12 +6,36 @@ import type {} from "custom-viz";import type { ComponentType } from "react";-import { createMockCustomVizPluginRuntime } from "metabase-types/api/mocks";--import { sanitizePluginSettings } from "./custom-viz-settings";+import { getCustomPluginIdentifier } from "metabase/visualizations/custom-visualizations/custom-viz-utils";+import {+ type CustomVizSettingWidgetProps,+ type VisualizationSettingDefinition,+ type VisualizationSettingsDefinitions,+ getCustomVizSettingKeyPrefix,+} from "metabase/viz-core";+import type { Series } from "metabase-types/api";+import {+ createMockCustomVizPluginRuntime,+ createMockSingleSeries,+} from "metabase-types/api/mocks";+import { isFunction, isObject } from "metabase-types/guards";++import {+ type HostContext,+ sanitizePluginSettings,+} from "./custom-viz-settings";import { getWidgetMountPlugin, isWidgetMount } from "./widget-mount";const PLUGIN = createMockCustomVizPluginRuntime();+const PREFIX = getCustomVizSettingKeyPrefix(getCustomPluginIdentifier(PLUGIN));+const SERIES: Series = [+ createMockSingleSeries({ visualization_settings: { threshold: 1 } }),+];+const SETTINGS = {+ "card.title": "Title",+ [`${PREFIX}threshold`]: 1,+ "custom:other:threshold": 2,+};function setupMount() {const handle: CustomVisualizationMountHandle<object> = {@@ -34,58 +58,94 @@ function setupMount() {return handle;};- return { mount, calls, handle };+ const context: HostContext = { prefix: PREFIX, mount, plugin: PLUGIN };++ return { context, calls, handle };+}++function mockWarn() {+ return jest.spyOn(console, "warn").mockImplementation(() => undefined);}describe("sanitizePluginSettings", () => {- it("returns undefined when the plugin declares no settings", () => {- const { mount } = setupMount();+ it("returns no definitions when the plugin declares no settings", () => {+ const { context } = setupMount();- expect(sanitizePluginSettings(undefined, mount, PLUGIN)).toBeUndefined();+ expect(sanitizePluginSettings(undefined, context)).toEqual({});});- it("passes built-in widget settings through unchanged", () => {- const { mount } = setupMount();+ it("namespaces setting ids and copies the documented fields", () => {+ const { context } = setupMount();const threshold = definePluginSetting({title: "Threshold",+ group: "Limits",+ index: 2,+ inline: true,+ persistDefault: true,widget: "number",});- const sanitized = sanitizePluginSettings({ threshold }, mount, PLUGIN);+ const sanitized = sanitizePluginSettings({ threshold }, context);- expect(sanitized?.threshold).toBe(threshold);+ expect(Object.keys(sanitized)).toEqual([`${PREFIX}threshold`]);+ const definition = getHostDefinition(sanitized, `${PREFIX}threshold`);+ expect(definition).toMatchObject({+ title: "Threshold",+ group: "Limits",+ index: 2,+ inline: true,+ persistDefault: true,+ widget: "number",+ });+ expect(definition).not.toBe(threshold);+ });++ it("leaves out fields that are not part of the plugin API", () => {+ const { context } = setupMount();++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ dashboard: false,+ getHidden: () => true,+ onUpdate: () => undefined,+ }),+ },+ context,+ );++ const definition = getHostDefinition(sanitized, `${PREFIX}threshold`);+ expect(definition).not.toHaveProperty("dashboard");+ expect(definition).not.toHaveProperty("getHidden");+ expect(definition).not.toHaveProperty("onUpdate");});it("skips definitions that are not objects", () => {- const { mount } = setupMount();+ const { context } = setupMount();const sanitized = sanitizePluginSettings({ broken: definePluginSetting("not-a-definition") },- mount,- PLUGIN,+ context,);expect(sanitized).toEqual({});});it("drops settings with reserved ids and warns, keeping the rest", () => {- const warn = jest- .spyOn(console, "warn")- .mockImplementation(() => undefined);- const { mount } = setupMount();- const threshold = definePluginSetting({ widget: "number" });+ const warn = mockWarn();+ const { context } = setupMount();const sanitized = sanitizePluginSettings({column: definePluginSetting({ widget: "input" }),column_settings: definePluginSetting({ widget: "input" }),- threshold,+ threshold: definePluginSetting({ widget: "number" }),},- mount,- PLUGIN,+ context,);- expect(sanitized).toEqual({ threshold });+ expect(Object.keys(sanitized)).toEqual([`${PREFIX}threshold`]);expect(warn).toHaveBeenCalledTimes(2);expect(warn).toHaveBeenCalledWith('Custom viz setting "column" uses a reserved id and was ignored.',@@ -97,50 +157,364 @@ describe("sanitizePluginSettings", () => {warn.mockRestore();});+ describe("dependencies", () => {+ it("namespaces read, write and erase dependencies to the plugin's own settings", () => {+ const { context } = setupMount();++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ readDependencies: ["label"],+ writeDependencies: ["label", "goalColumn"],+ eraseDependencies: ["segments"],+ }),+ label: definePluginSetting({ widget: "input" }),+ goalColumn: definePluginSetting({ widget: "input" }),+ segments: definePluginSetting({ widget: "input" }),+ },+ context,+ );++ expect(getHostDefinition(sanitized, `${PREFIX}threshold`)).toMatchObject({+ readDependencies: [`${PREFIX}label`],+ writeDependencies: [`${PREFIX}label`, `${PREFIX}goalColumn`],+ eraseDependencies: [`${PREFIX}segments`],+ });+ });++ it("drops dependencies that don't name the plugin's own settings", () => {+ const { context } = setupMount();++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ readDependencies: ["card.title"],+ writeDependencies: ["label", "card.title"],+ }),+ label: definePluginSetting({ widget: "input" }),+ },+ context,+ );++ const definition = getHostDefinition(sanitized, `${PREFIX}threshold`);+ expect(definition.readDependencies).toEqual([]);+ expect(definition.writeDependencies).toEqual([`${PREFIX}label`]);+ });++ it("drops dependencies that are not lists of ids", () => {+ const { context } = setupMount();++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ readDependencies: "label",+ writeDependencies: ["label", 42],+ }),+ label: definePluginSetting({ widget: "input" }),+ },+ context,+ );++ const definition = getHostDefinition(sanitized, `${PREFIX}threshold`);+ expect(definition.readDependencies).toBeUndefined();+ expect(definition.writeDependencies).toEqual([`${PREFIX}label`]);+ expect(definition.eraseDependencies).toBeUndefined();+ });+ });++ describe("callbacks", () => {+ it.each(["getDefault", "getValue", "isValid", "getProps"])(+ "calls %s with the plugin's view of the series and settings only",+ (name) => {+ const { context } = setupMount();+ const callback = jest.fn<boolean, [Series, ...unknown[]]>(() => true);++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ [name]: callback,+ }),+ },+ context,+ );+ getCallback(getHostDefinition(sanitized, `${PREFIX}threshold`), name)(+ SERIES,+ SETTINGS,+ {},+ jest.fn(),+ jest.fn(),+ );++ expect(callback).toHaveBeenCalledTimes(1);+ expect(callback).toHaveBeenCalledWith([{ data: SERIES[0].data }], {+ "card.title": "Title",+ threshold: 1,+ });+ const [series] = callback.mock.calls[0];+ expect(series[0].data).not.toBe(SERIES[0].data);+ },+ );++ it.each(["getDefault", "getValue"])(+ "copies what %s returns into the host",+ (name) => {+ const { context } = setupMount();+ const pluginValue = ["count"];++ const sanitized = sanitizePluginSettings(+ {+ columns: definePluginSetting({+ widget: "input",+ [name]: () => new Proxy(pluginValue, {}),+ }),+ },+ context,+ );+ const result = getCallback(+ getHostDefinition(sanitized, `${PREFIX}columns`),+ name,+ )(SERIES, SETTINGS, {});++ expect(result).toEqual(pluginValue);+ expect(result).not.toBe(pluginValue);+ expect(() => structuredClone(result)).not.toThrow();+ },+ );++ it("copies what getProps returns for a built-in widget", () => {+ const { context } = setupMount();+ const options = [{ name: "Count", value: "count" }];++ const sanitized = sanitizePluginSettings(+ {+ metric: definePluginSetting({+ widget: "select",+ getProps: () => new Proxy({ options: new Proxy(options, {}) }, {}),+ }),+ },+ context,+ );+ const props = getCallback(+ getHostDefinition(sanitized, `${PREFIX}metric`),+ "getProps",+ )(SERIES, SETTINGS, {});++ expect(props).toEqual({ options });+ if (!isObject(props)) {+ throw new Error("Expected props");+ }+ expect(props.options).not.toBe(options);+ expect(() => structuredClone(props)).not.toThrow();+ });++ it("drops built-in widget props that could pass for React elements", () => {+ const warn = mockWarn();+ const { context } = setupMount();+ const element = {+ $$typeof: Symbol.for("react.element"),+ type: "div",+ props: { dangerouslySetInnerHTML: { __html: "<img src=x onerror=1>" } },+ };++ const sanitized = sanitizePluginSettings(+ {+ mode: definePluginSetting({+ widget: "radio",+ getProps: () => ({ options: [{ name: element, value: "x" }] }),+ }),+ },+ context,+ );+ const props = getCallback(+ getHostDefinition(sanitized, `${PREFIX}mode`),+ "getProps",+ )(SERIES, SETTINGS, {});++ expect(props).toEqual({});+ expect(warn).toHaveBeenCalledTimes(1);+ warn.mockRestore();+ });++ it.each([undefined, null, "props", 42])(+ "turns the non-object getProps result %p into no props",+ (result) => {+ const { context } = setupMount();++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ getProps: () => result,+ }),+ },+ context,+ );++ expect(+ getCallback(+ getHostDefinition(sanitized, `${PREFIX}threshold`),+ "getProps",+ )(SERIES, SETTINGS, {}),+ ).toEqual({});+ },+ );++ it("hands a component widget its getProps result as is, callbacks included", () => {+ const { context } = setupMount();+ const Widget: ComponentType<Record<string, unknown>> = () => null;+ const pluginProps = { onFormat: () => "formatted" };++ const sanitized = sanitizePluginSettings(+ {+ custom: definePluginSetting({+ widget: Widget,+ getProps: () => pluginProps,+ }),+ },+ context,+ );++ expect(+ getCallback(+ getHostDefinition(sanitized, `${PREFIX}custom`),+ "getProps",+ )(SERIES, SETTINGS, {}),+ ).toBe(pluginProps);+ });++ it("drops a title, group and section that are not strings", () => {+ const { context } = setupMount();+ const element = { $$typeof: Symbol.for("react.element"), type: "div" };++ const sanitized = sanitizePluginSettings(+ {+ threshold: definePluginSetting({+ widget: "number",+ title: element,+ group: element,+ getSection: () => element,+ }),+ },+ context,+ );++ const definition = getHostDefinition(sanitized, `${PREFIX}threshold`);+ expect(definition.title).toBeUndefined();+ expect(definition.group).toBeUndefined();+ expect(+ getCallback(definition, "getSection")(SERIES, SETTINGS, {}),+ ).toBeUndefined();+ });++ it("calls getSection without arguments", () => {+ const { context } = setupMount();+ const getSection = jest.fn(() => "Display");++ const sanitized = sanitizePluginSettings(+ { threshold: definePluginSetting({ widget: "number", getSection }) },+ context,+ );++ expect(+ getCallback(+ getHostDefinition(sanitized, `${PREFIX}threshold`),+ "getSection",+ )(SERIES, SETTINGS, {}),+ ).toBe("Display");+ expect(getSection).toHaveBeenCalledWith();+ });+ });+describe("component widgets", () => {const Widget: ComponentType<Record<string, unknown>> = () => null;it("rewrites a component widget into a plugin-tagged WidgetMount", () => {- const { mount } = setupMount();+ const { context } = setupMount();const original = definePluginSetting({ title: "Custom", widget: Widget });const sanitized = sanitizePluginSettings({ customWidget: original },- mount,- PLUGIN,+ context,);- const definition = getRuntimeDefinition(sanitized?.customWidget);+ const definition = getHostDefinition(sanitized, `${PREFIX}customWidget`);expect(definition.title).toBe("Custom");- const widget = getMountWidget(sanitized?.customWidget);+ const widget = getMountWidget(definition);expect(isWidgetMount(widget)).toBe(true);expect(getWidgetMountPlugin(widget)).toBe(PLUGIN);-- expect(getRuntimeDefinition(original).widget).toBe(Widget);});- it("delegates mounting to the plugin's shared mount function", () => {- const { mount, calls, handle } = setupMount();+ it("delegates mounting to the plugin's shared mount function with the prefixed DOM id", () => {+ const { context, calls, handle } = setupMount();const sanitized = sanitizePluginSettings({ customWidget: definePluginSetting({ widget: Widget }) },- mount,- PLUGIN,+ context,);- const widget = getMountWidget(sanitized?.customWidget);+ const widget = getMountWidget(+ getHostDefinition(sanitized, `${PREFIX}customWidget`),+ );const container = document.createElement("div");- const initialProps = { id: "customWidget" };- const mountHandle = widget(container, initialProps);+ const mountHandle = widget(container, {+ id: `${PREFIX}customWidget`,+ value: null,+ onChange: jest.fn(),+ onChangeSettings: jest.fn(),+ });++ expect(calls).toMatchObject([{ Component: Widget, container }]);+ expect(calls[0].initialProps).toMatchObject({+ id: `${PREFIX}customWidget`,+ });++ mountHandle.unmount();+ expect(handle.unmount).toHaveBeenCalledTimes(1);+ });- expect(calls).toEqual([{ Component: Widget, container, initialProps }]);- expect(mountHandle).toBe(handle);+ it("namespaces the settings a widget writes", () => {+ const { context, calls } = setupMount();+ const onChangeSettings = jest.fn();+ const sanitized = sanitizePluginSettings(+ { customWidget: definePluginSetting({ widget: Widget }) },+ context,+ );++ const widget = getMountWidget(+ getHostDefinition(sanitized, `${PREFIX}customWidget`),+ );+ widget(document.createElement("div"), {+ id: `${PREFIX}customWidget`,+ value: null,+ onChange: jest.fn(),+ onChangeSettings,+ });+ const mountedProps = calls[0].initialProps;+ if (!isObject(mountedProps)) {+ throw new Error("Expected the widget to be mounted with props");+ }+ getCallback(+ mountedProps,+ "onChangeSettings",+ )({+ customWidget: "a",+ "gauge.segments": [],+ });++ expect(onChangeSettings).toHaveBeenCalledWith({+ [`${PREFIX}customWidget`]: "a",+ [`${PREFIX}gauge.segments`]: [],+ });});});describe("widget validation", () => {it("throws for unsupported built-in widget names", () => {- const { mount } = setupMount();+ const { context } = setupMount();expect(() =>sanitizePluginSettings(@@ -148,14 +522,35 @@ describe("sanitizePluginSettings", () => {threshold: definePluginSetting({ widget: "number" }),bad: definePluginSetting({ widget: "dropdown" }),},- mount,- PLUGIN,+ context,+ ),+ ).toThrow();+ });++ it("reports a bad widget name even on a reserved id that is later dropped", () => {+ const { context } = setupMount();++ expect(() =>+ sanitizePluginSettings(+ { column: definePluginSetting({ widget: "dropdown" }) },+ context,),).toThrow();});+ it("throws for a widget that is neither a name nor a component", () => {+ const { context } = setupMount();++ expect(() =>+ sanitizePluginSettings(+ { bad: definePluginSetting({ widget: 42 }) },+ context,+ ),+ ).toThrow(/unsupported widget/);+ });+it("accepts every allowed built-in widget name", () => {- const { mount } = setupMount();+ const { context } = setupMount();const allowedNames = ["input","number",@@ -175,9 +570,7 @@ describe("sanitizePluginSettings", () => {]),);- expect(() =>- sanitizePluginSettings(settings, mount, PLUGIN),- ).not.toThrow();+ expect(() => sanitizePluginSettings(settings, context)).not.toThrow();});});});@@ -193,30 +586,36 @@ function definePluginSetting(>;}-type RuntimeSettingDefinition = {- title?: string;- widget: WidgetMount | string;-};+function getHostDefinition(+ definitions: VisualizationSettingsDefinitions,+ id: string,+): VisualizationSettingDefinition<Series> {+ const definition = definitions[id];++ if (!isObject(definition)) {+ throw new Error(`Expected a definition for "${id}"`);+ }-function getRuntimeDefinition(- definition:- | CustomVisualizationSettingDefinition<Record<string, unknown>>- | undefined,-): RuntimeSettingDefinition {- // The branded type is opaque by design; at runtime it's a plain- // definition object, which is what these assertions inspect.- return definition as unknown as RuntimeSettingDefinition;+ return definition;+}++function getCallback(source: object, name: string) {+ const callback = Reflect.get(source, name);++ if (!isFunction(callback)) {+ throw new Error(`Expected "${name}" to be a function`);+ }++ return callback;}function getMountWidget(- definition:- | CustomVisualizationSettingDefinition<Record<string, unknown>>- | undefined,-): WidgetMount {- const { widget } = getRuntimeDefinition(definition);-- if (typeof widget === "string") {- throw new Error(`Expected a WidgetMount, got widget name "${widget}"`);+ definition: VisualizationSettingDefinition<Series>,+): WidgetMount<CustomVizSettingWidgetProps> {+ const { widget } = definition;++ if (!isWidgetMount(widget)) {+ throw new Error(`Expected a WidgetMount, got widget "${String(widget)}"`);}return widget;diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/plugin-view.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/plugin-view.tsnew file mode 100644index 00000000000..bc4eceeef43--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/plugin-view.ts@@ -0,0 +1,138 @@+import type { CustomVisualizationProps } from "custom-viz";++import { isCustomVizSettingKey } from "metabase/viz-core";+import type { Series, VisualizationSettings } from "metabase-types/api";++type PluginProps = CustomVisualizationProps<Record<string, unknown>>;++export type PluginSeries = PluginProps["series"];++export type PluginSettings = PluginProps["settings"];++// Keyed by a host object, then by the plugin's prefix.+// Every plugin gets its own copy, so one plugin's mutations can't reach another's.+class PerPluginCache<K extends object, V> {+ private readonly byKey = new WeakMap<K, Map<string, V>>();++ get(key: K, prefix: string): V | undefined {+ return this.byKey.get(key)?.get(prefix);+ }++ set(key: K, prefix: string, value: V): void {+ const byPrefix = this.byKey.get(key) ?? new Map<string, V>();+ byPrefix.set(prefix, value);+ this.byKey.set(key, byPrefix);+ }+}++const pluginSeriesCache = new PerPluginCache<Series, PluginSeries>();+const pluginDataCache = new PerPluginCache<+ Series[number]["data"],+ PluginSeries[number]["data"]+>();+const pluginSettingsCache = new PerPluginCache<+ VisualizationSettings,+ PluginSettings+>();++export function toPluginSeries(series: Series, prefix: string): PluginSeries {+ const cached = pluginSeriesCache.get(series, prefix);++ if (cached) {+ return cached;+ }++ const pluginSeries = series.map(({ data, error }) => ({+ data: toPluginData(data, prefix),+ error: structuredClone(error),+ }));+ pluginSeriesCache.set(series, prefix, pluginSeries);++ return pluginSeries;+}++// Sensibility probes rebuild the series array per display, so the expensive+// dataset clone is keyed on the stable data object - one clone per plugin and+// query result.+function toPluginData(+ data: Series[number]["data"],+ prefix: string,+): PluginSeries[number]["data"] {+ const cached = pluginDataCache.get(data, prefix);++ if (cached) {+ return cached;+ }++ const cloned = structuredClone(data);+ pluginDataCache.set(data, prefix, cloned);++ return cloned;+}++// The plugin sees internal Metabase settings plus its own without the prefix.+// On setting name collision, the plugin setting shadows the internal one.+export function toPluginSettings(+ settings: VisualizationSettings,+ prefix: string,+): PluginSettings {+ const cached = pluginSettingsCache.get(settings, prefix);++ if (cached) {+ return cached;+ }++ const entries = Object.entries(settings);+ const hostEntries = entries.filter(([key]) => !isCustomVizSettingKey(key));+ const pluginEntries = entries+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, value]) => [key.slice(prefix.length), value]);++ const merged = Object.fromEntries([...hostEntries, ...pluginEntries]);++ // Deep-clone so a plugin can't mutate a shared nested host object (e.g. `click_behavior`)+ // through the sandbox membrane.+ const pluginSettings: PluginSettings = cloneCloneableEntries(merged);++ if (typeof merged.column === "function") {+ pluginSettings.column = (column) => {+ // Fresh copy per call so mutating the result can't reach the host's memoized settings.+ const { column: _embeddedColumn, ...columnSettings } =+ merged.column(column);+ return {+ ...cloneCloneableEntries(columnSettings),+ column,+ };+ };+ }++ pluginSettingsCache.set(settings, prefix, pluginSettings);++ return pluginSettings;+}++// Drops entries values of which structuredClone rejects.+function cloneCloneableEntries(+ value: Record<string, unknown>,+): Record<string, unknown> {+ const cloned: Record<string, unknown> = {};++ for (const [key, entry] of Object.entries(value)) {+ try {+ cloned[key] = structuredClone(entry);+ } catch {+ // dropped+ }+ }++ return cloned;+}++export function toHostSettings(+ settings: Record<string, unknown>,+ prefix: string,+): Record<string, unknown> {+ return Object.fromEntries(+ Object.entries(settings).map(([key, value]) => [`${prefix}${key}`, value]),+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/plugin-view.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/plugin-view.unit.spec.tsnew file mode 100644index 00000000000..d0e3903ea9a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/plugin-view.unit.spec.ts@@ -0,0 +1,251 @@+import { createMockSingleSeries } from "metabase-types/api/mocks";+import { isFunction, isObject } from "metabase-types/guards";++import {+ toHostSettings,+ toPluginSeries,+ toPluginSettings,+} from "./plugin-view";++const PREFIX = "custom:demo-viz:";++describe("toPluginSeries", () => {+ it("hands the plugin a copy of only the documented series fields", () => {+ const series = [createMockSingleSeries({})];++ const pluginSeries = toPluginSeries(series, PREFIX);++ expect(Object.keys(pluginSeries[0]).sort()).toEqual(["data", "error"]);+ expect(pluginSeries[0].data).toEqual(series[0].data);+ expect(pluginSeries[0].data).not.toBe(series[0].data);+ });++ it("keeps plugin mutations away from the host series", () => {+ const series = [createMockSingleSeries({})];+ const { data } = series[0];++ const pluginSeries = toPluginSeries(series, PREFIX);+ pluginSeries[0].data.rows.push([1]);++ expect(data.rows).toEqual([]);+ });++ it("gives each plugin its own copy of the data", () => {+ const series = [createMockSingleSeries({})];++ const other = toPluginSeries(series, "custom:other:");+ other[0].data.rows.push([1]);++ expect(toPluginSeries(series, PREFIX)[0].data.rows).toEqual([]);+ });++ it("reuses the copy for the same series", () => {+ const series = [createMockSingleSeries({})];++ expect(toPluginSeries(series, PREFIX)).toBe(toPluginSeries(series, PREFIX));+ expect(toPluginSeries([...series], PREFIX)).not.toBe(+ toPluginSeries(series, PREFIX),+ );+ });++ it("reuses the data clone when the series array is rebuilt", () => {+ const series = [createMockSingleSeries({})];+ const rebuilt = series.map((single) => ({+ ...single,+ card: { ...single.card },+ }));++ expect(toPluginSeries(rebuilt, PREFIX)[0].data).toBe(+ toPluginSeries(series, PREFIX)[0].data,+ );+ });++ it("preserves Map and Date column values a JSON round-trip would corrupt", () => {+ const remapping = new Map([[1, "One"]]);+ const series = [createMockSingleSeries({})];+ series[0].data.cols[0].remapping = remapping;+ series[0].data.rows = [[new Date("2020-01-01T00:00:00.000Z")]];++ const pluginSeries = toPluginSeries(series, PREFIX);+ const pluginRemapping = Reflect.get(+ pluginSeries[0].data.cols[0],+ "remapping",+ );++ const getEntry =+ isObject(pluginRemapping) && isFunction(pluginRemapping.get)+ ? pluginRemapping.get+ : null;++ if (!getEntry) {+ throw new Error("Expected the plugin column to keep its remapping Map");+ }++ expect(pluginRemapping).not.toBe(remapping);+ expect(getEntry.call(pluginRemapping, 1)).toBe("One");+ expect(typeof pluginSeries[0].data.rows[0][0]).not.toBe("string");+ });+});++describe("toPluginSettings", () => {+ it("strips the plugin's prefix and keeps host settings", () => {+ expect(+ toPluginSettings(+ { "card.title": "Title", [`${PREFIX}threshold`]: 42 },+ PREFIX,+ ),+ ).toEqual({ "card.title": "Title", threshold: 42 });+ });++ it("drops other plugins' settings", () => {+ expect(toPluginSettings({ "custom:other:threshold": 1 }, PREFIX)).toEqual(+ {},+ );+ });++ it("lets a plugin setting shadow a same-named host setting", () => {+ expect(+ toPluginSettings(+ { "card.title": "Host", [`${PREFIX}card.title`]: "Plugin" },+ PREFIX,+ ),+ ).toEqual({ "card.title": "Plugin" });+ });++ it("keeps a plugin's mutation of a nested value away from the host settings", () => {+ const clickBehavior = { type: "crossfilter" };+ const settings = { click_behavior: clickBehavior };++ const pluginSettings = toPluginSettings(settings, PREFIX);+ const pluginClickBehavior: unknown = Reflect.get(+ pluginSettings,+ "click_behavior",+ );+ if (!isObject(pluginClickBehavior)) {+ throw new Error("Expected the plugin to see click_behavior");+ }+ pluginClickBehavior.type = "link";++ expect(clickBehavior.type).toBe("crossfilter");+ });++ it("keeps an undefined host value as an own key", () => {+ const pluginSettings = toPluginSettings(+ { click_behavior: undefined },+ PREFIX,+ );++ expect(Object.hasOwn(pluginSettings, "click_behavior")).toBe(true);+ });++ it("preserves a Map setting value a JSON round-trip would corrupt", () => {+ const pluginSettings = toPluginSettings(+ { [`${PREFIX}lookup`]: new Map([["a", 1]]) },+ PREFIX,+ );+ const lookup = Reflect.get(pluginSettings, "lookup");+ const getEntry =+ isObject(lookup) && isFunction(lookup.get) ? lookup.get : null;++ if (!getEntry) {+ throw new Error("Expected the plugin to keep its Map setting");+ }++ expect(getEntry.call(lookup, "a")).toBe(1);+ });++ it("exposes column as a callable whose results can't poison the host", () => {+ const columnSettings = { prefix: "$" };+ const settings = { column: () => columnSettings };++ const pluginSettings = toPluginSettings(settings, PREFIX);+ const column = Reflect.get(pluginSettings, "column");++ if (!isFunction(column)) {+ throw new Error("Expected the plugin to see the column function");+ }++ const col = { name: "X" };+ const first = column(col);++ if (!isObject(first)) {+ throw new Error("Expected column settings");+ }++ first.prefix = "mutated";++ expect(columnSettings.prefix).toBe("$");+ expect(column(col)).toEqual({ prefix: "$", column: col });+ });++ it("hands the caller's own column back and drops host caches from the result", () => {+ const settings = {+ column: (col: unknown) => ({+ prefix: "$",+ column: col,+ _numberFormatter: new Intl.NumberFormat(),+ }),+ };++ const pluginSettings = toPluginSettings(settings, PREFIX);+ const column = Reflect.get(pluginSettings, "column");++ if (!isFunction(column)) {+ throw new Error("Expected the plugin to see the column function");+ }++ const col = { name: "mine" };+ const result = column(col);++ if (!isObject(result)) {+ throw new Error("Expected column settings");+ }++ expect(result.column).toBe(col);+ expect(Object.hasOwn(result, "_numberFormatter")).toBe(false);+ });++ it("silently drops other function-valued settings", () => {+ const pluginSettings = toPluginSettings(+ { [`${PREFIX}callback`]: () => 1 },+ PREFIX,+ );++ expect(Object.hasOwn(pluginSettings, "callback")).toBe(false);+ });++ it("silently drops values structuredClone rejects", () => {+ const pluginSettings = toPluginSettings(+ { _numberFormatter: new Intl.NumberFormat(), "card.title": "Title" },+ PREFIX,+ );++ expect(Object.hasOwn(pluginSettings, "_numberFormatter")).toBe(false);+ expect(pluginSettings["card.title"]).toBe("Title");+ });++ it("reuses the translation for the same settings object", () => {+ const settings = { [`${PREFIX}threshold`]: 42 };++ expect(toPluginSettings(settings, PREFIX)).toBe(+ toPluginSettings(settings, PREFIX),+ );+ expect(toPluginSettings(settings, "custom:other:")).not.toBe(+ toPluginSettings(settings, PREFIX),+ );+ expect(toPluginSettings({ ...settings }, PREFIX)).not.toBe(+ toPluginSettings(settings, PREFIX),+ );+ });+});++describe("toHostSettings", () => {+ it("prefixes every key", () => {+ expect(+ toHostSettings({ threshold: 1, "gauge.segments": [] }, PREFIX),+ ).toEqual({+ [`${PREFIX}threshold`]: 1,+ [`${PREFIX}gauge.segments`]: [],+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.tsindex 2ac0a314aa1..e439dcab0e5 100644--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.ts+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.ts@@ -1,36 +1,87 @@-import type { WidgetMount } from "custom-viz";+import type { BaseWidgetProps, WidgetMount } from "custom-viz";import type { ComponentType } from "react";+import type { CustomVizSettingWidgetProps } from "metabase/viz-core";import type { CustomVizPluginRuntime } from "metabase-types/api";+import { isObject } from "metabase-types/guards";++import { copyPluginValue } from "./copy-plugin-value";+import { toHostSettings } from "./plugin-view";++// What the plugin's setting widget receives: the SDK base props + whatever setting definition's `getProps` adds.+export type PluginWidgetProps = BaseWidgetProps<+ unknown,+ Record<string, unknown>+> &+ Record<string, unknown>;/*** A host-allocated `WidgetMount` tagged with the plugin it renders.*/-type WidgetMountWithPlugin = WidgetMount & {+type WidgetMountWithPlugin = WidgetMount<CustomVizSettingWidgetProps> & {plugin: CustomVizPluginRuntime;};/*** Wrap a plugin-supplied function-shaped widget in a host-allocated- * `WidgetMount` tagged with its plugin.+ * `WidgetMount` tagged with its plugin. Props are translated on the way in,+ * and what the widget writes is copied so the host never holds sandbox objects.*/export function wrapPluginWidget(- pluginWidget: WidgetMount,+ pluginWidget: WidgetMount<PluginWidgetProps>,plugin: CustomVizPluginRuntime,+ prefix: string,): WidgetMountWithPlugin {- const mount: WidgetMount = (container, initialProps) =>- pluginWidget(container, initialProps);+ const mount: WidgetMount<CustomVizSettingWidgetProps> = (+ container,+ initialProps,+ ) => {+ const handle = pluginWidget(+ container,+ toPluginWidgetProps(initialProps, prefix),+ );+ return {+ update: (props) => handle.update(toPluginWidgetProps(props, prefix)),+ unmount: () => handle.unmount(),+ };+ };return Object.assign(mount, { plugin });}+function toPluginWidgetProps(+ {+ id,+ value,+ onChange,+ onChangeSettings,+ ...extraProps+ }: CustomVizSettingWidgetProps,+ prefix: string,+): PluginWidgetProps {+ return {+ ...extraProps,+ id,+ value: structuredClone(value),+ onChange: (value) => onChange(copyPluginValue(value)),+ onChangeSettings: (settings) =>+ onChangeSettings(+ toHostSettings(+ copyPluginValue(isObject(settings) ? settings : {}),+ prefix,+ ),+ ),+ };+}+export function isWidgetMount(value:| string- | WidgetMount+ | WidgetMount<CustomVizSettingWidgetProps>| ComponentType<{id: string;- }>,+ }>+ | undefined,): value is WidgetMountWithPlugin {return typeof value === "function" && "plugin" in value;}@@ -40,7 +91,7 @@ export function isWidgetMount(* `wrapPluginWidget`.*/export function getWidgetMountPlugin(- maybeWidgetMount: WidgetMount,+ maybeWidgetMount: WidgetMount<CustomVizSettingWidgetProps>,): CustomVizPluginRuntime | undefined {if (!isWidgetMount(maybeWidgetMount)) {return undefined;diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.unit.spec.tsnew file mode 100644index 00000000000..24432157b7e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.unit.spec.ts@@ -0,0 +1,220 @@+import type { WidgetMount, WidgetMountHandle } from "custom-viz";++import { createMockCustomVizPluginRuntime } from "metabase-types/api/mocks";+import { isFunction, isObject } from "metabase-types/guards";++import {+ getWidgetMountPlugin,+ isWidgetMount,+ wrapPluginWidget,+} from "./widget-mount";++const PLUGIN = createMockCustomVizPluginRuntime();+const PREFIX = "custom:demo-viz:";++type WidgetProps = Record<string, unknown>;++function setup() {+ const handle: WidgetMountHandle<WidgetProps> = {+ update: jest.fn(),+ unmount: jest.fn(),+ };+ const pluginWidget = jest.fn<+ WidgetMountHandle<WidgetProps>,+ Parameters<WidgetMount>+ >(() => handle);+ const onChange = jest.fn();+ const onChangeSettings = jest.fn();++ const mount = wrapPluginWidget(pluginWidget, PLUGIN, PREFIX);+ const container = document.createElement("div");+ const mountHandle = mount(container, {+ id: `${PREFIX}threshold`,+ value: 1,+ onChange,+ onChangeSettings,+ });++ return {+ container,+ handle,+ mount,+ mountHandle,+ mountedProps: pluginWidget.mock.calls[0][1],+ onChange,+ onChangeSettings,+ pluginWidget,+ };+}++describe("wrapPluginWidget", () => {+ it("tags the mount with its plugin", () => {+ const { mount } = setup();++ expect(isWidgetMount(mount)).toBe(true);+ expect(getWidgetMountPlugin(mount)).toBe(PLUGIN);+ });++ it("mounts into the container keeping the prefixed DOM id", () => {+ const { container, mountedProps, pluginWidget } = setup();++ expect(pluginWidget).toHaveBeenCalledWith(container, mountedProps);+ expect(mountedProps).toMatchObject({ id: `${PREFIX}threshold`, value: 1 });+ });++ it("forwards only the value to onChange", () => {+ const { mountedProps, onChange } = setup();++ getCallback(mountedProps, "onChange")(2, { forged: "question" });++ expect(onChange).toHaveBeenCalledWith(2);+ });++ it("namespaces every key written through onChangeSettings", () => {+ const { mountedProps, onChangeSettings } = setup();++ getCallback(mountedProps, "onChangeSettings")(+ {+ threshold: 2,+ "gauge.segments": [{ min: { type: "card", id: 1, column: "x" } }],+ },+ { forged: "question" },+ );++ expect(onChangeSettings).toHaveBeenCalledWith({+ [`${PREFIX}threshold`]: 2,+ [`${PREFIX}gauge.segments`]: [+ { min: { type: "card", id: 1, column: "x" } },+ ],+ });+ });++ it.each([null, undefined, "threshold", 42, true])(+ "turns the non-object payload %p into an empty update",+ (payload) => {+ const { mountedProps, onChangeSettings } = setup();++ getCallback(mountedProps, "onChangeSettings")(payload);++ expect(onChangeSettings).toHaveBeenCalledWith({});+ },+ );++ it("translates the props passed through update", () => {+ const { handle, mountHandle } = setup();+ const onChangeSettings = jest.fn();++ mountHandle.update({+ id: `${PREFIX}threshold`,+ value: 2,+ onChange: jest.fn(),+ onChangeSettings,+ });++ expect(handle.update).toHaveBeenCalledTimes(1);+ const updatedProps = jest.mocked(handle.update).mock.calls[0][0];+ expect(updatedProps).toMatchObject({ id: `${PREFIX}threshold`, value: 2 });++ getCallback(updatedProps, "onChangeSettings")({ threshold: 3 });+ expect(onChangeSettings).toHaveBeenCalledWith({+ [`${PREFIX}threshold`]: 3,+ });+ });++ it("clones the value so a widget can't mutate host state in place", () => {+ const handle: WidgetMountHandle<WidgetProps> = {+ update: jest.fn(),+ unmount: jest.fn(),+ };+ const pluginWidget = jest.fn<+ WidgetMountHandle<WidgetProps>,+ Parameters<WidgetMount>+ >(() => handle);+ const hostValue = { min: 1 };++ wrapPluginWidget(+ pluginWidget,+ PLUGIN,+ PREFIX,+ )(document.createElement("div"), {+ id: `${PREFIX}threshold`,+ value: hostValue,+ onChange: jest.fn(),+ onChangeSettings: jest.fn(),+ });++ const mountedValue = pluginWidget.mock.calls[0][1].value;++ if (!isObject(mountedValue)) {+ throw new Error("Expected the widget to receive the object value");+ }++ mountedValue.min = 99;++ expect(hostValue.min).toBe(1);+ });++ it("mounts without a value", () => {+ const pluginWidget = jest.fn<+ WidgetMountHandle<WidgetProps>,+ Parameters<WidgetMount>+ >(() => ({ update: jest.fn(), unmount: jest.fn() }));++ wrapPluginWidget(+ pluginWidget,+ PLUGIN,+ PREFIX,+ )(document.createElement("div"), {+ id: `${PREFIX}threshold`,+ value: undefined,+ onChange: jest.fn(),+ onChangeSettings: jest.fn(),+ });++ expect(pluginWidget.mock.calls[0][1].value).toBeUndefined();+ });++ it("copies the value a widget writes so the host never holds a sandbox object", () => {+ const { mountedProps, onChange } = setup();+ const pluginValue = ["count"];++ getCallback(mountedProps, "onChange")(new Proxy(pluginValue, {}));++ const [written] = onChange.mock.calls[0];+ expect(written).toEqual(pluginValue);+ expect(written).not.toBe(pluginValue);+ expect(() => structuredClone(written)).not.toThrow();+ });++ it("copies the settings a widget writes", () => {+ const { mountedProps, onChangeSettings } = setup();+ const pluginValue = ["count"];++ getCallback(+ mountedProps,+ "onChangeSettings",+ )(new Proxy({ columns: pluginValue }, {}));++ const [written] = onChangeSettings.mock.calls[0];+ expect(written).toEqual({ [`${PREFIX}columns`]: pluginValue });+ expect(written[`${PREFIX}columns`]).not.toBe(pluginValue);+ });++ it("delegates unmount", () => {+ const { handle, mountHandle } = setup();++ mountHandle.unmount();++ expect(handle.unmount).toHaveBeenCalledTimes(1);+ });+});++function getCallback(props: WidgetProps, name: string) {+ const callback = props[name];++ if (!isFunction(callback)) {+ throw new Error(`Expected "${name}" to be a function`);+ }++ return callback;+}diff --git a/frontend/src/metabase-types/guards/common.ts b/frontend/src/metabase-types/guards/common.tsindex 15a3fb48451..7e1fa8a7f7b 100644--- a/frontend/src/metabase-types/guards/common.ts+++ b/frontend/src/metabase-types/guards/common.ts@@ -3,3 +3,21 @@ export const isObject = (): value is Record<string | number | symbol, unknown> => {return typeof value === "object" && value !== null;};++export const isFunction = (+ value: unknown,+): value is (...args: unknown[]) => unknown => {+ return typeof value === "function";+};++export const isMap = (value: unknown): value is Map<unknown, unknown> => {+ return Object.prototype.toString.call(value) === "[object Map]";+};++export const isSet = (value: unknown): value is Set<unknown> => {+ return Object.prototype.toString.call(value) === "[object Set]";+};++export const isDate = (value: unknown): value is Date => {+ return Object.prototype.toString.call(value) === "[object Date]";+};diff --git a/frontend/src/metabase/documents/documents.slice.unit.spec.ts b/frontend/src/metabase/documents/documents.slice.unit.spec.tsindex 00817571b22..e02340551f2 100644--- a/frontend/src/metabase/documents/documents.slice.unit.spec.ts+++ b/frontend/src/metabase/documents/documents.slice.unit.spec.ts@@ -45,12 +45,12 @@ describe("documents slice", () => {createStateWithDraftCard({ "card.title": "Title", threshold: 42 }),replaceVizSettings({cardId: DRAFT_CARD_ID,- settings: { "custom-viz:plugin:threshold": 43 },+ settings: { "custom:plugin:threshold": 43 },}),);expect(getDraftCardSettings(state)).toEqual({- "custom-viz:plugin:threshold": 43,+ "custom:plugin:threshold": 43,});});diff --git a/frontend/src/metabase/plugins/oss/custom-viz.ts b/frontend/src/metabase/plugins/oss/custom-viz.tsindex 2131b7c4810..f0310d9903f 100644--- a/frontend/src/metabase/plugins/oss/custom-viz.ts+++ b/frontend/src/metabase/plugins/oss/custom-viz.ts@@ -4,6 +4,7 @@ import type { ToastArgs } from "metabase/common/hooks";import type { IconData } from "metabase/common/utils/icon";import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";import type { Dispatch } from "metabase/redux/store";+import type { CustomVizSettingWidgetProps } from "metabase/viz-core";import type {CustomVizPluginId,CustomVizPluginRuntime,@@ -84,11 +85,13 @@ const getDefaultPluginCustomViz = () => ({/*** Always false in OSS as there is no plugin to produce a mount handle.*/- isWidgetMount: (_value: unknown): _value is WidgetMount => false,+ isWidgetMount: (+ _value: unknown,+ ): _value is WidgetMount<CustomVizSettingWidgetProps> => false,CustomVizSettingWidget: PluginPlaceholder<{- mount: WidgetMount;- widgetProps: Record<string, unknown>;+ mount: WidgetMount<CustomVizSettingWidgetProps>;+ widgetProps: CustomVizSettingWidgetProps;}>,});diff --git a/frontend/src/metabase/query_builder/utils/viz-settings.ts b/frontend/src/metabase/query_builder/utils/viz-settings.tsindex 61774a02100..67d3769f7ad 100644--- a/frontend/src/metabase/query_builder/utils/viz-settings.ts+++ b/frontend/src/metabase/query_builder/utils/viz-settings.ts@@ -1,7 +1,10 @@import _ from "underscore";import { syncVizSettingsWithQuery } from "metabase/querying/viz-settings/utils/sync-viz-settings";-import { getPersistableDefaultSettingsForSeries } from "metabase/viz-core";+import {+ adoptLegacyCustomVizSettings,+ getPersistableDefaultSettingsForSeries,+} from "metabase/viz-core";import * as Lib from "metabase-lib";import type Question from "metabase-lib/v1/Question";import type { Series } from "metabase-types/api";@@ -16,7 +19,11 @@ export function getQuestionWithDefaultVisualizationSettings(question: Question,series: Series,) {- const oldVizSettings = question.settings();+ // Adopting a legacy custom viz key should not dirty the question+ const oldVizSettings = adoptLegacyCustomVizSettings(+ question.display(),+ question.settings(),+ );const newVizSettings = {...oldVizSettings,...getPersistableDefaultSettingsForSeries(series),diff --git a/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.ts b/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.tsnew file mode 100644index 00000000000..a067ca6b1c8--- /dev/null+++ b/frontend/src/metabase/query_builder/utils/viz-settings.unit.spec.ts@@ -0,0 +1,72 @@+import { createMockMetadata } from "__support__/metadata";+import { registerVisualizations } from "metabase/visualizations/register";+import { registerVisualization } from "metabase/viz-core";+import Question from "metabase-lib/v1/Question";+import type { VisualizationSettings } from "metabase-types/api";+import {+ createMockCard,+ createMockSingleSeries,+} from "metabase-types/api/mocks";+import { createSampleDatabase } from "metabase-types/api/mocks/presets";++import { getQuestionWithDefaultVisualizationSettings } from "./viz-settings";++registerVisualizations();++const PREFIX = "custom:demo-viz:";+const METADATA = createMockMetadata({ databases: [createSampleDatabase()] });++function setup(visualization_settings: VisualizationSettings) {+ const card = createMockCard({+ display: "custom:demo-viz",+ visualization_settings,+ });+ const question = new Question(card, METADATA);+ const series = [createMockSingleSeries(card)];++ return { question, series };+}++describe("getQuestionWithDefaultVisualizationSettings", () => {+ beforeAll(() => {+ registerVisualization({+ identifier: "custom:demo-viz",+ getUiName: () => "Demo viz",+ checkRenderable: () => undefined,+ settings: {+ [`${PREFIX}threshold`]: {+ widget: "number",+ persistDefault: true,+ getDefault: () => 0,+ },+ [`${PREFIX}label`]: {+ widget: "input",+ persistDefault: true,+ getDefault: () => "Label",+ },+ },+ });+ });++ it("leaves a question alone when its legacy keys already hold every persistable default", () => {+ const { question, series } = setup({ threshold: 5, label: "Mine" });++ expect(getQuestionWithDefaultVisualizationSettings(question, series)).toBe(+ question,+ );+ });++ it("writes a missing persistable default under its namespaced key and adopts the legacy keys", () => {+ const { question, series } = setup({ threshold: 5 });++ const result = getQuestionWithDefaultVisualizationSettings(+ question,+ series,+ );++ expect(result.settings()).toEqual({+ [`${PREFIX}threshold`]: 5,+ [`${PREFIX}label`]: "Label",+ });+ });+});diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/hooks.ts b/frontend/src/metabase/visualizations/components/ChartSettings/hooks.tsindex fd8ced90b24..25d3ac9f0d6 100644--- a/frontend/src/metabase/visualizations/components/ChartSettings/hooks.ts+++ b/frontend/src/metabase/visualizations/components/ChartSettings/hooks.ts@@ -8,6 +8,8 @@ import {type Widget,extractRemappings,getSettingsWidgetsForSeries,+ getStoredSettingsForSeries,+ getVisualizationRaw,getVisualizationTransformed,updateSettings,} from "metabase/viz-core";@@ -18,6 +20,7 @@ import type {TransformedSeries,VisualizationSettings,} from "metabase-types/api";+import { isCustomVizDisplay } from "metabase-types/guards";export type UseChartSettingsStateProps = {settings?: VisualizationSettings;@@ -43,10 +46,20 @@ export const useChartSettingsState = ({series,onChange,}: UseChartSettingsStateProps): UseChartSettingsStateReturned => {- const chartSettings = useMemo(- () => settings || series[0].card.visualization_settings,- [series, settings],- );+ const display = series[0].card.display;+ const visualization = getVisualizationRaw(series);+ const chartSettings = useMemo(() => {+ if (settings) {+ return settings;+ }++ if (!isCustomVizDisplay(display) || !visualization) {+ return series[0].card.visualization_settings;+ }++ // Only custom viz needs the stored-settings migration.+ return getStoredSettingsForSeries(series);+ }, [series, settings, display, visualization]);const handleChangeSettings = useCallback((changedSettings: VisualizationSettings, question?: Question) => {diff --git a/frontend/src/metabase/visualizations/components/ChartSettings/hooks.unit.spec.ts b/frontend/src/metabase/visualizations/components/ChartSettings/hooks.unit.spec.tsnew file mode 100644index 00000000000..923f6d5b445--- /dev/null+++ b/frontend/src/metabase/visualizations/components/ChartSettings/hooks.unit.spec.ts@@ -0,0 +1,147 @@+import { renderHook } from "@testing-library/react";++import { registerVisualizations } from "metabase/visualizations/register";+import { registerVisualization } from "metabase/viz-core";+import type { Series, VisualizationSettings } from "metabase-types/api";+import { createMockSingleSeries } from "metabase-types/api/mocks";++import { useChartSettingsState } from "./hooks";++registerVisualizations();++const PREFIX = "custom:demo-viz:";++interface SetupOpts {+ series: Series;+ settings?: VisualizationSettings;+}++const setup = ({ series, settings }: SetupOpts) => {+ const onChange = jest.fn();++ const { result } = renderHook(() =>+ useChartSettingsState({ series, settings, onChange }),+ );++ return { result, onChange };+};++describe("useChartSettingsState", () => {+ beforeAll(() => {+ registerVisualization({+ identifier: "custom:demo-viz",+ getUiName: () => "Demo viz",+ checkRenderable: () => undefined,+ settings: {+ [`${PREFIX}threshold`]: { widget: "number" },+ },+ });+ });++ it("uses the settings prop when given", () => {+ const series = [+ createMockSingleSeries({ visualization_settings: { threshold: 5 } }),+ ];+ const settings = { "graph.goal_value": 2 };++ const { result } = setup({ series, settings });++ expect(result.current.chartSettings).toBe(settings);+ });++ it("falls back to the card's stored settings", () => {+ const series = [+ createMockSingleSeries({+ display: "table",+ visualization_settings: { "graph.goal_value": 1 },+ }),+ ];++ const { result } = setup({ series });++ expect(result.current.chartSettings).toBe(+ series[0].card.visualization_settings,+ );+ });++ it("keeps a non-custom display's stored settings untouched (no renormalization)", () => {+ const series = [+ createMockSingleSeries({+ display: "table",+ visualization_settings: {+ column_settings: {+ '["ref",["field",1,null]]': { column_title: "One" },+ },+ },+ }),+ ];++ const { result } = setup({ series });++ expect(result.current.chartSettings).toBe(+ series[0].card.visualization_settings,+ );+ });++ it("reads a legacy non-namespaced custom viz key under its namespaced key", () => {+ const series = [+ createMockSingleSeries({+ display: "custom:demo-viz",+ visualization_settings: { threshold: 5 },+ }),+ ];++ const { result } = setup({ series });++ expect(result.current.chartSettings).toEqual({+ [`${PREFIX}threshold`]: 5,+ });+ });++ it("writes from the normalized settings, so the first edit drops a legacy non-namespaced custom viz key", () => {+ const series = [+ createMockSingleSeries({+ display: "custom:demo-viz",+ visualization_settings: { threshold: 5 },+ }),+ ];++ const { result, onChange } = setup({ series });+ result.current.handleChangeSettings({ "card.title": "Title" });++ expect(onChange).toHaveBeenCalledWith(+ { [`${PREFIX}threshold`]: 5, "card.title": "Title" },+ undefined,+ );+ });++ it("re-runs the migration once the plugin registers after the first render", () => {+ const series = [+ createMockSingleSeries({+ display: "custom:late-viz",+ visualization_settings: { threshold: 5 },+ }),+ ];++ const { result, rerender } = renderHook(() =>+ useChartSettingsState({ series, onChange: jest.fn() }),+ );++ expect(result.current.chartSettings).toEqual({ threshold: 5 });++ registerVisualization({+ identifier: "custom:late-viz",+ getUiName: () => "Late viz",+ checkRenderable: () => undefined,+ settings: {+ "custom:late-viz:threshold": { widget: "number" },+ },+ });++ rerender();++ expect(result.current.chartSettings).toEqual({+ "custom:late-viz:threshold": 5,+ });+ });+});diff --git a/frontend/src/metabase/visualizations/components/ChartSettingsWidget.tsx b/frontend/src/metabase/visualizations/components/ChartSettingsWidget.tsxindex 363929a6ad6..ee0d49646a7 100644--- a/frontend/src/metabase/visualizations/components/ChartSettingsWidget.tsx+++ b/frontend/src/metabase/visualizations/components/ChartSettingsWidget.tsx@@ -4,7 +4,9 @@ import type { CSSProperties, ComponentType } from "react";import FormS from "metabase/css/components/form.module.css";import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";import { Box, Group, Icon, Text, Tooltip } from "metabase/ui";-import type { WidgetMount } from "metabase-types/api";+import { checkNotNull } from "metabase/utils/types";+import type { CustomVizSettingWidgetProps } from "metabase/viz-core";+import type { VisualizationSettings, WidgetMount } from "metabase-types/api";import S from "./ChartSettingsWidget.module.css";@@ -15,12 +17,18 @@ type Props = {description?: string;hint?: string;hidden?: boolean;- widget?: string | ComponentType<{ id: string }> | WidgetMount;+ widget?:+ | string+ | ComponentType<{ id: string }>+ | WidgetMount<CustomVizSettingWidgetProps>;inline?: boolean;props?: Record<string, unknown>;variant?: ChartSettingsWidgetVariant;dataTestId?: string;id: string;+ value?: unknown;+ onChange?: (value?: unknown) => void;+ onChangeSettings?: (settings: Partial<VisualizationSettings>) => void;style?: CSSProperties;};@@ -80,7 +88,13 @@ const ChartSettingsWidget = ({(PLUGIN_CUSTOM_VIZ.isWidgetMount(Widget) ? (<PLUGIN_CUSTOM_VIZ.CustomVizSettingWidgetmount={Widget}- widgetProps={{ ...extraWidgetProps, ...props }}+ widgetProps={{+ ...props, // spread first so a plugin's getProps can't override the base props+ id: extraWidgetProps.id,+ value: extraWidgetProps.value,+ onChange: checkNotNull(extraWidgetProps.onChange),+ onChangeSettings: checkNotNull(extraWidgetProps.onChangeSettings),+ }}/>) : (<Widget {...extraWidgetProps} {...props} />diff --git a/frontend/src/metabase/visualizations/components/ChartSettingsWidget.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ChartSettingsWidget.unit.spec.tsxnew file mode 100644index 00000000000..3a9c62f429d--- /dev/null+++ b/frontend/src/metabase/visualizations/components/ChartSettingsWidget.unit.spec.tsx@@ -0,0 +1,114 @@+import type { WidgetMount } from "custom-viz";+import type { ComponentProps } from "react";++import { renderWithProviders } from "__support__/ui";+import { PLUGIN_CUSTOM_VIZ } from "metabase/plugins";+import type { CustomVizSettingWidgetProps } from "metabase/viz-core";++import ChartSettingsWidget from "./ChartSettingsWidget";++type Props = ComponentProps<typeof ChartSettingsWidget> & {+ question: object;+ onChangeSeriesColor: () => void;+ onShowWidget: () => void;+};++interface SetupOpts {+ props: Props;+}++const { isWidgetMount, CustomVizSettingWidget } = PLUGIN_CUSTOM_VIZ;++const setup = ({ props }: SetupOpts) => {+ let mountedProps: CustomVizSettingWidgetProps | undefined;+ function RecordingWidget({+ widgetProps,+ }: {+ widgetProps: CustomVizSettingWidgetProps;+ }) {+ mountedProps = widgetProps;+ return null;+ }+ PLUGIN_CUSTOM_VIZ.isWidgetMount = (+ value,+ ): value is WidgetMount<CustomVizSettingWidgetProps> =>+ typeof value === "function";++ PLUGIN_CUSTOM_VIZ.CustomVizSettingWidget = RecordingWidget;++ renderWithProviders(<ChartSettingsWidget {...props} />);++ return { mountedProps };+};++describe("ChartSettingsWidget", () => {+ afterEach(() => {+ PLUGIN_CUSTOM_VIZ.isWidgetMount = isWidgetMount;+ PLUGIN_CUSTOM_VIZ.CustomVizSettingWidget = CustomVizSettingWidget;+ });++ it("hands a custom viz widget only its documented props", () => {+ const mount: WidgetMount = () => ({+ update: () => undefined,+ unmount: () => undefined,+ });+ const onChange = jest.fn();+ const onChangeSettings = jest.fn();+ const { mountedProps } = setup({+ props: {+ id: "threshold",+ question: {},+ props: { placeholder: "Set threshold" },+ title: "Threshold",+ value: 1,+ widget: mount,+ onChange,+ onChangeSettings,+ onChangeSeriesColor: jest.fn(),+ onShowWidget: jest.fn(),+ },+ });++ expect(mountedProps).toEqual({+ id: "threshold",+ placeholder: "Set threshold",+ value: 1,+ onChange,+ onChangeSettings,+ });+ });++ it("keeps the base props ahead of whatever getProps adds", () => {+ const mount: WidgetMount = () => ({+ update: () => undefined,+ unmount: () => undefined,+ });+ const onChange = jest.fn();+ const onChangeSettings = jest.fn();+ const { mountedProps } = setup({+ props: {+ id: "threshold",+ question: {},+ props: {+ id: "forged",+ value: 2,+ onChange: jest.fn(),+ onChangeSettings: jest.fn(),+ },+ value: 1,+ widget: mount,+ onChange,+ onChangeSettings,+ onChangeSeriesColor: jest.fn(),+ onShowWidget: jest.fn(),+ },+ });++ expect(mountedProps).toEqual({+ id: "threshold",+ value: 1,+ onChange,+ onChangeSettings,+ });+ });+});diff --git a/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.ts b/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.tsindex 724a0462dc6..b2066003cf2 100644--- a/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.ts+++ b/frontend/src/metabase/visualizations/custom-visualizations/custom-viz-utils.ts@@ -2,9 +2,9 @@ import { getSubpathSafeUrl } from "metabase/urls";import { formatValue as internalFormatValue } from "metabase/value-formatting";import type {ColumnSettings,+ CustomVizDisplayType,CustomVizPluginId,CustomVizPluginRuntime,- VisualizationDisplay,} from "metabase-types/api";export function formatValue(value: unknown, options?: ColumnSettings): string {@@ -42,7 +42,7 @@ export function resolveCustomVizAssetUrl(export function getCustomPluginIdentifier(pluginOrIdentifier: Pick<CustomVizPluginRuntime, "identifier"> | string,-): VisualizationDisplay {+): CustomVizDisplayType {const identifier =typeof pluginOrIdentifier === "string"? pluginOrIdentifierdiff --git a/frontend/src/metabase/visualizations/tests/computed-settings-for-series.unit.spec.ts b/frontend/src/metabase/visualizations/tests/computed-settings-for-series.unit.spec.tsindex 8145c16e9a4..4405e05602c 100644--- a/frontend/src/metabase/visualizations/tests/computed-settings-for-series.unit.spec.ts+++ b/frontend/src/metabase/visualizations/tests/computed-settings-for-series.unit.spec.ts@@ -9,6 +9,7 @@ import { registerVisualizations } from "metabase/visualizations/register";import {getComputedSettingsForSeries,getStoredSettingsForSeries,+ registerVisualization,} from "metabase/viz-core";import type {Series,@@ -389,3 +390,116 @@ const cardWithTimeseriesBreakoutAndTwoMetrics = ({},),];++describe("getStoredSettingsForSeries", () => {+ describe("custom viz settings saved before namespacing", () => {+ const PREFIX = "custom:demo-viz:";++ beforeAll(() => {+ registerVisualization({+ identifier: "custom:demo-viz",+ getUiName: () => "Demo viz",+ checkRenderable: () => undefined,+ settings: {+ [`${PREFIX}threshold`]: { widget: "number" },+ [`${PREFIX}card.title`]: { widget: "input" },+ [`${PREFIX}graph.goal_value`]: { widget: "number" },+ [`${PREFIX}goal.color`]: { widget: "color" },+ [`${PREFIX}series_settings`]: { widget: "input" },+ [`${PREFIX}virtual_card`]: { widget: "input" },+ [`${PREFIX}toString`]: { widget: "input" },+ },+ });+ });++ function customVizSeries(+ visualization_settings: VisualizationSettings,+ ): Series {+ return [+ createMockSingleSeries({+ display: "custom:demo-viz",+ visualization_settings,+ }),+ ];+ }++ it("reads a bare plugin setting under its namespaced key", () => {+ expect(+ getStoredSettingsForSeries(customVizSeries({ threshold: 5 })),+ ).toEqual({ [`${PREFIX}threshold`]: 5 });+ });++ it("prefers the namespaced key when both are stored", () => {+ expect(+ getStoredSettingsForSeries(+ customVizSeries({ threshold: 5, [`${PREFIX}threshold`]: 7 }),+ ),+ ).toEqual({ [`${PREFIX}threshold`]: 7 });+ });++ it("leaves a host setting alone even when the plugin declares the same id", () => {+ expect(+ getStoredSettingsForSeries(customVizSeries({ "card.title": "Title" })),+ ).toEqual({ "card.title": "Title" });+ });++ it("never adopts or erases a host setting the plugin declares an id for", () => {+ const series = customVizSeries({ "graph.goal_value": 100 });++ expect(getStoredSettingsForSeries(series)).toEqual({+ "graph.goal_value": 100,+ });+ });++ it("adopts a dotted plugin id that names no host setting", () => {+ expect(+ getStoredSettingsForSeries(customVizSeries({ "goal.color": "red" })),+ ).toEqual({ [`${PREFIX}goal.color`]: "red" });+ });++ it("leaves a host setting registered by another display alone", () => {+ const series = customVizSeries({+ series_settings: { x: { title: "X" } },+ });++ expect(getStoredSettingsForSeries(series)).toEqual({+ series_settings: { x: { title: "X" } },+ });+ });++ it("leaves a stored key with no settings definition alone", () => {+ const series = customVizSeries({ virtual_card: { display: "text" } });++ expect(getStoredSettingsForSeries(series)).toEqual({+ virtual_card: { display: "text" },+ });+ });++ it("adopts a plugin id that shadows an Object.prototype member", () => {+ expect(+ getStoredSettingsForSeries(customVizSeries({ toString: "custom" })),+ ).toEqual({ [`${PREFIX}toString`]: "custom" });+ });++ it("returns the stored settings as is when there is nothing to adopt", () => {+ const series = customVizSeries({ [`${PREFIX}threshold`]: 7 });++ expect(getStoredSettingsForSeries(series)).toBe(+ series[0].card.visualization_settings,+ );+ });++ it("ignores bare plugin ids on other displays", () => {+ const series: Series = [+ createMockSingleSeries({+ display: "table",+ visualization_settings: { threshold: 5 },+ }),+ ];++ expect(getStoredSettingsForSeries(series)).toBe(+ series[0].card.visualization_settings,+ );+ });+ });+});diff --git a/frontend/src/metabase/visualizations/tests/dashcard-settings-merging.unit.spec.ts b/frontend/src/metabase/visualizations/tests/dashcard-settings-merging.unit.spec.tsindex f68c5ac91d2..6aacffc8a30 100644--- a/frontend/src/metabase/visualizations/tests/dashcard-settings-merging.unit.spec.ts+++ b/frontend/src/metabase/visualizations/tests/dashcard-settings-merging.unit.spec.ts@@ -219,6 +219,66 @@ describe("extendCardWithDashcardSettings", () => {"graph.goal_label": "goal label",});});++ describe("custom viz settings saved before namespacing", () => {+ const PREFIX = "custom:demo-viz:";++ it("keeps a dashcard override over the card's namespaced value", () => {+ const card = createMockCard({+ display: "custom:demo-viz",+ visualization_settings: { [`${PREFIX}threshold`]: 42 },+ });++ const result = extendCardWithDashcardSettings(card, { threshold: 10 });++ expect(result.visualization_settings).toEqual({+ [`${PREFIX}threshold`]: 10,+ });+ });++ it("prefers the dashcard's namespaced value over its stale bare one", () => {+ const card = createMockCard({+ display: "custom:demo-viz",+ visualization_settings: { [`${PREFIX}threshold`]: 42 },+ });++ const result = extendCardWithDashcardSettings(card, {+ threshold: 10,+ [`${PREFIX}threshold`]: 11,+ });++ expect(result.visualization_settings).toEqual({+ [`${PREFIX}threshold`]: 11,+ });+ });++ it("leaves a host setting the dashcard overrides alone", () => {+ const card = createMockCard({+ display: "custom:demo-viz",+ visualization_settings: { [`${PREFIX}card.title`]: "Plugin" },+ });++ const result = extendCardWithDashcardSettings(card, {+ "card.title": "Dashcard",+ });++ expect(result.visualization_settings).toEqual({+ [`${PREFIX}card.title`]: "Plugin",+ "card.title": "Dashcard",+ });+ });++ it("leaves a bare key the card doesn't namespace to the stored-settings migration", () => {+ const card = createMockCard({+ display: "custom:demo-viz",+ visualization_settings: {},+ });++ const result = extendCardWithDashcardSettings(card, { threshold: 10 });++ expect(result.visualization_settings).toEqual({ threshold: 10 });+ });+ });});describe("sanitizeDashcardSettings", () => {diff --git a/frontend/src/metabase/viz-core/index.ts b/frontend/src/metabase/viz-core/index.tsindex 0c186cc31ab..54169219d72 100644--- a/frontend/src/metabase/viz-core/index.ts+++ b/frontend/src/metabase/viz-core/index.ts@@ -219,6 +219,10 @@ export {} from "./lib/choropleth";export { withColorName } from "./lib/color-name";export { getColorScale } from "./lib/color-scales";+export {+ getCustomVizSettingKeyPrefix,+ isCustomVizSettingKey,+} from "./lib/custom-viz/setting-keys";export { groupRawSeriesMetrics, sumMetric } from "./lib/dataset";export {ChartSettingsError,@@ -355,6 +359,7 @@ export {validateStacking,} from "./lib/settings/validation";export {+ adoptLegacyCustomVizSettings,getComputedSettingsForSeries,getPersistableDefaultSettingsForSeries,getStoredSettingsForSeries,@@ -499,6 +504,7 @@ export type {ChartSettingTableColumnsProps,ChartSettingWidgetProps,ComparisonMenuOption,+ CustomVizSettingWidgetProps,DimensionsWidgetProps,EditWidgetData,SmartScalarComparisonWidgetProps,diff --git a/frontend/src/metabase/viz-core/lib/custom-viz/migrate-legacy-settings.ts b/frontend/src/metabase/viz-core/lib/custom-viz/migrate-legacy-settings.tsnew file mode 100644index 00000000000..ecbd87d009c--- /dev/null+++ b/frontend/src/metabase/viz-core/lib/custom-viz/migrate-legacy-settings.ts@@ -0,0 +1,117 @@+import type {+ VisualizationDisplay,+ VisualizationSettings,+} from "metabase-types/api";+import { isCustomVizDisplay } from "metabase-types/guards";++import type { VisualizationSettingsDefinitions } from "../../types";+import { visualizations } from "../registry";++import { getCustomVizSettingKeyPrefix } from "./setting-keys";++// Stored keys with no registered settings definition, or whose visualization+// is only registered by some bundles (e.g. registerDashboardVisualizations).+const EXTRA_HOST_SETTING_KEYS: ReadonlySet<string> = new Set([+ "virtual_card",+ "visualization",+ "iframe",+]);++/**+ * Custom viz settings used to be stored under the plugin's bare setting ids.+ * Now they live under `custom:<plugin>:<id>` keys.+ */+export function migrateStoredCustomVizSettings(+ display: VisualizationDisplay | undefined,+ storedSettings: VisualizationSettings,+ getDefinitions: () => VisualizationSettingsDefinitions,+): VisualizationSettings {+ if (!isCustomVizDisplay(display)) {+ return storedSettings;+ }++ const definitions = getDefinitions();++ return adoptLegacyKeys(storedSettings, {+ prefix: getCustomVizSettingKeyPrefix(display),+ namespacedKeys: Object.keys(definitions),+ isHostKey: getIsHostKey(definitions),+ });+}++/**+ * A dashcard override saved under a bare id has to keep overriding the card's+ * namespaced value once the two are merged, so it is namespaced first.+ */+export function migrateStoredDashcardCustomVizSettings(+ display: VisualizationDisplay | undefined,+ cardSettings: VisualizationSettings,+ dashcardSettings: VisualizationSettings,+ getDefinitions: () => VisualizationSettingsDefinitions,+): VisualizationSettings {+ if (!isCustomVizDisplay(display)) {+ return dashcardSettings;+ }++ return adoptLegacyKeys(dashcardSettings, {+ prefix: getCustomVizSettingKeyPrefix(display),+ namespacedKeys: Object.keys(cardSettings),+ isHostKey: getIsHostKey(getDefinitions()),+ });+}++function adoptLegacyKeys(+ storedSettings: VisualizationSettings,+ {+ prefix,+ namespacedKeys,+ isHostKey,+ }: {+ prefix: string;+ namespacedKeys: string[];+ isHostKey: (key: string) => boolean;+ },+): VisualizationSettings {+ const legacyKeys = namespacedKeys+ .filter((key) => key.startsWith(prefix))+ .map((key) => [key, key.slice(prefix.length)] as const)+ .filter(+ ([, legacyKey]) =>+ Object.hasOwn(storedSettings, legacyKey) && !isHostKey(legacyKey),+ );++ if (legacyKeys.length === 0) {+ return storedSettings;+ }++ const settings = { ...storedSettings };++ for (const [key, legacyKey] of legacyKeys) {+ if (typeof settings[key] === "undefined") {+ settings[key] = settings[legacyKey];+ }++ delete settings[legacyKey];+ }++ return settings;+}++function getIsHostKey(definitions: VisualizationSettingsDefinitions) {+ const hostSettingKeys = getHostSettingKeys();++ return (key: string) =>+ Object.hasOwn(definitions, key) || hostSettingKeys.has(key);+}++function getHostSettingKeys(): ReadonlySet<string> {+ const keys = new Set(EXTRA_HOST_SETTING_KEYS);++ for (const [, viz] of visualizations) {+ for (const key of Object.keys(viz.settings ?? {})) {+ keys.add(key);+ }+ }++ return keys;+}diff --git a/frontend/src/metabase/viz-core/lib/custom-viz/setting-keys.ts b/frontend/src/metabase/viz-core/lib/custom-viz/setting-keys.tsnew file mode 100644index 00000000000..37ed49ff350--- /dev/null+++ b/frontend/src/metabase/viz-core/lib/custom-viz/setting-keys.ts@@ -0,0 +1,18 @@+import type { CustomVizDisplayType } from "metabase-types/api";++const CUSTOM_VIZ_DISPLAY_PREFIX = "custom:";++// Plugin settings are stored under `custom:<plugin identifier>:<setting id>`+// so a plugin can never write an internal key.+export function getCustomVizSettingKeyPrefix(+ display: CustomVizDisplayType,+): string {+ return `${display}:`;+}++export function isCustomVizSettingKey(key: string): boolean {+ return (+ key.startsWith(CUSTOM_VIZ_DISPLAY_PREFIX) &&+ key.includes(":", CUSTOM_VIZ_DISPLAY_PREFIX.length)+ );+}diff --git a/frontend/src/metabase/viz-core/lib/custom-viz/setting-keys.unit.spec.ts b/frontend/src/metabase/viz-core/lib/custom-viz/setting-keys.unit.spec.tsnew file mode 100644index 00000000000..765a122f23b--- /dev/null+++ b/frontend/src/metabase/viz-core/lib/custom-viz/setting-keys.unit.spec.ts@@ -0,0 +1,21 @@+import {+ getCustomVizSettingKeyPrefix,+ isCustomVizSettingKey,+} from "./setting-keys";++describe("getCustomVizSettingKeyPrefix", () => {+ it("namespaces keys by the plugin identifier", () => {+ expect(getCustomVizSettingKeyPrefix("custom:demo-viz")).toBe(+ "custom:demo-viz:",+ );+ });+});++describe("isCustomVizSettingKey", () => {+ it("recognizes keys of any plugin", () => {+ expect(isCustomVizSettingKey("custom:demo-viz:threshold")).toBe(true);+ expect(isCustomVizSettingKey("custom:other:threshold")).toBe(true);+ expect(isCustomVizSettingKey("threshold")).toBe(false);+ expect(isCustomVizSettingKey("custom:demo-viz")).toBe(false);+ });+});diff --git a/frontend/src/metabase/viz-core/lib/settings/typed-utils.ts b/frontend/src/metabase/viz-core/lib/settings/typed-utils.tsindex 9474268b87d..695a2eb0063 100644--- a/frontend/src/metabase/viz-core/lib/settings/typed-utils.ts+++ b/frontend/src/metabase/viz-core/lib/settings/typed-utils.ts@@ -12,8 +12,11 @@ import type {VisualizationSettingDefinition,VisualizationSettingsDefinitions,} from "../../types";+import { migrateStoredDashcardCustomVizSettings } from "../custom-viz/migrate-legacy-settings";import { getVisualization } from "../registry";+import { getSettingDefinitionsForDisplay } from "./visualization";+// Merge two settings objects together.// Settings from the second argument take precedence over the first.export function mergeSettings(@@ -93,11 +96,18 @@ export function extendCardWithDashcardSettings<return isSettingHiddenOnDashboards(settings[key] ?? {});});+ const cardSettings = card.visualization_settings ?? {};+return {...card,visualization_settings: mergeSettings(- card?.visualization_settings,- _.omit(dashcardSettings, settingsToOmit),+ cardSettings,+ migrateStoredDashcardCustomVizSettings(+ card.display,+ cardSettings,+ _.omit(dashcardSettings ?? {}, settingsToOmit),+ () => getSettingDefinitionsForDisplay(card.display),+ ),),};}diff --git a/frontend/src/metabase/viz-core/lib/settings/visualization.ts b/frontend/src/metabase/viz-core/lib/settings/visualization.tsindex e2a89d05dae..cb4d2a21a12 100644--- a/frontend/src/metabase/viz-core/lib/settings/visualization.ts+++ b/frontend/src/metabase/viz-core/lib/settings/visualization.ts@@ -6,6 +6,7 @@ import type {ColumnSettings,DimensionReference,Series,+ VisualizationDisplay,VisualizationSettings,} from "metabase-types/api";@@ -14,7 +15,8 @@ import type {SettingsExtra,VisualizationSettingsDefinitions,} from "../../types";-import { getVisualizationRaw } from "../registry";+import { migrateStoredCustomVizSettings } from "../custom-viz/migrate-legacy-settings";+import { getVisualization } from "../registry";import {getComputedSettings,getPersistableDefaultSettings,@@ -60,16 +62,13 @@ const COMMON_SETTINGS: VisualizationSettingsDefinitions = {click_behavior: {},};-export function getSettingDefinitionsForSeries(- series: Series | null | undefined,+export function getSettingDefinitionsForDisplay(+ display: VisualizationDisplay | undefined,): VisualizationSettingsDefinitions {- if (!series) {- return {};- }- const visualization = getVisualizationRaw(series);+ const visualization = getVisualization(display ?? null);const definitions = {...COMMON_SETTINGS,- ...(visualization?.settings || {}),+ ...visualization?.settings,};for (const id in definitions) {definitions[id].id = id;@@ -77,6 +76,15 @@ export function getSettingDefinitionsForSeries(return definitions;}+export function getSettingDefinitionsForSeries(+ series: Series | null | undefined,+): VisualizationSettingsDefinitions {+ if (!series) {+ return {};+ }+ return getSettingDefinitionsForDisplay(series[0]?.card?.display);+}+function normalizeColumnSettings(columnSettings: Record<string, ColumnSettings>,): Record<string, ColumnSettings> {@@ -94,8 +102,10 @@ function normalizeColumnSettings(export function getStoredSettingsForSeries(series: Series | null | undefined,+ definitions?: VisualizationSettingsDefinitions,): VisualizationSettings {let storedSettings = series?.[0]?.card?.visualization_settings ?? {};+if (storedSettings.column_settings) {// normalize any settings stored under old style keys: [ref, [fk->, 1, 2]]storedSettings = assocIn(@@ -104,7 +114,21 @@ export function getStoredSettingsForSeries(normalizeColumnSettings(storedSettings.column_settings),);}- return storedSettings;++ return migrateStoredCustomVizSettings(+ series?.[0]?.card?.display,+ storedSettings,+ () => definitions ?? getSettingDefinitionsForSeries(series),+ );+}++export function adoptLegacyCustomVizSettings(+ display: VisualizationDisplay | undefined,+ storedSettings: VisualizationSettings,+): VisualizationSettings {+ return migrateStoredCustomVizSettings(display, storedSettings, () => {+ return getSettingDefinitionsForDisplay(display);+ });}export function getComputedSettingsForSeries(@@ -116,7 +140,7 @@ export function getComputedSettingsForSeries(}const settingsDefs = getSettingDefinitionsForSeries(series);- const storedSettings = getStoredSettingsForSeries(series);+ const storedSettings = getStoredSettingsForSeries(series, settingsDefs);return getComputedSettings(settingsDefs, series, storedSettings, extra);}diff --git a/frontend/src/metabase/viz-core/lib/widgets.ts b/frontend/src/metabase/viz-core/lib/widgets.tsindex 908216fa32a..200ba38c339 100644--- a/frontend/src/metabase/viz-core/lib/widgets.ts+++ b/frontend/src/metabase/viz-core/lib/widgets.ts@@ -131,7 +131,7 @@ export function getSettingsWidgetsForSeries(extra: SettingsExtra = {},) {const settingsDefs = getSettingDefinitionsForSeries(series);- const storedSettings = getStoredSettingsForSeries(series);+ const storedSettings = getStoredSettingsForSeries(series, settingsDefs);const computedSettings = getComputedSettingsForSeries(series);return getSettingsWidgets(diff --git a/frontend/src/metabase/viz-core/types/definition.ts b/frontend/src/metabase/viz-core/types/definition.tsindex e68d132f5c8..095d6ae19b2 100644--- a/frontend/src/metabase/viz-core/types/definition.ts+++ b/frontend/src/metabase/viz-core/types/definition.ts@@ -12,6 +12,7 @@ import type {SingleSeries,TransformedSeries,VisualizationSettings,+ WidgetMount,} from "metabase-types/api";import type { VisualizationDisplay } from "metabase-types/api/visualization";@@ -24,6 +25,7 @@ import type {ChartSettingSegmentsEditorProps,ChartSettingSeriesOrderProps,ChartSettingTableColumnsProps,+ CustomVizSettingWidgetProps,DimensionsWidgetProps,SmartScalarComparisonWidgetProps,TreemapGroupsPickerProps,@@ -68,7 +70,10 @@ export type VisualizationSettingDefinition<group?: string;index?: number;showColumnSetting?: boolean;- widget?: string | ComponentType<TProps & { id: string }>;+ widget?:+ | string+ | ComponentType<TProps & { id: string }>+ | WidgetMount<CustomVizSettingWidgetProps>;isValid?: (object: T,settings: T extends DatasetColumn@@ -103,7 +108,7 @@ export type VisualizationSettingDefinition<? ColumnSettings: ComputedVisualizationSettings,extra?: SettingsExtra,- ) => string;+ ) => string | undefined;getWrapperStyle?: (object: T,settings: T extends DatasetColumn@@ -368,7 +373,10 @@ export type Widget = {hidden?: boolean;props?: Record<string, unknown>;title?: string;- widget?: string | ComponentType<any>;+ widget?:+ | string+ | ComponentType<any>+ | WidgetMount<CustomVizSettingWidgetProps>;};export type VisualizationGridSize = {diff --git a/frontend/src/metabase/viz-core/types/widget-props.ts b/frontend/src/metabase/viz-core/types/widget-props.tsindex 3defb96a8a4..d0a4668f890 100644--- a/frontend/src/metabase/viz-core/types/widget-props.ts+++ b/frontend/src/metabase/viz-core/types/widget-props.ts@@ -24,6 +24,10 @@ export type ChartSettingWidgetProps<TValue> = {onChangeSettings: (settings: Partial<VisualizationSettings>) => void;};+export type CustomVizSettingWidgetProps = ChartSettingWidgetProps<unknown> & {+ id: string;+} & Record<string, unknown>;+export type ChartSettingEnumToggleProps<T extends string> = {value: T | undefined;onChange: (value: T) => void;diff --git a/frontend/test/jest-setup.js b/frontend/test/jest-setup.jsindex d68a36588d7..243ffe554be 100644--- a/frontend/test/jest-setup.js+++ b/frontend/test/jest-setup.js@@ -1,5 +1,6 @@import { webcrypto } from "crypto";import { TextDecoder, TextEncoder } from "util";+import { deserialize, serialize } from "v8";import { TextDecoderStream } from "@stardazed/streams-text-encoding";import {@@ -77,6 +78,11 @@ global.TransformStream = TransformStream;global.WritableStream = WritableStream;global.TextDecoderStream = TextDecoderStream;+// jsdom + Jest lacks structuredClone, which the app relies on in the browser.+// v8's serializer implements the structured-clone algorithm (Map, Date, BigInt, ...).+global.structuredClone =+ global.structuredClone || ((value) => deserialize(serialize(value)));+// https://github.com/jsdom/jsdom/issues/3002Range.prototype.getBoundingClientRect = () => ({bottom: 0,