Skip to content

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

Gdgt 1801 Leaflet components (#70299)

Jakub Chodorowicz6f4d71c279f9
diff --git a/frontend/src/metabase/visualizations/components/LeafletChoropleth.jsx b/frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx
similarity index 55%
rename from frontend/src/metabase/visualizations/components/LeafletChoropleth.jsx
rename to frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx
index 70124d67337..5d4dcb10328 100644
--- a/frontend/src/metabase/visualizations/components/LeafletChoropleth.jsx
+++ b/frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx
@@ -1,27 +1,49 @@
-/* eslint-disable react/prop-types */
import "leaflet/dist/leaflet.css";
+import type { Feature } from "geojson";
import L from "leaflet";
import CS from "metabase/css/core/index.css";
import { color } from "metabase/ui/utils/colors";
import { computeMinimalBounds } from "metabase/visualizations/lib/mapping";
+import type { GeoJSONData, Series } from "metabase-types/api";
import { CardRenderer } from "./CardRenderer";
+type FeatureInteraction = {
+ feature: Feature;
+ event: MouseEvent;
+};
+
+interface LeafletChoroplethProps {
+ series?: Series;
+ geoJson?: GeoJSONData;
+ minimalBounds?: L.LatLngBounds;
+ getColor?: (feature: Feature) => string;
+ onHoverFeature?: (payload: FeatureInteraction | null) => void;
+ onClickFeature?: (payload: FeatureInteraction) => void;
+ onRenderError?: (error?: unknown) => void;
+}
+
export const LeafletChoropleth = ({
series = [],
geoJson,
- minimalBounds = computeMinimalBounds(geoJson.features || [geoJson]),
+ minimalBounds = geoJson
+ ? computeMinimalBounds(
+ "features" in geoJson && Array.isArray(geoJson.features)
+ ? geoJson.features
+ : [geoJson],
+ )
+ : undefined,
getColor = () => color("brand"),
onHoverFeature = () => {},
onClickFeature = () => {},
onRenderError = () => {},
-}) => (
+}: LeafletChoroplethProps) => (
<CardRenderer
card={{ display: "map" }}
series={series}
className={CS.spread}
- renderer={(element, props) => {
+ renderer={(element: HTMLElement) => {
element.className = CS.spread;
element.style.backgroundColor = "transparent";
@@ -45,26 +67,26 @@ export const LeafletChoropleth = ({
keyboard: false,
});
- const style = (feature) => ({
- fillColor: getColor(feature),
+ const style = (feature?: Feature): L.PathOptions => ({
+ fillColor: feature ? getColor(feature) : color("brand"),
weight: 1,
opacity: 1,
color: "white",
fillOpacity: 1,
});
- const onEachFeature = (feature, layer) => {
+ const onEachFeature = (feature: Feature, layer: L.Layer) => {
layer.on({
- mousemove: (e) => {
+ mousemove: (e: L.LeafletMouseEvent) => {
onHoverFeature({
feature,
event: e.originalEvent,
});
},
- mouseout: (e) => {
+ mouseout: () => {
onHoverFeature(null);
},
- click: (e) => {
+ click: (e: L.LeafletMouseEvent) => {
onClickFeature({
feature,
event: e.originalEvent,
@@ -73,15 +95,19 @@ export const LeafletChoropleth = ({
});
};
- // main layer
- L.featureGroup([
- L.geoJson(geoJson, {
- style,
- onEachFeature,
- }),
- ]).addTo(map);
+ if (geoJson) {
+ // main layer
+ L.featureGroup([
+ L.geoJSON(geoJson, {
+ style,
+ onEachFeature,
+ }),
+ ]).addTo(map);
+ }
- map.fitBounds(minimalBounds);
+ if (minimalBounds) {
+ map.fitBounds(minimalBounds);
+ }
return () => {
map.remove();
diff --git a/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsx b/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.tsx
similarity index 50%
rename from frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsx
rename to frontend/src/metabase/visualizations/components/LeafletGridHeatMap.tsx
index f6f431968c4..f8815394b9c 100644
--- a/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.jsx
+++ b/frontend/src/metabase/visualizations/components/LeafletGridHeatMap.tsx
@@ -3,19 +3,38 @@ import L from "leaflet";
import { t } from "ttag";
import { color } from "metabase/lib/colors";
+import type { ClickObject, HoveredObject } from "metabase/visualizations/types";
import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
import { isMetric, isNumeric } from "metabase-lib/v1/types/utils/isa";
+import type { DatasetColumn } from "metabase-types/api";
import { computeNumericDataInterval } from "../lib/numeric";
-import { LeafletMap } from "./LeafletMap";
+import {
+ LeafletMap,
+ type LeafletMapPoint,
+ type LeafletMapProps,
+} from "./LeafletMap";
-const isValidCoordinatesColumn = (column) =>
- column.binning_info || (column.source === "native" && isNumeric(column));
+type GridHeatPoint = LeafletMapPoint<[number]>;
-export class LeafletGridHeatMap extends LeafletMap {
- static isSensible({ cols }) {
+type LeafletGridHeatMapProps = LeafletMapProps<GridHeatPoint> & {
+ min?: number;
+ max?: number;
+ onVisualizationClick?: ((clickObject: ClickObject | null) => void) | null;
+ onHoverChange?: ((hoverObject: HoveredObject | null) => void) | null;
+};
+
+const isValidCoordinatesColumn = (column: DatasetColumn | undefined) =>
+ !!column &&
+ (column.binning_info != null ||
+ (column.source === "native" && isNumeric(column)));
+
+export class LeafletGridHeatMap extends LeafletMap<LeafletGridHeatMapProps> {
+ gridLayer: L.LayerGroup | null = null;
+
+ static isSensible({ cols }: { cols: DatasetColumn[] }) {
return (
cols.filter(isValidCoordinatesColumn).length >= 2 &&
cols.filter(isMetric).length > 0
@@ -25,17 +44,28 @@ export class LeafletGridHeatMap extends LeafletMap {
componentDidMount() {
super.componentDidMount();
+ if (!this.map) {
+ return;
+ }
+
this.gridLayer = L.layerGroup([]).addTo(this.map);
- this.componentDidUpdate({}, {});
+ this.syncGridLayer();
}
- componentDidUpdate(prevProps, prevState) {
- super.componentDidUpdate(prevProps, prevState);
+ componentDidUpdate(prevProps: LeafletGridHeatMapProps) {
+ super.componentDidUpdate(prevProps);
+ this.syncGridLayer();
+ }
+ private syncGridLayer() {
try {
const { gridLayer } = this;
- const { points, min, max } = this.props;
+ if (!gridLayer) {
+ return;
+ }
+ const points = this.props.points ?? [];
+ const { min, max } = this.props;
const { latitudeColumn, longitudeColumn } = this._getLatLonColumns();
if (
!isValidCoordinatesColumn(latitudeColumn) ||
@@ -49,38 +79,45 @@ export class LeafletGridHeatMap extends LeafletMap {
const successColor = d3.rgb(color("success"));
const errorColor = d3.rgb(color("error"));
- const colorScale = d3
- .scaleLinear([min, max], [successColor, errorColor])
- .interpolate(d3.interpolateHcl);
+ const colorScale =
+ min == null || max == null
+ ? d3
+ .scaleLinear([successColor, errorColor])
+ .interpolate(d3.interpolateHcl)
+ : d3
+ .scaleLinear([min, max], [successColor, errorColor])
+ .interpolate(d3.interpolateHcl);
- const gridSquares = gridLayer.getLayers();
+ const gridSquares = gridLayer.getLayers().filter(isRectangleLayer);
const totalSquares = Math.max(points.length, gridSquares.length);
const latitudeValues = points.map((row) => row[latitudeIndex]);
const longitudeValues = points.map((row) => row[longitudeIndex]);
const latitudeBinning =
- latitudeColumn?.binning_info?.bin_width ??
+ latitudeColumn.binning_info?.bin_width ??
computeNumericDataInterval(latitudeValues);
const longitudeBinning =
- longitudeColumn?.binning_info?.bin_width ??
+ longitudeColumn.binning_info?.bin_width ??
computeNumericDataInterval(longitudeValues);
- for (let i = 0; i < totalSquares; i++) {
- if (i >= points.length) {
- gridLayer.removeLayer(gridSquares[i]);
+ for (let index = 0; index < totalSquares; index++) {
+ if (index >= points.length) {
+ gridLayer.removeLayer(gridSquares[index]);
}
- if (i >= gridSquares.length) {
- const gridSquare = this._createGridSquare(i);
+
+ if (index >= gridSquares.length) {
+ const gridSquare = this._createGridSquare(index);
gridLayer.addLayer(gridSquare);
gridSquares.push(gridSquare);
}
- if (i < points.length) {
- const [latitude, longitude, metric] = points[i];
+ if (index < points.length) {
+ const [latitude, longitude, metric] = points[index];
+ const gridSquare = gridSquares[index];
- gridSquares[i].setStyle({ color: colorScale(metric) });
+ gridSquare.setStyle({ color: colorScale(metric) });
const latMin = latitude;
const latMax = latitude + latitudeBinning;
@@ -88,15 +125,15 @@ export class LeafletGridHeatMap extends LeafletMap {
const lonMin = longitude;
const lonMax = longitude + longitudeBinning;
- gridSquares[i].setBounds([
+ gridSquare.setBounds([
[latMin, lonMin],
[latMax, lonMax],
]);
}
}
- } catch (err) {
- console.error(err);
- this.props.onRenderError(err.message || err);
+ } catch (error) {
+ console.error(error);
+ this.props.onRenderError(error instanceof Error ? error.message : error);
}
}
@@ -118,8 +155,8 @@ export class LeafletGridHeatMap extends LeafletMap {
return !isNative;
}
- _createGridSquare = (index) => {
- const bounds = [
+ _createGridSquare = (index: number): L.Rectangle => {
+ const bounds: L.LatLngBoundsLiteral = [
[54.559322, -5.767822],
[56.1210604, -3.02124],
];
@@ -128,7 +165,6 @@ export class LeafletGridHeatMap extends LeafletMap {
weight: 1,
stroke: true,
fillOpacity: 0.5,
- strokeOpacity: 1.0,
});
gridSquare.on("click", this._onVisualizationClick.bind(this, index));
gridSquare.on("mousemove", this._onHoverChange.bind(this, index));
@@ -136,53 +172,58 @@ export class LeafletGridHeatMap extends LeafletMap {
return gridSquare;
};
- _clickForPoint(index, e) {
- const {
- points,
- settings,
- series: [
- {
- data: { rows, cols },
- },
- ],
- } = this.props;
+ _clickForPoint(index: number, e: L.LeafletMouseEvent) {
+ const { settings, series } = this.props;
+ const points = this.props.points ?? [];
const point = points[index];
const metricColumn = this._getMetricColumn();
const { latitudeColumn, longitudeColumn } = this._getLatLonColumns();
+ const seriesEntry = series[0];
+ const rows = seriesEntry.data.rows;
+ const origin = { row: rows[index], cols: seriesEntry.data.cols };
+
return {
- value: point[2],
+ value: point?.[2],
column: metricColumn,
dimensions: [
{
- value: point[0],
+ value: point?.[0],
column: latitudeColumn,
},
{
- value: point[1],
+ value: point?.[1],
column: longitudeColumn,
},
],
event: e.originalEvent,
- origin: { row: rows[index], cols },
+ origin,
settings,
- };
+ } satisfies ClickObject;
}
- _onVisualizationClick(index, e) {
+ _onVisualizationClick(index: number, e: L.LeafletMouseEvent) {
const { onVisualizationClick } = this.props;
if (onVisualizationClick) {
onVisualizationClick(this._clickForPoint(index, e));
}
}
- _onHoverChange(index, e) {
+ _onHoverChange(index: number | null, event: L.LeafletMouseEvent) {
const { onHoverChange } = this.props;
if (onHoverChange) {
if (index == null) {
onHoverChange(null);
} else {
- onHoverChange(this._clickForPoint(index, e));
+ const hoveredObject = this._clickForPoint(
+ index,
+ event,
+ ) satisfies HoveredObject;
+ onHoverChange(hoveredObject);
}
}
}
}
+
+function isRectangleLayer(layer: L.Layer): layer is L.Rectangle {
+ return layer instanceof L.Rectangle;
+}
diff --git a/frontend/src/metabase/visualizations/components/LeafletMap.tsx b/frontend/src/metabase/visualizations/components/LeafletMap.tsx
index 45e978b169f..933cb2edf50 100644
--- a/frontend/src/metabase/visualizations/components/LeafletMap.tsx
+++ b/frontend/src/metabase/visualizations/components/LeafletMap.tsx
@@ -16,6 +16,14 @@ import type { Series } from "metabase-types/api";
import type { Point } from "metabase-types/api/dataset";
import { isObject } from "metabase-types/guards/common";
+export type LeafletMapPoint<TExtra extends unknown[] = []> = [
+ number,
+ number,
+ ...TExtra,
+];
+
+type AnyLeafletMapPoint = LeafletMapPoint<unknown[]>;
+
/**
* Checks if a hostname belongs to openstreetmap.org or one of its subdomains.
* Uses exact matching to prevent bypass via malicious domains like
@@ -36,13 +44,13 @@ type MapSettings = {
"map.zoom"?: number;
};
-export interface LeafletMapProps {
+export interface LeafletMapProps<TPoint extends AnyLeafletMapPoint = Point> {
className?: string;
width?: number;
height?: number;
bounds: L.LatLngBounds;
settings: MapSettings;
- points?: Point[] | null;
+ points?: TPoint[] | null;
series: Series;
metadata?: Metadata;
token?: string | null;
@@ -57,7 +65,9 @@ export interface LeafletMapProps {
onChangeCardAndRun: OnChangeCardAndRun;
}
-export class LeafletMap extends Component<LeafletMapProps> {
+export class LeafletMap<
+ T extends LeafletMapProps<AnyLeafletMapPoint> = LeafletMapProps,
+> extends Component<T> {
mapRef = createRef<HTMLDivElement>();
map: L.Map | null = null;
drawControl: L.Control.Draw | null = null;
@@ -126,6 +136,8 @@ export class LeafletMap extends Component<LeafletMapProps> {
const zoom = map.getZoom();
this.props.onMapZoomChange(zoom);
});
+
+ this.syncMapFromProps();
} catch (error) {
console.error(error);
this.props.onRenderError(
@@ -134,14 +146,18 @@ export class LeafletMap extends Component<LeafletMapProps> {
}
}
- componentDidUpdate(prevProps: LeafletMapProps) {
+ componentDidUpdate(prevProps: T) {
+ this.syncMapFromProps(prevProps);
+ }
+
+ protected syncMapFromProps(prevProps?: T) {
if (!this.map) {
return;
}
const { bounds, settings, zoomControl, zoom, lat, lng } = this.props;
- if (prevProps.zoomControl !== zoomControl) {
+ if (prevProps?.zoomControl !== zoomControl) {
if (zoomControl === false) {
this.map.zoomControl?.remove();
} else if (this.map.zoomControl) {
@@ -376,8 +392,8 @@ export class LeafletMap extends Component<LeafletMapProps> {
* so that we should recalculate the zoom.
*/
function shouldRecalculateZoom(
- prevPoints?: Point[] | null,
- nextPoints?: Point[] | null,
+ prevPoints?: LeafletMapPoint<unknown[]>[] | null,
+ nextPoints?: LeafletMapPoint<unknown[]>[] | null,
) {
if (!prevPoints && !nextPoints) {
return false;
diff --git a/frontend/src/metabase/visualizations/components/LeafletMarkerPinMap.jsx b/frontend/src/metabase/visualizations/components/LeafletMarkerPinMap.tsx
similarity index 66%
rename from frontend/src/metabase/visualizations/components/LeafletMarkerPinMap.jsx
rename to frontend/src/metabase/visualizations/components/LeafletMarkerPinMap.tsx
index a4bd72dacaf..c0a362873a8 100644
--- a/frontend/src/metabase/visualizations/components/LeafletMarkerPinMap.jsx
+++ b/frontend/src/metabase/visualizations/components/LeafletMarkerPinMap.tsx
@@ -2,14 +2,34 @@ import L from "leaflet";
import _ from "underscore";
import { getSubpathSafeUrl } from "metabase/lib/urls";
+import type { HoveredObject } from "metabase/visualizations/types";
+import type { ClickObject } from "metabase-lib";
import { isPK } from "metabase-lib/v1/types/utils/isa";
-import { LeafletMap } from "./LeafletMap";
+import {
+ LeafletMap,
+ type LeafletMapPoint,
+ type LeafletMapProps,
+} from "./LeafletMap";
+
+type IndexedPoint = LeafletMapPoint<[number]>;
+
+interface LeafletMarkerPinMapProps extends LeafletMapProps<IndexedPoint> {
+ onHoverChange?: (hoverObject?: HoveredObject | null) => void;
+ onVisualizationClick?: (clickObject: ClickObject | null) => void;
+}
+
+export class LeafletMarkerPinMap extends LeafletMap<LeafletMarkerPinMapProps> {
+ pinMarkerLayer: L.LayerGroup | null = null;
+ pinMarkerIcon: L.Icon | null = null;
-export class LeafletMarkerPinMap extends LeafletMap {
componentDidMount() {
super.componentDidMount();
+ if (!this.map) {
+ return;
+ }
+
this.pinMarkerLayer = L.layerGroup([]).addTo(this.map);
this.pinMarkerIcon = L.icon({
iconUrl: getSubpathSafeUrl("app/assets/img/pin.png"),
@@ -18,23 +38,28 @@ export class LeafletMarkerPinMap extends LeafletMap {
popupAnchor: [0, -13],
});
- this.componentDidUpdate({}, {});
+ this.syncMarkerLayer();
}
- componentDidUpdate(prevProps, prevState) {
- super.componentDidUpdate(prevProps, prevState);
+ componentDidUpdate(prevProps: LeafletMarkerPinMapProps) {
+ super.componentDidUpdate(prevProps);
+ this.syncMarkerLayer();
+ }
+ private syncMarkerLayer() {
try {
this._createMarkers(this.props.points);
} catch (err) {
console.error(err);
- this.props.onRenderError(err.message || err);
+ this.props.onRenderError(
+ err instanceof Error ? err.message : (err ?? undefined),
+ );
}
}
- _createMarkers = (points) => {
+ _createMarkers = (points?: IndexedPoint[] | null) => {
const { pinMarkerLayer } = this;
- if (!this.map) {
+ if (!this.map || !pinMarkerLayer || !points) {
return;
}
@@ -50,28 +75,30 @@ export class LeafletMarkerPinMap extends LeafletMap {
const crossesRightDateline = mapWest < 180 && mapEast > 180;
const shouldGetWrappedPoints = crossesLeftDateline || crossesRightDateline;
- const wrappedPoints = shouldGetWrappedPoints
+ const wrappedPoints: IndexedPoint[] = shouldGetWrappedPoints
? points.flatMap((point, index) => {
const [lat, lng] = point;
// we need to store the data index separately
// because the same point can have multiple markers
- const points = [[lat, lng, index]];
+ const wrapped: IndexedPoint[] = [[lat, lng, index]];
// note: for wide screens, we may need extra copies on both sides
if (crossesLeftDateline) {
// copy on the left side
- points.push([lat, lng - 360, index]);
+ wrapped.push([lat, lng - 360, index]);
}
if (crossesRightDateline) {
// copy on the right side
- points.push([lat, lng + 360, index]);
+ wrapped.push([lat, lng + 360, index]);
}
- return points;
+ return wrapped;
})
: points;
- const markers = pinMarkerLayer.getLayers();
+ const markers = pinMarkerLayer
+ .getLayers()
+ .filter((layer): layer is L.Marker => layer instanceof L.Marker);
const max = Math.max(wrappedPoints.length, markers.length);
for (let i = 0; i < max; i++) {
if (i >= wrappedPoints.length) {
@@ -92,7 +119,7 @@ export class LeafletMarkerPinMap extends LeafletMap {
const { lat, lng } = markers[i].getLatLng();
// if any marker doesn't match the point, update it
if (lng !== wrappedPoints[i][0] || lat !== wrappedPoints[i][1]) {
- markers[i].setLatLng(wrappedPoints[i].slice(0, 2));
+ markers[i].setLatLng([wrappedPoints[i][0], wrappedPoints[i][1]]);
// we need to re-attach the pointer events because the indexes might have changed from zooming
this._setupMarkerEvents(markers[i], index);
}
@@ -100,12 +127,14 @@ export class LeafletMarkerPinMap extends LeafletMap {
}
};
- _createMarker = (rowIndex) => {
- const marker = L.marker([0, 0], { icon: this.pinMarkerIcon });
+ _createMarker = (rowIndex: number) => {
+ const marker = L.marker([0, 0], {
+ ...(this.pinMarkerIcon ? { icon: this.pinMarkerIcon } : {}),
+ });
return this._setupMarkerEvents(marker, rowIndex);
};
- _setupMarkerEvents = (marker, rowIndex) => {
+ _setupMarkerEvents = (marker: L.Marker, rowIndex: number) => {
marker.off("mousemove");
marker.off("mouseout");
marker.off("click");
@@ -121,12 +150,12 @@ export class LeafletMarkerPinMap extends LeafletMap {
},
],
} = this.props;
- const hover = {
+ const hover: HoveredObject = {
dimensions: cols.map((col, colIndex) => ({
- value: rows[rowIndex][colIndex],
+ value: String(rows[rowIndex][colIndex] ?? ""),
column: col,
})),
- element: marker._icon,
+ element: marker.getElement(),
};
onHoverChange(hover);
});
@@ -159,8 +188,8 @@ export class LeafletMarkerPinMap extends LeafletMap {
onVisualizationClick({
value: hasPk ? rows[rowIndex][pkIndex] : null,
- column: hasPk ? cols[pkIndex] : null,
- element: marker._icon,
+ column: hasPk ? cols[pkIndex] : undefined,
+ element: marker.getElement(),
origin: { row: rows[rowIndex], cols },
settings,
data,
diff --git a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsx b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsx
deleted file mode 100644
index 77e3921b165..00000000000
--- a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.jsx
+++ /dev/null
@@ -1,146 +0,0 @@
-import L from "leaflet";
-
-import { EmbeddingEntityContext } from "metabase/embedding/context";
-import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import { GET } from "metabase/lib/api";
-import { isWithinIframe } from "metabase/lib/dom";
-
-import { getTileUrl } from "../lib/map";
-
-import { LeafletMap } from "./LeafletMap";
-
-export class LeafletTilePinMap extends LeafletMap {
- static contextType = EmbeddingEntityContext;
-
- componentDidMount() {
- super.componentDidMount();
-
- this.pinTileLayer = L.tileLayer("", {}).addTo(this.map);
-
- // Override only for SDK and not for cases when SDK is used under the hood for other embed types (Embed JS)
- if (isEmbeddingSdk() && !isWithinIframe()) {
- this._overrideCreateTileToUseFetch(this.pinTileLayer);
- }
-
- this.componentDidUpdate({}, {});
- }
-
- componentDidUpdate(prevProps, prevState) {
- super.componentDidUpdate(prevProps, prevState);
-
- try {
- const { pinTileLayer } = this;
- const newUrl = this._getTileUrl({ x: "{x}", y: "{y}" }, "{z}");
- if (newUrl !== pinTileLayer._url) {
- pinTileLayer.setUrl(newUrl);
- }
- } catch (err) {
- this.props.onRenderError(err.message || err);
- }
- }
-
- _getTileUrl = (coord, zoom) => {
- const [
- {
- card: { dataset_query, id },
- data,
- },
- ] = this.props.series;
-
- const { latitudeIndex, longitudeIndex } = this._getLatLonIndexes();
- const latitudeField = data.cols[latitudeIndex];
- const longitudeField = data.cols[longitudeIndex];
-
- if (!latitudeField || !longitudeField) {
- return;
- }
-
- const latFieldParam = JSON.stringify(latitudeField.field_ref);
- const lonFieldParam = JSON.stringify(longitudeField.field_ref);
-
- const { dashboard, dashcard } = this.props;
- // EmbeddingEntityContext is only available under embedding environment
- const { uuid, token } = this.context ?? {};
-
- return getTileUrl({
- cardId: id,
- dashboardId: dashboard?.id,
- dashcardId: dashcard?.id,
- zoom,
- coord,
- latField: latFieldParam,
- lonField: lonFieldParam,
- datasetQuery: dataset_query,
- uuid,
- token,
- datasetResult: this.props.series[0],
- });
- };
-
- /**
- * Overrides TileLayer.createTile to use fetch instead of setting img.src directly.
- * It's needed to be able to set custom headers (e.g. Authorization header for embedding).
- */
- _overrideCreateTileToUseFetch = (tileLayerInstance = {}) => {
- const onTileUnload = (event) => {
- const tile = event.tile;
-
- if (!tile) {
- return;
- }
-
- try {
- tile._fetchCtrl?.abort();
- } catch {}
- };
-
- tileLayerInstance.on("tileabort", onTileUnload);
- tileLayerInstance.on("tileunload", onTileUnload);
-
- tileLayerInstance.createTile = function (coords, done) {
- const tileUrl = this.getTileUrl(coords);
-
- const tile = document.createElement("img");
- tile.alt = "";
-
- if (!tileUrl) {
- done?.(null, tile);
-
- return tile;
- }
-
- const controller = new AbortController();
- tile._fetchCtrl = controller;
-
- GET(tileUrl, {
- fetch: true,
- signal: controller.signal,
- transformResponse: ({ response }) => response,
- })()
- .then((response) => response.blob())
- .then(async (blob) => {
- const reader = new FileReader();
-
- reader.onload = () => {
- tile.src = reader.result;
- };
-
- reader.readAsDataURL(blob);
- done?.(null, tile);
- })
- .catch((error) => {
- if (controller.signal.aborted) {
- return;
- }
-
- try {
- this._tileOnError(done, tile, error);
- } catch {
- done?.(error, tile);
- }
- });
-
- return tile;
- };
- };
-}
diff --git a/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx
new file mode 100644
index 00000000000..f309097dbfb
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/LeafletTilePinMap.tsx
@@ -0,0 +1,219 @@
+import L from "leaflet";
+import type { ContextType } from "react";
+
+import { EmbeddingEntityContext } from "metabase/embedding/context";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import { GET } from "metabase/lib/api";
+import { isWithinIframe } from "metabase/lib/dom";
+import type { DashboardId } from "metabase-types/api";
+
+import { getTileUrl } from "../lib/map";
+
+import { LeafletMap, type LeafletMapProps } from "./LeafletMap";
+
+type TileCoord = {
+ x: number | string;
+ y: number | string;
+};
+
+type TileImage = HTMLImageElement & {
+ _fetchCtrl?: AbortController;
+};
+
+type TileLayerWithInternals = L.TileLayer & {
+ _url?: string;
+ _tileOnError?: (
+ done: L.DoneCallback | undefined,
+ tile: HTMLElement,
+ error: unknown,
+ ) => void;
+ createTile: (coords: L.Coords, done?: L.DoneCallback) => HTMLElement;
+};
+
+function isTileLayerWithInternals(
+ tileLayer: L.TileLayer,
+): tileLayer is TileLayerWithInternals {
+ return (
+ "_url" in tileLayer &&
+ "_tileOnError" in tileLayer &&
+ "createTile" in tileLayer
+ );
+}
+
+function isTileImage(tile: unknown): tile is TileImage {
+ return tile instanceof HTMLImageElement;
+}
+
+interface LeafletTilePinMapProps extends LeafletMapProps {
+ dashboard?: {
+ id?: DashboardId | null;
+ } | null;
+ dashcard?: {
+ id?: number | null;
+ } | null;
+}
+
+export class LeafletTilePinMap extends LeafletMap<LeafletTilePinMapProps> {
+ static contextType = EmbeddingEntityContext;
+ // @ts-expect-error - see: https://linear.app/metabase/issue/GDGT-1891/migrate-babel-config-to-allowdeclarefields
+ context!: ContextType<typeof EmbeddingEntityContext>;
+
+ pinTileLayer: L.TileLayer | null = null;
+
+ componentDidMount() {
+ super.componentDidMount();
+
+ if (!this.map) {
+ return;
+ }
+
+ this.pinTileLayer = L.tileLayer("", {}).addTo(this.map);
+
+ // Override only for SDK and not for cases when SDK is used under the hood for other embed types (Embed JS)
+ if (isEmbeddingSdk() && !isWithinIframe()) {
+ this._overrideCreateTileToUseFetch(this.pinTileLayer);
+ }
+
+ this.componentDidUpdate(this.props);
+ }
+
+ componentDidUpdate(prevProps: LeafletTilePinMapProps) {
+ super.componentDidUpdate(prevProps);
+
+ try {
+ const { pinTileLayer } = this;
+ if (!pinTileLayer || !isTileLayerWithInternals(pinTileLayer)) {
+ return;
+ }
+
+ const newUrl = this._getTileUrl({ x: "{x}", y: "{y}" }, "{z}");
+ const currentUrl = pinTileLayer._url;
+ const nextUrl = newUrl ?? "";
+ if (nextUrl !== currentUrl) {
+ pinTileLayer.setUrl(nextUrl);
+ }
+ } catch (err: unknown) {
+ this.props.onRenderError(
+ err instanceof Error ? err.message : (err ?? undefined),
+ );
+ }
+ }
+
+ _getTileUrl = (
+ coord: TileCoord,
+ zoom: string | number,
+ ): string | undefined => {
+ const [datasetResult] = this.props.series;
+ if (!datasetResult) {
+ return undefined;
+ }
+
+ const { card, data } = datasetResult;
+ const cardId = card.id;
+
+ const { latitudeIndex, longitudeIndex } = this._getLatLonIndexes();
+ const latitudeField = data.cols[latitudeIndex];
+ const longitudeField = data.cols[longitudeIndex];
+
+ if (!latitudeField || !longitudeField) {
+ return undefined;
+ }
+
+ const latFieldParam = JSON.stringify(latitudeField.field_ref);
+ const lonFieldParam = JSON.stringify(longitudeField.field_ref);
+
+ const { dashboard, dashcard } = this.props;
+ // EmbeddingEntityContext is only available under embedding environment
+ const { uuid, token } = this.context ?? {};
+
+ return getTileUrl({
+ cardId,
+ dashboardId: dashboard?.id ?? undefined,
+ dashcardId: dashcard?.id ?? undefined,
+ zoom,
+ coord,
+ latField: latFieldParam,
+ lonField: lonFieldParam,
+ datasetQuery: card?.dataset_query,
+ uuid: uuid ?? undefined,
+ token: token ?? undefined,
+ parameters: datasetResult.json_query?.parameters ?? [],
+ });
+ };
+
+ /**
+ * Overrides TileLayer.createTile to use fetch instead of setting img.src directly.
+ * It's needed to be able to set custom headers (e.g. Authorization header for embedding).
+ */
+ _overrideCreateTileToUseFetch = (tileLayerInstance: L.TileLayer) => {
+ const onTileUnload = (event: L.TileEvent) => {
+ const { tile } = event;
+
+ try {
+ if (isTileImage(tile)) {
+ tile._fetchCtrl?.abort();
+ }
+ } catch {}
+ };
+
+ tileLayerInstance.on("tileunload", onTileUnload);
+
+ if (!isTileLayerWithInternals(tileLayerInstance)) {
+ return;
+ }
+
+ tileLayerInstance.createTile = function (
+ coords: L.Coords,
+ done?: L.DoneCallback,
+ ): HTMLElement {
+ const tileUrl = this.getTileUrl(coords);
+ const tile: TileImage = document.createElement("img");
+ tile.alt = "";
+
+ if (!tileUrl) {
+ done?.(undefined, tile);
+ return tile;
+ }
+
+ const controller = new AbortController();
+ tile._fetchCtrl = controller;
+
+ (
+ GET(tileUrl, {
+ fetch: true,
+ signal: controller.signal,
+ transformResponse: ({ response }: { response: Response }) => response,
+ // TODO: Remove casting after api.js is migrated to TS
+ })() as Promise<Response>
+ )
+ .then((response) => response.blob())
+ .then((blob) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ if (typeof reader.result === "string") {
+ tile.src = reader.result;
+ }
+ };
+
+ reader.readAsDataURL(blob);
+ done?.(undefined, tile);
+ })
+ .catch((error: unknown) => {
+ if (controller.signal.aborted) {
+ return;
+ }
+
+ try {
+ this._tileOnError?.(done, tile, error);
+ } catch {
+ done?.(
+ error instanceof Error ? error : new Error(String(error)),
+ tile,
+ );
+ }
+ });
+
+ return tile;
+ };
+ };
+}
diff --git a/frontend/src/metabase/visualizations/lib/map.ts b/frontend/src/metabase/visualizations/lib/map.ts
index 343372ebe91..4b0ef2b88a8 100644
--- a/frontend/src/metabase/visualizations/lib/map.ts
+++ b/frontend/src/metabase/visualizations/lib/map.ts
@@ -1,7 +1,7 @@
import { IS_EMBED_PREVIEW } from "metabase/lib/embed";
import { isJWT } from "metabase/lib/utils";
import { isUuid } from "metabase/lib/uuid";
-import type { DashboardId, Dataset, JsonQuery } from "metabase-types/api";
+import type { DashboardId, JsonQuery, Parameter } from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
interface TileCoordinate {
@@ -20,7 +20,7 @@ interface TileUrlParams {
datasetQuery?: JsonQuery;
uuid?: string;
token?: EntityToken;
- datasetResult?: Dataset;
+ parameters?: Parameter[];
/**
* Indicates whether the tile URL is being generated for a preview embed context.
* You probably don't need to set this manually as it defaults to `IS_EMBED_PREVIEW` (it's used for tests).
@@ -41,12 +41,10 @@ export function getTileUrl(params: TileUrlParams): string {
datasetQuery,
uuid,
token,
- datasetResult,
+ parameters,
isEmbedPreview = IS_EMBED_PREVIEW,
} = params;
- const parameters = datasetResult?.json_query?.parameters ?? [];
-
const isDashboard = dashboardId && dashcardId && cardId;
if (isDashboard) {
diff --git a/frontend/src/metabase/visualizations/lib/map.unit.spec.ts b/frontend/src/metabase/visualizations/lib/map.unit.spec.ts
index 9bf5ddddfc6..f8ef7f9d9cd 100644
--- a/frontend/src/metabase/visualizations/lib/map.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/lib/map.unit.spec.ts
@@ -1,5 +1,5 @@
-import type { JsonQuery } from "metabase-types/api";
-import { createMockDataset } from "metabase-types/api/mocks/dataset";
+import type { JsonQuery, Parameter } from "metabase-types/api";
+import { createMockParameter } from "metabase-types/api/mocks";
import { getTileUrl } from "./map";
@@ -9,7 +9,9 @@ describe("map", () => {
const zoom = "{z}";
const latField = "latitude";
const lonField = "longitude";
- const parameters = [{ id: "param1", value: "value1" }];
+ const parameters: Parameter[] = [
+ createMockParameter({ id: "param1", value: "value1" }),
+ ];
const encodedParameters = JSON.stringify(parameters);
describe("adhoc query", () => {
@@ -51,19 +53,13 @@ describe("map", () => {
});
it("should generate url for saved question with parameters", () => {
- const datasetResult = createMockDataset({
- json_query: {
- parameters,
- } as JsonQuery,
- });
-
const url = getTileUrl({
cardId: 123,
zoom,
coord,
latField,
lonField,
- datasetResult,
+ parameters,
});
expect(url).toBe(
@@ -114,12 +110,6 @@ describe("map", () => {
});
it("should generate url for dashboard with parameters", () => {
- const datasetResult = createMockDataset({
- json_query: {
- parameters,
- } as JsonQuery,
- });
-
const url = getTileUrl({
dashboardId: 10,
dashcardId: 20,
@@ -128,7 +118,7 @@ describe("map", () => {
coord,
latField,
lonField,
- datasetResult,
+ parameters,
});
expect(url).toBe(
@@ -154,12 +144,6 @@ describe("map", () => {
});
it("should generate url for public question with parameters", () => {
- const datasetResult = createMockDataset({
- json_query: {
- parameters,
- } as JsonQuery,
- });
-
const url = getTileUrl({
cardId: 123,
zoom,
@@ -167,7 +151,7 @@ describe("map", () => {
latField,
lonField,
uuid: "abc-123",
- datasetResult,
+ parameters,
});
expect(url).toBe(
@@ -196,12 +180,6 @@ describe("map", () => {
});
it("should generate url for public dashboard with parameters", () => {
- const datasetResult = createMockDataset({
- json_query: {
- parameters,
- } as JsonQuery,
- });
-
const url = getTileUrl({
// public dashboards have a uuid instead of an id
dashboardId: "621efc8c-9fd9-42db-a39a-1abdbfe23937",
@@ -212,7 +190,7 @@ describe("map", () => {
latField,
lonField,
uuid: "abc-123",
- datasetResult,
+ parameters,
});
expect(url).toBe(
@@ -238,11 +216,9 @@ describe("map", () => {
});
it("should generate url for embed question with parameters", () => {
- const datasetResult = createMockDataset({
- json_query: {
- parameters: [{ id: "original", value: "original" }],
- } as JsonQuery,
- });
+ const parametersOriginal = [
+ createMockParameter({ id: "original", value: "original" }),
+ ];
const url = getTileUrl({
cardId: 123,
@@ -251,12 +227,10 @@ describe("map", () => {
latField,
lonField,
token: "embed-token",
- datasetResult,
+ parameters: parametersOriginal,
});
- const expectedParameters = JSON.stringify([
- { id: "original", value: "original" },
- ]);
+ const expectedParameters = JSON.stringify(parametersOriginal);
expect(url).toBe(
`/api/embed/tiles/card/embed-token/${zoom}/${coord.x}/${coord.y}?latField=${encodeURIComponent(latField)}&lonField=${encodeURIComponent(lonField)}&parameters=${encodeURIComponent(expectedParameters)}`,
@@ -318,11 +292,9 @@ describe("map", () => {
});
it("should generate url for embed dashboard with parameters", () => {
- const datasetResult = createMockDataset({
- json_query: {
- parameters: [{ id: "original", value: "original" }],
- } as JsonQuery,
- });
+ const parametersOriginal = [
+ createMockParameter({ id: "original", value: "original" }),
+ ];
const url = getTileUrl({
dashboardId: jwt,
@@ -333,13 +305,10 @@ describe("map", () => {
latField,
lonField,
token: "embed-token",
- datasetResult,
+ parameters: parametersOriginal,
});
- const expectedParameters = JSON.stringify([
- { id: "original", value: "original" },
- ]);
-
+ const expectedParameters = JSON.stringify(parametersOriginal);
expect(url).toBe(
`/api/embed/tiles/dashboard/embed-token/dashcard/20/card/30/${zoom}/${coord.x}/${coord.y}?latField=${encodeURIComponent(latField)}&lonField=${encodeURIComponent(lonField)}&parameters=${encodeURIComponent(expectedParameters)}`,
);
diff --git a/frontend/src/metabase/visualizations/types/hover.ts b/frontend/src/metabase/visualizations/types/hover.ts
index 9d21261acb7..6901222caf1 100644
--- a/frontend/src/metabase/visualizations/types/hover.ts
+++ b/frontend/src/metabase/visualizations/types/hover.ts
@@ -9,7 +9,7 @@ export interface DataPoint extends ClickObjectDataRow {
}
export interface HoveredDimension {
- value: string;
+ value: RowValue;
column: RemappingHydratedDatasetColumn;
}