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: convert Map visualization to typescript (#70374)
Uladzimir Havenchyk09b2415b60c6
diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.jsxdeleted file mode 100644index e8f4f0e1fa2..00000000000--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.jsx+++ /dev/null@@ -1,443 +0,0 @@-/* eslint-disable react/prop-types */-import cx from "classnames";-import Color from "color";-import * as d3 from "d3";-import { Component } from "react";-import ss from "simple-statistics";-import { jt, t } from "ttag";-import _ from "underscore";--import { getMetabaseInstanceUrl } from "embedding-sdk-bundle/store/selectors";-import { Link } from "metabase/common/components/Link";-import { LoadingSpinner } from "metabase/common/components/LoadingSpinner";-import CS from "metabase/css/core/index.css";-import { isEmbeddingSdk } from "metabase/embedding-sdk/config";-import { connect, useSelector } from "metabase/redux";-import { getUserIsAdmin } from "metabase/selectors/user";-import { Flex, Text } from "metabase/ui";-import MetabaseSettings from "metabase/utils/settings";-import { MinColumnsError } from "metabase/visualizations/lib/errors";-import { formatValue } from "metabase/visualizations/lib/formatting";-import {- computeMinimalBounds,- getCanonicalRowKey,-} from "metabase/visualizations/lib/mapping";-import {- getDefaultSize,- getMinSize,-} from "metabase/visualizations/shared/utils/sizes";-import { isMetric, isString } from "metabase-lib/v1/types/utils/isa";--import { ChartWithLegend } from "./ChartWithLegend";-import { LeafletChoropleth } from "./LeafletChoropleth";-import { LegacyChoropleth } from "./LegacyChoropleth";--// TODO COLOR-// eslint-disable-next-line metabase/no-color-literals-const HEAT_MAP_COLORS = ["#C4E4FF", "#81C5FF", "#51AEFF", "#1E96FF", "#0061B5"];-// eslint-disable-next-line metabase/no-color-literals-const HEAT_MAP_ZERO_COLOR = "#CCC";--export function getColorplethColorScale(- color,- { lightness = 92, darken = 0.2, darkenLast = 0.3, saturate = 0.1 } = {},-) {- const lightColor = Color(color).lightness(lightness).saturate(saturate);-- const darkColor = Color(color).darken(darken).saturate(saturate);-- const scale = d3.scaleLinear(- [0, 1],- [lightColor.string(), darkColor.string()],- );-- const colors = d3.range(0, 1.25, 0.25).map((value) => scale(value));-- if (darkenLast) {- colors[colors.length - 1] = Color(color)- .darken(darkenLast)- .saturate(saturate)- .string();- }-- return colors;-}--const geoJsonCache = new Map();--function loadGeoJson(geoJsonPath, callback) {- if (geoJsonCache.has(geoJsonPath)) {- setTimeout(() => callback(geoJsonCache.get(geoJsonPath)), 0);- return;- }-- d3.json(geoJsonPath).then((json) => {- geoJsonCache.set(geoJsonPath, json);- callback(json);- });-}--export function getLegendTitles(groups, columnSettings) {- const formatMetric = (value, compact) =>- formatValue(value, { ...columnSettings, compact });-- const compact = shouldUseCompactFormatting(groups, formatMetric);-- return groups.map((group, index) => {- const min = formatMetric(group[0], compact);- const max = formatMetric(group[group.length - 1], compact);- return index === groups.length - 1- ? `${min} +` // the last value in the list- : min !== max- ? `${min} - ${max}` // typical case- : min; // special case to avoid zero-width ranges e.g. $88-$88- });-}--// if the average formatted length is greater than this, we switch to compact formatting-const AVERAGE_LENGTH_CUTOFF = 5;--function shouldUseCompactFormatting(groups, formatMetric) {- const minValues = groups.map(([x]) => x);- const maxValues = groups.slice(0, -1).map((group) => group[group.length - 1]);- const allValues = minValues.concat(maxValues);- const formattedValues = allValues.map((value) => formatMetric(value, false));- const averageLength =- formattedValues.reduce((sum, { length }) => sum + length, 0) /- formattedValues.length;- return averageLength > AVERAGE_LENGTH_CUTOFF;-}--const mapStateToProps = (state) => ({- sdkMetabaseInstanceUrl: getMetabaseInstanceUrl(state),-});--const connector = connect(mapStateToProps, null);--const ensureTrailingSlash = (url) => (url.endsWith("/") ? url : url + "/");--export function getMapUrl(details, props) {- const mapUrl = details.builtin- ? details.url- : "api/geojson/" + props.settings["map.region"];-- if (!isEmbeddingSdk() || !props?.sdkMetabaseInstanceUrl) {- return mapUrl;- }-- const baseUrl = new URL(props.sdkMetabaseInstanceUrl, window.location.origin)- .href;-- // if the second parameter ends with a slash, it will join them together- // new URL("/sub-path", "http://example.org/proxy/") => "http://example.org/proxy/sub-path"- return new URL(mapUrl, ensureTrailingSlash(baseUrl)).href;-}--const MapNotFound = () => {- const isAdmin = useSelector(getUserIsAdmin);- return (- <Flex direction="column" m="auto" maw="25rem">- <div className={cx(CS.textCentered, CS.mb4, CS.px2)}>- <Text component="p">- {t`Looks like this custom map is no longer available. Try using a different map to visualize this.`}- </Text>- {isAdmin && (- <Text component="p" className={CS.mt1}>- {jt`To add a new map, visit ${(- <Link key="link" to="/admin/settings/maps" className={CS.link}>- {t`Admin settings > Maps`}- </Link>- )}.`}- </Text>- )}- </div>- </Flex>- );-};--class ChoroplethMapInner extends Component {- static propTypes = {};-- static minSize = getMinSize("map");- static defaultSize = getDefaultSize("map");-- static isSensible({ cols }) {- return cols.filter(isString).length > 0 && cols.filter(isMetric).length > 0;- }-- static checkRenderable([- {- data: { cols, rows },- },- ]) {- if (cols.length < 2) {- throw new MinColumnsError(2);- }- }-- constructor(props, context) {- super(props, context);- this.state = {- geoJson: null,- geoJsonPath: null,- };- }-- UNSAFE_componentWillMount() {- this.UNSAFE_componentWillReceiveProps(this.props);- }-- _getDetails(props) {- return MetabaseSettings.get("custom-geojson", {})[- props.settings["map.region"]- ];- }-- UNSAFE_componentWillReceiveProps(nextProps) {- const details = this._getDetails(nextProps);-- if (details) {- const geoJsonPath = getMapUrl(details, nextProps);-- if (this.state.geoJsonPath !== geoJsonPath) {- this.setState({- geoJson: null,- geoJsonPath: geoJsonPath,- });- loadGeoJson(geoJsonPath, (geoJson) => {- this.setState({- geoJson: geoJson,- geoJsonPath: geoJsonPath,- minimalBounds: computeMinimalBounds(geoJson?.features ?? []),- });- });- }- }- }-- render() {- const details = this._getDetails(this.props);- if (!details) {- return <MapNotFound />;- }-- const {- series,- className,- gridSize,- hovered,- onHoverChange,- visualizationIsClickable,- onVisualizationClick,- settings,- } = this.props;- const { geoJson, minimalBounds } = this.state;-- // special case builtin maps to use legacy choropleth map- let projection, projectionFrame;- // 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 nameProperty = details.region_name;- const keyProperty = details.region_key;-- if (!geoJson) {- return (- <div className={cx(className, CS.flex, CS.layoutCentered)}>- <LoadingSpinner />- </div>- );- }-- const [- {- data: { cols, rows },- },- ] = series;- const dimensionIndex = _.findIndex(- cols,- (col) => col.name === settings["map.dimension"],- );- const metricIndex = _.findIndex(- cols,- (col) => col.name === settings["map.metric"],- );-- const getRowKey = (row) =>- getCanonicalRowKey(row[dimensionIndex], settings["map.region"]);- const getRowValue = (row) => row[metricIndex] || 0;-- const getFeatureName = (feature) =>- String(feature.properties[nameProperty]);- const getFeatureKey = (feature, { lowerCase = true } = {}) => {- const key = String(feature.properties[keyProperty]);- return lowerCase ? key.toLowerCase() : key;- };-- const getFeatureValue = (feature) => valuesMap[getFeatureKey(feature)];-- const rowByFeatureKey = new Map(rows.map((row) => [getRowKey(row), row]));-- const getFeatureClickObject = (row, feature) =>- row == null- ? // This branch lets you click on empty regions. We use in dashboard cross-filtering.- {- value: null,- column: cols[metricIndex],- dimensions: [],- data: feature- ? [- {- value: getFeatureKey(feature, { lowerCase: false }),- col: cols[dimensionIndex],- },- ]- : [],- origin: { row, cols },- settings,- }- : {- value: row[metricIndex],- column: cols[metricIndex],- dimensions: [- {- value: row[dimensionIndex],- column: cols[dimensionIndex],- },- ],- data: row.map((value, index) => ({- 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 isClickable = onVisualizationClick != null;-- const onClickFeature =- isClickable &&- ((click) => {- const featureKey = getFeatureKey(click.feature);- const row = rowByFeatureKey.get(featureKey);- const clickData = {- ...getFeatureClickObject(row, click.feature),- event: click.event,- };-- if (onVisualizationClick && visualizationIsClickable(clickData)) {- onVisualizationClick(clickData);- }- });- const onHoverFeature =- onHoverChange &&- ((hover) => {- const row = hover && rowByFeatureKey.get(getFeatureKey(hover.feature));- if (row && onHoverChange) {- onHoverChange({- ...getFeatureClickObject(row, hover.feature),- event: hover.event,- });- } else if (onHoverChange) {- onHoverChange(null);- }- });-- const valuesMap = {};- for (const row of rows) {- const key = getRowKey(row);- const value = getRowValue(row);- valuesMap[key] = (valuesMap[key] || 0) + value;- }- const domainSet = new Set(Object.values(valuesMap));- const domain = Array.from(domainSet);-- const _heatMapColors = settings["map.colors"] || 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(groupBoundaries, heatMapColors);-- const columnSettings = settings.column(cols[metricIndex]);- const legendTitles = getLegendTitles(groups, columnSettings);-- const getColor = (feature) => {- const value = getFeatureValue(feature);- return value == null ? HEAT_MAP_ZERO_COLOR : colorScale(value);- };-- let aspectRatio;- if (projection) {- const [[minX, minY], [maxX, maxY]] = projectionFrame.map(projection);- aspectRatio = (maxX - minX) / (maxY - minY);- } else {- aspectRatio =- (minimalBounds.getEast() - minimalBounds.getWest()) /- (minimalBounds.getNorth() - minimalBounds.getSouth());- }-- return (- <ChartWithLegend- className={className}- aspectRatio={aspectRatio}- legendTitles={legendTitles}- legendColors={heatMapColors}- gridSize={gridSize}- hovered={hovered}- onHoverChange={onHoverChange}- isDashboard={this.props.isDashboard}- isDocument={this.props.isDocument}- isMetricsViewer={this.props.isMetricsViewer}- >- {projection ? (- <LegacyChoropleth- series={series}- geoJson={geoJson}- getColor={getColor}- onHoverFeature={onHoverFeature}- onClickFeature={onClickFeature}- projection={projection}- projectionFrame={projectionFrame}- onRenderError={this.props.onRenderError}- />- ) : (- <LeafletChoropleth- series={series}- geoJson={geoJson}- getColor={getColor}- onHoverFeature={onHoverFeature}- onClickFeature={onClickFeature}- minimalBounds={minimalBounds}- onRenderError={this.props.onRenderError}- />- )}- </ChartWithLegend>- );- }-}--export const ChoroplethMap = connector(ChoroplethMapInner);diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsxnew file mode 100644index 00000000000..021a6e0e82a--- /dev/null+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx@@ -0,0 +1,561 @@+import cx from "classnames";+import Color from "color";+import * as d3 from "d3";+import type { Feature, FeatureCollection } from "geojson";+import type L from "leaflet";+import { useEffect, useState } from "react";+import ss from "simple-statistics";+import { jt, t } from "ttag";+import _ from "underscore";++import { Link } from "metabase/common/components/Link";+import { LoadingSpinner } from "metabase/common/components/LoadingSpinner";+import CS from "metabase/css/core/index.css";+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";+import { connect, useSelector } from "metabase/redux";+import type { State } from "metabase/redux/store";+import { getUserIsAdmin } from "metabase/selectors/user";+import { Flex, Text } from "metabase/ui";+import MetabaseSettings from "metabase/utils/settings";+import { MinColumnsError } from "metabase/visualizations/lib/errors";+import { formatValue } from "metabase/visualizations/lib/formatting";+import {+ computeMinimalBounds,+ getCanonicalRowKey,+} from "metabase/visualizations/lib/mapping";+import {+ getDefaultSize,+ getMinSize,+} from "metabase/visualizations/shared/utils/sizes";+import type {+ ColumnSettings,+ VisualizationDefinition,+ VisualizationProps,+} from "metabase/visualizations/types";+import { isMetric, isString } from "metabase-lib/v1/types/utils/isa";+import type {+ CustomGeoJSONMap,+ GeoJSONData,+ RowValue,+ VisualizationSettings,+} from "metabase-types/api";++import { ChartWithLegend } from "./ChartWithLegend";+import { LeafletChoropleth } from "./LeafletChoropleth";+import { LegacyChoropleth } from "./LegacyChoropleth";++// TODO COLOR+// eslint-disable-next-line metabase/no-color-literals+const HEAT_MAP_COLORS = ["#C4E4FF", "#81C5FF", "#51AEFF", "#1E96FF", "#0061B5"];+// eslint-disable-next-line metabase/no-color-literals+const HEAT_MAP_ZERO_COLOR = "#CCC";++type ColorScaleOptions = {+ lightness?: number;+ darken?: number;+ darkenLast?: number;+ saturate?: number;+};++export function getColorplethColorScale(+ color: string,+ {+ lightness = 92,+ darken = 0.2,+ darkenLast = 0.3,+ saturate = 0.1,+ }: ColorScaleOptions = {},+): string[] {+ const lightColor = Color(color).lightness(lightness).saturate(saturate);+ const darkColor = Color(color).darken(darken).saturate(saturate);++ const scale = d3.scaleLinear<string>(+ [0, 1],+ [lightColor.string(), darkColor.string()],+ );++ const colors = d3.range(0, 1.25, 0.25).map((value) => scale(value));++ if (darkenLast) {+ colors[colors.length - 1] = Color(color)+ .darken(darkenLast)+ .saturate(saturate)+ .string();+ }++ return colors;+}++const geoJsonCache = new Map<string, GeoJSONData>();++function loadGeoJson(+ geoJsonPath: string,+ callback: (json: GeoJSONData) => void,+) {+ const cached = geoJsonCache.get(geoJsonPath);+ if (cached) {+ setTimeout(() => callback(cached), 0);+ return;+ }++ d3.json<GeoJSONData>(geoJsonPath).then((json) => {+ if (json) {+ geoJsonCache.set(geoJsonPath, json);+ callback(json);+ }+ });+}++export function getLegendTitles(+ groups: number[][],+ columnSettings: ColumnSettings,+): string[] {+ const formatMetric = (value: number, compact: boolean): string =>+ String(formatValue(value, { ...columnSettings, compact }));++ const compact = shouldUseCompactFormatting(groups, formatMetric);++ return groups.map((group, index) => {+ const min = formatMetric(group[0], compact);+ const max = formatMetric(group[group.length - 1], compact);+ return index === groups.length - 1+ ? `${min} +` // the last value in the list+ : min !== max+ ? `${min} - ${max}` // typical case+ : min; // special case to avoid zero-width ranges e.g. $88-$88+ });+}++// if the average formatted length is greater than this, we switch to compact formatting+const AVERAGE_LENGTH_CUTOFF = 5;++function shouldUseCompactFormatting(+ groups: number[][],+ formatMetric: (value: number, compact: boolean) => string,+): boolean {+ const minValues = groups.map(([x]) => x);+ const maxValues = groups.slice(0, -1).map((group) => group[group.length - 1]);+ const allValues = minValues.concat(maxValues);+ const formattedValues = allValues.map((value) => formatMetric(value, false));+ const averageLength =+ formattedValues.reduce((sum, { length }) => sum + length, 0) /+ formattedValues.length;+ return averageLength > AVERAGE_LENGTH_CUTOFF;+}++type ChoroplethStateProps = {+ sdkMetabaseInstanceUrl?: string;+};++type StateWithMaybeSdk = State & {+ sdk?: { metabaseInstanceUrl?: string };+};++const mapStateToProps = (state: StateWithMaybeSdk): ChoroplethStateProps => ({+ sdkMetabaseInstanceUrl: state.sdk?.metabaseInstanceUrl,+});++const connector = connect(mapStateToProps, null);++const ensureTrailingSlash = (url: string): string =>+ url.endsWith("/") ? url : url + "/";++type GetMapUrlDetails = {+ builtin?: boolean;+ url?: string;+};++type GetMapUrlProps = {+ sdkMetabaseInstanceUrl?: string;+ settings?: VisualizationSettings;+};++export function getMapUrl(+ details: GetMapUrlDetails,+ props: GetMapUrlProps,+): string {+ const mapUrl = details.builtin+ ? (details.url ?? "")+ : `api/geojson/${props.settings?.["map.region"] ?? ""}`;++ if (!isEmbeddingSdk() || !props.sdkMetabaseInstanceUrl) {+ return mapUrl;+ }++ const baseUrl = new URL(props.sdkMetabaseInstanceUrl, window.location.origin)+ .href;++ // if the second parameter ends with a slash, it will join them together+ // new URL("/sub-path", "http://example.org/proxy/") => "http://example.org/proxy/sub-path"+ return new URL(mapUrl, ensureTrailingSlash(baseUrl)).href;+}++const MapNotFound = () => {+ const isAdmin = useSelector(getUserIsAdmin);+ return (+ <Flex direction="column" m="auto" maw="25rem">+ <div className={cx(CS.textCentered, CS.mb4, CS.px2)}>+ <Text component="p">+ {t`Looks like this custom map is no longer available. Try using a different map to visualize this.`}+ </Text>+ {isAdmin && (+ <Text component="p" className={CS.mt1}>+ {jt`To add a new map, visit ${(+ <Link key="link" to="/admin/settings/maps" className={CS.link}>+ {t`Admin settings > Maps`}+ </Link>+ )}.`}+ </Text>+ )}+ </div>+ </Flex>+ );+};++type ChoroplethMapProps = VisualizationProps & ChoroplethStateProps;++type ChoroplethMapState = {+ geoJson: GeoJSONData | null;+ geoJsonPath: string | null;+ minimalBounds?: L.LatLngBounds;+};++type Projection = d3.GeoProjection | null;+type ProjectionFrame = [[number, number], [number, number]];++function isFeatureCollection(value: GeoJSONData): value is FeatureCollection {+ return value.type === "FeatureCollection";+}++function getFeatures(geoJson: GeoJSONData): Feature[] {+ return isFeatureCollection(geoJson) ? geoJson.features : [geoJson];+}++function getDetails(+ settings: ChoroplethMapProps["settings"],+): CustomGeoJSONMap | undefined {+ const customGeoJson = MetabaseSettings.get("custom-geojson") ?? {};+ const region = settings["map.region"];+ 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;++ const [state, setState] = useState<ChoroplethMapState>({+ geoJson: null,+ geoJsonPath: null,+ });++ useEffect(() => {+ if (!geoJsonPath) {+ return;+ }+ let cancelled = false;+ setState({ geoJson: null, geoJsonPath });+ loadGeoJson(geoJsonPath, (geoJson) => {+ if (!cancelled) {+ setState({+ geoJson,+ geoJsonPath,+ minimalBounds: computeMinimalBounds(getFeatures(geoJson)),+ });+ }+ });+ return () => {+ cancelled = true;+ };+ }, [geoJsonPath]);++ if (!details) {+ return <MapNotFound />;+ }++ const { geoJson, minimalBounds } = state;++ // 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 nameProperty = details.region_name;+ const keyProperty = details.region_key;++ if (!geoJson) {+ return (+ <div className={cx(className, CS.flex, CS.layoutCentered)}>+ <LoadingSpinner />+ </div>+ );+ }++ const [+ {+ data: { cols, rows },+ },+ ] = series;+ const dimensionIndex = _.findIndex(+ cols,+ (col) => col.name === settings["map.dimension"],+ );+ const metricIndex = _.findIndex(+ cols,+ (col) => col.name === settings["map.metric"],+ );++ const getRowKey = (row: RowValue[]): string =>+ getCanonicalRowKey(row[dimensionIndex], settings["map.region"]);+ const getRowValue = (row: RowValue[]): number => {+ const value = row[metricIndex];+ return typeof value === "number" ? value : 0;+ };++ const getFeatureName = (feature: Feature): string =>+ String(feature.properties?.[nameProperty]);+ const getFeatureKey = (+ feature: Feature,+ { lowerCase = true }: { lowerCase?: boolean } = {},+ ): string => {+ const key = String(feature.properties?.[keyProperty]);+ 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 getFeatureValue = (feature: Feature): number | undefined =>+ valuesMap[getFeatureKey(feature)];++ const rowByFeatureKey = new Map<string, RowValue[]>(+ 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 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);+ }+ }+ : 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),+ event: hover.event,+ });+ } else {+ onHoverChange(null);+ }+ }+ : 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 columnSettings = settings.column?.(cols[metricIndex]) ?? {};+ const legendTitles = getLegendTitles(groups, columnSettings);++ const getColor = (feature: Feature): string => {+ const value = getFeatureValue(feature);+ 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 onLegendHoverChange = onHoverChange+ ? (hover?: { index: number; element?: HTMLElement | null } | null) => {+ if (hover) {+ onHoverChange({+ index: hover.index,+ element: hover.element ?? undefined,+ });+ } else {+ onHoverChange(null);+ }+ }+ : undefined;++ const propagateRenderError = (error?: unknown) => {+ onRenderError(error == null ? undefined : String(error));+ };++ return (+ <ChartWithLegend+ className={className}+ aspectRatio={aspectRatio}+ legendTitles={legendTitles}+ legendColors={heatMapColors}+ gridSize={gridSize}+ hovered={hovered}+ onHoverChange={onLegendHoverChange}+ isDashboard={isDashboard}+ isDocument={isDocument}+ isMetricsViewer={isMetricsViewer}+ >+ {projection ? (+ <LegacyChoropleth+ series={series}+ geoJson={geoJson}+ getColor={getColor}+ onHoverFeature={onHoverFeature}+ onClickFeature={onClickFeature}+ projection={projection}+ projectionFrame={projectionFrame}+ />+ ) : (+ <LeafletChoropleth+ series={series}+ geoJson={geoJson}+ getColor={getColor}+ onHoverFeature={onHoverFeature}+ onClickFeature={onClickFeature}+ minimalBounds={minimalBounds}+ onRenderError={propagateRenderError}+ />+ )}+ </ChartWithLegend>+ );+}++const choroplethStatics: Pick<+ VisualizationDefinition,+ "minSize" | "defaultSize" | "isSensible" | "checkRenderable"+> = {+ minSize: getMinSize("map"),+ defaultSize: getDefaultSize("map"),+ isSensible: ({ cols }) =>+ cols.filter(isString).length > 0 && cols.filter(isMetric).length > 0,+ checkRenderable: (series) => {+ const {+ data: { cols },+ } = series[0];+ if (cols.length < 2) {+ throw new MinColumnsError(2);+ }+ },+};++export const ChoroplethMap = Object.assign(+ connector(ChoroplethMapInner),+ choroplethStatics,+);diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.tsindex be64ecf9a6e..95b163e6a83 100644--- a/frontend/src/metabase/visualizations/types/visualization.ts+++ b/frontend/src/metabase/visualizations/types/visualization.ts@@ -1,5 +1,9 @@import type { CSSProperties, ComponentType, ReactNode } from "react";+import type {+ ColorRangeSelectorAttributes,+ ColorRangeSelectorProps,+} from "metabase/common/components/ColorRangeSelector/ColorRangeSelector";import type { Dispatch, QueryBuilderMode } from "metabase/redux/store";import type { IconProps } from "metabase/ui";import type { ColorGetter } from "metabase/ui/colors/types";@@ -516,6 +520,17 @@ export type VisualizationSettingsDefinitions = {"line.style"?: SingleSeriesSettingDefinition<Value, Props>;"link.text"?: SeriesSettingDefinition<Value, Props>;"link.url"?: SeriesSettingDefinition<Value, Props>;+ "map.pin_type"?: SeriesSettingDefinition<Value, Props>;+ "map.type"?: SeriesSettingDefinition<Value, Props>;+ "map.region"?: SeriesSettingDefinition<Value, Props>;+ "map.colors"?: SeriesSettingDefinition<+ Value,+ Omit<ColorRangeSelectorProps, keyof ColorRangeSelectorAttributes>+ >;+ "map.heat.radius"?: SeriesSettingDefinition<Value, Props>;+ "map.heat.blur"?: SeriesSettingDefinition<Value, Props>;+ "map.heat.min-opacity"?: SeriesSettingDefinition<Value, Props>;+ "map.heat.max-zoom"?: SeriesSettingDefinition<Value, Props>;markdown_template?: DatasetColumnSettingDefinition<Value, Props>;number_separators?: DatasetColumnSettingDefinition<Value, Props>;number_style?: DatasetColumnSettingDefinition<Value, Props>;diff --git a/frontend/src/metabase/visualizations/visualizations/Map/Map.jsx b/frontend/src/metabase/visualizations/visualizations/Map/Map.tsxsimilarity index 69%rename from frontend/src/metabase/visualizations/visualizations/Map/Map.jsxrename to frontend/src/metabase/visualizations/visualizations/Map/Map.tsxindex b23e0fd2fd9..ee0acf1522f 100644--- a/frontend/src/metabase/visualizations/visualizations/Map/Map.jsx+++ b/frontend/src/metabase/visualizations/visualizations/Map/Map.tsx@@ -1,5 +1,4 @@-/* eslint-disable react/prop-types */-import { Component } from "react";+import { memo } from "react";import { t } from "ttag";import _ from "underscore";@@ -18,6 +17,10 @@ import {getDefaultSize,getMinSize,} from "metabase/visualizations/shared/utils/sizes";+import type {+ VisualizationDefinition,+ VisualizationProps,+} from "metabase/visualizations/types";import {hasLatitudeAndLongitudeColumns,isCountry,@@ -28,6 +31,7 @@ import {isNumeric,isState,} from "metabase-lib/v1/types/utils/isa";+import type { CustomGeoJSONMap } from "metabase-types/api";import {ChoroplethMap,@@ -38,29 +42,51 @@ import { PinMap } from "../../components/PinMap";import { CustomMapFooter } from "./CustomMapFooter";-const PIN_MAP_TYPES = new Set(["pin", "heat", "grid"]);+const PIN_MAP_VALUES = ["pin", "heat", "grid"] as const;+type PinMapValue = (typeof PIN_MAP_VALUES)[number];-export class Map extends Component {- static getUiName = () => t`Map`;- static identifier = "map";- static iconName = "pinmap";+function isPinMapType(value: unknown): value is PinMapValue {+ return PIN_MAP_VALUES.some((v) => v === value);+}++const MAP_DISPLAY_ALIASES = ["state", "country", "pin_map"] as const;- static aliases = ["state", "country", "pin_map"];+function MapComponent(props: VisualizationProps) {+ const { settings } = props;+ const type = settings["map.type"];- static minSize = getMinSize("map");- static defaultSize = getDefaultSize("map");+ if (isPinMapType(type)) {+ return <PinMap {...props} />;+ }- static isSensible({ cols, rows }) {- return (- PinMap.isSensible({ cols, rows }) ||- ChoroplethMap.isSensible({ cols, rows }) ||- LeafletGridHeatMap.isSensible({ cols, rows })- );+ if (type === "region") {+ return <ChoroplethMap {...props} />;}- static hasEmptyState = true;+ return null;+}++function arePropsEqual(prev: VisualizationProps, next: VisualizationProps) {+ const sameSize = prev.width === next.width && prev.height === next.height;+ const sameSeries = isSameSeries(prev.series, next.series);+ const sameIsEditing = prev.isEditing === next.isEditing;- static settings = {+ return sameSize && sameSeries && sameIsEditing;+}++const MAP_VIZ_DEFINITION: VisualizationDefinition = {+ getUiName: () => t`Map`,+ identifier: "map",+ iconName: "pinmap",+ aliases: [...MAP_DISPLAY_ALIASES],+ minSize: getMinSize("map"),+ defaultSize: getDefaultSize("map"),+ isSensible: (data) =>+ PinMap.isSensible(data) ||+ Boolean(ChoroplethMap.isSensible?.(data)) ||+ LeafletGridHeatMap.isSensible(data),+ hasEmptyState: true,+ settings: {...columnSettings({ getHidden: () => true }),"map.type": {get title() {@@ -85,7 +111,8 @@ export class Map extends Component {],}),getDefault: ([{ card, data }], settings) => {- switch (card.display) {+ const display: string = card.display;+ switch (display) {case "state":case "country":return "region";@@ -99,6 +126,7 @@ export class Map extends Component {const longitudeColumn = _.findWhere(data.cols, {name: settings["map.longitude_column"],});+if (latitudeColumn &&longitudeColumn &&@@ -150,8 +178,8 @@ export class Map extends Component {: data.rows.length >= 1000? "tiles": "markers",- getHidden: (series, vizSettings) =>- !PIN_MAP_TYPES.has(vizSettings["map.type"]),+ getHidden: (_series, vizSettings) =>+ !isPinMapType(vizSettings["map.type"]),},...fieldSetting("map.latitude_column", {get title() {@@ -159,8 +187,8 @@ export class Map extends Component {},fieldFilter: isNumeric,getDefault: ([{ data }]) => (_.find(data.cols, isLatitude) || {}).name,- getHidden: (series, vizSettings) =>- !PIN_MAP_TYPES.has(vizSettings["map.type"]),+ getHidden: (_series, vizSettings) =>+ !isPinMapType(vizSettings["map.type"]),}),...fieldSetting("map.longitude_column", {get title() {@@ -168,16 +196,16 @@ export class Map extends Component {},fieldFilter: isNumeric,getDefault: ([{ data }]) => (_.find(data.cols, isLongitude) || {}).name,- getHidden: (series, vizSettings) =>- !PIN_MAP_TYPES.has(vizSettings["map.type"]),+ getHidden: (_series, vizSettings) =>+ !isPinMapType(vizSettings["map.type"]),}),...fieldSetting("map.metric_column", {get title() {return t`Metric field`;},fieldFilter: isMetric,- getHidden: (series, vizSettings) =>- !PIN_MAP_TYPES.has(vizSettings["map.type"]) ||+ getHidden: (_series, vizSettings) =>+ !isPinMapType(vizSettings["map.type"]) ||(vizSettings["map.pin_type"] !== "heat" &&vizSettings["map.pin_type"] !== "grid"),}),@@ -187,24 +215,28 @@ export class Map extends Component {},widget: "select",getDefault: ([{ card, data }]) => {- if (card.display === "state" || _.any(data.cols, isState)) {+ const display: string = card.display;+ if (display === "state" || _.any(data.cols, isState)) {return "us_states";- } else if (card.display === "country" || _.any(data.cols, isCountry)) {+ } else if (display === "country" || _.any(data.cols, isCountry)) {return "world_countries";}return null;},getProps: () => ({- options: _.chain(MetabaseSettings.get("custom-geojson", {}))+ options: _.chain(MetabaseSettings.get("custom-geojson") ?? {}).pairs()- .map(([key, value]) => ({ name: value.name || "", value: key }))+ .map(([key, value]: [string, CustomGeoJSONMap]) => ({+ name: value.name || "",+ value: key,+ })).sortBy((x) => x.name.toLowerCase()).value(),placeholder: t`Select a region`,footer: <CustomMapFooter />,hiddenIcons: true,}),- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "region",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "region",},...metricSetting("map.metric", {get title() {@@ -215,7 +247,7 @@ export class Map extends Component {data: { cols },},]) => cols.find(isMetric)?.name,- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "region",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "region",}),...dimensionSetting("map.dimension", {get title() {@@ -232,7 +264,7 @@ export class Map extends Component {}return cols.find(isDimension)?.name;},- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "region",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "region",}),"map.colors": {get title() {@@ -249,11 +281,11 @@ export class Map extends Component {),isQuantile: true,}),- getDefault: (series, vizSettings) =>+ getDefault: (_series, vizSettings) =>getColorplethColorScale(getPreferredColor(vizSettings["map.metric"]) ?? getAccentColors()[0],),- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "region",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "region",readDependencies: ["map.metric"],},"map.zoom": {},@@ -265,7 +297,7 @@ export class Map extends Component {},widget: "number",getDefault: () => 30,- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "heat",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "heat",},"map.heat.blur": {get title() {@@ -273,7 +305,7 @@ export class Map extends Component {},widget: "number",getDefault: () => 60,- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "heat",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "heat",},"map.heat.min-opacity": {get title() {@@ -281,7 +313,7 @@ export class Map extends Component {},widget: "number",getDefault: () => 0,- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "heat",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "heat",},"map.heat.max-zoom": {get title() {@@ -289,12 +321,13 @@ export class Map extends Component {},widget: "number",getDefault: () => 1,- getHidden: (series, vizSettings) => vizSettings["map.type"] !== "heat",+ getHidden: (_series, vizSettings) => vizSettings["map.type"] !== "heat",},- };+ },+ checkRenderable: (_series, settings) => {+ const type = settings["map.type"];- static checkRenderable([{ data }], settings) {- if (PIN_MAP_TYPES.has(settings["map.type"])) {+ if (isPinMapType(type)) {if (!settings["map.longitude_column"] ||!settings["map.latitude_column"]@@ -304,7 +337,7 @@ export class Map extends Component {{ section: t`Data` },);}- } else if (settings["map.type"] === "region") {+ } else if (type === "region") {if (!settings["map.region"]) {throw new ChartSettingsError(t`Please select a region map.`, {section: t`Data`,@@ -317,24 +350,10 @@ export class Map extends Component {);}}- }+ },+};- shouldComponentUpdate(nextProps, nextState) {- const sameSize =- this.props.width === nextProps.width &&- this.props.height === nextProps.height;- const sameSeries = isSameSeries(this.props.series, nextProps.series);- const sameIsEditing = this.props.isEditing === nextProps.isEditing;- return !(sameSize && sameSeries && sameIsEditing);- }-- render() {- const { settings } = this.props;- const type = settings["map.type"];- if (PIN_MAP_TYPES.has(type)) {- return <PinMap {...this.props} />;- } else if (type === "region") {- return <ChoroplethMap {...this.props} />;- }- }-}+export const Map = Object.assign(+ memo(MapComponent, arePropsEqual),+ MAP_VIZ_DEFINITION,+);diff --git a/frontend/src/types/global.d.ts b/frontend/src/types/global.d.tsindex 0808e987c98..752c6b1ecc6 100644--- a/frontend/src/types/global.d.ts+++ b/frontend/src/types/global.d.ts@@ -65,4 +65,12 @@ declare module "*.css" {declare module "iframe-resizer/js/iframeResizer.contentWindow.js";+declare module "simple-statistics" {+ const ss: {+ ckmeans: (data: number[], nClusters: number) => number[][];+ };+ // eslint-disable-next-line import/no-default-export -- third-party module declaration+ export default ss;+}+type Nullable<T> = T | null;