Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(layers): add scalar contour layer prototype (#3950)
Igor Dykhta046a81edcd7e
diff --git a/babel-register.js b/babel-register.jsindex ec92a1e97..2bd50f180 100644--- a/babel-register.js+++ b/babel-register.js@@ -8,6 +8,7 @@ const forceTranspile = [/@flowmap\.gl\//,/@math\.gl\//,/\/node_modules\/d3-/,+ /\/node_modules\/(delaunator|robust-predicates)\//,/\/node_modules\/kdbush\//,// For some reason babel crashes even before trying to transpile this library// Instead we force transpile @deck.gl/layers which includes it, and alias to a transpiled version in babel.config.jsdiff --git a/docs/user-guides/c-types-of-layers/contour.md b/docs/user-guides/c-types-of-layers/contour.mdnew file mode 100644index 000000000..45c5a2888--- /dev/null+++ b/docs/user-guides/c-types-of-layers/contour.md@@ -0,0 +1,129 @@+# Contour layer (prototype)++The Contour layer draws smooth, nested regions and outlines from a numeric scalar field.+Values can represent any quantity; the layer does not calculate travel time or point density.++## Layer availability++Contour is enabled in layer type pickers by default. To hide it, set the application+config flag before mounting the map:++```js+import {initApplicationConfig} from '@kepler.gl/utils';++initApplicationConfig({enableContourLayer: false});+```++The demo app also accepts `applicationConfig.enableContourLayer` in its runtime+`config.json`. Setting the flag to `false` hides Contour from the picker; existing+Contour layers in saved maps still load and render, as with other optional layer types.++## Try the sample++Start the demo app with `yarn start` and append `?sample=contour` to its URL. The sample+loads an abstract scalar field around Frankfurt with turquoise fills and outlines.+Use `?sample=contour-scattered` for scattered measurements of the same field.+It is synthetic data, not a travel-time map. The generator is in+`examples/demo-app/src/data/sample-contour-data.ts`.++## Input++Select **Contour** in the layer selector, then choose a column mode:++- **Scalar samples**: assign numeric longitude, latitude, and value columns.+- **GeoJSON**: assign a geometry column and a numeric value column. Each row produces+ one sample at the geometry's representative point, using the same centroid helper+ as Grid, Hexbin, and Heatmap. Points use their coordinates; lines, polygons, multi-+ geometries, and geometry collections use the average of their vertices (including+ closing ring vertices). This is not an area-weighted polygon centroid and can lie+ outside a concave feature. GeoJSON geometry/Feature objects and JSON strings are+ accepted. Missing, empty, or malformed geometries are skipped. The selected value+ column supplies the scalar; polygon boundaries do not clip the resulting contours.++Duplicate measurements at the same position are averaged; values remain in their+original units. Both column modes use the following surface settings:++- **Auto** (default): preserves supported regular grids, including missing cells. If+ the coordinates cannot form a supported grid, it interpolates scattered points.+ Quantized scattered coordinates can resemble an incomplete grid; choose+ **Scattered points** explicitly when those gaps should be interpolated.+- **Regular grid**: requires regularly spaced coordinates with at least two distinct+ coordinates per axis. Positions describe sample centers. Blank/nonfinite values,+ filtered-out samples, and missing cells remain holes, even after smoothing. A+ completely absent row or column can be inferred when other samples establish spacing.+- **Scattered points**: requires at least three distinct, non-collinear samples with+ finite values. Linear interpolation over Delaunay triangles creates a regular+ surface before smoothing and contour generation. It uses a regional projection+ with longitude scaled at the samples' central latitude. Cells outside the convex+ hull of valid samples stay empty. Null/nonfinite values and filtered-out samples+ are omitted; interpolation can bridge gaps between remaining points inside the hull.+ Filtering boundary points can therefore shrink the surface. No distance cutoff,+ barrier, or uncertainty model is applied across large unsampled gaps.++Polygon filters select source samples before smoothing and contour generation. Scalar+samples use their longitude/latitude; GeoJSON rows use the representative points described+above. Filters affect only their selected layers, including when layers share a dataset.+Regular grids retain rejected samples as holes; scattered inputs interpolate only retained+samples. Polygon filters do not clip the generated contours, so interpolation may bridge+excluded areas within the remaining samples' convex hull. Inverting, disabling, or clearing+the filter follows the same behavior as other layers.++## Controls++- **Color by level**: off uses the plain color (the default). Turn on to choose a+ standard or custom palette, including reversed palettes. Colors run from the+ lowest to highest generated contour value, independent of Invert. Palette stops+ are interpolated to the number of levels, so each level has its own sampled color.+ Both fills and outlines use these colors; translucent nested fills blend where+ they overlap. Switching modes preserves both the plain color and selected palette.+- **Input type**: Auto, Regular grid, or Scattered points, as described above.+- **Interpolation resolution**: 32–256 samples along the longer projected axis+ (default 192). Higher resolution gives finer contour geometry, not more measured+ detail. Applies only when interpolating; regular grids keep their native resolution.+- **Smoothing**: Gaussian standard deviation in grid cells; zero preserves the input.+ Smoothing changes the scalar field, so use it deliberately for measured quantities.+- **Number of levels**: 2–20 equally spaced thresholds. Automatic levels exclude the+ field's extrema to avoid outlining the entire rectangular extent. Numerically+ constant surfaces are omitted; roundoff from smoothing or interpolation does not+ create automatic levels.+- **Custom level range**: minimum and maximum thresholds, inclusive, in the original+ value units, selected with a two-handle range slider and read-only endpoint labels.+ Slider bounds use the exact finite minimum and maximum of the selected value+ column across the dataset and refresh when the dataset or column changes. Nulls+ and nonfinite values are ignored; empty or constant columns cannot supply a slider range.+ Enabling custom levels initializes both handles to the column bounds. When data+ changes, thresholds are kept within the new bounds; a disjoint selection resets+ to the full range. There is no manual-input fallback. These controls choose levels;+ they do not normalize or clamp the data.+- **Invert**: off fills regions where value ≤ threshold (the default). Turn on to+ fill regions where value ≥ threshold. Existing maps keep their saved direction.+- **Fill / outline**: enable independently. Each translucent filled region overlaps+ the larger regions below it, so opacity builds toward nested interiors. Outlines+ are rendered afterward, with brighter lines for inner regions.++Contours keep the same geographic shape and thresholds while panning or zooming.+Hover shows the value threshold. Settings are saved with the map.++The legend lists each generated contour level in ascending value order, with its+numeric threshold and ≤ or ≥ direction. The swatches use the outline+shades when outlines are enabled, or the blended color and accumulated opacity of+nested fills in fill-only mode. Each level occupies its own row, with the swatch beside its value.+The level list scrolls within a 156px height by default; the arrow beside the value+field expands or contracts this channel independently. The list, rows, and label+editor are shared with point legends. Click a label to edit it; its reset control+appears on hover or keyboard focus after editing and restores the default threshold.+Custom labels are saved+with the map and follow the value field, threshold, and ≤/≥ direction when colors+or levels change. Exports show the full list without editing controls.+Long labels show their full value on hover. The legend updates after+filtering, smoothing, or level changes and clears when no contours are generated.++## Prototype limits++This version supports regional 2D data, native grids up to 512 samples per axis, and+scattered-point interpolation onto grids up to 256 samples per axis. It does not support+globe mode, antimeridian-crossing data, routing, or dedicated contour export.+Geometry is calculated on the CPU when data or contour+settings change. Color, opacity, camera movement, and outline width do not regenerate it.+Smoothing is specified in cells, so its physical footprint depends on grid spacing or+interpolation resolution. The convex-hull boundary is approximated at grid resolution.diff --git a/examples/demo-app/src/app.tsx b/examples/demo-app/src/app.tsxindex 02c39b235..51aaf35f7 100644--- a/examples/demo-app/src/app.tsx+++ b/examples/demo-app/src/app.tsx@@ -69,6 +69,7 @@ import sampleAnimateTrip, {import sampleGpsData from './data/sample-gps-data';import sampleRowData, {config as rowDataConfig} from './data/sample-row-data';import {sampleFlowData, config as flowDataConfig} from './data/sample-flow-data';+import {createContourCsv, contourConfig, contourDataId} from './data/sample-contour-data';import {processCsvData, processGeojson, processRowObject} from '@kepler.gl/processors';/* eslint-enable no-unused-vars */@@ -674,6 +675,27 @@ const App = props => {);}, [dispatch]);+ const _loadContourData = useCallback(+ (scattered = false) => {+ dispatch(+ addDataToMap({+ datasets: [+ {+ info: {+ label: scattered ? 'Synthetic scattered samples' : 'Synthetic scalar grid',+ id: contourDataId+ },+ data: processCsvData(createContourCsv(scattered))+ }+ ],+ config: contourConfig as ParsedConfig,+ options: {keepExistingConfig: true}+ })+ );+ },+ [dispatch]+ );+const _loadFlowData = useCallback(() => {dispatch(addDataToMap({@@ -848,6 +870,10 @@ const App = props => {}, [dispatch]);const _loadSampleData = useCallback(() => {+ const sample = new URLSearchParams(window.location.search).get('sample');+ if (sample === 'contour' || sample === 'contour-scattered') {+ _loadContourData(sample === 'contour-scattered');+ }// _loadPointData();// _loadGeojsonData();// _loadTripGeoJson();@@ -881,6 +907,7 @@ const App = props => {_replaceData,_loadVectorTileData,_loadFlowData,+ _loadContourData,_loadWmsLayer,_loadRasterTileLayer,_loadBitmapLayer,diff --git a/examples/demo-app/src/data/sample-contour-data.ts b/examples/demo-app/src/data/sample-contour-data.tsnew file mode 100644index 000000000..b035d1f52--- /dev/null+++ b/examples/demo-app/src/data/sample-contour-data.ts@@ -0,0 +1,84 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++export const contourDataId = 'scalar-contour-sample';++/** Deterministic synthetic scalar field, sampled on a grid or at scattered positions. */+export function createContourSamples(scattered = false) {+ let seed = 42;+ const random = () => {+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;+ return seed / 4294967296;+ };+ const bumps = Array.from({length: 95}, () => ({+ x: (random() - 0.5) * 1.7,+ y: (random() - 0.5) * 1.7,+ width: 0.025 + random() * 0.065,+ strength: 7 + random() * 21+ }));+ const samples: {longitude: number; latitude: number; value: number}[] = [];+ const size = scattered ? 65 : 201;+ for (let row = 0; row < size; row++) {+ for (let col = 0; col < size; col++) {+ const x = scattered ? (col + (random() - 0.5) * 0.8) / 32 - 1 : col / 100 - 1;+ const y = scattered ? (row + (random() - 0.5) * 0.8) / 32 - 1 : row / 100 - 1;+ const warpedX = x + 0.07 * Math.sin(y * 13) + 0.03 * Math.sin(y * 27);+ const warpedY = y + 0.05 * Math.cos(x * 17);+ let surface = 65 * Math.exp(-(warpedX ** 2 / 0.22 + warpedY ** 2 / 0.13));+ surface += 16 * Math.exp(-((x + 0.3) ** 2 / 0.15 + (y - 0.13) ** 2 / 0.035));+ for (const bump of bumps) {+ surface +=+ bump.strength *+ Math.exp(-((x - bump.x) ** 2 + (y - bump.y) ** 2) / (2 * bump.width ** 2));+ }+ samples.push({+ longitude: Number((8.6821 + x * 0.32).toFixed(6)),+ latitude: Number((50.1109 + y * 0.22).toFixed(6)),+ value: Number((100 - surface).toFixed(4))+ });+ }+ }+ return samples;+}++export function createContourCsv(scattered = false) {+ return `longitude,latitude,value\n${createContourSamples(scattered)+ .map(d => `${d.longitude},${d.latitude},${d.value}`)+ .join('\n')}`;+}++export const contourConfig = {+ version: 'v1',+ config: {+ visState: {+ layers: [+ {+ id: 'scalar-contours',+ type: 'contour',+ config: {+ dataId: contourDataId,+ label: 'Synthetic scalar contours',+ color: [36, 218, 211],+ isVisible: true,+ columns: {lat: 'latitude', lng: 'longitude', value: 'value'},+ visConfig: {+ opacity: 0.85,+ smoothing: 1.5,+ levels: 8,+ below: true,+ customRange: true,+ minimum: 28,+ maximum: 88,+ filled: true,+ stroked: true,+ fillOpacity: 0.075,+ thickness: 1.5+ }+ }+ }+ ]+ },+ mapState: {latitude: 50.1109, longitude: 8.6821, zoom: 10.5, pitch: 0, bearing: 0},+ mapStyle: {styleType: 'dark'}+ }+};diff --git a/jest.config.js b/jest.config.jsindex 2c10d094c..bc7fb22bd 100644--- a/jest.config.js+++ b/jest.config.js@@ -50,7 +50,7 @@ const config = {// - tiny-sdf: https://github.com/visgl/deck.gl/issues/7735// - zarrita/@zarrita/@developmentseed: ESM-only, used by the Zarr layer.transformIgnorePatterns: [- '/node_modules\\/(?!(.*@mapbox\\/tiny-sdf\\.*|@loaders\\.gl|@deck\\.gl|@deck\\.gl-community|@luma\\.gl|@hubble\\.gl|@flowmap\\.gl|@math\\.gl|d3-.*|@sqlrooms|@paralleldrive/cuid2|@noble/hashes|kdbush|preact|maplibregl-mapbox-request-transformer|react-date-picker|react-time-picker|react-calendar|react-clock|react-fit|@wojtekmaj\\/date-utils|get-user-locale|make-event-props|update-input-width|detect-element-overflow|memoize|mimic-function|zarrita|@zarrita|numcodecs|@developmentseed))',+ '/node_modules\\/(?!(.*@mapbox\\/tiny-sdf\\.*|@loaders\\.gl|@deck\\.gl|@deck\\.gl-community|@luma\\.gl|@hubble\\.gl|@flowmap\\.gl|@math\\.gl|d3-.*|delaunator|robust-predicates|@sqlrooms|@paralleldrive/cuid2|@noble/hashes|kdbush|preact|maplibregl-mapbox-request-transformer|react-date-picker|react-time-picker|react-calendar|react-clock|react-fit|@wojtekmaj\\/date-utils|get-user-locale|make-event-props|update-input-width|detect-element-overflow|memoize|mimic-function|zarrita|@zarrita|numcodecs|@developmentseed))','\\.pnp\\.[^\\/]+$']};diff --git a/src/components/src/common/color-legend.tsx b/src/components/src/common/color-legend.tsxindex 8beb69819..44d68ab11 100644--- a/src/components/src/common/color-legend.tsx+++ b/src/components/src/common/color-legend.tsx@@ -29,9 +29,9 @@ const inputCss = css`pointer-events: none;}`;-const StyledLegend = styled.div<{$disableEdit: boolean; isExpanded?: boolean}>`+export const StyledLegend = styled.div<{$disableEdit: boolean; $isExpanded?: boolean}>`${props => props.theme.sidePanelScrollBar};- ${props => (props.isExpanded ? '' : `max-height: 156px;`)};+ max-height: ${props => (props.$isExpanded ? 'none' : '156px')};box-sizing: border-box;width: 100%;overflow-y: auto;@@ -74,6 +74,24 @@ const StyledLegendRow = styled.div`align-items: center;height: 20px;min-width: 0;++ .legend-row-reset {+ opacity: 0;+ pointer-events: none;+ }++ &:hover .legend-row-reset,+ &:focus-within .legend-row-reset {+ opacity: 1;+ pointer-events: auto;+ }++ @media (hover: none), (pointer: coarse) {+ .legend-row-reset {+ opacity: 1;+ pointer-events: auto;+ }+ }`;export function ResetColorLabelFactory() {@@ -102,7 +120,7 @@ const StyleInlineInput = styled(InlineInput)`text-overflow: ellipsis;white-space: nowrap;margin: 0 ${GAP}px;- :hover {+ &:hover {height: ${ROW_H}px;}`;@@ -204,7 +222,22 @@ export function LegendRowFactory() : (<StyledLabel>{value}</StyledLabel>)}- {onResetLabel ? <ResetColorLabel onClick={onReset} height="16px" /> : null}+ {onResetLabel ? (+ <ResetColorLabel+ className="legend-row-reset"+ role="button"+ aria-label="Reset label"+ tabIndex={0}+ onClick={onReset}+ onKeyDown={event => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ onReset();+ }+ }}+ height="16px"+ />+ ) : null}</StyledLegendRow>);};@@ -420,7 +453,7 @@ function ColorLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {<StyledLegendclassName="styled-color-legend"$disableEdit={disableEdit}- isExpanded={isExpanded}+ $isExpanded={isExpanded}>{legends.map((legend, i) => {const endpointLabel =diff --git a/src/components/src/map/layer-hover-info.tsx b/src/components/src/map/layer-hover-info.tsxindex 6d45d2c5a..54c91387a 100644--- a/src/components/src/map/layer-hover-info.tsx+++ b/src/components/src/map/layer-hover-info.tsx@@ -363,12 +363,14 @@ const CellInfo = ({colorDelta === elevationDelta;return (<tbody>- <Row- name={'total points'}- key="count"- value={String(data.points && data.points.length)}- isComparing={isComparing}- />+ {Array.isArray(data.points) ? (+ <Row+ name={'total points'}+ key="count"+ value={String(data.points.length)}+ isComparing={isComparing}+ />+ ) : null}{colorField && layer.visualChannels.color && colorMeasure ? (<Rowname={colorMeasure}diff --git a/src/components/src/map/map-legend.tsx b/src/components/src/map/map-legend.tsxindex 048780fa5..0f961484c 100644--- a/src/components/src/map/map-legend.tsx+++ b/src/components/src/map/map-legend.tsx@@ -1,22 +1,30 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {FC, useCallback, useState, ComponentType} from 'react';+import React, {FC, useCallback, useId, useState, ComponentType} from 'react';import styled from 'styled-components';import {rgb} from 'd3-color';import {format as d3Format} from 'd3-format';import {useIntl} from 'react-intl';-import ColorLegendFactory, {LegendRowFactory} from '../common/color-legend';+import ColorLegendFactory, {LegendRowFactory, StyledLegend} from '../common/color-legend';import RadiusLegend from '../common/radius-legend';import {CHANNEL_SCALES, DIMENSIONS} from '@kepler.gl/constants';import {FormattedMessage} from '@kepler.gl/localization';-import {Layer, LayerBaseConfig, VisualChannel, VisualChannelDescription} from '@kepler.gl/layers';+import {+ Layer,+ LayerBaseConfig,+ VisualChannel,+ VisualChannelDescription,+ KeplerGlLayers+} from '@kepler.gl/layers';import {LayerVisConfig, LayerOrder, MapState, RGBColor} from '@kepler.gl/types';import {getDistanceScales, zoomToScale} from '@math.gl/web-mercator';import {ArrowDown, ArrowRight, EyeSeen, EyeUnseen} from '../common/icons';import PanelHeaderActionFactory from '../side-panel/panel-header-action';import {getFlatLayerOrder, isLayerShownInLegend} from '@kepler.gl/reducers';+type ContourLayer = InstanceType<typeof KeplerGlLayers.ContourLayer>;+interface StyledMapControlLegendProps {width?: number;$last?: boolean;@@ -484,6 +492,100 @@ const LayerImageLegend: React.FC<{src: string; alt: string}> = ({src, alt}) => {);};+const StyledContourLevels = styled(StyledLegend)`+ margin-top: 6px;+`;++const StyledContourExpandToggle = styled(StyledExpandToggle)`+ background: none;+ border: 0;+ padding: 0;+`;++ContourLegendFactory.deps = [LegendRowFactory];++function ContourLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {+ const ContourLegend: React.FC<+ Omit<LayerLegendContentProps, 'layer' | 'containerW' | 'mapState'> & {layer: ContourLayer}+ > = ({layer, isExport, disableEdit, onLayerVisConfigChange, actionIcons}) => {+ const intl = useIntl();+ const listId = useId();+ const [isExpanded, setIsExpanded] = useState(false);+ const levels = layer.getContourLegend();+ const field = String(layer.config.columns.value.value);+ const colorRange = layer.config.visConfig.colorRange;+ const customLabels = colorRange?.colorLegends || {};+ const canEdit = !disableEdit && !isExport && Boolean(onLayerVisConfigChange);+ const ExpandIcon = isExpanded ? actionIcons.expanded : actionIcons.collapsed;+ const updateLabel = (key: string, label?: string) => {+ const colorLegends = {...customLabels};+ if (label === undefined) delete colorLegends[key];+ else colorLegends[key] = label;+ onLayerVisConfigChange?.(layer, {colorRange: {...colorRange, colorLegends}});+ };+ if (!levels.length) return null;+ return (+ <div className="legend--layer__item">+ <div className="legend--layer_color-schema">+ <div className="legend--layer_size-title-row">+ <VisualChannelMetric name={field} />+ {!isExport ? (+ <StyledContourExpandToggle+ as="button"+ type="button"+ aria-label={field}+ aria-expanded={isExpanded}+ aria-controls={listId}+ onClick={() => setIsExpanded(expanded => !expanded)}+ >+ <ExpandIcon height="16px" />+ </StyledContourExpandToggle>+ ) : null}+ </div>+ <StyledContourLevels+ id={listId}+ $isExpanded={Boolean(isExport || isExpanded)}+ $disableEdit={!canEdit}+ role="list"+ tabIndex={isExport ? undefined : 0}+ aria-label={intl.formatMessage({id: 'mapLegend.layers.contour.levels'})}+ >+ {levels.map(({threshold, below, color}) => {+ const defaultLabel = `${below ? '≤' : '≥'} ${intl.formatNumber(threshold, {+ maximumSignificantDigits: 12+ })}`;+ // Labels follow the scalar threshold, not a color that can change or repeat.+ const key = JSON.stringify([field, below, threshold]);+ const label = customLabels[key] ?? defaultLabel;+ return (+ <div+ className="legend--contour-level"+ key={key}+ role="listitem"+ title={customLabels[key] ?? `${below ? '≤' : '≥'} ${threshold}`}+ >+ <LegendRow+ label={label}+ displayLabel+ color={`rgba(${color[0]}, ${color[1]}, ${color[2]}, ${color[3] / 255})`}+ onUpdateLabel={canEdit ? (_color, value) => updateLabel(key, value) : undefined}+ onResetLabel={+ canEdit && customLabels[key] !== undefined+ ? () => updateLabel(key)+ : undefined+ }+ />+ </div>+ );+ })}+ </StyledContourLevels>+ </div>+ </div>+ );+ };+ return ContourLegend;+}+export type LayerLegendContentProps = {layer: Layer;containerW: number;@@ -494,10 +596,11 @@ export type LayerLegendContentProps = {actionIcons: MapLegendIcons;};-LayerLegendContentFactory.deps = [LayerColorLegendFactory];+LayerLegendContentFactory.deps = [LayerColorLegendFactory, ContourLegendFactory];export function LayerLegendContentFactory(- LayerColorLegend: ReturnType<typeof LayerColorLegendFactory>+ LayerColorLegend: ReturnType<typeof LayerColorLegendFactory>,+ ContourLegend: ReturnType<typeof ContourLegendFactory>) {const LayerLegendContent: React.FC<LayerLegendContentProps> = ({layer,@@ -508,6 +611,17 @@ export function LayerLegendContentFactory(onLayerVisConfigChange,actionIcons}) => {+ if (layer.type === 'contour') {+ return (+ <ContourLegend+ layer={layer as ContourLayer}+ isExport={isExport}+ disableEdit={disableEdit}+ onLayerVisConfigChange={onLayerVisConfigChange}+ actionIcons={actionIcons}+ />+ );+ }const visualChannels = layer.getLegendVisualChannels();const legendImageUrl = layer.getLegendImageUrl();const channelKeys = Object.values(visualChannels);diff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsxindex 7b6e84324..18ecaa57b 100644--- a/src/components/src/side-panel/layer-manager.tsx+++ b/src/components/src/side-panel/layer-manager.tsx@@ -209,6 +209,7 @@ function LayerManagerFactory(const enableA5Layer = getApplicationConfig().enableA5Layer;const enableGeohashLayer = getApplicationConfig().enableGeohashLayer;const enableFlowFieldLayer = getApplicationConfig().enableFlowFieldLayer;+ const enableContourLayer = getApplicationConfig().enableContourLayer;const enableZarrLayer = getApplicationConfig().enableZarrLayer;const enableLayerGroups = getApplicationConfig().enableLayerGroups;@@ -238,6 +239,10 @@ function LayerManagerFactory(const {flowField: _flowField, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;}+ if (!enableContourLayer) {+ const {contour: _contour, ...rest} = filteredClasses;+ filteredClasses = rest as LayerClassesType;+ }if (!enableZarrLayer) {const {zarr: _zarr, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;@@ -250,6 +255,7 @@ function LayerManagerFactory(enableA5Layer,enableGeohashLayer,enableFlowFieldLayer,+ enableContourLayer,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 ebd91bd67..f4777c7bd 100644--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx@@ -3,12 +3,14 @@/* eslint-disable complexity */import {FormattedMessage} from '@kepler.gl/localization';-import React, {Component, useCallback, useRef, useState} from 'react';+import React, {Component, useCallback, useEffect, useRef, useState} from 'react';import {useIntl} from 'react-intl';import styled from 'styled-components';+import {createSelector} from 'reselect';import ItemSelector from '../../common/item-selector/item-selector';import {InputLight, PanelLabel, SidePanelSection} from '../../common/styled-components';+import Switch from '../../common/switch';import SourceDataSelectorFactory from '../common/source-data-selector';import AggrScaleSelectorFactory from './aggr-scale-selector';@@ -25,6 +27,7 @@ import LayerErrorMessage from './layer-error-message';import LayerTypeSelectorFactory from './layer-type-selector';import TextLabelPanelFactory from './text-label-panel';import VisConfigSliderFactory from './vis-config-slider';+import RangeSliderFactory from '../../common/range-slider';import VisConfigSwitchFactory from './vis-config-switch';import ScenegraphModelSelectorFactory, {SCENEGRAPH_3D_MODEL_OPTIONS@@ -58,8 +61,8 @@ import {isExplicitZarrAxis,formatZarrCoordinate} from '@kepler.gl/table';-import {ColorUI, LayerVisConfig, NestedPartial} from '@kepler.gl/types';-import {capitalizeFirstLetter} from '@kepler.gl/utils';+import {ColorUI, Field, LayerVisConfig, NestedPartial} from '@kepler.gl/types';+import {capitalizeFirstLetter, clamp, getNumericStepSize} from '@kepler.gl/utils';const FLOW_RENDERING_MODE_LABELS: Record<string, string> = {straight: 'Straight',@@ -127,6 +130,19 @@ const StyledLayerVisualConfigurator = styled.div.attrs({.bitmap-bounds-sliders .kg-range-slider__input {width: 80px;}++ .contour-range-values {+ display: flex;+ justify-content: space-between;+ margin-top: 8px;+ color: ${props => props.theme.textColor};+ font-size: ${props => props.theme.sliderInputFontSize};+ }++ .contour-invert-switch {+ display: flex;+ justify-content: space-between;+ }`;const BitmapDropZone = styled.div<{$isDragging: boolean}>`@@ -431,7 +447,8 @@ LayerConfiguratorFactory.deps = [AggrScaleSelectorFactory,VectorTileLayerConfiguratorFactory,RasterTileLayerConfiguratorFactory,- ScenegraphModelSelectorFactory+ ScenegraphModelSelectorFactory,+ RangeSliderFactory];export default function LayerConfiguratorFactory(@@ -449,7 +466,8 @@ export default function LayerConfiguratorFactory(AggrScaleSelector: ReturnType<typeof AggrScaleSelectorFactory>,VectorTileLayerConfigurator: ReturnType<typeof VectorTileLayerConfiguratorFactory>,RasterTileLayerConfigurator: ReturnType<typeof RasterTileLayerConfiguratorFactory>,- ScenegraphModelSelector: ReturnType<typeof ScenegraphModelSelectorFactory>+ ScenegraphModelSelector: ReturnType<typeof ScenegraphModelSelectorFactory>,+ RangeSlider: ReturnType<typeof RangeSliderFactory>): React.ComponentType<LayerConfiguratorProps> {const AggregationTextLabelPanel: React.FC<Omit<React.ComponentProps<typeof TextLabelPanel>, 'fields'>@@ -463,6 +481,52 @@ export default function LayerConfiguratorFactory();};+ const ContourRangeSlider: React.FC<{+ layer: Layer;+ range: [number, number];+ onChange: LayerConfiguratorProps['updateLayerVisConfig'];+ }> = ({layer, range, onChange}) => {+ const intl = useIntl();+ const {minimum, maximum} = layer.config.visConfig;+ const low = Number.isFinite(minimum) ? clamp(range, minimum) : range[0];+ const high = Number.isFinite(maximum) ? clamp(range, maximum) : range[1];+ const [value0, value1] = low < high ? [low, high] : range;+ useEffect(() => {+ if (minimum !== value0 || maximum !== value1) {+ onChange({minimum: value0, maximum: value1});+ }+ }, [minimum, maximum, value0, value1, onChange]);+ return (+ <SidePanelSection>+ <RangeSlider+ range={range}+ value0={value0}+ value1={value1}+ step={getNumericStepSize(range[1] - range[0])}+ isRanged+ showInput={false}+ onChange={([nextMinimum, nextMaximum]) => {+ if (+ Number.isFinite(nextMinimum) &&+ Number.isFinite(nextMaximum) &&+ nextMinimum < nextMaximum+ ) {+ onChange({minimum: nextMinimum, maximum: nextMaximum});+ }+ }}+ />+ <div className="contour-range-values">+ <output aria-label={intl.formatMessage({id: 'layerVisConfigs.contour.minimum'})}>+ {value0}+ </output>+ <output aria-label={intl.formatMessage({id: 'layerVisConfigs.contour.maximum'})}>+ {value1}+ </output>+ </div>+ </SidePanelSection>+ );+ };+class LayerConfigurator extends Component<LayerConfiguratorProps> {_renderPointLayerConfig(props) {return this._renderScatterplotLayerConfig(props, true);@@ -1939,6 +2003,147 @@ export default function LayerConfiguratorFactory();}+ _contourValueRange = createSelector(+ (dataContainer: Datasets[string]['dataContainer'] | undefined) => dataContainer,+ (_dataContainer, valueAccessor: Field['valueAccessor'] | undefined) => valueAccessor,+ (_dataContainer, _valueAccessor, dataRevision: number | undefined) => dataRevision,+ (dataContainer, valueAccessor): [number, number] | null => {+ if (!dataContainer || !valueAccessor) return null;+ let minimum = Infinity;+ let maximum = -Infinity;+ for (let index = 0; index < dataContainer.numRows(); index++) {+ const value = valueAccessor({index});+ if (Number.isFinite(value)) {+ minimum = Math.min(minimum, value);+ maximum = Math.max(maximum, value);+ }+ }+ return minimum <= maximum ? [minimum, maximum] : null;+ }+ );++ _renderContourLayerConfig({layer, dataset, visConfiguratorProps, layerConfiguratorProps}) {+ const {visConfigSettings: settings, config} = layer;+ const valueColumn = config.columns.value.value;+ const valueRange = this._contourValueRange(+ dataset?.dataContainer,+ dataset?.getColumnField(valueColumn)?.valueAccessor,+ dataset?.dataRevision+ );+ const hasValueRange = valueRange && valueRange[0] < valueRange[1];+ const inputModes = [+ {id: 'auto', label: 'Auto'},+ {id: 'grid', label: 'Regular grid'},+ {id: 'points', label: 'Scattered points'}+ ];+ return (+ <StyledLayerVisualConfigurator>+ <LayerConfigGroup label="layer.color" collapsible>+ <VisConfigSwitch {...settings.colorByLevel} {...visConfiguratorProps} />+ {config.visConfig.colorByLevel ? (+ <LayerColorRangeSelector+ {...visConfiguratorProps}+ onChange={({colorRange}) =>+ visConfiguratorProps.onChange({+ colorRange: {+ ...colorRange,+ colorLegends: config.visConfig.colorRange.colorLegends+ }+ })+ }+ />+ ) : (+ <LayerColorSelector {...layerConfiguratorProps} />+ )}+ <ConfigGroupCollapsibleContent>+ <VisConfigSlider {...settings.opacity} {...visConfiguratorProps} />+ </ConfigGroupCollapsibleContent>+ </LayerConfigGroup>+ <LayerConfigGroup+ label="layerVisConfigs.contour.levelsGroup"+ collapsible+ expanded={config.visConfig.customRange}+ >+ <VisConfigSlider {...settings.levels} {...visConfiguratorProps} />+ <ConfigGroupCollapsibleContent>+ <SidePanelSection>+ <div className="contour-invert-switch">+ <PanelLabel htmlFor={`${layer.id}-invert-switch`}>+ <FormattedMessage id="layerVisConfigs.contour.invert" />+ </PanelLabel>+ <Switch+ id={`${layer.id}-invert-switch`}+ checked={!config.visConfig.below}+ onChange={() => visConfiguratorProps.onChange({below: !config.visConfig.below})}+ />+ </div>+ </SidePanelSection>+ <VisConfigSwitch+ {...settings.customRange}+ {...visConfiguratorProps}+ onChange={({customRange}) =>+ visConfiguratorProps.onChange(+ customRange && hasValueRange+ ? {customRange, minimum: valueRange[0], maximum: valueRange[1]}+ : {customRange}+ )+ }+ />+ {config.visConfig.customRange ? (+ <div className="contour-level-range">+ {hasValueRange ? (+ <ContourRangeSlider+ key={JSON.stringify([config.dataId, valueColumn, valueRange])}+ {...visConfiguratorProps}+ range={valueRange}+ />+ ) : (+ <FormattedMessage id="layerVisConfigs.contour.noValueRange" />+ )}+ </div>+ ) : null}+ </ConfigGroupCollapsibleContent>+ </LayerConfigGroup>+ <LayerConfigGroup label="layerVisConfigs.contour.surface" collapsible>+ <VisConfigSlider {...settings.smoothing} {...visConfiguratorProps} />+ <ConfigGroupCollapsibleContent>+ <SidePanelSection>+ <PanelLabel>+ <FormattedMessage id={settings.inputMode.label} />+ </PanelLabel>+ <ItemSelector+ options={inputModes}+ selectedItems={inputModes.find(mode => mode.id === config.visConfig.inputMode)}+ displayOption="label"+ getOptionValue="id"+ multiSelect={false}+ searchable={false}+ onChange={inputMode => visConfiguratorProps.onChange({inputMode})}+ />+ </SidePanelSection>+ {config.visConfig.inputMode !== 'grid' ? (+ <VisConfigSlider {...settings.interpolationResolution} {...visConfiguratorProps} />+ ) : null}+ </ConfigGroupCollapsibleContent>+ </LayerConfigGroup>+ <LayerConfigGroup+ {...settings.filled}+ {...visConfiguratorProps}+ label="layerVisConfigs.contour.fillGroup"+ >+ {config.visConfig.filled ? (+ <VisConfigSlider {...settings.fillOpacity} {...visConfiguratorProps} />+ ) : null}+ </LayerConfigGroup>+ <LayerConfigGroup {...settings.stroked} {...visConfiguratorProps} label="layer.outline">+ {config.visConfig.stroked ? (+ <VisConfigSlider {...settings.thickness} {...visConfiguratorProps} />+ ) : null}+ </LayerConfigGroup>+ </StyledLayerVisualConfigurator>+ );+ }+_renderFlowFieldLayerConfig({layer, visConfiguratorProps, layerConfiguratorProps}) {const colorBySpeed = Boolean(layer.config.visConfig.colorBySpeed);return (diff --git a/src/components/src/side-panel/layer-panel/layer-panel-header.spec.tsx b/src/components/src/side-panel/layer-panel/layer-panel-header.spec.tsxindex cbefdf0bb..0d41736a2 100644--- a/src/components/src/side-panel/layer-panel/layer-panel-header.spec.tsx+++ b/src/components/src/side-panel/layer-panel/layer-panel-header.spec.tsx@@ -3,6 +3,8 @@import React from 'react';import {fireEvent} from '@testing-library/react';+import {IntlProvider} from 'react-intl';+import {messages} from '@kepler.gl/localization';import {renderWithTheme} from 'test/helpers/component-jest-utils';import PanelHeaderActionFactory from '../panel-header-action';@@ -63,6 +65,29 @@ function openOptions(container: HTMLElement) {fireEvent.click(container.querySelector('.layer__options-toggle svg') as SVGElement);}+test.each(Object.keys(messages))('resolves the contour header type in locale %s', locale => {+ const LayerTitleSection = LayerTitleSectionFactory();+ const id = 'layer.type.contour';+ const translation = messages[locale][id];+ expect(translation).toEqual(expect.any(String));+ expect(translation).not.toBe(id);+ const view = renderWithTheme(+ <IntlProvider locale={locale === 'cn' ? 'zh-CN' : locale} messages={messages[locale]}>+ <LayerTitleSection+ layerId="contour-header"+ layerType="Contour"+ label="Sample scalar field"+ onUpdateLayerLabel={noop}+ onFocus={noop}+ onBlur={noop}+ />+ </IntlProvider>+ );+ expect(view.queryByText(id)).toBeNull();+ expect(view.getByText(translation)).toBeInTheDocument();+ expect(view.getByRole('textbox')).toHaveValue('Sample scalar field');+});+describe('LayerPanelHeader options menu', () => {test('keeps visibility and settings visible and moves other actions into the menu', () => {const {container, onZoomToLayer, onDuplicateLayer, onRemoveLayer, onToggleJsonEditor} =diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex 554c819d9..726d85728 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -1544,6 +1544,7 @@ export const GLOBE_SUPPORTED_LAYERS: Record<string, boolean> = {trip: true,rasterTile: true,heatmap: true,+ contour: 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 274be3175..1d9279a50 100644--- a/src/constants/src/layers.ts+++ b/src/constants/src/layers.ts@@ -662,6 +662,7 @@ export const LAYER_TYPES = keyMirror({cluster: null,icon: null,heatmap: null,+ contour: null,hexagonId: null,'3D': null,trip: null,@@ -688,5 +689,6 @@ export const EDITOR_AVAILABLE_LAYERS: string[] = [LAYER_TYPES.line,LAYER_TYPES.hexagonId,LAYER_TYPES.geojson,- LAYER_TYPES.heatmap+ LAYER_TYPES.heatmap,+ LAYER_TYPES.contour];diff --git a/src/layers/package.json b/src/layers/package.jsonindex 589093534..d82aeba5d 100644--- a/src/layers/package.json+++ b/src/layers/package.json@@ -77,9 +77,11 @@"apache-arrow": ">=15.0.0","buffer": "6.0.3","d3-array": "^2.8.0",+ "d3-contour": "^3.0.2","d3-format": "^3.1.0","d3-interpolate": "^3.0.1","d3-shape": "^1.2.0",+ "delaunator": "^5.1.0","es-toolkit": "^1.39.10","global": "^4.3.0","keymirror": "^0.1.1",@@ -121,5 +123,8 @@"require": "./dist/cjs/index.js","default": "./dist/cjs/index.js"}+ },+ "devDependencies": {+ "@types/d3-contour": "^3.0.6"}}diff --git a/src/layers/src/contour-layer/contour-layer-icon.tsx b/src/layers/src/contour-layer/contour-layer-icon.tsxnew file mode 100644index 000000000..3c9909e52--- /dev/null+++ b/src/layers/src/contour-layer/contour-layer-icon.tsx@@ -0,0 +1,17 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {Base, BaseProps} from '../base';++export default function ContourLayerIcon(props: Partial<BaseProps>) {+ return (+ <Base viewBox="0 0 64 64" {...props}>+ <g fill="none" stroke="currentColor" strokeWidth="3" strokeLinejoin="round">+ <path d="M5 36C3 19 19 5 33 9S55 7 59 26S48 57 30 55S8 50 5 36Z" />+ <path d="M15 34C12 24 23 15 32 20S47 17 49 30S40 46 30 45S17 43 15 34Z" />+ <path d="M25 34C23 28 28 25 34 28S41 33 37 37S27 39 25 34Z" />+ </g>+ </Base>+ );+}diff --git a/src/layers/src/contour-layer/contour-layer.spec.ts b/src/layers/src/contour-layer/contour-layer.spec.tsnew file mode 100644index 000000000..121677ae2--- /dev/null+++ b/src/layers/src/contour-layer/contour-layer.spec.ts@@ -0,0 +1,1317 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {KeplerTable, getGpuFilterProps, assignGpuChannels} from '@kepler.gl/table';+import {EDITOR_AVAILABLE_LAYERS, FILTER_TYPES} from '@kepler.gl/constants';+import {generatePolygonFilter, getDefaultFilter} from '@kepler.gl/utils';+import {PickingInfo} from '@deck.gl/core';+import {Int64, Uint64, Table, vectorFromArray} from 'apache-arrow';+import {processCsvData} from '@kepler.gl/processors';+import ContourLayer from './contour-layer';+import Layer from '../base-layer';+import {LayerClasses} from '../index';+import {+ createContourSamples,+ contourConfig+} from '../../../../examples/demo-app/src/data/sample-contour-data';+import {buildContourGrid, generateContours} from './contour-utils';+import SchemaManager from '@kepler.gl/schemas';+import {+ calculateLayerData,+ INITIAL_VIS_STATE,+ layerTypeChangeUpdater,+ removeLayerUpdater+} from '@kepler.gl/reducers';+import {StateWFiles} from 'test/helpers/mock-state';+import {messages} from '@kepler.gl/localization';+import React from 'react';+import {fireEvent, render, within} from '@testing-library/react';+import {ThemeProvider} from 'styled-components';+import {IntlProvider} from 'react-intl';+import {theme} from '@kepler.gl/styles';+import {appInjector, MapLegendFactory, LayerHoverInfoFactory} from '@kepler.gl/components';++test.each(Object.keys(messages))('resolves contour column labels in locale %s', locale => {+ const layer = new ContourLayer({dataId: 'contour-labels'});+ for (const key of layer.requiredLayerColumns) {+ const id = `columns.${layer.columnLabels[key] || key}`;+ expect(messages[locale][id]).toEqual(expect.any(String));+ expect(messages[locale][id]).not.toBe(id);+ }+});++async function setup(scatteredRows?: number[][]) {+ const rows = Array.from({length: 81}, (_, i) => {+ const x = i % 9;+ const y = Math.floor(i / 9);+ return `${x},${y},${(x - 4) ** 2 + (y - 4) ** 2}`;+ });+ const dataset = new KeplerTable({info: {id: 'contour-test'}, color: [0, 0, 0]});+ const data = processCsvData(`longitude,latitude,value\n${rows.join('\n')}`)!;+ if (scatteredRows) {+ // Small CSV fixtures may infer integer columns; provide the intended numeric schema.+ data.fields = data.fields.map(field => ({...field, type: 'real'}));+ data.rows = scatteredRows;+ }+ await dataset.importData({data});+ dataset.gpuFilter = getGpuFilterProps([], dataset.id, dataset.fields);+ const column = name => ({value: name, fieldIdx: dataset.fields.findIndex(f => f.name === name)});+ const layer = new ContourLayer({+ dataId: dataset.id,+ columns: {lat: column('latitude'), lng: column('longitude'), value: column('value')}+ });+ layer.updateLayerVisConfig({+ customRange: true,+ minimum: 2,+ maximum: 6,+ smoothing: 0,+ levels: 3,+ filled: true,+ stroked: true+ });+ return {dataset, layer, datasets: {[dataset.id]: dataset}};+}++const scatteredSamples = [+ [0, 0, 3],+ [2, 0, 7],+ [0.75, 2, 10.5],+ [1.125, 0.625, 7.125]+];++function calculateContourLayerData(layer: ContourLayer, datasets) {+ return calculateLayerData(layer, {+ datasets,+ animationConfig: StateWFiles.visState.animationConfig+ });+}++test.each([+ {+ name: 'irregular grid',+ scattered: true,+ invalid: {inputMode: 'grid'},+ message: /regularly spaced/+ },+ {name: 'reversed range', scattered: false, invalid: {minimum: 9, maximum: 3}, message: /minimum/},+ {name: 'constant range', scattered: false, invalid: {minimum: 4, maximum: 4}, message: /minimum/},+ {+ name: 'nonfinite range',+ scattered: false,+ invalid: {minimum: NaN, maximum: 8},+ message: /minimum/+ }+])(+ 'retains $name validation errors through layer calculation and recovers',+ async ({scattered, invalid, message}) => {+ const {layer, datasets} = await setup(scattered ? scatteredSamples : undefined);+ layer.updateLayerVisConfig({minimum: 4, maximum: 8, interpolationResolution: 32});+ expect(calculateContourLayerData(layer, datasets).layerData.data).toHaveLength(3);+ expect(layer.getContourLegend()).toHaveLength(3);+ layer.updateLayerVisConfig(invalid);+ for (let attempt = 0; attempt < 2; attempt++) {+ const result = calculateContourLayerData(layer, datasets);+ expect(result.layer.isValid).toBe(false);+ expect(result.layer.errorMessage).toMatch(message);+ expect(result.layer.config.isVisible).toBe(false);+ expect(result.layerData).toEqual({});+ expect(layer.getContourLegend()).toEqual([]);+ }+ layer.updateLayerVisConfig({inputMode: 'auto', minimum: 4, maximum: 8});+ const recovered = calculateContourLayerData(layer, datasets);+ expect(recovered.layer.isValid).toBe(true);+ expect(recovered.layer.errorMessage).toBeNull();+ expect(recovered.layer.config.isVisible).toBe(true);+ expect(recovered.layerData.data).toHaveLength(3);+ expect(layer.getContourLegend()).toHaveLength(3);+ }+);+const pointGeometry = (x: number, y: number) => ({type: 'Point', coordinates: [x, y]});+const polygonGeometry = (x: number, y: number) => ({+ type: 'Polygon',+ // The closing vertex makes the vertex average [x, y], unlike an area centroid.+ coordinates: [+ [+ [x - 1, y - 1],+ [x + 3, y - 1],+ [x - 1, y + 3],+ [x - 1, y - 1]+ ]+ ]+});++function setupGeojson(+ rows: unknown[][] = scatteredSamples.map(([x, y, value]) => [pointGeometry(x, y), value])+) {+ const dataset = new KeplerTable({info: {id: 'contour-geojson'}, color: [0, 0, 0]}).updateSchema({+ fields: [+ {name: 'geometry', type: 'geojson', analyzerType: 'GEOMETRY'},+ {name: 'value', type: 'real'}+ ],+ rows+ });+ const layer = new ContourLayer({+ dataId: dataset.id,+ columnMode: 'geojson',+ columns: {+ geojson: {value: 'geometry', fieldIdx: 0},+ value: {value: 'value', fieldIdx: 1}+ }+ });+ layer.updateLayerVisConfig({+ customRange: true,+ minimum: 4,+ maximum: 8,+ levels: 3,+ smoothing: 0,+ interpolationResolution: 64+ });+ return {layer, dataset, datasets: {[dataset.id]: dataset}};+}++test('registers the layer and renders both passes without recomputing on camera movement', async () => {+ const {layer, dataset, datasets} = await setup();+ expect(LayerClasses.contour).toBe(ContourLayer);+ const data = layer.formatLayerData(datasets);+ expect(data.data).toHaveLength(3);+ const opts = {+ data,+ visible: true,+ idx: 0,+ gpuFilter: dataset.gpuFilter,+ layerCallbacks: {},+ mapState: {zoom: 10}+ };+ const passes = layer.renderLayer(opts);+ expect(passes).toHaveLength(2);+ expect(layer.config.visConfig.colorByLevel).toBe(false);+ expect(passes[0].props.getFillColor).toEqual([36, 218, 211, 19]);+ expect(passes[0].props.data).toBe(data.data);+ expect(passes[1].props.data).toBe(data.data);+ expect(layer.renderLayer({...opts, mapState: {zoom: 15, longitude: 8}})[0].props.data).toBe(+ data.data+ );+ expect(layer.renderLayer({...opts, visible: false})).toEqual([]);+ layer.updateLayerVisConfig({filled: false});+ expect(layer.renderLayer(opts)).toHaveLength(1);+ expect(layer.getHoverData(data.data[0])).toEqual({+ fieldValues: [{labelMessage: 'columns.contour.value', value: 'value ≤ 6'}]+ });+ expect(layer.getHoverData(null)).toBeNull();+});++test.each(['fill', 'outline'])('clears %s picks on removal or type changes', async pass => {+ const {layer, dataset, datasets} = await setup();+ const data = layer.formatLayerData(datasets);+ const deckLayer = layer+ .renderLayer({data, visible: true, idx: 0, gpuFilter: dataset.gpuFilter, mapState: {zoom: 10}})+ .find(rendered => rendered.id === `${layer.id}-${pass}`)!;+ const pick: PickingInfo = {+ picked: true,+ layer: deckLayer,+ object: data.data[0],+ color: null,+ index: 0,+ x: 0,+ y: 0,+ pixelRatio: 1+ };+ const other = new LayerClasses.point({id: `${layer.id}-other`, dataId: dataset.id});+ const state = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [layer, other],+ layerData: [data, {data: []}],+ layerOrder: [layer.id, other.id],+ clicked: pick,+ hoverInfo: pick+ };+ expect(layer.hasHoveredObject(pick)).toBe(data.data[0]);+ const removed = removeLayerUpdater(state, {id: layer.id});+ expect(removed.layers).toEqual([other]);+ expect(removed.clicked).toBeUndefined();+ expect(removed.hoverInfo).toBeUndefined();+ const changed = layerTypeChangeUpdater(state, {oldLayer: layer, newType: 'point'});+ expect(changed.layers[0].type).toBe('point');+ expect(changed.clicked).toBeUndefined();+ expect(changed.hoverInfo).toBeUndefined();++ const unrelated = {...pick, layer: deckLayer.clone({id: other.id})};+ const otherState = {...state, clicked: unrelated, hoverInfo: unrelated};+ for (const result of [+ removeLayerUpdater(otherState, {id: layer.id}),+ layerTypeChangeUpdater(otherState, {oldLayer: layer, newType: 'point'})+ ]) {+ expect(result.clicked).toBe(unrelated);+ expect(result.hoverInfo).toBe(unrelated);+ }+ for (const info of [null, undefined, {...pick, picked: false}, unrelated]) {+ expect(layer.hasHoveredObject(info)).toBeNull();+ }+});++describe.each([Int64, Uint64])('Arrow %p contour inputs', ArrowType => {+ test.each(['value', 'coordinates', 'both', 'geojson'])(+ 'matches numeric contours with 64-bit %s columns, missing values, and filtering',+ async mode => {+ const {layer, dataset, datasets} = await setup();+ const longitudes = Array.from({length: 81}, (_, i) => i % 9);+ const latitudes = Array.from({length: 81}, (_, i) => Math.floor(i / 9));+ const values = longitudes.map((x, i) =>+ i === 40 ? null : (x - 4) ** 2 + (latitudes[i] - 4) ** 2+ );+ const arrowVector = (numbers: (number | null)[]) =>+ vectorFromArray(+ numbers.map(value => (value === null ? null : BigInt(value))),+ new ArrowType()+ );+ const arrowTable = new Table({+ longitude:+ mode === 'coordinates' || mode === 'both'+ ? arrowVector(longitudes)+ : vectorFromArray(longitudes),+ latitude:+ mode === 'coordinates' || mode === 'both'+ ? arrowVector(latitudes)+ : vectorFromArray(latitudes),+ value: mode === 'coordinates' ? vectorFromArray(values) : arrowVector(values),+ geometry: vectorFromArray(+ longitudes.map((x, i) => JSON.stringify(pointGeometry(x, latitudes[i])))+ )+ });+ const arrowDataset = new KeplerTable({info: {id: dataset.id}, color: [0, 0, 0]});+ await arrowDataset.importData({+ data: {+ rows: [],+ fields: [+ ...dataset.fields,+ {name: 'geometry', type: 'geojson', analyzerType: 'GEOMETRY'}+ ],+ cols: arrowTable.schema.fields.map((_, i) => arrowTable.getChildAt(i)!),+ arrowTable+ }+ });+ const numeric = new KeplerTable({info: {id: dataset.id}, color: [0, 0, 0]}).updateSchema({+ fields: dataset.fields,+ rows: longitudes.map((x, i) => [x, latitudes[i], values[i]])+ });+ numeric.filteredIndex = numeric.filteredIndex.filter(index => index !== 41);+ arrowDataset.filteredIndex = numeric.filteredIndex;+ const expected = layer.formatLayerData({...datasets, [dataset.id]: numeric});+ expect(expected.data).toHaveLength(3);+ if (mode === 'geojson') {+ layer.updateLayerConfig({+ columnMode: 'geojson',+ columns: {+ ...layer.config.columns,+ geojson: {value: 'geometry', fieldIdx: 3}+ }+ });+ }+ expect(typeof arrowDataset.dataContainer.valueAt(0, mode === 'coordinates' ? 0 : 2)).toBe(+ 'bigint'+ );+ expect(arrowDataset.fields[2].valueAccessor({index: 40})).toBeNull();+ expect(layer.formatLayerData({...datasets, [dataset.id]: arrowDataset})).toEqual(expected);+ }+ );+});++test('shows contour thresholds without selected tooltip fields and preserves real aggregation counts', async () => {+ const {layer, dataset, datasets} = await setup();+ const data = layer.formatLayerData(datasets);+ const LayerHoverInfo = appInjector.get(LayerHoverInfoFactory);+ const view = render(+ React.createElement(LayerHoverInfo, {+ layer,+ data: layer.getHoverData(data.data[0]),+ fields: dataset.fields,+ fieldsToShow: []+ }),+ {+ wrapper: ({children}) =>+ React.createElement(ThemeProvider, {+ theme,+ children: React.createElement(IntlProvider, {+ locale: 'en',+ messages: messages.en,+ children+ })+ })+ }+ );+ expect(view.queryByText(/total points/i)).toBeNull();+ expect(view.queryByText('undefined')).toBeNull();+ expect(view.getByText('value ≤ 6')).toBeInTheDocument();++ for (const below of [false, true]) {+ const feature = {...data.data[0], properties: {...data.data[0].properties, below}};+ view.rerender(+ React.createElement(LayerHoverInfo, {+ layer,+ data: layer.getHoverData(feature),+ fields: dataset.fields,+ fieldsToShow: [{name: 'longitude', format: null}]+ })+ );+ expect(view.getByText(`value ${below ? '≤' : '≥'} 6`)).toBeInTheDocument();+ expect(view.queryByText(/total points/i)).toBeNull();+ }++ const gridLayer = new LayerClasses.grid({dataId: dataset.id});+ for (const points of [[], [{index: 0}, {index: 1}]]) {+ view.rerender(+ React.createElement(LayerHoverInfo, {+ layer: gridLayer,+ data: {points},+ fields: [],+ fieldsToShow: []+ })+ );+ expect(view.getByText(/total points/i)).toBeInTheDocument();+ expect(view.getByText(String(points.length))).toBeInTheDocument();+ }+});++function renderLegend(+ layer: Layer,+ isExport = false,+ options: Partial<React.ComponentProps<ReturnType<typeof MapLegendFactory>>> = {}+) {+ const MapLegend = appInjector.get(MapLegendFactory);+ const props = {layers: [layer], isExport, ...options};+ const view = render(React.createElement(MapLegend, props), {+ wrapper: ({children}) =>+ React.createElement(ThemeProvider, {+ theme,+ children: React.createElement(IntlProvider, {locale: 'en', messages: messages.en, children})+ })+ });+ return {+ ...view,+ update: () => view.rerender(React.createElement(MapLegend, props))+ };+}++function renderContourPasses(layer: ContourLayer, dataset: KeplerTable, data) {+ return layer.renderLayer({+ data,+ visible: true,+ idx: 0,+ gpuFilter: dataset.gpuFilter,+ layerCallbacks: {},+ mapState: {zoom: 10}+ });+}++test.each([true, false])(+ 'colors each contour level from low to high values (below = %s)',+ async below => {+ const {layer, dataset, datasets} = await setup();+ layer.updateLayerVisConfig({+ colorByLevel: true,+ below,+ fillOpacity: 0.2,+ colorRange: {...layer.config.visConfig.colorRange, colors: ['#FF0000', '#00FF00', '#0000FF']}+ });+ const data = layer.formatLayerData(datasets);+ const passes = renderContourPasses(layer, dataset, data);+ const getFillColor = passes[0].props.getFillColor;+ const getLineColor = passes[1].props.getLineColor;+ if (typeof getFillColor !== 'function' || typeof getLineColor !== 'function') {+ throw new Error('Expected colors for each contour level');+ }+ const ordered = [...data.data].sort((a, b) => a.properties.threshold - b.properties.threshold);+ const view = renderLegend(layer);+ const items = view.getAllByRole('listitem');+ [+ [255, 0, 0],+ [0, 255, 0],+ [0, 0, 255]+ ].forEach((rgb, index) => {+ const info = {index, data: ordered, target: []};+ expect(getFillColor(ordered[index], info)).toEqual([...rgb, 51]);+ const outline = getLineColor(ordered[index], info);+ expect(outline.slice(0, 3)).toEqual(rgb);+ expect(layer.getContourLegend()[index].color).toEqual(outline);+ expect(items[index].querySelector('.legend-row-color')).toHaveStyle({+ backgroundColor: `rgba(${rgb.join(', ')}, ${(outline[3] ?? 255) / 255})`+ });+ });++ layer.updateLayerVisConfig({colorByLevel: false});+ const plain = renderContourPasses(layer, dataset, data);+ expect(plain[0].props.getFillColor).toEqual([36, 218, 211, 51]);+ expect(plain[0].props.data).toBe(data.data);+ expect(plain[0].props.updateTriggers?.getFillColor).not.toEqual(+ passes[0].props.updateTriggers?.getFillColor+ );+ expect(plain[1].props.updateTriggers?.getLineColor).not.toEqual(+ passes[1].props.updateTriggers?.getLineColor+ );+ expect(+ layer.getContourLegend().every(level => level.color.slice(0, 3).join() === '36,218,211')+ ).toBe(true);+ }+);++test('interpolates a palette to the level count and reverses it without losing threshold labels', async () => {+ const {layer, dataset, datasets} = await setup();+ const colorLegends = {[JSON.stringify(['value', true, 2])]: 'Low'};+ layer.updateLayerVisConfig({+ colorByLevel: true,+ levels: 5,+ colorRange: {+ ...layer.config.visConfig.colorRange,+ category: 'Custom',+ colors: ['#FFFFFF', '#000000'],+ colorLegends+ }+ });+ const data = layer.formatLayerData(datasets);+ const before = renderContourPasses(layer, dataset, data);+ expect(layer.getContourLegend().map(level => level.color.slice(0, 3))).toEqual(+ [255, 191, 128, 64, 0].map(value => [value, value, value])+ );+ layer.updateLayerColorUI('colorRange', {colorRangeConfig: {reversed: true}});+ const after = renderContourPasses(layer, dataset, data);+ expect(layer.getContourLegend().map(level => level.color.slice(0, 3))).toEqual(+ [0, 64, 128, 191, 255].map(value => [value, value, value])+ );+ expect(after[0].props.data).toBe(data.data);+ expect(after[0].props.updateTriggers?.getFillColor).not.toEqual(+ before[0].props.updateTriggers?.getFillColor+ );+ expect(after[1].props.updateTriggers?.getLineColor).not.toEqual(+ before[1].props.updateTriggers?.getLineColor+ );+ expect(layer.config.visConfig.colorRange.colorLegends).toEqual(colorLegends);+});++test.each([true, false])(+ 'exports composite palette colors for nested fills (below = %s)',+ async below => {+ const {layer, datasets} = await setup();+ layer.updateLayerVisConfig({+ colorByLevel: true,+ below,+ stroked: false,+ fillOpacity: 0.2,+ colorRange: {...layer.config.visConfig.colorRange, colors: ['#FF0000', '#00FF00', '#0000FF']}+ });+ layer.formatLayerData(datasets);+ const expected = below+ ? [+ [105, 84, 67, 124],+ [0, 142, 113, 92],+ [0, 0, 255, 51]+ ]+ : [+ [255, 0, 0, 51],+ [113, 142, 0, 92],+ [67, 84, 105, 124]+ ];+ expect(layer.getContourLegend().map(level => level.color)).toEqual(expected);+ const view = renderLegend(layer, true);+ view.getAllByRole('listitem').forEach((item, index) => {+ const [r, g, b, alpha] = expected[index];+ expect(item.querySelector('.legend-row-color')).toHaveStyle({+ backgroundColor: `rgba(${r}, ${g}, ${b}, ${alpha / 255})`+ });+ });+ layer.updateLayerVisConfig({fillOpacity: 0});+ expect(+ layer+ .getContourLegend()+ .every(level => level.color.every(Number.isFinite) && level.color[3] === 0)+ ).toBe(true);+ }+);++test.each([undefined, [], ['invalid'], ['#112233']])(+ 'handles a missing, invalid, or single-color palette: %j',+ async colors => {+ const {layer, datasets} = await setup();+ layer.updateLayerVisConfig({+ colorByLevel: true,+ colorRange: {...layer.config.visConfig.colorRange, colors}+ });+ layer.formatLayerData(datasets);+ const expected = colors?.[0] === '#112233' ? [17, 34, 51] : layer.config.color;+ expect(layer.getContourLegend().map(level => level.color.slice(0, 3))).toEqual([+ expected,+ expected,+ expected+ ]);+ }+);++test.each([true, false])(+ 'shows each contour threshold and matching outline color (below = %s)',+ async below => {+ const {layer, dataset, datasets} = await setup();+ layer.updateLayerVisConfig({below});+ const data = layer.formatLayerData(datasets);+ const view = renderLegend(layer);+ const items = () =>+ within(view.getByRole('list', {name: 'Contour levels'})).getAllByRole('listitem');+ const expected = [2, 4, 6].map(value => `${below ? '≤' : '≥'} ${value}`);+ expect(items().map(item => item.textContent)).toEqual(expected);++ const checkColors = () => {+ const passes = layer.renderLayer({+ data,+ visible: true,+ idx: 0,+ gpuFilter: dataset.gpuFilter,+ layerCallbacks: {},+ mapState: {zoom: 10}+ });+ const getLineColor = passes[passes.length - 1].props.getLineColor;+ if (typeof getLineColor !== 'function') throw new Error('Expected per-level outline colors');+ const ordered = [...data.data].sort(+ (a, b) => a.properties.threshold - b.properties.threshold+ );+ items().forEach((item, i) => {+ const [r, g, b, alpha = 255] = getLineColor(ordered[i], {+ index: i,+ data: ordered,+ target: []+ });+ expect(item.querySelector('.legend-row-color')).toHaveStyle({+ backgroundColor: `rgba(${r}, ${g}, ${b}, ${alpha / 255})`+ });+ });+ };+ checkColors();++ layer.updateLayerConfig({color: [200, 100, 50]});+ layer.updateLayerVisConfig({filled: false, stroked: true});+ view.update();+ checkColors();+ expect(items().map(item => item.textContent)).toEqual(expected);+ }+);++test('shows accumulated nested fill colors in the exported legend', async () => {+ const {layer, datasets} = await setup();+ layer.updateLayerVisConfig({stroked: false, fillOpacity: 0.2});+ layer.formatLayerData(datasets);+ const view = renderLegend(layer, true);+ const items = view.getAllByRole('listitem');+ expect(items.map(item => item.textContent)).toEqual(['≤ 2', '≤ 4', '≤ 6']);+ // Three, two, then one overlapping regions, each with 20% opacity.+ [124, 92, 51].forEach((alpha, i) => {+ expect(items[i].querySelector('.legend-row-color')).toHaveStyle({+ backgroundColor: `rgba(36, 218, 211, ${alpha / 255})`+ });+ });+ layer.updateLayerVisConfig({fillOpacity: 0});+ view.update();+ view.getAllByRole('listitem').forEach(item => {+ expect(item.querySelector('.legend-row-color')).toHaveStyle({+ backgroundColor: 'rgba(36, 218, 211, 0)'+ });+ });++ layer.updateLayerVisConfig({filled: false, stroked: false});+ view.update();+ expect(view.queryByRole('list')).toBeNull();+});++test('limits long contour legends to a scrollable channel that can expand independently', async () => {+ const {layer, datasets} = await setup();+ const {layer: otherLayer} = await setup();+ layer.updateLayerVisConfig({minimum: 0.25, maximum: 7.85, levels: 20});+ layer.formatLayerData(datasets);+ otherLayer.formatLayerData(datasets);+ const view = renderLegend(layer, false, {layers: [layer, otherLayer]});+ const [list, otherList] = view.getAllByRole('list', {name: 'Contour levels'});+ const [toggle, otherToggle] = view.getAllByRole('button', {name: 'value'});+ expect(within(list).getAllByRole('listitem')).toHaveLength(20);+ expect(list).toHaveStyle({overflowY: 'auto'});+ expect(parseFloat(getComputedStyle(list).maxHeight)).toBeGreaterThan(0);+ expect(list).toHaveAttribute('tabindex', '0');+ expect(toggle).toHaveAttribute('aria-controls', list.id);+ expect(toggle).toHaveAttribute('aria-expanded', 'false');++ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute('aria-expanded', 'true');+ expect(list).toHaveStyle({maxHeight: 'none'});+ expect(otherToggle).toHaveAttribute('aria-expanded', 'false');+ expect(parseFloat(getComputedStyle(otherList).maxHeight)).toBeGreaterThan(0);++ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute('aria-expanded', 'false');+ expect(parseFloat(getComputedStyle(list).maxHeight)).toBeGreaterThan(0);+ expect(within(list).getAllByRole('listitem')).toHaveLength(20);+});++test.each(['point', 'contour'])(+ '%s legend keeps row and editor heights stable on hover and reveals a working reset control',+ async layerType => {+ const fixture = await setup();+ const layer =+ layerType === 'contour'+ ? fixture.layer+ : new LayerClasses.point({+ dataId: fixture.dataset.id,+ columns: fixture.layer.config.columns+ });+ if (layerType === 'contour') {+ fixture.layer.formatLayerData(fixture.datasets);+ } else {+ layer.updateLayerConfig({+ colorField: fixture.dataset.fields[2],+ colorDomain: [0, 32]+ });+ }+ const view = renderLegend(layer, false, {+ onLayerVisConfigChange: (oldLayer, config) => oldLayer.updateLayerVisConfig(config)+ });+ const editor = view.getAllByRole('textbox')[0] as HTMLInputElement;+ const defaultLabel = editor.value;+ const row = editor.parentElement!;+ expect(within(row).queryByRole('button', {name: 'Reset label'})).toBeNull();+ fireEvent.change(editor, {target: {value: 'Custom label'}});+ view.update();+ const reset = within(row).getByRole('button', {name: 'Reset label'});+ // JSDOM matches :hover while the document is unfocused. Match the real+ // compiled CSS against explicit interaction attributes instead.+ const rules = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter(rule => rule.type === CSSRule.STYLE_RULE) as CSSStyleRule[];+ const styleAt = (element: Element, property: string) =>+ rules+ .filter(rule =>+ element.matches(+ rule.selectorText+ .replace(/:hover/g, '[data-legend-hover]')+ .replace(/:focus-within/g, '[data-legend-focus]')+ )+ )+ .map(rule => rule.style.getPropertyValue(property))+ .filter(Boolean)+ .pop();+ const rowHeight = styleAt(row, 'height');+ const editorHeight = styleAt(editor, 'height');+ expect(rowHeight).toBeTruthy();+ expect(editorHeight).toBeTruthy();+ expect(styleAt(reset, 'opacity')).toBe('0');++ row.setAttribute('data-legend-hover', '');+ editor.setAttribute('data-legend-hover', '');+ expect(styleAt(row, 'height')).toBe(rowHeight);+ expect(styleAt(editor, 'height')).toBe(editorHeight);+ expect(styleAt(reset, 'opacity')).toBe('1');+ expect(styleAt(reset, 'pointer-events')).toBe('auto');+ row.removeAttribute('data-legend-hover');+ editor.removeAttribute('data-legend-hover');+ expect(styleAt(reset, 'opacity')).toBe('0');++ row.setAttribute('data-legend-focus', '');+ expect(styleAt(reset, 'opacity')).toBe('1');+ expect(reset).toHaveAttribute('tabindex', '0');+ fireEvent.keyDown(reset, {key: 'Enter'});+ view.update();+ expect(editor.value).toBe(defaultLabel);+ expect(within(row).queryByRole('button', {name: 'Reset label'})).toBeNull();+ }+);++test('edits and resets contour labels by threshold even when levels have the same color', async () => {+ const {layer, datasets} = await setup();+ layer.updateLayerVisConfig({stroked: false, fillOpacity: 0});+ layer.formatLayerData(datasets);+ const onLayerVisConfigChange = jest.fn((oldLayer, config) => {+ oldLayer.updateLayerVisConfig(config);+ });+ const view = renderLegend(layer, false, {onLayerVisConfigChange});+ const inputs = () => view.getAllByRole('textbox') as HTMLInputElement[];+ expect(inputs().map(input => input.value)).toEqual(['≤ 2', '≤ 4', '≤ 6']);+ fireEvent.change(inputs()[0], {target: {value: 'Low'}});+ view.update();+ fireEvent.change(inputs()[1], {target: {value: 'Medium'}});+ view.update();+ expect(onLayerVisConfigChange).toHaveBeenCalledTimes(2);+ expect(inputs().map(input => input.value)).toEqual(['Low', 'Medium', '≤ 6']);++ layer.updateLayerConfig({color: [100, 150, 200]});+ layer.updateLayerVisConfig({stroked: true, minimum: 4});+ layer.formatLayerData(datasets);+ view.update();+ expect(inputs().map(input => input.value)).toEqual(['Medium', '≤ 5', '≤ 6']);+ layer.updateLayerVisConfig({minimum: 2, below: false});+ layer.formatLayerData(datasets);+ view.update();+ expect(inputs().map(input => input.value)).toEqual(['≥ 2', '≥ 4', '≥ 6']);+ layer.updateLayerVisConfig({below: true});+ layer.formatLayerData(datasets);+ view.update();+ expect(inputs().map(input => input.value)).toEqual(['Low', 'Medium', '≤ 6']);++ fireEvent.click(+ within(view.getAllByRole('listitem')[0]).getByRole('button', {name: 'Reset label'})+ );+ view.update();+ expect(inputs().map(input => input.value)).toEqual(['≤ 2', 'Medium', '≤ 6']);+ expect(layer.config.visConfig.colorRange.colorLegends).toEqual({+ [JSON.stringify(['value', true, 4])]: 'Medium'+ });+});++test.each(['point', 'grid'])(+ 'changing from Contour to %s removes threshold labels while preserving the palette and color labels',+ async newType => {+ const {layer, datasets, dataset} = await setup();+ const data = layer.formatLayerData(datasets);+ const key = JSON.stringify(['value', true, 6]);+ const colorRange = {+ ...layer.config.visConfig.colorRange,+ colors: ['#FF0000', '#00FF00', '#0000FF'],+ colorLegends: {[key]: 'Custom contour', '#FF0000': 'Existing color label'}+ };+ layer.updateLayerVisConfig({colorRange});+ const state = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [layer],+ layerData: [data],+ layerOrder: [layer.id]+ };+ const result = layerTypeChangeUpdater(state, {oldLayer: layer, newType});+ const converted = result.layers[0];+ expect(converted.config.visConfig.colorRange).toEqual({+ ...colorRange,+ colorLegends: {'#FF0000': 'Existing color label'}+ });+ expect(layer.config.visConfig.colorRange).toEqual(colorRange);+ if (newType === 'point') {+ converted.updateLayerConfig({colorField: dataset.fields[2]});+ converted.updateLayerDomain(datasets);+ const view = renderLegend(converted);+ expect(view.queryByDisplayValue('Custom contour')).toBeNull();+ expect(view.getByDisplayValue('Existing color label')).toBeInTheDocument();+ expect(view.container.querySelectorAll('.legend-row-color')).toHaveLength(3);+ }+ const roundTrip = layerTypeChangeUpdater(result, {oldLayer: converted, newType: 'contour'});+ expect(roundTrip.layers[0].config.visConfig.colorRange).toEqual(+ converted.config.visConfig.colorRange+ );+ const retained = layerTypeChangeUpdater(state, {oldLayer: layer, newType: 'contour'});+ expect(retained.layers[0].config.visConfig.colorRange).toEqual(colorRange);+ }+);++test.each([false, true])(+ 'preserves custom labels without editors in read-only legends (export = %s)',+ async isExport => {+ const {layer, datasets} = await setup();+ layer.updateLayerVisConfig({+ minimum: 0.25,+ maximum: 7.85,+ levels: 20,+ colorRange: {+ ...layer.config.visConfig.colorRange,+ colorLegends: {[JSON.stringify(['value', true, 0.25])]: 'Low'}+ }+ });+ layer.formatLayerData(datasets);+ const onLayerVisConfigChange = jest.fn();+ const view = renderLegend(layer, isExport, {disableEdit: !isExport, onLayerVisConfigChange});+ expect(view.queryAllByRole('textbox')).toHaveLength(0);+ expect(view.getByText('Low')).toBeInTheDocument();+ expect(view.getAllByRole('listitem')).toHaveLength(20);+ if (isExport) {+ expect(view.queryByRole('button', {name: 'value'})).toBeNull();+ expect(view.getByRole('list')).toHaveStyle({maxHeight: 'none'});+ }+ expect(onLayerVisConfigChange).not.toHaveBeenCalled();+ }+);++test('keeps legend levels in sync with auto ranges, filters, and invalid or empty data', async () => {+ const {layer, dataset, datasets} = await setup();+ layer.updateLayerVisConfig({customRange: false});+ layer.formatLayerData(datasets);+ const view = renderLegend(layer);+ const labels = () => view.queryAllByRole('listitem').map(item => item.textContent);+ expect(labels()).toEqual(['≤ 8', '≤ 16', '≤ 24']);++ const all = dataset.filteredIndex;+ dataset.filteredIndex = all.filter(i => dataset.dataContainer.valueAt(i, 2) <= 8);+ layer.formatLayerData(datasets);+ view.update();+ expect(labels()).toEqual(['≤ 2', '≤ 4', '≤ 6']);++ dataset.filteredIndex = all;+ layer.updateLayerVisConfig({customRange: true, minimum: 0.25, maximum: 7.85, levels: 20});+ layer.formatLayerData(datasets);+ view.update();+ expect(labels()).toHaveLength(20);+ expect(labels()[0]).toBe('≤ 0.25');+ expect(labels()[19]).toBe('≤ 7.85');++ layer.updateLayerVisConfig({below: false, minimum: 10, maximum: 40, levels: 4});+ layer.formatLayerData(datasets);+ view.update();+ // No geometry exists above 40, so it must not appear as a rendered contour level.+ expect(labels()).toEqual(['≥ 10', '≥ 20', '≥ 30']);++ layer.updateLayerVisConfig({minimum: 50});+ calculateContourLayerData(layer, datasets);+ view.update();+ expect(layer.errorMessage).toMatch(/minimum/);+ expect(labels()).toEqual([]);+ layer.updateLayerVisConfig({minimum: 2, maximum: 6});+ calculateContourLayerData(layer, datasets);+ view.update();+ expect(labels()).toHaveLength(4);+ dataset.filteredIndex = [];+ layer.formatLayerData(datasets);+ view.update();+ expect(labels()).toEqual([]);+ expect(layer.getContourLegend()).toEqual([]);+});++test('filtered samples become holes and clearing the filter restores them', async () => {+ const {layer, dataset, datasets} = await setup();+ const all = dataset.filteredIndex;+ dataset.filteredIndex = all.filter(index => index !== 40);+ const filtered = layer.formatLayerData(datasets);+ expect(filtered.data.every(f => f.geometry.coordinates[0].length === 2)).toBe(true);+ dataset.filteredIndex = all;+ const restored = layer.formatLayerData(datasets);+ expect(restored.data.every(f => f.geometry.coordinates[0].length === 1)).toBe(true);+});++function contourPolygonFilter(layer: ContourLayer, bounds: number[], inverted = false) {+ const [west, south, east, north] = bounds;+ return {+ ...generatePolygonFilter([layer], {+ type: 'Feature',+ id: 'contour-filter-polygon',+ properties: {},+ geometry: {+ type: 'Polygon',+ coordinates: [+ [+ [west, south],+ [east, south],+ [east, north],+ [west, north],+ [west, south]+ ]+ ]+ }+ }),+ inverted+ };+}++test('polygon filters preserve grid holes, isolate layers, and restore on disable or clear', async () => {+ const {layer, dataset, datasets} = await setup();+ layer.updateLayerVisConfig({inputMode: 'grid'});+ const other = new ContourLayer({dataId: dataset.id, columns: layer.config.columns});+ other.updateLayerVisConfig(layer.config.visConfig);+ const point = new LayerClasses.point({dataId: dataset.id, columns: layer.config.columns});+ const layers = [layer, other, point];+ const original = calculateContourLayerData(layer, datasets).layerData.data;+ const pointState = {datasets, animationConfig: StateWFiles.visState.animationConfig};+ const originalPoint = calculateLayerData(point, pointState).layerData.data;+ expect(originalPoint).toHaveLength(dataset.dataContainer.numRows());+ const all = dataset.filteredIndex;+ const filter = contourPolygonFilter(layer, [3.5, 3.5, 4.5, 4.5], true);+ expect(EDITOR_AVAILABLE_LAYERS).toContain(layer.type);++ dataset.filterTable([filter], layers);+ expect(dataset.filteredIndex).toEqual(all);+ expect(dataset.filteredIndexByLayer[layer.id]).toEqual(all.filter(index => index !== 40));+ const filtered = calculateContourLayerData(layer, datasets).layerData.data;+ expect(filtered).toHaveLength(3);+ expect(filtered.every(feature => feature.geometry.coordinates[0].length === 2)).toBe(true);+ expect(other.formatLayerData(datasets).data).toEqual(original);+ expect(calculateLayerData(point, pointState).layerData.data).toEqual(originalPoint);++ dataset.filterTable([{...filter, inverted: false}], layers);+ expect(dataset.filteredIndexByLayer[layer.id]).toEqual([40]);+ expect(calculateContourLayerData(layer, datasets).layerData.data).not.toEqual(filtered);++ dataset.filterTable([{...filter, enabled: false}], layers);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual(original);+ dataset.filterTable([filter], layers);+ dataset.filterTable([], layers);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual(original);++ dataset.filterTable([contourPolygonFilter(layer, [20, 20, 21, 21])], layers);+ expect(dataset.filteredIndexByLayer[layer.id]).toEqual([]);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual([]);+ expect(layer.getContourLegend()).toEqual([]);+ expect(other.formatLayerData(datasets).data).toEqual(original);+});++test.each([false, true])('combines polygon filtering with numeric filters (GPU %s)', async gpu => {+ const {layer, dataset, datasets} = await setup();+ const polygon = contourPolygonFilter(layer, [3.5, 3.5, 4.5, 4.5], true);+ const range = {+ ...getDefaultFilter({dataId: [dataset.id]}),+ type: FILTER_TYPES.range,+ name: ['value'],+ fieldIdx: [2],+ value: [0, 4],+ domain: [0, 32],+ gpu+ };+ dataset.filterTable(assignGpuChannels([polygon, range]), [layer]);+ const grid = buildContourGrid(+ dataset.dataContainer.mapIndex(({index}) => {+ const [longitude, latitude, value] = dataset.dataContainer.rowAsArray(index);+ return {longitude, latitude, value: index !== 40 && value <= 4 ? value : null};+ })+ );+ const expected = generateContours(grid, {smoothing: 0, levels: 3, below: true, domain: [2, 6]});+ expect(expected.length).toBeGreaterThan(0);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual(expected);+});++test.each(['grid', 'geojson'])(+ 'polygon filters %s source samples before scattered interpolation and smoothing',+ async columnMode => {+ const rows = scatteredSamples.map((row, index) => [+ row[0],+ row[1],+ index === 1 ? 1000 : row[2]+ ]);+ const {layer, dataset, datasets} =+ columnMode === 'geojson'+ ? setupGeojson([+ ...rows.map(([x, y, value]) => [polygonGeometry(x, y), value]),+ [null, 1000],+ ['invalid geojson', 1000],+ [{type: 'Point', coordinates: [null, null]}, 1000]+ ])+ : await setup(rows);+ const filter = contourPolygonFilter(layer, [-0.5, -0.5, 1.5, 2.5]);+ // Apply before the first render, so filtering cannot depend on cached geometry.+ dataset.filterTable([filter], [layer]);+ expect(dataset.filteredIndexByLayer[layer.id]).toEqual([0, 2, 3]);+ for (const inputMode of ['auto', 'points'] as const) {+ layer.updateLayerVisConfig({+ inputMode,+ minimum: 4,+ maximum: 8,+ interpolationResolution: 32,+ smoothing: 1.5+ });+ const expectedGrid = buildContourGrid(+ rows.map(([longitude, latitude, value], index) => ({+ longitude,+ latitude,+ value: index === 1 ? null : value+ })),+ inputMode,+ 32+ );+ const expected = generateContours(expectedGrid, {+ smoothing: 1.5,+ levels: 3,+ below: true,+ domain: [4, 8]+ });+ expect(expected.length).toBeGreaterThan(0);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual(expected);+ }+ dataset.filterTable([contourPolygonFilter(layer, [20, 20, 21, 21])], [layer]);+ expect(calculateContourLayerData(layer, datasets).layerData.data).toEqual([]);+ expect(layer.isValid).toBe(true);+ }+);++test.each([Int64, Uint64])(+ 'polygon filters Arrow %p coordinates without coercing nulls',+ async ArrowType => {+ const reference = await setup([+ [0, 0, 3],+ [0, 2, 9],+ [1, 1, 8]+ ]);+ const {layer} = reference;+ layer.updateLayerVisConfig({+ inputMode: 'points',+ minimum: 4,+ maximum: 8,+ interpolationResolution: 32+ });+ const expected = layer.formatLayerData(reference.datasets).data;+ const arrowVector = (values: (number | null)[]) =>+ vectorFromArray(+ values.map(value => (value === null ? null : BigInt(value))),+ new ArrowType()+ );+ const table = new Table({+ longitude: arrowVector([0, 2, 0, 1, null]),+ latitude: arrowVector([0, 0, 2, 1, 1]),+ value: arrowVector([3, 1000, 9, 8, 1000])+ });+ const dataset = new KeplerTable({info: {id: reference.dataset.id}, color: [0, 0, 0]});+ await dataset.importData({+ data: {+ rows: [],+ fields: reference.dataset.fields,+ cols: table.schema.fields.map((_, index) => table.getChildAt(index)!),+ arrowTable: table+ }+ });+ dataset.filterTable([contourPolygonFilter(layer, [-0.5, -0.5, 1.5, 2.5])], [layer]);+ expect(dataset.filteredIndexByLayer[layer.id]).toEqual([0, 2, 3]);+ expect(layer.formatLayerData({[dataset.id]: dataset}).data).toEqual(expected);+ }+);++test('reports invalid settings and recovers after correcting them', async () => {+ const {layer, datasets} = await setup();+ layer.updateLayerVisConfig({minimum: 9, maximum: 3});+ expect(calculateContourLayerData(layer, datasets).layerData).toEqual({});+ expect(layer.errorMessage).toMatch(/minimum/);+ layer.updateLayerVisConfig({minimum: 2, maximum: 6});+ expect(calculateContourLayerData(layer, datasets).layerData.data).toHaveLength(3);+ expect(layer.errorMessage).toBeNull();+ layer.updateLayerVisConfig({levels: 5});+ expect(layer.formatLayerData(datasets).data.map(f => f.properties.threshold)).toEqual([+ 6, 5, 4, 3, 2+ ]);+});++test('applies numeric GPU filters before contouring even at a zero-valued range', async () => {+ const {layer, dataset, datasets} = await setup();+ dataset.gpuFilter = {+ ...dataset.gpuFilter,+ filterValueUpdateTriggers: {test: true},+ filterRange: [[0, 0]],+ filterValueAccessor: () => () => d => [d.index === 40 ? 1 : 0]+ } as any;+ expect(+ layer.formatLayerData(datasets).data.every(f => f.geometry.coordinates[0].length === 2)+ ).toBe(true);+});++test.each(['grid', 'geojson'])(+ 'saves and reloads %s contour settings and columns through the map schema',+ async columnMode => {+ const {layer} = columnMode === 'geojson' ? setupGeojson() : await setup();+ layer.updateLayerVisConfig({+ inputMode: 'points',+ interpolationResolution: 128,+ colorByLevel: true,+ colorRange: {+ ...layer.config.visConfig.colorRange,+ colors: ['#FF0000', '#00FF00', '#0000FF'],+ colorLegends: {[JSON.stringify(['value', true, 2])]: 'Low'}+ }+ });+ const saved = SchemaManager.getConfigToSave({+ ...StateWFiles,+ visState: {...StateWFiles.visState, layers: [layer], layerOrder: [layer.id]}+ });+ const parsed = SchemaManager.parseSavedConfig(saved);+ if (!parsed) throw new Error('Expected the saved contour configuration to parse.');+ const restored = parsed.visState!.layers![0];+ expect(restored.type).toBe('contour');+ expect(restored.config.columnMode).toBe(columnMode);+ expect(restored.config.visConfig).toEqual(layer.config.visConfig);+ // Saved configs retain column names; field indices are resolved against the loaded table.+ expect(restored.config.columns.value).toBe('value');+ if (columnMode === 'geojson') expect(restored.config.columns.geojson).toBe('geometry');+ }+);++describe('GeoJSON scalar inputs', () => {+ test.each([+ ['Point', pointGeometry],+ [+ 'LineString',+ (x, y) => ({+ type: 'LineString',+ coordinates: [+ [x - 1, y - 1],+ [x + 1, y + 1]+ ]+ })+ ],+ ['Polygon', polygonGeometry],+ [+ 'MultiPoint',+ (x, y) => ({+ type: 'MultiPoint',+ coordinates: [+ [x - 1, y],+ [x + 1, y]+ ]+ })+ ],+ [+ 'MultiLineString',+ (x, y) => ({+ type: 'MultiLineString',+ coordinates: [+ [+ [x - 1, y - 1],+ [x + 1, y + 1]+ ]+ ]+ })+ ],+ [+ 'MultiPolygon',+ (x, y) => ({+ type: 'MultiPolygon',+ coordinates: [polygonGeometry(x - 1, y).coordinates, polygonGeometry(x + 1, y).coordinates]+ })+ ],+ [+ 'GeometryCollection',+ (x, y) => ({+ type: 'GeometryCollection',+ geometries: [pointGeometry(x - 1, y), pointGeometry(x + 1, y)]+ })+ ]+ ] as const)(+ 'uses %s representative points and the selected scalar column',+ async (_type, geometry) => {+ const rows = scatteredSamples.map(([x, y, value], index) => {+ const shape = geometry(x, y);+ const feature = {type: 'Feature', geometry: shape, properties: {value: 999}};+ // Exercise raw geometries, Features and both JSON string forms.+ return [[shape, feature, JSON.stringify(shape), JSON.stringify(feature)][index], value];+ });+ const {layer, datasets} = setupGeojson(rows);+ const reference = await setup(scatteredSamples);+ reference.layer.updateLayerVisConfig(layer.config.visConfig);+ expect(layer.hasAllColumns()).toBe(true);+ const actual = layer.formatLayerData(datasets);+ expect(actual.data).toHaveLength(3);+ expect(actual).toEqual(reference.layer.formatLayerData(reference.datasets));+ expect(layer.errorMessage).toBeNull();+ }+ );++ test('requires geometry and value columns only in GeoJSON mode', () => {+ const {layer, datasets} = setupGeojson();+ expect(layer.hasAllColumns()).toBe(true);+ layer.updateLayerConfig({columnMode: 'grid'});+ expect(layer.hasAllColumns()).toBe(false);+ layer.updateLayerConfig({columnMode: 'geojson'});+ for (const name of ['geojson', 'value']) {+ const original = layer.config.columns[name];+ layer.config.columns[name] = {value: null, fieldIdx: -1};+ expect(layer.hasAllColumns()).toBe(false);+ expect(layer.formatLayerData(datasets).data).toEqual([]);+ layer.config.columns[name] = original;+ }+ expect(layer.formatLayerData(datasets).data).toHaveLength(3);+ });++ test('skips invalid geometries without losing valid rows, and handles empty input', () => {+ const invalid = [+ null,+ {},+ 'not geojson',+ {type: 'Feature', geometry: null},+ {type: 'Point', coordinates: [null, null]},+ {type: 'Polygon', coordinates: []},+ {type: 'GeometryCollection', geometries: {}}+ ];+ const valid = scatteredSamples.map(([x, y, value]) => [pointGeometry(x, y), value]);+ const baseline = setupGeojson(valid);+ const mixed = setupGeojson([...invalid.map(geometry => [geometry, 100]), ...valid]);+ expect(mixed.layer.formatLayerData(mixed.datasets)).toEqual(+ baseline.layer.formatLayerData(baseline.datasets)+ );+ expect(mixed.layer.errorMessage).toBeNull();+ for (const rows of [[], invalid.map(geometry => [geometry, 100])]) {+ const empty = setupGeojson(rows);+ expect(empty.layer.formatLayerData(empty.datasets).data).toEqual([]);+ expect(empty.layer.errorMessage).toBeNull();+ }+ });++ test.each(['cpu', 'gpu'])(+ 'applies %s filters before interpolating GeoJSON samples',+ filterType => {+ const {layer, dataset, datasets} = setupGeojson();+ expect(layer.formatLayerData(datasets).data).toHaveLength(3);+ if (filterType === 'cpu') {+ dataset.filteredIndex = [0, 1, 3];+ } else {+ dataset.gpuFilter = {+ ...getGpuFilterProps([], dataset.id, dataset.fields),+ filterValueUpdateTriggers: {test: true},+ filterRange: [[0, 0]],+ filterValueAccessor: () => () => d => [d.index === 2 ? 1 : 0]+ } as any;+ }+ expect(layer.formatLayerData(datasets).data.length).toBeGreaterThan(0);+ expect(layer.meta.bounds[3]).toBeCloseTo(0.625);+ }+ );++ test('retains grid holes when GeoJSON points form a regular lattice', () => {+ const rows = Array.from({length: 81}, (_, i) => {+ const x = i % 9;+ const y = Math.floor(i / 9);+ return [pointGeometry(x, y), i === 40 ? null : 1];+ });+ const {layer, datasets} = setupGeojson(rows);+ layer.updateLayerVisConfig({smoothing: 2});+ const result = layer.formatLayerData(datasets);+ expect(result.data).toHaveLength(3);+ expect(result.data.every(f => f.geometry.coordinates[0].length === 2)).toBe(true);+ });+});++test('interpolates scattered data and recomputes its support when samples are filtered', async () => {+ const {layer, dataset, datasets} = await setup([+ [0, 0, 3],+ [2, 0, 7],+ [0.7, 2, 10.4],+ [1.1, 0.6, 7]+ ]);+ layer.updateLayerVisConfig({minimum: 4, maximum: 8, interpolationResolution: 64});+ expect(layer.formatLayerData(datasets).data).toHaveLength(3);+ expect(layer.errorMessage).toBeNull();+ expect(layer.meta.bounds[3]).toBeCloseTo(2);+ const all = dataset.filteredIndex;+ dataset.filteredIndex = [0, 1, 3];+ expect(layer.formatLayerData(datasets).data.length).toBeGreaterThan(0);+ expect(layer.meta.bounds[3]).toBeCloseTo(0.6);+ dataset.filteredIndex = all;+ layer.updateLayerVisConfig({inputMode: 'grid'});+ expect(calculateContourLayerData(layer, datasets).layerData).toEqual({});+ expect(layer.errorMessage).toMatch(/regularly spaced/);+ layer.updateLayerVisConfig({inputMode: 'points'});+ expect(calculateContourLayerData(layer, datasets).layerData.data).toHaveLength(3);+ expect(layer.errorMessage).toBeNull();+ expect(layer.meta.bounds[3]).toBeCloseTo(2);+});++test.each([false, true])(+ 'sample (scattered = %s) generates all levels with islands and finite closed geometry',+ scattered => {+ const sample = createContourSamples(scattered);+ const {visConfig} = contourConfig.config.visState.layers[0].config;+ const result = generateContours(buildContourGrid(sample), {+ ...visConfig,+ domain: [visConfig.minimum, visConfig.maximum]+ });+ expect(result).toHaveLength(visConfig.levels);+ expect(result.some(f => f.geometry.coordinates.length > 5)).toBe(true);+ for (const feature of result) {+ for (const polygon of feature.geometry.coordinates) {+ for (const ring of polygon) {+ expect(ring[0]).toEqual(ring[ring.length - 1]);+ expect(ring.flat().every(Number.isFinite)).toBe(true);+ }+ }+ }+ }+);diff --git a/src/layers/src/contour-layer/contour-layer.ts b/src/layers/src/contour-layer/contour-layer.tsnew file mode 100644index 000000000..d1cc8d163--- /dev/null+++ b/src/layers/src/contour-layer/contour-layer.ts@@ -0,0 +1,370 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {GeoJsonLayer} from '@deck.gl/layers';+import {PickingInfo} from '@deck.gl/core';+import {Datasets, KeplerTable} from '@kepler.gl/table';+import {RGBColor, VisConfigNumber} from '@kepler.gl/types';+import {LAYER_VIS_CONFIGS} from '@kepler.gl/constants';+import {colorMaybeToRGB, DataContainerInterface} from '@kepler.gl/utils';+import Layer, {LayerBaseConfigPartial} from '../base-layer';+import {getFilterDataFunc} from '../aggregation-layer';+import {getCentroidFromGeometry, parseGeoJsonRawFeature} from '../geojson-layer/geojson-utils';+import ContourLayerIcon from './contour-layer-icon';+import {buildContourGrid, ContourFeature, generateContours, ScalarSample} from './contour-utils';++const numberConfig = (+ property: string,+ defaultValue: number,+ range: [number, number],+ step: number+): VisConfigNumber => ({+ type: 'number',+ property,+ defaultValue,+ range,+ step,+ isRanged: false,+ group: 'contour',+ label: `layerVisConfigs.contour.${property}`+});++export const contourVisConfigs = {+ opacity: 'opacity',+ colorRange: 'colorRange',+ colorByLevel: {+ type: 'boolean',+ property: 'colorByLevel',+ defaultValue: false,+ label: 'layerVisConfigs.contour.colorByLevel'+ },+ inputMode: {+ type: 'select',+ property: 'inputMode',+ defaultValue: 'auto',+ label: 'layerVisConfigs.contour.inputMode',+ options: ['auto', 'grid', 'points']+ },+ interpolationResolution: {+ ...numberConfig('interpolationResolution', 192, [32, 256], 16),+ description: 'layerVisConfigs.contour.interpolationResolutionDescription'+ },+ levels: numberConfig('levels', 7, [2, 20], 1),+ smoothing: {+ ...numberConfig('smoothing', 1.5, [0, 6], 0.25),+ description: 'layerVisConfigs.contour.smoothingDescription'+ },+ fillOpacity: numberConfig('fillOpacity', 0.075, [0, 0.3], 0.005),+ thickness: numberConfig('thickness', 1.5, [0.5, 5], 0.1),+ filled: {...LAYER_VIS_CONFIGS.filled, defaultValue: true},+ stroked: 'stroked',+ below: {+ type: 'boolean',+ property: 'below',+ defaultValue: true,+ label: 'layerVisConfigs.contour.below'+ },+ customRange: {+ type: 'boolean',+ property: 'customRange',+ defaultValue: false,+ label: 'layerVisConfigs.contour.customRange'+ },+ minimum: {...numberConfig('minimum', 0, [-100, 100], 0.1), allowCustomValue: true},+ maximum: {...numberConfig('maximum', 100, [-100, 100], 0.1), allowCustomValue: true}+};++export default class ContourLayer extends Layer {+ constructor(props) {+ super(props);+ this.registerVisConfig(contourVisConfigs);+ }++ get type() {+ return 'contour';+ }+ get name() {+ return 'Contour';+ }+ get layerIcon() {+ return ContourLayerIcon;+ }+ get isAggregated() {+ return true;+ }+ get visualChannels() {+ return {};+ }+ getContourLegend(): Array<+ ContourFeature['properties'] & {color: [number, number, number, number]}+ > {+ const {filled, stroked} = this.config.visConfig;+ if (!filled && !stroked) return [];+ const levels: ContourFeature['properties'][] = this.meta.contourLevels || [];+ const colors = this.getContourColors(levels.length);+ return levels+ .map(level => ({+ ...level,+ color: this.getContourLevelColor(level.rank, colors, stroked)+ }))+ .sort((a, b) => a.threshold - b.threshold);+ }++ private getContourColors(count: number): RGBColor[] {+ const {color, visConfig} = this.config;+ const palette =+ visConfig.colorByLevel && Array.isArray(visConfig.colorRange?.colors)+ ? visConfig.colorRange.colors+ .map(colorMaybeToRGB)+ .filter((value): value is RGBColor => value !== null)+ : [];+ return Array.from({length: count}, (_, rank) => {+ if (!palette.length) return color;+ // Geometry is ordered outside-in. Keep the palette in low-to-high value order+ // regardless of the threshold direction, interpolating to the level count.+ const index = visConfig.below ? count - 1 - rank : rank;+ const position = (index / Math.max(1, count - 1)) * (palette.length - 1);+ const start = Math.floor(position);+ const fraction = position - start;+ const first = palette[start];+ const second = palette[Math.min(start + 1, palette.length - 1)];+ return first.map((value, channel) =>+ Math.round(value + (second[channel] - value) * fraction)+ ) as RGBColor;+ });+ }++ private getContourLevelColor(+ rank: number,+ colors: RGBColor[],+ outlined: boolean+ ): [number, number, number, number] {+ if (outlined) {+ const alpha = 0.3 + (0.7 * rank) / Math.max(1, colors.length - 1);+ return [...colors[rank], Math.round(255 * alpha)];+ }+ // Fill-only swatches composite every enclosing region in draw order, using+ // the renderer's byte-rounded alpha, so nested palette colors also match.+ const fillAlpha = Math.round(255 * this.config.visConfig.fillOpacity) / 255;+ const alpha = 1 - (1 - fillAlpha) ** (rank + 1);+ if (!alpha) return [...colors[rank], 0];+ const blended: RGBColor = [0, 0, 0];+ for (let index = 0; index <= rank; index++) {+ for (let channel = 0; channel < 3; channel++) {+ blended[channel] = colors[index][channel] * fillAlpha + blended[channel] * (1 - fillAlpha);+ }+ }+ return [+ ...(blended.map(value => Math.round(value / alpha)) as RGBColor),+ Math.round(255 * alpha)+ ];+ }++ updateColorRangeByColorUI(newConfig, previous, prop) {+ const previousRange = this.config.visConfig.colorRange;+ super.updateColorRangeByColorUI(newConfig, previous, prop);+ if (+ prop === 'colorRange' &&+ this.config.visConfig.colorRange !== previousRange &&+ previousRange.colorLegends+ ) {+ // Contour labels are keyed by threshold, unlike the standard color-keyed labels.+ this.updateLayerVisConfig({+ colorRange: {+ ...this.config.visConfig.colorRange,+ colorLegends: previousRange.colorLegends+ }+ });+ }+ }+ get columnPairs() {+ return this.defaultPointColumnPairs;+ }+ get columnLabels() {+ return {lat: 'contour.lat', lng: 'contour.lng', value: 'contour.value'};+ }+ get supportedColumnModes() {+ return [+ {key: 'grid', label: 'Scalar samples', requiredColumns: ['lat', 'lng', 'value']},+ {key: 'geojson', label: 'GeoJSON', requiredColumns: ['geojson', 'value']}+ ];+ }+ get noneLayerDataAffectingProps() {+ return [+ ...super.noneLayerDataAffectingProps,+ 'color',+ 'colorRange',+ 'colorByLevel',+ 'fillOpacity',+ 'filled',+ 'stroked'+ ];+ }+ getDefaultLayerConfig(props: LayerBaseConfigPartial) {+ return {...super.getDefaultLayerConfig(props), color: props.color ?? [36, 218, 211]};+ }++ getPositionAccessor(dataContainer?: DataContainerInterface, dataset?: KeplerTable) {+ if (!dataContainer || !this.hasAllColumns()) return () => null;+ const {lat, lng, geojson} = this.config.columns;+ if (this.config.columnMode === 'geojson') {+ const geoArrowEncoding = (+ dataset?.fields[geojson.fieldIdx] ?? dataContainer.getField?.(geojson.fieldIdx)+ )?.metadata?.get('ARROW:extension:name');+ return ({index}: {index: number}) => {+ try {+ const feature = parseGeoJsonRawFeature(+ dataContainer.valueAt(index, geojson.fieldIdx),+ geoArrowEncoding+ );+ // Use the same representative point for polygon filtering and contour generation.+ return getCentroidFromGeometry(feature?.geometry);+ } catch {+ return null;+ }+ };+ }+ return (data: {index: number}) =>+ [lng, lat].map(({fieldIdx}) => {+ const value = dataset+ ? dataset.fields[fieldIdx].valueAccessor(data)+ : dataContainer.valueAt(data.index, fieldIdx);+ // Polygon filtering receives only the container, whose Arrow coordinates may be BigInt.+ return typeof value === 'bigint' ? Number(value) : value;+ });+ }++ formatLayerData(datasets: Datasets): {data: ContourFeature[]} {+ this.errorMessage = null;+ this.updateMeta({contourLevels: []});+ const dataset = this.config.dataId ? datasets[this.config.dataId] : null;+ if (!dataset || !this.hasAllColumns()) return {data: []};+ const {dataContainer, gpuFilter, filteredIndex, filteredIndexByLayer} = dataset;+ const {value} = this.config.columns;+ const getPosition = this.getPositionAccessor(dataContainer, dataset);+ const selected = new Set(filteredIndexByLayer?.[this.id] ?? filteredIndex);+ const activeFilter =+ gpuFilter &&+ Object.values(gpuFilter.filterValueUpdateTriggers).some(trigger => trigger !== null);+ const matches = activeFilter+ ? getFilterDataFunc(gpuFilter.filterRange, gpuFilter.filterValueAccessor(dataContainer)())+ : null;+ const samples: ScalarSample[] = [];+ for (let index = 0; index < dataContainer.numRows(); index++) {+ const position = getPosition({index});+ if (!position) continue;+ // Keep the source lattice even when filters remove an entire row/column.+ samples.push({+ longitude: position[0],+ latitude: position[1],+ value:+ selected.has(index) && (!matches || matches({index}))+ ? dataset.fields[value.fieldIdx].valueAccessor({index})+ : null+ });+ }+ // Let calculateLayerData retain validation errors and manage invalid/recovered state.+ const grid = buildContourGrid(+ samples,+ this.config.visConfig.inputMode,+ this.config.visConfig.interpolationResolution+ );+ if (grid)+ this.updateMeta({+ bounds: [+ grid.longitude,+ grid.latitude,+ grid.longitude + (grid.width - 1) * grid.stepLng,+ grid.latitude + (grid.height - 1) * grid.stepLat+ ]+ });+ const {smoothing, levels, below, customRange, minimum, maximum} = this.config.visConfig;+ const data = generateContours(grid, {+ smoothing,+ levels,+ below,+ domain: customRange ? [minimum, maximum] : undefined+ });+ this.updateMeta({contourLevels: data.map(feature => feature.properties)});+ return {data};+ }++ getHoverData(object: ContourFeature | null) {+ if (!object) return null;+ const {threshold, below} = object.properties;+ const field = String(this.config.columns.value.value || 'value');+ return {+ fieldValues: [+ {labelMessage: 'columns.contour.value', value: `${field} ${below ? '≤' : '≥'} ${threshold}`}+ ]+ };+ }++ isLayerHovered(objectInfo: PickingInfo): boolean {+ const id = objectInfo?.layer?.props?.id;+ return Boolean(+ objectInfo?.picked &&+ (id === this.id || id === `${this.id}-fill` || id === `${this.id}-outline`)+ );+ }++ renderLayer(opts) {+ const {data} = opts;+ if (!data?.data?.length || !this.config.isVisible || opts.visible === false) return [];+ const {color, visConfig} = this.config;+ const colors = this.getContourColors(data.data.length);+ const colorTriggers = [+ color,+ visConfig.colorByLevel,+ visConfig.colorRange,+ visConfig.below,+ data.data.length+ ];+ const defaultProps = this.getDefaultDeckLayerProps(opts);+ const shared = {+ ...defaultProps,+ data: data.data,+ extensions: [],+ // Both passes are coplanar; render fills first and outlines above all fills.+ parameters: {...defaultProps.parameters, depthMask: false},+ autoHighlight: false,+ extruded: false+ };+ return [+ ...(visConfig.filled+ ? [+ new GeoJsonLayer<ContourFeature['properties']>({+ ...shared,+ id: `${this.id}-fill`,+ filled: true,+ stroked: false,+ getFillColor: visConfig.colorByLevel+ ? feature => [+ ...colors[feature.properties.rank],+ Math.round(255 * visConfig.fillOpacity)+ ]+ : [...color, Math.round(255 * visConfig.fillOpacity)],+ updateTriggers: {getFillColor: [...colorTriggers, visConfig.fillOpacity]}+ })+ ]+ : []),+ ...(visConfig.stroked+ ? [+ new GeoJsonLayer<ContourFeature['properties']>({+ ...shared,+ id: `${this.id}-outline`,+ filled: false,+ stroked: true,+ getLineColor: feature =>+ this.getContourLevelColor(feature.properties.rank, colors, true),+ getLineWidth: visConfig.thickness,+ lineWidthUnits: 'pixels',+ lineJointRounded: true,+ lineCapRounded: true,+ updateTriggers: {getLineColor: colorTriggers}+ })+ ]+ : [])+ ];+ }+}diff --git a/src/layers/src/contour-layer/contour-utils.spec.ts b/src/layers/src/contour-layer/contour-utils.spec.tsnew file mode 100644index 000000000..a8704c7c5--- /dev/null+++ b/src/layers/src/contour-layer/contour-utils.spec.ts@@ -0,0 +1,302 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {+ buildContourGrid,+ buildScalarGrid,+ generateContours,+ interpolateScalarSamples,+ ScalarSample,+ smoothScalarGrid+} from './contour-utils';++function samples(size: number, value: (x: number, y: number) => number | null): ScalarSample[] {+ return Array.from({length: size * size}, (_, i) => ({+ longitude: i % size,+ latitude: Math.floor(i / size),+ value: value(i % size, Math.floor(i / size))+ }));+}++const options = {smoothing: 0, levels: 3, below: true, domain: [2, 6] as [number, number]};++describe('scalar contours', () => {+ test('traces nested lower-value regions with thresholds in the original units', () => {+ const grid = buildScalarGrid(samples(9, (x, y) => (x - 4) ** 2 + (y - 4) ** 2));+ const features = generateContours(grid, options);+ expect(features.map(f => f.properties.threshold)).toEqual([6, 4, 2]);+ const widths = features.map(f => {+ const xs = f.geometry.coordinates.flat(2).map(p => p[0]);+ return Math.max(...xs) - Math.min(...xs);+ });+ expect(widths[0]).toBeGreaterThan(widths[1]);+ expect(widths[1]).toBeGreaterThan(widths[2]);+ // The value = 4 contour crosses the center row exactly at x = 2 and x = 6.+ expect(features[1].geometry.coordinates.flat(2)).toContainEqual([2, 4]);+ expect(features[1].geometry.coordinates.flat(2)).toContainEqual([6, 4]);+ });++ test('also supports upper-value regions and negative scalar values', () => {+ const grid = buildScalarGrid(samples(9, (x, y) => -((x - 4) ** 2 + (y - 4) ** 2)));+ const result = generateContours(grid, {...options, below: false, domain: [-6, -2]});+ expect(result.map(f => f.properties.threshold)).toEqual([-6, -4, -2]);+ expect(result.every(f => f.geometry.coordinates.length === 1)).toBe(true);+ });++ test('smooths an isolated spike and preserves constant values at boundaries', () => {+ const spike = buildScalarGrid(samples(9, (x, y) => (x === 4 && y === 4 ? 100 : 0)))!;+ expect(smoothScalarGrid(spike, 0)).toBe(spike.values);+ const smooth = smoothScalarGrid(spike, 1.5);+ expect(smooth[40]).toBeLessThan(100);+ expect(smooth[40]).toBeGreaterThan(smooth[41]);+ expect(smooth[41]).toBeGreaterThan(0);+ const constant = buildScalarGrid(samples(9, () => -12))!;+ expect([...smoothScalarGrid(constant, 2)].every(value => Math.abs(value + 12) < 1e-10)).toBe(+ true+ );+ });++ test.each([0, 10, -12, 1e-20, 1e20])(+ 'does not invent automatic contours in a constant field of %s',+ value => {+ for (const holes of [false, true]) {+ const grid = buildScalarGrid(+ samples(9, (x, y) => (holes && x === 4 && y === 4 ? null : value))+ );+ for (const smoothing of [0, 1.5, 6]) {+ for (const below of [false, true]) {+ expect(generateContours(grid, {smoothing, levels: 7, below})).toEqual([]);+ }+ }+ }+ }+ );++ test.each([+ [0, 1e-20],+ [10, 1e-10]+ ])('preserves real small variations around %s at scale %s', (baseline, scale) => {+ const grid = buildScalarGrid(samples(9, (x, y) => baseline + scale * (x + y)));+ const result = generateContours(grid, {smoothing: 1.5, levels: 7, below: true});+ expect(result).toHaveLength(7);+ expect(new Set(result.map(feature => feature.properties.threshold)).size).toBe(7);+ expect(+ result.flatMap(feature => feature.geometry.coordinates.flat(3)).every(Number.isFinite)+ ).toBe(true);+ });++ test.each([0, 10, -12, 1e-20, 1e20])(+ 'preserves constant values and explicit threshold regions for %s',+ value => {+ const span = Math.abs(value) || 1;+ for (const holes of [false, true]) {+ const grid = buildScalarGrid(+ samples(9, (x, y) => (holes && x === 4 && y === 4 ? null : value))+ )!;+ for (const below of [false, true]) {+ const settings = {+ levels: 3,+ below,+ domain: [value - span, value + span] as [number, number]+ };+ const expected = generateContours(grid, {...settings, smoothing: 0});+ const atValue = expected.find(feature => feature.properties.threshold === value)!;+ expect(atValue.geometry.coordinates).toHaveLength(1);+ expect(atValue.geometry.coordinates[0]).toHaveLength(holes ? 2 : 1);+ for (const smoothing of [1.5, 6]) {+ expect(smoothScalarGrid(grid, smoothing)).toEqual(grid.values);+ expect(generateContours(grid, {...settings, smoothing})).toEqual(expected);+ }+ }+ }+ }+ );++ test('keeps missing values as holes after smoothing', () => {+ const grid = buildScalarGrid(samples(9, (x, y) => (x === 4 && y === 4 ? null : 1)))!;+ expect(Number.isNaN(smoothScalarGrid(grid, 2)[40])).toBe(true);+ const result = generateContours(grid, {...options, smoothing: 2});+ expect(result).toHaveLength(3);+ expect(result.every(f => f.geometry.coordinates[0].length === 2)).toBe(true);+ expect(+ result+ .flatMap(f => f.geometry.coordinates.flat(2))+ .flat()+ .every(Number.isFinite)+ ).toBe(true);+ });++ test('retains a missing full column at the original spacing', () => {+ const input = samples(5, () => 1).filter(d => d.longitude !== 2);+ const grid = buildScalarGrid(input)!;+ expect(grid.width).toBe(5);+ expect(Number.isNaN(grid.values[2])).toBe(true);+ expect(grid.values[3]).toBe(1);+ });++ test('averages duplicate measurements without treating them as weights', () => {+ const grid = buildScalarGrid([+ ...samples(3, () => 10),+ {longitude: 1, latitude: 1, value: 30}+ ])!;+ expect(grid.values[4]).toBe(20);+ });++ test('handles empty, nonfinite, constant, and invalid inputs', () => {+ expect(buildScalarGrid([])).toBeNull();+ expect(generateContours(null, options)).toEqual([]);+ expect(generateContours(buildScalarGrid(samples(3, () => NaN)), options)).toEqual([]);+ expect(+ generateContours(buildScalarGrid(samples(3, () => 4)), {...options, domain: undefined})+ ).toEqual([]);+ expect(() => buildScalarGrid([{longitude: 1, latitude: 1, value: 2}])).toThrow('at least two');+ expect(() =>+ buildScalarGrid(+ samples(3, () => 1).map(d => ({...d, longitude: d.longitude === 2 ? 2.5 : d.longitude}))+ )+ ).toThrow('regularly spaced');+ expect(() =>+ generateContours(buildScalarGrid(samples(3, () => 1)), {...options, domain: [5, 2]})+ ).toThrow('minimum');+ });+});++describe('scattered scalar interpolation', () => {+ const plane = (x: number, y: number) => 3 + 2 * x + 3 * y;+ const scattered = [+ [0, 0],+ [2, 0],+ [0.7, 2],+ [1.1, 0.6]+ ].map(([longitude, latitude]) => ({+ longitude,+ latitude,+ value: plane(longitude, latitude)+ }));++ test('reproduces a linear field and keeps cells outside the sample hull empty', () => {+ const grid = interpolateScalarSamples(scattered, 64)!;+ let valid = 0;+ for (let i = 0; i < grid.values.length; i++) {+ if (!Number.isFinite(grid.values[i])) continue;+ valid++;+ expect(grid.values[i]).toBeCloseTo(+ plane(+ grid.longitude + (i % grid.width) * grid.stepLng,+ grid.latitude + Math.floor(i / grid.width) * grid.stepLat+ ),+ 10+ );+ }+ expect(valid).toBeGreaterThan(1000);+ expect(grid.values[0]).toBe(3);+ expect(grid.values[grid.width - 1]).toBeCloseTo(7);+ expect(Number.isNaN(grid.values[grid.values.length - 1])).toBe(true);+ expect(Number.isNaN(smoothScalarGrid(grid, 2)[grid.values.length - 1])).toBe(true);+ });++ test('auto interpolates irregular positions and generates contours in the input units', () => {+ const grid = buildContourGrid(scattered, 'auto', 64)!;+ expect(Math.max(grid.width, grid.height)).toBe(64);+ expect(+ generateContours(grid, {...options, domain: [4, 8], smoothing: 1}).map(+ f => f.properties.threshold+ )+ ).toEqual([8, 6, 4]);+ expect(() => buildContourGrid(scattered, 'grid')).toThrow('regularly spaced');+ });++ test('does not invent automatic contours when interpolating constant scattered values', () => {+ const grid = buildContourGrid(+ scattered.map(sample => ({...sample, value: 10})),+ 'auto',+ 32+ );+ expect(generateContours(grid, {smoothing: 1.5, levels: 7, below: true})).toEqual([]);+ });++ test.each([0, 1.5])(+ 'preserves constant scattered regions at custom thresholds with smoothing %s',+ smoothing => {+ for (const value of [0, 10, -12, 1e-20, 1e20]) {+ const grid = buildContourGrid(+ scattered.map(sample => ({...sample, value})),+ 'auto',+ 32+ )!;+ const constantGrid = {+ ...grid,+ values: Float64Array.from(grid.values, cell => (Number.isFinite(cell) ? value : NaN))+ };+ const span = Math.abs(value) || 1;+ for (const below of [false, true]) {+ const settings = {+ levels: 3,+ below,+ domain: [value - span, value + span] as [number, number]+ };+ const expected = generateContours(constantGrid, {...settings, smoothing: 0});+ const result = generateContours(grid, {...settings, smoothing});+ expect(result).toEqual(expected);+ const atValue = result.find(feature => feature.properties.threshold === value)!;+ expect(atValue.geometry.coordinates).toHaveLength(1);+ expect(atValue.geometry.coordinates[0]).toHaveLength(1);+ }+ expect(new Set([...grid.values].filter(Number.isFinite))).toEqual(new Set([value]));+ expect(Number.isNaN(smoothScalarGrid(grid, smoothing)[grid.values.length - 1])).toBe(true);+ }+ }+ );++ test('auto preserves the original grid and its holes; explicit points mode fills gaps', () => {+ const input = samples(5, (x, y) => (x === 2 && y === 2 ? null : plane(x, y)));+ expect(buildContourGrid(input, 'auto', 256)).toEqual(buildScalarGrid(input));+ const interpolated = buildContourGrid(input, 'points', 33)!;+ expect(interpolated.width).toBeGreaterThan(5);+ expect([...interpolated.values].every(Number.isFinite)).toBe(true);+ });++ test('averages duplicate measurements and ignores missing or invalid samples', () => {+ const grid = interpolateScalarSamples(+ [+ {longitude: 0, latitude: 0, value: 2},+ {longitude: 0, latitude: 0, value: 6},+ {longitude: 2, latitude: 0, value: 8},+ {longitude: 0.7, latitude: 2, value: 10},+ {longitude: 20, latitude: 20, value: null},+ {longitude: 20, latitude: 20, value: Infinity},+ {longitude: NaN, latitude: 0, value: 100}+ ],+ 32+ )!;+ expect(grid.values[0]).toBe(4);+ expect(grid.longitude + (grid.width - 1) * grid.stepLng).toBeCloseTo(2);+ expect([...grid.values].filter(Number.isFinite).every(value => value >= 4 && value <= 10)).toBe(+ true+ );+ });++ test('bounds resolution and handles empty, insufficient, collinear and global samples', () => {+ const grid = interpolateScalarSamples(scattered, 10000)!;+ expect(Math.max(grid.width, grid.height)).toBe(256);+ expect(interpolateScalarSamples([])).toBeNull();+ expect(interpolateScalarSamples(scattered.map(d => ({...d, value: null})))).toBeNull();+ expect(() => interpolateScalarSamples(scattered.slice(0, 2))).toThrow('non-collinear');+ expect(() =>+ interpolateScalarSamples(+ [0, 1, 2].map(x => ({+ longitude: x,+ latitude: 2 * x,+ value: x+ }))+ )+ ).toThrow('non-collinear');+ expect(() =>+ buildContourGrid([+ {longitude: -179, latitude: 0, value: 1},+ {longitude: 179, latitude: 0, value: 2},+ {longitude: 179, latitude: 1, value: 3}+ ])+ ).toThrow('antimeridian');+ });+});diff --git a/src/layers/src/contour-layer/contour-utils.ts b/src/layers/src/contour-layer/contour-utils.tsnew file mode 100644index 000000000..905edd37f--- /dev/null+++ b/src/layers/src/contour-layer/contour-utils.ts@@ -0,0 +1,353 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {contours} from 'd3-contour';+import Delaunator from 'delaunator';+import {Feature, MultiPolygon} from 'geojson';++/** Scalar measurements. In grid mode, positions are cell centers and nulls remain no-data. */+export type ScalarSample = {longitude: number; latitude: number; value: number | null};+export type ScalarGrid = {+ width: number;+ height: number;+ longitude: number;+ latitude: number;+ stepLng: number;+ stepLat: number;+ values: Float64Array;+};+export type ContourFeature = Feature<+ MultiPolygon,+ {threshold: number; below: boolean; rank: number}+>;+export type ContourOptions = {+ smoothing: number;+ levels: number;+ below: boolean;+ domain?: [number, number];+};++const MAX_AXIS = 512;++export type ContourInputMode = 'auto' | 'grid' | 'points';++// Only grid-layout failures may fall back to interpolation. Geographic errors must surface.+class ScalarGridLayoutError extends Error {}++function hasValidPosition(d: ScalarSample): boolean {+ return (+ Number.isFinite(d.longitude) &&+ Number.isFinite(d.latitude) &&+ Math.abs(d.longitude) <= 180 &&+ Math.abs(d.latitude) < 90+ );+}++function regionalBounds(samples: ScalarSample[]) {+ let west = Infinity;+ let east = -Infinity;+ let south = Infinity;+ let north = -Infinity;+ for (const d of samples) {+ west = Math.min(west, d.longitude);+ east = Math.max(east, d.longitude);+ south = Math.min(south, d.latitude);+ north = Math.max(north, d.latitude);+ }+ if (east - west > 180) {+ throw new Error(+ 'This contour prototype requires regional samples that do not cross the antimeridian.'+ );+ }+ return {west, east, south, north};+}++function gridAxis(values: number[]): {origin: number; step: number; length: number} {+ const sorted = [...new Set(values)].sort((a, b) => a - b);+ if (sorted.length < 2) {+ throw new ScalarGridLayoutError(+ 'Contours need at least two distinct latitudes and longitudes.'+ );+ }+ // The smallest separation also preserves entirely missing rows/columns.+ let step = Infinity;+ for (let i = 1; i < sorted.length; i++) step = Math.min(step, sorted[i] - sorted[i - 1]);+ const origin = sorted[0];+ const length = Math.round((sorted[sorted.length - 1] - origin) / step) + 1;+ if (length > MAX_AXIS) {+ throw new ScalarGridLayoutError(+ 'Contour grids support up to 512 samples per axis. Use a coarser regular grid.'+ );+ }+ if (+ sorted.some(+ value => Math.abs((value - origin) / step - Math.round((value - origin) / step)) > 0.001+ )+ ) {+ throw new ScalarGridLayoutError(+ 'Contours require regularly spaced longitude/latitude samples.'+ );+ }+ return {origin, step, length};+}++export function buildScalarGrid(samples: ScalarSample[]): ScalarGrid | null {+ const located = samples.filter(hasValidPosition);+ if (!located.length) return null;+ regionalBounds(located);+ const x = gridAxis(located.map(d => d.longitude));+ const y = gridAxis(located.map(d => d.latitude));+ const values = new Float64Array(x.length * y.length).fill(NaN);+ const counts = new Uint32Array(values.length);+ for (const d of located) {+ if (typeof d.value !== 'number' || !Number.isFinite(d.value)) continue;+ const col = Math.round((d.longitude - x.origin) / x.step);+ const row = Math.round((d.latitude - y.origin) / y.step);+ const i = row * x.length + col;+ // Repeated measurements at a cell represent an average, never density.+ const count = ++counts[i];+ values[i] = count === 1 ? d.value : values[i] + (d.value - values[i]) / count;+ }+ return {+ width: x.length,+ height: y.length,+ longitude: x.origin,+ latitude: y.origin,+ stepLng: x.step,+ stepLat: y.step,+ values+ };+}++/** Keep supported lattices (including holes) intact; interpolate only when requested/needed. */+export function buildContourGrid(+ samples: ScalarSample[],+ mode: ContourInputMode = 'auto',+ resolution = 192+): ScalarGrid | null {+ if (mode === 'grid') return buildScalarGrid(samples);+ if (mode === 'auto') {+ try {+ return buildScalarGrid(samples);+ } catch (error) {+ if (!(error instanceof ScalarGridLayoutError)) throw error;+ }+ }+ return interpolateScalarSamples(samples, resolution);+}++/** Linear interpolation over Delaunay triangles; never extrapolate beyond the sample hull. */+export function interpolateScalarSamples(+ samples: ScalarSample[],+ resolution = 192+): ScalarGrid | null {+ const unique = new Map<string, ScalarSample & {value: number; count: number}>();+ for (const sample of samples) {+ if (+ !hasValidPosition(sample) ||+ typeof sample.value !== 'number' ||+ !Number.isFinite(sample.value)+ )+ continue;+ const key = `${sample.longitude},${sample.latitude}`;+ const point = unique.get(key);+ if (point) {+ point.count++;+ point.value += (sample.value - point.value) / point.count;+ } else {+ unique.set(key, {...sample, value: sample.value, count: 1});+ }+ }+ const points = [...unique.values()];+ if (!points.length) return null;+ const {west, east, south, north} = regionalBounds(points);+ const insufficient =+ 'Interpolation needs at least three distinct, non-collinear samples with valid values.';+ if (points.length < 3 || west === east || south === north) throw new Error(insufficient);++ // Regional equirectangular coordinates correct the longitude/latitude aspect ratio.+ const scaleX = Math.cos((((south + north) / 2) * Math.PI) / 180);+ const spanX = (east - west) * scaleX;+ const spanY = north - south;+ const span = Math.max(spanX, spanY);+ const size = Number.isFinite(resolution)+ ? Math.max(32, Math.min(256, Math.round(resolution)))+ : 192;+ const width = Math.max(2, Math.round(((size - 1) * spanX) / span) + 1);+ const height = Math.max(2, Math.round(((size - 1) * spanY) / span) + 1);+ const coords = new Float64Array(points.length * 2);+ for (let i = 0; i < points.length; i++) {+ coords[2 * i] = ((points[i].longitude - west) * scaleX) / span;+ coords[2 * i + 1] = (points[i].latitude - south) / span;+ }+ const {triangles} = new Delaunator(coords);+ if (!triangles.length) throw new Error(insufficient);+ const values = new Float64Array(width * height).fill(NaN);+ const stepX = spanX / span / (width - 1);+ const stepY = spanY / span / (height - 1);+ const tolerance = 1e-10;+ // Rasterize each triangle's bounding box, rather than searching every point for every cell.+ for (let t = 0; t < triangles.length; t += 3) {+ const ia = triangles[t];+ const ib = triangles[t + 1];+ const ic = triangles[t + 2];+ // Preserve flat triangles exactly so roundoff cannot split an explicit threshold region.+ const constantValue =+ points[ia].value === points[ib].value && points[ia].value === points[ic].value+ ? points[ia].value+ : null;+ const ax = coords[2 * ia];+ const ay = coords[2 * ia + 1];+ const bx = coords[2 * ib];+ const by = coords[2 * ib + 1];+ const cx = coords[2 * ic];+ const cy = coords[2 * ic + 1];+ const denominator = (by - cy) * (ax - cx) + (cx - bx) * (ay - cy);+ if (denominator === 0) continue;+ const col0 = Math.max(0, Math.ceil(Math.min(ax, bx, cx) / stepX - tolerance));+ const col1 = Math.min(width - 1, Math.floor(Math.max(ax, bx, cx) / stepX + tolerance));+ const row0 = Math.max(0, Math.ceil(Math.min(ay, by, cy) / stepY - tolerance));+ const row1 = Math.min(height - 1, Math.floor(Math.max(ay, by, cy) / stepY + tolerance));+ for (let row = row0; row <= row1; row++) {+ for (let col = col0; col <= col1; col++) {+ const x = col * stepX;+ const y = row * stepY;+ const a = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / denominator;+ const b = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / denominator;+ const c = 1 - a - b;+ if (a < -tolerance || b < -tolerance || c < -tolerance) continue;+ // Clamp round-off at triangle edges to keep values within their samples' range.+ const wa = Math.max(0, a);+ const wb = Math.max(0, b);+ const wc = Math.max(0, c);+ values[row * width + col] =+ constantValue ??+ (wa * points[ia].value + wb * points[ib].value + wc * points[ic].value) / (wa + wb + wc);+ }+ }+ }+ return {+ width,+ height,+ longitude: west,+ latitude: south,+ stepLng: (east - west) / (width - 1),+ stepLat: (north - south) / (height - 1),+ values+ };+}++/** Separable, normalized Gaussian smoothing. Missing samples remain missing. */+export function smoothScalarGrid(grid: ScalarGrid, sigma: number): Float64Array {+ if (!Number.isFinite(sigma) || sigma <= 0) return grid.values;+ // A constant field is already smooth. Avoid convolution roundoff changing+ // membership at an explicit threshold equal to that value; retain no-data cells.+ const first = grid.values.find(Number.isFinite);+ if (grid.values.every(value => !Number.isFinite(value) || value === first)) return grid.values;+ const boundedSigma = Math.min(sigma, 6);+ const radius = Math.ceil(boundedSigma * 3);+ const kernel = Array.from({length: radius * 2 + 1}, (_, i) =>+ Math.exp(-0.5 * ((i - radius) / boundedSigma) ** 2)+ );+ let numerator = Float64Array.from(grid.values, value => (Number.isFinite(value) ? value : 0));+ let denominator = Float64Array.from(grid.values, value => (Number.isFinite(value) ? 1 : 0));+ for (const horizontal of [true, false]) {+ const nextNumerator = new Float64Array(grid.values.length);+ const nextDenominator = new Float64Array(grid.values.length);+ for (let row = 0; row < grid.height; row++) {+ for (let col = 0; col < grid.width; col++) {+ const i = row * grid.width + col;+ for (let offset = -radius; offset <= radius; offset++) {+ const x = col + (horizontal ? offset : 0);+ const y = row + (horizontal ? 0 : offset);+ if (x < 0 || x >= grid.width || y < 0 || y >= grid.height) continue;+ const j = y * grid.width + x;+ const weight = kernel[offset + radius];+ nextNumerator[i] += numerator[j] * weight;+ nextDenominator[i] += denominator[j] * weight;+ }+ }+ }+ numerator = nextNumerator;+ denominator = nextDenominator;+ }+ return Float64Array.from(grid.values, (value, i) =>+ Number.isFinite(value) && denominator[i] > 0 ? numerator[i] / denominator[i] : NaN+ );+}++export function generateContours(+ grid: ScalarGrid | null,+ options: ContourOptions+): ContourFeature[] {+ if (!grid) return [];+ const values = smoothScalarGrid(grid, options.smoothing);+ let min = Infinity;+ let max = -Infinity;+ for (const value of values) {+ if (Number.isFinite(value)) {+ min = Math.min(min, value);+ max = Math.max(max, value);+ }+ }+ if (!Number.isFinite(min)) return [];+ const count = Number.isFinite(options.levels)+ ? Math.max(2, Math.min(20, Math.round(options.levels)))+ : 7;+ const domain = options.domain;+ if (domain && (!domain.every(Number.isFinite) || domain[0] >= domain[1])) {+ throw new Error('Contour minimum must be less than maximum.');+ }+ // Interpolation and normalized smoothing can introduce a few ULPs of variation+ // in a constant field. Scale the tolerance to the values, without an absolute+ // floor that would discard meaningful variation in very small scalar units.+ const roundoff = Math.max(Math.abs(min), Math.abs(max)) * Number.EPSILON * 32;+ if (!domain && max - min <= roundoff) return [];+ // Auto levels lie inside the range to avoid a rectangle at the field boundary.+ const thresholds = Array.from({length: count}, (_, i) =>+ domain+ ? domain[0] + ((domain[1] - domain[0]) * i) / (count - 1)+ : min + ((max - min) * (i + 1)) / (count + 1)+ );+ const sign = options.below ? -1 : 1;+ const input = Array.from(values, value => (Number.isFinite(value) ? value * sign : NaN));+ // d3-contour v3's built-in interpolation produces NaN vertices beside no-data.+ // Stitch the rings first, then interpolate only edges with two valid samples.+ // Unknown-cell boundaries retain their cell-edge midpoint and remain holes.+ const geometries = contours()+ .size([grid.width, grid.height])+ .smooth(false)+ .thresholds(thresholds.map(value => value * sign).sort((a, b) => a - b))(input);+ return geometries+ .filter(geometry => geometry.coordinates.length > 0)+ .map((geometry, rank) => ({+ type: 'Feature',+ properties: {threshold: geometry.value * sign, below: options.below, rank},+ geometry: {+ type: 'MultiPolygon',+ coordinates: geometry.coordinates.map(polygon =>+ polygon.map(ring =>+ ring.map(([x, y]) => {+ const col = Math.floor(x);+ const row = Math.floor(y);+ const b = input[row * grid.width + col];+ if (x > 0 && x < grid.width && Number.isInteger(x)) {+ const a = input[row * grid.width + col - 1];+ if (Number.isFinite(a) && Number.isFinite(b) && a !== b)+ x += (geometry.value - a) / (b - a) - 0.5;+ }+ if (y > 0 && y < grid.height && Number.isInteger(y)) {+ const a = input[(row - 1) * grid.width + col];+ if (Number.isFinite(a) && Number.isFinite(b) && a !== b)+ y += (geometry.value - a) / (b - a) - 0.5;+ }+ return [+ grid.longitude + (x - 0.5) * grid.stepLng,+ grid.latitude + (y - 0.5) * grid.stepLat+ ];+ })+ )+ )+ }+ }));+}diff --git a/src/layers/src/index.ts b/src/layers/src/index.tsindex 3709f0daf..7d7321f6e 100644--- a/src/layers/src/index.ts+++ b/src/layers/src/index.ts@@ -25,6 +25,7 @@ export {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';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';@@ -145,6 +146,7 @@ export const KeplerGlLayers = {ClusterLayer,IconLayer,HeatmapLayer,+ ContourLayer,H3Layer,ScenegraphLayer,TripLayer,@@ -172,6 +174,7 @@ export const LayerClasses = {[LAYER_TYPES.cluster]: ClusterLayer,[LAYER_TYPES.icon]: IconLayer,[LAYER_TYPES.heatmap]: HeatmapLayer,+ [LAYER_TYPES.contour]: ContourLayer,[LAYER_TYPES.hexagonId]: H3Layer,[LAYER_TYPES['3D']]: ScenegraphLayer,[LAYER_TYPES.trip]: TripLayer,diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 42795ab37..40e064597 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -149,6 +149,7 @@ export default {cluster: 'cluster',icon: 'icon',heatmap: 'heatmap',+ contour: 'contour',hexagon: 'hexagon',hexagonid: 'H3',trip: 'trip',@@ -293,6 +294,28 @@ export default {locationTotalsEnabled: 'Location Totals',maxTopFlowsDisplayNum: 'Max Top Flows'},+ contour: {+ surface: 'Surface',+ levelsGroup: 'Contour levels',+ fillGroup: 'Fill',+ colorByLevel: 'Color by level',+ inputMode: 'Input type',+ interpolationResolution: 'Interpolation resolution',+ interpolationResolutionDescription:+ 'Samples along the longer axis of the interpolated surface. Regular grids retain their original resolution.',+ smoothing: 'Smoothing',+ smoothingDescription: 'Gaussian smoothing in grid cells. Missing values remain empty.',+ levels: 'Number of levels',+ below: 'Fill below each level',+ invert: 'Invert',+ customRange: 'Custom level range',+ noValueRange:+ 'Select a value column with at least two distinct finite values to use the range slider.',+ minimum: 'Minimum level',+ maximum: 'Maximum level',+ fillOpacity: 'Opacity',+ thickness: 'Outline width'+ },flowField: {streamlines: 'Streamlines',animation: 'Animation',@@ -1146,6 +1169,11 @@ ${'```'}hexagon: {worldUnitSize: 'Hexagon Radius (km)'},+ contour: {+ lat: 'Latitude',+ lng: 'Longitude',+ value: 'Value'+ },hex_id: 'hex id',flowField: {u: 'U (Eastward)',@@ -1254,6 +1282,9 @@ ${'```'}min: 'Min',max: 'Max',layers: {+ contour: {+ levels: 'Contour levels'+ },line: {singleColor: {sourceColor: 'Source',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 2a2d21b70..385e05c35 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -69,6 +69,7 @@ import {applyFiltersToDatasets,arrayInsert,combineSplitMapsByIndex,+ colorMaybeToRGB,computeSplitMapLayers,adjustValueToFilterDomain,areFilterFieldTypesCompatible,@@ -1181,6 +1182,25 @@ export function layerTypeChangeUpdater(state.datasets,defaultLayerProps);++ // Contour uses scalar thresholds as legend-label keys. When leaving Contour,+ // retain only color-keyed labels while preserving the palette.+ const colorRange = newLayer.config.visConfig.colorRange;+ if (+ oldLayer.type === LAYER_TYPES.contour &&+ newType !== LAYER_TYPES.contour &&+ colorRange?.colorLegends+ ) {+ newLayer.updateLayerVisConfig({+ colorRange: {+ ...colorRange,+ colorLegends: Object.fromEntries(+ Object.entries(colorRange.colorLegends).filter(([color]) => colorMaybeToRGB(color))+ )+ }+ });+ }+if (!AGGREGATION_COUNT_LAYER_TYPES.has(newType)) {const textLabel = newLayer.config.textLabel.filter(label => !isPointCountLabel(label));if (textLabel.length !== newLayer.config.textLabel.length) {diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex 2ae91381e..1a9cddd94 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -189,6 +189,11 @@ export type KeplerApplicationConfig = {// Flow Field (streamlines) layer configenableFlowFieldLayer?: boolean;+ // Contour layer config -- Experimental+ // Enabled by default. Set false to hide Contour in layer type pickers.+ // Existing Contour layers in saved maps can still render.+ enableContourLayer?: boolean;+/** Whether to show example URLs in tileset setup forms (vector tile, raster tile, WMS, 3D tile) */showInlineTilesetExamples?: boolean;@@ -477,6 +482,9 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {// Flow Field layer configenableFlowFieldLayer: true,+ // Contour layer config -- disable via initApplicationConfig+ enableContourLayer: true,+showInlineTilesetExamples: true,// Image export configdiff --git a/src/utils/src/filter-utils.ts b/src/utils/src/filter-utils.tsindex e1434fb15..765e2da94 100644--- a/src/utils/src/filter-utils.ts+++ b/src/utils/src/filter-utils.ts@@ -648,6 +648,7 @@ export const getPolygonFilterFunctor = (layer, filter, dataContainer) => {return layer.isInPolygon(data, data.index, filter.value);};case LAYER_TYPES.heatmap:+ case LAYER_TYPES.contour:if (layer.centroids?.length) {return data => {const centroid = layer.centroids[data.index];diff --git a/test/browser/components/side-panel/layer-configurator-test.js b/test/browser/components/side-panel/layer-configurator-test.jsindex 42d1021b0..30ccc172e 100644--- a/test/browser/components/side-panel/layer-configurator-test.js+++ b/test/browser/components/side-panel/layer-configurator-test.js@@ -6,7 +6,11 @@import React from 'react';import test from 'tape';import sinon from 'sinon';-import {fireEvent, within} from '@testing-library/react';+import {fireEvent, render, within} from '@testing-library/react';+import {ThemeProvider} from 'styled-components';+import {theme} from '@kepler.gl/styles';+import {KeplerTable} from '@kepler.gl/table';+import {Int64, Uint64, Table, vectorFromArray} from 'apache-arrow';import {renderWithTheme} from 'test/helpers/component-jest-utils';import {@@ -167,6 +171,619 @@ test('Components -> LayerConfigurator localizes the aggregation count label', tt.end();});+function contourRangeDataset(+ id = 'contour-range-data',+ rows = [+ [-2, 1000],+ [8, 2000]+ ],+ names = ['value', 'other']+) {+ return new KeplerTable({info: {id}, color: [0, 0, 0]}).updateSchema({+ fields: names.map(name => ({name, type: 'real', analyzerType: 'FLOAT'})),+ rows+ });+}++function contourRangeLayer(dataset) {+ return new LayerClasses.contour({+ id: 'contour-range',+ dataId: dataset.id,+ columns: {value: {value: 'value', fieldIdx: 0}}+ });+}++function renderContourRange(layer, datasets, onChange, overrides = {}) {+ const props = {...defaultProps, layer, datasets, updateLayerVisConfig: onChange, ...overrides};+ const view = render(<LayerConfigurator {...props} />, {+ wrapper: ({children}) => (+ <ThemeProvider theme={theme}>+ <IntlWrapper>{children}</IntlWrapper>+ </ThemeProvider>+ )+ });+ return {+ ...view,+ ...within(view.container),+ update: () => view.rerender(<LayerConfigurator {...props} />)+ };+}++function dragContourHandle(container, index, percent) {+ const range = container.querySelector('.contour-level-range');+ const slider = range.querySelector('.kg-slider');+ Object.defineProperty(slider, 'offsetWidth', {configurable: true, value: 100});+ const handles = range.querySelectorAll('.kg-range-slider__handle');+ fireEvent.mouseDown(handles[index], {clientX: percent});+ fireEvent.mouseMove(document, {clientX: percent});+ fireEvent.mouseUp(document);+}++function contourRangeLabels(container) {+ return Array.from(container.querySelectorAll('.contour-range-values output'), item =>+ Number(item.textContent)+ );+}++function contourConfigGroup(view, label) {+ return view+ .getByText(label, {selector: '.layer-config-group__label span'})+ .closest('.layer-config-group');+}++function toggleConfigGroup(group) {+ fireEvent.click(group.querySelector('.layer-config-group__header'));+}++test('Components -> LayerConfigurator -> contour switches between plain color and the palette picker', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ const plainColor = layer.config.color;+ const colorLegends = {[JSON.stringify(['value', true, 2])]: 'Low'};+ layer.updateLayerVisConfig({colorRange: {...layer.config.visConfig.colorRange, colorLegends}});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange, {+ updateLayerColorUI: (property, config) => layer.updateLayerColorUI(property, config)+ });+ try {+ const group = contourConfigGroup(view, 'Color');+ const toggle = group.querySelector('#contour-range-colorByLevel-switch');+ t.notOk(toggle.checked, 'existing maps start in plain-color mode');+ t.ok(group.querySelector('.color-selector__selector__block'), 'shows the plain color picker');+ t.notOk(+ toggle.closest('.layer-config-group__content__collapsible'),+ 'color mode is available without expanding'+ );+ fireEvent.click(toggle);+ t.deepEqual(onChange.lastCall.args[0], {colorByLevel: true}, 'enables color by level');+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.notOk(+ group.querySelector('.color-selector__selector__block'),+ 'replaces the single-color picker'+ );+ t.ok(group.querySelector('.color-range-palette'), 'shows a palette preview');++ fireEvent.click(group.querySelector('.color-selector__selector'));+ view.update();+ t.ok(group.querySelector('.color-range-selector'), 'opens the standard palette picker');+ fireEvent.click(group.querySelector('.color-palette-outer'));+ const {colorRange} = onChange.lastCall.args[0];+ t.ok(colorRange.colors.length > 1, 'selecting a palette emits multiple colors');+ t.deepEqual(+ colorRange.colorLegends,+ colorLegends,+ 'palette selection retains threshold labels'+ );+ layer.updateLayerVisConfig({colorRange});+ view.update();+ fireEvent.click(group.querySelector('#reversed-toggle'));+ view.update();+ t.deepEqual(+ layer.config.visConfig.colorRange.colors,+ [...colorRange.colors].reverse(),+ 'standard reverse control reverses the palette'+ );+ t.deepEqual(+ layer.config.visConfig.colorRange.colorLegends,+ colorLegends,+ 'reversing preserves threshold labels'+ );+ const savedPalette = layer.config.visConfig.colorRange;++ fireEvent.click(toggle);+ t.deepEqual(onChange.lastCall.args[0], {colorByLevel: false}, 'returns to plain color');+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.ok(+ group.querySelector('.color-selector__selector__block'),+ 'restores the plain color picker'+ );+ t.deepEqual(layer.config.color, plainColor, 'retains the original plain color');+ fireEvent.click(toggle);+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.deepEqual(+ layer.config.visConfig.colorRange,+ savedPalette,+ 'retains the chosen palette when switching modes'+ );+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour groups expand independently without changing settings', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ const groups = ['Color', 'Contour levels', 'Surface'].map(label =>+ contourConfigGroup(view, label)+ );+ t.ok(+ groups.every(group => group.classList.contains('collapsed')),+ 'details start collapsed'+ );+ for (const label of ['Number of levels', 'Smoothing']) {+ t.notOk(+ view.getByText(label).closest('.layer-config-group__content__collapsible'),+ `${label} remains available without expanding a group`+ );+ }+ toggleConfigGroup(groups[1]);+ t.notOk(groups[1].classList.contains('collapsed'), 'opens the level controls');+ t.ok(groups[2].classList.contains('collapsed'), 'surface details stay closed');+ toggleConfigGroup(groups[2]);+ t.notOk(groups[2].classList.contains('collapsed'), 'opens the surface controls independently');+ toggleConfigGroup(groups[1]);+ t.ok(groups[1].classList.contains('collapsed'), 'closes the level controls');+ t.notOk(groups[2].classList.contains('collapsed'), 'leaves the surface controls open');++ toggleConfigGroup(groups[0]);+ t.notOk(groups[0].classList.contains('collapsed'), 'opens the color controls');+ toggleConfigGroup(groups[0]);+ t.ok(groups[0].classList.contains('collapsed'), 'closes the color controls');+ t.ok(onChange.notCalled, 'expanding and collapsing groups does not change layer settings');++ layer.updateLayerVisConfig({inputMode: 'grid'});+ view.update();+ t.notOk(view.queryByText('Interpolation resolution'), 'grid mode hides interpolation settings');+ t.notOk(groups[2].classList.contains('collapsed'), 'updating settings keeps the group open');+ layer.updateLayerVisConfig({inputMode: 'points'});+ view.update();+ t.ok(+ view.queryByText('Interpolation resolution'),+ 'scattered mode exposes interpolation settings'+ );+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour invert reverses the saved fill direction', t => {+ for (const below of [true, false]) {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({below});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ toggleConfigGroup(contourConfigGroup(view, 'Contour levels'));+ const toggle = view.getByRole('checkbox', {name: 'Invert'});+ t.equal(toggle.checked, !below, 'Invert reflects the saved direction without changing it');+ t.ok(onChange.notCalled, 'loading the control preserves the saved map');+ fireEvent.click(toggle);+ t.deepEqual(onChange.lastCall.args[0], {below: !below}, 'updates the existing below setting');+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.equal(toggle.checked, below, 'reflects the inverted direction');+ fireEvent.click(toggle);+ t.deepEqual(+ onChange.lastCall.args[0],+ {below},+ 'toggling again restores the original direction'+ );+ t.notOk('invert' in layer.config.visConfig, 'does not introduce a new saved setting');+ } finally {+ view.unmount();+ }+ }+ t.end();+});++test('Components -> LayerConfigurator -> contour fill and outline groups retain independent settings', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({fillOpacity: 0.12, thickness: 2.5});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ for (const [property, label, controlLabel, savedProperty, savedValue] of [+ ['filled', 'Fill', 'Opacity', 'fillOpacity', 0.12],+ ['stroked', 'Outline', 'Outline width', 'thickness', 2.5]+ ]) {+ const group = contourConfigGroup(view, label);+ const controls = within(group);+ const toggle = group.querySelector('.layer-config-group__header input');+ t.ok(toggle.checked, `${label} is enabled in its header`);+ t.notOk(+ controls.getByText(controlLabel).closest('.layer-config-group__content__collapsible'),+ `${controlLabel} is available immediately without expanding a group`+ );+ const slider = group.querySelector('.kg-slider');+ Object.defineProperty(slider, 'offsetWidth', {configurable: true, value: 100});+ fireEvent.mouseDown(group.querySelectorAll('.kg-range-slider__handle')[1], {clientX: 60});+ fireEvent.mouseMove(document, {clientX: 60});+ fireEvent.mouseUp(document);+ t.deepEqual(+ onChange.lastCall.args[0],+ {[savedProperty]: property === 'filled' ? 0.18 : 3.2},+ `${controlLabel} slider edits only its own setting`+ );+ t.ok(controls.queryByText(controlLabel), `${label} exposes its control`);+ fireEvent.click(toggle);+ t.deepEqual(onChange.lastCall.args[0], {[property]: false}, `disables only ${label}`);+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.notOk(controls.queryByText(controlLabel), `hides the disabled ${label} control`);+ t.equal(layer.config.visConfig[savedProperty], savedValue, 'preserves the stored setting');++ fireEvent.click(toggle);+ t.deepEqual(onChange.lastCall.args[0], {[property]: true}, `re-enables only ${label}`);+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.ok(controls.queryByText(controlLabel), `restores the enabled ${label} control`);+ t.equal(layer.config.visConfig[savedProperty], savedValue, 'restores the previous value');+ }+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour custom range is revealed on load and survives collapsing', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({customRange: true, minimum: -1, maximum: 6});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ const group = contourConfigGroup(view, 'Contour levels');+ t.notOk(group.classList.contains('collapsed'), 'reveals the saved custom range on load');+ toggleConfigGroup(group);+ t.ok(group.classList.contains('collapsed'), 'allows the custom range to be collapsed');+ toggleConfigGroup(group);+ t.notOk(group.classList.contains('collapsed'), 'reveals the custom range again');+ t.deepEqual(contourRangeLabels(view.container), [-1, 6], 'preserves both slider endpoints');+ t.ok(onChange.notCalled, 'does not reset saved thresholds while collapsing');+ dragContourHandle(view.container, 1, 85);+ t.deepEqual(onChange.lastCall.args[0], {minimum: -1, maximum: 6.5}, 'slider remains editable');+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour custom range uses one two-handle slider without manual inputs', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({customRange: true, minimum: -2, maximum: 8});+ const onChange = sinon.spy();+ const {container, unmount} = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ const range = container.querySelector('.contour-level-range');+ t.equal(range.querySelectorAll('.kg-range-slider__handle').length, 2, 'shows both handles');+ t.equal(+ range.querySelectorAll('input').length,+ 0,+ 'has no manual numeric inputs or custom-input checkbox'+ );+ t.deepEqual(contourRangeLabels(container), [-2, 8], 'shows numeric endpoint labels');+ t.ok(onChange.notCalled, 'rendering a valid saved range does not change it');++ dragContourHandle(container, 0, 25);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 0.5, maximum: 8},+ 'dragging the lower handle updates the paired thresholds'+ );+ dragContourHandle(container, 1, 85);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: -2, maximum: 6.5},+ 'dragging the upper handle updates the paired thresholds'+ );+ t.notOk(+ 'contourRange' in layer.config.visConfig,+ 'does not add a new saved configuration property'+ );+ } finally {+ unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour custom range starts with the column bounds and stays a slider', t => {+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ t.notOk(+ view.container.querySelector('.contour-level-range'),+ 'hides the slider in automatic mode'+ );+ toggleConfigGroup(contourConfigGroup(view, 'Contour levels'));+ fireEvent.click(view.container.querySelector('#contour-range-customRange-switch'));+ t.deepEqual(+ onChange.lastCall.args[0],+ {customRange: true, minimum: -2, maximum: 8},+ 'enabling custom levels starts at the actual column minimum and maximum'+ );+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.deepEqual(contourRangeLabels(view.container), [-2, 8], 'displays the data-derived range');++ layer.updateLayerVisConfig({minimum: -500, maximum: 2500});+ view.update();+ t.equal(+ view.container.querySelectorAll('.contour-level-range .kg-range-slider__handle').length,+ 2,+ 'saved out-of-domain values do not replace the slider with inputs'+ );+ t.equal(+ view.container.querySelectorAll('.contour-level-range input').length,+ 0,+ 'never falls back to manual fields'+ );+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: -2, maximum: 8},+ 'synchronizes out-of-domain thresholds with the displayed slider'+ );+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour slider bounds follow the full selected column and dataset', t => {+ const dataset = contourRangeDataset('contour-range-data', [+ [-2.25, 1000.125],+ [8.75, 5000.875],+ [null, null],+ [NaN, NaN],+ [Infinity, Infinity],+ [-Infinity, -Infinity]+ ]);+ dataset.filteredIndex = [0];+ const nextDataset = contourRangeDataset(+ 'contour-range-next',+ [+ [10, -0.0042],+ [20, 0.0048]+ ],+ ['other', 'value']+ );+ const datasets = {[dataset.id]: dataset, [nextDataset.id]: nextDataset};+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({customRange: true, minimum: -2, maximum: 8});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, datasets, onChange);+ try {+ dragContourHandle(view.container, 0, 0);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: -2.25, maximum: 8},+ 'uses the exact finite minimum, ignoring null and nonfinite entries'+ );+ dragContourHandle(view.container, 1, 100);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: -2, maximum: 8.75},+ 'uses the full-column maximum even when filters exclude that row'+ );++ layer.updateLayerConfig({+ columns: {...layer.config.columns, value: {value: 'other', fieldIdx: 1}}+ });+ view.update();+ t.deepEqual(+ contourRangeLabels(view.container),+ [1000.125, 5000.875],+ 'refreshes to the new column range without manual input'+ );+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 1000.125, maximum: 5000.875},+ 'synchronizes thresholds when the old selection is disjoint'+ );+ layer.updateLayerVisConfig({minimum: 1500, maximum: 4000});+ view.update();+ dragContourHandle(view.container, 1, 100);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 1500, maximum: 5000.875},+ 'uses both new column bounds when dragging'+ );++ layer.updateLayerConfig({+ dataId: nextDataset.id,+ columns: {...layer.config.columns, value: {value: 'value', fieldIdx: 0}}+ });+ view.update();+ t.deepEqual(+ contourRangeLabels(view.container),+ [-0.0042, 0.0048],+ 'resolves the value column by name when a new dataset reorders fields'+ );+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: -0.0042, maximum: 0.0048},+ 'updates stored thresholds to match the new dataset slider'+ );+ dragContourHandle(view.container, 1, 70);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: -0.0042, maximum: 0.0021},+ 'scales the slider step for small decimal data'+ );++ datasets[nextDataset.id] = contourRangeDataset(+ nextDataset.id,+ [+ [0, -10.5],+ [0, 12.5]+ ],+ ['other', 'value']+ );+ view.update();+ t.deepEqual(+ contourRangeLabels(view.container),+ [-10.5, 12.5],+ 'refreshes bounds when a dataset is replaced under the same id'+ );+ t.equal(+ view.container.querySelectorAll('.contour-level-range input').length,+ 0,+ 'dataset changes keep the graphical slider'+ );+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour slider supports Arrow Int64 and Uint64 ranges', async t => {+ for (const ArrowType of [Int64, Uint64]) {+ const dataset = new KeplerTable({info: {id: 'contour-arrow-range'}, color: [0, 0, 0]});+ const arrowTable = new Table({value: vectorFromArray([10n, 20n, null], new ArrowType())});+ await dataset.importData({+ data: {+ fields: [{name: 'value', type: 'integer', analyzerType: 'INT'}],+ rows: [],+ cols: [arrowTable.getChildAt(0)],+ arrowTable+ }+ });+ const layer = contourRangeLayer(dataset);+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ toggleConfigGroup(contourConfigGroup(view, 'Contour levels'));+ fireEvent.click(view.container.querySelector('#contour-range-customRange-switch'));+ t.deepEqual(+ onChange.lastCall.args[0],+ {customRange: true, minimum: 10, maximum: 20},+ 'initializes from numeric field accessors and ignores nulls'+ );+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ view.update();+ t.deepEqual(contourRangeLabels(view.container), [10, 20], 'shows both Arrow bounds');+ dragContourHandle(view.container, 0, 50);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 15, maximum: 20},+ 'Arrow ranges remain adjustable'+ );+ } finally {+ view.unmount();+ }+ }+ t.end();+});++test('Components -> LayerConfigurator -> contour slider refreshes after in-place data changes', async t => {+ const dataset = contourRangeDataset('contour-refresh-range', [[10], [20]], ['value']);+ const container = dataset.dataContainer;+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({customRange: true, minimum: 10, maximum: 20});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ t.deepEqual(contourRangeLabels(view.container), [10, 20], 'starts at the original range');+ await dataset.update({fields: dataset.fields, rows: [[100], [200]]});+ t.equal(dataset.dataContainer, container, 'snapshot updates keep the container identity');+ view.update();+ t.deepEqual(+ contourRangeLabels(view.container),+ [100, 200],+ 'refreshes the range after a snapshot'+ );+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 100, maximum: 200},+ 'synchronizes disjoint saved thresholds'+ );+ layer.updateLayerVisConfig(onChange.lastCall.args[0]);+ t.ok(dataset.appendRows([[300]]), 'appends a value to the same container');+ view.update();+ t.deepEqual(+ contourRangeLabels(view.container),+ [100, 200],+ 'preserves the selection within expanded bounds'+ );+ dragContourHandle(view.container, 1, 100);+ t.deepEqual(+ onChange.lastCall.args[0],+ {minimum: 100, maximum: 300},+ 'allows selecting an appended maximum'+ );+ await dataset.update({fields: dataset.fields, rows: [[null], [NaN]]});+ view.update();+ t.equal(+ view.container.querySelectorAll('.contour-level-range .kg-range-slider__handle').length,+ 0,+ 'clears stale bounds when no finite values remain'+ );+ } finally {+ view.unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> contour slider handles missing, empty, and constant value columns', t => {+ for (const rows of [[], [[null]], [[NaN], [Infinity], [-Infinity]], [[7]], [[7], [7]]]) {+ const dataset = contourRangeDataset('contour-invalid-range', rows);+ const layer = contourRangeLayer(dataset);+ layer.updateLayerVisConfig({customRange: true});+ const onChange = sinon.spy();+ const view = renderContourRange(layer, {[dataset.id]: dataset}, onChange);+ try {+ t.equal(+ view.container.querySelectorAll('.contour-level-range .kg-range-slider__handle').length,+ 0,+ 'does not invent slider bounds without a nonzero finite span'+ );+ t.ok(+ view.container.querySelector('.contour-level-range').textContent.length > 0,+ 'explains why no slider is available'+ );+ t.ok(onChange.notCalled, 'preserves saved settings while bounds are unavailable');+ } finally {+ view.unmount();+ }+ }+ const dataset = contourRangeDataset();+ const layer = contourRangeLayer(dataset);+ layer.updateLayerConfig({+ columns: {...layer.config.columns, value: {value: 'missing', fieldIdx: 0}}+ });+ layer.updateLayerVisConfig({customRange: true});+ const view = renderContourRange(layer, {[dataset.id]: dataset}, sinon.spy());+ t.equal(+ view.container.querySelectorAll('.contour-level-range .kg-range-slider__handle').length,+ 0,+ 'does not use a stale index for a missing column'+ );+ view.unmount();+ t.end();+});+test('Components -> LayerConfigurator.mount -> LayerColumnConfig', t => {// mountconst updateLayerConfigSpy = sinon.spy();diff --git a/test/browser/components/side-panel/layer-manager-test.js b/test/browser/components/side-panel/layer-manager-test.jsindex cca7d347d..94b492202 100644--- a/test/browser/components/side-panel/layer-manager-test.js+++ b/test/browser/components/side-panel/layer-manager-test.js@@ -3,6 +3,11 @@import React from 'react';import test from 'tape';+import {fireEvent, render} from '@testing-library/react';+import {ThemeProvider} from 'styled-components';+import {theme} from '@kepler.gl/styles';+import {LayerClasses} from '@kepler.gl/layers';+import {getApplicationConfig, initApplicationConfig} from '@kepler.gl/utils';import {LayerManagerFactory,@@ -57,6 +62,67 @@ 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()+ );+ t.equal(+ options.includes('contour'),+ enabled === true,+ `${panelListView}: Contour is offered only when the flag is true (${enabled})`+ );+ t.ok(options.includes('point'), 'regular layer types stay available');+ t.equal(layer.type, 'contour', 'changing the flag does not replace the saved layer');+ }+ } finally {+ view.unmount();+ view.container.remove();+ }+ }+ } finally {+ initApplicationConfig({enableContourLayer});+ }+ t.end();+});+test('Components -> LayerManager -> render -> list view', t => {// mountlet wrapper;diff --git a/yarn.lock b/yarn.lockindex 42b7cc5e4..6254a3cdd 100644--- a/yarn.lock+++ b/yarn.lock@@ -4387,6 +4387,7 @@ __metadata:"@turf/center": "npm:^7.2.0""@turf/distance": "npm:^7.2.0""@turf/helpers": "npm:^7.2.0"+ "@types/d3-contour": "npm:^3.0.6""@types/geojson": "npm:^7946.0.8""@types/keymirror": "npm:^0.1.1""@types/styled-components": "npm:^5.1.32"@@ -4394,9 +4395,11 @@ __metadata:apache-arrow: "npm:>=15.0.0"buffer: "npm:6.0.3"d3-array: "npm:^2.8.0"+ d3-contour: "npm:^3.0.2"d3-format: "npm:^3.1.0"d3-interpolate: "npm:^3.0.1"d3-shape: "npm:^1.2.0"+ delaunator: "npm:^5.1.0"es-toolkit: "npm:^1.39.10"global: "npm:^4.3.0"keymirror: "npm:^0.1.1"@@ -10402,6 +10405,13 @@ __metadata:languageName: nodelinkType: hard+"@types/d3-array@npm:*":+ version: 3.2.2+ resolution: "@types/d3-array@npm:3.2.2"+ checksum: 10c0/6137cb97302f8a4f18ca22c0560c585cfcb823f276b23d89f2c0c005d72697ec13bca671c08e68b4b0cabd622e3f0e91782ee221580d6774074050be96dd7028+ languageName: node+ linkType: hard+"@types/d3-array@npm:^2.8.0":version: 2.12.7resolution: "@types/d3-array@npm:2.12.7"@@ -10418,6 +10428,16 @@ __metadata:languageName: nodelinkType: hard+"@types/d3-contour@npm:^3.0.6":+ version: 3.0.6+ resolution: "@types/d3-contour@npm:3.0.6"+ dependencies:+ "@types/d3-array": "npm:*"+ "@types/geojson": "npm:*"+ checksum: 10c0/e7d83e94719af4576ceb5ac7f277c5806f83ba6c3631744ae391cffc3641f09dfa279470b83053cd0b2acd6784e8749c71141d05bdffa63ca58ffb5b31a0f27c+ languageName: node+ linkType: hard+"@types/d3-scale@npm:^3.2.2":version: 3.3.5resolution: "@types/d3-scale@npm:3.3.5"@@ -15532,6 +15552,15 @@ __metadata:languageName: nodelinkType: hard+"d3-contour@npm:^3.0.2":+ version: 3.1.0+ resolution: "d3-contour@npm:3.1.0"+ dependencies:+ d3-array: "npm:2 - 3"+ checksum: 10c0/4590a5a89a3405a537c4cbcdfbb45fd783732dcfb69a0df60c9ad957d65961e227b71a22b2d19dbb99fc7bd5505053603ba0be9f5469982acf6205815456e77f+ languageName: node+ linkType: hard+"d3-dispatch@npm:1 - 3":version: 3.0.1resolution: "d3-dispatch@npm:3.0.1"@@ -16221,6 +16250,15 @@ __metadata:languageName: nodelinkType: hard+"delaunator@npm:^5.1.0":+ version: 5.1.0+ resolution: "delaunator@npm:5.1.0"+ dependencies:+ robust-predicates: "npm:^3.0.2"+ checksum: 10c0/6489e3598212ab8759575e30f3ac26063471846e25c779048f441f2ccefd25efb9a52275e7e8e3dcc5bf5bc5c35169cf1de27f985d359fd5a24057be88fd1817+ languageName: node+ linkType: hard+"delayed-stream@npm:~1.0.0":version: 1.0.0resolution: "delayed-stream@npm:1.0.0"@@ -29925,6 +29963,13 @@ __metadata:languageName: nodelinkType: hard+"robust-predicates@npm:^3.0.2":+ version: 3.0.3+ resolution: "robust-predicates@npm:3.0.3"+ checksum: 10c0/ae23a0318be809545f091a076818747848f144495491e24e6df5d767f2bad0a1501bbeac34e78b74681d1437ecff0585f593ebfe6c8d49a50e79c5053b962693+ languageName: node+ linkType: hard+"router@npm:^2.2.0":version: 2.2.0resolution: "router@npm:2.2.0"