Skip to content

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

static viz typing (#73193)

Aleksandr Lesnenko72ba6a81c111
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
index c3569966b50..02f7c715c5c 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
@@ -348,7 +348,7 @@ export function DashCardVisualization({
visualization_settings: settings,
} as Card,
_.omit(dashcard.visualization_settings, "visualization"),
- ) as Card;
+ );
if (!didEveryDatasetLoad) {
return [{ card }] as RawSeries;
diff --git a/frontend/src/metabase/static-viz/index.js b/frontend/src/metabase/static-viz/index.js
deleted file mode 100644
index db5f33aa416..00000000000
--- a/frontend/src/metabase/static-viz/index.js
+++ /dev/null
@@ -1,154 +0,0 @@
-import "./mock-environment";
-import "fast-text-encoding";
-
-import { setPlatformAPI } from "echarts/core";
-import ReactDOMServer from "react-dom/server";
-
-// eslint-disable-next-line import/order
-import enterpriseOverrides from "ee-overrides";
-import "metabase/utils/dayjs";
-
-import { StaticVisualization } from "metabase/static-viz/components/StaticVisualization";
-import { createStaticRenderingContext } from "metabase/static-viz/lib/rendering-context";
-import { measureTextEChartsAdapter } from "metabase/static-viz/lib/text";
-import { updateStartOfWeek } from "metabase/utils/i18n";
-import MetabaseSettings from "metabase/utils/settings";
-import { extractRemappings, isCartesianChart } from "metabase/visualizations";
-import { extendCardWithDashcardSettings } from "metabase/visualizations/lib/settings/typed-utils";
-import {
- createDataSource,
- getVisualizationColumns,
- mergeVisualizerData,
- shouldSplitVisualizerSeries,
- splitVisualizerSeries,
-} from "metabase/visualizer/utils";
-
-import { LegacyStaticChart } from "./containers/LegacyStaticChart";
-
-setPlatformAPI({
- measureText: measureTextEChartsAdapter,
-});
-
-/**
- * @deprecated use RenderChart instead
- */
-export function LegacyRenderChart(type, options) {
- return ReactDOMServer.renderToStaticMarkup(
- <LegacyStaticChart type={type} options={options} />,
- );
-}
-
-// Dashcard settings should be merged with the first card settings
-// Replicates the logic from frontend/src/metabase/dashboard/components/DashCard/DashCard.tsx
-function getRawSeriesWithDashcardSettings(rawSeries, dashcardSettings) {
- return rawSeries.map((series, index) => {
- const isMainCard = index === 0;
- if (isMainCard) {
- return {
- ...series,
- card: extendCardWithDashcardSettings(series.card, dashcardSettings),
- };
- }
- return series;
- });
-}
-
-function getVisualizerRawSeries(rawSeries, dashcardSettings) {
- const { columnValuesMapping } = dashcardSettings.visualization;
- const datasets = rawSeries.reduce((acc, series) => {
- if (series.card.id) {
- acc[`card:${series.card.id}`] = series;
- }
- return acc;
- }, {});
-
- const dataSources = rawSeries.map((series) =>
- createDataSource("card", series.card.id, series.card.name),
- );
-
- const columns = getVisualizationColumns(
- dashcardSettings.visualization,
- datasets,
- dataSources,
- );
-
- const mergedData = mergeVisualizerData({
- columns,
- columnValuesMapping,
- datasets,
- dataSources,
- });
-
- const { display, settings } = dashcardSettings.visualization;
- return [
- {
- card: {
- display,
- visualization_settings: settings,
- },
- data: mergedData,
- columnValuesMapping,
- },
- ];
-}
-
-export function RenderChart(rawSeries, dashcardSettings, options) {
- MetabaseSettings.set("token-features", options.tokenFeatures);
- MetabaseSettings.set("application-colors", options.applicationColors);
-
- if (typeof enterpriseOverrides === "function") {
- enterpriseOverrides();
- }
-
- MetabaseSettings.set("custom-formatting", options.customFormatting);
-
- const renderingContext = createStaticRenderingContext(
- options.applicationColors,
- );
-
- // If this is a visualizer card, we need to merge the data and split the series if needed
- if ("visualization" in dashcardSettings) {
- const dataSourceNameMap = Object.fromEntries(
- rawSeries.map((series) => {
- const source = createDataSource(
- "card",
- series.card.id,
- series.card.name,
- );
- return [source.id, source.name];
- }),
- );
- rawSeries = getVisualizerRawSeries(rawSeries, dashcardSettings);
- const { display, columnValuesMapping } = dashcardSettings.visualization;
- if (
- display &&
- isCartesianChart(display) &&
- shouldSplitVisualizerSeries(columnValuesMapping)
- ) {
- rawSeries = splitVisualizerSeries(
- rawSeries,
- columnValuesMapping,
- dataSourceNameMap,
- );
- }
- }
-
- updateStartOfWeek(options.startOfWeek);
- const rawSeriesWithDashcardSettings = getRawSeriesWithDashcardSettings(
- rawSeries,
- dashcardSettings,
- );
- const rawSeriesWithRemappings = extractRemappings(
- rawSeriesWithDashcardSettings,
- );
-
- const hasDevWatermark = Boolean(options.tokenFeatures?.development_mode);
-
- return ReactDOMServer.renderToStaticMarkup(
- <StaticVisualization
- rawSeries={rawSeriesWithRemappings}
- renderingContext={renderingContext}
- hasDevWatermark={hasDevWatermark}
- />,
- );
-}
diff --git a/frontend/src/metabase/static-viz/index.tsx b/frontend/src/metabase/static-viz/index.tsx
new file mode 100644
index 00000000000..fc7903370b5
--- /dev/null
+++ b/frontend/src/metabase/static-viz/index.tsx
@@ -0,0 +1,184 @@
+import "./mock-environment";
+import "fast-text-encoding";
+
+import { setPlatformAPI } from "echarts/core";
+import ReactDOMServer from "react-dom/server";
+
+// eslint-disable-next-line import/order
+import enterpriseOverrides from "ee-overrides";
+import "metabase/utils/dayjs";
+
+import { StaticVisualization } from "metabase/static-viz/components/StaticVisualization";
+import { LegacyStaticChart } from "metabase/static-viz/containers/LegacyStaticChart";
+import type { LegacyStaticChartType } from "metabase/static-viz/containers/LegacyStaticChart/LegacyStaticChart";
+import { createStaticRenderingContext } from "metabase/static-viz/lib/rendering-context";
+import { measureTextEChartsAdapter } from "metabase/static-viz/lib/text";
+import type { ColorPalette } from "metabase/ui/colors/types";
+import { updateStartOfWeek } from "metabase/utils/i18n";
+import MetabaseSettings from "metabase/utils/settings";
+import { extractRemappings, isCartesianChart } from "metabase/visualizations";
+import { extendCardWithDashcardSettings } from "metabase/visualizations/lib/settings/typed-utils";
+import {
+ createDataSource,
+ getVisualizationColumns,
+ mergeVisualizerData,
+ shouldSplitVisualizerSeries,
+ splitVisualizerSeries,
+} from "metabase/visualizer/utils";
+import type {
+ Card,
+ DashCardVisualizationSettings,
+ Dataset,
+ DatasetData,
+ DayOfWeekId,
+ FormattingSettings,
+ RawSeries,
+ SettingKey,
+ TokenFeatures,
+ VisualizerDataSourceId,
+ VisualizerVizDefinition,
+} from "metabase-types/api";
+
+setPlatformAPI({
+ measureText: measureTextEChartsAdapter,
+});
+
+export type RenderChartOptions = {
+ tokenFeatures: TokenFeatures;
+ applicationColors: ColorPalette;
+ customFormatting: FormattingSettings;
+ startOfWeek: DayOfWeekId | null | undefined;
+};
+
+type RenderChartDashcardSettings = DashCardVisualizationSettings & {
+ visualization?: VisualizerVizDefinition;
+};
+
+/**
+ * @deprecated use RenderChart instead
+ */
+export function LegacyRenderChart(
+ type: LegacyStaticChartType,
+ options: unknown,
+) {
+ return ReactDOMServer.renderToStaticMarkup(
+ <LegacyStaticChart type={type} options={options} />,
+ );
+}
+
+function getRawSeriesWithDashcardSettings(
+ rawSeries: RawSeries,
+ dashcardSettings: DashCardVisualizationSettings,
+): RawSeries {
+ return rawSeries.map((series, index) => {
+ const isMainCard = index === 0;
+ if (isMainCard) {
+ return {
+ ...series,
+ card: extendCardWithDashcardSettings(series.card, dashcardSettings),
+ };
+ }
+ return series;
+ });
+}
+
+function getVisualizerRawSeries(
+ rawSeries: RawSeries,
+ visualization: VisualizerVizDefinition,
+ dataSources: ReturnType<typeof createDataSource>[],
+): RawSeries {
+ const { columnValuesMapping, display, settings } = visualization;
+
+ const datasets = Object.fromEntries(
+ rawSeries
+ .filter((series) => series.card.id)
+ .map((series) => [`card:${series.card.id}`, series]),
+ ) as unknown as Record<VisualizerDataSourceId, Dataset | null | undefined>;
+
+ const columns = getVisualizationColumns(visualization, datasets, dataSources);
+
+ return [
+ {
+ card: {
+ display,
+ visualization_settings: settings,
+ } as Card,
+ data: mergeVisualizerData({
+ columns,
+ columnValuesMapping,
+ datasets,
+ dataSources,
+ }) as DatasetData,
+ columnValuesMapping,
+ },
+ ];
+}
+
+export function RenderChart(
+ rawSeries: RawSeries,
+ dashcardSettings: RenderChartDashcardSettings,
+ options: RenderChartOptions,
+) {
+ MetabaseSettings.set("token-features", options.tokenFeatures);
+ MetabaseSettings.set(
+ "application-colors" as SettingKey,
+ options.applicationColors,
+ );
+
+ if (enterpriseOverrides) {
+ enterpriseOverrides();
+ }
+
+ MetabaseSettings.set("custom-formatting", options.customFormatting);
+
+ const renderingContext = createStaticRenderingContext(
+ options.applicationColors,
+ );
+
+ let seriesForRender = rawSeries;
+ if (dashcardSettings.visualization) {
+ const { visualization } = dashcardSettings;
+ const dataSources = rawSeries.map((series) =>
+ createDataSource("card", series.card.id, series.card.name),
+ );
+ seriesForRender = getVisualizerRawSeries(
+ rawSeries,
+ visualization,
+ dataSources,
+ );
+ const { display, columnValuesMapping } = visualization;
+ if (
+ display &&
+ isCartesianChart(display) &&
+ shouldSplitVisualizerSeries(columnValuesMapping)
+ ) {
+ const dataSourceNameMap = Object.fromEntries(
+ dataSources.map((source) => [source.id, source.name]),
+ );
+ seriesForRender = splitVisualizerSeries(
+ seriesForRender,
+ columnValuesMapping,
+ dataSourceNameMap,
+ );
+ }
+ }
+
+ updateStartOfWeek(options.startOfWeek);
+ const rawSeriesWithDashcardSettings = getRawSeriesWithDashcardSettings(
+ seriesForRender,
+ dashcardSettings,
+ );
+ const rawSeriesWithRemappings = extractRemappings(
+ rawSeriesWithDashcardSettings,
+ );
+
+ const hasDevWatermark = Boolean(options.tokenFeatures.development_mode);
+
+ return ReactDOMServer.renderToStaticMarkup(
+ <StaticVisualization
+ rawSeries={rawSeriesWithRemappings}
+ renderingContext={renderingContext}
+ hasDevWatermark={hasDevWatermark}
+ />,
+ );
+}
diff --git a/frontend/src/metabase/static-viz/lib/numbers.ts b/frontend/src/metabase/static-viz/lib/numbers.ts
index beb2d1b46d8..c9de21fbd04 100644
--- a/frontend/src/metabase/static-viz/lib/numbers.ts
+++ b/frontend/src/metabase/static-viz/lib/numbers.ts
@@ -1,13 +1,13 @@
import type { CurrencyStyle } from "metabase/utils/formatting";
import { formatNumber as appFormatNumber } from "metabase/utils/formatting/numbers";
-export type NumberStyle = "currency" | "decimal" | "scientific" | "percentage";
+export type NumberStyle = "currency" | "decimal" | "scientific" | "percent";
export type NumberFormatOptions = {
number_style?: NumberStyle;
currency?: string;
currency_style?: CurrencyStyle;
- number_separators?: ".,";
+ number_separators?: string;
decimals?: number;
scale?: number;
prefix?: string;
diff --git a/frontend/src/metabase/static-viz/lib/numbers.unit.spec.js b/frontend/src/metabase/static-viz/lib/numbers.unit.spec.ts
similarity index 100%
rename from frontend/src/metabase/static-viz/lib/numbers.unit.spec.js
rename to frontend/src/metabase/static-viz/lib/numbers.unit.spec.ts
diff --git a/frontend/src/metabase/static-viz/mock-environment.js b/frontend/src/metabase/static-viz/mock-environment.js
deleted file mode 100644
index 2f6267e3bca..00000000000
--- a/frontend/src/metabase/static-viz/mock-environment.js
+++ /dev/null
@@ -1,415 +0,0 @@
-/* eslint-disable no-prototype-builtins */
-import ResizeObserver from "resize-observer-polyfill";
-
-global.ResizeObserver = ResizeObserver;
-
-global.EventTarget = function () {
- this.listeners = {};
-};
-global.EventTarget.prototype.addEventListener = function () {};
-global.EventTarget.prototype.removeEventListener = function () {};
-global.EventTarget.prototype.dispatchEvent = function () {};
-
-global.window = new global.EventTarget();
-
-Object.assign(global.window, global);
-
-global.document = new global.EventTarget();
-Object.assign(global.document, {
- createElement: function (tagName) {
- return {
- tagName: tagName.toUpperCase(),
- style: {},
- children: [],
- appendChild: function (child) {
- this.children.push(child);
- },
- setAttribute: function (name, value) {
- this[name] = value;
- },
- getAttribute: function (name) {
- return this[name];
- },
- addEventListener: function () {},
- removeEventListener: function () {},
- innerHTML: "",
- };
- },
- createTextNode: function (text) {
- return { textContent: text };
- },
- getElementById: function () {
- return null;
- },
- getElementsByTagName: function () {
- return [];
- },
- querySelector: function () {
- return null;
- },
- querySelectorAll: function () {
- return [];
- },
- body: {
- appendChild: function () {},
- addEventListener: function () {},
- removeEventListener: function () {},
- style: {},
- },
- head: {
- appendChild: function () {},
- addEventListener: function () {},
- removeEventListener: function () {},
- style: {},
- },
- documentElement: {
- style: {},
- },
- addEventListener: function () {},
- removeEventListener: function () {},
- dispatchEvent: function () {},
- readyState: "complete",
- cookie: "",
-});
-global.window.document = global.document;
-
-global.Element = function (tagName) {
- EventTarget.call(this);
- this.tagName = tagName.toUpperCase();
- this.children = [];
- this.style = {};
- this.attributes = {};
-};
-Object.setPrototypeOf(global.Element.prototype, global.EventTarget.prototype);
-global.Element.prototype.appendChild = function (child) {
- this.children.push(child);
- return child;
-};
-global.Element.prototype.setAttribute = function (name, value) {
- this.attributes[name] = value;
-};
-global.Element.prototype.getAttribute = function (name) {
- return this.attributes[name];
-};
-Object.setPrototypeOf(global.Element.prototype, global.EventTarget.prototype);
-global.Element.prototype.appendChild = function (child) {
- this.children.push(child);
-};
-
-if (typeof globalThis === "undefined") {
- global.globalThis = global.window;
-}
-
-global.document = new EventTarget();
-Object.assign(global.document, {
- createElement: function (tagName) {
- return new global.Element(tagName);
- },
- createTextNode: function (text) {
- return { textContent: text };
- },
- getElementById: function () {
- return null;
- },
- getElementsByTagName: function () {
- return [];
- },
- querySelector: function () {
- return null;
- },
- querySelectorAll: function () {
- return [];
- },
- documentElement: new global.Element("html"),
- head: new global.Element("head"),
- body: new global.Element("body"),
- readyState: "complete",
- cookie: "",
-});
-
-global.navigator = {
- userAgent: "GraalJS",
- language: "en-US",
- languages: ["en-US", "en"],
- platform: "GraalJS",
- appName: "StaticViz",
- appVersion: "1.0",
- cookieEnabled: false,
- geolocation: {
- getCurrentPosition: function () {},
- watchPosition: function () {},
- clearWatch: function () {},
- },
- onLine: true,
- mediaDevices: {
- getUserMedia: function () {},
- },
-};
-
-const navigator = {
- userAgent: "GraalJS",
- platform: "GraalJS",
- language: "en-US",
- languages: ["en-US", "en"],
-};
-
-global.navigator = navigator;
-global.window.navigator = navigator;
-
-global.location = {
- href: "",
- protocol: "",
- host: "",
- hostname: "",
- port: "",
- pathname: "",
- search: "",
- hash: "",
- origin: "",
- reload: function () {},
- replace: function () {},
- assign: function () {},
-};
-
-global.history = {
- length: 0,
- state: null,
- back: function () {},
- forward: function () {},
- go: function () {},
- pushState: function () {},
- replaceState: function () {},
-};
-
-global.screen = {
- width: 0,
- height: 0,
- availWidth: 0,
- availHeight: 0,
- colorDepth: 24,
- pixelDepth: 24,
-};
-
-global.setTimeout = function () {
- return 0;
-};
-global.clearTimeout = function () {};
-global.setInterval = function () {
- return 0;
-};
-global.clearInterval = function () {};
-
-global.requestAnimationFrame = function () {};
-global.cancelAnimationFrame = function () {};
-
-global.Event = function (type) {
- return {
- type: type,
- bubbles: false,
- cancelable: false,
- composed: false,
- target: null,
- currentTarget: null,
- eventPhase: 0,
- stopPropagation: function () {},
- stopImmediatePropagation: function () {},
- preventDefault: function () {},
- isTrusted: false,
- timeStamp: Date.now(),
- };
-};
-
-global.CustomEvent = function (type) {
- return new global.Event(type);
-};
-
-global.EventTarget = function () {
- this.listeners = {};
-};
-global.EventTarget.prototype.addEventListener = function () {};
-global.EventTarget.prototype.removeEventListener = function () {};
-global.EventTarget.prototype.dispatchEvent = function () {};
-
-global.localStorage = {
- _data: {},
- setItem: function (key, value) {
- this._data[key] = String(value);
- },
- getItem: function (key) {
- return this._data.hasOwnProperty(key) ? this._data[key] : null;
- },
- removeItem: function (key) {
- delete this._data[key];
- },
- clear: function () {
- this._data = {};
- },
- key: function (index) {
- return Object.keys(this._data)[index] || null;
- },
- get length() {
- return Object.keys(this._data).length;
- },
-};
-
-global.sessionStorage = {
- _data: {},
- setItem: function (key, value) {
- this._data[key] = String(value);
- },
- getItem: function (key) {
- return this._data.hasOwnProperty(key) ? this._data[key] : null;
- },
- removeItem: function (key) {
- delete this._data[key];
- },
- clear: function () {
- this._data = {};
- },
- key: function (index) {
- return Object.keys(this._data)[index] || null;
- },
- get length() {
- return Object.keys(this._data).length;
- },
-};
-
-Object.defineProperty(global.document, "cookie", {
- get: function () {
- return this._cookie || "";
- },
- set: function (value) {
- this._cookie = value;
- },
-});
-
-global.matchMedia = function (query) {
- return {
- matches: false,
- media: query,
- addListener: function () {},
- removeListener: function () {},
- };
-};
-
-global.URL = function (url) {
- return {
- href: url,
- origin: "",
- protocol: "",
- username: "",
- password: "",
- host: "",
- hostname: "",
- port: "",
- pathname: "",
- search: "",
- searchParams: {},
- hash: "",
- toString: function () {
- return url;
- },
- };
-};
-
-global.MutationObserver = function () {
- return {
- observe: function () {},
- disconnect: function () {},
- takeRecords: function () {
- return [];
- },
- };
-};
-
-global.IntersectionObserver = function () {
- return {
- observe: function () {},
- unobserve: function () {},
- disconnect: function () {},
- takeRecords: function () {
- return [];
- },
- };
-};
-
-global.FileReader = function () {
- return {
- readAsArrayBuffer: function () {},
- readAsBinaryString: function () {},
- readAsDataURL: function () {},
- readAsText: function () {},
- abort: function () {},
- result: null,
- error: null,
- onloadstart: null,
- onprogress: null,
- onload: null,
- onabort: null,
- onerror: null,
- onloadend: null,
- readyState: 0,
- };
-};
-
-global.Blob = function () {
- return {
- size: 0,
- type: "",
- slice: function () {
- return new global.Blob();
- },
- };
-};
-
-global.File = function (parts, filename, options) {
- return new global.Blob(parts, options);
-};
-
-global.crypto = {
- getRandomValues: function () {},
- subtle: {},
-};
-
-global.Headers = function () {
- return {
- append: function () {},
- delete: function () {},
- get: function () {
- return null;
- },
- has: function () {
- return false;
- },
- set: function () {},
- forEach: function () {},
- };
-};
-
-global.FormData = function () {
- return {
- append: function () {},
- delete: function () {},
- get: function () {
- return null;
- },
- getAll: function () {
- return [];
- },
- has: function () {
- return false;
- },
- set: function () {},
- forEach: function () {},
- };
-};
-
-class TextEncoder {
- encode() {}
-}
-
-global.TextEncoder = TextEncoder;
-
-global.document.documentElement.style = {};
-global.document.body.style = {};
-global.document.head.style = {};
diff --git a/frontend/src/metabase/static-viz/mock-environment.ts b/frontend/src/metabase/static-viz/mock-environment.ts
new file mode 100644
index 00000000000..4b17ba93321
--- /dev/null
+++ b/frontend/src/metabase/static-viz/mock-environment.ts
@@ -0,0 +1,302 @@
+import ResizeObserver from "resize-observer-polyfill";
+
+const defineGlobal = (name: PropertyKey, value: unknown): void => {
+ Object.defineProperty(globalThis, name, {
+ value,
+ writable: true,
+ configurable: true,
+ });
+};
+
+defineGlobal("ResizeObserver", ResizeObserver);
+
+class MockEventTarget {
+ listeners: Record<string, unknown[]> = {};
+ addEventListener(): void {}
+ removeEventListener(): void {}
+ dispatchEvent(): boolean {
+ return false;
+ }
+}
+defineGlobal("EventTarget", MockEventTarget);
+
+class MockElement extends MockEventTarget {
+ tagName: string;
+ children: unknown[] = [];
+ style: Record<string, unknown> = {};
+ attributes: Record<string, unknown> = {};
+
+ constructor(tagName: string) {
+ super();
+ this.tagName = tagName.toUpperCase();
+ }
+
+ appendChild(child: unknown): unknown {
+ this.children.push(child);
+ return child;
+ }
+
+ setAttribute(name: string, value: unknown): void {
+ this.attributes[name] = value;
+ }
+
+ getAttribute(name: string): unknown {
+ return this.attributes[name];
+ }
+}
+defineGlobal("Element", MockElement);
+
+const mockWindow = new MockEventTarget();
+defineGlobal("window", mockWindow);
+
+const createMockDocument = () => {
+ const document = new MockEventTarget();
+ const documentElement = new MockElement("html");
+ const head = new MockElement("head");
+ const body = new MockElement("body");
+ let cookie = "";
+ Object.assign(document, {
+ createElement: (tagName: string) => new MockElement(tagName),
+ createTextNode: (text: string) => ({ textContent: text }),
+ getElementById: (): null => null,
+ getElementsByTagName: (): unknown[] => [],
+ querySelector: (): null => null,
+ querySelectorAll: (): unknown[] => [],
+ documentElement,
+ head,
+ body,
+ readyState: "complete",
+ });
+ Object.defineProperty(document, "cookie", {
+ get: () => cookie,
+ set: (value: string) => {
+ cookie = value;
+ },
+ configurable: true,
+ });
+ return document;
+};
+
+const mockDocument = createMockDocument();
+defineGlobal("document", mockDocument);
+Object.assign(mockWindow, { document: mockDocument });
+
+const mockNavigator = {
+ userAgent: "GraalJS",
+ language: "en-US",
+ languages: ["en-US", "en"],
+ platform: "GraalJS",
+ appName: "StaticViz",
+ appVersion: "1.0",
+ cookieEnabled: false,
+ geolocation: {
+ getCurrentPosition: () => {},
+ watchPosition: () => {},
+ clearWatch: () => {},
+ },
+ onLine: true,
+ mediaDevices: {
+ getUserMedia: () => {},
+ },
+};
+defineGlobal("navigator", mockNavigator);
+Object.assign(mockWindow, { navigator: mockNavigator });
+
+defineGlobal("location", {
+ href: "",
+ protocol: "",
+ host: "",
+ hostname: "",
+ port: "",
+ pathname: "",
+ search: "",
+ hash: "",
+ origin: "",
+ reload: () => {},
+ replace: () => {},
+ assign: () => {},
+});
+
+defineGlobal("history", {
+ length: 0,
+ state: null,
+ back: () => {},
+ forward: () => {},
+ go: () => {},
+ pushState: () => {},
+ replaceState: () => {},
+});
+
+defineGlobal("screen", {
+ width: 0,
+ height: 0,
+ availWidth: 0,
+ availHeight: 0,
+ colorDepth: 24,
+ pixelDepth: 24,
+});
+
+defineGlobal("setTimeout", () => 0);
+defineGlobal("clearTimeout", () => {});
+defineGlobal("setInterval", () => 0);
+defineGlobal("clearInterval", () => {});
+defineGlobal("requestAnimationFrame", () => {});
+defineGlobal("cancelAnimationFrame", () => {});
+
+const createMockEvent = (type: string) => ({
+ type,
+ bubbles: false,
+ cancelable: false,
+ composed: false,
+ target: null,
+ currentTarget: null,
+ eventPhase: 0,
+ stopPropagation: () => {},
+ stopImmediatePropagation: () => {},
+ preventDefault: () => {},
+ isTrusted: false,
+ timeStamp: Date.now(),
+});
+defineGlobal("Event", createMockEvent);
+defineGlobal("CustomEvent", createMockEvent);
+
+const createMockStorage = () => {
+ const data: Record<string, string> = {};
+ return {
+ setItem(key: string, value: unknown): void {
+ data[key] = String(value);
+ },
+ getItem(key: string): string | null {
+ return Object.hasOwn(data, key) ? data[key] : null;
+ },
+ removeItem(key: string): void {
+ delete data[key];
+ },
+ clear(): void {
+ for (const key of Object.keys(data)) {
+ delete data[key];
+ }
+ },
+ key(index: number): string | null {
+ return Object.keys(data)[index] ?? null;
+ },
+ get length(): number {
+ return Object.keys(data).length;
+ },
+ };
+};
+defineGlobal("localStorage", createMockStorage());
+defineGlobal("sessionStorage", createMockStorage());
+
+defineGlobal("matchMedia", (query: string) => ({
+ matches: false,
+ media: query,
+ addListener: () => {},
+ removeListener: () => {},
+}));
+
+class MockURL {
+ href: string;
+ origin = "";
+ protocol = "";
+ username = "";
+ password = "";
+ host = "";
+ hostname = "";
+ port = "";
+ pathname = "";
+ search = "";
+ searchParams: Record<string, unknown> = {};
+ hash = "";
+
+ constructor(url: string) {
+ this.href = url;
+ }
+
+ toString(): string {
+ return this.href;
+ }
+}
+defineGlobal("URL", MockURL);
+
+class MockMutationObserver {
+ observe(): void {}
+ disconnect(): void {}
+ takeRecords(): unknown[] {
+ return [];
+ }
+}
+defineGlobal("MutationObserver", MockMutationObserver);
+
+class MockIntersectionObserver {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+ takeRecords(): unknown[] {
+ return [];
+ }
+}
+defineGlobal("IntersectionObserver", MockIntersectionObserver);
+
+class MockFileReader {
+ result: unknown = null;
+ error: unknown = null;
+ onloadstart: unknown = null;
+ onprogress: unknown = null;
+ onload: unknown = null;
+ onabort: unknown = null;
+ onerror: unknown = null;
+ onloadend: unknown = null;
+ readyState = 0;
+ readAsArrayBuffer(): void {}
+ readAsBinaryString(): void {}
+ readAsDataURL(): void {}
+ readAsText(): void {}
+ abort(): void {}
+}
+defineGlobal("FileReader", MockFileReader);
+
+class MockBlob {
+ size = 0;
+ type = "";
+ slice(): MockBlob {
+ return new MockBlob();
+ }
+}
+defineGlobal("Blob", MockBlob);
+
+defineGlobal("File", function MockFile() {
+ return new MockBlob();
+});
+
+defineGlobal("crypto", {
+ getRandomValues: () => {},
+ subtle: {},
+});
+
+class MockWebAPICollection {
+ append(): void {}
+ delete(): void {}
+ get(): null {
+ return null;
+ }
+ has(): boolean {
+ return false;
+ }
+ set(): void {}
+ forEach(): void {}
+}
+defineGlobal("Headers", class MockHeaders extends MockWebAPICollection {});
+defineGlobal(
+ "FormData",
+ class MockFormData extends MockWebAPICollection {
+ getAll(): unknown[] {
+ return [];
+ }
+ },
+);
+
+class MockTextEncoder {
+ encode(): void {}
+}
+defineGlobal("TextEncoder", MockTextEncoder);
diff --git a/frontend/src/metabase/static-viz/register.js b/frontend/src/metabase/static-viz/register.ts
similarity index 61%
rename from frontend/src/metabase/static-viz/register.js
rename to frontend/src/metabase/static-viz/register.ts
index 8719efab364..45f674ef6aa 100644
--- a/frontend/src/metabase/static-viz/register.js
+++ b/frontend/src/metabase/static-viz/register.ts
@@ -18,19 +18,34 @@ import { SmartScalar } from "metabase/visualizations/visualizations/SmartScalar"
import { WaterfallChart } from "metabase/visualizations/visualizations/WaterfallChart";
export const registerStaticVisualizations = () => {
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(Scalar);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(SmartScalar);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(LineChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(AreaChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(Funnel);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(BarChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(WaterfallChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(ComboChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(ScatterPlot);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(BoxPlot);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(PieChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(SankeyChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(RowChart);
+ // @ts-expect-error: incompatible prop types with registerVisualization
registerVisualization(Progress);
+ // @ts-expect-error: incompatible prop types with registerVisualization
setDefaultVisualization(Scalar);
};
diff --git a/frontend/src/metabase/visualizations/lib/settings/typed-utils.ts b/frontend/src/metabase/visualizations/lib/settings/typed-utils.ts
index 424c0ce9c66..8b2ddd23caa 100644
--- a/frontend/src/metabase/visualizations/lib/settings/typed-utils.ts
+++ b/frontend/src/metabase/visualizations/lib/settings/typed-utils.ts
@@ -89,10 +89,10 @@ export function sanitizeDashcardSettings(
});
}
-export function extendCardWithDashcardSettings(
- card: Card | VirtualCard,
+export function extendCardWithDashcardSettings<T extends Card | VirtualCard>(
+ card: T,
dashcardSettings?: VisualizationSettings,
-): Card | VirtualCard {
+): T {
// Legacy broken behavior: When editing dashcard viz settings, we save both the edited setting and any settings with
// persistDefault: true. This leads to saving data settings like graph.dimensions/graph.metrics even when they can't be edited in dashboards.
const visualization = getVisualization(card.display);
diff --git a/frontend/src/types/ee-overrides.d.ts b/frontend/src/types/ee-overrides.d.ts
new file mode 100644
index 00000000000..95ccae45c4a
--- /dev/null
+++ b/frontend/src/types/ee-overrides.d.ts
@@ -0,0 +1,5 @@
+declare module "ee-overrides" {
+ const enterpriseOverrides: (() => void) | undefined;
+ // eslint-disable-next-line import/no-default-export -- deprecated usage
+ export default enterpriseOverrides;
+}
diff --git a/rspack.static-viz.config.js b/rspack.static-viz.config.js
index af723a406f7..e5f80d1d77f 100644
--- a/rspack.static-viz.config.js
+++ b/rspack.static-viz.config.js
@@ -31,7 +31,7 @@ module.exports = (env) => {
entry: {
"lib-static-viz": {
- import: "./static-viz/index.js",
+ import: "./static-viz/index.tsx",
library: {
name: "StaticViz",
type: "var",