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
Apply column formatting to static viz map legend, add render to side (#76024)
Nick Fitzpatrick194821f2227c
diff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_StaticChoropleth_US_States_Currency.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_StaticChoropleth_US_States_Currency.pngnew file mode 100644index 00000000000..9da82cdf9feBinary files /dev/null and b/.loki/reference/chrome_laptop_Viz_Static_Viz_StaticChoropleth_US_States_Currency.png differdiff --git a/.loki/reference/chrome_laptop_Viz_Static_Viz_StaticChoropleth_US_States_Currency_Side_Legend.png b/.loki/reference/chrome_laptop_Viz_Static_Viz_StaticChoropleth_US_States_Currency_Side_Legend.pngnew file mode 100644index 00000000000..5713e910ad1Binary files /dev/null and b/.loki/reference/chrome_laptop_Viz_Static_Viz_StaticChoropleth_US_States_Currency_Side_Legend.png differdiff --git a/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.stories.tsx b/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.stories.tsxindex 91f88533ec2..2cba59c1451 100644--- a/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.stories.tsx+++ b/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.stories.tsx@@ -6,7 +6,13 @@ import {StaticChoropleth,type StaticChoroplethProps,} from "./StaticChoropleth";-import { customRegion, noData, usStates, worldCountries } from "./stories-data";+import {+ customRegion,+ noData,+ usStates,+ usStatesCurrency,+ worldCountries,+} from "./stories-data";export default {title: "Viz/Static Viz/StaticChoropleth",@@ -17,7 +23,12 @@ const renderingContext = createStaticRenderingContext();const Template: StoryFn<StaticChoroplethProps> = (args) => {return (- <div style={{ border: "1px solid black", display: "inline-block" }}>+ <div+ style={{+ border: "1px solid black",+ display: "inline-block",+ }}+ ><StaticChoropleth {...args} /></div>);@@ -41,6 +52,20 @@ export const CustomRegion = {args: { ...customRegion, renderingContext },};+// A currency metric: legend labels carry the column's formatting ("$1.4k"-style), matching the live+// dashboard. Guards that getStaticChoroplethSettings feeds column formatting into the legend.+export const USStatesCurrency = {+ render: Template,+ args: { ...usStatesCurrency, renderingContext },+};++// Same data with the legend placed vertically to the side (the wide-card layout the live map uses),+// instead of the default horizontal strip below the map.+export const USStatesCurrencySideLegend = {+ render: Template,+ args: { ...usStatesCurrency, renderingContext, legendPosition: "side" },+};+// No rows join to a feature: every region falls to the no-data gray and no legend is drawn.export const NoData = {render: Template,diff --git a/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.tsx b/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.tsxindex 1953d1f3779..d79c6ee25b5 100644--- a/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.tsx+++ b/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.tsx@@ -27,12 +27,15 @@ type GeoJSONDetails = {region_name: string;};+type LegendPosition = "bottom" | "side";+export interface StaticChoroplethProps {rawSeries: RawSeries;settings: ComputedVisualizationSettings;geoJson: GeoJSONData;geoJsonDetails: GeoJSONDetails;renderingContext: RenderingContext;+ legendPosition?: LegendPosition;}export const StaticChoropleth = ({@@ -41,6 +44,7 @@ export const StaticChoropleth = ({geoJson,geoJsonDetails,renderingContext,+ legendPosition = "bottom",}: StaticChoroplethProps) => {const [{@@ -95,18 +99,56 @@ export const StaticChoropleth = ({const geo = geoPath(projection);const [[minX, minY], [maxX, maxY]] = geo.bounds(geoJson);+ const bounds: MapBounds = { minX, minY, maxX, maxY };const mapWidth = maxX - minX;const mapHeight = maxY - minY;- // Legend strip rendered below the map, in the same projected coordinate space.- const legendGap = mapHeight * 0.04;- const swatchHeight = mapHeight * 0.045;- const fontSize = mapHeight * 0.035;- const legendY = maxY + legendGap;- const labelY = legendY + swatchHeight + fontSize * 1.2;- const itemWidth =- legendTitles.length > 0 ? mapWidth / legendTitles.length : 0;- const totalHeight = mapHeight + legendGap + swatchHeight + fontSize * 1.6;+ const fontColor = renderingContext.getColor("text-secondary");+ const features = (+ <g>+ {getFeatures(geoJson).map((feature, index) => (+ <path+ key={index}+ d={geo(feature) ?? undefined}+ stroke="white"+ strokeWidth={1}+ fill={getColor(feature)}+ />+ ))}+ </g>+ );++ const hasLegend = legendTitles.length > 0;++ // Vertical legend to the left of the map: widen the viewBox leftward so the swatch column sits beside+ // the (unmoved) map in the same projected coordinate space.+ if (legendPosition === "side" && hasLegend) {+ const legendWidth = mapWidth * SIDE_LEGEND.widthRatio;+ const totalWidth = mapWidth + legendWidth;+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width={totalWidth}+ height={mapHeight}+ viewBox={`${minX - legendWidth} ${minY} ${totalWidth} ${mapHeight}`}+ >+ {features}+ <SideLegend+ titles={legendTitles}+ colors={heatMapColors}+ fontColor={fontColor}+ bounds={bounds}+ legendWidth={legendWidth}+ />+ </svg>+ );+ }++ const totalHeight =+ mapHeight ++ getLegendGap(mapHeight) ++ getSwatchHeight(mapHeight) ++ getLegendFontSize(mapHeight) * BOTTOM_LEGEND.heightReserveRatio;return (<svg@@ -115,45 +157,160 @@ export const StaticChoropleth = ({height={totalHeight}viewBox={`${minX} ${minY} ${mapWidth} ${totalHeight}`}>- <g>- {getFeatures(geoJson).map((feature, index) => (- <path- key={index}- d={geo(feature) ?? undefined}- stroke="white"- strokeWidth={1}- fill={getColor(feature)}- />- ))}- </g>- {legendTitles.length > 0 && (- <g>- {legendTitles.map((title, index) => {- const x = minX + index * itemWidth;- return (- <g key={index}>- <rect- x={x}- y={legendY}- width={itemWidth}- height={swatchHeight}- fill={heatMapColors[index]}- />- <text- x={x + itemWidth / 2}- y={labelY}- fontSize={fontSize}- fontFamily="Lato, sans-serif"- textAnchor="middle"- fill={renderingContext.getColor("text-secondary")}- >- {title}- </text>- </g>- );- })}- </g>+ {features}+ {hasLegend && (+ <BottomLegend+ titles={legendTitles}+ colors={heatMapColors}+ fontColor={fontColor}+ bounds={bounds}+ />)}</svg>);};++type MapBounds = {+ minX: number;+ minY: number;+ maxX: number;+ maxY: number;+};++type LegendProps = {+ titles: string[];+ colors: string[];+ fontColor: string;+ bounds: MapBounds;+};++// Legend geometry as ratios so the legend scales with the projected map. Grouped here as the single+// place to tune spacing; each field notes what it's a ratio of.+const BOTTOM_LEGEND = {+ gapRatio: 0.04, // of map height+ swatchHeightRatio: 0.045, // of map height+ fontSizeRatio: 0.035, // of map height+ labelOffsetRatio: 1.2, // of font size, drops the label below its swatch+ heightReserveRatio: 1.6, // of font size, vertical space reserved below the map+} as const;++const SIDE_LEGEND = {+ widthRatio: 0.34, // of map width+ fontSizeRatio: 0.042, // of map height+ rowHeightRatio: 0.09, // of map height+ swatchSizeRatio: 1.1, // of font size+ gapRatio: 0.6, // of font size+ swatchInsetRatio: 0.4, // of font size+ labelBaselineRatio: 0.35, // of font size, vertical-centering nudge for the label+} as const;++// Shared so the main component reserves the same space (totalHeight) that BottomLegend draws into —+// otherwise the strip gets clipped.+const getLegendGap = (mapHeight: number) => mapHeight * BOTTOM_LEGEND.gapRatio;+const getSwatchHeight = (mapHeight: number) =>+ mapHeight * BOTTOM_LEGEND.swatchHeightRatio;+const getLegendFontSize = (mapHeight: number) =>+ mapHeight * BOTTOM_LEGEND.fontSizeRatio;++// Horizontal swatch strip below the map: one equal-width swatch per bin, label centered beneath it.+const BottomLegend = ({ titles, colors, fontColor, bounds }: LegendProps) => {+ if (titles.length === 0) {+ return null;+ }++ const { minX, maxY } = bounds;+ const mapWidth = bounds.maxX - minX;+ const mapHeight = maxY - bounds.minY;+ const swatchHeight = getSwatchHeight(mapHeight);+ const fontSize = getLegendFontSize(mapHeight);+ const legendY = maxY + getLegendGap(mapHeight);+ const labelY =+ legendY + swatchHeight + fontSize * BOTTOM_LEGEND.labelOffsetRatio;+ const itemWidth = mapWidth / titles.length;++ return (+ <g>+ {titles.map((title, index) => {+ const x = minX + index * itemWidth;+ return (+ <g key={index}>+ <rect+ x={x}+ y={legendY}+ width={itemWidth}+ height={swatchHeight}+ fill={colors[index]}+ />+ <text+ x={x + itemWidth / 2}+ y={labelY}+ fontSize={fontSize}+ fontFamily="Lato, sans-serif"+ textAnchor="middle"+ fill={fontColor}+ >+ {title}+ </text>+ </g>+ );+ })}+ </g>+ );+};++// Vertical legend column left of the map: a small swatch per bin with its label to the right, stacked+// and centered against the map's height. Batik ignores dominant-baseline, so the label baseline is+// offset manually to vertically center it against the swatch.+const SideLegend = ({+ titles,+ colors,+ fontColor,+ bounds,+ legendWidth,+}: LegendProps & { legendWidth: number }) => {+ if (titles.length === 0) {+ return null;+ }++ const { minX, minY } = bounds;+ const mapHeight = bounds.maxY - minY;+ const fontSize = mapHeight * SIDE_LEGEND.fontSizeRatio;+ const rowHeight = mapHeight * SIDE_LEGEND.rowHeightRatio;+ const swatchSize = fontSize * SIDE_LEGEND.swatchSizeRatio;+ const gap = fontSize * SIDE_LEGEND.gapRatio;+ const swatchX = minX - legendWidth + fontSize * SIDE_LEGEND.swatchInsetRatio;+ const top = minY + (mapHeight - titles.length * rowHeight) / 2;++ return (+ <g>+ {titles.map((title, index) => {+ const rowY = top + index * rowHeight;+ return (+ <g key={index}>+ <rect+ x={swatchX}+ y={rowY}+ width={swatchSize}+ height={swatchSize}+ fill={colors[index]}+ />+ <text+ x={swatchX + swatchSize + gap}+ y={+ rowY ++ swatchSize / 2 ++ fontSize * SIDE_LEGEND.labelBaselineRatio+ }+ fontSize={fontSize}+ fontFamily="Lato, sans-serif"+ textAnchor="start"+ fill={fontColor}+ >+ {title}+ </text>+ </g>+ );+ })}+ </g>+ );+};diff --git a/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.unit.spec.tsx b/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.unit.spec.tsxindex 6e7767d4363..ffc4a1cfa4f 100644--- a/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.unit.spec.tsx+++ b/frontend/src/metabase/static-viz/components/StaticChoropleth/StaticChoropleth.unit.spec.tsx@@ -9,8 +9,13 @@ import type {RenderingContext,} from "metabase/visualizations/types";import type { RawSeries } from "metabase-types/api";+import {+ createMockColumn,+ createMockSingleSeries,+} from "metabase-types/api/mocks";import { StaticChoropleth } from "./StaticChoropleth";+import { getStaticChoroplethSettings } from "./utils";const renderingContext = {getColor: (name: string) =>@@ -135,6 +140,78 @@ describe("StaticChoropleth", () => {expect(svg).toContain('fill="#888888"');});+ it("formats legend labels with the metric column's settings via getStaticChoroplethSettings", () => {+ // getStaticChoroplethSettings rebuilds the `settings.column` accessor that the static-viz bundle+ // can't (map isn't registered there); without it the currency formatting never reaches the legend.+ const currencyRawSeries: RawSeries = [+ createMockSingleSeries(+ {+ display: "map",+ visualization_settings: {+ "map.region": "us_states",+ "map.dimension": "state",+ "map.metric": "revenue",+ },+ },+ {+ data: {+ cols: [+ createMockColumn({+ name: "state",+ base_type: "type/Text",+ semantic_type: "type/State",+ }),+ createMockColumn({+ name: "revenue",+ base_type: "type/Float",+ semantic_type: "type/Income",+ settings: { number_style: "currency", currency: "USD" },+ }),+ ],+ rows: [+ ["CA", 12400],+ ["New York", 1400],+ ],+ },+ },+ ),+ ];++ const svg = ReactDOMServer.renderToStaticMarkup(+ <StaticChoropleth+ rawSeries={currencyRawSeries}+ settings={getStaticChoroplethSettings(currencyRawSeries)}+ geoJson={geoJson}+ geoJsonDetails={{ region_key: "STATE", region_name: "NAME" }}+ renderingContext={renderingContext}+ />,+ );++ // Currency symbol from the column settings reaches the legend, and the raw value is abbreviated away.+ expect(svg).toContain("$");+ expect(svg).not.toContain("12400");+ });++ it("renders the legend to the side when legendPosition is 'side'", () => {+ // The side layout widens the viewBox leftward (negative x origin) to seat the vertical legend+ // column beside the map; the default bottom strip starts at the map's own origin.+ const sideSvg = ReactDOMServer.renderToStaticMarkup(+ <StaticChoropleth+ rawSeries={rawSeries}+ settings={settings}+ geoJson={geoJson}+ geoJsonDetails={{ region_key: "STATE", region_name: "NAME" }}+ renderingContext={renderingContext}+ legendPosition="side"+ />,+ );++ expect(sideSvg.startsWith("<svg")).toBe(true);+ expect(sideSvg).toContain("<text");+ expect(sideSvg).toMatch(/viewBox="-[\d.]+ /);+ expect(toSvgString()).not.toMatch(/viewBox="-/);+ });+it("renders a custom (non-us_states) region via Mercator + fitWidth", () => {// Any region other than us_states uses geoMercator().fitWidth, which fits arbitrary GeoJSON bounds —// this is what makes user-defined custom maps work without hardcoded projection frames.diff --git a/frontend/src/metabase/static-viz/components/StaticChoropleth/index.ts b/frontend/src/metabase/static-viz/components/StaticChoropleth/index.tsindex b058705afff..e221197083c 100644--- a/frontend/src/metabase/static-viz/components/StaticChoropleth/index.ts+++ b/frontend/src/metabase/static-viz/components/StaticChoropleth/index.ts@@ -1 +1,2 @@export { StaticChoropleth } from "./StaticChoropleth";+export { getStaticChoroplethSettings } from "./utils";diff --git a/frontend/src/metabase/static-viz/components/StaticChoropleth/stories-data.ts b/frontend/src/metabase/static-viz/components/StaticChoropleth/stories-data.tsindex c073e609060..89938f0effb 100644--- a/frontend/src/metabase/static-viz/components/StaticChoropleth/stories-data.ts+++ b/frontend/src/metabase/static-viz/components/StaticChoropleth/stories-data.ts@@ -7,6 +7,8 @@ import worldCountriesGeoJson from "assets/geojson/world.json";import type { ComputedVisualizationSettings } from "metabase/visualizations/types";import type { RawSeries } from "metabase-types/api";+import { getStaticChoroplethSettings } from "./utils";+// A user-defined custom region (non-us_states, non-default region_key): exercises the Mercator + fitWidth branch.const customRegionGeoJson: FeatureCollection = {type: "FeatureCollection",@@ -51,10 +53,14 @@ const stateCols = [{ name: "count", base_type: "type/Integer", semantic_type: "type/Quantity" },];-const makeRawSeries = (cols: unknown[], rows: unknown[][]): RawSeries =>+const makeRawSeries = (+ cols: unknown[],+ rows: unknown[][],+ visualizationSettings: Record<string, unknown> = {},+): RawSeries =>[{- card: { display: "map" },+ card: { display: "map", visualization_settings: visualizationSettings },data: { cols, rows },},] as unknown as RawSeries;@@ -132,6 +138,50 @@ export const customRegion = {),};+// A currency metric with thousands-scale values: the legend abbreviates to "$1.4k"-style labels+// (matching the live dashboard) only when the metric column's formatting reaches getLegendTitles via+// getStaticChoroplethSettings — the behavior this story guards.+const revenueCols = [+ { name: "state", base_type: "type/Text", semantic_type: "type/State" },+ {+ name: "revenue",+ base_type: "type/Float",+ semantic_type: "type/Income",+ settings: {+ number_style: "currency",+ currency: "USD",+ currency_style: "symbol",+ },+ },+];++const revenueRawSeries = makeRawSeries(+ revenueCols,+ [+ ["CA", 108500],+ ["TX", 66000],+ ["NY", 44700],+ ["FL", 42600],+ ["IL", 30000],+ ["PA", 27200],+ ["OH", 16800],+ ["GA", 12400],+ ["WA", 1400],+ ],+ {+ "map.region": "us_states",+ "map.dimension": "state",+ "map.metric": "revenue",+ },+);++export const usStatesCurrency = {+ geoJson: usStatesGeoJson,+ geoJsonDetails: { region_key: "STATE", region_name: "NAME" },+ rawSeries: revenueRawSeries,+ settings: getStaticChoroplethSettings(revenueRawSeries),+};+// Same region as `usStates` but no rows join — exercises the all-gray, no-legend (no-data) branch.export const noData = {geoJson: usStatesGeoJson,diff --git a/frontend/src/metabase/static-viz/components/StaticChoropleth/utils.ts b/frontend/src/metabase/static-viz/components/StaticChoropleth/utils.tsindex d780e89bd13..55e409de4e2 100644--- a/frontend/src/metabase/static-viz/components/StaticChoropleth/utils.ts+++ b/frontend/src/metabase/static-viz/components/StaticChoropleth/utils.ts@@ -2,7 +2,11 @@ import Color from "color";import type { Feature, FeatureCollection } from "geojson";import { getCanonicalRowKey } from "metabase/visualizations/lib/region-codes";-import type { GeoJSONData, RowValue } from "metabase-types/api";+import { getComputedSettings } from "metabase/visualizations/lib/settings";+import { columnSettings } from "metabase/visualizations/lib/settings/column";+import { getStoredSettingsForSeries } from "metabase/visualizations/lib/settings/visualization";+import type { ComputedVisualizationSettings } from "metabase/visualizations/types";+import type { GeoJSONData, RawSeries, RowValue } from "metabase-types/api";// Color constants and legend helpers are shared with the runtime ChoroplethMap via// metabase/visualizations/lib/choropleth (a Leaflet-free module the static-viz bundle can load).@@ -27,6 +31,18 @@ export function getFeatureKey(feature: Feature, keyProperty: string): string {return String(feature.properties?.[keyProperty]).toLowerCase();}+// `map` isn't registered in the static-viz bundle (needs Leaflet), so computed settings here lack the+// `settings.column` accessor — rebuild it so PDF legends format the metric like the live ChoroplethMap.+export function getStaticChoroplethSettings(+ rawSeries: RawSeries,+): ComputedVisualizationSettings {+ const storedSettings = getStoredSettingsForSeries(rawSeries);+ return {+ ...storedSettings,+ ...getComputedSettings(columnSettings(), rawSeries, storedSettings),+ };+}+// Sum each row's metric by canonical region key (for feature lookup); non-numeric metrics count as 0.export function getRegionValues(rows: RowValue[][],diff --git a/frontend/src/metabase/static-viz/index.tsx b/frontend/src/metabase/static-viz/index.tsxindex 4e04f2db3ac..db31dda1ad7 100644--- a/frontend/src/metabase/static-viz/index.tsx+++ b/frontend/src/metabase/static-viz/index.tsx@@ -8,7 +8,10 @@ import ReactDOMServer from "react-dom/server";import enterpriseOverrides from "ee-overrides";import "metabase/utils/dayjs";-import { StaticChoropleth } from "metabase/static-viz/components/StaticChoropleth";+import {+ StaticChoropleth,+ getStaticChoroplethSettings,+} from "metabase/static-viz/components/StaticChoropleth";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";@@ -19,7 +22,6 @@ 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 type { ComputedVisualizationSettings } from "metabase/visualizations/types";import {createDataSource,getVisualizationColumns,@@ -191,10 +193,7 @@ export function RenderChart(return ReactDOMServer.renderToStaticMarkup(<StaticChoroplethrawSeries={rawSeriesWithRemappings}- settings={- rawSeriesWithRemappings[0].card- .visualization_settings as ComputedVisualizationSettings- }+ settings={getStaticChoroplethSettings(rawSeriesWithRemappings)}geoJson={geoJson}geoJsonDetails={geoJsonDetails}renderingContext={renderingContext}