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
chore: rework ChoroplethMap to function component and convert test to ts (#74483)
Uladzimir Havenchyk346170cf3fb6
diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsxindex 021a6e0e82a..d0ec4719f62 100644--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx@@ -35,6 +35,7 @@ import type {import { isMetric, isString } from "metabase-lib/v1/types/utils/isa";import type {CustomGeoJSONMap,+ DatasetColumn,GeoJSONData,RowValue,VisualizationSettings,@@ -239,25 +240,7 @@ function getDetails(return region ? customGeoJson[region] : undefined;}-function ChoroplethMapInner(props: ChoroplethMapProps) {- const {- series,- className,- gridSize,- hovered,- onHoverChange,- visualizationIsClickable,- onVisualizationClick,- settings,- isDashboard,- isDocument,- isMetricsViewer,- onRenderError,- } = props;-- const details = getDetails(settings);- const geoJsonPath = details ? getMapUrl(details, props) : null;-+function useGeoJson(geoJsonPath: string | null): ChoroplethMapState {const [state, setState] = useState<ChoroplethMapState>({geoJson: null,geoJsonPath: null,@@ -283,34 +266,186 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {};}, [geoJsonPath]);- if (!details) {- return <MapNotFound />;+ return state;+}++// projectionFrame is the lng/lat of the top left and bottom right corners+function getMapProjection(region: string | undefined): {+ projection: Projection;+ projectionFrame: ProjectionFrame | null;+} {+ // special case builtin maps to use legacy choropleth map+ if (region === "us_states") {+ return {+ projection: d3.geoAlbersUsa(),+ projectionFrame: [+ [-135.0, 46.6],+ [-69.1, 21.7],+ ],+ };+ }+ if (region === "world_countries") {+ return {+ projection: d3.geoMercator(),+ projectionFrame: [+ [-170, 78],+ [180, -60],+ ],+ };+ }+ return { projection: null, projectionFrame: null };+}++function buildValuesMap(+ rows: RowValue[][],+ getRowKey: (row: RowValue[]) => string,+ getRowValue: (row: RowValue[]) => number,+): Record<string, number> {+ const valuesMap: Record<string, number> = {};+ for (const row of rows) {+ const key = getRowKey(row);+ valuesMap[key] = (valuesMap[key] || 0) + getRowValue(row);}+ return valuesMap;+}- const { geoJson, minimalBounds } = state;+function buildColorScale(+ domain: number[],+ settingsColors: string[] | undefined,+): {+ colorScale: (value: number) => string;+ groups: number[][];+ heatMapColors: string[];+} {+ const baseColors = settingsColors ?? HEAT_MAP_COLORS;+ const heatMapColors = baseColors.slice(-domain.length);- // special case builtin maps to use legacy choropleth map- let projection: Projection;- let projectionFrame: ProjectionFrame | null = null;- // projectionFrame is the lng/lat of the top left and bottom right corners- if (settings["map.region"] === "us_states") {- projection = d3.geoAlbersUsa();- projectionFrame = [- [-135.0, 46.6],- [-69.1, 21.7],- ];- } else if (settings["map.region"] === "world_countries") {- projection = d3.geoMercator();- projectionFrame = [- [-170, 78],- [180, -60],- ];- } else {- projection = null;+ const groups = ss.ckmeans(domain, heatMapColors.length);+ const groupBoundaries = groups.slice(1).map((cluster) => cluster[0]);++ const colorScale = d3+ .scaleThreshold<number, string>()+ .domain(groupBoundaries)+ .range(heatMapColors);++ return { colorScale, groups, heatMapColors };+}++function computeAspectRatio(+ projection: Projection,+ projectionFrame: ProjectionFrame | null,+ minimalBounds: L.LatLngBounds | undefined,+): number {+ if (projection && projectionFrame) {+ const [[minX, minY], [maxX, maxY]] = projectionFrame.map((coord) => {+ const projected = projection(coord);+ return projected ?? [0, 0];+ });+ return (maxX - minX) / (maxY - minY);}+ if (minimalBounds) {+ return (+ (minimalBounds.getEast() - minimalBounds.getWest()) /+ (minimalBounds.getNorth() - minimalBounds.getSouth())+ );+ }+ return 1;+}- const nameProperty = details.region_name;- const keyProperty = details.region_key;+type FeatureClickContext = {+ cols: DatasetColumn[];+ dimensionIndex: number;+ metricIndex: number;+ settings: VisualizationSettings;+ getFeatureName: (feature: Feature) => string;+ getFeatureKey: (feature: Feature, opts?: { lowerCase?: boolean }) => string;+};++function buildFeatureClickObject(+ row: RowValue[] | undefined,+ feature: Feature | null,+ ctx: FeatureClickContext,+) {+ const {+ cols,+ dimensionIndex,+ metricIndex,+ settings,+ getFeatureName,+ getFeatureKey,+ } = ctx;++ if (row == null) {+ // This branch lets you click on empty regions. We use in dashboard cross-filtering.+ return {+ value: null,+ column: cols[metricIndex],+ dimensions: [],+ data: feature+ ? [+ {+ key: cols[dimensionIndex].display_name,+ value: getFeatureKey(feature, { lowerCase: false }),+ col: cols[dimensionIndex],+ },+ ]+ : [],+ settings,+ };+ }++ return {+ value: row[metricIndex],+ column: cols[metricIndex],+ dimensions: [+ {+ value: row[dimensionIndex],+ column: cols[dimensionIndex],+ },+ ],+ data: row.map((value, index) => ({+ key: cols[index].display_name,+ value:+ index === dimensionIndex && feature != null+ ? getFeatureName(feature)+ : value,+ // We set clickBehaviorValue to the raw data value for use in a filter via crossfiltering.+ // `value` above is used in the tool tips so it needs to use `getFeatureName`.+ clickBehaviorValue: value,+ col: cols[index],+ })),+ origin: { row, cols },+ settings,+ };+}++function ChoroplethMapInner(props: ChoroplethMapProps) {+ const {+ series,+ className,+ gridSize,+ hovered,+ onHoverChange,+ visualizationIsClickable,+ onVisualizationClick,+ settings,+ isDashboard,+ isDocument,+ isMetricsViewer,+ onRenderError,+ } = props;++ const details = getDetails(settings);+ const geoJsonPath = details ? getMapUrl(details, props) : null;+ const { geoJson, minimalBounds } = useGeoJson(geoJsonPath);++ if (!details) {+ return <MapNotFound />;+ }++ const { projection, projectionFrame } = getMapProjection(+ settings["map.region"],+ );if (!geoJson) {return (@@ -320,6 +455,9 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {);}+ const nameProperty = details.region_name;+ const keyProperty = details.region_key;+const [{data: { cols, rows },@@ -351,13 +489,7 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {return lowerCase ? key.toLowerCase() : key;};- const valuesMap: Record<string, number> = {};- for (const row of rows) {- const key = getRowKey(row);- const value = getRowValue(row);- valuesMap[key] = (valuesMap[key] || 0) + value;- }-+ const valuesMap = buildValuesMap(rows, getRowKey, getRowValue);const getFeatureValue = (feature: Feature): number | undefined =>valuesMap[getFeatureKey(feature)];@@ -365,77 +497,35 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {rows.map((row) => [getRowKey(row), row]),);- const getFeatureClickObject = (- row: RowValue[] | undefined,- feature: Feature | null,- ) => {- if (row == null) {- // This branch lets you click on empty regions. We use in dashboard cross-filtering.- return {- value: null,- column: cols[metricIndex],- dimensions: [],- data: feature- ? [- {- key: cols[dimensionIndex].display_name,- value: getFeatureKey(feature, { lowerCase: false }),- col: cols[dimensionIndex],- },- ]- : [],- settings,- };- }- return {- value: row[metricIndex],- column: cols[metricIndex],- dimensions: [- {- value: row[dimensionIndex],- column: cols[dimensionIndex],- },- ],- data: row.map((value, index) => ({- key: cols[index].display_name,- value:- index === dimensionIndex- ? feature != null- ? getFeatureName(feature)- : row[dimensionIndex]- : value,- // We set clickBehaviorValue to the raw data value for use in a filter via crossfiltering.- // `value` above is used in the tool tips so it needs to use `getFeatureName`.- clickBehaviorValue: value,- col: cols[index],- })),- origin: { row, cols },- settings,- };+ const clickContext: FeatureClickContext = {+ cols,+ dimensionIndex,+ metricIndex,+ settings,+ getFeatureName,+ getFeatureKey,};- const isClickable = onVisualizationClick != null;-- const onClickFeature = isClickable- ? (click: { feature: Feature; event: MouseEvent }) => {- const featureKey = getFeatureKey(click.feature);- const row = rowByFeatureKey.get(featureKey);- const clickData = {- ...getFeatureClickObject(row, click.feature),- event: click.event,- };-- if (visualizationIsClickable(clickData)) {- onVisualizationClick(clickData);+ const onClickFeature =+ onVisualizationClick != null+ ? (click: { feature: Feature; event: MouseEvent }) => {+ const row = rowByFeatureKey.get(getFeatureKey(click.feature));+ const clickData = {+ ...buildFeatureClickObject(row, click.feature, clickContext),+ event: click.event,+ };+ if (visualizationIsClickable(clickData)) {+ onVisualizationClick(clickData);+ }}- }- : undefined;+ : undefined;+const onHoverFeature = onHoverChange? (hover: { feature: Feature; event: MouseEvent } | null) => {const row = hover && rowByFeatureKey.get(getFeatureKey(hover.feature));if (row && hover) {onHoverChange({- ...getFeatureClickObject(row, hover.feature),+ ...buildFeatureClickObject(row, hover.feature, clickContext),event: hover.event,});} else {@@ -444,20 +534,11 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {}: undefined;- const domainSet = new Set(Object.values(valuesMap));- const domain = Array.from(domainSet);-- const settingsColors: string[] | undefined = settings["map.colors"];- const _heatMapColors = settingsColors ?? HEAT_MAP_COLORS;- const heatMapColors = _heatMapColors.slice(-domain.length);-- const groups = ss.ckmeans(domain, heatMapColors.length);- const groupBoundaries = groups.slice(1).map((cluster) => cluster[0]);-- const colorScale = d3- .scaleThreshold<number, string>()- .domain(groupBoundaries)- .range(heatMapColors);+ const domain = Array.from(new Set(Object.values(valuesMap)));+ const { colorScale, groups, heatMapColors } = buildColorScale(+ domain,+ settings["map.colors"],+ );const columnSettings = settings.column?.(cols[metricIndex]) ?? {};const legendTitles = getLegendTitles(groups, columnSettings);@@ -467,20 +548,11 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {return value == null ? HEAT_MAP_ZERO_COLOR : colorScale(value);};- let aspectRatio: number;- if (projection && projectionFrame) {- const [[minX, minY], [maxX, maxY]] = projectionFrame.map((coord) => {- const projected = projection?.(coord);- return projected ?? [0, 0];- });- aspectRatio = (maxX - minX) / (maxY - minY);- } else if (minimalBounds) {- aspectRatio =- (minimalBounds.getEast() - minimalBounds.getWest()) /- (minimalBounds.getNorth() - minimalBounds.getSouth());- } else {- aspectRatio = 1;- }+ const aspectRatio = computeAspectRatio(+ projection,+ projectionFrame,+ minimalBounds,+ );const onLegendHoverChange = onHoverChange? (hover?: { index: number; element?: HTMLElement | null } | null) => {diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.js b/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.tssimilarity index 77%rename from frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.jsrename to frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.tsindex 4ab3256f386..7277b0a4d53 100644--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.js+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.unit.spec.ts@@ -3,6 +3,14 @@ import {getLegendTitles,getMapUrl,} from "metabase/visualizations/components/ChoroplethMap";+import type { ColumnSettings } from "metabase/visualizations/types";++const currencyColumnSettings: ColumnSettings = {+ column: { base_type: "type/Float" },+ number_style: "currency",+ currency: "USD",+ currency_style: "symbol",+};describe("getLegendTitles", () => {it("should not format short values compactly", () => {@@ -11,14 +19,8 @@ describe("getLegendTitles", () => {[1.32, 1.48],[9, 12, 13],];- const columnSettings = {- column: { base_type: "type/Float" },- number_style: "currency",- currency: "USD",- currency_style: "symbol",- };- const titles = getLegendTitles(groups, columnSettings);+ const titles = getLegendTitles(groups, currencyColumnSettings);expect(titles).toEqual(["$1.12 - $1.25", "$1.32 - $1.48", "$9.00 +"]);});@@ -29,14 +31,8 @@ describe("getLegendTitles", () => {[2000.32, 2200, 2500.48],[11000, 12000, 13000],];- const columnSettings = {- column: { base_type: "type/Float" },- number_style: "currency",- currency: "USD",- currency_style: "symbol",- };- const titles = getLegendTitles(groups, columnSettings);+ const titles = getLegendTitles(groups, currencyColumnSettings);expect(titles).toEqual(["$1.0k - $1.2k", "$2.0k - $2.5k", "$11.0k +"]);});@@ -47,10 +43,14 @@ describe("getLegendTitles", () => {await mockIsEmbeddingSdk();});- const setup = ({ sdkMetabaseInstanceUrl }) => {+ const setup = ({+ sdkMetabaseInstanceUrl,+ }: {+ sdkMetabaseInstanceUrl: string;+ }) => {return getMapUrl({ builtin: true, url: "api/geojson/world.json" },- { isSdk: true, sdkMetabaseInstanceUrl },+ { sdkMetabaseInstanceUrl },);};@@ -84,9 +84,10 @@ describe("getLegendTitles", () => {const url = getMapUrl({ builtin: false },{- isSdk: true,sdkMetabaseInstanceUrl: "http://mb-instance.example.com",- settings: { "map.region": "f3b71a29-5e4b-4d6c-8a1f-9c0e2d3a4b5c" },+ settings: {+ "map.region": "f3b71a29-5e4b-4d6c-8a1f-9c0e2d3a4b5c",+ },},);