Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

[Feat] Custom color scale for categorical/ordinal field (#2880)

Igor Dykhta4bcf55bd6652
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 3238b347a..5e65f6972 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -59,7 +59,7 @@ export function applyLayerConfig(
export type LayerConfigChangeUpdaterAction = {
oldLayer: Layer;
- newConfig: Partial<LayerBaseConfig>;
+ newConfig: Partial<Layer['config']>;
};
/**
* Update layer base config: dataId, label, column, isVisible
@@ -184,7 +184,7 @@ export function layerTypeChange(
}
export type LayerVisualChannelConfigChangeUpdaterAction = {
oldLayer: Layer;
- newConfig: Partial<LayerBaseConfig>;
+ newConfig: Partial<Layer['config']>;
channel: string;
newVisConfig?: Partial<LayerVisConfig>;
};
diff --git a/src/components/src/common/color-legend.tsx b/src/components/src/common/color-legend.tsx
index ba94ec8b3..45f8c3e22 100644
--- a/src/components/src/common/color-legend.tsx
+++ b/src/components/src/common/color-legend.tsx
@@ -1,17 +1,20 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {ColorRange} from '@kepler.gl/types';
+import React, {useCallback, useMemo} from 'react';
+import styled, {css} from 'styled-components';
+
+import {SCALE_TYPES} from '@kepler.gl/constants';
import {Layer} from '@kepler.gl/layers';
-import {HexColor, MapState} from '@kepler.gl/types';
+import {ColorRange, HexColor, MapState} from '@kepler.gl/types';
import {
getLayerColorScale,
getLegendOfScale,
getVisualChannelScaleByZoom,
+ colorMapToCategoricalColorBreaks,
isObject
} from '@kepler.gl/utils';
-import React, {useCallback, useMemo} from 'react';
-import styled, {css} from 'styled-components';
+
import {Reset} from './icons';
import {InlineInput} from './styled-components';
@@ -203,7 +206,7 @@ type OverrideByCustomLegendOptions = {
/**
* Original Legends
*/
- currentLegends: ReturnType<typeof getLegendOfScale>;
+ currentLegends?: ReturnType<typeof getLegendOfScale>;
};
/**
@@ -243,10 +246,22 @@ export function useLayerColorLegends(
[scale, layer, mapState]
);
- const currentLegends = useMemo(
- () => getLegendOfScale({scale: scaleByZoom, scaleType, labelFormat, fieldType}),
- [scaleByZoom, scaleType, labelFormat, fieldType]
- );
+ const currentLegends = useMemo(() => {
+ if (scaleType === SCALE_TYPES.customOrdinal && range?.colorMap) {
+ const colorBreaks = colorMapToCategoricalColorBreaks(range.colorMap);
+ return colorBreaks?.map(cb => {
+ return {
+ data: cb.data,
+ label: Array.isArray(cb.label)
+ ? cb.label.length > 5
+ ? `${cb.label.length} selected`
+ : cb.label
+ : cb.label || ''
+ };
+ });
+ }
+ return getLegendOfScale({scale: scaleByZoom, scaleType, labelFormat, fieldType});
+ }, [range, scaleByZoom, scaleType, labelFormat, fieldType]);
const LegendsWithCustomLegends = useMemo(
() =>
@@ -257,7 +272,7 @@ export function useLayerColorLegends(
[range?.colorLegends, currentLegends]
);
- return LegendsWithCustomLegends;
+ return LegendsWithCustomLegends || [];
}
export type ColorLegendProps = {
diff --git a/src/components/src/common/item-selector/chickleted-input.tsx b/src/components/src/common/item-selector/chickleted-input.tsx
index 5a03a8c12..ed2b74f40 100644
--- a/src/components/src/common/item-selector/chickleted-input.tsx
+++ b/src/components/src/common/item-selector/chickleted-input.tsx
@@ -25,7 +25,7 @@ interface ChickletedInputProps {
error?: boolean;
placeholder?: string;
inputTheme?: string;
- CustomChickletComponent?: ElementType;
+ CustomChickletComponent?: ElementType | null;
className?: string;
reorderItems?: (newOrder: any) => void;
}
diff --git a/src/components/src/common/styled-components.tsx b/src/components/src/common/styled-components.tsx
index 9a6633654..796364a00 100644
--- a/src/components/src/common/styled-components.tsx
+++ b/src/components/src/common/styled-components.tsx
@@ -148,7 +148,8 @@ export const SidePanelDivider = styled.div.attrs({
height: ${props => props.theme.sidepanelDividerHeight}px;
`;
-export const Tooltip = styled(ReactTooltip)`
+type TooltipProps = {interactive?: boolean};
+export const Tooltip = styled(ReactTooltip)<TooltipProps>`
&.__react_component_tooltip {
font-size: ${props => props.theme.tooltipFontSize};
font-weight: 400;
@@ -199,6 +200,7 @@ export type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & {
disabled?: boolean;
width?: string;
inactive?: boolean;
+ size?: string;
};
// this needs to be an actual button to be able to set disabled attribute correctly
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.tsx
index 58a9a4360..af8ac1fc5 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
@@ -1,12 +1,12 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React from 'react';
+import React, {useCallback} 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 {ColorUI, Field, LayerVisConfig, NestedPartial} from '@kepler.gl/types';
import DimensionScaleSelectorFactory from './dimension-scale-selector';
import VisConfigByFieldSelectorFactory from './vis-config-by-field-selector';
@@ -22,12 +22,7 @@ export type ChannelByValueSelectorProps = {
fields: Field[];
dataset: KeplerTable | undefined;
description?: string;
- setColorUI: (
- prop: string,
- newConfig: {
- [key in keyof ColorUI]: ColorUI[keyof ColorUI];
- }
- ) => void;
+ setColorUI: (prop: string, newConfig: NestedPartial<ColorUI>) => void;
updateLayerVisConfig: (newConfig: Partial<LayerVisConfig>) => void;
disabled?: boolean;
};
@@ -58,6 +53,12 @@ export function ChannelByValueSelectorFactory(
const supportedFields = fields.filter(({type}) => channelSupportedFieldTypes.includes(type));
const showScale = !layer.isAggregated && layer.config[scale] && layer.config[field];
const defaultDescription = 'layerConfiguration.defaultDescription';
+ const updateField = useCallback(
+ val => {
+ onChange({[field]: val}, key);
+ },
+ [onChange, field, key]
+ );
return (
<div className="channel-by-value-selector">
@@ -70,7 +71,7 @@ export function ChannelByValueSelectorFactory(
disabled={disabled}
placeholder={defaultMeasure || 'placeholder.selectField'}
selectedField={layer.config[field]}
- updateField={val => onChange({[field]: val}, key)}
+ updateField={updateField}
/>
{showScale && !disabled ? (
<DimensionScaleSelector
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.tsx
index 54cc2ce8e..521861e6f 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,15 +1,16 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
+import {toArray} from '@kepler.gl/common-utils';
import {SCALE_TYPES} from '@kepler.gl/constants';
import {KeplerTable} from '@kepler.gl/table';
-import {Bin, ColorUI, Field} from '@kepler.gl/types';
+import {Bin, ColorMap, ColorUI, Field} from '@kepler.gl/types';
import {
ColorBreak,
ColorBreakOrdinal,
colorBreaksToColorMap,
colorMapToColorBreaks,
- isNumericColorBreaks
+ isNumericColorBreaks as notOrdinalColorBreaks
} from '@kepler.gl/utils';
import React, {useCallback, useMemo} from 'react';
import styled from 'styled-components';
@@ -20,6 +21,7 @@ import CustomPaletteFactory, {
ColorPaletteItem,
ColorSwatch,
EditableColorRange,
+ CategoricalSelector,
SetColorUIFunc
} from './custom-palette';
@@ -52,7 +54,7 @@ export type ColorBreaksDisplayProps = {
};
export const ColorBreaksDisplay: React.FC<ColorBreaksDisplayProps> = ({currentBreaks, onEdit}) => {
- if (!isNumericColorBreaks(currentBreaks)) {
+ if (!notOrdinalColorBreaks(currentBreaks)) {
// don't display color breaks for ordinal breaks, user can change it in custom breaks
return null;
}
@@ -76,9 +78,35 @@ export const ColorBreaksDisplay: React.FC<ColorBreaksDisplayProps> = ({currentBr
);
};
-/**
- * ColorBreaksPanelProps
- */
+export type CategoricalColorDisplayProps = {
+ colorMap?: ColorMap;
+ onEdit: (() => void) | null;
+};
+
+export const CategoricalColorDisplay: React.FC<CategoricalColorDisplayProps> = ({
+ colorMap,
+ onEdit
+}: CategoricalColorDisplayProps) => {
+ return (
+ <StyledColorBreaksDisplay>
+ {onEdit ? <EditButton onClickEdit={onEdit} /> : null}
+ {colorMap?.map((cm, index) => (
+ <ColorPaletteItem className="disabled" key={index}>
+ <div className="custom-palette-input__left">
+ <ColorSwatch color={cm[1]} />
+ <CategoricalSelector
+ index={index}
+ selectedValues={toArray(cm[0])}
+ allValues={[]}
+ editable={false}
+ />
+ </div>
+ </ColorPaletteItem>
+ ))}
+ </StyledColorBreaksDisplay>
+ );
+};
+
export type ColorBreaksPanelProps = {
colorBreaks: ColorBreak[] | ColorBreakOrdinal[] | null;
colorUIConfig: ColorUI;
@@ -89,6 +117,7 @@ export type ColorBreaksPanelProps = {
filteredBins: Bin[];
isFiltered: boolean;
histogramDomain: number[];
+ ordinalDomain: number[] | string[];
setColorUI: SetColorUIFunc;
onScaleChange: (v: string, visConfg?: Record<string, any>) => void;
onApply: (e: React.MouseEvent) => void;
@@ -101,6 +130,7 @@ function ColorBreaksPanelFactory(
CustomPalette: ReturnType<typeof CustomPaletteFactory>,
ColumnStatsChart: ReturnType<typeof ColumnStatsChartFactory>
): React.FC<ColorBreaksPanelProps> {
+ // eslint-disable-next-line complexity
const ColorBreaksPanel: React.FC<ColorBreaksPanelProps> = ({
colorBreaks,
colorUIConfig,
@@ -111,6 +141,7 @@ function ColorBreaksPanelFactory(
filteredBins,
isFiltered,
histogramDomain,
+ ordinalDomain,
setColorUI,
onScaleChange,
onApply,
@@ -173,7 +204,7 @@ function ColorBreaksPanelFactory(
return (
<ColorBreaksPanelWrapper>
- {dataset && allBins.length > 1 ? (
+ {dataset && allBins.length > 1 && notOrdinalColorBreaks(colorBreaks) ? (
<ColumnStatsChart
colorField={colorField}
dataset={dataset}
@@ -188,17 +219,25 @@ function ColorBreaksPanelFactory(
<StyledColorBreaksPanel>
{isEditingCustomBreaks ? (
<CustomPalette
+ ordinalDomain={ordinalDomain}
customPalette={customPalette}
setColorPaletteUI={setColorUI}
showSketcher={showSketcher}
onApply={onApply}
onCancel={onCilckCancel}
/>
- ) : currentBreaks && allBins.length > 1 ? (
+ ) : currentBreaks && allBins.length > 1 && notOrdinalColorBreaks(colorBreaks) ? (
<ColorBreaksDisplay
currentBreaks={currentBreaks}
onEdit={isCustomBreaks ? onClickEditCustomBreaks : null}
/>
+ ) : customPalette.colorMap &&
+ customPalette.type === 'customOrdinal' &&
+ customPalette.name?.endsWith(colorField.name) ? (
+ <CategoricalColorDisplay
+ colorMap={customPalette.colorMap}
+ onEdit={isCustomBreaks ? onClickEditCustomBreaks : null}
+ />
) : null}
</StyledColorBreaksPanel>
</ColorBreaksPanelWrapper>
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.tsx
index 29791bfb6..bc17d1b87 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
@@ -7,11 +7,11 @@ import styled from 'styled-components';
import {ALL_FIELD_TYPES, SCALE_TYPES} from '@kepler.gl/constants';
import {AggregatedBin, Layer, VisualChannelDomain} from '@kepler.gl/layers';
import {KeplerTable} from '@kepler.gl/table';
-import {ColorRange, ColorUI, Field, NestedPartial} from '@kepler.gl/types';
+import {ColorRange, ColorUI, Field} from '@kepler.gl/types';
import {
- colorBreaksToColorMap,
getLayerColorScale,
getLegendOfScale,
+ initCustomPaletteByCustomScale,
histogramFromValues,
histogramFromThreshold,
getHistogramDomain,
@@ -56,6 +56,7 @@ export type ColorScaleSelectorProps = {
displayOption: string;
getOptionValue: string;
aggregatedBins?: AggregatedBin[];
+ channelKey: string;
};
const DropdownPropContext = React.createContext({});
@@ -136,6 +137,7 @@ function ColorScaleSelectorFactory(
range,
setColorUI,
colorUIConfig,
+ channelKey,
...dropdownSelectProps
}) => {
const displayOption = Accessor.generateOptionToStringFor(dropdownSelectProps.displayOption);
@@ -192,6 +194,10 @@ function ColorScaleSelectorFactory(
return getHistogramDomain({aggregatedBins, columnStats, dataset, fieldValueAccessor});
}, [dataset, fieldValueAccessor, aggregatedBins, columnStats]);
+ const ordinalDomain = useMemo(() => {
+ return layer.config[layer.visualChannels[channelKey].domain] || [];
+ }, [channelKey, layer.config, layer.visualChannels]);
+
const isFiltered = aggregatedBins
? false
: dataset.filteredIndexForDomain.length !== dataset.allIndexes.length;
@@ -215,19 +221,15 @@ function ColorScaleSelectorFactory(
const onSelectScale = useCallback(
val => {
// highlight selected option
- if (getOptionValue(val) === SCALE_TYPES.custom) {
- // update custom breaks
- const customPalette: NestedPartial<ColorRange> = {
- name: 'color.customPalette',
- type: 'custom',
- category: 'Custom',
- colors: range.colors,
- colorMap: range.colorMap
- ? range.colorMap
- : colorBreaks
- ? colorBreaksToColorMap(colorBreaks)
- : null
- };
+ if (!val || isEditingColorBreaks) return;
+ const selectedScale = getOptionValue(val);
+ if (selectedScale === SCALE_TYPES.custom) {
+ const customPalette = initCustomPaletteByCustomScale({
+ scale: selectedScale,
+ field,
+ range,
+ colorBreaks
+ });
setColorUI({
showColorChart: true,
colorRangeConfig: {
@@ -235,39 +237,31 @@ function ColorScaleSelectorFactory(
},
customPalette
});
- onSelect(SCALE_TYPES.custom, customPalette);
- } else {
+ onSelect(selectedScale, customPalette);
+ } else if (hasColorMap(range) && selectedScale !== SCALE_TYPES.customOrdinal) {
// not custom
- if (isEditingColorBreaks) {
- setColorUI({
- colorRangeConfig: {
- customBreaks: false
- }
- });
- }
- if (hasColorMap(range)) {
- // remove custom breaks
- // eslint-disable-next-line no-unused-vars
- const {colorMap: _, ...newRange} = range;
- onSelect(getOptionValue(val), newRange);
- } else {
- onSelect(getOptionValue(val));
- }
+ // remove colorMap
+ // eslint-disable-next-line no-unused-vars
+ const {colorMap: _, ...newRange} = range;
+ onSelect(selectedScale, newRange);
+ } else {
+ onSelect(selectedScale);
}
},
- [setColorUI, onSelect, range, getOptionValue, isEditingColorBreaks, colorBreaks]
+ [isEditingColorBreaks, field, setColorUI, onSelect, range, getOptionValue, colorBreaks]
);
const onApply = useCallback(() => {
- onSelect(SCALE_TYPES.custom, colorUIConfig.customPalette);
+ onSelect(scaleType, colorUIConfig.customPalette);
hideTippy(tippyInstance);
- }, [onSelect, colorUIConfig.customPalette, tippyInstance]);
+ }, [onSelect, colorUIConfig.customPalette, tippyInstance, scaleType]);
const onCancel = useCallback(() => {
hideTippy(tippyInstance);
}, [tippyInstance]);
- const isCustomBreaks = scaleType === SCALE_TYPES.custom;
+ const isCustomBreaks =
+ scaleType === SCALE_TYPES.custom || scaleType === SCALE_TYPES.customOrdinal;
return (
<DropdownPropContext.Provider
@@ -282,6 +276,7 @@ function ColorScaleSelectorFactory(
filteredBins,
isFiltered,
histogramDomain,
+ ordinalDomain,
onScaleChange: onSelect,
onApply,
onCancel
diff --git a/src/components/src/side-panel/layer-panel/custom-palette.tsx b/src/components/src/side-panel/layer-panel/custom-palette.tsx
index a5f2f048e..24d7357c8 100644
--- a/src/components/src/side-panel/layer-panel/custom-palette.tsx
+++ b/src/components/src/side-panel/layer-panel/custom-palette.tsx
@@ -11,6 +11,7 @@ import React, {
useRef,
useState
} from 'react';
+import uniq from 'lodash.uniq';
import {
SortableContainer,
SortableContainerProps,
@@ -20,13 +21,24 @@ import {
} from 'react-sortable-hoc';
import styled, {StyledComponent, css} from 'styled-components';
import Portaled from '../../common/portaled';
+import {Tooltip} from '../../common/styled-components';
+import Typeahead from '../../common/item-selector/typeahead';
+import ChickletedInput from '../../common/item-selector/chickleted-input';
+import DropdownList, {ListItem} from '../../common/item-selector/dropdown-list';
+import {toArray} from '@kepler.gl/common-utils';
import {KeyEvent} from '@kepler.gl/constants';
import {ColorMap, ColorUI, HexColor, NestedPartial} from '@kepler.gl/types';
-import {colorMapToColorBreaks, isNumericColorBreaks} from '@kepler.gl/utils';
import {
+ addCategoricalValuesToColorMap,
addCustomPaletteColor,
+ colorMapToCategoricalColorBreaks,
+ colorMapToColorBreaks,
+ isNumericColorBreaks,
+ resetCategoricalColorMapByIndex,
+ removeCategoricalValueFromColorMap,
removeCustomPaletteColor,
+ selectRestCategoricalColorMapByIndex,
sortCustomPaletteColor,
updateCustomPaletteColor
} from '@kepler.gl/utils';
@@ -59,6 +71,7 @@ export type CustomPaletteProps = {
customPalette: ColorUI['customPalette'];
setColorPaletteUI: SetColorUIFunc;
showSketcher: number | boolean;
+ ordinalDomain?: string[] | number[];
actionIcons?: ActionIcons;
onApply: (e: React.MouseEvent) => void;
onCancel: () => void;
@@ -171,6 +184,19 @@ const StyledButtonContainer = styled.div`
padding: 0 12px;
`;
+const StyledAddStepContainer = styled.div`
+ margin-top: 11px;
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-start;
+ align-items: center;
+ padding: 0 12px;
+ color: ${props => props.theme.inputColor};
+ .addcolor {
+ margin-top: 4px;
+ }
+`;
+
const StyledInput = styled(
Input as StyledComponent<'input', any, {width: string; textAlign: string; disabled: boolean}, any>
)`
@@ -421,6 +447,317 @@ export const CustomPaletteInput: React.FC<CustomPaletteInputProps> = ({
);
};
+const StyledCategoricalValuePickerWrapper = styled.div.attrs({
+ className: 'categorical-value-picker'
+})`
+ width: 150px;
+ color: ${props => props.theme.inputColor};
+ display: flex;
+ flex-direction: row;
+ justify-content: flex-end;
+ column-gap: 8px;
+ align-items: center;
+ cursor: pointer;
+`;
+
+type StyledCategoricalValuePickerProps = {noBorder: boolean};
+const StyledCategoricalValuePicker = styled.div<StyledCategoricalValuePickerProps>`
+ width: fit-content;
+ font-size: 11px;
+ border-bottom: ${props => (props.noBorder ? '' : '1px dashed')};
+ cursor: pointer;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ overflow: hidden;
+ max-width: 100px;
+`;
+
+type DropdownValuesWrapperProps = {width: number};
+const DropdownValuesWrapper = styled.div<DropdownValuesWrapperProps>`
+ border: 0;
+ width: 100%;
+ left: 0;
+ z-index: ${props => props.theme.dropdownWrapperZ};
+ width: ${props => props.width}px;
+`;
+
+type SelectedValuesWrapperProps = {width: number; height: number};
+const SelectedValuesWrapper = styled(DropdownValuesWrapper)<SelectedValuesWrapperProps>`
+ width: ${props => props.width}px;
+ max-height: ${props => props.height}px;
+ overflow: auto;
+
+ .custom-palette-chickleted-input {
+ padding: 8px;
+ background-color: ${props => props.theme.dropdownWrapperZ};
+ }
+`;
+
+const StyledDropdownHeader = styled.div`
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ color: ${props => props.theme.inputColor};
+ padding: 0 8px;
+ font-size: 10px;
+
+ .button {
+ margin: 0;
+ padding: 0;
+ width: fit-content;
+ }
+`;
+
+const StyledTooltipContent = styled.div`
+ padding: 8px;
+ width: 150px;
+ box-sizing: border-box;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+
+ div {
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ }
+`;
+
+const NUMBER_VALUES_IN_TOOLTIP = 10;
+
+const CategoricalSelectorContext = React.createContext({
+ onSelectRest: () => null,
+ onReset: () => null
+});
+
+// Categorical values dropdownlist:
+// extending DropdownList and adding 'Select the Rest' and 'Reset' buttons
+class ModifiedDropdownList extends DropdownList {
+ constructor(props) {
+ super(props);
+ }
+
+ render() {
+ return (
+ <>
+ <CategoricalSelectorContext.Consumer>
+ {context => (
+ <>
+ <StyledDropdownHeader>
+ <Button link size="smal" onClick={context.onSelectRest}>
+ Select the Rest
+ </Button>
+ <Button link size="smal" onClick={context.onReset}>
+ Reset
+ </Button>
+ </StyledDropdownHeader>
+ <DividerLine />
+ <DropdownList {...this.props} />
+ </>
+ )}
+ </CategoricalSelectorContext.Consumer>
+ </>
+ );
+ }
+}
+
+export type CategoricalSelectorProps = {
+ index: number;
+ selectedValues: (string | number | null)[];
+ allValues: string[] | number[];
+ addColorMapValue?: (v: (number | string | null)[], i: number) => void;
+ removeColorMapValue?: (v: number | string, i: number) => void;
+ resetColorMapValue?: (i: number) => void;
+ selectRestColorMapValue?: (i: number) => void;
+ editable?: boolean;
+};
+
+// Categorical values selector for editing categorical values
+export const CategoricalSelector: React.FC<CategoricalSelectorProps> = ({
+ index,
+ selectedValues,
+ allValues,
+ addColorMapValue,
+ removeColorMapValue,
+ resetColorMapValue,
+ selectRestColorMapValue,
+ editable = true
+}: CategoricalSelectorProps) => {
+ const [showTypeahead, setShowTypeahead] = useState(false);
+
+ const onOptionSelected = useCallback(
+ value => {
+ const previousSelected = toArray(selectedValues);
+ const items = uniq(previousSelected.concat(toArray(value)));
+ addColorMapValue?.(items, index);
+ },
+ [selectedValues, index, addColorMapValue]
+ );
+
+ const onOpenDropdown = useCallback(() => {
+ setShowTypeahead(true);
+ }, []);
+
+ const onCloseDropdown = useCallback(() => {
+ setShowTypeahead(false);
+ }, []);
+
+ const onRemoveItem = useCallback(
+ value => {
+ removeColorMapValue?.(value, index);
+ },
+ [index, removeColorMapValue]
+ );
+
+ const onReset = useCallback(() => {
+ resetColorMapValue?.(index);
+ setShowTypeahead(false);
+ return null;
+ }, [resetColorMapValue, index]);
+
+ const onSelectRest = useCallback(() => {
+ selectRestColorMapValue?.(index);
+ setShowTypeahead(false);
+ return null;
+ }, [selectRestColorMapValue, index]);
+
+ return (
+ <StyledCategoricalValuePickerWrapper>
+ {editable && <Add height="12px" onClick={onOpenDropdown} />}
+ <StyledCategoricalValuePicker
+ noBorder={selectedValues.length === 0 || !editable}
+ onClick={onOpenDropdown}
+ data-tip
+ data-for={`category-values-${index}`}
+ >
+ {selectedValues.length === 0
+ ? 'Add Value'
+ : selectedValues.length === 1
+ ? selectedValues[0]
+ : `${selectedValues.length} selected`}
+ {selectedValues.length > 1 && (
+ <Tooltip id={`category-values-${index}`} place="top" interactive={true}>
+ <StyledTooltipContent>
+ {selectedValues.slice(0, NUMBER_VALUES_IN_TOOLTIP).map((value, i) => (
+ <div key={i}>{value}</div>
+ ))}
+ {selectedValues.length > NUMBER_VALUES_IN_TOOLTIP && <div>...</div>}
+ </StyledTooltipContent>
+ </Tooltip>
+ )}
+ </StyledCategoricalValuePicker>
+ {editable && (
+ <Portaled left={0} top={0} isOpened={showTypeahead} onClose={onCloseDropdown}>
+ {selectedValues.length > 1 && (
+ <SelectedValuesWrapper width={250} height={200}>
+ <ChickletedInput
+ className={'custom-palette-chickleted-input'}
+ selectedItems={selectedValues}
+ placeholder={''}
+ removeItem={onRemoveItem}
+ onClick={() => null}
+ CustomChickletComponent={null}
+ />
+ </SelectedValuesWrapper>
+ )}
+ <DropdownValuesWrapper width={250}>
+ <div style={{position: 'relative'}}>
+ <CategoricalSelectorContext.Provider
+ value={{
+ onReset,
+ onSelectRest
+ }}
+ >
+ <Typeahead
+ customClasses={{
+ results: 'list-selector',
+ input: 'typeahead__input',
+ listItem: 'list__item',
+ listAnchor: 'list__item__anchor'
+ }}
+ options={allValues}
+ placeholder={'Search'}
+ onOptionSelected={onOptionSelected}
+ customListComponent={ModifiedDropdownList}
+ customListItemComponent={ListItem}
+ searchable={true}
+ showOptionsWhenEmpty
+ selectedItems={selectedValues}
+ />
+ </CategoricalSelectorContext.Provider>
+ </div>
+ </DropdownValuesWrapper>
+ </Portaled>
+ )}
+ </StyledCategoricalValuePickerWrapper>
+ );
+};
+
+export type CategoricalCustomPaletteInputProps = {
+ index: number;
+ isSorting: boolean;
+ color: HexColor;
+ colorMap?: ColorMap | null;
+ addColorMapValue: (v: (number | string | null)[], i: number) => void;
+ removeColorMapValue: (v: number | string, i: number) => void;
+ resetColorMapValue: (i: number) => void;
+ selectRestColorMapValue: (i: number) => void;
+ actionIcons?: ActionIcons;
+ onDelete: (index: number) => void;
+ onAdd: (index: number) => void;
+ onToggleSketcher: (index: number) => void;
+ allValues: string[] | number[];
+};
+
+export const CategoricalCustomPaletteInput: React.FC<CategoricalCustomPaletteInputProps> = ({
+ index,
+ isSorting,
+ color,
+ colorMap,
+ actionIcons = defaultActionIcons,
+ onDelete,
+ onAdd,
+ onToggleSketcher,
+ addColorMapValue,
+ removeColorMapValue,
+ resetColorMapValue,
+ selectRestColorMapValue,
+ allValues
+}: CategoricalCustomPaletteInputProps) => {
+ const selectedValues: (number | string | null)[] = useMemo(() => {
+ if (!colorMap) return [];
+ const value = colorMap[index][0];
+ const values = Array.isArray(value) ? value : value !== null ? [value] : [];
+ return values;
+ }, [colorMap, index]);
+
+ const onClickSwtach = useCallback(() => onToggleSketcher(index), [onToggleSketcher, index]);
+ const onColorDelete = useCallback(() => onDelete(index), [onDelete, index]);
+
+ return (
+ <SortableItem index={index} isSorting={isSorting}>
+ <div className="custom-palette-input__left">
+ <DragHandle className="layer__drag-handle">
+ <actionIcons.sort height="20px" />
+ </DragHandle>
+ <ColorSwatch color={color} onClick={onClickSwtach} />
+ {colorMap && colorMap[index] && (
+ <CategoricalSelector
+ selectedValues={selectedValues}
+ allValues={allValues}
+ addColorMapValue={addColorMapValue}
+ removeColorMapValue={removeColorMapValue}
+ resetColorMapValue={resetColorMapValue}
+ selectRestColorMapValue={selectRestColorMapValue}
+ index={index}
+ />
+ )}
+ </div>
+ <div className="custom-palette-input__right">
+ <DeleteColorStop onColorDelete={onColorDelete} IconComponent={actionIcons.delete} />
+ </div>
+ </SortableItem>
+ );
+};
+
export const BottomAction = ({onCancel, onConfirm}) => (
<StyledButtonContainer>
<Button className="confirm-apply__button" small onClick={onConfirm}>
@@ -440,6 +777,7 @@ const StyledCustomPalette = styled.div.attrs({
function CustomPaletteFactory(): React.FC<CustomPaletteProps> {
const CustomPalette: React.FC<CustomPaletteProps> = ({
+ ordinalDomain,
customPalette,
setColorPaletteUI,
showSketcher,
@@ -450,8 +788,13 @@ function CustomPaletteFactory(): React.FC<CustomPaletteProps> {
const [isSorting, setIsSorting] = useState(false);
const {colors, colorMap} = customPalette;
const colorBreaks = useMemo(
- () => (colorMap ? colorMapToColorBreaks(colorMap) : null),
- [colorMap]
+ () =>
+ colorMap
+ ? customPalette.type === 'custom'
+ ? colorMapToColorBreaks(colorMap)
+ : colorMapToCategoricalColorBreaks(colorMap)
+ : null,
+ [customPalette.type, colorMap]
);
const onPickerUpdate = useCallback(
@@ -498,6 +841,10 @@ function CustomPaletteFactory(): React.FC<CustomPaletteProps> {
[customPalette, setColorPaletteUI]
);
+ const onAddCategoricalStep = useCallback(() => {
+ onAdd(colors.length - 1);
+ }, [colors.length, onAdd]);
+
const onSwatchClose = useCallback(() => {
onToggleSketcher(false);
}, [onToggleSketcher]);
@@ -565,6 +912,70 @@ function CustomPaletteFactory(): React.FC<CustomPaletteProps> {
[setColorPaletteUI, customPalette]
);
+ // remove a selected category item from a color map
+ const removeCategoricalColorMapValue = useCallback(
+ (item, index) => {
+ if (!colorMap) {
+ return;
+ }
+ setColorPaletteUI({
+ customPalette: {
+ ...customPalette,
+ colorMap: removeCategoricalValueFromColorMap(colorMap, item, index)
+ }
+ });
+ },
+ [setColorPaletteUI, customPalette, colorMap]
+ );
+
+ // add selected categorical items to a color map
+ const addCategoricalColorMapValue = useCallback(
+ (items, index) => {
+ if (!colorMap) {
+ return;
+ }
+ setColorPaletteUI({
+ customPalette: {
+ ...customPalette,
+ colorMap: addCategoricalValuesToColorMap(colorMap, items, index)
+ }
+ });
+ },
+ [setColorPaletteUI, customPalette, colorMap]
+ );
+
+ // reset a color map
+ const resetCategoricalColorMapValue = useCallback(
+ index => {
+ if (!colorMap) {
+ return;
+ }
+ setColorPaletteUI({
+ customPalette: {
+ ...customPalette,
+ colorMap: resetCategoricalColorMapByIndex(colorMap, index)
+ }
+ });
+ },
+ [setColorPaletteUI, customPalette, colorMap]
+ );
+
+ // select the rest values for a color map
+ const selectRestCategoricalColorMap = useCallback(
+ index => {
+ if (!colorMap) {
+ return;
+ }
+ setColorPaletteUI({
+ customPalette: {
+ ...customPalette,
+ colorMap: selectRestCategoricalColorMapByIndex(colorMap, index, ordinalDomain)
+ }
+ });
+ },
+ [setColorPaletteUI, customPalette, colorMap, ordinalDomain]
+ );
+
return (
<StyledCustomPalette>
<WrappedSortableContainer
@@ -575,24 +986,53 @@ function CustomPaletteFactory(): React.FC<CustomPaletteProps> {
helperClass="sorting-colors"
useDragHandle
>
- {colors.map((color, index) => (
- <CustomPaletteInput
- key={index}
- colorBreaks={colorBreaks}
- index={index}
- isSorting={isSorting}
- color={color}
- inputColorHex={inputColorHex}
- disableAppend={colors.length >= 20}
- disableDelete={colors.length <= 2}
- actionIcons={actionIcons}
- onAdd={onAdd}
- onDelete={onDelete}
- onToggleSketcher={onToggleSketcher}
- editColorMapValue={editColorMapValue}
- />
- ))}
+ {colors.map((color, index) =>
+ customPalette.type === 'custom' ? (
+ <CustomPaletteInput
+ key={index}
+ colorBreaks={colorBreaks}
+ index={index}
+ isSorting={isSorting}
+ color={color}
+ inputColorHex={inputColorHex}
+ disableAppend={colors.length >= 20}
+ disableDelete={colors.length <= 2}
+ actionIcons={actionIcons}
+ onAdd={onAdd}
+ onDelete={onDelete}
+ onToggleSketcher={onToggleSketcher}
+ editColorMapValue={editColorMapValue}
+ />
+ ) : (
+ ordinalDomain && (
+ <CategoricalCustomPaletteInput
+ key={index}
+ colorMap={colorMap}
+ index={index}
+ isSorting={isSorting}
+ color={color}
+ actionIcons={actionIcons}
+ onAdd={onAdd}
+ onDelete={onDelete}
+ onToggleSketcher={onToggleSketcher}
+ addColorMapValue={addCategoricalColorMapValue}
+ removeColorMapValue={removeCategoricalColorMapValue}
+ resetColorMapValue={resetCategoricalColorMapValue}
+ selectRestColorMapValue={selectRestCategoricalColorMap}
+ allValues={ordinalDomain}
+ />
+ )
+ )
+ )}
</WrappedSortableContainer>
+ {customPalette.type === 'customOrdinal' && (
+ <StyledAddStepContainer>
+ <AddColorStop onColorAdd={onAddCategoricalStep} IconComponent={actionIcons.add} />
+ <Button link size="smal" onClick={onAddCategoricalStep}>
+ Add Step
+ </Button>
+ </StyledAddStepContainer>
+ )}
<DividerLine />
{/* Cancel or Confirm Buttons */}
<BottomAction onCancel={onCancel} onConfirm={onConfirm} />
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.tsx
index 896865691..3da373cbc 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
@@ -69,7 +69,8 @@ function DimensionScaleSelectorFactory(
searchable: false,
onChange: onSelect,
displayOption: 'label',
- getOptionValue: 'value'
+ getOptionValue: 'value',
+ channelKey: key
};
return (
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index a35102e46..ff69895cb 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -393,6 +393,7 @@ export type SCALE_TYPES_DEF = {
point: 'point';
threshold: 'threshold';
custom: 'custom';
+ customOrdinal: 'customOrdinal';
};
export const SCALE_TYPES: SCALE_TYPES_DEF = keyMirror({
@@ -404,6 +405,7 @@ export const SCALE_TYPES: SCALE_TYPES_DEF = keyMirror({
log: null,
threshold: null,
custom: null,
+ customOrdinal: null,
// ordinal domain to linear range
point: null
});
@@ -416,6 +418,7 @@ export const SCALE_TYPE_NAMES: {[key in keyof SCALE_TYPES_DEF]: string} = {
log: 'Log',
threshold: 'Threshold',
custom: 'Custom Breaks',
+ customOrdinal: 'Custom Ordinal',
point: 'Point'
};
@@ -432,7 +435,8 @@ export const SCALE_FUNC = {
[SCALE_TYPES.log]: scaleLog,
[SCALE_TYPES.point]: scalePoint,
[SCALE_TYPES.threshold]: scaleThreshold,
- [SCALE_TYPES.custom]: scaleThreshold
+ [SCALE_TYPES.custom]: scaleThreshold,
+ [SCALE_TYPES.customOrdinal]: scaleOrdinal
};
export const ALL_FIELD_TYPES = keyMirror({
@@ -666,7 +670,7 @@ export const linearFieldAggrScaleFunctions = {
};
export const ordinalFieldScaleFunctions = {
- [CHANNEL_SCALES.color]: [SCALE_TYPES.ordinal],
+ [CHANNEL_SCALES.color]: [SCALE_TYPES.ordinal, SCALE_TYPES.customOrdinal],
[CHANNEL_SCALES.radius]: [SCALE_TYPES.point],
[CHANNEL_SCALES.size]: [SCALE_TYPES.point]
};
@@ -753,7 +757,13 @@ export const FIELD_OPTS = {
[ALL_FIELD_TYPES.integer]: {
type: 'numerical',
scale: {
- ...linearFieldScaleFunctions,
+ ...{
+ ...linearFieldScaleFunctions,
+ [CHANNEL_SCALES.color]: [
+ ...linearFieldScaleFunctions[CHANNEL_SCALES.color],
+ SCALE_TYPES.customOrdinal
+ ]
+ },
...linearFieldAggrScaleFunctions
},
format: {
diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.ts
index 212aa2a9f..a5517e067 100644
--- a/src/layers/src/base-layer.ts
+++ b/src/layers/src/base-layer.ts
@@ -73,6 +73,7 @@ import {
import {
getScaleFunction,
initializeLayerColorMap,
+ getCategoricalColorScale,
updateCustomColorRangeByColorUI
} from '@kepler.gl/utils';
import memoize from 'lodash.memoize';
@@ -1030,6 +1031,10 @@ class Layer implements KeplerLayer {
colorDomain: VisualChannelDomain,
colorRange: ColorRange
): GetVisChannelScaleReturnType {
+ if (colorScale === SCALE_TYPES.customOrdinal) {
+ return getCategoricalColorScale(colorDomain, colorRange);
+ }
+
if (hasColorMap(colorRange) && colorScale === SCALE_TYPES.custom) {
const cMap = new Map();
colorRange.colorMap?.forEach(([k, v]) => {
@@ -1041,7 +1046,7 @@ class Layer implements KeplerLayer {
const scale = getScaleFunction(scaleType, cMap.values(), cMap.keys(), false);
scale.unknown(cMap.get(UNKNOWN_COLOR_KEY) || NO_VALUE_COLOR);
- return scale as () => any;
+ return scale as GetVisChannelScaleReturnType;
}
return this.getVisChannelScale(colorScale, colorDomain, colorRange.colors.map(hexToRgb));
}
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index c09d02ff9..6c628aea0 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -86,7 +86,9 @@ import {
MAX_DEFAULT_TOOLTIPS,
PLOT_TYPES,
SORT_ORDER,
- SYNC_TIMELINE_MODES
+ SYNC_TIMELINE_MODES,
+ CHANNEL_SCALES,
+ SCALE_TYPES
} from '@kepler.gl/constants';
import {LAYER_ID_LENGTH, Layer, LayerClasses} from '@kepler.gl/layers';
import {
@@ -144,7 +146,8 @@ import {
getDefaultTimeFormat,
LayerToFilterTimeInterval,
TIME_INTERVALS_ORDERED,
- mergeFilterDomain
+ mergeFilterDomain,
+ initCustomPaletteByCustomScale
} from '@kepler.gl/utils';
import {createEffect} from '@kepler.gl/effects';
import {PayloadAction} from '@reduxjs/toolkit';
@@ -958,6 +961,7 @@ export function layerVisualChannelChangeUpdater(
if (!oldLayer.config.dataId) {
return state;
}
+
const dataset = state.datasets[oldLayer.config.dataId];
const idx = state.layers.findIndex(l => l.id === oldLayer.id);
@@ -967,11 +971,50 @@ export function layerVisualChannelChangeUpdater(
newLayer.updateLayerVisualChannel(dataset, channel);
// calling update animation domain first to merge all layer animation domain
- const updatedState = updateAnimationDomain(state);
+ let updatedState = updateAnimationDomain(state);
+
+ const visualChannel = oldLayer.visualChannels[channel];
+ if (visualChannel?.channelScaleType === CHANNEL_SCALES.color && newConfig[visualChannel.field]) {
+ // if color field changed, set customBreaks to false
+ newLayer.updateLayerColorUI(visualChannel.range, {
+ colorRangeConfig: {
+ ...newLayer.config.colorUI[visualChannel.range].colorRangeConfig,
+ customBreaks: false
+ }
+ });
+
+ updatedState = {
+ ...updatedState,
+ layers: updatedState.layers.map(l => (l.id === oldLayer.id ? newLayer : l))
+ };
+ }
const oldLayerData = updatedState.layerData[idx];
const {layerData, layer} = calculateLayerData(newLayer, updatedState, oldLayerData);
+ if (
+ visualChannel?.channelScaleType === CHANNEL_SCALES.color &&
+ newConfig[visualChannel?.scale] === SCALE_TYPES.customOrdinal &&
+ !newVisConfig
+ ) {
+ // when switching to customOrdinal scale, create a customPalette in colorUI with updated colorDomain
+ const customPalette = initCustomPaletteByCustomScale({
+ scale: SCALE_TYPES.customOrdinal,
+ field: layer.config[visualChannel.field],
+ ordinalDomain: layer.config[layer.visualChannels[channel].domain],
+ range: layer.config.visConfig[visualChannel.range],
+ colorBreaks: null
+ });
+ // update colorRange with new customPalette
+ layer.updateLayerColorUI(visualChannel.range, {
+ showColorChart: true,
+ colorRangeConfig: {
+ ...layer.config.colorUI[visualChannel.range].colorRangeConfig,
+ customBreaks: true
+ },
+ customPalette
+ });
+ }
return updateStateWithLayerAndData(updatedState, {layerData, layer, idx});
}
diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.ts
index 742888b5c..ab51dfe4d 100644
--- a/src/table/src/kepler-table.ts
+++ b/src/table/src/kepler-table.ts
@@ -481,6 +481,7 @@ class KeplerTable<F extends Field = Field> {
switch (scaleType) {
case SCALE_TYPES.ordinal:
+ case SCALE_TYPES.customOrdinal:
case SCALE_TYPES.point:
// do not recalculate ordinal domain based on filtered data
// don't need to update ordinal domain every time
@@ -495,6 +496,7 @@ class KeplerTable<F extends Field = Field> {
case SCALE_TYPES.quantize:
case SCALE_TYPES.linear:
case SCALE_TYPES.sqrt:
+ case SCALE_TYPES.custom:
default:
return getLinearDomain(filteredIndexForDomain, indexValueAccessor);
}
diff --git a/src/types/layers.d.ts b/src/types/layers.d.ts
index 816dbe214..bbdf112d5 100644
--- a/src/types/layers.d.ts
+++ b/src/types/layers.d.ts
@@ -178,7 +178,7 @@ export type ColorRangeConfig = {
colorBlindSafe: boolean;
};
-export type ColorMap = [string[] | string | number | null, HexColor][];
+export type ColorMap = [string[] | number[] | string | number | null, HexColor][];
// Key is HexColor but as key we can use only string
export type ColorLegends = {[key: HexColor]: string};
diff --git a/src/utils/src/color-utils.ts b/src/utils/src/color-utils.ts
index 73a50d67a..5faffb5cc 100644
--- a/src/utils/src/color-utils.ts
+++ b/src/utils/src/color-utils.ts
@@ -12,7 +12,7 @@ import {rgb as d3Rgb} from 'd3-color';
import {interpolate} from 'd3-interpolate';
import {arrayInsert, arrayMove} from './utils';
import Console from 'global/console';
-import {KEPLER_COLOR_PALETTES, PALETTE_TYPES} from '@kepler.gl/constants';
+import {KEPLER_COLOR_PALETTES, PALETTE_TYPES, SCALE_TYPES} from '@kepler.gl/constants';
/**
* get r g b from hex code
@@ -134,6 +134,17 @@ export function interpolateHex(hex1: HexColor, hex2: HexColor): HexColor {
return d3Rgb(interpolate(hex1, hex2)(0.5)).hex().toUpperCase();
}
+function addNewCategoricalStepAtIndex(colorMap, index, newColor) {
+ if (!Array.isArray(colorMap) || !colorMap.length) {
+ return colorMap;
+ }
+
+ let newColorMap = colorMap.map(([val, c]) => [Array.isArray(val) ? [...val] : val, c]);
+ newColorMap = arrayInsert(newColorMap, index + 1, [null, newColor]);
+
+ return newColorMap;
+}
+
export function addNewQuantativeColorBreakAtIndex(colorMap, index, newColors) {
if (!Array.isArray(colorMap) || !colorMap.length) {
return colorMap;
@@ -177,7 +188,10 @@ export function addCustomPaletteColor(customPalette: ColorRange, index: number):
// add color to colorMap
if (colorMap) {
- update.colorMap = addNewQuantativeColorBreakAtIndex(colorMap, index, update.colors);
+ update.colorMap =
+ customPalette.type === 'customOrdinal'
+ ? addNewCategoricalStepAtIndex(colorMap, index, newColor)
+ : addNewQuantativeColorBreakAtIndex(colorMap, index, update.colors);
}
return {
@@ -456,5 +470,9 @@ export function initializeCustomPalette(colorRange: ColorRange, colorMap?: Color
...(colorMap ? {colorMap} : {})
};
+ // only customPalette.colors are needed for custom palette editor with custom ordinal scale
+ if (!colorMap && colorRange.type === SCALE_TYPES.customOrdinal) {
+ delete customPalette.colorMap;
+ }
return customPalette;
}
diff --git a/src/utils/src/data-scale-utils.ts b/src/utils/src/data-scale-utils.ts
index aeb52e4c2..495b728d5 100644
--- a/src/utils/src/data-scale-utils.ts
+++ b/src/utils/src/data-scale-utils.ts
@@ -2,11 +2,11 @@
// Copyright contributors to the kepler.gl project
import {bisectLeft, quantileSorted as d3Quantile, extent} from 'd3-array';
+import uniq from 'lodash.uniq';
import moment from 'moment';
-import {notNullorUndefined} from '@kepler.gl/common-utils';
-import {ALL_FIELD_TYPES, SCALE_FUNC, SCALE_TYPES} from '@kepler.gl/constants';
-// import {AggregatedBin, Layer, VisualChannel, VisualChannelDomain} from '@kepler.gl/layers';
+import {notNullorUndefined, toArray} from '@kepler.gl/common-utils';
+import {ALL_FIELD_TYPES, SCALE_FUNC, SCALE_TYPES, NO_VALUE_COLOR} from '@kepler.gl/constants';
// import {FilterProps, KeplerTable} from '@kepler.gl/layers';
import {
AggregatedBin,
@@ -16,10 +16,14 @@ import {
KeplerLayer as Layer,
MapState,
VisualChannel,
- VisualChannelDomain
+ VisualChannelDomain,
+ RGBColor,
+ RGBAColor,
+ ColorUI,
+ Field
} from '@kepler.gl/types';
-import {isRgbColor, rgbToHex} from './color-utils';
+import {isRgbColor, rgbToHex, hexToRgb} from './color-utils';
import {DataContainerInterface} from './data-container-interface';
import {formatNumber, isNumber, reverseFormatNumber, unique} from './data-utils';
import {getTimeWidgetHintFormatter} from './filter-utils';
@@ -33,7 +37,7 @@ export type ColorBreak = {
};
export type ColorBreakOrdinal = {
data: HexColor;
- label: string;
+ label: string | number | string[] | number[] | null;
};
export type D3ScaleFunction = Record<string, any> & ((x: any) => any);
@@ -294,7 +298,11 @@ export function getLegendOfScale({
if (!scale || scale.byZoom) {
return [];
}
- if (scaleType === SCALE_TYPES.ordinal) {
+ if (
+ scaleType === SCALE_TYPES.ordinal ||
+ scaleType === SCALE_TYPES.customOrdinal ||
+ fieldType === ALL_FIELD_TYPES.string
+ ) {
return getOrdinalLegends(scale);
}
@@ -367,6 +375,71 @@ export function getVisualChannelScaleByZoom({
return scale;
}
+/**
+ * Get categorical colorMap from colors and domain (unique values)
+ */
+export function getCategoricalColorMap(
+ colors: string[],
+ domain: (string | number | string[] | number[] | null)[]
+): any {
+ // colorMap: [string | string[], hexstring]
+ const colorToUniqueValues = {};
+ const uniqueValues = unique(domain).filter(notNullorUndefined).sort();
+ // each unique value assign to a color, the rest unique values assign to last color
+ const lastColor = colors[colors.length - 1];
+ for (let i = 0; i < uniqueValues.length; ++i) {
+ if (i < colors.length) {
+ colorToUniqueValues[colors[i]] = uniqueValues[i];
+ } else {
+ colorToUniqueValues[lastColor] = [
+ ...(Array.isArray(colorToUniqueValues[lastColor])
+ ? colorToUniqueValues[lastColor]
+ : [colorToUniqueValues[lastColor]]),
+ uniqueValues[i]
+ ];
+ }
+ }
+
+ const colorMap = colors.map(color => {
+ if (color in colorToUniqueValues) {
+ return [colorToUniqueValues[color], color];
+ }
+ return [null, color];
+ });
+
+ return colorMap;
+}
+
+/**
+ * Get categorical colorBreaks from colorMap
+ */
+export function colorMapToCategoricalColorBreaks(
+ colorMap?: ColorMap | null
+): ColorBreakOrdinal[] | null {
+ if (!colorMap) {
+ return null;
+ }
+ const colorBreaks = colorMap.map(([value, color], i) => {
+ return {
+ data: color,
+ label: value
+ };
+ });
+
+ return colorBreaks;
+}
+
+/**
+ * create categorical colorMap from colorBreaks
+ */
+export function colorBreaksToCategoricalColorMap(colorBreaks: ColorBreakOrdinal[]): ColorMap {
+ // colorMap: [string | string[], hexstring]
+ const colors = uniq(colorBreaks.map(cb => cb.data));
+ const values = uniq(colorBreaks.map(cb => cb.label));
+
+ return getCategoricalColorMap(colors, values);
+}
+
/**
* Convert color breaks UI input into colorRange.colorMap
*/
@@ -427,7 +500,7 @@ export function colorMapToColorBreaks(colorMap?: ColorMap | null): ColorBreak[]
* Whether color breaks is for numeric field
*/
export function isNumericColorBreaks(colorBreaks: unknown): colorBreaks is ColorBreak[] {
- return Array.isArray(colorBreaks) && colorBreaks.length && colorBreaks[0].inputs;
+ return Boolean(Array.isArray(colorBreaks) && colorBreaks.length && colorBreaks[0].inputs);
}
// return domainMin, domainMax, histogramMean
@@ -481,3 +554,183 @@ export function getHistogramDomain({
const histogramMean = nValid > 0 ? domainSum / nValid : 0;
return [nValid > 0 ? domainMin : 0, nValid > 0 ? domainMax : 0, histogramMean];
}
+
+export function resetCategoricalColorMapByIndex(colorMap: ColorMap, index: number): any {
+ if (!colorMap) {
+ return colorMap;
+ }
+ const newColorMap = colorMap.map((cm, i) => {
+ if (i === index) {
+ return [null, cm[1]];
+ }
+ return cm;
+ });
+ return newColorMap;
+}
+
+/**
+ * select rest categorical values for a colorMap by its index
+ */
+export function selectRestCategoricalColorMapByIndex(
+ colorMap: ColorMap | null,
+ index: number,
+ uniqueValues?: number[] | string[]
+): ColorMap | undefined | null {
+ if (!colorMap || !uniqueValues) {
+ return colorMap;
+ }
+
+ // find unique values that has not been used in current colorMap
+ const uniqValueDict = Object.fromEntries(uniqueValues.map(val => [val, false]));
+ colorMap.forEach(cm => {
+ toArray(cm[0]).forEach(v => {
+ if (v) uniqValueDict[v] = true;
+ });
+ });
+ const rest = Object.keys(uniqValueDict).filter(v => !uniqValueDict[v]);
+
+ // use the not used unique values in the selected color map
+ const newColorMap = colorMap.map((cm, i) => {
+ if (i === index) {
+ return [[...rest, ...toArray(cm[0])], cm[1]];
+ }
+ return cm;
+ }) as ColorMap;
+
+ return newColorMap;
+}
+
+/**
+ * remove a categorical value from a colorMap by its index
+ */
+export function removeCategoricalValueFromColorMap(
+ colorMap: ColorMap | null | undefined,
+ item: number | string,
+ index: number
+): ColorMap | null | undefined {
+ if (!colorMap) {
+ return colorMap;
+ }
+ const newColorMap = colorMap.map((cm, i) => {
+ if (i === index) {
+ if (!cm[0]) {
+ return [null, cm[1]];
+ }
+ const currentUniqueValues = toArray(cm[0]);
+ const updatedUniqueValues = currentUniqueValues.filter(v => v !== item);
+ return [updatedUniqueValues, cm[1]];
+ }
+ return cm;
+ }) as ColorMap;
+
+ return newColorMap;
+}
+
+/**
+ * add categorical values (from multisel dropdown) to a colorMap by its index
+ */
+export function addCategoricalValuesToColorMap(
+ colorMap: ColorMap,
+ items: (string | number)[],
+ index: number
+): ColorMap {
+ if (!colorMap) {
+ return colorMap;
+ }
+
+ const newColorMap = colorMap.map((cm, i) => {
+ if (i === index) {
+ if (!cm[0]) {
+ return [items, cm[1]];
+ }
+ const currentUniqueValues = toArray(cm[0]);
+ const updatedUniqueValues = uniq(currentUniqueValues.concat(items));
+ return [updatedUniqueValues, cm[1]];
+ }
+ // remove value from other colorMap
+ const currentUniqueValues = cm[0];
+ if (Array.isArray(currentUniqueValues)) {
+ const updatedUniqueValues: string[] | number[] = (currentUniqueValues as any[]).filter(
+ v => !items.includes(v)
+ );
+ return [updatedUniqueValues, cm[1]];
+ } else if (currentUniqueValues && items.includes(currentUniqueValues)) {
+ return [null, cm[1]];
+ }
+
+ return cm;
+ }) as ColorMap;
+
+ return newColorMap;
+}
+
+/**
+ * get a color scale func for categorical (custom ordinal) scale
+ */
+export function getCategoricalColorScale(
+ colorDomain: number[] | string[],
+ colorRange: ColorRange,
+ useRgb: boolean = true
+): (categoryValue: string | number) => RGBColor | RGBAColor {
+ const cMap = colorRange.colorMap
+ ? colorRange.colorMap
+ : getCategoricalColorMap(colorRange.colors, colorDomain);
+
+ const range: number[][] = [];
+ const domain: string[] = [];
+ cMap.forEach(cm => {
+ if (Array.isArray(cm[0])) {
+ cm[0].forEach(val => {
+ domain.push(val);
+ range.push(useRgb ? hexToRgb(cm[1]) : cm[1]);
+ });
+ } else {
+ domain.push(cm[0]);
+ range.push(useRgb ? hexToRgb(cm[1]) : cm[1]);
+ }
+ });
+
+ const scale = getScaleFunction(SCALE_TYPES.customOrdinal, range, domain, false);
+ scale.unknown(NO_VALUE_COLOR);
+ return scale as any;
+}
+
+/**
+ * initialize customPalette by custom scale or customOrdinal scale
+ */
+export function initCustomPaletteByCustomScale({
+ scale,
+ field,
+ ordinalDomain,
+ range,
+ colorBreaks
+}: {
+ scale: string;
+ field: Field;
+ ordinalDomain?: number[] | string[];
+ range: ColorRange;
+ colorBreaks: ColorBreakOrdinal[] | null;
+}): ColorUI['customPalette'] {
+ const customPaletteName = `color.customPalette.${scale}.${field.name}`;
+ // reuse range.colorMap if the field and scale not changed
+ const reuseColorMap = range.colorMap && range.name === customPaletteName && range.type === scale;
+ const colorMap = reuseColorMap
+ ? range.colorMap
+ : scale === SCALE_TYPES.customOrdinal && ordinalDomain
+ ? getCategoricalColorMap(range.colors, ordinalDomain)
+ : colorBreaks && isNumericColorBreaks(colorBreaks)
+ ? colorBreaksToColorMap(colorBreaks)
+ : null;
+ const colors = reuseColorMap ? range.colors : colorMap ? colorMap.map(cm => cm[1]) : range.colors;
+
+ // update custom breaks
+ const customPalette: ColorUI['customPalette'] = {
+ category: 'Custom',
+ name: customPaletteName,
+ type: scale,
+ colorMap,
+ colors: colors || []
+ };
+
+ return customPalette;
+}
diff --git a/src/utils/src/index.ts b/src/utils/src/index.ts
index 82bf71647..d791a8d5e 100644
--- a/src/utils/src/index.ts
+++ b/src/utils/src/index.ts
@@ -153,7 +153,15 @@ export {
getThresholdsFromQuantiles,
getQuantLabelFormat,
getHistogramDomain,
- getQuantLegends
+ getQuantLegends,
+ getCategoricalColorMap,
+ getCategoricalColorScale,
+ initCustomPaletteByCustomScale,
+ colorMapToCategoricalColorBreaks,
+ resetCategoricalColorMapByIndex,
+ selectRestCategoricalColorMapByIndex,
+ removeCategoricalValueFromColorMap,
+ addCategoricalValuesToColorMap
} from './data-scale-utils';
export type {ColorBreak, ColorBreakOrdinal, DomainQuantiles, DomainStops} from './data-scale-utils';
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.js
index bfe19c90e..9d7805ee9 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
@@ -45,7 +45,7 @@ function nop() {
const ExpectedCustomPalette = {
customPalette: {
- name: 'color.customPalette',
+ name: 'color.customPalette.custom.uid',
type: 'custom',
category: 'Custom',
colors: expectedColorRangeInLayer.colors,
@@ -98,8 +98,8 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> disabled', t
t.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 color scale select for string field'
);
t.equal(
@@ -218,8 +218,8 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi
// scale optons
t.equal(
wrapper.find(ColorScaleSelector).at(0).find('.list__item').length,
- 3,
- 'should render 3 scale options'
+ 4,
+ 'should render 4 scale options'
);
t.equal(wrapper.find(ColorBreaksPanel).length, 1, 'Should render 1 ColorBreaksPanel');
@@ -261,7 +261,7 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi
customBreaks: true
},
customPalette: {
- name: 'color.customPalette',
+ name: 'color.customPalette.custom.uid',
type: 'custom',
category: 'Custom',
colors: ['#00939C', '#6BB5B9', '#AAD7D9', '#E6FAFA'],
@@ -279,7 +279,7 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi
'color',
{
colorRange: {
- name: 'color.customPalette',
+ name: 'color.customPalette.custom.uid',
type: 'custom',
category: 'Custom',
colors: ['#00939C', '#6BB5B9', '#AAD7D9', '#E6FAFA'],
@@ -436,7 +436,7 @@ test('Components -> ChannelByValueSelector -> ColorScaleSelector -> ColorBreakDi
'color',
{
colorRange: {
- name: 'color.customPalette',
+ name: 'color.customPalette.custom.uid',
type: 'custom',
category: 'Custom',
colors: ['#00939C', '#6BB5B9', '#AAD7D9', '#E6FAFA']
diff --git a/test/browser/layer-tests/base-layer-specs.js b/test/browser/layer-tests/base-layer-specs.js
index ffbe4f9a1..255e95d9e 100644
--- a/test/browser/layer-tests/base-layer-specs.js
+++ b/test/browser/layer-tests/base-layer-specs.js
@@ -107,7 +107,7 @@ test('#BaseLayer -> updateLayerDomain', t => {
t.deepEqual(
updatedLayer.config.colorDomain,
expectedOrdinalDomain,
- 'should skip domain calculation if field is oridinal'
+ 'should skip domain calculation if field is ordinal'
);
t.end();