Skip to content

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

Migrate PinMap to a typed function component and extract a pure getPoints (#78067)

Andrei Chernykhf24e4bed1f55
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 5aa7867096f..e2aa3e84bb6 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -254,6 +254,9 @@ export type XAxisScale = "ordinal" | "histogram" | "timeseries" | NumericScale;
export type YAxisScale = NumericScale;
+export type MapType = "region" | "pin" | "heat" | "grid";
+export type PinMapStyle = "tiles" | "markers" | "grid" | "heat";
+
export type ColumnSettings = TimeOnlyOptions & {
_column_title_full?: string;
"pivot_table.column_show_totals"?: boolean;
@@ -522,6 +525,16 @@ export type VisualizationSettings = {
/** Show median values, all values, or no value labels. */
"boxplot.show_values_mode"?: BoxPlotShowValuesMode;
+ /** Map settings */
+ "map.type"?: MapType;
+ "map.pin_type"?: PinMapStyle;
+ "map.latitude_column"?: string;
+ "map.longitude_column"?: string;
+ "map.metric_column"?: string;
+ "map.center_latitude"?: number;
+ "map.center_longitude"?: number;
+ "map.zoom"?: number;
+
/** Columns selected for custom list view. */
"list.columns"?: ListViewColumns;
diff --git a/frontend/src/metabase/visualizations/components/LeafletMap.tsx b/frontend/src/metabase/visualizations/components/LeafletMap.tsx
index 8b7c69c3a03..48753e21986 100644
--- a/frontend/src/metabase/visualizations/components/LeafletMap.tsx
+++ b/frontend/src/metabase/visualizations/components/LeafletMap.tsx
@@ -12,7 +12,7 @@ import type { OnChangeCardAndRun } from "metabase/visualizations/types";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
-import type { Series } from "metabase-types/api";
+import type { Series, VisualizationSettings } from "metabase-types/api";
import type { Point } from "metabase-types/api/dataset";
import { isObject } from "metabase-types/guards/common";
@@ -35,14 +35,15 @@ export function isOpenStreetMapHost(hostname: string): boolean {
);
}
-type MapSettings = {
- "map.latitude_column"?: string;
- "map.longitude_column"?: string;
- "map.metric_column"?: string;
- "map.center_latitude"?: number;
- "map.center_longitude"?: number;
- "map.zoom"?: number;
-};
+type MapSettings = Pick<
+ VisualizationSettings,
+ | "map.latitude_column"
+ | "map.longitude_column"
+ | "map.metric_column"
+ | "map.center_latitude"
+ | "map.center_longitude"
+ | "map.zoom"
+>;
export interface LeafletMapProps<TPoint extends AnyLeafletMapPoint = Point> {
className?: string;
@@ -62,7 +63,7 @@ export interface LeafletMapProps<TPoint extends AnyLeafletMapPoint = Point> {
onMapZoomChange: (zoom: number) => void;
onRenderError: (error?: unknown) => void;
onFiltering: (filtering: boolean) => void;
- onChangeCardAndRun: OnChangeCardAndRun;
+ onChangeCardAndRun?: OnChangeCardAndRun | null;
}
export class LeafletMap<
@@ -325,7 +326,7 @@ export class LeafletMap<
const updatedQuestion = question.setQuery(updatedQuery);
const nextCard = updatedQuestion.card();
- onChangeCardAndRun({ nextCard });
+ onChangeCardAndRun?.({ nextCard });
}
this.props.onFiltering(false);
diff --git a/frontend/src/metabase/visualizations/components/PinMap.jsx b/frontend/src/metabase/visualizations/components/PinMap.jsx
deleted file mode 100644
index b846d8037eb..00000000000
--- a/frontend/src/metabase/visualizations/components/PinMap.jsx
+++ /dev/null
@@ -1,309 +0,0 @@
-/* eslint-disable react/prop-types */
-import cx from "classnames";
-import * as d3 from "d3";
-import L from "leaflet";
-import { Component } from "react";
-import { t } from "ttag";
-import _ from "underscore";
-
-import ButtonsS from "metabase/css/components/buttons.module.css";
-import CS from "metabase/css/core/index.css";
-import DashboardS from "metabase/css/dashboard.module.css";
-import { LatitudeLongitudeError } from "metabase/visualizations/lib/errors";
-import { hasLatitudeAndLongitudeColumns } from "metabase-lib/v1/types/utils/isa";
-
-import { LeafletGridHeatMap } from "./LeafletGridHeatMap";
-import { LeafletMarkerPinMap } from "./LeafletMarkerPinMap";
-import { LeafletTilePinMap } from "./LeafletTilePinMap";
-import S from "./PinMap.module.css";
-
-const WORLD_BOUNDS = [
- [-90, -180],
- [90, 180],
-];
-
-const MAP_COMPONENTS_BY_TYPE = {
- markers: LeafletMarkerPinMap,
- tiles: LeafletTilePinMap,
- grid: LeafletGridHeatMap,
-};
-
-export class PinMap extends Component {
- static getUiName = () => t`Pin Map`;
- static identifier = "pin_map";
- static iconName = "pinmap";
-
- static isSensible({ cols, rows }) {
- return hasLatitudeAndLongitudeColumns(cols);
- }
-
- static checkRenderable([
- {
- data: { cols, rows },
- },
- ]) {
- if (!hasLatitudeAndLongitudeColumns(cols)) {
- throw new LatitudeLongitudeError();
- }
- }
-
- state;
- _map = null;
-
- constructor(props) {
- super(props);
- this.state = {
- lat: null,
- lng: null,
- zoom: null,
- filtering: false,
- ...this._getPoints(props),
- };
- }
-
- UNSAFE_componentWillReceiveProps(newProps) {
- const SETTINGS_KEYS = [
- "map.latitude_column",
- "map.longitude_column",
- "map.metric_column",
- ];
- if (
- newProps.series[0].data !== this.props.series[0].data ||
- !_.isEqual(
- _.pick(newProps.settings, ...SETTINGS_KEYS),
- _.pick(this.props.settings, ...SETTINGS_KEYS),
- )
- ) {
- this.setState(this._getPoints(newProps));
- }
- }
-
- updateSettings = () => {
- const newSettings = {};
- if (this.state.lat != null) {
- newSettings["map.center_latitude"] = this.state.lat;
- }
- if (this.state.lng != null) {
- newSettings["map.center_longitude"] = this.state.lng;
- }
- if (this.state.zoom != null) {
- newSettings["map.zoom"] = this.state.zoom;
- }
- this.props.onUpdateVisualizationSettings(newSettings);
- this.setState({ lat: null, lng: null, zoom: null });
- };
-
- onMapCenterChange = (lat, lng) => {
- this.setState({ lat, lng });
- };
-
- onMapZoomChange = (zoom) => {
- this.setState({ zoom });
- };
-
- _getPoints(props) {
- const {
- settings,
- series: [
- {
- data: { cols, rows },
- },
- ],
- onUpdateWarnings,
- } = props;
- const latitudeIndex = _.findIndex(
- cols,
- (col) => col.name === settings["map.latitude_column"],
- );
- const longitudeIndex = _.findIndex(
- cols,
- (col) => col.name === settings["map.longitude_column"],
- );
- const metricIndex = _.findIndex(
- cols,
- (col) => col.name === settings["map.metric_column"],
- );
-
- const allPoints = rows.map((row) => [
- row[latitudeIndex],
- row[longitudeIndex],
- metricIndex >= 0 ? row[metricIndex] : 1,
- ]);
-
- // only use points with numeric coordinates & metric
- const validPoints = allPoints.map(([lat, lng, metric]) => {
- if (settings["map.type"] === "pin") {
- return lat != null && lng != null;
- }
-
- return lat != null && lng != null && metric != null;
- });
- const points = allPoints.filter((_, i) => validPoints[i]);
- const updatedRows = rows.filter((_, i) => validPoints[i]);
-
- const warnings = [];
- const filteredRows = allPoints.length - points.length;
- if (filteredRows > 0) {
- warnings.push(
- t`We filtered out ${filteredRows} row(s) containing null values.`,
- );
- }
- if (onUpdateWarnings && warnings) {
- onUpdateWarnings(warnings);
- }
-
- const bounds = L.latLngBounds(points.length > 0 ? points : WORLD_BOUNDS);
-
- const min = d3.min(points, (point) => point[2]);
- const max = d3.max(points, (point) => point[2]);
-
- const binWidth =
- cols[longitudeIndex] &&
- cols[longitudeIndex].binning_info &&
- cols[longitudeIndex].binning_info.bin_width;
- const binHeight =
- cols[latitudeIndex] &&
- cols[latitudeIndex].binning_info &&
- cols[latitudeIndex].binning_info.bin_width;
-
- if (binWidth != null) {
- bounds._northEast.lng += binWidth;
- }
- if (binHeight != null) {
- bounds._northEast.lat += binHeight;
- }
-
- return { rows: updatedRows, points, bounds, min, max, binWidth, binHeight };
- }
-
- render() {
- const { className, settings, isEditing, isDashboard, token } = this.props;
- const { lat, lng, zoom } = this.state;
-
- const isStaticEmbedding = !!token;
-
- const disableUpdateButton = lat == null && lng == null && zoom == null;
-
- const Map = MAP_COMPONENTS_BY_TYPE[settings["map.pin_type"]];
-
- const { rows, points, bounds, min, max, binHeight, binWidth } = this.state;
-
- const mapProps = { ...this.props };
- mapProps.series[0].data.rows = rows;
-
- // For static embedding we hide the button
- const shouldShowDefaultViewChangeButton =
- !isStaticEmbedding && (isEditing || !isDashboard);
-
- return (
- <div
- data-element-id="pin-map"
- className={cx(
- className,
- DashboardS.PinMap,
- CS.relative,
- CS.hoverParent,
- CS.hoverVisibility,
- )}
- onMouseDownCapture={(e) => e.stopPropagation() /* prevent dragging */}
- >
- {Map ? (
- <Map
- {...mapProps}
- ref={(map) => (this._map = map)}
- className={cx(
- CS.absolute,
- CS.top,
- CS.left,
- CS.bottom,
- CS.right,
- CS.z1,
- )}
- onMapCenterChange={this.onMapCenterChange}
- onMapZoomChange={this.onMapZoomChange}
- lat={lat}
- lng={lng}
- zoom={zoom}
- points={points}
- bounds={bounds}
- min={min}
- max={max}
- binWidth={binWidth}
- binHeight={binHeight}
- onFiltering={(filtering) => this.setState({ filtering })}
- zoomControl={!(isDashboard && isEditing)}
- onHoverChange={
- isDashboard && isEditing ? null : mapProps.onHoverChange
- }
- onVisualizationClick={
- isDashboard && isEditing ? null : mapProps.onVisualizationClick
- }
- />
- ) : null}
- <div
- className={cx(
- CS.absolute,
- CS.top,
- CS.right,
- CS.m1,
- CS.z2,
- CS.flex,
- CS.flexColumn,
- CS.hoverChild,
- )}
- >
- {shouldShowDefaultViewChangeButton ? (
- <div
- className={cx(
- "PinMapUpdateButton",
- ButtonsS.Button,
- ButtonsS.ButtonSmall,
- ButtonsS.ButtonWhite,
- S.pinMapButton,
- {
- [DashboardS.PinMapUpdateButtonDisabled]: disableUpdateButton,
- },
- )}
- onClick={this.updateSettings}
- >
- {t`Set as default view`}
- </div>
- ) : null}
- {!isDashboard &&
- this._map &&
- this._map.supportsFilter &&
- this._map.supportsFilter() && (
- <div
- className={cx(
- "PinMapUpdateButton",
- ButtonsS.Button,
- ButtonsS.ButtonSmall,
- ButtonsS.ButtonWhite,
- S.pinMapButton,
- )}
- onClick={() => {
- if (
- !this.state.filtering &&
- this._map &&
- this._map.startFilter
- ) {
- this._map.startFilter();
- } else if (
- this.state.filtering &&
- this._map &&
- this._map.stopFilter
- ) {
- this._map.stopFilter();
- }
- }}
- >
- {!this.state.filtering
- ? t`Draw box to filter`
- : t`Cancel filter`}
- </div>
- )}
- </div>
- </div>
- );
- }
-}
diff --git a/frontend/src/metabase/visualizations/components/PinMap.tsx b/frontend/src/metabase/visualizations/components/PinMap.tsx
new file mode 100644
index 00000000000..d1494860cac
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/PinMap.tsx
@@ -0,0 +1,340 @@
+import cx from "classnames";
+import * as d3 from "d3";
+import L from "leaflet";
+import { type ComponentClass, useCallback, useEffect, useState } from "react";
+import { t } from "ttag";
+
+import ButtonsS from "metabase/css/components/buttons.module.css";
+import CS from "metabase/css/core/index.css";
+import DashboardS from "metabase/css/dashboard.module.css";
+import type { VisualizationProps } from "metabase/visualizations/types";
+import type {
+ DatasetData,
+ PinMapStyle,
+ RowValue,
+ RowValues,
+ VisualizationSettings,
+} from "metabase-types/api";
+
+import { LeafletGridHeatMap } from "./LeafletGridHeatMap";
+import {
+ LeafletMap,
+ type LeafletMapPoint,
+ type LeafletMapProps,
+} from "./LeafletMap";
+import { LeafletMarkerPinMap } from "./LeafletMarkerPinMap";
+import { LeafletTilePinMap } from "./LeafletTilePinMap";
+import S from "./PinMap.module.css";
+
+const WORLD_BOUNDS: L.LatLngTuple[] = [
+ [-90, -180],
+ [90, 180],
+];
+
+// The child map classes declare narrower prop types than PinMapChildProps.
+const MAP_COMPONENTS_BY_TYPE = {
+ markers: LeafletMarkerPinMap,
+ tiles: LeafletTilePinMap,
+ grid: LeafletGridHeatMap,
+} as Partial<Record<PinMapStyle, ComponentClass<PinMapChildProps>>>;
+
+export type PinMapPoint = LeafletMapPoint<[number | null]>;
+
+export interface GetPointsResult {
+ rows: RowValues[];
+ points: PinMapPoint[];
+ bounds: L.LatLngBounds;
+ min: number | undefined;
+ max: number | undefined;
+ warnings: string[];
+}
+
+interface GetPointsParams {
+ data: DatasetData;
+ latitudeColumnName?: string;
+ longitudeColumnName?: string;
+ metricColumnName?: string;
+ isPinMap?: boolean;
+}
+
+export function getPoints({
+ data: { cols, rows },
+ latitudeColumnName,
+ longitudeColumnName,
+ metricColumnName,
+ isPinMap = false,
+}: GetPointsParams): GetPointsResult {
+ const latitudeIndex = cols.findIndex(
+ (col) => col.name === latitudeColumnName,
+ );
+ const longitudeIndex = cols.findIndex(
+ (col) => col.name === longitudeColumnName,
+ );
+ const metricIndex = cols.findIndex((col) => col.name === metricColumnName);
+
+ const allPoints = rows.map((row): [RowValue, RowValue, RowValue] => [
+ row[latitudeIndex],
+ row[longitudeIndex],
+ metricIndex >= 0 ? row[metricIndex] : 1,
+ ]);
+
+ // only use points with numeric coordinates & metric
+ const validPoints = allPoints.map(([lat, lng, metric]) => {
+ if (isPinMap) {
+ return lat != null && lng != null;
+ }
+
+ return lat != null && lng != null && metric != null;
+ });
+ const points = allPoints.filter(
+ (_point, i): _point is PinMapPoint => validPoints[i],
+ );
+ const updatedRows = rows.filter((_row, i) => validPoints[i]);
+
+ const warnings: string[] = [];
+ const filteredRows = allPoints.length - points.length;
+ if (filteredRows > 0) {
+ warnings.push(
+ t`We filtered out ${filteredRows} row(s) containing null values.`,
+ );
+ }
+
+ const boundsPoints: L.LatLngTuple[] =
+ points.length > 0
+ ? points.map(([lat, lng]): L.LatLngTuple => [lat, lng])
+ : WORLD_BOUNDS;
+ const bounds = L.latLngBounds(boundsPoints);
+
+ const min = d3.min(points, (point) => point[2]);
+ const max = d3.max(points, (point) => point[2]);
+
+ const binWidth = cols[longitudeIndex]?.binning_info?.bin_width;
+ const binHeight = cols[latitudeIndex]?.binning_info?.bin_width;
+
+ const northEast = bounds.getNorthEast();
+ if (binWidth != null) {
+ bounds.extend([northEast.lat, northEast.lng + binWidth]);
+ }
+ if (binHeight != null) {
+ bounds.extend([northEast.lat + binHeight, northEast.lng]);
+ }
+
+ return { rows: updatedRows, points, bounds, min, max, warnings };
+}
+
+interface PinMapProps extends VisualizationProps {
+ token?: string | null;
+}
+
+type PinMapChildProps = LeafletMapProps<PinMapPoint> & {
+ min?: number;
+ max?: number;
+ onHoverChange?: VisualizationProps["onHoverChange"] | null;
+ onVisualizationClick?: VisualizationProps["onVisualizationClick"] | null;
+ dashboard?: VisualizationProps["dashboard"];
+ dashcard?: VisualizationProps["dashcard"];
+};
+
+export function PinMap(props: PinMapProps) {
+ const {
+ className,
+ settings,
+ series,
+ isEditing,
+ isDashboard,
+ token,
+ onRender,
+ onUpdateVisualizationSettings,
+ onRenderError,
+ } = props;
+
+ const [lat, setLat] = useState<number | null>(null);
+ const [lng, setLng] = useState<number | null>(null);
+ const [zoom, setZoom] = useState<number | null>(null);
+ const [filtering, setFiltering] = useState(false);
+ const [mapInstance, setMapInstance] = useState<LeafletMap | null>(null);
+
+ const pointsInputs = {
+ data: series[0].data,
+ latitudeColumnName: settings["map.latitude_column"],
+ longitudeColumnName: settings["map.longitude_column"],
+ metricColumnName: settings["map.metric_column"],
+ };
+ const isPinMap = settings["map.type"] === "pin";
+
+ // A new points identity makes LeafletMap refit the viewport to the data
+ // bounds, so points must be recomputed only when the data or the mapped
+ // columns change; `map.type` is read at recompute time but must not trigger
+ // one, hence state adjusted during render instead of useMemo.
+ const [pointsCache, setPointsCache] = useState(() => ({
+ inputs: pointsInputs,
+ result: getPoints({ ...pointsInputs, isPinMap }),
+ }));
+ const { inputs } = pointsCache;
+ if (
+ inputs.data !== pointsInputs.data ||
+ inputs.latitudeColumnName !== pointsInputs.latitudeColumnName ||
+ inputs.longitudeColumnName !== pointsInputs.longitudeColumnName ||
+ inputs.metricColumnName !== pointsInputs.metricColumnName
+ ) {
+ setPointsCache({
+ inputs: pointsInputs,
+ result: getPoints({ ...pointsInputs, isPinMap }),
+ });
+ }
+ const { rows, points, bounds, min, max, warnings } = pointsCache.result;
+
+ // Report through onRender so Visualization merges these with its own
+ // warnings (e.g. truncation) instead of overwriting them.
+ useEffect(() => {
+ onRender({ warnings });
+ }, [onRender, warnings]);
+
+ const handleMapRef = useCallback((instance: unknown) => {
+ setMapInstance(instance instanceof LeafletMap ? instance : null);
+ }, []);
+
+ const updateSettings = () => {
+ const newSettings: VisualizationSettings = {};
+ if (lat != null) {
+ newSettings["map.center_latitude"] = lat;
+ }
+ if (lng != null) {
+ newSettings["map.center_longitude"] = lng;
+ }
+ if (zoom != null) {
+ newSettings["map.zoom"] = zoom;
+ }
+ onUpdateVisualizationSettings(newSettings);
+ setLat(null);
+ setLng(null);
+ setZoom(null);
+ };
+
+ const handleMapCenterChange = useCallback(
+ (nextLat: number, nextLng: number) => {
+ setLat(nextLat);
+ setLng(nextLng);
+ },
+ [],
+ );
+
+ const handleRenderError = useCallback(
+ (error?: unknown) => {
+ onRenderError(error == null ? undefined : String(error));
+ },
+ [onRenderError],
+ );
+
+ const isStaticEmbedding = Boolean(token);
+
+ const disableUpdateButton = lat == null && lng == null && zoom == null;
+
+ const pinType = settings["map.pin_type"];
+ const MapComponent = pinType ? MAP_COMPONENTS_BY_TYPE[pinType] : undefined;
+
+ const mapProps = { ...props };
+ mapProps.series[0].data.rows = rows;
+
+ // For static embedding we hide the button
+ const shouldShowDefaultViewChangeButton =
+ !isStaticEmbedding && (isEditing || !isDashboard);
+
+ return (
+ <div
+ data-element-id="pin-map"
+ className={cx(
+ className,
+ DashboardS.PinMap,
+ CS.relative,
+ CS.hoverParent,
+ CS.hoverVisibility,
+ )}
+ onMouseDownCapture={(e) => e.stopPropagation() /* prevent dragging */}
+ >
+ {MapComponent ? (
+ <MapComponent
+ {...mapProps}
+ ref={handleMapRef}
+ className={cx(
+ CS.absolute,
+ CS.top,
+ CS.left,
+ CS.bottom,
+ CS.right,
+ CS.z1,
+ )}
+ onMapCenterChange={handleMapCenterChange}
+ onMapZoomChange={setZoom}
+ onRenderError={handleRenderError}
+ lat={lat}
+ lng={lng}
+ zoom={zoom}
+ points={points}
+ bounds={bounds}
+ min={min}
+ max={max}
+ onFiltering={setFiltering}
+ zoomControl={!(isDashboard && isEditing)}
+ onHoverChange={isDashboard && isEditing ? null : props.onHoverChange}
+ onVisualizationClick={
+ isDashboard && isEditing ? null : props.onVisualizationClick
+ }
+ />
+ ) : null}
+ <div
+ className={cx(
+ CS.absolute,
+ CS.top,
+ CS.right,
+ CS.m1,
+ CS.z2,
+ CS.flex,
+ CS.flexColumn,
+ CS.hoverChild,
+ )}
+ >
+ {shouldShowDefaultViewChangeButton ? (
+ <div
+ className={cx(
+ "PinMapUpdateButton",
+ ButtonsS.Button,
+ ButtonsS.ButtonSmall,
+ ButtonsS.ButtonWhite,
+ S.pinMapButton,
+ {
+ [DashboardS.PinMapUpdateButtonDisabled]: disableUpdateButton,
+ },
+ )}
+ onClick={updateSettings}
+ >
+ {t`Set as default view`}
+ </div>
+ ) : null}
+ {!isDashboard && mapInstance?.supportsFilter() && (
+ <div
+ className={cx(
+ "PinMapUpdateButton",
+ ButtonsS.Button,
+ ButtonsS.ButtonSmall,
+ ButtonsS.ButtonWhite,
+ S.pinMapButton,
+ )}
+ onClick={() => {
+ if (!mapInstance) {
+ return;
+ }
+ if (filtering) {
+ mapInstance.stopFilter();
+ } else {
+ mapInstance.startFilter();
+ }
+ }}
+ >
+ {filtering ? t`Cancel filter` : t`Draw box to filter`}
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/metabase/visualizations/components/PinMap.unit.spec.ts b/frontend/src/metabase/visualizations/components/PinMap.unit.spec.ts
deleted file mode 100644
index 14dcd9673fb..00000000000
--- a/frontend/src/metabase/visualizations/components/PinMap.unit.spec.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { PinMap } from "metabase/visualizations/components/PinMap";
-
-describe("PinMap", () => {
- it("should filter out rows with null values in either the lat, long, or metric column", () => {
- const onUpdateWarnings = jest.fn();
- const data = {
- cols: ["lat", "lng", "metric"].map((name) => ({ name })),
- rows: [
- [null, 0, 0],
- [0, null, 0],
- [0, 0, null],
- [0, 0, 0],
- ],
- };
- const props = {
- settings: {
- "map.latitude_column": "lat",
- "map.longitude_column": "lng",
- "map.metric_column": "metric",
- },
- series: [{ data }],
- onUpdateWarnings,
- };
- const { points } = new PinMap(props)._getPoints(props);
-
- expect(points).toEqual([[0, 0, 0]]);
- expect(onUpdateWarnings.mock.calls[0][0]).toEqual([
- "We filtered out 3 row(s) containing null values.",
- ]);
- });
-
- it("should filter out rows only if the lat or long values are null for pin maps", () => {
- const onUpdateWarnings = jest.fn();
- const data = {
- cols: ["lat", "lng", "metric"].map((name) => ({ name })),
- rows: [
- [null, 0, 0],
- [0, null, 0],
- [0, 0, null],
- [1, 2, null],
- [0, 0, 0],
- ],
- };
- const props = {
- settings: {
- "map.latitude_column": "lat",
- "map.longitude_column": "lng",
- "map.metric_column": "metric",
- "map.type": "pin",
- },
- series: [{ data }],
- onUpdateWarnings,
- };
- const { points } = new PinMap(props)._getPoints(props);
-
- expect(points).toEqual([
- [0, 0, null],
- [1, 2, null],
- [0, 0, 0],
- ]);
- expect(onUpdateWarnings.mock.calls[0][0]).toEqual([
- "We filtered out 2 row(s) containing null values.",
- ]);
- });
-});
diff --git a/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx b/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx
new file mode 100644
index 00000000000..c042c791f26
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/PinMap.unit.spec.tsx
@@ -0,0 +1,265 @@
+import { render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+
+import { createMockMetadata } from "__support__/metadata";
+import MetabaseSettings from "metabase/utils/settings";
+import { createMockVisualizationProps } from "metabase/visualizations/types/mocks";
+import type { RowValue } from "metabase-types/api";
+import {
+ createMockColumn,
+ createMockDatasetData,
+ createMockSingleSeries,
+ createMockStructuredDatasetQuery,
+} from "metabase-types/api/mocks";
+import {
+ ORDERS_ID,
+ SAMPLE_DB_ID,
+ createSampleDatabase,
+} from "metabase-types/api/mocks/presets";
+
+import { PinMap, getPoints } from "./PinMap";
+
+const createData = (cols: string[], rows: RowValue[][]) =>
+ createMockDatasetData({
+ cols: cols.map((name) => createMockColumn({ name })),
+ rows,
+ });
+
+describe("getPoints", () => {
+ it("should filter out rows with null values in either the lat, long, or metric column", () => {
+ const { points, warnings } = getPoints({
+ data: createData(
+ ["lat", "lng", "metric"],
+ [
+ [null, 0, 0],
+ [0, null, 0],
+ [0, 0, null],
+ [0, 0, 0],
+ ],
+ ),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ });
+
+ expect(points).toEqual([[0, 0, 0]]);
+ expect(warnings).toEqual([
+ "We filtered out 3 row(s) containing null values.",
+ ]);
+ });
+
+ it("should filter out rows only if the lat or long values are null for pin maps", () => {
+ const { points, warnings } = getPoints({
+ data: createData(
+ ["lat", "lng", "metric"],
+ [
+ [null, 0, 0],
+ [0, null, 0],
+ [0, 0, null],
+ [1, 2, null],
+ [0, 0, 0],
+ ],
+ ),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ isPinMap: true,
+ });
+
+ expect(points).toEqual([
+ [0, 0, null],
+ [1, 2, null],
+ [0, 0, 0],
+ ]);
+ expect(warnings).toEqual([
+ "We filtered out 2 row(s) containing null values.",
+ ]);
+ });
+
+ it("should return no warnings when no rows are filtered out", () => {
+ const { points, warnings } = getPoints({
+ data: createData(
+ ["lat", "lng", "metric"],
+ [
+ [0, 0, 0],
+ [1, 2, 3],
+ ],
+ ),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ });
+
+ expect(points).toEqual([
+ [0, 0, 0],
+ [1, 2, 3],
+ ]);
+ expect(warnings).toEqual([]);
+ });
+
+ it("should fall back to world bounds when all rows are filtered out", () => {
+ const { points, bounds, warnings } = getPoints({
+ data: createData(["lat", "lng", "metric"], [[null, null, null]]),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ });
+
+ expect(points).toEqual([]);
+ expect([
+ bounds.getSouth(),
+ bounds.getWest(),
+ bounds.getNorth(),
+ bounds.getEast(),
+ ]).toEqual([-90, -180, 90, 180]);
+ expect(warnings).toEqual([
+ "We filtered out 1 row(s) containing null values.",
+ ]);
+ });
+
+ it("should extend the bounds by one bin to the north/east for binned coordinates", () => {
+ const { bounds } = getPoints({
+ data: createMockDatasetData({
+ cols: [
+ createMockColumn({ name: "lat", binning_info: { bin_width: 2 } }),
+ createMockColumn({ name: "lng", binning_info: { bin_width: 3 } }),
+ createMockColumn({ name: "metric" }),
+ ],
+ rows: [[10, 20, 1]],
+ }),
+ latitudeColumnName: "lat",
+ longitudeColumnName: "lng",
+ metricColumnName: "metric",
+ });
+
+ expect([
+ bounds.getSouth(),
+ bounds.getWest(),
+ bounds.getNorth(),
+ bounds.getEast(),
+ ]).toEqual([10, 20, 12, 23]);
+ });
+});
+
+describe("PinMap", () => {
+ const setup = ({
+ isDashboard = false,
+ token,
+ }: { isDashboard?: boolean; token?: string } = {}) => {
+ const onRender = jest.fn();
+
+ const series = [
+ createMockSingleSeries(
+ {
+ dataset_query: createMockStructuredDatasetQuery({
+ database: SAMPLE_DB_ID,
+ query: { "source-table": ORDERS_ID },
+ }),
+ },
+ {
+ data: createData(
+ ["lat", "lng"],
+ [
+ [10, 20],
+ [null, 30],
+ ],
+ ),
+ },
+ ),
+ ];
+
+ const props = createMockVisualizationProps({
+ series,
+ rawSeries: series,
+ data: series[0].data,
+ card: series[0].card,
+ settings: {
+ "map.type": "pin",
+ "map.pin_type": "markers",
+ "map.latitude_column": "lat",
+ "map.longitude_column": "lng",
+ },
+ metadata: createMockMetadata({ databases: [createSampleDatabase()] }),
+ isDashboard,
+ height: 300,
+ onRender,
+ });
+
+ const { rerender } = render(<PinMap {...props} token={token} />);
+
+ return { onRender, props, rerender };
+ };
+
+ beforeEach(() => {
+ jest.spyOn(MetabaseSettings, "get").mockImplementation((key: string) => {
+ if (key === "map-tile-server-url") {
+ return "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
+ }
+ return null;
+ });
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("should render the 'Set as default view' button with the PinMapUpdateButton class", () => {
+ setup();
+
+ const button = screen.getByText("Set as default view");
+ expect(button).toHaveClass("PinMapUpdateButton");
+ });
+
+ it("should render the 'Draw box to filter' button outside dashboards", async () => {
+ setup();
+
+ const button = await screen.findByText("Draw box to filter");
+ expect(button).toHaveClass("PinMapUpdateButton");
+ });
+
+ it("should report rows filtered out because of null coordinates through onRender", () => {
+ const { onRender } = setup();
+
+ expect(onRender).toHaveBeenCalledWith({
+ warnings: ["We filtered out 1 row(s) containing null values."],
+ });
+ });
+
+ it("should not render the 'Set as default view' button for static embedding", () => {
+ setup({ token: "token" });
+
+ expect(screen.queryByText("Set as default view")).not.toBeInTheDocument();
+ });
+
+ it("should not render either map button on dashboards outside editing", async () => {
+ setup({ isDashboard: true });
+
+ expect(await screen.findByText("OpenStreetMap")).toBeInTheDocument();
+ expect(screen.queryByText("Set as default view")).not.toBeInTheDocument();
+ expect(screen.queryByText("Draw box to filter")).not.toBeInTheDocument();
+ });
+
+ it("should toggle the filter button label when starting a box filter", async () => {
+ setup();
+
+ await userEvent.click(await screen.findByText("Draw box to filter"));
+
+ expect(screen.getByText("Cancel filter")).toBeInTheDocument();
+ expect(screen.queryByText("Draw box to filter")).not.toBeInTheDocument();
+ });
+
+ it("should clear the map instance when switching to a pin type with no renderer", async () => {
+ const { props, rerender } = setup();
+
+ expect(await screen.findByText("Draw box to filter")).toBeInTheDocument();
+
+ rerender(
+ <PinMap
+ {...props}
+ settings={{ ...props.settings, "map.pin_type": "heat" }}
+ />,
+ );
+
+ expect(screen.queryByText("Draw box to filter")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/visualizations/types/mocks.ts b/frontend/src/metabase/visualizations/types/mocks.ts
new file mode 100644
index 00000000000..4cff9af60b4
--- /dev/null
+++ b/frontend/src/metabase/visualizations/types/mocks.ts
@@ -0,0 +1,42 @@
+import {
+ createMockCard,
+ createMockDatasetData,
+} from "metabase-types/api/mocks";
+
+import type { VisualizationProps } from "./visualization";
+
+export function createMockVisualizationProps(
+ opts?: Partial<VisualizationProps>,
+): VisualizationProps {
+ return {
+ card: createMockCard(),
+ data: createMockDatasetData({}),
+ series: [],
+ rawSeries: [],
+ settings: {},
+ fontFamily: "Lato",
+ isFullscreen: false,
+ isQueryBuilder: false,
+ isEmbeddingSdk: false,
+ showTitle: false,
+ isDashboard: false,
+ isDocument: false,
+ isVisualizer: false,
+ isVisualizerCard: false,
+ isEditing: false,
+ isMetricsViewer: false,
+ isMobile: false,
+ isSettings: false,
+ width: 500,
+ height: 500,
+ visualizationIsClickable: () => false,
+ onRender: () => undefined,
+ onRenderError: () => undefined,
+ onActionDismissal: () => undefined,
+ onHoverChange: () => undefined,
+ onVisualizationClick: () => undefined,
+ onUpdateVisualizationSettings: () => undefined,
+ dispatch: () => undefined,
+ ...opts,
+ };
+}