Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(timeline): group line chart series by a field (#3781)
Igor Dykhta363e7542b06b
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.tsindex f24896a39..3a84cf812 100644--- a/src/actions/src/vis-state-actions.ts+++ b/src/actions/src/vis-state-actions.ts@@ -1781,7 +1781,10 @@ export function toggleLayerForMap(type FilterPlotNewProp = {yAxis?: null | Record<string, any>;- plotType?: {type: string};+ plotType?: {+ type?: string;+ [key: string]: any;+ };};export type SetFilterPlotUpdaterAction = {idx: number;diff --git a/src/components/src/common/histogram-plot.tsx b/src/components/src/common/histogram-plot.tsxindex 750149d5e..562f581d4 100644--- a/src/components/src/common/histogram-plot.tsx+++ b/src/components/src/common/histogram-plot.tsx@@ -25,6 +25,8 @@ const histogramStyle = {const HistogramWrapper = styled.svg`overflow: visible;+ border-radius: 2px;+ background: ${props => props.theme.rangePlotBgd};`;const HistogramMaskRect = styled.rect`diff --git a/src/components/src/common/line-chart.tsx b/src/components/src/common/line-chart.tsxindex 215baaf3a..7b8bc0ea9 100644--- a/src/components/src/common/line-chart.tsx+++ b/src/components/src/common/line-chart.tsx@@ -1,7 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useCallback, useMemo, useRef} from 'react';+import React, {useCallback, useLayoutEffect, useMemo, useRef, useState} from 'react';import {scaleTime, scaleLinear} from 'd3-scale';import {bisector} from 'd3-array';import {LineChart} from '@kepler.gl/types';@@ -11,10 +11,15 @@ import {datetimeFormatter} from '@kepler.gl/utils';export interface LineSeriesPoint {x: number;y: number;+ color?: string;+ name?: string;+ points?: LineSeriesPoint[];}const LineChartWrapper = styled.div`position: relative;+ border-radius: 2px;+ background: ${props => props.theme.rangePlotBgd};.line-chart__grid-line {stroke: ${props => props.theme.histogramFillOutRange};@@ -32,24 +37,88 @@ const StyledHint = styled.div`border-radius: 2px;color: ${props => props.theme.textColorLT};font-size: 9px;- margin: 4px;padding: 3px 6px;pointer-events: none;user-select: none;- position: absolute;white-space: nowrap;++ .hint--series {+ display: flex;+ align-items: center;+ gap: 4px;+ }++ .hint--swatch {+ width: 8px;+ height: 8px;+ border-radius: 2px;+ flex: none;+ }`;+const HINT_GAP = 6;++/** Keep the hover hint off the time axis. A tall hint grows upward. */+function placeLineChartHint(+ pointX: number,+ pointY: number,+ hintWidth: number,+ hintHeight: number,+ plotWidth: number,+ plotHeight: number+): {left: number; top: number} {+ let left = pointX + HINT_GAP;+ if (hintWidth && left + hintWidth > plotWidth) {+ left = pointX - hintWidth - HINT_GAP;+ }+ if (left < 0) {+ left = 0;+ }++ const above = pointY - hintHeight - HINT_GAP;+ const below = pointY + HINT_GAP;+ const fitsAbove = above >= 0;+ const fitsBelow = hintHeight > 0 && below + hintHeight <= plotHeight;+ let top = above;+ if (!fitsAbove && fitsBelow) {+ top = below;+ } else if (!fitsAbove && !fitsBelow && hintHeight > 0 && hintHeight <= plotHeight) {+ top = Math.max(0, plotHeight - hintHeight);+ }+ return {left, top};+}+interface HintContentProps {x: number;y: number;+ name?: string;+ points?: LineSeriesPoint[];format: (ts: number) => string;}-const HintContent = ({x, y, format}: HintContentProps) => (+const HintContent = ({x, y, name, points, format}: HintContentProps) => (<StyledHint>- <div className="hint--x">{format(x)}</div>- <div className="row">{y}</div>+ {points && points.length > 1 ? (+ <>+ <div className="hint--x">{format(x)}</div>+ {points.map((point, index) => (+ <div className="hint--series" key={`${point.name ?? 'series'}-${index}`}>+ <span+ className="hint--swatch"+ style={{backgroundColor: point.color || 'transparent'}}+ />+ {point.name ? <span className="hint--name">{point.name}</span> : null}+ <span className="row">{point.y}</span>+ </div>+ ))}+ </>+ ) : (+ <>+ {name ? <div className="hint--name">{name}</div> : null}+ <div className="hint--x">{format(x)}</div>+ <div className="row">{y}</div>+ </>+ )}</StyledHint>);@@ -57,6 +126,8 @@ export interface HoverDP {x: number;y: number;color?: string | number;+ name?: string;+ points?: LineSeriesPoint[];opacity?: string | number;stroke?: string | number;fill?: string | number;@@ -104,9 +175,13 @@ function LineChartFactory() {theme}: LineChartProps) => {const svgRef = useRef<SVGSVGElement>(null);+ const hintRef = useRef<HTMLDivElement>(null);+ const clipIdRef = useRef(`line-chart-clip-${Math.random().toString(36).slice(2)}`);+ const clipId = clipIdRef.current;+ const [hintSize, setHintSize] = useState({width: 0, height: 0});const {yDomain, xDomain} = lineChart || {};- // @ts-expect-error seems lineChart.series has ambiguous types. Requires refactoring.- const series: {lines: any[]; markers: any[]} = lineChart?.series;+ const series =+ lineChart?.series && !Array.isArray(lineChart.series) ? lineChart.series : undefined;const lineColor = color || (theme && theme.activeColor) || '#3A414C';@@ -174,13 +249,6 @@ function LineChartFactory() {[timezone, timeFormat]);- const isHoveredDPVisible = hoveredDP- ? !yAxisAutoRange ||- !paddedYDomain ||- paddedYDomain.length < 2 ||- (hoveredDP.y >= paddedYDomain[0] && hoveredDP.y <= paddedYDomain[1])- : false;-const clampedHoveredDP = useMemo(() => {if (!hoveredDP || !paddedYDomain || paddedYDomain.length < 2) return hoveredDP;return {@@ -199,15 +267,34 @@ function LineChartFactory() {return yScale.ticks(3);}, [yScale]);- const linePaths = useMemo(() => {- if (!xScale || !yScale || !series?.lines) return [];- return series.lines.map(lineData => {- const points = lineData- .filter(p => p.x != null && p.y != null)- .map(p => `${xScale(new Date(p.x))},${yScale(p.y)}`);- return points.length > 1 ? `M${points.join('L')}` : '';+ const lineMarks = useMemo(() => {+ const paths: {key: number; d: string; color: string}[] = [];+ const dots: {key: number; x: number; y: number; color: string}[] = [];+ if (!xScale || !yScale || !series?.lines) {+ return {paths, dots};+ }+ series.lines.forEach((lineData, index) => {+ const points = lineData.filter(point => point.x != null && point.y != null);+ const markColor = series.colors?.[index] || lineColor;+ if (points.length > 1) {+ paths.push({+ key: index,+ d: `M${points+ .map(point => `${xScale(new Date(point.x))},${yScale(point.y)}`)+ .join('L')}`,+ color: markColor+ });+ } else if (points.length === 1) {+ dots.push({+ key: index,+ x: xScale(new Date(points[0].x)),+ y: yScale(points[0].y),+ color: markColor+ });+ }});- }, [xScale, yScale, series]);+ return {paths, dots};+ }, [xScale, yScale, series, lineColor]);const bisectX = useMemo(() => bisector<LineSeriesPoint, number>(d => d.x).left, []);@@ -215,23 +302,43 @@ function LineChartFactory() {(mouseX: number) => {if (!xScale || !series?.lines) return null;const xValue = xScale.invert(mouseX).getTime();- let nearest: LineSeriesPoint | null = null;+ let bestX: number | null = null;let minDist = Infinity;- for (const line of series.lines) {- if (line.length === 0) continue;+ series.lines.forEach(line => {+ if (line.length === 0) return;const idx = bisectX(line, xValue);- // Check the two candidates around the bisection pointfor (const i of [idx - 1, idx]) {- if (i >= 0 && i < line.length) {- const dist = Math.abs(line[i].x - xValue);- if (dist < minDist) {- minDist = dist;- nearest = line[i];- }+ const point = line[i];+ if (!point || point.y == null) continue;+ const dist = Math.abs(point.x - xValue);+ if (dist < minDist) {+ minDist = dist;+ bestX = point.x;}}- }- return nearest;+ });+ if (bestX == null) return null;++ const points: LineSeriesPoint[] = [];+ series.lines.forEach((line, lineIndex) => {+ if (line.length === 0) return;+ const idx = bisectX(line, bestX as number);+ for (const i of [idx - 1, idx, idx + 1]) {+ const point = line[i];+ if (point && point.x === bestX && point.y != null) {+ points.push({+ x: point.x,+ y: point.y,+ color: series.colors?.[lineIndex],+ name: series.names?.[lineIndex]+ });+ break;+ }+ }+ });+ if (!points.length) return null;+ const anchor = points.reduce((best, point) => (point.y > best.y ? point : best), points[0]);+ return points.length > 1 ? {...anchor, points} : anchor;},[xScale, series, bisectX]);@@ -255,11 +362,24 @@ function LineChartFactory() {const hintPosition = useMemo(() => {if (!clampedHoveredDP || !xScale || !yScale) return null;- return {- left: xScale(new Date(clampedHoveredDP.x)),- top: yScale(clampedHoveredDP.y)- };- }, [clampedHoveredDP, xScale, yScale]);+ return placeLineChartHint(+ xScale(new Date(clampedHoveredDP.x)),+ yScale(clampedHoveredDP.y),+ hintSize.width,+ hintSize.height,+ width,+ height+ );+ }, [clampedHoveredDP, xScale, yScale, hintSize, width, height]);++ useLayoutEffect(() => {+ const node = hintRef.current;+ if (!node) {+ return;+ }+ const next = {width: node.offsetWidth, height: node.offsetHeight};+ setHintSize(prev => (prev.width === next.width && prev.height === next.height ? prev : next));+ }, [clampedHoveredDP, hintFormatter]);return (<LineChartWrapper style={{marginTop: `${margin.top}px`}}>@@ -271,27 +391,49 @@ function LineChartFactory() {onMouseLeave={handleMouseLeave}style={{overflow: 'visible'}}>- {gridLines.map((tick, i) => (- <line- key={i}- className="line-chart__grid-line"- x1={0}- x2={width}- y1={yScale!(tick)}- y2={yScale!(tick)}- />- ))}- {linePaths.map((d, i) => (- <path key={i} d={d} fill="none" stroke={lineColor} strokeWidth={1} />- ))}- {isHoveredDPVisible && hoveredDP && xScale && yScale && (- <circle- cx={xScale(new Date(hoveredDP.x))}- cy={yScale(hoveredDP.y)}- r={4}- fill={lineColor}- />- )}+ <defs>+ <clipPath id={clipId}>+ <rect x="0" y="0" width={width} height={height} />+ </clipPath>+ </defs>+ <g clipPath={`url(#${clipId})`}>+ {gridLines.map((tick, i) => (+ <line+ key={i}+ className="line-chart__grid-line"+ x1={0}+ x2={width}+ y1={yScale!(tick)}+ y2={yScale!(tick)}+ />+ ))}+ {lineMarks.paths.map(mark => (+ <path+ key={mark.key}+ d={mark.d}+ fill="none"+ stroke={mark.color}+ strokeWidth={series?.colors ? 1.5 : 1}+ />+ ))}+ {lineMarks.dots.map(mark => (+ <circle key={`dot-${mark.key}`} cx={mark.x} cy={mark.y} r={1.5} fill={mark.color} />+ ))}+ {xScale &&+ yScale &&+ (hoveredDP?.points?.length ? hoveredDP.points : hoveredDP ? [hoveredDP] : []).map(+ (point, index) =>+ point.y == null ? null : (+ <circle+ key={`${point.name ?? 'series'}-${index}`}+ cx={xScale(new Date(point.x))}+ cy={yScale(point.y)}+ r={4}+ fill={String(point.color || lineColor)}+ />+ )+ )}+ </g>{isEnlarged &&yAxisTicks.map((tick, i) => (<text@@ -308,7 +450,17 @@ function LineChartFactory() {{brushComponent}</svg>{clampedHoveredDP && enableChartHover && !brushing && hintPosition ? (- <div style={{position: 'absolute', left: hintPosition.left, top: hintPosition.top}}>+ <div+ ref={hintRef}+ style={{+ position: 'absolute',+ left: hintPosition.left,+ top: hintPosition.top,+ zIndex: 2,+ pointerEvents: 'none',+ visibility: hintSize.height ? 'visible' : 'hidden'+ }}+ ><HintContent {...hoveredDP!} format={hintFormatter} /></div>) : null}diff --git a/src/components/src/filters/time-widget-settings.tsx b/src/components/src/filters/time-widget-settings.tsxindex 3bf6e4be9..31731fd3d 100644--- a/src/components/src/filters/time-widget-settings.tsx+++ b/src/components/src/filters/time-widget-settings.tsx@@ -10,6 +10,8 @@ import {ArrowRight} from '../common/icons';import {TIME_AGGREGATION,AGGREGATION_TYPES,+ ALL_FIELD_TYPES,+ DEFAULT_COLOR_UI,durationMillisecond,durationSecond,durationMinute,@@ -19,12 +21,21 @@ import {durationMonth,durationYear} from '@kepler.gl/constants';-import {TimeRangeFilter, Field} from '@kepler.gl/types';+import {TimeRangeFilter, Field, ColorRange, ColorUI, NestedPartial} from '@kepler.gl/types';import {Datasets} from '@kepler.gl/table';-import {getDefaultTimeFormat} from '@kepler.gl/utils';+import {+ getDefaultTimeFormat,+ PLOT_NUM_GROUPS_ALL,+ PLOT_NUM_GROUPS_OPTIONS,+ DEFAULT_PLOT_NUM_GROUPS,+ MAX_PLOT_NUM_GROUPS,+ updateColorRangeByMatchingPalette,+ updateCustomColorRangeByColorUI+} from '@kepler.gl/utils';import {FormattedMessage} from '@kepler.gl/localization';import TimezoneSelector from './timezone-selector';+import ColorSelectorFactory, {ColorSet} from '../side-panel/layer-panel/color-selector';const MAX_BINS = 2048;@@ -189,6 +200,78 @@ const DisabledBlock = styled.div<DisabledOverlayProps>`pointer-events: ${props => (props.$disabled ? 'none' : 'auto')};`;+const ColorSelectorWrap = styled.div`+ position: relative;+ width: 180px;++ .color-selector__dropdown {+ position: absolute;+ right: 0;+ bottom: calc(100% + 4px);+ z-index: 10;+ width: 292px;+ max-height: 360px;+ }+`;++const GROUP_BY_FIELD_TYPES = new Set<string>([+ ALL_FIELD_TYPES.string,+ ALL_FIELD_TYPES.boolean,+ ALL_FIELD_TYPES.integer,+ ALL_FIELD_TYPES.real,+ ALL_FIELD_TYPES.date+]);++const COLOR_RANGE_UI_KEYS = ['reversed', 'steps', 'colorBlindSafe', 'type'] as const;++function shouldUpdateGroupColorRange(next: NestedPartial<ColorUI>, current: ColorUI): boolean {+ const config = next.colorRangeConfig;+ if (!config) {+ return false;+ }+ return COLOR_RANGE_UI_KEYS.some(+ key =>+ Object.prototype.hasOwnProperty.call(config, key) &&+ config[key] !== current.colorRangeConfig?.[key]+ );+}++function colorRangeFromColorUI(+ currentRange: ColorRange,+ colorRangeConfig: ColorUI['colorRangeConfig'],+ next: NestedPartial<ColorUI>+): ColorRange {+ const isCustomReversed =+ currentRange.category === 'Custom' &&+ Boolean(next.colorRangeConfig) &&+ Object.prototype.hasOwnProperty.call(next.colorRangeConfig, 'reversed');+ if (isCustomReversed) {+ // The helper reverses colors in place. Copy them so filter state stays unchanged.+ return updateCustomColorRangeByColorUI(+ {...currentRange, colors: [...(currentRange.colors || [])]},+ colorRangeConfig+ );+ }+ const updated = updateColorRangeByMatchingPalette(currentRange, colorRangeConfig);+ if (updated !== currentRange) {+ return updated;+ }+ const baseColors = currentRange.colors?.length ? currentRange.colors : [];+ if (!baseColors.length) {+ return currentRange;+ }+ const steps = Math.max(2, colorRangeConfig.steps || baseColors.length);+ const colors = Array.from({length: steps}, (_, i) => baseColors[i % baseColors.length]);+ if (colorRangeConfig.reversed) {+ colors.reverse();+ }+ return {+ ...currentRange,+ colors,+ reversed: Boolean(colorRangeConfig.reversed)+ };+}+export type TimeWidgetSettingsProps = {filter: TimeRangeFilter;datasets: Datasets;@@ -205,9 +288,12 @@ function parseInterval(intervalId: string | undefined): {step: number; unit: strreturn {step: 1, unit: 'day'};}-TimeWidgetSettingsFactory.deps = [FieldSelectorFactory];+TimeWidgetSettingsFactory.deps = [FieldSelectorFactory, ColorSelectorFactory];-function TimeWidgetSettingsFactory(FieldSelector: ReturnType<typeof FieldSelectorFactory>) {+function TimeWidgetSettingsFactory(+ FieldSelector: ReturnType<typeof FieldSelectorFactory>,+ ColorSelector: ReturnType<typeof ColorSelectorFactory>+) {const TimeWidgetSettings: React.FC<TimeWidgetSettingsProps> = ({filter,datasets,@@ -263,6 +349,16 @@ function TimeWidgetSettingsFactory(FieldSelector: ReturnType<typeof FieldSelecto[datasets, filter.dataId]);+ const groupByFields = useMemo(+ () =>+ ((datasets[filter.dataId[0]] || {}).fields || []).filter((f: Field) =>+ GROUP_BY_FIELD_TYPES.has(f.type)+ ),+ [datasets, filter.dataId]+ );++ const groupBy = filter.plotType?.groupBy;+const applyInterval = useCallback((step: number, unit: string) => {if (isIntervalTooSmall(step, unit)) {@@ -325,6 +421,61 @@ function TimeWidgetSettingsFactory(FieldSelector: ReturnType<typeof FieldSelecto[setFilterPlot, filter.plotType?.yAxisAutoRange]);+ const _setGroupByField = useCallback(+ field =>+ setFilterPlot({+ plotType: {groupBy: field ? {fieldName: field.name} : null}+ }),+ [setFilterPlot]+ );++ const _setNumGroups = useCallback(+ value => {+ if (value === null || value === undefined) {+ return;+ }+ setFilterPlot({plotType: {groupBy: {numGroups: value}}});+ },+ [setFilterPlot]+ );++ const _toggleGroupOthers = useCallback(+ () => setFilterPlot({plotType: {groupBy: {groupOthers: !groupBy?.groupOthers}}}),+ [setFilterPlot, groupBy?.groupOthers]+ );++ const _setGroupColor = useCallback(+ colorRange => setFilterPlot({plotType: {groupBy: {colorRange}}}),+ [setFilterPlot]+ );++ const _setGroupColorUI = useCallback(+ (next: NestedPartial<ColorUI>) => {+ const current = (groupBy?.colorUI || DEFAULT_COLOR_UI) as ColorUI;+ const merged = {+ ...current,+ ...next,+ colorRangeConfig: {+ ...current.colorRangeConfig,+ ...(next.colorRangeConfig || {})+ }+ } as ColorUI;+ const currentRange = groupBy?.colorRange;+ const colorRange =+ currentRange && shouldUpdateGroupColorRange(next, current)+ ? colorRangeFromColorUI(currentRange, merged.colorRangeConfig, next)+ : undefined;+ setFilterPlot({+ plotType: {+ groupBy: colorRange ? {colorUI: merged, colorRange} : {colorUI: merged}+ }+ });+ },+ [setFilterPlot, groupBy?.colorUI, groupBy?.colorRange]+ );++ const displayNumGroups = useCallback((opt: number) => String(opt), []);+const displayUnitOption = useCallback((opt: any) => {if (typeof opt === 'string') {return INTERVAL_UNITS.find(u => u.id === opt)?.label || opt;@@ -443,6 +594,92 @@ function TimeWidgetSettingsFactory(FieldSelector: ReturnType<typeof FieldSelecto</DisabledBlock></AxisRow></AxisSection>+ {filter.yAxis ? (+ <AxisSection className="time-widget__group-by">+ <AxisHeader>+ <ArrowRight height="10px" />+ <FormattedMessage id="filterManager.groupBy" />+ </AxisHeader>+ <AxisRow>+ <FieldBlock>+ <FieldLabel>+ <FormattedMessage id="filterManager.groupByField" />+ </FieldLabel>+ <FieldSelectorWrapper>+ <FieldSelector+ fields={groupByFields}+ placement="top"+ id="time-widget-group-by-field"+ value={groupBy?.fieldName || null}+ onSelect={_setGroupByField}+ erasable+ showToken={false}+ />+ </FieldSelectorWrapper>+ </FieldBlock>+ <DisabledBlock $disabled={!groupBy?.fieldName}>+ <FieldBlock>+ <FieldLabel>+ <FormattedMessage id="filterManager.maxGroups" />+ </FieldLabel>+ <SelectorWrapper>+ <ItemSelector+ selectedItems={+ groupBy?.numGroups === PLOT_NUM_GROUPS_ALL+ ? MAX_PLOT_NUM_GROUPS+ : groupBy?.numGroups ?? DEFAULT_PLOT_NUM_GROUPS+ }+ options={PLOT_NUM_GROUPS_OPTIONS}+ multiSelect={false}+ searchable={false}+ onChange={_setNumGroups}+ displayOption={displayNumGroups}+ getOptionValue={opt => opt}+ placement="top"+ disabled={!groupBy?.fieldName}+ />+ </SelectorWrapper>+ </FieldBlock>+ </DisabledBlock>+ <DisabledBlock $disabled={!groupBy?.fieldName}>+ <FieldBlock>+ <FieldLabel>+ <FormattedMessage id="filterManager.groupOthers" />+ </FieldLabel>+ <SwitchBlock>+ <Switch+ checked={Boolean(groupBy?.groupOthers)}+ id={`${filter.id}-group-others`}+ onChange={_toggleGroupOthers}+ disabled={!groupBy?.fieldName}+ secondary+ />+ </SwitchBlock>+ </FieldBlock>+ </DisabledBlock>+ {groupBy?.fieldName && groupBy.colorRange ? (+ <FieldBlock>+ <FieldLabel>+ <FormattedMessage id="filterManager.seriesColors" />+ </FieldLabel>+ <ColorSelectorWrap>+ <ColorSelector+ colorSets={[+ {+ selectedColor: groupBy.colorRange,+ isRange: true,+ setColor: colorRange => _setGroupColor(colorRange as ColorRange)+ } as ColorSet+ ]}+ colorUI={groupBy.colorUI || DEFAULT_COLOR_UI}+ setColorUI={_setGroupColorUI}+ />+ </ColorSelectorWrap>+ </FieldBlock>+ ) : null}+ </AxisRow>+ </AxisSection>+ ) : null}</SettingsPanel>);};diff --git a/src/components/src/filters/time-widget.tsx b/src/components/src/filters/time-widget.tsxindex f8779a537..d60c004ab 100644--- a/src/components/src/filters/time-widget.tsx+++ b/src/components/src/filters/time-widget.tsx@@ -5,8 +5,13 @@ import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';import styled from 'styled-components';import throttle from 'es-toolkit/compat/throttle';import {DEFAULT_TIME_FORMAT, FILTER_VIEW_TYPES} from '@kepler.gl/constants';-import {clamp, datetimeFormatter} from '@kepler.gl/utils';-import {BottomWidgetInner, Button, PanelLabel} from '../common/styled-components';+import {clamp, datetimeFormatter, lineChartSeriesLegend} from '@kepler.gl/utils';+import {+ BottomWidgetInner,+ Button,+ PanelLabel,+ shouldForwardProp+} from '../common/styled-components';import TimeRangeSliderFactory from '../common/time-range-slider';import FloatingTimeDisplayFactory from '../common/animation-control/floating-time-display';import {timeRangeSliderFieldsSelector} from './time-range-filter';@@ -32,6 +37,30 @@ const TimelineContainer = styled.div`touch-action: none;`;+const SeriesLegend = styled.div`+ display: flex;+ flex-wrap: wrap;+ gap: 4px 12px;+ margin-top: -8px;+`;++const SeriesLegendItem = styled.span`+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: ${props => props.theme.textColor};+ font-size: 10px;+ line-height: 14px;+`;++const SeriesSwatch = styled.span.withConfig({shouldForwardProp})<{$color: string}>`+ width: 10px;+ height: 10px;+ border-radius: 2px;+ background: ${props => props.$color};+ flex: 0 0 auto;+`;+const TimelineStatusBar = styled.div`position: absolute;top: -32px;@@ -388,6 +417,11 @@ function TimeWidgetFactory(setTimelineDomain(null);}, []);+ const seriesLegend = useMemo(+ () => (isMinified ? [] : lineChartSeriesLegend(filter.lineChart)),+ [filter.lineChart, isMinified]+ );+return (<TimeBottomWidgetInner className="bottom-widget--inner"><TimeWidgetTop@@ -407,6 +441,16 @@ function TimeWidgetFactory(/>) : null}<TimelineSection>+ {seriesLegend.length > 1 ? (+ <SeriesLegend className="time-widget__series-legend">+ {seriesLegend.map(item => (+ <SeriesLegendItem key={item.name}>+ <SeriesSwatch $color={item.color} />+ {item.name}+ </SeriesLegendItem>+ ))}+ </SeriesLegend>+ ) : null}{timelineZoomed && timelineRangeLabel ? (<TimelineStatusBar><PanelLabel>Showing</PanelLabel>diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 49247515a..af64a2d17 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -403,7 +403,13 @@ export default {timeIntervalEndFieldHint:'Optional. Features stay visible while the playback window overlaps this time span.',timezone: 'Time Zone',- selectTimezone: 'Select display timezone'+ selectTimezone: 'Select display timezone',+ groupBy: 'Group By',+ groupByField: 'Group by field',+ maxGroups: 'Max number of groups',+ groupOthers: 'Group others',+ seriesColors: 'Colors',+ allGroups: 'All'},datasetTitle: {showDataTable: 'Show data table',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 07f089851..a8bd2795f 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -225,6 +225,7 @@ import {mergeTimeDomains,adjustValueToAnimationWindow,updateTimeFilterPlotType,+ mergePlotGroupBy,getDefaultTimeFormat,LayerToFilterTimeInterval,TIME_INTERVALS_ORDERED,@@ -1672,7 +1673,14 @@ export const setFilterPlotUpdater = (for (const prop in newProp) {if (prop === 'plotType') {- newFilter = pick_('plotType')(merge_(newProp.plotType))(newFilter);+ let plotTypeUpdate = newProp.plotType;+ if (plotTypeUpdate && Object.prototype.hasOwnProperty.call(plotTypeUpdate, 'groupBy')) {+ plotTypeUpdate = {+ ...plotTypeUpdate,+ groupBy: mergePlotGroupBy(newFilter.plotType?.groupBy, plotTypeUpdate.groupBy)+ };+ }+ newFilter = pick_('plotType')(merge_(plotTypeUpdate))(newFilter);} else if (prop === 'yAxis') {const chartType = newProp.yAxis ? PLOT_TYPES.lineChart : PLOT_TYPES.histogram;diff --git a/src/styles/src/base.ts b/src/styles/src/base.tsindex 209cedc86..034f9eb8e 100644--- a/src/styles/src/base.ts+++ b/src/styles/src/base.ts@@ -357,6 +357,8 @@ export const mapControlTop = 52;// Plotexport const rangeBrushBgd = '#3A414C';+// Recessed plot surface. Kept darker than the widget so the range brush wash stays visible.+export const rangePlotBgd = '#242730';export const histogramFillInRange = activeColor;export const histogramFillOutRange = sliderBarColor;export const histogramOverlayColor = '#999999';@@ -1479,6 +1481,7 @@ export const theme = {// PlotrangeBrushBgd,+ rangePlotBgd,histogramFillInRange,histogramFillOutRange,histogramOverlayColor,@@ -1676,6 +1679,7 @@ export const themeLT = {linkBtnActColor: textColorLT,rangeBrushBgd: '#D3D8E0',+ rangePlotBgd: '#FFFFFF',histogramFillInRange: activeColorLT,histogramFillOutRange: '#A0A7B4',axisFontColor: textColorLT@@ -1750,6 +1754,7 @@ export const themeBS = {histogramFillInRange: '#000000',histogramFillOutRange: '#E2E2E2',rangeBrushBgd: '#E2E2E2',+ rangePlotBgd: '#FFFFFF',sliderBarBgd: '#E2E2E2',sliderHandleColor: '#FFFFFF',sliderInactiveBorderColor: '#FFFFFF',diff --git a/src/styles/src/space-theme.ts b/src/styles/src/space-theme.tsindex 8638428d6..2787495d9 100644--- a/src/styles/src/space-theme.ts+++ b/src/styles/src/space-theme.ts@@ -175,6 +175,7 @@ export const themeSpace = {sliderBarBgd: COLOR.AZURE900,sliderBarHoverColor: COLOR.AZURE100,rangeBrushBgd: COLOR.AZURE700,+ rangePlotBgd: COLOR.AZURE950,histogramFillInRange: COLOR.BLUE,histogramFillOutRange: COLOR.AZURE600,histogramOverlayColor: COLOR.AZURE600,diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex b0f6569cf..2b01f319f 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -2,6 +2,7 @@// Copyright contributors to the kepler.gl projectimport {Field, Millisecond} from './types';+import {ColorMap, ColorRange, ColorUI} from './layers';import {MapSplitMode, MapViewMode} from '@kepler.gl/constants';type MapViewState = {latitude: number;@@ -125,8 +126,33 @@ export interface LineDatum {pct: number | null;}+export type LineChartSeries = {+ lines: LineDatum[][];+ markers: LineDatum[];+ /** Stroke color for each line segment. Segments from one group share a color. */+ colors?: string[];+ /** Series name for each line segment. */+ names?: string[];+};++export type LineChartGroupBy = {+ fieldName: string;+ numGroups: number | 'ALL';+ groupOthers: boolean;+ colors: string[] | null;+ colorMap?: ColorMap | null;+};++export type PlotGroupBy = {+ fieldName?: string;+ numGroups: number | 'ALL';+ groupOthers: boolean;+ colorRange?: ColorRange;+ colorUI?: ColorUI;+};+export type LineChart = {- series: {x: number; y: number}[];+ series: {x: number; y: number}[] | LineChartSeries;yDomain: number[] | undefined[];xDomain: number[];@@ -135,6 +161,8 @@ export type LineChart = {interval: string;yAxis: string;bins?: Bins;+ /** Cache key for timeline series grouping. Null when the plot is a single series. */+ groupBy?: LineChartGroupBy | null;};type FilterViewType = 'side' | 'enlarged' | 'minified';@@ -269,6 +297,9 @@ export interface PlotType {aggregation: ValueOf<AggregationTypes>;defaultTimeFormat: string;colorsByDataId?: {[dataId: string]: string};+ /** Categorical series split for the timeline line chart. */+ groupBy?: PlotGroupBy | null;+ yAxisAutoRange?: boolean;}export type Feature = {diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex a611fdc4b..3cc09554a 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -57,7 +57,16 @@ export {histogramFromTimeIntervals,mergePolygonLayerIndexes,runGpuFilterForPlot,- updateTimeFilterPlotType+ updateTimeFilterPlotType,+ getLineChart,+ mergePlotGroupBy,+ lineChartSeriesLegend,+ defaultPlotGroupColorRange,+ PLOT_GROUP_OTHERS_NAME,+ PLOT_NUM_GROUPS_ALL,+ PLOT_NUM_GROUPS_OPTIONS,+ DEFAULT_PLOT_NUM_GROUPS,+ MAX_PLOT_NUM_GROUPS} from './plot';// eslint-disable-next-line prettier/prettierexport * from './data-utils';diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.tsindex ea8ce48e9..f45b99818 100644--- a/src/utils/src/plot.ts+++ b/src/utils/src/plot.ts@@ -12,11 +12,16 @@ import {TimeRangeFilter,RangeFilter,PlotType,+ PlotGroupBy,Filter,LineChart,+ LineChartGroupBy,+ LineChartSeries,Field,ValueOf,- LineDatum+ LineDatum,+ ColorRange,+ ColorUI} from '@kepler.gl/types';import {notNullorUndefined, toArray} from '@kepler.gl/common-utils';import {@@ -26,7 +31,11 @@ import {TIME_AGGREGATION,AGGREGATION_TYPES,PLOT_TYPES,- AggregationTypes+ AggregationTypes,+ KEPLER_COLOR_PALETTES,+ colorPaletteToColorRange,+ DEFAULT_COLOR_UI,+ DEFAULT_CUSTOM_PALETTE} from '@kepler.gl/constants';import {isNumber, roundValToStep} from './data-utils';@@ -518,7 +527,7 @@ export const getAggregationOptiosnBasedOnField = field => {function getDelta(bins: LineDatum[],- y: number,+ y: unknown,_interval: PlotType['interval']): Partial<LineDatum> & {delta: 'last'; pct: number | null} {// if (WOW[interval]) return getWow(bins, y, interval);@@ -537,6 +546,332 @@ export function getPctChange(y: unknown, y0: unknown): number | null {return null;}+export const PLOT_GROUP_OTHERS_NAME = 'Others';+export const PLOT_NUM_GROUPS_ALL = 'ALL' as const;+export const DEFAULT_PLOT_NUM_GROUPS = 10;+/** Qualitative palettes stop at 20. All uses this cap instead of one series per value. */+export const MAX_PLOT_NUM_GROUPS = 20;+export const PLOT_NUM_GROUPS_OPTIONS = [1, 3, 5, 7, 10, MAX_PLOT_NUM_GROUPS];++const DEFAULT_PLOT_GROUP_PALETTE = 'Uber Viz Qualitative';+const FALLBACK_SERIES_COLORS = ['#12939A', '#DDB27C', '#88572C', '#FF991F', '#F15C17', '#223F9A'];++export function plotGroupColorSteps(+ numGroups: number | typeof PLOT_NUM_GROUPS_ALL | undefined+): number {+ if (numGroups === PLOT_NUM_GROUPS_ALL || typeof numGroups !== 'number' || numGroups < 1) {+ return MAX_PLOT_NUM_GROUPS;+ }+ return Math.max(2, Math.min(numGroups, MAX_PLOT_NUM_GROUPS));+}++export function defaultPlotGroupColorRange(+ numGroups?: number | typeof PLOT_NUM_GROUPS_ALL+): ColorRange {+ const steps = plotGroupColorSteps(numGroups);+ const palette = KEPLER_COLOR_PALETTES.find(item => item.name === DEFAULT_PLOT_GROUP_PALETTE);+ if (!palette) {+ return {+ name: DEFAULT_PLOT_GROUP_PALETTE,+ type: 'qualitative',+ category: 'Uber',+ colors: FALLBACK_SERIES_COLORS+ };+ }+ return colorPaletteToColorRange(palette, {reversed: false, steps});+}++function defaultPlotGroupColorUI(+ numGroups: number | typeof PLOT_NUM_GROUPS_ALL,+ colorRange: ColorRange+): ColorUI {+ return {+ ...DEFAULT_COLOR_UI,+ colorRangeConfig: {+ ...DEFAULT_COLOR_UI.colorRangeConfig,+ type: 'qualitative',+ steps: plotGroupColorSteps(numGroups)+ },+ customPalette: {+ ...DEFAULT_CUSTOM_PALETTE,+ colors: colorRange.colors || []+ }+ };+}++function mergeGroupColorUI(+ prev: ColorUI | undefined,+ next: Partial<ColorUI> | null | undefined,+ numGroups: number | typeof PLOT_NUM_GROUPS_ALL,+ colorRange: ColorRange+): ColorUI {+ const base = prev ?? defaultPlotGroupColorUI(numGroups, colorRange);+ if (!next) {+ return base;+ }+ return {+ ...base,+ ...next,+ colorRangeConfig: {+ ...base.colorRangeConfig,+ ...(next.colorRangeConfig || {})+ },+ customPalette: next.customPalette+ ? {...base.customPalette, ...next.customPalette}+ : base.customPalette+ };+}++/**+ * Merge a partial timeline group-by onto the previous one.+ * `null` clears grouping. Missing fields keep the previous value, then defaults.+ */+export function mergePlotGroupBy(+ prev: PlotGroupBy | null | undefined,+ next: Partial<PlotGroupBy> | null | undefined+): PlotGroupBy | null {+ if (next === null) {+ return null;+ }+ if (!next && !prev) {+ return null;+ }+ const source = next || {};+ const numGroups = source.numGroups ?? prev?.numGroups ?? DEFAULT_PLOT_NUM_GROUPS;+ const colorRange = source.colorRange ?? prev?.colorRange ?? defaultPlotGroupColorRange(numGroups);+ return {+ fieldName: source.fieldName !== undefined ? source.fieldName : prev?.fieldName,+ numGroups,+ groupOthers: Boolean(source.groupOthers !== undefined ? source.groupOthers : prev?.groupOthers),+ colorRange,+ colorUI: mergeGroupColorUI(prev?.colorUI, source.colorUI, numGroups, colorRange)+ };+}++function groupByCacheValue(plotType: Filter['plotType']): LineChartGroupBy | null {+ const groupBy = plotType?.groupBy as PlotGroupBy | null | undefined;+ if (!groupBy?.fieldName) {+ return null;+ }+ return {+ fieldName: groupBy.fieldName,+ numGroups: groupBy.numGroups ?? DEFAULT_PLOT_NUM_GROUPS,+ groupOthers: Boolean(groupBy.groupOthers),+ colors: groupBy.colorRange?.colors ?? null,+ colorMap: groupBy.colorRange?.colorMap ?? null+ };+}++function toGroupKey(value: unknown): string | null {+ if (value === null || value === undefined || value === '') {+ return null;+ }+ return String(value);+}++function mappedSeriesColor(colorRange: ColorRange | undefined, key: string): string | null {+ const colorMap = colorRange?.colorMap;+ if (!Array.isArray(colorMap)) {+ return null;+ }+ for (const entry of colorMap) {+ const domain = entry?.[0];+ const color = entry?.[1];+ if (!color) {+ continue;+ }+ if (Array.isArray(domain)) {+ if (domain.map(item => String(item)).includes(key)) {+ return color;+ }+ } else if (domain !== null && domain !== undefined && String(domain) === key) {+ return color;+ }+ }+ return null;+}++function seriesColor(colorRange: ColorRange | undefined, key: string, index: number): string {+ const mapped = mappedSeriesColor(colorRange, key);+ if (mapped) {+ return mapped;+ }+ const colors = colorRange?.colors;+ if (colors?.length) {+ return colors[index % colors.length];+ }+ return FALLBACK_SERIES_COLORS[index % FALLBACK_SERIES_COLORS.length];+}++const OTHERS_SERIES_COLOR = '#A0A7B4';++function defaultQualitativeColors(): string[] {+ const palette = KEPLER_COLOR_PALETTES.find(item => item.name === DEFAULT_PLOT_GROUP_PALETTE);+ if (palette?.type === 'qualitative') {+ return palette.colors(palette.maxStep);+ }+ return FALLBACK_SERIES_COLORS;+}++/** Others must not wrap onto a color already used by a kept group. */+function othersSeriesColor(colorRange: ColorRange | undefined, used: string[]): string {+ const mapped = mappedSeriesColor(colorRange, PLOT_GROUP_OTHERS_NAME);+ if (mapped) {+ return mapped;+ }+ const usedSet = new Set(used.map(color => color.toLowerCase()));+ const candidates = [+ ...(colorRange?.colors ?? []),+ ...defaultQualitativeColors(),+ ...FALLBACK_SERIES_COLORS,+ OTHERS_SERIES_COLOR+ ];+ return candidates.find(color => !usedSet.has(color.toLowerCase())) ?? OTHERS_SERIES_COLOR;+}++function groupValueAccessor(dataset, fieldName: string): ((index: number) => unknown) | null {+ const field = dataset?.fields?.find(item => item.name === fieldName);+ if (!field?.valueAccessor) {+ return null;+ }+ return index => field.valueAccessor({index});+}++function groupLimit(numGroups: number | typeof PLOT_NUM_GROUPS_ALL): number {+ if (numGroups === PLOT_NUM_GROUPS_ALL) {+ return MAX_PLOT_NUM_GROUPS;+ }+ if (typeof numGroups !== 'number' || !(numGroups > 0)) {+ return DEFAULT_PLOT_NUM_GROUPS;+ }+ return Math.min(numGroups, MAX_PLOT_NUM_GROUPS);+}++/**+ * Split time bins into one line per group-by value.+ * Groups keep first-seen order, then the list is capped at numGroups.+ * Remaining values fold into an Others series when groupOthers is set.+ */+function buildGroupedLineSeries({+ bins,+ dataset,+ plotType,+ getYValue,+ interval+}: {+ bins: Bin[];+ dataset: Datasets[string];+ plotType: Filter['plotType'];+ getYValue: (bin: Bin) => number;+ interval: PlotType['interval'];+}): {series: LineChartSeries; points: LineDatum[]} | null {+ const cache = groupByCacheValue(plotType);+ if (!cache) {+ return null;+ }+ const getGroup = groupValueAccessor(dataset, cache.fieldName);+ if (!getGroup) {+ return null;+ }++ const order: string[] = [];+ const seen = new Set<string>();+ for (const bin of bins) {+ for (const idx of bin.indexes || []) {+ const key = toGroupKey(getGroup(idx));+ if (key === null || seen.has(key)) {+ continue;+ }+ seen.add(key);+ order.push(key);+ }+ }+ if (!order.length) {+ return null;+ }++ const limit = groupLimit(cache.numGroups);+ const keep = order.slice(0, limit);+ const rest = order.slice(keep.length);+ const includeOthers = Boolean(cache.groupOthers) && rest.length > 0;+ const colorRange = (plotType?.groupBy as PlotGroupBy | undefined)?.colorRange;+ const groups = keep.map((key, index) => ({+ name: key,+ keys: new Set([key]),+ color: seriesColor(colorRange, key, index)+ }));+ if (includeOthers) {+ groups.push({+ name: PLOT_GROUP_OTHERS_NAME,+ keys: new Set(rest),+ color: othersSeriesColor(+ colorRange,+ groups.map(group => group.color)+ )+ });+ }++ const keyToGroup = new Map<string, number>();+ groups.forEach((group, index) => {+ group.keys.forEach(key => keyToGroup.set(key, index));+ });++ const lines: LineDatum[][] = [];+ const colors: string[] = [];+ const names: string[] = [];+ const points: LineDatum[] = [];++ groups.forEach((group, groupIndex) => {+ const seriesPoints: LineDatum[] = [];+ bins.forEach(bin => {+ const indexes: number[] = [];+ for (const idx of bin.indexes || []) {+ const key = toGroupKey(getGroup(idx));+ if (key !== null && keyToGroup.get(key) === groupIndex) {+ indexes.push(idx);+ }+ }+ const y = indexes.length ? getYValue({...bin, indexes, count: indexes.length}) : undefined;+ const delta = getDelta(seriesPoints, y, interval);+ const point = {+ x: bin.x0,+ y,+ ...delta+ } as LineDatum;+ seriesPoints.push(point);+ points.push(point);+ });++ const split = splitSeries(seriesPoints);+ split.lines.forEach(line => {+ lines.push(line);+ colors.push(group.color);+ names.push(group.name);+ });+ });++ return {+ series: {lines, markers: [], colors, names},+ points+ };+}++export function lineChartSeriesLegend(+ lineChart?: LineChart | null+): {name: string; color: string}[] {+ const series = lineChart?.series;+ if (!series || Array.isArray(series) || !series.names || !series.colors) {+ return [];+ }+ const seen = new Map<string, string>();+ series.names.forEach((name, index) => {+ if (name && !seen.has(name)) {+ seen.set(name, series.colors?.[index] || FALLBACK_SERIES_COLORS[0]);+ }+ });+ return Array.from(seen, ([name, color]) => ({name, color}));+}+/**** @param datasets@@ -547,12 +882,14 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {const {aggregation, interval} = plotType;const seriesDataId = dataId[0];const bins = (filter as TimeRangeFilter).timeBins?.[seriesDataId]?.[interval];+ const groupBy = groupByCacheValue(plotType);if (lineChart &&lineChart.aggregation === aggregation &&lineChart.interval === interval &&lineChart.yAxis === yAxis?.name &&+ isEqual(lineChart.groupBy ?? null, groupBy) &&// we need to make sure we validate bins because of cross filter data changesisEqual(bins, lineChart?.bins)) {@@ -562,24 +899,30 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {const dataset = datasets[seriesDataId];const getYValue = getValueAggrFunc(yAxis, aggregation, dataset);+ const grouped =+ groupBy && bins?.length+ ? buildGroupedLineSeries({bins, dataset, plotType, getYValue, interval})+ : null;const init: LineDatum[] = [];- const series = (bins || []).reduce((accu, bin) => {- const y = getYValue(bin);- const delta = getDelta(accu, y, interval);- accu.push({- x: bin.x0,- y,- ...delta- });- return accu;- }, init);+ const series = grouped+ ? grouped.points+ : (bins || []).reduce((accu, bin) => {+ const y = getYValue(bin);+ const delta = getDelta(accu, y, interval);+ accu.push({+ x: bin.x0,+ y,+ ...delta+ });+ return accu;+ }, init);const yDomain = extent<{y: any}>(series, d => d.y);const xDomain = bins ? [bins[0].x0, bins[bins.length - 1].x1] : [];// treat missing data as another series- const split = splitSeries(series);+ const split = grouped ? grouped.series : splitSeries(series);const aggrName = AGGREGATION_NAME[aggregation];return {@@ -599,7 +942,8 @@ export function getLineChart(datasets: Datasets, filter: Filter): LineChart {value: aggregate(series, AGGREGATION_TYPES.average, d => d.y)},// @ts-expect-error bins is Bins[], not a Bins map. Refactor to use correct types.- bins+ bins,+ ...(groupBy ? {groupBy} : {})};}diff --git a/test/browser/components/filters/time-widget-test.js b/test/browser/components/filters/time-widget-test.jsindex 5e3de1b14..1fd6e95f0 100644--- a/test/browser/components/filters/time-widget-test.js+++ b/test/browser/components/filters/time-widget-test.js@@ -616,3 +616,59 @@ test('Components -> TimeWidget.mount -> keyboard panning calls setFilterAnimatioclientSizeStub.restore();t.end();});++test('Components -> TimeWidget.mount -> group by field', t => {+ const setFilterPlot = sinon.spy();+ const filter = {+ ...defaultProps.filter,+ yAxis: {name: 'uid', type: 'integer'},+ plotType: {+ ...(defaultProps.filter.plotType || {}),+ type: 'lineChart',+ aggregation: 'average'+ }+ };++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <TimeWidget {...defaultProps} filter={filter} setFilterPlot={setFilterPlot} />+ </IntlWrapper>,+ {attachTo: document.body}+ );+ }, 'mount TimeWidget should not fail');++ wrapper.find(Icons.Gear).at(0).simulate('click');+ wrapper.update();++ t.ok(wrapper.find('.time-widget__group-by').length > 0, 'should render group by settings');++ const selectors = wrapper.find(FieldSelector);+ let groupBySelector = null;+ for (let i = 0; i < selectors.length; i++) {+ if (selectors.at(i).props().id === 'time-widget-group-by-field') {+ groupBySelector = selectors.at(i);+ }+ }+ t.ok(groupBySelector, 'should render a group by field selector');++ const field = groupBySelector.props().fields[0];+ t.ok(field && field.name, 'group by fields include dataset columns');+ groupBySelector.props().onSelect(field);+ t.equal(+ setFilterPlot.lastCall.args[1].plotType.groupBy.fieldName,+ field.name,+ 'should set the group by field'+ );++ groupBySelector.props().onSelect(null);+ t.equal(+ setFilterPlot.lastCall.args[1].plotType.groupBy,+ null,+ 'should clear group by when the field is removed'+ );++ wrapper.detach();+ t.end();+});diff --git a/test/node/utils/plot-test.js b/test/node/utils/plot-test.jsindex d28df8fc0..d59f12c43 100644--- a/test/node/utils/plot-test.js+++ b/test/node/utils/plot-test.js@@ -7,7 +7,13 @@ import {histogramFromValues,histogramFromTimeIntervals,mergePolygonLayerIndexes,- runGpuFilterForPlot+ runGpuFilterForPlot,+ getLineChart,+ mergePlotGroupBy,+ lineChartSeriesLegend,+ PLOT_GROUP_OTHERS_NAME,+ PLOT_NUM_GROUPS_ALL,+ MAX_PLOT_NUM_GROUPS} from '@kepler.gl/utils';const values1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];@@ -311,3 +317,220 @@ test('Utils -> histogramFromTimeIntervals', t => {t.end();});++const groupedRows = [+ {v: 10, g: 'a'},+ {v: 30, g: 'b'},+ {v: 20, g: 'a'},+ {v: 5, g: 'c'},+ {v: 7, g: null}+];++function groupedDataset() {+ return {+ fields: [+ {name: 'v', type: 'integer', valueAccessor: ({index}) => groupedRows[index].v},+ {name: 'g', type: 'string', valueAccessor: ({index}) => groupedRows[index].g}+ ]+ };+}++const groupedBins = [+ {count: 3, indexes: [0, 1, 4], x0: 0, x1: 1},+ {count: 1, indexes: [2], x0: 1, x1: 2},+ {count: 1, indexes: [3], x0: 2, x1: 3}+];++function groupedFilter(groupBy) {+ return {+ dataId: ['ds'],+ yAxis: {name: 'v', type: 'integer'},+ plotType: {+ aggregation: 'sum',+ interval: '1-day',+ type: 'lineChart',+ groupBy+ },+ timeBins: {ds: {'1-day': groupedBins}}+ };+}++function seriesSummary(lineChart) {+ return {+ names: lineChart.series.names,+ colors: lineChart.series.colors,+ ys: lineChart.series.lines.map(line => line.map(point => point.y))+ };+}++test('Utils -> getLineChart groupBy splits series and folds the rest into Others', t => {+ const datasets = {ds: groupedDataset()};+ const colors = ['#111111', '#222222', '#333333'];+ const filter = groupedFilter({+ fieldName: 'g',+ numGroups: 2,+ groupOthers: true,+ colorRange: {colors}+ });++ const ungrouped = getLineChart(datasets, groupedFilter(null));+ t.deepEqual(+ seriesSummary(ungrouped).ys,+ [[47, 20, 5]],+ 'should keep a single series when groupBy is cleared'+ );++ const grouped = getLineChart(datasets, filter);+ t.deepEqual(+ seriesSummary(grouped),+ {+ names: ['a', 'b', PLOT_GROUP_OTHERS_NAME],+ colors,+ ys: [[10, 20], [30], [5]]+ },+ 'should keep the first groups and aggregate the rest as Others'+ );+ t.deepEqual(+ lineChartSeriesLegend(grouped),+ [+ {name: 'a', color: '#111111'},+ {name: 'b', color: '#222222'},+ {name: PLOT_GROUP_OTHERS_NAME, color: '#333333'}+ ],+ 'should expose one legend entry per series'+ );++ const capped = getLineChart(datasets, {+ ...filter,+ plotType: {+ ...filter.plotType,+ groupBy: {...filter.plotType.groupBy, groupOthers: false}+ }+ });+ t.deepEqual(+ seriesSummary(capped).names,+ ['a', 'b'],+ 'should drop groups past numGroups when groupOthers is off'+ );++ const collided = getLineChart(+ datasets,+ groupedFilter({+ fieldName: 'g',+ numGroups: 2,+ groupOthers: true,+ colorRange: {colors: ['#111111', '#222222']}+ })+ );+ const collidedColors = seriesSummary(collided).colors;+ t.deepEqual(+ collidedColors.slice(0, 2),+ ['#111111', '#222222'],+ 'should keep the colors of the groups that fit'+ );+ t.ok(+ !collidedColors.slice(0, 2).includes(collidedColors[2]),+ 'should give Others a color that is not already used'+ );++ const mapped = getLineChart(+ datasets,+ groupedFilter({+ fieldName: 'g',+ numGroups: 2,+ groupOthers: true,+ colorRange: {+ colors: ['#111111', '#222222'],+ colorMap: [[PLOT_GROUP_OTHERS_NAME, '#abcdef']]+ }+ })+ );+ t.equal(+ seriesSummary(mapped).colors[2],+ '#abcdef',+ 'should keep an explicit Others color from the color map'+ );++ const cached = getLineChart(datasets, {...filter, lineChart: grouped});+ t.equal(cached, grouped, 'should reuse the line chart when groupBy and bins are unchanged');++ const narrowed = getLineChart(datasets, {+ ...filter,+ lineChart: grouped,+ plotType: {+ ...filter.plotType,+ groupBy: {...filter.plotType.groupBy, numGroups: 1, groupOthers: false}+ }+ });+ t.deepEqual(seriesSummary(narrowed).names, ['a'], 'should recompute when numGroups changes');++ t.end();+});++test('Utils -> getLineChart groupBy caps All at the palette size', t => {+ const rowCount = MAX_PLOT_NUM_GROUPS + 5;+ const rows = Array.from({length: rowCount}, (_, index) => ({v: 1, g: `g${index}`}));+ const datasets = {+ ds: {+ fields: [+ {name: 'v', type: 'integer', valueAccessor: ({index}) => rows[index].v},+ {name: 'g', type: 'string', valueAccessor: ({index}) => rows[index].g}+ ]+ }+ };+ const filter = {+ dataId: ['ds'],+ yAxis: {name: 'v', type: 'integer'},+ plotType: {+ aggregation: 'sum',+ interval: '1-day',+ type: 'lineChart',+ groupBy: {+ fieldName: 'g',+ numGroups: PLOT_NUM_GROUPS_ALL,+ groupOthers: true,+ colorRange: {colors: ['#111111']}+ }+ },+ timeBins: {+ ds: {+ '1-day': [{count: rowCount, indexes: rows.map((_, index) => index), x0: 0, x1: 1}]+ }+ }+ };++ const chart = getLineChart(datasets, filter);+ const names = seriesSummary(chart).names;+ t.equal(names.length, MAX_PLOT_NUM_GROUPS + 1, 'should keep the cap plus Others');+ t.equal(names[names.length - 1], PLOT_GROUP_OTHERS_NAME, 'should fold the rest into Others');+ t.deepEqual(+ names.slice(0, MAX_PLOT_NUM_GROUPS),+ rows.slice(0, MAX_PLOT_NUM_GROUPS).map(row => row.g),+ 'should keep the first groups in first-seen order'+ );++ t.end();+});++test('Utils -> mergePlotGroupBy fills defaults and clears', t => {+ const created = mergePlotGroupBy(null, {fieldName: 'city'});+ t.equal(created.fieldName, 'city', 'should keep the selected field');+ t.equal(created.numGroups, 10, 'should default max groups to 10');+ t.equal(created.groupOthers, false, 'should default group others off');+ t.ok(created.colorRange.colors.length >= 2, 'should assign a qualitative color range');+ t.equal(+ created.colorUI.colorRangeConfig.type,+ 'qualitative',+ 'should use a qualitative color UI'+ );++ const updated = mergePlotGroupBy(created, {numGroups: 3, groupOthers: true});+ t.equal(updated.fieldName, 'city', 'should keep the field when only the cap changes');+ t.equal(updated.numGroups, 3, 'should apply the new cap');+ t.equal(updated.groupOthers, true, 'should apply group others');+ t.equal(updated.colorRange, created.colorRange, 'should keep the existing series colors');++ t.equal(mergePlotGroupBy(updated, null), null, 'should clear groupBy');++ t.end();+});