Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(layers): add Voronoi Mosaic layer (#3977)
Igor Dykhta8a69d93e6bd3
diff --git a/SUMMARY.md b/SUMMARY.mdindex 97b8bcd40..4ad9a8ac4 100644--- a/SUMMARY.md+++ b/SUMMARY.md@@ -14,6 +14,7 @@* [Add Data to the Map](docs/user-guides/b-kepler-gl-workflow/a-add-data-to-the-map.md)* [Layers](docs/user-guides/c-types-of-layers/README.md)* [Point](docs/user-guides/c-types-of-layers/a-point.md)+ * [Voronoi Mosaic](docs/user-guides/c-types-of-layers/t-voronoi.md)* [S2 Layer](docs/user-guides/c-types-of-layers/l-s2.md)* [A5 Layer](docs/user-guides/c-types-of-layers/q-a5.md)* [GeoHash Layer](docs/user-guides/c-types-of-layers/r-geohash.md)diff --git a/babel-register.js b/babel-register.jsindex 2bd50f180..accf6ee61 100644--- a/babel-register.js+++ b/babel-register.js@@ -26,7 +26,7 @@ require('@babel/register')({}],only: [__dirname],- extensions: ['.ts', '.js', '.tsx', '.json']+ extensions: ['.ts', '.js', '.tsx', '.json', '.mjs']});require('@babel/polyfill');diff --git a/docs/user-guides/c-types-of-layers/README.md b/docs/user-guides/c-types-of-layers/README.mdindex 0900878f6..2e85bf8b5 100644--- a/docs/user-guides/c-types-of-layers/README.md+++ b/docs/user-guides/c-types-of-layers/README.md@@ -10,6 +10,12 @@ Single feature layers render 1 featurePoint layers draw points for a given event or object based on its location - latitude and longitude.+## Voronoi Mosaic++[Voronoi Mosaic](t-voronoi.md) creates irregular nearest-site cells around point locations.+Color cells by an attribute to compare stores, stations, sensors, and facilities. Cell+boundaries follow the point distribution; they do not represent travel-time catchments.+## Arcdiff --git a/docs/user-guides/c-types-of-layers/t-voronoi.md b/docs/user-guides/c-types-of-layers/t-voronoi.mdnew file mode 100644index 000000000..3ebfdd538--- /dev/null+++ b/docs/user-guides/c-types-of-layers/t-voronoi.md@@ -0,0 +1,59 @@+# Voronoi Mosaic++Voronoi Mosaic turns point locations into adjoining, irregular cells. Each cell belongs to+the nearest input location in the map's Web Mercator projection. Color cells by a source+attribute to compare stores, stations, sensors, or facilities.++These are nearest-site areas, **not travel-time or routing catchments**. Distances are+measured in the map projection, so this layer is intended for regional exploration rather+than precise geographic distance analysis. It is available in the flat map view.++## Create a mosaic++1. Load a table with numeric latitude and longitude columns, or a GeoJSON geometry column.+ Arrow-backed tables are supported.+2. Add a layer or change a Point layer's type to **Voronoi Mosaic**.+3. Choose **Point Columns** and select latitude/longitude, or choose **GeoJSON Centroids**+ and select the geometry column. Each geometry produces one site: its point coordinate+ or the average of its vertices, using the same centroid calculation as the Heatmap layer.+4. Under **Fill Color**, choose an attribute and a color palette. Hover over a cell to see+ the original point's values.++## Appearance and bounds++- **Fill Color** controls the cell fill, attribute-based colors, and opacity.+- **Stroke Color** controls outlines and their width in pixels.+- **Cell Bounds → Bounds Padding (%)** extends the dataset's bounding rectangle on each+ side. Padding is measured in the map projection. It clips the otherwise unbounded outer+ cells; it does not change internal nearest-site boundaries.++Cells stay fixed while panning and zooming. Filters rebuild the mosaic from the remaining+points, allowing their cells to expand into the areas of excluded points. This includes+numeric and time filters, as well as drawn polygon filters that select source point+locations (centroids in GeoJSON mode). The outer clipping rectangle stays tied to all+source sites in the full dataset and its padding.+An empty selection draws no cells; clearing filters restores the original mosaic.+Changing the input coordinates or padding also rebuilds the mosaic. Settings are saved+with the map.++Missing, nonfinite, and out-of-range coordinates are skipped. Latitude must be within the+Web Mercator range, approximately ±85.05°. Coincident locations share one cell, assigned to+the first remaining row in the dataset. A single input point receives a finite display rectangle; a+collinear set also receives a nonzero display extent.++The layer renders flat cells and does not calculate road-network service areas.++## Application configuration++Voronoi Mosaic is enabled by default. Applications embedding kepler.gl can hide it+from layer type pickers with:++```js+import {initApplicationConfig} from '@kepler.gl/utils';++initApplicationConfig({enableVoronoiLayer: false});+```++Existing Voronoi layers in saved maps remain available for rendering and configuration.++[Back to layers](README.md)diff --git a/jest.config.js b/jest.config.jsindex bc7fb22bd..f77aeccaf 100644--- a/jest.config.js+++ b/jest.config.js@@ -41,7 +41,7 @@ const config = {presets: [['@babel/preset-env', {targets: {node: 'current'}}]]}],- '\\.[jt]sx?$': 'babel-jest'+ '\\.(?:[jt]sx?|mjs)$': 'babel-jest'},// Per https://jestjs.io/docs/configuration#transformignorepatterns-arraystring, transformIgnorePatterns ignores// node_modules and pnp folders by default so that they are not transpileddiff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsxindex 18ecaa57b..33344f179 100644--- a/src/components/src/side-panel/layer-manager.tsx+++ b/src/components/src/side-panel/layer-manager.tsx@@ -210,6 +210,7 @@ function LayerManagerFactory(const enableGeohashLayer = getApplicationConfig().enableGeohashLayer;const enableFlowFieldLayer = getApplicationConfig().enableFlowFieldLayer;const enableContourLayer = getApplicationConfig().enableContourLayer;+ const enableVoronoiLayer = getApplicationConfig().enableVoronoiLayer;const enableZarrLayer = getApplicationConfig().enableZarrLayer;const enableLayerGroups = getApplicationConfig().enableLayerGroups;@@ -243,6 +244,10 @@ function LayerManagerFactory(const {contour: _contour, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;}+ if (!enableVoronoiLayer) {+ const {voronoi: _voronoi, ...rest} = filteredClasses;+ filteredClasses = rest as LayerClassesType;+ }if (!enableZarrLayer) {const {zarr: _zarr, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;@@ -256,6 +261,7 @@ function LayerManagerFactory(enableGeohashLayer,enableFlowFieldLayer,enableContourLayer,+ enableVoronoiLayer,enableZarrLayer,layerClasses]);diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsxindex 30b9372de..9ab34ab63 100644--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx@@ -860,6 +860,57 @@ export default function LayerConfiguratorFactory();}+ _renderVoronoiLayerConfig({+ layer,+ visConfiguratorProps,+ layerConfiguratorProps,+ layerChannelConfigProps+ }) {+ return (+ <StyledLayerVisualConfigurator>+ <LayerConfigGroup+ {...layer.visConfigSettings.filled}+ {...visConfiguratorProps}+ label="layer.fillColor"+ collapsible+ >+ <ChannelByValueSelector+ channel={layer.visualChannels.color}+ {...layerChannelConfigProps}+ />+ {layer.config.colorField ? (+ <LayerColorRangeSelector {...visConfiguratorProps} />+ ) : (+ <LayerColorSelector {...layerConfiguratorProps} />+ )}+ <ConfigGroupCollapsibleContent>+ <VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />+ </ConfigGroupCollapsibleContent>+ </LayerConfigGroup>+ <LayerConfigGroup+ {...layer.visConfigSettings.stroked}+ {...visConfiguratorProps}+ label="layer.strokeColor"+ collapsible+ >+ <LayerColorSelector+ {...visConfiguratorProps}+ selectedColor={layer.config.visConfig.strokeColor}+ property="strokeColor"+ />+ <VisConfigSlider {...layer.visConfigSettings.thickness} {...visConfiguratorProps} />+ </LayerConfigGroup>+ <LayerConfigGroup+ {...visConfiguratorProps}+ label="layerVisConfigs.voronoi.bounds"+ collapsible+ >+ <VisConfigSlider {...layer.visConfigSettings.boundsPadding} {...visConfiguratorProps} />+ </LayerConfigGroup>+ </StyledLayerVisualConfigurator>+ );+ }+_renderClusterLayerConfig({layer, visConfiguratorProps, layerChannelConfigProps}) {return (<StyledLayerVisualConfigurator>diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex 726d85728..4f5ae8e31 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -1545,6 +1545,7 @@ export const GLOBE_SUPPORTED_LAYERS: Record<string, boolean> = {rasterTile: true,heatmap: true,contour: false,+ voronoi: false,s2: false,tile3d: false,// Flow arrows are flat quads in common space (equatorial plane) and collapse whendiff --git a/src/constants/src/layers.ts b/src/constants/src/layers.tsindex 1d9279a50..7f15eb332 100644--- a/src/constants/src/layers.ts+++ b/src/constants/src/layers.ts@@ -663,6 +663,7 @@ export const LAYER_TYPES = keyMirror({icon: null,heatmap: null,contour: null,+ voronoi: null,hexagonId: null,'3D': null,trip: null,@@ -690,5 +691,6 @@ export const EDITOR_AVAILABLE_LAYERS: string[] = [LAYER_TYPES.hexagonId,LAYER_TYPES.geojson,LAYER_TYPES.heatmap,- LAYER_TYPES.contour+ LAYER_TYPES.contour,+ LAYER_TYPES.voronoi];diff --git a/src/layers/package.json b/src/layers/package.jsonindex d82aeba5d..4878a821d 100644--- a/src/layers/package.json+++ b/src/layers/package.json@@ -70,6 +70,7 @@"@turf/center": "^7.2.0","@turf/distance": "^7.2.0","@turf/helpers": "^7.2.0",+ "@types/d3-delaunay": "^6","@types/geojson": "^7946.0.8","@types/keymirror": "^0.1.1","@types/styled-components": "^5.1.32",@@ -78,6 +79,7 @@"buffer": "6.0.3","d3-array": "^2.8.0","d3-contour": "^3.0.2",+ "d3-delaunay": "^6","d3-format": "^3.1.0","d3-interpolate": "^3.0.1","d3-shape": "^1.2.0",diff --git a/src/layers/src/index.ts b/src/layers/src/index.tsindex 7d7321f6e..eadcfd5e0 100644--- a/src/layers/src/index.ts+++ b/src/layers/src/index.ts@@ -26,6 +26,8 @@ import {default as ClusterLayer} from './cluster-layer/cluster-layer';import {default as IconLayer} from './icon-layer/icon-layer';import {default as HeatmapLayer} from './heatmap-layer/heatmap-layer';import {default as ContourLayer} from './contour-layer/contour-layer';+import VoronoiLayer from './voronoi-layer/voronoi-layer';+export {default as VoronoiLayer} from './voronoi-layer/voronoi-layer';export {MAX_ZOOM_LEVEL} from './heatmap-layer/heatmap-layer';import {default as H3Layer} from './h3-hexagon-layer/h3-hexagon-layer';export {defaultElevation as h3DefaultElevation} from './h3-hexagon-layer/h3-hexagon-layer';@@ -147,6 +149,7 @@ export const KeplerGlLayers = {IconLayer,HeatmapLayer,ContourLayer,+ VoronoiLayer,H3Layer,ScenegraphLayer,TripLayer,@@ -175,6 +178,7 @@ export const LayerClasses = {[LAYER_TYPES.icon]: IconLayer,[LAYER_TYPES.heatmap]: HeatmapLayer,[LAYER_TYPES.contour]: ContourLayer,+ [LAYER_TYPES.voronoi]: VoronoiLayer,[LAYER_TYPES.hexagonId]: H3Layer,[LAYER_TYPES['3D']]: ScenegraphLayer,[LAYER_TYPES.trip]: TripLayer,diff --git a/src/layers/src/voronoi-layer/voronoi-layer-icon.tsx b/src/layers/src/voronoi-layer/voronoi-layer-icon.tsxnew file mode 100644index 000000000..ad787e664--- /dev/null+++ b/src/layers/src/voronoi-layer/voronoi-layer-icon.tsx@@ -0,0 +1,22 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {Base, BaseProps} from '../base';++export default function VoronoiLayerIcon(props: Partial<BaseProps>) {+ return (+ <Base viewBox="0 0 64 64" {...props}>+ <g fill="none" stroke="currentColor" strokeWidth="3" strokeLinejoin="round">+ <path d="M5 5H59V59H5Z M5 25L22 19L37 30L33 47L16 59 M22 19L26 5 M37 30L59 22 M33 47L59 53" />+ </g>+ <g fill="currentColor">+ <circle cx="14" cy="13" r="2" />+ <circle cx="44" cy="14" r="2" />+ <circle cx="18" cy="38" r="2" />+ <circle cx="48" cy="39" r="2" />+ <circle cx="35" cy="55" r="2" />+ </g>+ </Base>+ );+}diff --git a/src/layers/src/voronoi-layer/voronoi-layer.spec.ts b/src/layers/src/voronoi-layer/voronoi-layer.spec.tsnew file mode 100644index 000000000..a0c8e0c2d--- /dev/null+++ b/src/layers/src/voronoi-layer/voronoi-layer.spec.ts@@ -0,0 +1,577 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {Table, vectorFromArray, Float64, Int64} from 'apache-arrow';+import {+ KeplerTable,+ copyTableAndUpdate,+ getGpuFilterProps,+ assignGpuChannels+} from '@kepler.gl/table';+import {processArrowBatches} from '@kepler.gl/processors';+import {getPolygonFilterFunctor, getDefaultFilter} from '@kepler.gl/utils';+import {EDITOR_AVAILABLE_LAYERS, FILTER_TYPES} from '@kepler.gl/constants';+import {DATA_TYPES} from 'type-analyzer';+import SchemaManager from '@kepler.gl/schemas';+import {INITIAL_VIS_STATE, layerTypeChangeUpdater, setFilterUpdater} from '@kepler.gl/reducers';+import {StateWFiles} from 'test/helpers/mock-state';+import {LayerClasses} from '../index';+import VoronoiLayer from './voronoi-layer';+import * as voronoiUtils from './voronoi-utils';++afterEach(() => jest.restoreAllMocks());++const rows = [+ [-1, -1, 10],+ [1, -1, 20],+ [-1, 1, 30],+ [1, 1, 40]+];+const fields = [+ {name: 'longitude', type: 'real'},+ {name: 'latitude', type: 'real'},+ {name: 'value', type: 'real'}+];++async function setup(data?: Parameters<KeplerTable['importData']>[0]['data']) {+ const dataset = new KeplerTable({info: {id: 'voronoi-test'}, color: [0, 0, 0]});+ await dataset.importData({data: data || {fields, rows}});+ dataset.gpuFilter = getGpuFilterProps([], dataset.id, dataset.fields);+ const layer = new VoronoiLayer({+ dataId: dataset.id,+ columns: {+ lng: {value: 'longitude', fieldIdx: 0},+ lat: {value: 'latitude', fieldIdx: 1}+ }+ });+ return {layer, dataset, datasets: {[dataset.id]: dataset}};+}++function render(layer, dataset, data) {+ return layer.renderLayer({+ data,+ idx: 0,+ gpuFilter: dataset.gpuFilter,+ mapState: {zoom: 10},+ visible: true+ })[0];+}++test('registers a selectable layer without adding a new default layer on import', async () => {+ const {layer, dataset} = await setup();+ expect(LayerClasses.voronoi).toBe(VoronoiLayer);+ expect(VoronoiLayer.findDefaultLayerProps(dataset).props).toEqual([]);+ expect(layer.hasAllColumns()).toBe(true);+ expect(layer.isAggregated).toBe(false);+});++test('keeps source row colors and hover data on the generated polygons', async () => {+ const {layer, dataset, datasets} = await setup();+ layer.updateLayerConfig({colorField: dataset.fields[2], colorScale: 'quantize'});+ layer.updateLayerDomain(datasets);+ layer.updateLayerVisConfig({+ colorRange: {...layer.config.visConfig.colorRange, colors: ['#FF0000', '#00FF00']}+ });+ const data = layer.formatLayerData(datasets);+ expect(data.data.map(cell => cell.index)).toEqual([0, 1, 2, 3]);+ expect(data.getFillColor(data.data[0])).toEqual([255, 0, 0]);+ expect(data.getFillColor(data.data[3])).toEqual([0, 255, 0]);+ expect(layer.getHoverData(data.data[3], dataset.dataContainer)).toEqual(+ dataset.dataContainer.row(3)+ );+ const polygon = render(layer, dataset, data);+ expect(polygon.props.getPolygon(data.data[0])).toEqual(data.data[0].polygon);+ expect(polygon.props.pickable).toBe(true);+ expect(polygon.props.filled).toBe(true);+ expect(polygon.props.stroked).toBe(true);+ expect(polygon.props.extruded).toBe(false);+});++test('CPU and per-layer filters rebuild cells within unchanged dataset bounds', async () => {+ const {layer, dataset, datasets} = await setup();+ const original = layer.formatLayerData(datasets);+ const bounds = layer.meta.bounds;+ for (const table of [+ copyTableAndUpdate(dataset, {filteredIndex: [1, 3]}),+ copyTableAndUpdate(dataset, {filteredIndexByLayer: {[layer.id]: [1, 3]}})+ ]) {+ const filtered = layer.formatLayerData({[dataset.id]: table}, original);+ expect(filtered.data.map(cell => cell.index)).toEqual([1, 3]);+ expect(filtered.data[0].polygon).not.toEqual(original.data[1].polygon);+ expect(filtered.data[1].polygon).not.toEqual(original.data[3].polygon);+ // Both surviving sites are in the east; their cells now also cover the west.+ for (const cell of filtered.data) {+ expect(Math.min(...cell.polygon.map(point => point[0]))).toBeCloseTo(bounds[0]);+ expect(Math.max(...cell.polygon.map(point => point[0]))).toBeCloseTo(bounds[2]);+ }+ expect(layer.meta.bounds).toEqual(bounds);+ expect(layer.formatLayerData(datasets, filtered).data).toEqual(original.data);+ }+ const empty = copyTableAndUpdate(dataset, {filteredIndex: []});+ expect(layer.formatLayerData({[dataset.id]: empty}, original).data).toEqual([]);+ expect(layer.meta.bounds).toEqual(bounds);+ expect(layer.formatLayerData(datasets).data).toEqual(original.data);+});++test('GPU numeric filters rebuild cells even when the CPU row indices do not change', async () => {+ const {layer, dataset, datasets} = await setup();+ const original = layer.formatLayerData(datasets);+ const bounds = layer.meta.bounds;+ const filter = {+ ...getDefaultFilter({dataId: [dataset.id]}),+ type: FILTER_TYPES.range,+ name: ['value'],+ fieldIdx: [2],+ domain: [10, 40],+ value: [20, 20],+ gpu: true+ };+ let previous = original;+ for (const {value, indices} of [+ {value: [20, 20], indices: [1]},+ {value: [10, 10], indices: [0]},+ {value: [20, 40], indices: [1, 2, 3]},+ {value: [21, 29], indices: []}+ ]) {+ dataset.filterTable(assignGpuChannels([{...filter, value}]), [layer]);+ expect(dataset.filteredIndex).toEqual([0, 1, 2, 3]);+ const data = layer.formatLayerData(datasets, previous);+ expect(data.data.map(cell => cell.index)).toEqual(indices);+ expect(layer.meta.bounds).toEqual(bounds);+ if (indices.length === 1) {+ const polygon = data.data[0].polygon;+ expect(Math.min(...polygon.map(point => point[0]))).toBeCloseTo(bounds[0]);+ expect(Math.max(...polygon.map(point => point[0]))).toBeCloseTo(bounds[2]);+ expect(Math.min(...polygon.map(point => point[1]))).toBeCloseTo(bounds[1]);+ expect(Math.max(...polygon.map(point => point[1]))).toBeCloseTo(bounds[3]);+ }+ const rendered = render(layer, dataset, data);+ expect(rendered.props.filterRange).toEqual(dataset.gpuFilter.filterRange);+ expect(data.data.map(rendered.props.getFilterValue)).toEqual(+ indices.map(index => [rows[index][2] - 10, 0, 0, 0])+ );+ previous = data;+ }+ dataset.filterTable(assignGpuChannels([{...filter, enabled: false}]), [layer]);+ expect(layer.formatLayerData(datasets, previous).data).toEqual(original.data);+});++test('timeline updates rebuild the mosaic and clearing the filter restores all sites', async () => {+ const {layer, dataset, datasets} = await setup({+ fields: [...fields, {name: 'time', type: 'timestamp', format: ''}],+ rows: rows.map((row, i) => [...row, (i + 1) * 1000])+ });+ const prepare = jest.spyOn(voronoiUtils, 'prepareVoronoiSites');+ const clip = jest.spyOn(voronoiUtils, 'getVoronoiClip');+ const original = layer.formatLayerData(datasets);+ const bounds = layer.meta.bounds;+ let state = {+ ...INITIAL_VIS_STATE,+ datasets,+ filters: [getDefaultFilter({dataId: [dataset.id]})],+ layers: [layer],+ layerData: [original],+ layerOrder: [layer.id]+ };+ state = setFilterUpdater(state, {idx: 0, prop: 'name', value: 'time'});+ expect(state.filters[0].type).toBe(FILTER_TYPES.timeRange);+ expect(state.filters[0].gpu).toBe(true);+ for (const {value, indices} of [+ {value: [1000, 2000], indices: [0, 1]},+ {value: [3000, 4000], indices: [2, 3]},+ {value: [2100, 2900], indices: []},+ {value: [1000, 2000], indices: [0, 1]}+ ]) {+ state = setFilterUpdater(state, {idx: 0, prop: 'value', value});+ expect(state.layers[0].isValid).toBe(true);+ expect(state.layerData[0].data.map(cell => cell.index)).toEqual(indices);+ expect(state.layers[0].meta.bounds).toEqual(bounds);+ if (indices.length) {+ expect(state.layerData[0].data[0].polygon).not.toEqual(original.data[indices[0]].polygon);+ }+ }+ state = setFilterUpdater(state, {idx: 0, prop: 'enabled', value: false});+ expect(state.layerData[0].data).toEqual(original.data);+ expect(prepare).toHaveBeenCalledTimes(1);+ expect(clip).toHaveBeenCalledTimes(1);+});++test('polygon filters operate on the source site rather than the cell boundary', async () => {+ const {layer, dataset} = await setup();+ expect(EDITOR_AVAILABLE_LAYERS).toContain('voronoi');+ const filter = {+ value: {+ type: 'Feature',+ properties: {},+ geometry: {+ type: 'Polygon',+ coordinates: [+ [+ [-2, -2],+ [0, -2],+ [0, 2],+ [-2, 2],+ [-2, -2]+ ]+ ]+ }+ }+ };+ const contains = getPolygonFilterFunctor(layer, filter, dataset.dataContainer);+ expect([0, 1, 2, 3].map(index => contains({index}))).toEqual([true, false, true, false]);+});++test('reuses geometry for styling and rebuilds for padding, coordinates, and data revision', async () => {+ const {layer, dataset, datasets} = await setup();+ const first = layer.formatLayerData(datasets);+ layer.updateLayerVisConfig({opacity: 0.4, thickness: 2, filled: false});+ const styled = layer.formatLayerData(datasets, first);+ expect(styled.data).toBe(first.data);+ expect(render(layer, dataset, styled).props.filled).toBe(false);+ expect(render(layer, dataset, styled).props.opacity).toBe(0.4);+ layer.updateLayerVisConfig({boundsPadding: 30});+ const padded = layer.formatLayerData(datasets, styled);+ expect(padded.data[0].polygon).not.toEqual(first.data[0].polygon);+ await dataset.update({+ fields,+ rows: [+ [-2, 0, 15],+ [2, 0, 25]+ ]+ });+ const replaced = layer.formatLayerData(datasets, padded);+ expect(replaced.data).toHaveLength(2);+ expect(replaced.data[0].position).toEqual([-2, 0]);+ layer.updateLayerConfig({columns: {...layer.config.columns, lng: layer.config.columns.lat}});+ const moved = layer.formatLayerData(datasets, replaced);+ expect(moved.data).toHaveLength(1);+ expect(moved.data[0].position).toEqual([0, 0]);+});++test.each(['points', 'geojson'])(+ 'reuses %s source preparation and bounds across CPU/GPU filters and padding changes',+ async columnMode => {+ const geometryFields = ['shape', 'alternate'].map(name => ({+ name,+ type: 'geojson',+ analyzerType: DATA_TYPES.GEOMETRY+ }));+ const {layer, dataset, datasets} = await setup({+ fields: [...fields, ...geometryFields],+ rows: rows.map(([lng, lat, value]) => [+ lng,+ lat,+ value,+ JSON.stringify({type: 'Point', coordinates: [lng, lat]}),+ JSON.stringify({type: 'Point', coordinates: [lng + 10, lat]})+ ])+ });+ if (columnMode === 'geojson') {+ layer.updateLayerConfig({+ columnMode,+ columns: layer.assignColumn('geojson', dataset.fields[3])+ });+ }+ const read = jest.spyOn(dataset.dataContainer, 'valueAt');+ const prepare = jest.spyOn(voronoiUtils, 'prepareVoronoiSites');+ const clip = jest.spyOn(voronoiUtils, 'getVoronoiClip');+ const coordinateReads = () =>+ read.mock.calls.filter(([, field]) =>+ columnMode === 'geojson' ? field === 3 : field === 0 || field === 1+ ).length;+ const original = layer.formatLayerData(datasets);+ const sourceReads = coordinateReads();+ expect(sourceReads).toBe(rows.length * (columnMode === 'geojson' ? 1 : 2));+ const bounds = layer.meta.bounds;+ let previous = original;+ for (const indices of [[1, 3], [], [0, 1, 2, 3]]) {+ const table = copyTableAndUpdate(dataset, {filteredIndexByLayer: {[layer.id]: indices}});+ const filtered = layer.formatLayerData({[dataset.id]: table}, previous);+ expect(filtered.data.map(cell => cell.index)).toEqual(indices);+ expect(layer.meta.bounds).toBe(bounds);+ previous = filtered;+ }+ const filter = {+ ...getDefaultFilter({dataId: [dataset.id]}),+ type: FILTER_TYPES.range,+ name: ['value'],+ fieldIdx: [2],+ domain: [10, 40],+ value: [20, 20],+ gpu: true+ };+ for (const {value, indices} of [+ {value: [20, 20], indices: [1]},+ {value: [21, 29], indices: []},+ {value: [10, 40], indices: [0, 1, 2, 3]}+ ]) {+ dataset.filterTable(assignGpuChannels([{...filter, value}]), [layer]);+ const filtered = layer.formatLayerData(datasets, previous);+ expect(filtered.data.map(cell => cell.index)).toEqual(indices);+ expect(layer.meta.bounds).toBe(bounds);+ previous = filtered;+ }+ expect(previous.data).toEqual(original.data);+ expect(coordinateReads()).toBe(sourceReads);+ expect(prepare).toHaveBeenCalledTimes(1);+ expect(clip).toHaveBeenCalledTimes(1);++ layer.updateLayerVisConfig({boundsPadding: 30});+ const padded = layer.formatLayerData(datasets, previous);+ expect(padded.data[0].polygon).not.toEqual(original.data[0].polygon);+ expect(coordinateReads()).toBe(sourceReads);+ expect(prepare).toHaveBeenCalledTimes(1);+ expect(clip).toHaveBeenCalledTimes(2);++ layer.updateLayerConfig({+ columns: layer.assignColumn(+ columnMode === 'geojson' ? 'geojson' : 'lng',+ dataset.fields[columnMode === 'geojson' ? 4 : 1]+ )+ });+ const moved = layer.formatLayerData(datasets, padded);+ expect(moved.data[0].position).toEqual(columnMode === 'geojson' ? [9, -1] : [-1, -1]);+ expect(moved.data).not.toEqual(padded.data);+ expect(prepare).toHaveBeenCalledTimes(2);+ expect(clip).toHaveBeenCalledTimes(3);+ }+);++test('missing datasets and columns clear stale cells and recover after reassignment', async () => {+ const {layer, datasets} = await setup();+ const original = layer.formatLayerData(datasets);+ expect(layer.formatLayerData({}, original).data).toEqual([]);+ expect(layer.meta.bounds).toBeNull();+ expect(layer.formatLayerData(datasets).data).toEqual(original.data);+ layer.updateLayerConfig({columns: {...layer.config.columns, lat: {value: null, fieldIdx: -1}}});+ expect(layer.formatLayerData(datasets).data).toEqual([]);+});++test('GeoJSON features and geometries produce centroid sites with source colors and hover data', async () => {+ const {layer, dataset, datasets} = await setup({+ fields: [{name: 'shape', type: 'geojson', analyzerType: DATA_TYPES.GEOMETRY}, fields[2]],+ rows: [+ [{type: 'Feature', properties: {}, geometry: {type: 'Point', coordinates: [-1, -1]}}, 10],+ [+ {+ type: 'LineString',+ coordinates: [+ [1, -2],+ [1, 0]+ ]+ },+ 20+ ],+ [+ {+ type: 'Polygon',+ coordinates: [+ [+ [-2, 0],+ [0, 0],+ [0, 2],+ [-2, 2],+ [-2, 0]+ ]+ ]+ },+ 30+ ],+ [+ {+ type: 'MultiPoint',+ coordinates: [+ [0, 1],+ [2, 1]+ ]+ },+ 40+ ],+ [+ {+ type: 'GeometryCollection',+ geometries: [+ {type: 'Point', coordinates: [-1, 3]},+ {+ type: 'LineString',+ coordinates: [+ [1, 2],+ [3, 4]+ ]+ }+ ]+ },+ 50+ ],+ [JSON.stringify({type: 'Point', coordinates: [3, 3]}), 200],+ [null, 70],+ ['invalid geometry', 80],+ [{type: 'Feature', properties: {}, geometry: null}, 90],+ [{type: 'Polygon', coordinates: []}, 100],+ [{type: 'Point', coordinates: [NaN, 0]}, 110],+ [{type: 'Point', coordinates: [200, 0]}, 120]+ ]+ });+ const defaults = VoronoiLayer.findDefaultLayerProps(dataset);+ expect(defaults.props).toEqual([]);+ expect(defaults.altProps).toHaveLength(1);+ layer.updateLayerConfig({+ columnMode: defaults.altProps[0].columnMode,+ columns: {...layer.config.columns, ...defaults.altProps[0].columns},+ colorField: dataset.fields[1],+ colorScale: 'quantize'+ });+ layer.updateLayerDomain(datasets);+ layer.updateLayerVisConfig({+ colorRange: {...layer.config.visConfig.colorRange, colors: ['#FF0000', '#00FF00']}+ });+ expect(layer.hasAllColumns()).toBe(true);+ const data = layer.formatLayerData(datasets);+ expect(data.data.map(cell => cell.index)).toEqual([0, 1, 2, 3, 4, 5]);+ const expected = [+ [-1, -1],+ [1, -1],+ [-1.2, 0.8],+ [1, 1],+ [1, 3],+ [3, 3]+ ];+ data.data.forEach((cell, index) => {+ expect(cell.position[0]).toBeCloseTo(expected[index][0]);+ expect(cell.position[1]).toBeCloseTo(expected[index][1]);+ expect(data.getFillColor(cell)).toEqual(index === 5 ? [0, 255, 0] : [255, 0, 0]);+ expect(layer.getHoverData(cell, dataset.dataContainer)).toEqual(+ dataset.dataContainer.row(index)+ );+ });+ const bounds = layer.meta.bounds;+ const remaining = copyTableAndUpdate(dataset, {filteredIndex: [3]});+ const filtered = layer.formatLayerData({[dataset.id]: remaining}, data);+ expect(filtered.data.map(cell => cell.index)).toEqual([3]);+ expect(filtered.data[0].polygon).not.toEqual(data.data[3].polygon);+ expect(layer.meta.bounds).toEqual(bounds);++ const contains = getPolygonFilterFunctor(+ layer,+ {+ value: {+ type: 'Feature',+ properties: {},+ geometry: {+ type: 'Polygon',+ coordinates: [+ [+ [0.5, 0.5],+ [1.5, 0.5],+ [1.5, 1.5],+ [0.5, 1.5],+ [0.5, 0.5]+ ]+ ]+ }+ }+ },+ dataset.dataContainer+ );+ expect(contains({index: 3})).toBe(true); // Centroid is inside; both source points are outside.+ expect(contains({index: 2})).toBe(false);+ expect(contains({index: 6})).toBe(false);+ expect(contains({index: 7})).toBe(false);++ const invalid = copyTableAndUpdate(dataset, {filteredIndex: [6, 7, 8, 9, 10, 11]});+ expect(layer.formatLayerData({[dataset.id]: invalid}, filtered).data).toEqual([]);+});++test('switching input modes rebuilds cells and GeoJSON settings survive layer type changes', async () => {+ const {layer, dataset, datasets} = await setup({+ fields: [...fields, {name: 'shape', type: 'geojson', analyzerType: DATA_TYPES.GEOMETRY}],+ rows: rows.map(row => [...row, {type: 'Point', coordinates: [row[0] + 10, row[1]]}])+ });+ layer.updateLayerConfig({columns: layer.assignColumn('geojson', dataset.fields[3])});+ const original = layer.formatLayerData(datasets);+ layer.updateLayerConfig({columnMode: 'geojson'});+ const centroids = layer.formatLayerData(datasets, original);+ expect(centroids.data.map(cell => cell.position)).toEqual(rows.map(row => [row[0] + 10, row[1]]));+ layer.updateLayerConfig({columnMode: 'points'});+ expect(layer.formatLayerData(datasets, centroids).data).toEqual(original.data);++ // A geometry-only layer must stay valid without latitude/longitude assignments.+ layer.updateLayerConfig({+ columnMode: 'geojson',+ columns: {+ ...layer.config.columns,+ lat: {value: null, fieldIdx: -1},+ lng: {value: null, fieldIdx: -1}+ }+ });+ const saved = SchemaManager.getConfigToSave({+ ...StateWFiles,+ visState: {...StateWFiles.visState, layers: [layer], layerOrder: [layer.id]}+ });+ const config = SchemaManager.parseSavedConfig(saved)!.visState!.layers![0].config;+ expect(config.columnMode).toBe('geojson');+ expect(config.columns.geojson).toBe('shape');+ const state = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [layer],+ layerData: [layer.formatLayerData(datasets)],+ layerOrder: [layer.id]+ };+ const geojsonState = layerTypeChangeUpdater(state, {oldLayer: layer, newType: 'geojson'});+ const mosaicState = layerTypeChangeUpdater(geojsonState, {+ oldLayer: geojsonState.layers[0],+ newType: 'voronoi'+ });+ expect(mosaicState.layers[0].config.columnMode).toBe('geojson');+ expect(mosaicState.layerData[0].data).toEqual(centroids.data);+ layer.updateLayerConfig({+ columns: {...layer.config.columns, geojson: {value: null, fieldIdx: -1}}+ });+ expect(layer.hasAllColumns()).toBe(false);+ expect(layer.formatLayerData(datasets).data).toEqual([]);+});++test.each([new Float64(), new Int64()])(+ 'reads numeric Arrow-backed coordinates: %s',+ async type => {+ const values = type instanceof Int64 ? [-1n, 1n, -1n, 1n] : [-1, 1, -1, 1];+ const table = new Table({+ longitude: vectorFromArray(values, type),+ latitude: vectorFromArray([-1, -1, 1, 1], new Float64()),+ value: vectorFromArray([10, 20, 30, 40], new Float64())+ });+ const {layer, datasets} = await setup(processArrowBatches(table.batches)!);+ expect(layer.formatLayerData(datasets).data.map(cell => cell.position)).toEqual(+ rows.map(row => row.slice(0, 2))+ );+ }+);++test('saves Voronoi settings and switches between point and Voronoi without changing data', async () => {+ const {layer, dataset, datasets} = await setup();+ layer.updateLayerVisConfig({boundsPadding: 25, strokeColor: [12, 34, 56]});+ const saved = SchemaManager.getConfigToSave({+ ...StateWFiles,+ visState: {...StateWFiles.visState, layers: [layer], layerOrder: [layer.id]}+ });+ const parsed = SchemaManager.parseSavedConfig(saved)!;+ expect(parsed.visState!.layers![0].type).toBe('voronoi');+ expect(parsed.visState!.layers![0].config.visConfig).toEqual(layer.config.visConfig);+ const state = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [layer],+ layerData: [layer.formatLayerData(datasets)],+ layerOrder: [layer.id]+ };+ const pointState = layerTypeChangeUpdater(state, {oldLayer: layer, newType: 'point'});+ expect(pointState.layers[0].type).toBe('point');+ const mosaicState = layerTypeChangeUpdater(pointState, {+ oldLayer: pointState.layers[0],+ newType: 'voronoi'+ });+ expect(mosaicState.layers[0].hasAllColumns()).toBe(true);+ expect(mosaicState.layerData[0].data).toHaveLength(4);+ expect(dataset.dataContainer.numRows()).toBe(4);+});diff --git a/src/layers/src/voronoi-layer/voronoi-layer.ts b/src/layers/src/voronoi-layer/voronoi-layer.tsnew file mode 100644index 000000000..3dcb392ac--- /dev/null+++ b/src/layers/src/voronoi-layer/voronoi-layer.ts@@ -0,0 +1,258 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {PolygonLayer} from '@deck.gl/layers';+import type {DataFilterExtensionProps} from '@deck.gl/extensions';+import {Datasets, KeplerTable} from '@kepler.gl/table';+import {GEOARROW_METADATA_KEY, GEOJSON_FIELDS, LAYER_VIS_CONFIGS} from '@kepler.gl/constants';+import {DataContainerInterface} from '@kepler.gl/utils';+import {DATA_TYPES} from 'type-analyzer';+import Layer from '../base-layer';+import {getFilterDataFunc} from '../aggregation-layer';+import {getCentroidFromGeometry, parseGeoJsonRawFeature} from '../geojson-layer/geojson-utils';+import {applyDefaultColorField} from '../layer-color-utils';+import {assignPointPairToLayerColumn} from '../layer-utils';+import VoronoiLayerIcon from './voronoi-layer-icon';+import {+ getVoronoiClip,+ prepareVoronoiSites,+ tessellateVoronoiMosaic,+ VoronoiCell,+ VoronoiMosaic,+ VoronoiSite+} from './voronoi-utils';++type VoronoiLayerData = {+ data: VoronoiCell[];+ mosaic?: VoronoiMosaic;+} & Record<string, any>;++const SUPPORTED_COLUMN_MODES = [+ {key: 'points', label: 'Point Columns', requiredColumns: ['lat', 'lng']},+ {key: 'geojson', label: 'GeoJSON Centroids', requiredColumns: ['geojson']}+];++export const voronoiVisConfigs = {+ opacity: 'opacity',+ colorRange: 'colorRange',+ filled: {...LAYER_VIS_CONFIGS.filled, defaultValue: true},+ stroked: {...LAYER_VIS_CONFIGS.stroked, defaultValue: true},+ strokeColor: {...LAYER_VIS_CONFIGS.strokeColor, defaultValue: [30, 35, 45]},+ thickness: {+ ...LAYER_VIS_CONFIGS.thickness,+ defaultValue: 0.8,+ range: [0, 5],+ step: 0.1,+ allowCustomValue: false+ },+ boundsPadding: {+ type: 'number',+ property: 'boundsPadding',+ defaultValue: 10,+ range: [0, 100],+ step: 1,+ isRanged: false,+ label: 'layerVisConfigs.voronoi.boundsPadding',+ description: 'layerVisConfigs.voronoi.boundsPaddingDescription'+ }+};++export default class VoronoiLayer extends Layer {+ private source?: ReturnType<typeof prepareVoronoiSites>;+ private clip?: ReturnType<typeof getVoronoiClip>;+ private mosaic?: VoronoiMosaic;+ private geometryTriggers?: {+ dataContainer: DataContainerInterface;+ dataRevision: number;+ columns: Layer['config']['columns'];+ columnMode: Layer['config']['columnMode'];+ padding: number;+ filteredIndex: number[];+ gpuFilter: KeplerTable['gpuFilter'];+ };++ constructor(props) {+ super(props);+ this.registerVisConfig(voronoiVisConfigs);+ }++ get type() {+ return 'voronoi';+ }++ get name() {+ return 'Voronoi Mosaic';+ }++ get layerIcon() {+ return VoronoiLayerIcon;+ }++ get supportedColumnModes() {+ return SUPPORTED_COLUMN_MODES;+ }++ get columnPairs() {+ return {lat: {pair: 'lng', fieldPairKey: 'lat'}, lng: {pair: 'lat', fieldPairKey: 'lng'}};+ }++ get visualChannels() {+ return {color: {...super.visualChannels.color, accessor: 'getFillColor'}};+ }++ static findDefaultLayerProps(dataset: KeplerTable) {+ const geometryColumns = dataset.fields+ .filter(+ field =>+ (field.type === 'geojson' || field.type === 'geoarrow') &&+ [+ DATA_TYPES.GEOMETRY,+ DATA_TYPES.GEOMETRY_FROM_STRING,+ DATA_TYPES.PAIR_GEOMETRY_FROM_STRING+ ].includes(field.analyzerType)+ )+ .map(field => field.name);+ const geojsonColumns =+ this.findDefaultColumnField(+ {geojson: [...GEOJSON_FIELDS.geojson, ...geometryColumns]},+ dataset.fields+ ) || [];+ // Offer column defaults when changing layer type, without creating extra layers on import.+ return {+ props: [],+ altProps: [+ ...(dataset.fieldPairs || []).map(pair => ({+ label: 'Voronoi Mosaic',+ columns: assignPointPairToLayerColumn(pair, false),+ columnMode: 'points'+ })),+ ...geojsonColumns.map(columns => ({+ label: 'Voronoi Mosaic',+ columns,+ columnMode: 'geojson'+ }))+ ]+ };+ }++ setInitialLayerConfig(dataset: KeplerTable) {+ applyDefaultColorField(this, dataset);+ return this;+ }++ getPositionAccessor(dataContainer?: DataContainerInterface) {+ if (!dataContainer || !this.hasAllColumns()) return () => [NaN, NaN];+ if (this.config.columnMode === 'geojson') {+ const {fieldIdx} = this.config.columns.geojson;+ const encoding = dataContainer.getField?.(fieldIdx)?.metadata?.get(GEOARROW_METADATA_KEY);+ return ({index}: {index: number}) => {+ const feature = parseGeoJsonRawFeature(dataContainer.valueAt(index, fieldIdx), encoding);+ return getCentroidFromGeometry(feature?.geometry) || [NaN, NaN];+ };+ }+ const {lng, lat} = this.config.columns;+ return ({index}: {index: number}) =>+ [lng, lat].map(({fieldIdx}) => {+ const value = dataContainer.valueAt(index, fieldIdx);+ return typeof value === 'bigint' ? Number(value) : value;+ });+ }++ formatLayerData(datasets: Datasets, oldLayerData?: VoronoiLayerData): VoronoiLayerData {+ const dataset = this.config.dataId ? datasets[this.config.dataId] : undefined;+ if (!dataset || !this.hasAllColumns()) {+ this.source = undefined;+ this.clip = undefined;+ this.mosaic = undefined;+ this.geometryTriggers = undefined;+ this.updateMeta({bounds: null});+ return {data: []};+ }+ const {dataContainer, dataRevision, gpuFilter} = dataset;+ const filteredIndex = dataset.filteredIndexByLayer?.[this.id] ?? dataset.filteredIndex;+ const getFilterValue = gpuFilter.filterValueAccessor(dataContainer)();+ const {columns, columnMode, visConfig} = this.config;+ const previous = this.geometryTriggers;+ const sourceChanged =+ !this.source ||+ previous?.dataContainer !== dataContainer ||+ previous.dataRevision !== dataRevision ||+ previous.columns !== columns ||+ previous.columnMode !== columnMode;+ if (sourceChanged) {+ const getPosition = this.getPositionAccessor(dataContainer);+ const sites: VoronoiSite[] = [];+ for (let index = 0; index < dataContainer.numRows(); index++) {+ sites.push({index, position: getPosition({index}) as [number, number]});+ }+ this.source = prepareVoronoiSites(sites);+ }+ const clipChanged =+ !this.clip || sourceChanged || previous?.padding !== visConfig.boundsPadding;+ if (clipChanged) {+ this.clip = getVoronoiClip(this.source!, visConfig.boundsPadding);+ }+ if (+ !this.mosaic ||+ clipChanged ||+ previous?.filteredIndex !== filteredIndex ||+ previous.gpuFilter !== gpuFilter+ ) {+ const visible = new Set(filteredIndex);+ const hasGpuFilter = Object.values(gpuFilter.filterValueUpdateTriggers).some(+ trigger => trigger !== null+ );+ const matchesGpuFilter = hasGpuFilter+ ? getFilterDataFunc(gpuFilter.filterRange, getFilterValue)+ : null;+ this.mosaic = tessellateVoronoiMosaic(+ this.source!,+ this.clip!,+ site => visible.has(site.index) && (!matchesGpuFilter || matchesGpuFilter(site))+ );+ this.geometryTriggers = {+ dataContainer,+ dataRevision,+ columns,+ columnMode,+ padding: visConfig.boundsPadding,+ filteredIndex,+ gpuFilter+ };+ this.updateMeta({bounds: this.mosaic.bounds});+ }+ const data = oldLayerData?.mosaic === this.mosaic ? oldLayerData.data : this.mosaic.cells;+ return {+ data,+ mosaic: this.mosaic,+ getFilterValue,+ ...this.getAttributeAccessors({dataContainer})+ };+ }++ renderLayer(opts) {+ const {data, gpuFilter} = opts;+ const {visConfig} = this.config;+ return [+ new PolygonLayer<VoronoiCell, DataFilterExtensionProps<VoronoiCell>>({+ ...this.getDefaultDeckLayerProps(opts),+ filterRange: gpuFilter?.filterRange as [number, number][] | undefined,+ data: data.data,+ getPolygon: cell => cell.polygon,+ getFillColor: data.getFillColor,+ getFilterValue: data.getFilterValue,+ getLineColor: visConfig.strokeColor || this.config.color,+ getLineWidth: visConfig.thickness,+ lineWidthUnits: 'pixels',+ filled: visConfig.filled,+ stroked: visConfig.stroked,+ extruded: false,+ autoHighlight: true,+ updateTriggers: {+ ...this.getVisualChannelUpdateTriggers(),+ getFilterValue: gpuFilter.filterValueUpdateTriggers+ }+ })+ ];+ }+}diff --git a/src/layers/src/voronoi-layer/voronoi-utils.spec.ts b/src/layers/src/voronoi-layer/voronoi-utils.spec.tsnew file mode 100644index 000000000..f6eec50dc--- /dev/null+++ b/src/layers/src/voronoi-layer/voronoi-utils.spec.ts@@ -0,0 +1,152 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {lngLatToWorld} from '@math.gl/web-mercator';+import {buildVoronoiMosaic, VoronoiSite} from './voronoi-utils';++const sites = (coordinates: number[][]): VoronoiSite[] =>+ coordinates.map((position, index) => ({index, position: position as [number, number]}));++test('creates a cell for each site with vertices closest to its owner in projected space', () => {+ const input = sites([+ [-2, -1],+ [1, -2],+ [2, 2],+ [-1, 3],+ [0, 0]+ ]);+ const {cells} = buildVoronoiMosaic(input, 15);+ expect(cells.map(cell => cell.index)).toEqual([0, 1, 2, 3, 4]);+ const projected = input.map(site => lngLatToWorld(site.position));+ const distance = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2;+ for (const cell of cells) {+ expect(cell.polygon[0]).toEqual(cell.polygon[cell.polygon.length - 1]);+ for (const vertex of cell.polygon) {+ const point = lngLatToWorld(vertex);+ for (const other of projected) {+ expect(distance(point, projected[cell.index])).toBeLessThanOrEqual(+ distance(point, other) + 1e-8+ );+ }+ }+ }+});++test.each(+ [+ [[0, 0]],+ [+ [-1, 0],+ [1, 0]+ ],+ [+ [-1, 0],+ [0, 0],+ [1, 0]+ ],+ [+ [0, -1],+ [0, 0],+ [0, 1]+ ]+ ].map(coordinates => ({coordinates}))+)('produces finite nonzero cells for $coordinates', ({coordinates}) => {+ const {cells, bounds} = buildVoronoiMosaic(sites(coordinates), 0);+ expect(cells).toHaveLength(coordinates.length);+ expect(bounds![2]).toBeGreaterThan(bounds![0]);+ expect(bounds![3]).toBeGreaterThan(bounds![1]);+ cells.forEach(cell => {+ expect(cell.polygon.length).toBeGreaterThanOrEqual(4);+ expect(cell.polygon.flat().every(Number.isFinite)).toBe(true);+ const area = cell.polygon.slice(1).reduce((sum, point, i) => {+ const previous = cell.polygon[i];+ return sum + previous[0] * point[1] - point[0] * previous[1];+ }, 0);+ expect(Math.abs(area)).toBeGreaterThan(0);+ });+});++test('ignores invalid coordinates and assigns coincident sites to the first row', () => {+ expect(buildVoronoiMosaic([], 10)).toEqual({cells: [], bounds: null});+ const {cells} = buildVoronoiMosaic(+ sites([+ [NaN, 0],+ [0, Infinity],+ [181, 0],+ [0, 90],+ [0, 0],+ [0, 0],+ [1, 1]+ ]),+ 10+ );+ expect(cells.map(cell => cell.index)).toEqual([4, 6]);+ expect(buildVoronoiMosaic(sites([[NaN, NaN]]), 10)).toEqual({cells: [], bounds: null});+});++test('clips cells to padded dataset bounds without moving their internal bisector', () => {+ const input = sites([+ [-1, -1],+ [1, 1]+ ]);+ const tight = buildVoronoiMosaic(input, 0);+ const padded = buildVoronoiMosaic(input, 25);+ expect(tight.bounds![0]).toBeCloseTo(-1);+ expect(tight.bounds![2]).toBeCloseTo(1);+ expect(padded.bounds![0]).toBeCloseTo(-1.5);+ expect(padded.bounds![2]).toBeCloseTo(1.5);+ for (const cell of padded.cells) {+ for (const [lng, lat] of cell.polygon) {+ expect(lng).toBeGreaterThanOrEqual(padded.bounds![0] - 1e-8);+ expect(lng).toBeLessThanOrEqual(padded.bounds![2] + 1e-8);+ expect(lat).toBeGreaterThanOrEqual(padded.bounds![1] - 1e-8);+ expect(lat).toBeLessThanOrEqual(padded.bounds![3] + 1e-8);+ }+ }+});++test('keeps neighboring sites together across the antimeridian', () => {+ const {cells, bounds} = buildVoronoiMosaic(+ sites([+ [179, 0],+ [-179, 0]+ ]),+ 0+ );+ expect(cells).toHaveLength(2);+ expect(bounds![0]).toBeCloseTo(179);+ expect(bounds![2]).toBeCloseTo(181);+ expect(Math.max(...cells[0].polygon.map(point => point[0]))).toBeCloseTo(180);+ expect(Math.min(...cells[1].polygon.map(point => point[0]))).toBeCloseTo(180);+});++test('filtered dateline sites retain the full extent and the same longitude unwrapping', () => {+ const input = sites([+ [179, 0],+ [-179, 0]+ ]);+ const original = buildVoronoiMosaic(input, 10);+ const filtered = buildVoronoiMosaic(input, 10, site => site.index === 1);+ expect(filtered.bounds).toEqual(original.bounds);+ expect(filtered.cells.map(cell => cell.index)).toEqual([1]);+ expect(Math.min(...filtered.cells[0].polygon.map(point => point[0]))).toBeCloseTo(+ original.bounds![0]+ );+ expect(Math.max(...filtered.cells[0].polygon.map(point => point[0]))).toBeCloseTo(+ original.bounds![2]+ );+ expect(buildVoronoiMosaic(input, 10, () => false)).toEqual({cells: [], bounds: original.bounds});+});++test('the first remaining duplicate owns the cell when an earlier duplicate is filtered out', () => {+ const input = sites([+ [0, 0],+ [0, 0],+ [2, 0]+ ]);+ const original = buildVoronoiMosaic(input, 10);+ const filtered = buildVoronoiMosaic(input, 10, site => site.index !== 0);+ expect(filtered.cells.map(cell => cell.index)).toEqual([1, 2]);+ expect(filtered.cells[0].polygon).toEqual(original.cells[0].polygon);+ expect(filtered.bounds).toEqual(original.bounds);+});diff --git a/src/layers/src/voronoi-layer/voronoi-utils.ts b/src/layers/src/voronoi-layer/voronoi-utils.tsnew file mode 100644index 000000000..b6d5bdf50--- /dev/null+++ b/src/layers/src/voronoi-layer/voronoi-utils.ts@@ -0,0 +1,141 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {Delaunay} from 'd3-delaunay';+import {lngLatToWorld, worldToLngLat, MAX_LATITUDE} from '@math.gl/web-mercator';++export type VoronoiSite = {index: number; position: [number, number]};+export type VoronoiCell = VoronoiSite & {polygon: [number, number][]};+export type VoronoiMosaic = {+ cells: VoronoiCell[];+ bounds: [number, number, number, number] | null;+};+type Bounds = [number, number, number, number];+type VoronoiSource = {+ sites: VoronoiSite[];+ coordinates: [number, number][];+ extent: Bounds | null;+};+type VoronoiClip = {extent: Bounds | null; bounds: Bounds | null};++// A single site still needs a finite display extent: a 1 km square at the equator.+const MIN_EXTENT = (512 * 1000) / 40075016.68557849;++/** Normalize, project and measure the full dataset once, independently of filters. */+export function prepareVoronoiSites(sites: VoronoiSite[]): VoronoiSource {+ const located: VoronoiSite[] = [];+ for (const site of sites) {+ const [lng, lat] = site.position;+ if (+ !Number.isFinite(lng) ||+ !Number.isFinite(lat) ||+ Math.abs(lng) > 180 ||+ Math.abs(lat) > MAX_LATITUDE+ ) {+ continue;+ }+ const longitude = lng === 180 ? -180 : lng;+ located.push({index: site.index, position: [longitude, lat]});+ }+ if (!located.length) return {sites: [], coordinates: [], extent: null};++ // Unwrap across the largest empty longitude gap so dateline neighbors stay neighbors.+ const longitudes = located.map(site => site.position[0]).sort((a, b) => a - b);+ let west = longitudes[0];+ let largestGap = longitudes[0] + 360 - longitudes[longitudes.length - 1];+ for (let i = 1; i < longitudes.length; i++) {+ const gap = longitudes[i] - longitudes[i - 1];+ if (gap > largestGap) {+ largestGap = gap;+ west = longitudes[i];+ }+ }+ const coordinates = located.map(({position: [lng, lat]}) =>+ lngLatToWorld([lng < west ? lng + 360 : lng, lat])+ );+ let minX = Infinity;+ let minY = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ for (const [x, y] of coordinates) {+ minX = Math.min(minX, x);+ minY = Math.min(minY, y);+ maxX = Math.max(maxX, x);+ maxY = Math.max(maxY, y);+ }+ const span = Math.max(maxX - minX, maxY - minY, MIN_EXTENT);+ // Give collinear/single-site data a nonzero extent even with no padding.+ if (maxX === minX) {+ minX -= span / 2;+ maxX += span / 2;+ }+ if (maxY === minY) {+ minY -= span / 2;+ maxY += span / 2;+ }+ return {sites: located, coordinates, extent: [minX, minY, maxX, maxY]};+}++export function getVoronoiClip(source: VoronoiSource, paddingPercent: number): VoronoiClip {+ if (!source.extent) return {extent: null, bounds: null};+ const [minX, minY, maxX, maxY] = source.extent;+ const padding = Number.isFinite(paddingPercent)+ ? Math.max(0, Math.min(100, paddingPercent)) / 100+ : 0.1;+ const padX = (maxX - minX) * padding;+ const padY = (maxY - minY) * padding;+ const extent: [number, number, number, number] = [+ minX - padX,+ Math.max(0, minY - padY),+ maxX + padX,+ Math.min(512, maxY + padY)+ ];+ const [westLng, south] = worldToLngLat([extent[0], extent[1]]);+ const [east, north] = worldToLngLat([extent[2], extent[3]]);+ return {extent, bounds: [westLng, south, east, north]};+}++export function tessellateVoronoiMosaic(+ source: VoronoiSource,+ clip: VoronoiClip,+ includeSite: (site: VoronoiSite) => boolean = () => true+): VoronoiMosaic {+ if (!clip.extent) return {cells: [], bounds: null};+ const {sites, coordinates} = source;+ // Keep bounds and longitude unwrapping anchored to the full dataset. Only the+ // sites participating in the tessellation change when a filter changes.+ const unique: VoronoiSite[] = [];+ const activeCoordinates: typeof coordinates = [];+ const seen = new Set<string>();+ sites.forEach((site, index) => {+ if (!includeSite(site)) return;+ const key = site.position.join(',');+ // Coincident sites share a region, owned by the first remaining row.+ if (seen.has(key)) return;+ seen.add(key);+ unique.push(site);+ activeCoordinates.push(coordinates[index]);+ });+ const voronoi = Delaunay.from(activeCoordinates).voronoi(clip.extent);+ const cells: VoronoiCell[] = [];+ unique.forEach((site, index) => {+ const polygon = voronoi.cellPolygon(index);+ if (polygon) {+ cells.push({+ ...site,+ polygon: polygon.map(point => worldToLngLat(point) as [number, number])+ });+ }+ });+ return {cells, bounds: clip.bounds};+}++/** Planar nearest-site cells in Web Mercator, independent of the map viewport. */+export function buildVoronoiMosaic(+ sites: VoronoiSite[],+ paddingPercent: number,+ includeSite: (site: VoronoiSite) => boolean = () => true+): VoronoiMosaic {+ const source = prepareVoronoiSites(sites);+ return tessellateVoronoiMosaic(source, getVoronoiClip(source, paddingPercent), includeSite);+}diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 4103f22fa..c1b3eedb6 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -150,6 +150,7 @@ export default {icon: 'icon',heatmap: 'heatmap',contour: 'contour',+ voronoi: 'Voronoi Mosaic',hexagon: 'hexagon',hexagonid: 'H3',trip: 'trip',@@ -175,6 +176,12 @@ export default {aggregation: 'Aggregation'},layerVisConfigs: {+ voronoi: {+ bounds: 'Cell Bounds',+ boundsPadding: 'Bounds Padding (%)',+ boundsPaddingDescription:+ 'Extend the dataset bounds on each side. Cells represent nearest sites in the map projection, not travel-time catchments.'+ },angle: 'Angle',strokeWidth: 'Stroke Width (Pixels)',strokeWidthRange: 'Stroke Width Range',diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex 1a9cddd94..eaf8734a8 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -194,6 +194,11 @@ export type KeplerApplicationConfig = {// Existing Contour layers in saved maps can still render.enableContourLayer?: boolean;+ // Voronoi Mosaic layer config+ // Enabled by default. Set false to hide Voronoi in layer type pickers.+ // Existing Voronoi layers in saved maps can still render.+ enableVoronoiLayer?: boolean;+/** Whether to show example URLs in tileset setup forms (vector tile, raster tile, WMS, 3D tile) */showInlineTilesetExamples?: boolean;@@ -485,6 +490,9 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {// Contour layer config -- disable via initApplicationConfigenableContourLayer: true,+ // Voronoi Mosaic layer config -- disable via initApplicationConfig+ enableVoronoiLayer: true,+showInlineTilesetExamples: true,// Image export configdiff --git a/src/utils/src/filter-utils.ts b/src/utils/src/filter-utils.tsindex 765e2da94..921d40d2b 100644--- a/src/utils/src/filter-utils.ts+++ b/src/utils/src/filter-utils.ts@@ -564,6 +564,7 @@ export const getPolygonFilterFunctor = (layer, filter, dataContainer) => {switch (layer.type) {case LAYER_TYPES.point:case LAYER_TYPES.icon:+ case LAYER_TYPES.voronoi:if (layer.config?.columnMode === 'geoarrow' &&dataContainerdiff --git a/test/browser/components/side-panel/layer-configurator-test.js b/test/browser/components/side-panel/layer-configurator-test.jsindex 0e551064f..ca48bf4eb 100644--- a/test/browser/components/side-panel/layer-configurator-test.js+++ b/test/browser/components/side-panel/layer-configurator-test.js@@ -1893,3 +1893,77 @@ test('Components -> LayerConfigurator -> collapsed Heatmap surface toggle group'}});});++test('Components -> LayerConfigurator -> Voronoi fill, outline and bounds controls', async t => {+ const layer = new KeplerGlLayers.VoronoiLayer({dataId: testCsvDataId});+ const changed = sinon.spy();+ function Editor() {+ const [, setVersion] = React.useState(0);+ return (+ <IntlWrapper>+ <LayerConfigurator+ {...defaultProps}+ layer={layer}+ updateLayerConfig={value => {+ layer.updateLayerConfig(value);+ setVersion(version => version + 1);+ }}+ updateLayerVisConfig={value => {+ changed(value);+ layer.updateLayerVisConfig(value);+ setVersion(version => version + 1);+ }}+ />+ </IntlWrapper>+ );+ }+ const view = renderWithTheme(<Editor />);+ const editor = within(view.container);+ const user = userEvent.setup();+ try {+ fireEvent.click(editor.getByLabelText('GeoJSON Centroids'));+ t.equal(layer.config.columnMode, 'geojson', 'selects GeoJSON centroid input');+ t.equal(layer.hasAllColumns(), false, 'requires a geometry column before rendering');+ fireEvent.click(editor.getByLabelText('Point Columns'));+ t.equal(layer.config.columnMode, 'points', 'can return to latitude/longitude input');+ const fill = editor.getByText('Fill Color').closest('.layer-config-group');+ const stroke = editor.getByText('Stroke Color').closest('.layer-config-group');+ fireEvent.click(stroke.querySelector('.layer-config-group__header'));+ t.notOk(+ stroke.querySelector('[id="property.thickness"]'),+ 'stroke width does not offer a custom-input toggle'+ );+ const strokeWidth = stroke.querySelector('.kg-range-slider__input');+ await user.clear(strokeWidth);+ await user.type(strokeWidth, '2');+ await user.tab();+ t.deepEqual(changed.lastCall.args[0], {thickness: 2}, 'stroke width uses the standard slider');+ fireEvent.click(+ within(fill.querySelector('.layer-config-group__header')).getByRole('checkbox', {+ hidden: true+ })+ );+ t.equal(layer.config.visConfig.filled, false, 'fill can be disabled');+ t.equal(layer.config.visConfig.stroked, true, 'disabling fill preserves outlines');+ fireEvent.click(+ within(stroke.querySelector('.layer-config-group__header')).getByRole('checkbox', {+ hidden: true+ })+ );+ t.equal(layer.config.visConfig.stroked, false, 'outline can be disabled independently');+ const bounds = editor.getByText('Cell Bounds').closest('.layer-config-group');+ fireEvent.click(bounds.querySelector('.layer-config-group__header'));+ const input = bounds.querySelector('.kg-range-slider__input');+ await user.clear(input);+ await user.type(input, '25');+ await user.tab();+ t.deepEqual(+ changed.lastCall.args[0],+ {boundsPadding: 25},+ 'padding commits through the standard slider'+ );+ } finally {+ view.unmount();+ t.end();+ }+});diff --git a/test/browser/components/side-panel/layer-manager-test.js b/test/browser/components/side-panel/layer-manager-test.jsindex 94b492202..e40150e39 100644--- a/test/browser/components/side-panel/layer-manager-test.js+++ b/test/browser/components/side-panel/layer-manager-test.js@@ -62,66 +62,71 @@ const defaultProps = {overlayBlending: 'normal'};-test('Components -> LayerManager -> contour picker follows application config in both list views', t => {- const {enableContourLayer} = getApplicationConfig();- t.equal(enableContourLayer, true, 'Contour is enabled by default');- const dataId = Object.keys(defaultProps.datasets)[0];- const layer = new LayerClasses.contour({id: 'optional-contour', dataId});- layer.updateLayerConfig({isConfigActive: true});- try {- for (const panelListView of ['list', 'byDataset']) {- initApplicationConfig({enableContourLayer: false});- const props = {- ...defaultProps,- layers: [layer],- layerOrder: [layer.id],- layerClasses: LayerClasses,- panelListView- };- const view = render(<LayerManager {...props} />, {- wrapper: ({children}) => (- <ThemeProvider theme={theme}>- <IntlWrapper>{children}</IntlWrapper>- </ThemeProvider>- )- });- try {- const selector = view.container.querySelector('.layer-config__type');- t.ok(selector, `${panelListView}: existing Contour layer remains configurable`);- t.equal(- selector.querySelector('.layer-type-selector__item__label').textContent.toLowerCase(),- 'contour',- 'still identifies the saved layer when its type is disabled'- );- fireEvent.click(selector.querySelector('.item-selector__dropdown'));-- for (const enabled of [false, true, false, undefined]) {- initApplicationConfig({enableContourLayer: enabled});- view.rerender(<LayerManager {...props} />);- const options = Array.from(- view.baseElement.querySelectorAll(- '.layer-type-selector__item .layer-type-selector__item__label'- ),- element => element.textContent.toLowerCase()- );+for (const {type, flag, label} of [+ {type: 'contour', flag: 'enableContourLayer', label: 'Contour'},+ {type: 'voronoi', flag: 'enableVoronoiLayer', label: 'Voronoi Mosaic'}+]) {+ test(`Components -> LayerManager -> ${type} picker follows application config in both list views`, t => {+ const originalFlag = getApplicationConfig()[flag];+ t.equal(originalFlag, true, `${label} is enabled by default`);+ const dataId = Object.keys(defaultProps.datasets)[0];+ const layer = new LayerClasses[type]({id: `optional-${type}`, dataId});+ layer.updateLayerConfig({isConfigActive: true});+ try {+ for (const panelListView of ['list', 'byDataset']) {+ initApplicationConfig({[flag]: false});+ const props = {+ ...defaultProps,+ layers: [layer],+ layerOrder: [layer.id],+ layerClasses: LayerClasses,+ panelListView+ };+ const view = render(<LayerManager {...props} />, {+ wrapper: ({children}) => (+ <ThemeProvider theme={theme}>+ <IntlWrapper>{children}</IntlWrapper>+ </ThemeProvider>+ )+ });+ try {+ const selector = view.container.querySelector('.layer-config__type');+ t.ok(selector, `${panelListView}: existing ${label} layer remains configurable`);t.equal(- options.includes('contour'),- enabled === true,- `${panelListView}: Contour is offered only when the flag is true (${enabled})`+ selector.querySelector('.layer-type-selector__item__label').textContent.toLowerCase(),+ label.toLowerCase(),+ 'still identifies the saved layer when its type is disabled');- t.ok(options.includes('point'), 'regular layer types stay available');- t.equal(layer.type, 'contour', 'changing the flag does not replace the saved layer');+ fireEvent.click(selector.querySelector('.item-selector__dropdown'));++ for (const enabled of [false, true, false, undefined]) {+ initApplicationConfig({[flag]: enabled});+ view.rerender(<LayerManager {...props} />);+ const options = Array.from(+ view.baseElement.querySelectorAll(+ '.layer-type-selector__item .layer-type-selector__item__label'+ ),+ element => element.textContent.toLowerCase()+ );+ t.equal(+ options.includes(label.toLowerCase()),+ enabled === true,+ `${panelListView}: ${label} is offered only when the flag is true (${enabled})`+ );+ t.ok(options.includes('point'), 'regular layer types stay available');+ t.equal(layer.type, type, 'changing the flag does not replace the saved layer');+ }+ } finally {+ view.unmount();+ view.container.remove();}- } finally {- view.unmount();- view.container.remove();}+ } finally {+ initApplicationConfig({[flag]: originalFlag});}- } finally {- initApplicationConfig({enableContourLayer});- }- t.end();-});+ t.end();+ });+}test('Components -> LayerManager -> render -> list view', t => {// mountdiff --git a/yarn.lock b/yarn.lockindex 281188b80..7441f7386 100644--- a/yarn.lock+++ b/yarn.lock@@ -4177,6 +4177,7 @@ __metadata:"@turf/distance": "npm:^7.2.0""@turf/helpers": "npm:^7.2.0""@types/d3-contour": "npm:^3.0.6"+ "@types/d3-delaunay": "npm:^6""@types/geojson": "npm:^7946.0.8""@types/keymirror": "npm:^0.1.1""@types/styled-components": "npm:^5.1.32"@@ -4185,6 +4186,7 @@ __metadata:buffer: "npm:6.0.3"d3-array: "npm:^2.8.0"d3-contour: "npm:^3.0.2"+ d3-delaunay: "npm:^6"d3-format: "npm:^3.1.0"d3-interpolate: "npm:^3.0.1"d3-shape: "npm:^1.2.0"@@ -10272,6 +10274,13 @@ __metadata:languageName: nodelinkType: hard+"@types/d3-delaunay@npm:^6":+ version: 6.0.4+ resolution: "@types/d3-delaunay@npm:6.0.4"+ checksum: 10c0/d154a8864f08c4ea23ecb9bdabcef1c406a25baa8895f0cb08a0ed2799de0d360e597552532ce7086ff0cdffa8f3563f9109d18f0191459d32bb620a36939123+ languageName: node+ linkType: hard+"@types/d3-scale@npm:^3.2.2":version: 3.3.5resolution: "@types/d3-scale@npm:3.3.5"@@ -15517,6 +15526,15 @@ __metadata:languageName: nodelinkType: hard+"d3-delaunay@npm:^6":+ version: 6.0.5+ resolution: "d3-delaunay@npm:6.0.5"+ dependencies:+ delaunator: "npm:5"+ checksum: 10c0/ee29d7549fcd3c3e7730c324705e8095b115b9e9166f2d24d89304e71e994a4185130bd624af9b6518d0008ff22d32559e75522a0dd19745ca49ad5246ecd7a9+ languageName: node+ linkType: hard+"d3-dispatch@npm:1 - 3":version: 3.0.1resolution: "d3-dispatch@npm:3.0.1"@@ -16206,7 +16224,7 @@ __metadata:languageName: nodelinkType: hard-"delaunator@npm:^5.1.0":+"delaunator@npm:5, delaunator@npm:^5.1.0":version: 5.1.0resolution: "delaunator@npm:5.1.0"dependencies: