Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
[feat] Support custom ordinal color scale on string field in layer config (#2868)
Igor Dykhta77e78571321c
diff --git a/src/components/src/common/color-legend.tsx b/src/components/src/common/color-legend.tsxindex 7618e1fa2..ba94ec8b3 100644--- a/src/components/src/common/color-legend.tsx+++ b/src/components/src/common/color-legend.tsx@@ -336,7 +336,11 @@ function ColorLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {);return (- <StyledLegend disableEdit={disableEdit} isExpanded={isExpanded}>+ <StyledLegend+ className="styled-color-legend"+ disableEdit={disableEdit}+ isExpanded={isExpanded}+ >{legends.map((legend, i) => (<LegendRowkey={`${legend.data}-${i}`}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 d16a428e2..4374f944a 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@@ -37,7 +37,9 @@ const StyledColorBreaksDisplay = styled.div.attrs({const ColorBreaksPanelWrapper = styled.div``;-export const EditButton = ({onClickEdit}) => (+type EditButtonProps = {onClickEdit: () => void};++export const EditButton: React.FC<EditButtonProps> = ({onClickEdit}) => (<Button className="editp__button" link onClick={onClickEdit}><Edit height="16px" />Edit@@ -51,7 +53,7 @@ export type ColorBreaksDisplayProps = {export const ColorBreaksDisplay: React.FC<ColorBreaksDisplayProps> = ({currentBreaks, onEdit}) => {if (!isNumericColorBreaks(currentBreaks)) {- // TODO: implement display for ordinal breaks+ // don't display color breaks for ordinal breaks, user can change it in custom breaksreturn null;}return (diff --git a/src/components/src/side-panel/layer-panel/color-palette.tsx b/src/components/src/side-panel/layer-panel/color-palette.tsxindex e5254c616..1aea9e210 100644--- a/src/components/src/side-panel/layer-panel/color-palette.tsx+++ b/src/components/src/side-panel/layer-panel/color-palette.tsx@@ -59,7 +59,7 @@ const ColorPalette: React.FC<ColorPaletteProps> = ({><PaletteWrapper style={{height, transform: `scale(${isReversed ? -1 : 1}, 1)`}}>{colors.map((color: number | string, index: number) =>- colorWidths ? (+ colorWidths && colorWidths[index] ? (<StyledColorBlockkey={`${color}-${index}`}style={{backgroundColor: String(color), width: colorWidths[index]}}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 b1e9cc0b3..7da360ecf 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@@ -13,6 +13,7 @@ import {getLayerColorScale,getLegendOfScale,histogramFromValues,+ histogramFromOrdinal,histogramFromThreshold,getHistogramDomain,hasColorMap@@ -187,8 +188,10 @@ function ColorScaleSelectorFactory(}return columnStats?.bins? columnStats?.bins+ : field?.type === ALL_FIELD_TYPES.string+ ? histogramFromOrdinal(colorScale?.domain() || [], dataset.allIndexes, fieldValueAccessor): histogramFromValues(dataset.allIndexes, HISTOGRAM_BINS, fieldValueAccessor);- }, [aggregatedBins, columnStats, dataset, fieldValueAccessor]);+ }, [aggregatedBins, columnStats, dataset, fieldValueAccessor, colorScale, field?.type]);const histogramDomain = useMemo(() => {return getHistogramDomain({aggregatedBins, columnStats, dataset, fieldValueAccessor});@@ -218,17 +221,22 @@ function ColorScaleSelectorFactory(val => {// highlight selected optionif (getOptionValue(val) === SCALE_TYPES.custom) {+ const colorMap = range.colorMap+ ? range.colorMap+ : colorBreaks+ ? colorBreaksToColorMap(colorBreaks)+ : undefined;+ const colors =+ field?.type === ALL_FIELD_TYPES.string+ ? range.colors.slice(0, colorMap?.length)+ : range.colors;// update custom breaksconst customPalette: NestedPartial<ColorRange> = {name: 'color.customPalette',type: 'custom',category: 'Custom',- colors: range.colors,- colorMap: range.colorMap- ? range.colorMap- : colorBreaks- ? colorBreaksToColorMap(colorBreaks)- : undefined+ colors,+ colorMap};setColorUI({showColorChart: true,diff --git a/src/components/src/side-panel/layer-panel/custom-palette.tsx b/src/components/src/side-panel/layer-panel/custom-palette.tsxindex f73d28b69..23c7cbee4 100644--- a/src/components/src/side-panel/layer-panel/custom-palette.tsx+++ b/src/components/src/side-panel/layer-panel/custom-palette.tsx@@ -221,7 +221,23 @@ export const DragHandle = SortableHandle<DragHandleProps>(({className, children}<StyledDragHandle className={className}>{children}</StyledDragHandle>));-export const ColorPaletteInput = ({value, onChange, id, width, textAlign, editable}) => {+export type ColorPaletteInputProps = {+ value: string | number;+ onChange: (val: unknown) => void;+ id: string;+ width: string;+ textAlign: string;+ editable: boolean;+};++export const ColorPaletteInput = ({+ value,+ onChange,+ id,+ width,+ textAlign,+ editable+}: ColorPaletteInputProps) => {const [stateValue, setValue] = useState(value);const inputRef = useRef(null);useEffect(() => {@@ -393,7 +409,19 @@ export const CustomPaletteInput: React.FC<CustomPaletteInputProps> = ({editColorMap={editColorMapValue}editable/>- ) : null}+ ) : (+ colorBreaks &&+ colorBreaks[index] && (+ <ColorPaletteInput+ value={colorBreaks[index].label}+ id={`color-palette-input-${index}-left`}+ width="auto"+ textAlign="end"+ editable={false}+ onChange={v => v}+ />+ )+ )}</div><div className="custom-palette-input__right">{!disableAppend ? (diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex c445296e1..3e9a398c8 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -666,7 +666,7 @@ export const linearFieldAggrScaleFunctions = {};export const ordinalFieldScaleFunctions = {- [CHANNEL_SCALES.color]: [SCALE_TYPES.ordinal],+ [CHANNEL_SCALES.color]: [SCALE_TYPES.ordinal, SCALE_TYPES.custom],[CHANNEL_SCALES.radius]: [SCALE_TYPES.point],[CHANNEL_SCALES.size]: [SCALE_TYPES.point]};diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.tsindex 84075b15e..35a507e6b 100644--- a/src/layers/src/base-layer.ts+++ b/src/layers/src/base-layer.ts@@ -1027,13 +1027,22 @@ class Layer implements KeplerLayer {colorDomain: VisualChannelDomain,colorRange: ColorRange): GetVisChannelScaleReturnType {- if (hasColorMap(colorRange) && colorScale === SCALE_TYPES.custom) {+ if (+ hasColorMap(colorRange) &&+ (colorScale === SCALE_TYPES.custom || colorScale === SCALE_TYPES.ordinal)+ ) {const cMap = new Map();colorRange.colorMap?.forEach(([k, v]) => {cMap.set(k, typeof v === 'string' ? hexToRgb(v) : v);});- const scaleType = colorScale === SCALE_TYPES.custom ? colorScale : SCALE_TYPES.ordinal;+ // in kepler, scaleThreshold function will be used for SCALE_TYPES.custom+ // so we adjust scaleType to SCALE_TYPES.custom to ordinal if necessary+ const isOrdinalDomain = (colorDomain as (string | number)[]).every(+ i => typeof i === 'string'+ );+ const scaleType =+ colorScale === SCALE_TYPES.custom && !isOrdinalDomain ? colorScale : SCALE_TYPES.ordinal;const scale = getScaleFunction(scaleType, cMap.values(), cMap.keys(), false);scale.unknown(cMap.get(UNKNOWN_COLOR_KEY) || NO_VALUE_COLOR);diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.tsindex 742888b5c..f3d61e2aa 100644--- a/src/table/src/kepler-table.ts+++ b/src/table/src/kepler-table.ts@@ -496,7 +496,9 @@ class KeplerTable<F extends Field = Field> {case SCALE_TYPES.linear:case SCALE_TYPES.sqrt:default:- return getLinearDomain(filteredIndexForDomain, indexValueAccessor);+ return field.type === ALL_FIELD_TYPES.string+ ? getOrdinalDomain(dataContainer, valueAccessor)+ : getLinearDomain(filteredIndexForDomain, indexValueAccessor);}}diff --git a/src/utils/src/data-scale-utils.ts b/src/utils/src/data-scale-utils.tsindex 7ca9171e2..4b0eeb97c 100644--- a/src/utils/src/data-scale-utils.ts+++ b/src/utils/src/data-scale-utils.ts@@ -295,7 +295,7 @@ export function getLegendOfScale({if (!scale || scale.byZoom) {return [];}- if (scaleType === SCALE_TYPES.ordinal) {+ if (scaleType === SCALE_TYPES.ordinal || fieldType === ALL_FIELD_TYPES.string) {return getOrdinalLegends(scale);}@@ -396,6 +396,13 @@ export function colorMapToColorBreaks(colorMap?: ColorMap): ColorBreak[] | nullreturn null;}const colorBreaks = colorMap.map(([value, color], i) => {+ if (typeof value === 'string') {+ // for ordinal string value+ return {+ data: color,+ label: value+ };+ }const range =i === 0? // firstdiff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex f854a9072..42e942e8a 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -39,6 +39,7 @@ export {histogramFromThreshold,histogramFromValues,histogramFromDomain,+ histogramFromOrdinal,runGpuFilterForPlot,updateTimeFilterPlotType} from './plot';diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.tsindex d048d4271..be51bdc45 100644--- a/src/utils/src/plot.ts+++ b/src/utils/src/plot.ts@@ -109,6 +109,30 @@ export function histogramFromValues(});}+export function histogramFromOrdinal(+ domain: [string],+ values: (Millisecond | null | number)[],+ valueAccessor?: (d: unknown) => string+): Bin[] {+ // @ts-expect-error to typed to expect strings+ const getBins = d3Histogram().thresholds(domain);+ if (valueAccessor) {+ // @ts-expect-error to typed to expect strings+ getBins.value(valueAccessor);+ }++ // @ts-expect-error null values aren't expected+ const bins = getBins(values);++ // @ts-ignore d3-array types doesn't match+ return bins.map(bin => ({+ count: bin.length,+ indexes: bin,+ x0: bin.x0,+ x1: bin.x0+ }));+}+/**** @param domaindiff --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 ebf557ba9..9088b2609 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@@ -98,8 +98,8 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> disabled', tt.equal(wrapper.find(ColorScaleSelector).length, 1, 'Should render 1 ColorScaleSelector');t.equal(wrapper.find(ColorScaleSelector).at(0).props().disabled,- true,- 'Should disabled color scale select if only 1 option'+ false,+ 'Should enable ordinal and custom color scale select');t.equal(