Skip to content

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

Lazy load `leaflet` (#75222)

Romeo Van Snicke5b06223a1e2
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts
index 10a24c444bb..0da0dde9c9e 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-specific-imports.ts
@@ -18,6 +18,14 @@ import "./polyfill/use-sync-external-store";
import "html2canvas-pro";
import "jspdf";
+/**
+ * The map renderer (and leaflet) is lazily chunk-split in the main app, but the
+ * SDK bundle can't fetch on-demand chunks at runtime. Importing it eagerly here
+ * pulls it into the preloaded SDK bundle so the `import()` in `Map.tsx` resolves
+ * from an already-loaded chunk instead of 404ing.
+ */
+import "metabase/visualizations/visualizations/Map/MapRenderer";
+
// react-virtualized powers the pivot table grid and is lazily imported in the
// main app. The SDK bundle can't fetch on-demand chunks at runtime, so force the
// pivot table module to be included eagerly here.
diff --git a/frontend/src/metabase/admin/settings/components/widgets/CustomGeoJSONWidget.tsx b/frontend/src/metabase/admin/settings/components/widgets/CustomGeoJSONWidget.tsx
index 860c6f838f9..06b8d14bc8a 100644
--- a/frontend/src/metabase/admin/settings/components/widgets/CustomGeoJSONWidget.tsx
+++ b/frontend/src/metabase/admin/settings/components/widgets/CustomGeoJSONWidget.tsx
@@ -1,5 +1,12 @@
import cx from "classnames";
-import { type ChangeEvent, memo, useCallback, useState } from "react";
+import {
+ type ChangeEvent,
+ Suspense,
+ lazy,
+ memo,
+ useCallback,
+ useState,
+} from "react";
import { t } from "ttag";
import noResultsSource from "assets/img/no_results.svg";
@@ -13,7 +20,6 @@ import ButtonsS from "metabase/css/components/buttons.module.css";
import CS from "metabase/css/core/index.css";
import { Button, Ellipsified, Image, Modal, Stack, Text } from "metabase/ui";
import { uuid } from "metabase/utils/uuid";
-import { LeafletChoropleth } from "metabase/visualizations/components/LeafletChoropleth";
import type {
CustomGeoJSONMap,
CustomGeoJSONSetting,
@@ -499,8 +505,18 @@ interface ChoroplethPreviewProps {
geoJson: GeoJSONData | undefined;
}
+// leaflet (~225KB) is loaded lazily here so it stays out of the admin bundle
+// until someone actually previews a custom GeoJSON map.
+const LeafletChoropleth = lazy(() =>
+ import("metabase/visualizations/components/LeafletChoropleth").then(
+ (module) => ({ default: module.LeafletChoropleth }),
+ ),
+);
+
const ChoroplethPreview = memo(({ geoJson }: ChoroplethPreviewProps) => (
- <LeafletChoropleth geoJson={geoJson} />
+ <Suspense fallback={<LoadingAndErrorWrapper loading />}>
+ <LeafletChoropleth geoJson={geoJson} />
+ </Suspense>
));
ChoroplethPreview.displayName = "ChoroplethPreview";
diff --git a/frontend/src/metabase/api/geojson.ts b/frontend/src/metabase/api/geojson.ts
index cd8705176cf..198b42d5ce3 100644
--- a/frontend/src/metabase/api/geojson.ts
+++ b/frontend/src/metabase/api/geojson.ts
@@ -1,7 +1,7 @@
import type { Feature, FeatureCollection } from "geojson";
import { t } from "ttag";
-import { computeMinimalBounds } from "metabase/visualizations/lib/mapping";
+import { computeMinimalBoundsCoordinates } from "metabase/visualizations/lib/mapping";
import type { GeoJSONData } from "metabase-types/api";
import { Api } from "./api";
@@ -55,9 +55,9 @@ function assertsValidGeoJson(
}
}
- const bounds = computeMinimalBounds(validatedData.features);
- const northEast = bounds.getNorthEast();
- const southWest = bounds.getSouthWest();
+ const { northEast, southWest } = computeMinimalBoundsCoordinates(
+ validatedData.features,
+ );
if (
[
diff --git a/frontend/src/metabase/metrics-viewer/utils/dimension-breakout-config.ts b/frontend/src/metabase/metrics-viewer/utils/dimension-breakout-config.ts
index 418dcb8014e..3e8a0445457 100644
--- a/frontend/src/metabase/metrics-viewer/utils/dimension-breakout-config.ts
+++ b/frontend/src/metabase/metrics-viewer/utils/dimension-breakout-config.ts
@@ -2,8 +2,8 @@ import {
DIMENSION_PREDICATES,
getGeoSubtype,
} from "metabase/common/metrics/utils/dimension-types";
-import { getColorplethColorScale } from "metabase/visualizations/components/ChoroplethMap";
import { getBreakoutSeriesName } from "metabase/visualizations/echarts/cartesian/model/series";
+import { getColorplethColorScale } from "metabase/visualizations/visualizations/Map/map-color-scale";
import type { DimensionMetadata } from "metabase-lib/metric";
import { isCountry, isState } from "metabase-lib/v1/types/utils/isa";
import type {
diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx
index c703b289b00..55d5fedea60 100644
--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx
+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx
@@ -1,5 +1,4 @@
import cx from "classnames";
-import Color from "color";
import * as d3 from "d3";
import type { Feature, FeatureCollection } from "geojson";
import type L from "leaflet";
@@ -22,10 +21,7 @@ import {
getLegendTitles,
} from "metabase/visualizations/lib/choropleth";
import { MinColumnsError } from "metabase/visualizations/lib/errors";
-import {
- computeMinimalBounds,
- getCanonicalRowKey,
-} from "metabase/visualizations/lib/mapping";
+import { getCanonicalRowKey } from "metabase/visualizations/lib/mapping";
import {
getDefaultSize,
getMinSize,
@@ -46,42 +42,7 @@ import type {
import { ChartWithLegend } from "./ChartWithLegend";
import { LeafletChoropleth } from "./LeafletChoropleth";
import { LegacyChoropleth } from "./LegacyChoropleth";
-
-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;
-}
+import { computeMinimalBounds } from "./leaflet-bounds";
const geoJsonCache = new Map<string, GeoJSONData>();
diff --git a/frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx b/frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx
index ea54305dd3d..7dcb8bdb0fa 100644
--- a/frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx
+++ b/frontend/src/metabase/visualizations/components/LeafletChoropleth.tsx
@@ -4,10 +4,10 @@ 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";
+import { computeMinimalBounds } from "./leaflet-bounds";
type FeatureInteraction = {
feature: Feature;
diff --git a/frontend/src/metabase/visualizations/components/leaflet-bounds.ts b/frontend/src/metabase/visualizations/components/leaflet-bounds.ts
new file mode 100644
index 00000000000..5f2b8aa9b71
--- /dev/null
+++ b/frontend/src/metabase/visualizations/components/leaflet-bounds.ts
@@ -0,0 +1,15 @@
+import type { Feature } from "geojson";
+import L from "leaflet";
+
+import { computeMinimalBoundsCoordinates } from "metabase/visualizations/lib/mapping";
+
+// Builds an `L.LatLngBounds` from the leaflet-free bounds coordinates. Lives in
+// its own (leaflet-importing) module so the only consumers are the lazily
+// loaded leaflet map components.
+export function computeMinimalBounds(features: Feature[]): L.LatLngBounds {
+ const { southWest, northEast } = computeMinimalBoundsCoordinates(features);
+ return L.latLngBounds(
+ L.latLng(southWest.lat, southWest.lng),
+ L.latLng(northEast.lat, northEast.lng),
+ );
+}
diff --git a/frontend/src/metabase/visualizations/lib/mapping.ts b/frontend/src/metabase/visualizations/lib/mapping.ts
index 390516a955c..8746b3cbc65 100644
--- a/frontend/src/metabase/visualizations/lib/mapping.ts
+++ b/frontend/src/metabase/visualizations/lib/mapping.ts
@@ -1,20 +1,30 @@
import * as d3 from "d3";
import type { Feature, Position } from "geojson";
-import L from "leaflet";
// getCanonicalRowKey lives in a Leaflet-free module so the static-viz bundle can use it; re-exported
// here to keep existing import sites working.
export { getCanonicalRowKey } from "./region-codes";
-export function computeMinimalBounds(features: Feature[]) {
+export type BoundsCoordinates = {
+ northEast: { lat: number; lng: number };
+ southWest: { lat: number; lng: number };
+};
+
+// Leaflet-free bounds calculation, so this module (and eager consumers such as
+// the geojson API) stay out of the leaflet bundle. Leaflet consumers turn these
+// plain coordinates into an `L.LatLngBounds` where they need one.
+export function computeMinimalBoundsCoordinates(
+ features: Feature[],
+): BoundsCoordinates {
const points = getAllFeaturesPoints(features);
- const [west, east] = d3.extent(points, (d) => d[0]);
- const [north, south] = d3.extent(points, (d) => d[1]);
+ const [minLng, maxLng] = d3.extent(points, (d) => d[0]);
+ const [minLat, maxLat] = d3.extent(points, (d) => d[1]);
- return L.latLngBounds(
- L.latLng(south ?? 0, west ?? 0), // SW
- L.latLng(north ?? 0, east ?? 0), // NE
- );
+ // Matches the normalized corners that `L.latLngBounds` would produce.
+ return {
+ southWest: { lat: minLat ?? 0, lng: minLng ?? 0 },
+ northEast: { lat: maxLat ?? 0, lng: maxLng ?? 0 },
+ };
}
export function getAllFeaturesPoints(features: Feature[]): Position[] {
diff --git a/frontend/src/metabase/visualizations/visualizations/Map/Map.tsx b/frontend/src/metabase/visualizations/visualizations/Map/Map.tsx
index 8df27f1acc7..6ad5dc2bfb3 100644
--- a/frontend/src/metabase/visualizations/visualizations/Map/Map.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Map/Map.tsx
@@ -1,10 +1,12 @@
-import { memo } from "react";
+import { Suspense, lazy, memo } from "react";
import { t } from "ttag";
import _ from "underscore";
import { ColorRangeSelector } from "metabase/common/components/ColorRangeSelector";
+import { Flex } from "metabase/ui";
import { getAccentColors, getPreferredColor } from "metabase/ui/colors/groups";
import MetabaseSettings from "metabase/utils/settings";
+import MapSkeleton from "metabase/visualizations/components/skeletons/MapSkeleton/MapSkeleton";
import {
getDefaultMapDimension,
getDefaultMapMetric,
@@ -36,37 +38,32 @@ import {
} from "metabase-lib/v1/types/utils/isa";
import type { CustomGeoJSONMap } from "metabase-types/api";
-import {
- ChoroplethMap,
- getColorplethColorScale,
-} from "../../components/ChoroplethMap";
-import { LeafletGridHeatMap } from "../../components/LeafletGridHeatMap";
-import { PinMap } from "../../components/PinMap";
-
import { CustomMapFooter } from "./CustomMapFooter";
-
-const PIN_MAP_VALUES = ["pin", "heat", "grid"] as const;
-type PinMapValue = (typeof PIN_MAP_VALUES)[number];
-
-function isPinMapType(value: unknown): value is PinMapValue {
- return PIN_MAP_VALUES.some((v) => v === value);
-}
+import { getColorplethColorScale } from "./map-color-scale";
+import { isMapSensible, isPinMapType } from "./utils";
const MAP_DISPLAY_ALIASES = ["state", "country", "pin_map"] as const;
-function MapComponent(props: VisualizationProps) {
- const { settings } = props;
- const type = settings["map.type"];
-
- if (isPinMapType(type)) {
- return <PinMap {...props} />;
- }
-
- if (type === "region") {
- return <ChoroplethMap {...props} />;
- }
+// Leaflet (and the map renderer that uses it) is loaded lazily so it stays out
+// of the initial bundle for the majority of users who never open a map.
+const MapRenderer = lazy(() =>
+ import(/* webpackChunkName: "map-renderer" */ "./MapRenderer").then(
+ (module) => ({ default: module.MapRenderer }),
+ ),
+);
- return null;
+function MapComponent(props: VisualizationProps) {
+ return (
+ <Suspense
+ fallback={
+ <Flex h="100%" w="100%" direction="column">
+ <MapSkeleton />
+ </Flex>
+ }
+ >
+ <MapRenderer {...props} />
+ </Suspense>
+ );
}
function arePropsEqual(prev: VisualizationProps, next: VisualizationProps) {
@@ -84,10 +81,7 @@ const MAP_VIZ_DEFINITION: VisualizationDefinition = {
aliases: [...MAP_DISPLAY_ALIASES],
minSize: getMinSize("map"),
defaultSize: getDefaultSize("map"),
- isSensible: (data) =>
- PinMap.isSensible(data) ||
- Boolean(ChoroplethMap.isSensible?.(data)) ||
- LeafletGridHeatMap.isSensible(data),
+ isSensible: isMapSensible,
hasEmptyState: true,
settings: {
...columnSettings({ getHidden: () => true }),
diff --git a/frontend/src/metabase/visualizations/visualizations/Map/MapRenderer.tsx b/frontend/src/metabase/visualizations/visualizations/Map/MapRenderer.tsx
new file mode 100644
index 00000000000..5813150d964
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/Map/MapRenderer.tsx
@@ -0,0 +1,23 @@
+import type { VisualizationProps } from "metabase/visualizations/types";
+
+import { ChoroplethMap } from "../../components/ChoroplethMap";
+import { PinMap } from "../../components/PinMap";
+
+import { isPinMapType } from "./utils";
+
+// Renders the actual leaflet-backed map. This module (and everything it pulls
+// in, including leaflet) is loaded lazily by Map.tsx so it stays out of the
+// initial bundle.
+export function MapRenderer(props: VisualizationProps) {
+ const type = props.settings["map.type"];
+
+ if (isPinMapType(type)) {
+ return <PinMap {...props} />;
+ }
+
+ if (type === "region") {
+ return <ChoroplethMap {...props} />;
+ }
+
+ return null;
+}
diff --git a/frontend/src/metabase/visualizations/visualizations/Map/map-color-scale.ts b/frontend/src/metabase/visualizations/visualizations/Map/map-color-scale.ts
new file mode 100644
index 00000000000..9cdf0bb0ee4
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/Map/map-color-scale.ts
@@ -0,0 +1,43 @@
+import Color from "color";
+import * as d3 from "d3";
+
+// Leaflet-free color-scale helper for the region (choropleth) map. It lives in
+// its own module (rather than in ChoroplethMap, which pulls in the leaflet
+// renderer) so the Map visualization definition can use it for its settings
+// without forcing leaflet into the initial bundle.
+
+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;
+}
diff --git a/frontend/src/metabase/visualizations/visualizations/Map/utils.ts b/frontend/src/metabase/visualizations/visualizations/Map/utils.ts
new file mode 100644
index 00000000000..5fa0ef29ea4
--- /dev/null
+++ b/frontend/src/metabase/visualizations/visualizations/Map/utils.ts
@@ -0,0 +1,34 @@
+import {
+ hasLatitudeAndLongitudeColumns,
+ isMetric,
+ isNumeric,
+ isString,
+} from "metabase-lib/v1/types/utils/isa";
+import type { DatasetColumn, DatasetData } from "metabase-types/api";
+
+export const PIN_MAP_VALUES = ["pin", "heat", "grid"] as const;
+export type PinMapValue = (typeof PIN_MAP_VALUES)[number];
+
+export function isPinMapType(value: unknown): value is PinMapValue {
+ return PIN_MAP_VALUES.some((v) => v === value);
+}
+
+const isValidCoordinatesColumn = (column: DatasetColumn | undefined) =>
+ !!column &&
+ (column.binning_info != null ||
+ (column.source === "native" && isNumeric(column)));
+
+// Leaflet-free equivalent of `PinMap.isSensible || ChoroplethMap.isSensible ||
+// LeafletGridHeatMap.isSensible`. Kept here (rather than reaching into those
+// leaflet-importing components) so the Map visualization definition can decide
+// whether a dataset is map-able without pulling leaflet into the initial bundle.
+export function isMapSensible({ cols }: DatasetData): boolean {
+ const isPinMapSensible = hasLatitudeAndLongitudeColumns(cols);
+ const isRegionMapSensible =
+ cols.filter(isString).length > 0 && cols.filter(isMetric).length > 0;
+ const isGridMapSensible =
+ cols.filter(isValidCoordinatesColumn).length >= 2 &&
+ cols.filter(isMetric).length > 0;
+
+ return isPinMapSensible || isRegionMapSensible || isGridMapSensible;
+}