Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[feat] color scale histogram (#2851)
Igor Dykhtaf9c52e538a31
diff --git a/src/components/src/common/column-stats-chart.tsx b/src/components/src/common/column-stats-chart.tsxnew file mode 100644index 000000000..a80463fe5--- /dev/null+++ b/src/components/src/common/column-stats-chart.tsx@@ -0,0 +1,453 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {format as d3Format} from 'd3-format';+import {scaleLinear} from 'd3-scale';+import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';+import styled from 'styled-components';++import {KeplerTable} from '@kepler.gl/table';+import {Field} from '@kepler.gl/types';+import {+ ColorBreak,+ ColorBreakOrdinal,+ histogramFromThreshold,+ histogramFromValues,+ isNumber,+ isNumericColorBreaks,+ useDimensions+} from '@kepler.gl/utils';++import ColorPalette from '../side-panel/layer-panel/color-palette';+import HistogramPlotFactory, {HISTOGRAM_MASK_MODE} from './histogram-plot';+import LoadingSpinner from './loading-spinner';++export const HISTOGRAM_WIDTH = 210;+export const HISTOGRAM_HEIGHT = 80;+const HISTOGRAM_MARGIN = {top: 10, bottom: 8, left: 10, right: 20};+const COLOR_CHART_TICK_WRAPPER_HEIGHT = 10;+const COLOR_CHART_TICK_HEIGHT = 8;+const COLOR_CHART_TICK_WIDTH = 4;+const COLOR_CHART_TICK_BORDER_COLOR = '#999999';+const HISTOGRAM_BINS = 30;++const StyledContainer = styled.div.attrs({+ className: 'color-chart-loading'+})`+ height: ${HISTOGRAM_HEIGHT}px;+`;++// height 142 = 18 + 110 + 10+const ColorChartContainer = styled.div.attrs({+ className: 'color-chart-container'+})`+ margin-top: 8px;+`;++const ColorChartHeaderWrapper = styled.div.attrs({+ className: 'color-chart-header'+})`+ display: flex;+ justify-content: space-around;+ color: ${props => props.theme.textColor};+ margin-left: ${HISTOGRAM_MARGIN.left}px;+ margin-right: ${HISTOGRAM_MARGIN.right}px;+ font-size: 9px;+`;++const ColorChartHeaderItem = styled.div`+ width: 33%;+ overflow: hidden;+ white-space: nowrap;+`;++const ColorChartWrapper = styled.div.attrs({+ className: 'color-chart-wrapper'+})`+ position: relative;+ height: ${HISTOGRAM_HEIGHT + 30}px;+`;++const ColorPaletteWrapper = styled.div.attrs({+ className: 'color-chart-palette'+})`+ position: absolute;+ margin-top: ${HISTOGRAM_MARGIN.top}px;+ margin-left: ${HISTOGRAM_MARGIN.left}px;+ margin-right: ${HISTOGRAM_MARGIN.right}px;+`;++const HistogramWrapper = styled.div.attrs({+ className: 'color-chart-histogram'+})`+ position: absolute;+`;++const ColorChartTickContainer = styled.div.attrs({+ className: 'color-chart-tick-container'+})`+ height: ${COLOR_CHART_TICK_WRAPPER_HEIGHT}px;+ position: relative;+ margin-left: ${HISTOGRAM_MARGIN.left}px;+ margin-right: ${HISTOGRAM_MARGIN.right}px;+`;++export const ColorChartHeader = ({minVal, meanVal, maxVal}) => {+ return (+ <ColorChartHeaderWrapper>+ <ColorChartHeaderItem title={minVal}>MIN: {minVal}</ColorChartHeaderItem>+ <ColorChartHeaderItem title={meanVal}>MEAN: {d3Format('.4~r')(meanVal)}</ColorChartHeaderItem>+ <ColorChartHeaderItem title={maxVal} style={{textAlign: 'right'}}>+ MAX: {maxVal}+ </ColorChartHeaderItem>+ </ColorChartHeaderWrapper>+ );+};++export type ColorChartTickProps = {+ colors: string[];+ positions: number[];+ onTickMoving: (positions: number[], dragTick: number) => void;+ onTickChanged: () => void;+ histogramWidth: number;+};++export const ColorChartTick: React.FC<ColorChartTickProps> = ({+ colors,+ positions,+ histogramWidth,+ onTickMoving,+ onTickChanged+}) => {+ const [statePositions, setPositions] = useState(positions);+ const [dragTick, setDragTick] = useState(-1);+ const containerRef = useRef<HTMLDivElement>(null);++ useEffect(() => {+ setPositions(positions);+ setDragTick(dragTick);+ }, [positions, dragTick]);++ const onMouseMove = useCallback(+ e => {+ if (dragTick >= 0) {+ // @ts-ignore+ const offsetX = containerRef.current.getBoundingClientRect().x;+ statePositions[dragTick] = e.clientX - (offsetX ?? 0);+ const leftBound = dragTick === 0 ? 0 : statePositions[dragTick - 1] + 1;+ const rightBound =+ dragTick === positions.length - 1 ? histogramWidth : statePositions[dragTick + 1] - 1;++ // restrict user drag-n-move between left and right neighboring ticks+ if (statePositions[dragTick] < leftBound) {+ statePositions[dragTick] = leftBound;+ }+ if (statePositions[dragTick] > rightBound) {+ statePositions[dragTick] = rightBound;+ }+ setPositions([...statePositions]);+ onTickMoving(statePositions, dragTick);+ }+ },+ [dragTick, onTickMoving, positions.length, statePositions, histogramWidth]+ );++ const onMouseUp = useCallback(+ e => {+ if (dragTick >= 0) {+ onTickChanged();+ setDragTick(-1);+ e.stopPropagation();+ e.preventDefault();+ }+ },+ [dragTick, onTickChanged]+ );++ const onMouseDown = useCallback((e, tickIndex) => {+ if (isNumber(tickIndex)) {+ setDragTick(tickIndex);+ e.stopPropagation();+ e.preventDefault();+ }+ }, []);++ return (+ <ColorChartTickContainer+ ref={containerRef}+ onMouseMove={onMouseMove}+ onMouseUp={onMouseUp}+ onMouseLeave={onMouseUp}+ >+ {colors.map((color, index) => (+ <div+ draggable={true}+ key={`color-chart-tick-${color}-${index}`}+ onMouseDown={e => onMouseDown(e, index)}+ style={{+ backgroundColor: color,+ left: `${statePositions[index] - COLOR_CHART_TICK_WIDTH / 2 - 1}px`,+ borderWidth: `1px`,+ borderStyle: 'solid',+ borderColor: COLOR_CHART_TICK_BORDER_COLOR,+ position: 'absolute',+ width: `${COLOR_CHART_TICK_WIDTH}px`,+ height: `${COLOR_CHART_TICK_HEIGHT}px`,+ cursor: 'pointer'+ }}+ />+ ))}+ </ColorChartTickContainer>+ );+};++// only for numetic field+ColumnStatsChartFactory.deps = [HistogramPlotFactory];++export type ColumnStatsChartWLoadingProps = {+ colorField: Field;+ dataset: KeplerTable;+ colorBreaks: ColorBreak[] | ColorBreakOrdinal[] | null;+ onChangedUpdater: (ticks: ColorBreak[]) => void;+};++export type ColumnStatsChartProps = {+ field: Field;+ dataset: KeplerTable;+ colorBreaks: ColorBreak[];+ onChangedUpdater: (ticks: ColorBreak[]) => void;+};+function ColumnStatsChartFactory(+ HistogramPlot: ReturnType<typeof HistogramPlotFactory>+): React.FC<ColumnStatsChartWLoadingProps> {+ const ColumnStatsChart: React.FC<ColumnStatsChartProps> = ({+ field,+ dataset,+ colorBreaks,+ onChangedUpdater+ }) => {+ const [ticks, setTicks] = useState(colorBreaks);+ const [ref, size] = useDimensions<HTMLDivElement>();+ const histogramWidth = size+ ? size.width - HISTOGRAM_MARGIN.left - HISTOGRAM_MARGIN.right+ : HISTOGRAM_WIDTH;++ // distinguish between props.colorBreaks and states.ticks+ const isTickChangingRef = React.useRef(false);++ useEffect(() => {+ setTicks(ticks);+ // reset isTickChanging once histogram domain is recomputed+ isTickChangingRef.current = false;+ }, [ticks]);++ const valueAccessor = useMemo(() => {+ return idx => dataset.getValue(field.name, idx);+ }, [dataset, field.name]);++ const columnStats = field.filterProps?.columnStats;++ // get bins with allIndexes+ const allBins = useMemo(() => {+ if (columnStats?.bins) {+ return columnStats?.bins;+ }+ return histogramFromValues(dataset.allIndexes, HISTOGRAM_BINS, valueAccessor);+ }, [columnStats, dataset.allIndexes, valueAccessor]);++ const isFiltered = dataset.filteredIndexForDomain.length !== dataset.allIndexes.length;++ // get filteredBins+ const filteredBins = useMemo(() => {+ if (!isFiltered) {+ return allBins;+ }+ // get threholds+ const filterEmptyBins = false;+ const threholds = allBins.map(b => b.x0);+ return histogramFromThreshold(+ threholds,+ dataset.filteredIndexForDomain,+ valueAccessor,+ filterEmptyBins+ );+ }, [dataset, valueAccessor, allBins, isFiltered]);++ // histograms used by histogram-plot.js+ const histogramsByGroup = useMemo(+ () => ({+ bins: allBins,+ filteredBins+ }),+ [allBins, filteredBins]+ );++ // get domain (min, max) of histogram+ const histogramDomain = useMemo(() => {+ if (columnStats && columnStats.quantiles && columnStats.mean) {+ // no need to recalcuate min/max/mean if its already in columnStats+ return [+ columnStats.quantiles[0].value,+ columnStats.quantiles[columnStats.quantiles.length - 1].value,+ columnStats.mean+ ];+ }+ let domainMin = Number.POSITIVE_INFINITY;+ let domainMax = Number.NEGATIVE_INFINITY;+ let nValid = 0;+ let domainSum = 0;+ dataset.allIndexes.forEach((x, i) => {+ const val = valueAccessor(x);+ if (isNumber(val)) {+ if (val < domainMin) domainMin = val;+ if (val > domainMax) domainMax = val;+ domainSum += val;+ nValid += 1;+ }+ });+ const histogramMean = nValid > 0 ? domainSum / nValid : 0;++ return [domainMin, domainMax, histogramMean];+ }, [dataset, valueAccessor, columnStats]);++ // get colors from colorBreaks+ const domainColors = useMemo(+ () => (colorBreaks ? colorBreaks.map(c => c.data) : []),+ [colorBreaks]+ );++ const tickPositions = useMemo(() => {+ if (!isTickChangingRef.current) {+ setTicks(colorBreaks);+ }++ const [valueMin, valueMax] = histogramDomain;+ const widthScale = scaleLinear().domain([valueMin, valueMax]).range([0, histogramWidth]);+ return ticks.slice(0, -1).map(cb => {+ const pos = widthScale(cb.range[1]);+ if (pos < 0) return 0;+ else if (pos > histogramWidth) return histogramWidth;+ return pos;+ });+ }, [histogramDomain, ticks, colorBreaks, histogramWidth]);++ const domainColorWidths = useMemo(() => {+ const n = tickPositions.length;+ const widths = [tickPositions[0]];+ for (let i = 1; i < n; ++i) {+ widths.push(tickPositions[i] - tickPositions[i - 1]);+ }+ widths.push(histogramWidth - tickPositions[n - 1]);+ return widths;+ }, [tickPositions, histogramWidth]);++ // handle tick drag-n-move+ const onTickMovingHandler = useCallback(+ (newTickPositions, tickIndex) => {+ const [valueMin, valueMax] = histogramDomain;+ const valueRange = valueMax - valueMin;+ const breaks = [valueMin];+ newTickPositions.forEach(element => {+ breaks.push(valueMin + (valueRange * element) / histogramWidth);+ });+ breaks.push(valueMax);++ for (let i = 0; i < ticks.length; ++i) {+ const leftValue = i === tickIndex + 1 ? breaks[i] : ticks[i].range[0];+ const rightValue = i + 1 === tickIndex + 1 ? breaks[i + 1] : ticks[i].range[1];++ ticks[i] = {+ ...ticks[i],+ range: [leftValue, rightValue],+ inputs: [leftValue, rightValue],+ label: `${d3Format('.2f')(breaks[i])} to ${d3Format('.2f')(breaks[i + 1])}`+ };+ }+ isTickChangingRef.current = true;+ setTicks([...ticks]);+ },+ [histogramDomain, ticks, histogramWidth]+ );++ // update parent and sibling components when tick dragging ended+ const onTickChangedHandler = useCallback(() => {+ onChangedUpdater(ticks);+ }, [onChangedUpdater, ticks]);++ return (+ <ColorChartContainer ref={ref}>+ <ColorChartHeader+ minVal={histogramDomain[0]}+ maxVal={histogramDomain[1]}+ meanVal={histogramDomain[2]}+ />+ <ColorChartWrapper>+ <ColorPaletteWrapper>+ <ColorPalette+ colors={domainColors}+ colorWidths={domainColorWidths}+ height={HISTOGRAM_HEIGHT + 16}+ />+ </ColorPaletteWrapper>+ <HistogramWrapper>+ <HistogramPlot+ histogramsByGroup={histogramsByGroup}+ colorsByGroup={null}+ isMasked={isFiltered ? HISTOGRAM_MASK_MODE.MaskWithOverlay : HISTOGRAM_MASK_MODE.Mask}+ value={histogramDomain}+ width={histogramWidth}+ height={HISTOGRAM_HEIGHT}+ margin={HISTOGRAM_MARGIN}+ breakLines={tickPositions}+ />+ </HistogramWrapper>+ </ColorChartWrapper>+ <ColorChartTick+ colors={domainColors.slice(0, -1)}+ positions={tickPositions}+ histogramWidth={histogramWidth}+ onTickMoving={onTickMovingHandler}+ onTickChanged={onTickChangedHandler}+ />+ </ColorChartContainer>+ );+ };++ const ColumnStatsChartWLoading: React.FC<ColumnStatsChartWLoadingProps> = ({+ colorField,+ dataset,+ colorBreaks,+ onChangedUpdater+ }) => {+ const fieldName = colorField.name;+ const field = useMemo(() => dataset.getColumnField(fieldName), [dataset, fieldName]);++ const isLoading = field?.isLoadingStats;++ if (!isNumericColorBreaks(colorBreaks) || !field) {+ // TODO: implement display for ordinal breaks+ return null;+ }++ if (isLoading) {+ return (+ <StyledContainer>+ <LoadingSpinner />+ </StyledContainer>+ );+ }++ return (+ <ColumnStatsChart+ colorBreaks={colorBreaks}+ field={field}+ dataset={dataset}+ onChangedUpdater={onChangedUpdater}+ />+ );+ };++ return ColumnStatsChartWLoading;+}++export default ColumnStatsChartFactory;diff --git a/src/components/src/common/histogram-plot.tsx b/src/components/src/common/histogram-plot.tsxindex 5d4d85730..94093c625 100644--- a/src/components/src/common/histogram-plot.tsx+++ b/src/components/src/common/histogram-plot.tsx@@ -7,6 +7,17 @@ import {hcl} from 'd3-color';import {min, max} from 'd3-array';import styled from 'styled-components';+import {Bins} from '@kepler.gl/types';++// clipping mask constants+export const HISTOGRAM_MASK_MODE = {+ NoMask: 0,+ Mask: 1,+ MaskWithOverlay: 2+};+const HISTOGRAM_MASK_BGCOLOR = '#FFFFFF';+const HISTOGRAM_MASK_FGCOLOR = '#000000';+const histogramStyle = {highlightW: 0.7,unHighlightedW: 0.4@@ -16,13 +27,26 @@ const HistogramWrapper = styled.svg`overflow: visible;`;+const HistogramMaskRect = styled.rect`+ fill: ${props => props.theme.panelBackground};+`;++const HistogramBreakLine = styled.g`+ stroke: ${props => props.theme.histogramBreakLineColor};+ stroke-width: 1px;+ transform: translate(0, 0);+`;+type BarType = {inRange: boolean;+ isOverlay: boolean;};const BarUnmemoized = styled.rect<BarType>(- ({theme, inRange, color}) => `+ ({theme, inRange, isOverlay, color}) => `${- inRange+ isOverlay+ ? `fill: ${color ?? theme.histogramOverlayColor};`+ : inRange? `fill: ${color ?? theme.histogramFillInRange};`: `fill: ${color ? hcl(color).darker() : theme.histogramFillOutRange};`}@@ -31,17 +55,25 @@ const BarUnmemoized = styled.rect<BarType>(const Bar = React.memo(BarUnmemoized);Bar.displayName = 'Bar';+export type HistogramMaskModeType = {+ NoMask: number;+ Mask: number;+ MaskWithOverlay: number;+};+interface HistogramPlotProps {width: number;height: number;margin: {top: number; bottom: number; left: number; right: number};isRanged?: boolean;value: number[];+ isMasked?: number;brushComponent?: ReactElement;- histogramsByGroup: any;- colorsByGroup: any;- countProp: any;- range: any;+ histogramsByGroup: Bins;+ colorsByGroup?: null | {[dataId: string]: string};+ countProp?: string;+ range?: number[];+ breakLines?: number[];}function HistogramPlotFactory() {@@ -50,12 +82,14 @@ function HistogramPlotFactory() {height,histogramsByGroup,colorsByGroup,+ isMasked = HISTOGRAM_MASK_MODE.NoMask,countProp = 'count',margin,isRanged,range,value,- brushComponent+ brushComponent,+ breakLines}: HistogramPlotProps) => {const undefinedToZero = (x: number | undefined) => (x ? x : 0);const groupKeys = useMemo(@@ -69,8 +103,8 @@ function HistogramPlotFactory() {const domain = useMemo(() =>range ?? [- min(groupKeys, key => histogramsByGroup[key][0].x0),- max(groupKeys, key => histogramsByGroup[key][histogramsByGroup[key].length - 1].x1)+ min(groupKeys, key => histogramsByGroup[key][0].x0) ?? 0,+ max(groupKeys, key => histogramsByGroup[key][histogramsByGroup[key].length - 1].x1) ?? 0],[range, histogramsByGroup, groupKeys]);@@ -83,9 +117,7 @@ function HistogramPlotFactory() {.domain([0,Math.max(- Number(- max(groupKeys, key => max(histogramsByGroup[key], (d: number[]) => d[countProp]))- ),+ Number(max(groupKeys, key => max(histogramsByGroup[key], d => d[countProp]))),1)])@@ -108,17 +140,105 @@ function HistogramPlotFactory() {const xStep = maxGroup[stdBinIdx].x1 - maxGroup[stdBinIdx].x0;const maxBins = (domain[1] - domain[0]) / xStep;if (!maxBins) return 0;- return width / maxBins / groupKeys.length;- }, [histogramsByGroup, domain, groupKeys, width]);+ return width / maxBins / (isMasked ? 1 : groupKeys.length);+ }, [histogramsByGroup, domain, groupKeys, width, isMasked]);if (groupKeys.length === 0) {return null;}- return (- <HistogramWrapper width={width} height={height} style={{marginTop: `${margin.top}px`}}>++ const maskedHistogram = () => {+ return (+ <HistogramWrapper+ width={width}+ height={height}+ style={{margin: `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`}}+ >+ <defs>+ <mask id="histogram-mask">+ <rect+ x="0"+ y="0"+ width={width}+ height={height + margin.bottom}+ fill={HISTOGRAM_MASK_BGCOLOR}+ />+ <g key="filtered-bins" className="histogram-bars">+ {histogramsByGroup.filteredBins.map((bar, idx) => {+ const inRange = bar.x1 <= value[1] && bar.x0 >= value[0];+ const wRatio = inRange+ ? histogramStyle.highlightW+ : histogramStyle.unHighlightedW;+ return (+ <Bar+ inRange={inRange}+ color={HISTOGRAM_MASK_FGCOLOR}+ key={`mask-${idx}`}+ height={y(bar[countProp])}+ width={barWidth * wRatio}+ x={x(bar.x0) + (barWidth * (1 - wRatio)) / 2}+ y={height - y(bar[countProp])}+ />+ );+ })}+ </g>+ </mask>+ </defs>+ <g transform="translate(0,0)">+ <HistogramMaskRect+ x="0"+ y="0"+ width="100%"+ height={height + margin.bottom}+ mask="url(#histogram-mask)"+ />+ </g>+ {isMasked === HISTOGRAM_MASK_MODE.MaskWithOverlay && (+ <g key="bins" transform="translate(0,0)" className="overlay-histogram-bars">+ {histogramsByGroup.bins.map((bar, idx) => {+ const filterBar = histogramsByGroup.filteredBins[idx];+ const maskHeight = filterBar+ ? y(bar[countProp]) - y(filterBar[countProp])+ : y(bar[countProp]);+ const inRange = bar.x1 <= value[1] && bar.x0 >= value[0];+ const wRatio = inRange ? histogramStyle.highlightW : histogramStyle.unHighlightedW;+ return (+ <Bar+ inRange={inRange}+ isOverlay={true}+ key={`bar-${idx}`}+ height={maskHeight}+ width={barWidth * wRatio}+ x={x(bar.x0) + (barWidth * (1 - wRatio)) / 2}+ y={height - y(bar[countProp])}+ />+ );+ })}+ </g>+ )}+ <HistogramBreakLine>+ {(breakLines ?? []).map((pos, idx) => {+ return (+ <path key={`mask-line-${idx}`} strokeDasharray="4,4" d={`M${pos}, 0 l0 100`} />+ );+ })}+ </HistogramBreakLine>+ <g transform={`translate(${isRanged ? 0 : barWidth / 2}, 0)`}>{brushComponent}</g>+ </HistogramWrapper>+ );+ };++ return isMasked ? (+ maskedHistogram()+ ) : (+ <HistogramWrapper+ width={width}+ height={height}+ style={{margin: `${margin.top}px ${margin.right}px ${margin.bottom}px ${margin.left}px`}}+ >{groupKeys.map((key, i) => (<g key={key} className="histogram-bars">- {histogramsByGroup[key].map(bar => {+ {histogramsByGroup[key].map((bar, idx) => {const inRange =undefinedToZero(bar.x1) <= value[1] && undefinedToZero(bar.x0) >= value[0];const wRatio = inRange ? histogramStyle.highlightW : histogramStyle.unHighlightedW;@@ -129,7 +249,7 @@ function HistogramPlotFactory() {<BarinRange={inRange}color={colorsByGroup ? colorsByGroup[key] : undefined}- key={bar.x0}+ key={`bar-${idx}`}height={y(bar[countProp])}width={barWidth * wRatio}x={startX}diff --git a/src/components/src/common/item-selector/dropdown-list.tsx b/src/components/src/common/item-selector/dropdown-list.tsxindex b210b3bcc..3c06b8406 100644--- a/src/components/src/common/item-selector/dropdown-list.tsx+++ b/src/components/src/common/item-selector/dropdown-list.tsx@@ -63,6 +63,7 @@ interface DropdownListProps {listItemComponent?: ElementType;light?: boolean;fixedOptions?: any[];+ selectedItems?: any[]; // Passed through by Typeahead}interface DropdownListState {@@ -236,7 +237,10 @@ export default class DropdownList extends Component<DropdownListProps, DropdownLclassName={classNames(classList.listItem,{- hover: this.props.selectionIndex === i + valueOffset+ hover: this.props.selectionIndex === i + valueOffset,+ selected: (this.props.selectedItems || []).find(+ item => display(item) === display(value)+ )},this.props.customClasses?.listItem)}diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex b16862099..11671f538 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -89,6 +89,7 @@ export {default as LayerConfiguratorFactory,getLayerConfiguratorProps,getLayerDataset,+ getLayerFields,getVisConfiguratorProps} from './side-panel/layer-panel/layer-configurator';export {default as LayerPanelFactory} from './side-panel/layer-panel/layer-panel';@@ -145,7 +146,7 @@ export {default as MapStyleSelectorFactory} from './side-panel/map-style-panel/mexport {default as CoordinateInfoFactory} from './map/coordinate-info';export {default as LayerHoverInfoFactory} from './map/layer-hover-info';export {default as LayerSelectorPanelFactory} from './map/layer-selector-panel';-export {default as LazzyTippy} from './map/lazy-tippy';+export {default as LazyTippy} from './map/lazy-tippy';export {default as LocalePanelFactory} from './map/locale-panel';export {default as MapControlFactory} from './map/map-control';export {default as MapControlPanelFactory} from './map/map-control-panel';@@ -206,8 +207,15 @@ export {default as ResetControlFactory} from './common/animation-control/reset-cexport {default as SpeedControlFactory} from './common/animation-control/speed-control';export {default as WindowActionControlFactory} from './common/animation-control/window-action-control';-export {default as HistogramPlotFactory} from './common/histogram-plot';+export {default as HistogramPlotFactory, HISTOGRAM_MASK_MODE} from './common/histogram-plot';export {default as IconButton} from './common/icon-button';+export {+ default as ColumnStatsChartFactory,+ HISTOGRAM_WIDTH,+ HISTOGRAM_HEIGHT,+ ColorChartHeader,+ ColorChartTick+} from './common/column-stats-chart';export {default as ImagePreview} from './common/image-preview';export {default as LineChartFactory} from './common/line-chart';export {default as RangeBrushFactory} from './common/range-brush';diff --git a/src/components/src/map/lazy-tippy.tsx b/src/components/src/map/lazy-tippy.tsxindex 065992dfa..8dbb0f0a8 100644--- a/src/components/src/map/lazy-tippy.tsx+++ b/src/components/src/map/lazy-tippy.tsx@@ -4,6 +4,7 @@// @ts-nocheckimport React, {useState, forwardRef} from 'react';import Tippy from '@tippyjs/react/headless';+import type {TippyProps} from '@tippyjs/react';import {isTest} from '@kepler.gl/utils';const isTestEnv = isTest();@@ -13,7 +14,8 @@ const isTestEnv = isTest();* https://gist.github.com/atomiks/520f4b0c7b537202a23a3059d4eec908*/// eslint-disable-next-line react/display-name-const LazyTippy = forwardRef((props, ref) => {+const LazyTippy = forwardRef((props: TippyProps, ref) => {+ // Mount in test env for easier testingconst [mounted, setMounted] = useState(isTestEnv);const lazyPlugin = {diff --git a/src/components/src/map/map-legend-panel.tsx b/src/components/src/map/map-legend-panel.tsxindex a46b41525..7e20cfe3e 100644--- a/src/components/src/map/map-legend-panel.tsx+++ b/src/components/src/map/map-legend-panel.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project+import {createPortal} from 'react-dom';import React, {ComponentType, useCallback, useContext, useState} from 'react';import styled, {withTheme} from 'styled-components';@@ -9,7 +10,7 @@ import {MapControlButton} from '../common/styled-components';import MapControlTooltipFactory from './map-control-tooltip';import MapControlPanelFactory from './map-control-panel';import MapLegendFactory from './map-legend';-import {createPortal} from 'react-dom';+import {DIMENSIONS} from '@kepler.gl/constants';import {LayerVisConfig, MapControlMapLegend, MapControls, MapState} from '@kepler.gl/types';import {Layer} from '@kepler.gl/layers';diff --git a/src/components/src/side-panel/layer-panel/channel-by-value-selector.tsx b/src/components/src/side-panel/layer-panel/channel-by-value-selector.tsxindex d9855648d..58a9a4360 100644--- a/src/components/src/side-panel/layer-panel/channel-by-value-selector.tsx+++ b/src/components/src/side-panel/layer-panel/channel-by-value-selector.tsx@@ -5,7 +5,9 @@ import React from 'react';import {CHANNEL_SCALE_SUPPORTED_FIELDS} from '@kepler.gl/constants';import {Layer, VisualChannel} from '@kepler.gl/layers';+import {KeplerTable} from '@kepler.gl/table';import {ColorUI, Field, LayerVisConfig} from '@kepler.gl/types';+import DimensionScaleSelectorFactory from './dimension-scale-selector';import VisConfigByFieldSelectorFactory from './vis-config-by-field-selector';@@ -18,6 +20,7 @@ export type ChannelByValueSelectorProps = {newVisConfig?: Partial<LayerVisConfig>) => void;fields: Field[];+ dataset: KeplerTable | undefined;description?: string;setColorUI: (prop: string,@@ -43,6 +46,7 @@ export function ChannelByValueSelectorFactory(channel,onChange,fields,+ dataset,description,setColorUI,disabled@@ -72,6 +76,7 @@ export function ChannelByValueSelectorFactory(<DimensionScaleSelectorlayer={layer}channel={channel}+ dataset={dataset}label={`${property} scale`}setColorUI={setColorUI}onChange={onChange}diff --git a/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx b/src/components/src/side-panel/layer-panel/color-breaks-panel.tsxindex b4708e110..4b389fb01 100644--- a/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx+++ b/src/components/src/side-panel/layer-panel/color-breaks-panel.tsx@@ -1,12 +1,21 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import {Button, Edit} from '@kepler.gl/components';-import {ColorUI} from '@kepler.gl/types';-import {colorMapToColorBreaks, isNumericColorBreaks} from '@kepler.gl/utils';+import {SCALE_TYPES} from '@kepler.gl/constants';+import {KeplerTable} from '@kepler.gl/table';+import {ColorUI, Field} from '@kepler.gl/types';+import {+ ColorBreak,+ ColorBreakOrdinal,+ colorBreaksToColorMap,+ colorMapToColorBreaks,+ isNumericColorBreaks+} from '@kepler.gl/utils';import React, {useCallback, useMemo} from 'react';import styled from 'styled-components';-import {ColorBreak, ColorBreakOrdinal} from '@kepler.gl/utils';+import ColumnStatsChartFactory from '../../common/column-stats-chart';+import {Edit} from '../../common/icons';+import {Button} from '../../common/styled-components';import CustomPaletteFactory, {ColorPaletteItem,ColorSwatch,@@ -14,13 +23,20 @@ import CustomPaletteFactory, {SetColorUIFunc} from './custom-palette';-const StyledColorBreaksPanel = styled.div`+const StyledColorBreaksPanel = styled.div.attrs({+ className: 'styled-color-breaks-panel'+})`margin-bottom: 10px;`;-const StyledColorBreaksDisplay = styled.div`++const StyledColorBreaksDisplay = styled.div.attrs({+ className: 'styled-color-breaks-display'+})`padding: 8px 12px 0 12px;`;+const ColorBreaksPanelWrapper = styled.div``;+export const EditButton = ({onClickEdit}) => (<Button className="editp__button" link onClick={onClickEdit}><Edit height="16px" />@@ -64,22 +80,29 @@ export const ColorBreaksDisplay: React.FC<ColorBreaksDisplayProps> = ({currentBrexport type ColorBreaksPanelProps = {colorBreaks: ColorBreak[] | ColorBreakOrdinal[] | null;colorUIConfig: ColorUI;+ dataset: KeplerTable | undefined;+ colorField: Field;isCustomBreaks: boolean;setColorUI: SetColorUIFunc;+ onScaleChange: (v: string, visConfg?: Record<string, any>) => void;onApply: (e: React.MouseEvent) => void;onCancel: () => void;};-ColorBreaksPanelFactory.deps = [CustomPaletteFactory];+ColorBreaksPanelFactory.deps = [CustomPaletteFactory, ColumnStatsChartFactory];function ColorBreaksPanelFactory(- CustomPalette: ReturnType<typeof CustomPaletteFactory>+ CustomPalette: ReturnType<typeof CustomPaletteFactory>,+ ColumnStatsChart: ReturnType<typeof ColumnStatsChartFactory>): React.FC<ColorBreaksPanelProps> {const ColorBreaksPanel: React.FC<ColorBreaksPanelProps> = ({colorBreaks,colorUIConfig,+ dataset,+ colorField,isCustomBreaks,setColorUI,+ onScaleChange,onApply,onCancel}) => {@@ -109,23 +132,61 @@ function ColorBreaksPanelFactory(onCancel();}, [setColorUI, onCancel]);+ const onColumnStatsChartChanged = useCallback(+ newColorBreaks => {+ const newColors = newColorBreaks.map(cb => cb.data);+ const newColorMap = colorBreaksToColorMap(newColorBreaks);++ const newCustomPalette = {+ ...customPalette,+ colorMap: newColorMap,+ colors: newColors+ };++ if (!isEditingCustomBreaks) {+ // set scale to custom and enable custom pallette editing+ setColorUI({+ colorRangeConfig: {+ customBreaks: true+ },+ customPalette: newCustomPalette+ });++ onScaleChange(SCALE_TYPES.custom, newCustomPalette);+ } else {+ setColorUI({customPalette: newCustomPalette});+ }+ },+ [setColorUI, customPalette, isEditingCustomBreaks, onScaleChange]+ );+return (- <StyledColorBreaksPanel>- {isEditingCustomBreaks ? (- <CustomPalette- customPalette={customPalette}- showSketcher={showSketcher}- onApply={onApply}- setColorPaletteUI={setColorUI}- onCancel={onCilckCancel}- />- ) : currentBreaks ? (- <ColorBreaksDisplay- currentBreaks={currentBreaks}- onEdit={isCustomBreaks ? onClickEditCustomBreaks : null}+ <ColorBreaksPanelWrapper>+ {dataset ? (+ <ColumnStatsChart+ colorField={colorField}+ dataset={dataset}+ colorBreaks={currentBreaks}+ onChangedUpdater={onColumnStatsChartChanged}/>) : null}- </StyledColorBreaksPanel>+ <StyledColorBreaksPanel>+ {isEditingCustomBreaks ? (+ <CustomPalette+ customPalette={customPalette}+ setColorPaletteUI={setColorUI}+ showSketcher={showSketcher}+ onApply={onApply}+ onCancel={onCilckCancel}+ />+ ) : currentBreaks ? (+ <ColorBreaksDisplay+ currentBreaks={currentBreaks}+ onEdit={isCustomBreaks ? onClickEditCustomBreaks : null}+ />+ ) : null}+ </StyledColorBreaksPanel>+ </ColorBreaksPanelWrapper>);};diff --git a/src/components/src/side-panel/layer-panel/color-palette.tsx b/src/components/src/side-panel/layer-panel/color-palette.tsxindex 2b0251602..e5254c616 100644--- a/src/components/src/side-panel/layer-panel/color-palette.tsx+++ b/src/components/src/side-panel/layer-panel/color-palette.tsx@@ -8,6 +8,7 @@ import classnames from 'classnames';type ColorPaletteProps = {colors: RGBColor | HexColor[];+ colorWidths?: number[];height?: number;className?: string;isSelected?: boolean;@@ -27,13 +28,13 @@ const PaletteWrapper = styled.div.attrs({const PaletteContainer = styled.div.attrs(props => ({className: classnames('color-range-palette', props.className)-}))<{isSelected?: boolean}>`+}))<{isSelected?: boolean; isColorChart?: boolean}>`display: flex;flex-grow: 1;- border-width: 1px;+ border-width: ${props => (props.isColorChart ? '0px' : '1px')};border-style: solid;border-color: ${props => (props.isSelected ? '#FFFFFF' : 'transparent')};- padding: 4px;+ padding: ${props => (props.isColorChart ? '0px' : '4px')};border-radius: 4px;`;@@ -46,15 +47,27 @@ const StyledColorBlock = styled.div.attrs({const ColorPalette: React.FC<ColorPaletteProps> = ({colors = [],height = 10,+ colorWidths = null,className = '',isSelected = false,isReversed = false}) => (- <PaletteContainer className={className} isSelected={isSelected}>+ <PaletteContainer+ className={className}+ isSelected={isSelected}+ isColorChart={Boolean(colorWidths)}+ ><PaletteWrapper style={{height, transform: `scale(${isReversed ? -1 : 1}, 1)`}}>- {colors.map((color: number | string, index: number) => (- <StyledColorBlock key={`${color}-${index}`} style={{backgroundColor: String(color)}} />- ))}+ {colors.map((color: number | string, index: number) =>+ colorWidths ? (+ <StyledColorBlock+ key={`${color}-${index}`}+ style={{backgroundColor: String(color), width: colorWidths[index]}}+ />+ ) : (+ <StyledColorBlock key={`${color}-${index}`} style={{backgroundColor: String(color)}} />+ )+ )}</PaletteWrapper></PaletteContainer>);diff --git a/src/components/src/side-panel/layer-panel/color-scale-selector.tsx b/src/components/src/side-panel/layer-panel/color-scale-selector.tsxindex 48187384f..215eb7d62 100644--- a/src/components/src/side-panel/layer-panel/color-scale-selector.tsx+++ b/src/components/src/side-panel/layer-panel/color-scale-selector.tsx@@ -1,11 +1,10 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import Tippy from '@tippyjs/react/headless';import React, {useCallback, useMemo, useState} from 'react';import styled from 'styled-components';-import {Accessor, DropdownList, Typeahead} from '@kepler.gl/components';+import {Accessor, DropdownList, LazyTippy, Typeahead} from '@kepler.gl/components';import {ColorRange, SCALE_TYPES} from '@kepler.gl/constants';import {Layer, VisualChannelDomain} from '@kepler.gl/layers';import {ColorUI, Field} from '@kepler.gl/types';@@ -13,6 +12,8 @@ import {getLayerColorScale, getLegendOfScale, hasColorMap} from '@kepler.gl/utilimport ColorBreaksPanelFactory, {ColorBreaksPanelProps} from './color-breaks-panel';import {SetColorUIFunc} from './custom-palette';import DropdownSelect from '../../common/item-selector/dropdown-select';+import {KeplerTable} from '@kepler.gl/table';+import type {Instance as TippyInstance} from 'tippy.js';export type ScaleOption = {label: string;@@ -25,6 +26,7 @@ export type ContextProps = ColorBreaksPanelProps;export type ColorScaleSelectorProps = {layer: Layer;field: Field;+ dataset: KeplerTable;scaleType: string;domain: VisualChannelDomain;range: ColorRange;@@ -110,6 +112,7 @@ function ColorScaleSelectorFactory(const ColorScaleSelector: React.FC<ColorScaleSelectorProps> = ({layer,field,+ dataset,onSelect,scaleType,domain,@@ -123,7 +126,7 @@ function ColorScaleSelectorFactory(() => Accessor.generateOptionToStringFor(dropdownSelectProps.getOptionValue),[dropdownSelectProps.getOptionValue]);- const [tippyInstance, setTippyInstance] = useState();+ const [tippyInstance, setTippyInstance] = useState<TippyInstance>();const isEditingColorBreaks = colorUIConfig?.colorRangeConfig?.customBreaks;const colorScale = useMemo(() =>@@ -144,14 +147,16 @@ function ColorScaleSelectorFactory(const onSelectScale = useCallback(val => {+ // highlight selected optionif (getOptionValue(val) === SCALE_TYPES.custom) {- // trigger ui update only, when setting scale to custom+ // update custom breakssetColorUI({showColorChart: true,colorRangeConfig: {customBreaks: true}});+ onSelect(SCALE_TYPES.custom);} else {if (hasColorMap(range)) {// remove custom breaks@@ -162,15 +167,16 @@ function ColorScaleSelectorFactory(onSelect(getOptionValue(val));}// if current is not custom- setColorUI({- colorRangeConfig: {- customBreaks: false- }- });- hideTippy(tippyInstance);+ if (isEditingColorBreaks) {+ setColorUI({+ colorRangeConfig: {+ customBreaks: false+ }+ });+ }}},- [setColorUI, onSelect, range, getOptionValue, tippyInstance]+ [setColorUI, onSelect, range, getOptionValue, isEditingColorBreaks]);const onApply = useCallback(() => {@@ -186,31 +192,42 @@ function ColorScaleSelectorFactory(return (<DropdownPropContext.Provider- value={{setColorUI, colorUIConfig, colorBreaks, isCustomBreaks, onApply, onCancel}}+ value={{+ setColorUI,+ colorField: field,+ dataset,+ colorUIConfig,+ colorBreaks,+ isCustomBreaks,+ onScaleChange: onSelect,+ onApply,+ onCancel+ }}><StyledColorScaleSelector>- <Tippy+ <LazyTippytrigger="click"placement="bottom-start"appendTo="parent"interactive={true}hideOnClick={!isEditingColorBreaks}- // @ts-ignoreonCreate={setTippyInstance}popperOptions={POPPER_OPTIONS}render={attrs => (<DropdownWrapper {...attrs}>{/*@ts-ignore*/}- <Typeahead- {...dropdownSelectProps}- displayOption={displayOption}- // @ts-ignore- getOptionValue={getOptionValue}- onOptionSelected={onSelectScale}- customListComponent={ColorScaleSelectDropdown}- searchable={false}- showOptionsWhenEmpty- />+ {!dropdownSelectProps.disabled && (+ <Typeahead+ {...dropdownSelectProps}+ displayOption={displayOption}+ // @ts-ignore+ getOptionValue={getOptionValue}+ onOptionSelected={onSelectScale}+ customListComponent={ColorScaleSelectDropdown}+ searchable={false}+ showOptionsWhenEmpty+ />+ )}</DropdownWrapper>)}>@@ -222,7 +239,7 @@ function ColorScaleSelectorFactory(value={dropdownSelectProps.selectedItems[0]}/></div>- </Tippy>+ </LazyTippy></StyledColorScaleSelector></DropdownPropContext.Provider>);diff --git a/src/components/src/side-panel/layer-panel/custom-palette.tsx b/src/components/src/side-panel/layer-panel/custom-palette.tsxindex c71149feb..9e72e8204 100644--- a/src/components/src/side-panel/layer-panel/custom-palette.tsx+++ b/src/components/src/side-panel/layer-panel/custom-palette.tsx@@ -21,7 +21,7 @@ import {import styled, {StyledComponent, css} from 'styled-components';import Portaled from '../../common/portaled';-import {KeyEvent} from '@kepler.gl/constants';+import {ColorMap, KeyEvent} from '@kepler.gl/constants';import {ColorUI, HexColor, NestedPartial} from '@kepler.gl/types';import {colorMapToColorBreaks, isNumericColorBreaks} from '@kepler.gl/utils';import {@@ -96,8 +96,8 @@ const dragHandleActive = css`export const ColorPaletteItem = styled.div`display: flex;align-items: center;- padding-top: 6px;- padding-bottom: 6px;+ padding-top: 2px;+ padding-bottom: 2px;z-index: ${props => props.theme.dropdownWrapperZ + 1};justify-content: space-between;@@ -531,10 +531,19 @@ function CustomPaletteFactory(): React.FC<CustomPaletteProps> {const newColorMap = customPalette.colorMap.map((cm, i) => (i === index ? [value, cm[1]] : cm) as [string, string]);++ // sort the user inputs in case the break values are not ordered+ const breaks = newColorMap+ .map(cm => cm[0] as string | null)+ .slice(0, -1)+ .sort((a, b) => Number(a) - Number(b))+ .concat(null);+ const sortedNewColorMap: ColorMap = newColorMap.map((cm, i) => [breaks[i], cm[1]]);+setColorPaletteUI({customPalette: {...customPalette,- colorMap: newColorMap+ colorMap: sortedNewColorMap}});},diff --git a/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx b/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsxindex e88b101b8..b3661add5 100644--- a/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx+++ b/src/components/src/side-panel/layer-panel/dimension-scale-selector.tsx@@ -11,6 +11,7 @@ import {Field} from '@kepler.gl/types';import ItemSelector from '../../common/item-selector/item-selector';import {PanelLabel, SidePanelSection} from '../../common/styled-components';import ColorScaleSelectorFactory from './color-scale-selector';+import {KeplerTable} from '@kepler.gl/table';const SizeScaleSelector = ({...dropdownSelectProps}: any) => (<ItemSelector {...dropdownSelectProps} />@@ -20,6 +21,7 @@ export type DimensionScaleSelectorProps = {layer: Layer;channel: VisualChannel;label?: string;+ dataset: KeplerTable | undefined;onChange: (newConfig: {[key: string]: Field | null | string},key: string,@@ -36,6 +38,7 @@ function DimensionScaleSelectorFactory(const DimensionScaleSelector: React.FC<DimensionScaleSelectorProps> = ({layer,channel,+ dataset,label,onChange,setColorUI@@ -75,11 +78,12 @@ function DimensionScaleSelectorFactory(defaultMessage={label}/></PanelLabel>- {isColorScale ? (+ {isColorScale && dataset ? (<ColorScaleSelector{...dropdownSelectProps}layer={layer}field={layer.config[field]}+ dataset={dataset}onSelect={onSelect}scaleType={scaleType}domain={layer.config[domain]}diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsxindex 984ba1080..9ae3944db 100644--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx@@ -94,11 +94,11 @@ const StyledLayerVisualConfigurator = styled.div.attrs({`;export const getLayerFields = (datasets: Datasets, layer: Layer) =>- layer.config?.dataId && datasets[layer.config.dataId] ? datasets[layer.config.dataId].fields : [];+ datasets[layer.config?.dataId || ''] ? datasets[layer.config.dataId].fields : [];/** Return any to be able to customize the Dataset entity */export const getLayerDataset = (datasets: Datasets, layer: Layer): any =>- layer.config?.dataId && datasets[layer.config.dataId] ? datasets[layer.config.dataId] : null;+ datasets[layer.config?.dataId || ''];export const getLayerConfiguratorProps = (props: LayerConfiguratorProps) => ({layer: props.layer,@@ -116,6 +116,7 @@ export const getVisConfiguratorProps = (props: LayerConfiguratorProps) => ({export const getLayerChannelConfigProps = (props: LayerConfiguratorProps) => ({layer: props.layer,+ dataset: getLayerDataset(props.datasets, props.layer),fields: getLayerFields(props.datasets, props.layer),onChange: props.updateLayerVisualChannelConfig,setColorUI: props.updateLayerColorUIdiff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.tsindex 21f2e9dca..dc6436243 100644--- a/src/layers/src/base-layer.ts+++ b/src/layers/src/base-layer.ts@@ -18,7 +18,6 @@ import {CHANNEL_SCALE_SUPPORTED_FIELDS,ColorRange,DEFAULT_COLOR_UI,- DEFAULT_CUSTOM_PALETTE,DEFAULT_HIGHLIGHT_COLOR,DEFAULT_LAYER_LABEL,DEFAULT_TEXT_LABEL,@@ -71,7 +70,12 @@ import {updateCustomColorRangeByColorUI} from '@kepler.gl/utils';import memoize from 'lodash.memoize';-import {isDomainQuantile, getDomainStepsbyZoom, getThresholdsFromQuantiles} from '@kepler.gl/utils';+import {+ initializeCustomPalette,+ isDomainQuantile,+ getDomainStepsbyZoom,+ getThresholdsFromQuantiles+} from '@kepler.gl/utils';export type VisualChannelDomain = number[] | string[];export type VisualChannelField = Field | null;@@ -899,11 +903,15 @@ class Layer {return;}+ if (newConfig.customPalette) {+ // if new config also set customPalette, no need to initiate new+ return;+ }const {colorUI, visConfig} = this.config;if (!visConfig[prop]) return;// make copy of current color range to customPalette- const customPalette = {+ let customPalette = {...visConfig[prop]};@@ -920,15 +928,12 @@ class Layer {}// add name|type|category to updateCustomPalette if customBreaks, so that// colors will not be override as well when inverse palette with custom break- customPalette.name = DEFAULT_CUSTOM_PALETTE.name;- customPalette.type = DEFAULT_CUSTOM_PALETTE.type;- customPalette.category = DEFAULT_CUSTOM_PALETTE.category;// initiate colorMap from current scale- customPalette.colorMap = initializeLayerColorMap(this, visualChannels[channelKey]);++ const colorMap = initializeLayerColorMap(this, visualChannels[channelKey]);+ customPalette = initializeCustomPalette(visConfig[prop], colorMap);} else if (newConfig.colorRangeConfig.custom) {- customPalette.name = DEFAULT_CUSTOM_PALETTE.name;- customPalette.type = DEFAULT_CUSTOM_PALETTE.type;- customPalette.category = DEFAULT_CUSTOM_PALETTE.category;+ customPalette = initializeCustomPalette(visConfig[prop]);}this.updateLayerConfig({diff --git a/src/styles/src/base.ts b/src/styles/src/base.tsindex 5bc5ef08d..8731b87ca 100644--- a/src/styles/src/base.ts+++ b/src/styles/src/base.ts@@ -355,6 +355,8 @@ export const mapControlTop = 52;export const rangeBrushBgd = '#3A414C';export const histogramFillInRange = activeColor;export const histogramFillOutRange = sliderBarColor;+export const histogramOverlayColor = '#999999';+export const histogramBreakLineColor = '#505b7c';export const axisFontSize = '10px';export const axisFontColor = textColor;export const timeTitleFontSize = '10px';@@ -931,6 +933,9 @@ const dropdownListItem = css`color: ${props => props.theme.textColorHl};}}+ &.selected {+ background-color: ${props => props.theme.dropdownListHighlightBg};+ }`;const dropdownListItemLT = css`@@ -1480,6 +1485,8 @@ export const theme = {rangeBrushBgd,histogramFillInRange,histogramFillOutRange,+ histogramOverlayColor,+ histogramBreakLineColor,axisFontSize,axisFontColor,timeTitleFontSize,diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.tsindex 92773ab6e..652316a00 100644--- a/src/table/src/kepler-table.ts+++ b/src/table/src/kepler-table.ts@@ -75,16 +75,19 @@ export type NumericFieldFilterProps = RangeFieldDomain & {type: string;typeOptions: string[];gpu: boolean;+ columnStats?: Record<string, any>;};export type BooleanFieldFilterProps = SelectFieldDomain & {type: string;value: boolean;gpu: boolean;+ columnStats?: Record<string, any>;};export type StringFieldFilterProps = MultiSelectFieldDomain & {type: string;value: string[];gpu: boolean;+ columnStats?: Record<string, any>;};export type TimeFieldFilterProps = TimeRangeFieldDomain & {type: string;@@ -92,6 +95,7 @@ export type TimeFieldFilterProps = TimeRangeFieldDomain & {fixedDomain: boolean;value: number[];gpu: boolean;+ columnStats?: Record<string, any>;};// Unique identifier of each fielddiff --git a/src/types/layers.d.ts b/src/types/layers.d.tsindex f588f5630..192f785d1 100644--- a/src/types/layers.d.ts+++ b/src/types/layers.d.ts@@ -122,6 +122,7 @@ export type Field = {filterProps?: FilterProps;metadata?: Record<string, any>;displayFormat?: string;+ isLoadingStats?: boolean;indexBy?: IndexBy;};diff --git a/src/utils/src/color-utils.ts b/src/utils/src/color-utils.tsindex 6436ae827..29cd774e2 100644--- a/src/utils/src/color-utils.ts+++ b/src/utils/src/color-utils.ts@@ -3,8 +3,10 @@import {CategoricalPalette,+ ColorMap,ColorPalette,ColorRange,+ DEFAULT_CUSTOM_PALETTE,colorPaletteToColorRange} from '@kepler.gl/constants';import {ColorRangeConfig, HexColor, RGBColor} from '@kepler.gl/types';@@ -442,3 +444,19 @@ export function colorRangeBackwardCompatibility(colorRange: ColorRange): ColorRareturn colorRange;}++/**+ * Initialize custom palette from current standard color range object+ */+export function initializeCustomPalette(colorRange: ColorRange, colorMap?: ColorMap): ColorRange {+ // TODO: check on `isReversed` key, whether we can remove it here+ const customPalette = {+ ...colorRange,+ name: DEFAULT_CUSTOM_PALETTE.name,+ type: DEFAULT_CUSTOM_PALETTE.type,+ category: DEFAULT_CUSTOM_PALETTE.category,+ ...(colorMap ? {colorMap} : {})+ };++ return customPalette;+}diff --git a/src/utils/src/data-scale-utils.ts b/src/utils/src/data-scale-utils.tsindex 6221c3d26..8804d98d4 100644--- a/src/utils/src/data-scale-utils.ts+++ b/src/utils/src/data-scale-utils.ts@@ -11,7 +11,7 @@ import {HexColor, MapState} from '@kepler.gl/types';import {isRgbColor, rgbToHex} from './color-utils';import {DataContainerInterface} from './data-container-interface';-import {formatNumber, reverseFormatNumber, unique} from './data-utils';+import {formatNumber, isNumber, reverseFormatNumber, unique} from './data-utils';import {getTimeWidgetHintFormatter} from './filter-utils';import {isPlainObject} from './utils';@@ -261,7 +261,7 @@ export function getQuantLabelFormat(domain, fieldType) {? getTimeLabelFormat(domain): !fieldType? defaultFormat- : n => (n ? formatNumber(n, fieldType) : 'no value');+ : n => (isNumber(n) ? formatNumber(n, fieldType) : 'no value');}/**diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 4f3cec33e..a4c2bb4c2 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -23,7 +23,8 @@ export {paletteIsType,paletteIsColorBlindSafe,updateColorRangeByMatchingPalette,- updateCustomColorRangeByColorUI+ updateCustomColorRangeByColorUI,+ initializeCustomPalette} from './color-utils';export {errorNotification} from './notifications-utils';@@ -36,6 +37,7 @@ export {adjustValueToAnimationWindow,getBinThresholds,histogramFromThreshold,+ histogramFromValues,histogramFromDomain,runGpuFilterForPlot,updateTimeFilterPlotType@@ -92,7 +94,11 @@ export {scaleMapStyleByResolution} from './map-style-utils/mapbox-gl-style-editor';export {validateToken} from './mapbox-utils';-export * from './observe-dimensions';+export {+ default as useDimensions,+ observeDimensions,+ unobserveDimensions+} from './observe-dimensions';export type {Dimensions} from './observe-dimensions';export {snapToMarks} from './plot';export * from './projection-utils';@@ -129,6 +135,7 @@ export type {FilterChanged, FilterResult, dataValueAccessor} from './filter-utilexport {colorMapToColorBreaks,+ colorBreaksToColorMap,getLayerColorScale,getLegendOfScale,getLinearDomain,@@ -142,7 +149,8 @@ export {isDomainStops,isDomainQuantile,getDomainStepsbyZoom,- getThresholdsFromQuantiles+ getThresholdsFromQuantiles,+ getQuantLabelFormat} from './data-scale-utils';export type {ColorBreak, ColorBreakOrdinal, DomainQuantiles, DomainStops} from './data-scale-utils';diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.tsindex 59db003e6..4d887d704 100644--- a/src/utils/src/plot.ts+++ b/src/utils/src/plot.ts@@ -29,7 +29,7 @@ import {AggregationTypes} from '@kepler.gl/constants';-import {roundValToStep} from './data-utils';+import {isNumber, roundValToStep} from './data-utils';import {aggregate, AGGREGATION_NAME} from './aggregation';import {capitalizeFirstLetter} from './strings';import {getDefaultTimeFormat} from './format';@@ -49,18 +49,24 @@ type Datasets = any;export function histogramFromThreshold(thresholds: number[],values: number[],- indexes: number[]+ valueAccessor?: (d: unknown) => number,+ filterEmptyBins = true): Bin[] {- const bins = d3Histogram()- .value(idx => values[idx])+ const getBins = d3Histogram().domain([thresholds[0], thresholds[thresholds.length - 1]])- .thresholds(thresholds)(indexes)- .map(bin => ({- count: bin.length,- indexes: bin,- x0: bin.x0,- x1: bin.x1- }));+ .thresholds(thresholds);++ if (valueAccessor) {+ getBins.value(valueAccessor);+ }++ // @ts-ignore+ const bins = getBins(values).map(bin => ({+ count: bin.length,+ indexes: bin,+ x0: bin.x0,+ x1: bin.x1+ }));// d3-histogram ignores threshold values outside the domain// The first bin.x0 is always equal to the minimum domain value, and the last bin.x1 is always equal to the maximum domain value.@@ -69,9 +75,38 @@ export function histogramFromThreshold(// bins[bins.length - 1].x1 = thresholds[thresholds.length - 1];// @ts-ignore- // filter out bins with 0 counts- return bins.filter(b => b.count > 0);- // return bins;+ return filterEmptyBins ? bins.filter(b => b.count > 0) : bins;+}++/**+ *+ * @param values+ * @param numBins+ * @param valueAccessor+ */+export function histogramFromValues(+ values: (Millisecond | null | number)[],+ numBins: number,+ valueAccessor?: (d: unknown) => number+) {+ const getBins = d3Histogram().thresholds(numBins);++ if (valueAccessor) {+ getBins.value(valueAccessor);+ }++ // @ts-ignore d3-array types doesn't match+ return getBins(values)+ .map(bin => ({+ count: bin.length,+ indexes: bin,+ x0: bin.x0,+ x1: bin.x1+ }))+ .filter(b => {+ const {x0, x1} = b;+ return isNumber(x0) && isNumber(x1);+ });}/**@@ -142,8 +177,8 @@ export function binByTime(indexes, dataset, interval, filter) {return null;}const intervalBins = getBinThresholds(interval, filter.domain);-- const bins = histogramFromThreshold(intervalBins, mappedValue, indexes);+ const valueAccessor = idx => mappedValue[idx];+ const bins = histogramFromThreshold(intervalBins, indexes, valueAccessor);return bins;}diff --git a/test/browser/components/common/column-stats-chart-test.js b/test/browser/components/common/column-stats-chart-test.jsnew file mode 100644index 000000000..5902e2e04--- /dev/null+++ b/test/browser/components/common/column-stats-chart-test.js@@ -0,0 +1,387 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {layerVisualChannelConfigChange} from '@kepler.gl/actions';+import {+ ColorBreaksDisplay,+ ColorBreaksPanelFactory,+ ColorChartHeader,+ ColorChartTick,+ ColumnStatsChartFactory,+ EditButton,+ HISTOGRAM_HEIGHT,+ HISTOGRAM_WIDTH,+ appInjector+} from '@kepler.gl/components';+import {keplerGlReducerCore as coreReducer} from '@kepler.gl/reducers';+import {getLayerColorScale, getLegendOfScale} from '@kepler.gl/utils';+import {scaleLinear} from 'd3-scale';+import cloneDeep from 'lodash.clonedeep';+import React from 'react';+import sinon from 'sinon';+import test from 'tape';+import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';+import {StateWFilesFiltersLayerColor} from 'test/helpers/mock-state';++const ColorBreaksPanel = appInjector.get(ColorBreaksPanelFactory);+const ColumnStatsChart = appInjector.get(ColumnStatsChartFactory);++const TEST_PALETTE_COLORS = ['#FFF7F3', '#F369A3', '#49006A'];++const ColumnStatsChartProps = (filterData = false) => {+ const InitialState = cloneDeep(StateWFilesFiltersLayerColor);+ const {layers, datasets} = InitialState.visState;+ const pointLayer = layers[0];+ const dataset = datasets[pointLayer.config.dataId];++ // use uid as colorField (contains null values)+ const colorField = datasets[pointLayer.config.dataId].fields[6];+ const updatedState = coreReducer(+ InitialState,+ layerVisualChannelConfigChange(pointLayer, {colorField}, 'color')+ );++ if (filterData) {+ dataset.filteredIndexForDomain = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20];+ }++ const pointLayer1 = updatedState.visState.layers[0];++ const domain = pointLayer1.config.colorDomain;+ const scaleType = 'quantize';+ const range = {+ colors: TEST_PALETTE_COLORS,+ name: 'RdPu',+ type: 'sequential',+ category: 'ColorBrewer'+ };+ const colorScale = getLayerColorScale({range, domain, scaleType, layer: pointLayer1});+ const colorBreaks = getLegendOfScale({scale: colorScale, scaleType, fieldType: colorField.type});++ return {+ colorField,+ dataset,+ colorBreaks,+ onChangedUpdater: sinon.spy()+ };+};++const GetTickPositions = colorBreaks => {+ const x = scaleLinear().domain([1, 12124]).range([0, HISTOGRAM_WIDTH]);+ return colorBreaks.map(cb => x(cb.range[1]));+};++test('Components -> ColumnStatsChart -> ColorChartTick', t => {+ const ExpectedTickPositions = [70, 140];+ let MovedTickPositions = null;++ const InitialProps = {+ colors: ['#FFF7F3', '#F369A3'],+ positions: ExpectedTickPositions,+ onTickMoving: positions => {+ MovedTickPositions = positions;+ },+ onTickChanged: sinon.spy()+ };++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColorChartTick {...InitialProps} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColorChartTick');++ const colorChartTickWrapper = wrapper.find('.color-chart-tick-container');+ t.equal(colorChartTickWrapper.length, 1, 'should render 1 ColorChartTickContainer');+ t.equal(colorChartTickWrapper.children().length, 2, 'should render 2 ticks');++ const TestTickPositions = colorChartTickWrapper.children().map(x => {+ const style = x.props().style;+ return (+ parseInt(style.left, 10) + parseInt(style.borderWidth, 10) + parseInt(style.width, 10) / 2+ );+ });++ t.deepEqual(+ ExpectedTickPositions,+ TestTickPositions,+ 'should position 2 ticks at correct locations'+ );++ // simulate drag tick to move+ const firstTick = colorChartTickWrapper.childAt(0);+ firstTick.simulate('mousedown');+ firstTick.simulate('mousemove', {clientX: 80});+ firstTick.simulate('mouseup');++ t.deepEqual(MovedTickPositions, [80, 140], 'should move 2 ticks to correct locations');++ firstTick.simulate('mousedown');+ firstTick.simulate('mousemove', {clientX: -10});+ firstTick.simulate('mouseup');++ t.deepEqual(MovedTickPositions, [0, 140], 'should move the first tick to correct locations');++ firstTick.simulate('mousedown');+ firstTick.simulate('mousemove', {clientX: 150});+ firstTick.simulate('mouseup');++ t.deepEqual(+ MovedTickPositions,+ [139, 140],+ 'should move the first tick 1 pixel left to the second tick'+ );++ t.end();+});++test('Components -> ColumnStatsChart -> ColorChartHeader', t => {+ const InitialProps = {+ minVal: 1,+ maxVal: 100,+ meanVal: 50+ };++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColorChartHeader {...InitialProps} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColumnStatsChart');++ const colorChartHeader = wrapper.find('.color-chart-header');+ t.equal(colorChartHeader.length, 1, 'should render 1 ColorChartHeader');+ t.equal(colorChartHeader.children().length, 3, 'should render 3 divs in color chart header');+ t.equal(+ colorChartHeader.children().at(0).text(),+ 'MIN: 1',+ 'should render MIN value in color chart header'+ );+ t.equal(+ colorChartHeader.children().at(1).text(),+ 'MEAN: 50',+ 'should render MEAN value in color chart header'+ );+ t.equal(+ colorChartHeader.children().at(2).text(),+ 'MAX: 100',+ 'should render MAX value in color chart header'+ );++ t.end();+});++const GetColorPaletteWidths = tickPositions => {+ const n = tickPositions.length;+ const widths = [tickPositions[0]];+ for (let i = 1; i < n; ++i) {+ widths.push(tickPositions[i] - tickPositions[i - 1]);+ }+ return widths;+};++test('Components -> ColumnStatsChart -> IsLoading', t => {+ const InitialProps = ColumnStatsChartProps();+ const modifiedDataset = InitialProps.dataset;+ modifiedDataset.fields = modifiedDataset.fields.map(f => {+ // hack to test case of loading stats+ f.isLoadingStats = true;+ return f;+ });+ const InitialPropsWithLoading = {+ ...InitialProps,+ dataset: modifiedDataset+ };+ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColumnStatsChart {...InitialPropsWithLoading} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColumnStatsChart');++ t.equal(wrapper.find('.color-chart-loading').length, 1, 'should render loading component');+ t.equal(wrapper.find('.color-chart-header').length, 0, 'should not render ColorChartHeader');+ t.end();+});++test('Components -> ColumnStatsChart', t => {+ const InitialProps = ColumnStatsChartProps();+ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColumnStatsChart {...InitialProps} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColumnStatsChart');++ // test ColorChartHeader+ const colorChartHeader = wrapper.find('.color-chart-header');+ t.equal(colorChartHeader.length, 1, 'should render 1 ColorChartHeader');+ t.equal(colorChartHeader.children().length, 3, 'should render 3 divs in color chart header');++ // test ColorPalette+ const colorChartPalette = wrapper.find('.color-range-palette__inner');+ t.equal(colorChartPalette.length, 1, 'should render 1 ColorChartPalette');++ const ExpectedTickPositions = GetTickPositions(InitialProps.colorBreaks);+ const ExpectedColorPaletteWidths = GetColorPaletteWidths(ExpectedTickPositions);++ const TestColorPaletteWidths = colorChartPalette.children().map(x => x.props().style.width);+ t.deepEqual(+ TestColorPaletteWidths,+ ExpectedColorPaletteWidths,+ 'should render color palette widths correctly.'+ );++ const TestColorPaletteColors = colorChartPalette+ .children()+ .map(x => x.props().style.backgroundColor);+ t.deepEqual(+ TestColorPaletteColors,+ TEST_PALETTE_COLORS,+ 'should render color palette colors correctly'+ );++ // test histogram+ const colorChartHistogram = wrapper.find('.color-chart-histogram');+ const histogramSVG = colorChartHistogram.find('svg');+ t.equal(histogramSVG.length, 1, 'should render 1 histogram');+ t.equal(histogramSVG.props().width, HISTOGRAM_WIDTH, 'should render histogram with 210 width');+ t.equal(histogramSVG.props().height, HISTOGRAM_HEIGHT, 'should render histogram with 210 width');+ t.equal(+ histogramSVG.find('mask').props().id,+ 'histogram-mask',+ 'should render a mask using histogram bins'+ );+ t.equal(+ histogramSVG.find('.histogram-bars').children().length,+ 25,+ 'should render histogram bars'+ );++ t.end();+});++test('Components -> ColumnStatsChart -> FilteredBins', t => {+ const InitialProps = ColumnStatsChartProps(true);++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColumnStatsChart {...InitialProps} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColumnStatsChart');++ const colorChartHistogram = wrapper.find('.color-chart-histogram');+ t.equal(+ colorChartHistogram.find('mask').props().id,+ 'histogram-mask',+ 'should render a mask using histogram bins'+ );+ t.equal(+ colorChartHistogram.find('.histogram-bars').children().length,+ 25,+ 'should render histogram bars'+ );+ t.equal(+ colorChartHistogram.find('.overlay-histogram-bars').children().length,+ 25,+ 'should render additional overlayed histogram bars'+ );+ t.end();+});++test('Components -> ColorBreaksPanel -> ColorBreaksDisplay', t => {+ let wrapper;++ const InitialProps1 = {+ currentBreaks: [],+ onEdit: false+ };++ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColorBreaksDisplay {...InitialProps1} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColorBreaksDisplay even with empty colorBreaks');++ const {colorBreaks} = ColumnStatsChartProps();+ const InitialProps = {+ currentBreaks: colorBreaks,+ onEdit: true+ };++ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColorBreaksDisplay {...InitialProps} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColorBreaksDisplay');++ t.ok(wrapper.find(EditButton).length, 'should render EditButton');++ t.end();+});++test('Components -> ColorBreaksPanel -> ColumnStatsChart', t => {+ const InitialProps = {+ ...ColumnStatsChartProps(),+ colorUIConfig: {+ customPalette: {},+ showSketcher: false,+ colorRangeConfig: {+ customBreaks: false+ }+ },+ isCustomBreaks: false,+ setColorUI: sinon.spy(),+ onApply: sinon.spy(),+ onCancel: sinon.spy(),+ onScaleChange: sinon.spy()+ };++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ColorBreaksPanel {...InitialProps} />+ </IntlWrapper>+ );+ }, 'should not fail rendering ColumnStatsChart');++ const colorChartTickWrapper = wrapper.find('.color-chart-tick-container');++ // simulate drag tick to move+ const firstTick = colorChartTickWrapper.childAt(0);+ firstTick.simulate('mousedown');+ firstTick.simulate('mousemove', {clientX: 80});+ firstTick.simulate('mouseup');++ wrapper.update();++ const TestTickPositions = wrapper+ .find('.color-chart-tick-container')+ .children()+ .map(x => {+ const style = x.props().style;+ return (+ parseInt(style.left, 10) + parseInt(style.borderWidth, 10) + parseInt(style.width, 10) / 2+ );+ });++ t.deepEqual(TestTickPositions, [80, 140], 'should move ticks to correct positions');++ t.end();+});diff --git a/test/browser/components/common/index.js b/test/browser/components/common/index.jsindex 0be99e0dc..df5a35585 100644--- a/test/browser/components/common/index.js+++ b/test/browser/components/common/index.js@@ -7,3 +7,4 @@ import './range-slider-test';import './item-selector-test';import './range-plot-test';import './animation-control-test';+import './column-stats-chart-test';diff --git a/test/browser/components/side-panel/channel-by-value-selctor-test.js b/test/browser/components/side-panel/channel-by-value-selctor-test.jsindex b3243724d..9a0c9466b 100644--- a/test/browser/components/side-panel/channel-by-value-selctor-test.js+++ b/test/browser/components/side-panel/channel-by-value-selctor-test.js@@ -5,6 +5,7 @@import {layerColorUIChange, layerVisualChannelConfigChange} from '@kepler.gl/actions';import {keplerGlReducerCore as coreReducer} from '@kepler.gl/reducers';+import {ColorBreaksDisplay} from '@kepler.gl/components';import cloneDeep from 'lodash.clonedeep';import React from 'react';import sinon from 'sinon';@@ -85,6 +86,7 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> disabled', tchannel={pointLayer.visualChannels.color}onChange={updateLayerVisualChannelConfig}fields={datasets[pointLayer.config.dataId].fields}+ dataset={datasets[pointLayer.config.dataId]}setColorUI={nop}/></IntlWrapper>@@ -224,6 +226,7 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDichannel: pointLayer1.visualChannels.color,onChange: updateLayerVisualChannelConfig,fields: updatedState.visState.datasets[pointLayer1.config.dataId].fields,+ dataset: updatedState.visState.datasets[pointLayer1.config.dataId],setColorUI};@@ -259,6 +262,9 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi);t.equal(wrapper.find(ColorBreaksPanel).length, 1, 'Should render 1 ColorBreaksPanel');+ t.equal(wrapper.find(ColorBreaksDisplay).length, 1, 'Should render 1 ColorBreaksDisplay');+ t.equal(wrapper.find(CustomPalette).length, 0, 'Should not render CustomPalette');+t.equal(wrapper.find(ColorPaletteItem).length, 4, 'Should render 4 ColorPaletteItem');const expectedText = [@@ -304,9 +310,20 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi}}];+ const expectedArgs1 = [{colorScale: 'custom'}, 'color', undefined];t.deepEqual(setColorUI.args[0], expectedArgs, 'should set customBreaks to true');- const updatedState1 = coreReducer(updatedState, layerColorUIChange(pointLayer1, ...expectedArgs));+ t.ok(updateLayerVisualChannelConfig.calledOnce, 'should call updateLayerVisualChannelConfig');+ t.deepEqual(updateLayerVisualChannelConfig.args[0], expectedArgs1, 'should pass custom scale');++ const updatedStateTemp = coreReducer(+ updatedState,+ layerColorUIChange(pointLayer1, ...expectedArgs)+ );+ const updatedState1 = coreReducer(+ updatedStateTemp,+ layerVisualChannelConfigChange(pointLayer1, ...expectedArgs1)+ );t.deepEqual(updatedState1.visState.layers[0].config.colorUI.colorRange,@@ -319,6 +336,7 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi});t.equal(wrapper.find(CustomPalette).length, 1, 'should render 1 CustomPalette');+ t.equal(wrapper.find(ColorBreaksDisplay).length, 0, 'should not render ColorBreaksDisplay');t.equal(wrapper.find(EditableColorRange).length, 4, 'Should render 4 EditableColorRange');t.equal(wrapper.find(ColorSwatch).length, 4, 'Should render 4 ColorSwatch');@@ -383,20 +401,199 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi];t.deepEqual(setColorUI.args[1], expectedArgs2, 'should set customBreaks.colorMap');- // on confirm+ // on confirm custom breakst.equal(wrapper.find(CustomPalette).find(Button).length, 2, 'should render 2 buttons');- wrapper+ const confirmButton = wrapper.find(CustomPalette).find(Button)+ .at(0);+ t.equal(confirmButton.text(), 'Confirm', 'should render confirm button');+ confirmButton.simulate('click');++ t.ok(updateLayerVisualChannelConfig.calledTwice, 'should call updateLayerVisualChannelConfig');++ const expectedArgs3 = [+ {colorScale: 'custom'},+ 'color',+ {colorRange: ExpectedCustomPalette.customPalette}+ ];+ t.deepEqual(+ updateLayerVisualChannelConfig.args[1],+ expectedArgs3,+ 'should pass custom scale and custom colorRange'+ );+ const expectedArgs4 = [+ 'colorRange',+ {showSketcher: false, colorRangeConfig: {customBreaks: false}}+ ];+ t.deepEqual(setColorUI.args[2], expectedArgs4, 'should set customBreaks to false');++ const pointLayer2 = updatedState1.visState.layers[0];+ const updatedStateTemp1 = coreReducer(+ updatedState1,+ layerVisualChannelConfigChange(pointLayer2, ...expectedArgs3)+ );+ const updatedState2 = coreReducer(+ updatedStateTemp1,+ layerColorUIChange(pointLayer2, ...expectedArgs4)+ );++ t.deepEqual(+ updatedState2.visState.layers[0].config.colorUI.colorRange,+ {+ ...ExpectedCustomPalette,+ colorRangeConfig: {+ ...ExpectedCustomPalette.colorRangeConfig,+ customBreaks: false+ }+ },+ 'Should set customPalette and colorMap'+ );+ t.deepEqual(+ updatedState2.visState.layers[0].config.colorScale,+ 'custom',+ 'Should set color scale to custom'+ );+ t.deepEqual(+ updatedState2.visState.layers[0].config.visConfig.colorRange,+ ExpectedCustomPalette.customPalette,+ 'Should set color range to custom palette'+ );++ wrapper.setProps({+ children: <ChannelByValueSelector {...InitialProps} layer={updatedState2.visState.layers[0]} />+ });+ // set scale back to standard scale (:quantile)+ const quantileOption = wrapper+ .find(ColorScaleSelector).at(0)- .simulate('click');+ .find('.list__item')+ .at(1);+ t.equal(quantileOption.text(), 'Quantile', '2nd scale option should be quantile');+ quantileOption.simulate('click');- t.ok(updateLayerVisualChannelConfig.calledOnce, 'should call updateLayerVisualChannelConfig');+ const expectedArgs5 = [+ {colorScale: 'quantile'},+ 'color',+ {+ colorRange: {+ name: 'color.customPalette',+ type: 'custom',+ category: 'Custom',+ colors: ['#00939C', '#6BB5B9', '#AAD7D9', '#E6FAFA']+ }+ }+ ];t.deepEqual(- updateLayerVisualChannelConfig.args[0],- [{colorScale: 'custom'}, 'color', {colorRange: ExpectedCustomPalette.customPalette}],+ updateLayerVisualChannelConfig.args[2],+ expectedArgs5,'should pass custom scale and custom colorRange');++ t.deepEqual(setColorUI.args.length, 3, 'should not call setColorUI');++ t.end();+});++const GetTickPositions = wrapper => {+ wrapper.find('.color-chart-tick-container').update();+ return wrapper+ .find('.color-chart-tick-container')+ .children()+ .map(x => {+ const style = x.props().style;+ return Math.round(+ parseFloat(style.left) + parseFloat(style.borderWidth) + parseFloat(style.width) / 2+ );+ });+};++const GetInitialPropsFromState = (layer, updatedState) => {+ return {+ layer,+ channel: layer.visualChannels.color,+ onChange: newConfig => layer.updateLayerConfig(newConfig),+ fields: updatedState.visState.datasets[layer.config.dataId].fields,+ dataset: updatedState.visState.datasets[layer.config.dataId],+ setColorUI: (prop, newConfig) => layer.updateLayerColorUI(prop, newConfig)+ };+};++test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColumnStatsChart', t => {+ const InitialState = cloneDeep(StateWFilesFiltersLayerColor);+ const {layers, datasets} = InitialState.visState;+ const pointLayer = layers[0];++ // set point layer color field to integar id+ const colorField = datasets[pointLayer.config.dataId].fields[6];+ const updatedState = coreReducer(+ InitialState,+ layerVisualChannelConfigChange(pointLayer, {colorField}, 'color')+ );+ const pointLayer1 = updatedState.visState.layers[0];+ const InitialProps = GetInitialPropsFromState(pointLayer1, updatedState);++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountWithTheme(+ <IntlWrapper>+ <ChannelByValueSelector {...InitialProps} />+ </IntlWrapper>+ );+ }, 'Should not fail rendering point layer');++ t.equal(+ wrapper.find('.color-chart-container').length,+ 1,+ 'Should render color chart with histogram'+ );++ const quantizeTestCase = {+ optionIndex: 0,+ optionName: 'quantize',+ expectedTickPositions: [53, 105, 158]+ };++ const quantileTestCase = {+ optionIndex: 1,+ optionName: 'quantile',+ expectedTickPositions: [0, 0, 1]+ };++ const customTestCase = {+ optionIndex: 2,+ optionName: 'custom',+ // uses tick positions from the previous test case!+ expectedTickPositions: [0, 0, 1]+ };++ [quantizeTestCase, quantileTestCase, customTestCase].forEach(tc => {+ // simulate click color scale option+ wrapper+ .find(ColorScaleSelector)+ .at(0)+ .find('.list__item')+ .at(tc.optionIndex)+ .simulate('click');++ // trigger action+ const updatedState2 = coreReducer(+ updatedState,+ layerVisualChannelConfigChange(pointLayer1, {colorScale: tc.optionName}, 'color')+ );+ const pointLayer2 = updatedState2.visState.layers[0];+ const InitialProps2 = GetInitialPropsFromState(pointLayer2, updatedState2);+ wrapper.setProps({+ children: <ChannelByValueSelector {...InitialProps2} />+ });++ t.deepEqual(+ GetTickPositions(wrapper),+ tc.expectedTickPositions,+ `Should render three ticks for scale ${tc.optionName}`+ );+ });+t.end();});diff --git a/test/browser/components/side-panel/layer-configurator-test.js b/test/browser/components/side-panel/layer-configurator-test.jsindex fd43254eb..2c4f85d1c 100644--- a/test/browser/components/side-panel/layer-configurator-test.js+++ b/test/browser/components/side-panel/layer-configurator-test.js@@ -16,7 +16,9 @@ import {ColumnSelectorFactory,appInjector,dropdownListClassList,- Checkbox+ Checkbox,+ getLayerFields,+ getLayerDataset} from '@kepler.gl/components';import {StateWFiles, StateWTripGeojson, testCsvDataId} from 'test/helpers/mock-state';@@ -100,6 +102,7 @@ test('Components -> LayerConfigurator.mount -> default prop 1', t => {},layerChannelConfigProps: {layer: expectedLayer,+ dataset: expectedDataset,fields: expectedDataset.fields,onChange: updateLayerVisualChannelConfig,setColorUI: updateLayerColorUI@@ -133,7 +136,7 @@ test('Components -> LayerConfigurator.mount -> default prop 1', t => {t.deepEqual(args.layerChannelConfigProps,expectedArgs.layerChannelConfigProps,- 'render layer method should receive corrent layerChannelConfigProps arg'+ 'render layer method should receive correct layerChannelConfigProps arg');t.end();@@ -371,3 +374,31 @@ test('Components -> LayerConfigurator.mount -> LayerColumnModeConfig ', t => {t.end();});++test('Components -> LayerConfigurator -> getLayerFields', t => {+ const layer = StateWTripGeojson.visState.layers[0];+ const datasets = StateWTripGeojson.visState.datasets;++ const fields = getLayerFields(datasets, layer);++ t.equal(fields.length, 5, 'should get 4 fields');++ const expectedFields = datasets.trip_data.fields;+ t.deepEqual(fields, expectedFields, 'should get 4 fields from the first layer');++ t.end();+});++test('Components -> LayerConfigurator -> getLayerDataset', t => {+ const layer = StateWTripGeojson.visState.layers[0];+ const datasets = StateWTripGeojson.visState.datasets;++ const ds = getLayerDataset(datasets, layer);++ t.equal(ds.id, 'trip_data', 'should get 1 dataset: trip_data');++ const expectedDS = datasets.trip_data;+ t.deepEqual(ds, expectedDS, 'should get 1 dataset for the input layer');++ t.end();+});diff --git a/test/fixtures/state-saved-v0.js b/test/fixtures/state-saved-v0.jsindex fa1bb8936..5a1eefee9 100644--- a/test/fixtures/state-saved-v0.js+++ b/test/fixtures/state-saved-v0.js@@ -931,8 +931,7 @@ export const mergedFilters = [1453770173000,1453770394000,1453770540000- ],- [0, 1, 2, 3, 4, 5, 6, 7, 8]+ ])}}diff --git a/test/fixtures/test-csv-data.js b/test/fixtures/test-csv-data.jsindex 0ceac58ed..8c79c05d2 100644--- a/test/fixtures/test-csv-data.js+++ b/test/fixtures/test-csv-data.js@@ -742,8 +742,7 @@ export const mergedEpochFilter = {[dataId]: {'15-minute': histogramFromThreshold(getBinThresholds('15-minute', [1472688000000, 1472774400000]),- epochMappedValue,- epochMappedValue.map((_, i) => i)+ epochMappedValue)}}@@ -786,15 +785,13 @@ export const expectedSyncedTsFilter = {'test-csv-data-1': {'15-second': histogramFromThreshold(getBinThresholds('15-second', [1474070995000, 1474072208000]),- timeStampmappedValue.slice(0, 20),- epochMappedValue.map((_, i) => i)+ timeStampmappedValue.slice(0, 20))},'test-csv-data-2': {'15-second': histogramFromThreshold(getBinThresholds('15-second', [1474070995000, 1474072208000]),- timeStampmappedValue.slice(5, timeStampmappedValue.length),- epochMappedValue.map((_, i) => i)+ timeStampmappedValue.slice(5, timeStampmappedValue.length))}},diff --git a/test/node/utils/data-scale-utils-test.js b/test/node/utils/data-scale-utils-test.jsindex 4894dc040..02d5bf5c7 100644--- a/test/node/utils/data-scale-utils-test.js+++ b/test/node/utils/data-scale-utils-test.js@@ -10,7 +10,8 @@ import {getLogDomain,createDataContainer,getThresholdsFromQuantiles,- getDomainStepsbyZoom+ getDomainStepsbyZoom,+ getQuantLabelFormat} from '@kepler.gl/utils';function numberSort(a, b) {@@ -162,3 +163,17 @@ test('DataScaleUtils -> getDomainStepsbyZoom', t => {t.end();});++test('DataScaleUtils -> getQuantLabelFormat', t => {+ const fieldType = 'real';+ const domain = [1, 2];++ const format = getQuantLabelFormat(domain, fieldType);++ t.deepEqual(format(0), '0', 'should get correct quant label format for 0');+ t.deepEqual(format(null), 'no value', 'should get correct quant label format for null');+ t.deepEqual(format(undefined), 'no value', 'should get correct quant label format for undefined');+ t.deepEqual(format(1.0), '1', 'should get correct quant label format for number');++ t.end();+});diff --git a/test/node/utils/index.js b/test/node/utils/index.jsindex 5ee5b38a3..b803f7a88 100644--- a/test/node/utils/index.js+++ b/test/node/utils/index.js@@ -22,6 +22,7 @@ import './s2-utils-test';import './editor-utils-test';import './kepler-gl-utils-test';import './timeline-test';+import './plot-test';import './composer-helpers-test';import './dom-to-image';import './effect-utils-test';diff --git a/test/node/utils/plot-test.js b/test/node/utils/plot-test.jsnew file mode 100644index 000000000..68d4d6bf2--- /dev/null+++ b/test/node/utils/plot-test.js@@ -0,0 +1,119 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import test from 'tape';+import {histogramFromThreshold, histogramFromValues} from '@kepler.gl/utils';++const values1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];++test('Utils -> histogramFromThreshold', t => {+ const thresholds1 = [1, 3, 6, 13];++ const bins1 = histogramFromThreshold(thresholds1, values1);+ const expectedHistogram1 = [+ {+ count: 2,+ indexes: [1, 2],+ x0: 1,+ x1: 3+ },+ {+ count: 3,+ indexes: [3, 4, 5],+ x0: 3,+ x1: 6+ },+ {+ count: 7,+ indexes: [6, 7, 8, 9, 10, 11, 12],+ x0: 6,+ x1: 13+ },+ {+ count: 1,+ indexes: [13],+ x0: 13,+ x1: 13+ }+ ];+ expectedHistogram1.forEach(bin => {+ bin.indexes.x0 = bin.x0;+ bin.indexes.x1 = bin.x1;+ });+ t.deepEqual(bins1.length, 4, 'should create histogram with 4 bins.');+ t.deepEqual(expectedHistogram1, bins1, 'should create histogram as expectedHistogram1.');++ const bins2 = histogramFromThreshold([], values1);+ t.deepEqual(bins2.length, 0, 'should create no histogram no threshold.');++ const bins3 = histogramFromThreshold(thresholds1, []);+ t.deepEqual(bins3.length, 0, 'should create no histogram no values.');++ const valueAccessor = idx => values1[idx];+ const filteredIndex = [0, 1, 3, 5, 7, 9, 11];+ const bins4 = histogramFromThreshold(thresholds1, filteredIndex, valueAccessor);++ const expectedHistogram4 = [+ {+ count: 2,+ indexes: [0, 1],+ x0: 1,+ x1: 3+ },+ {+ count: 1,+ indexes: [3],+ x0: 3,+ x1: 6+ },+ {+ count: 4,+ indexes: [5, 7, 9, 11],+ x0: 6,+ x1: 13+ }+ ];+ expectedHistogram4.forEach(bin => {+ bin.indexes.x0 = bin.x0;+ bin.indexes.x1 = bin.x1;+ });++ t.deepEqual(bins4, expectedHistogram4, 'should create histogram with valueAccessor.');++ t.end();+});++test('Utils -> histogramFromValues', t => {+ const numBins = 4;+ const bins5 = histogramFromValues(values1, numBins);+ const expectedHistogram5 = [+ {+ count: 4,+ indexes: [1, 2, 3, 4],+ x0: 0,+ x1: 5+ },+ {+ count: 5,+ indexes: [5, 6, 7, 8, 9],+ x0: 5,+ x1: 10+ },+ {+ count: 4,+ indexes: [10, 11, 12, 13],+ x0: 10,+ x1: 15+ }+ ];+ expectedHistogram5.forEach(bin => {+ bin.indexes.x0 = bin.x0;+ bin.indexes.x1 = bin.x1;+ });++ // d3.histogram uses ticks() to find nice number of breaks (bins), so the+ // number of returned bins may be different than the input number of bins+ t.deepEqual(bins5, expectedHistogram5, 'should create histogram with 3 bins from values.');++ t.end();+});