Skip to content

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

[feat] Edit color legend value (#2681)

Igor Dykhtaecb5ed418530
diff --git a/src/components/src/common/color-legend.tsx b/src/components/src/common/color-legend.tsx
index 31e53aba5..d4f48f4d3 100644
--- a/src/components/src/common/color-legend.tsx
+++ b/src/components/src/common/color-legend.tsx
@@ -1,30 +1,38 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {Component} from 'react';
-import styled from 'styled-components';
-import {createSelector} from 'reselect';
+import React, {useCallback, useMemo} from 'react';
+import styled, {css} from 'styled-components';
import moment from 'moment';
-import {SCALE_TYPES, SCALE_FUNC, ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {SCALE_TYPES, SCALE_FUNC, ALL_FIELD_TYPES, ColorRange} from '@kepler.gl/constants';
import {getTimeWidgetHintFormatter, formatNumber} from '@kepler.gl/utils';
+import {isObject} from '@kepler.gl/utils';
+import {Reset} from './icons';
+import {InlineInput} from './styled-components';
+import {HexColor} from '@kepler.gl/types';
-const ROW_H = 10;
+const ROW_H = 15;
const GAP = 4;
const RECT_W = 20;
-const StyledLegend = styled.div`
- ${props => props.theme.sidePanelScrollBar};
-
- max-height: 150px;
- overflow-y: auto;
+const stopClickPropagation = e => e.stopPropagation();
- svg {
- text {
- font-size: 9px;
- fill: ${props => props.theme.textColor};
- }
+const inputCss = css`
+ input {
+ pointer-events: none;
}
`;
+const StyledLegend = styled.div<{disableEdit: boolean}>`
+ ${props => props.theme.sidePanelScrollBar};
+ max-height: 180px;
+ overflow: auto;
+ margin-bottom: ${GAP}px;
+ display: grid;
+ grid-row-gap: ${GAP}px;
+ padding: 2px 0;
+
+ ${props => (props.disableEdit ? inputCss : '')}
+`;
const defaultFormat = d => d;
@@ -44,19 +52,17 @@ const getQuantLabelFormat = (domain, fieldType) => {
const getOrdinalLegends = scale => {
const domain = scale.domain();
- return {
- data: domain.map(scale),
- labels: domain
- };
+ const labels = scale.domain();
+ const data = domain.map(scale);
+ return data.map((datum, index) => ({
+ data: datum,
+ label: labels[index]
+ }));
};
const getQuantLegends = (scale, labelFormat) => {
if (typeof scale.invertExtent !== 'function') {
- // only quantile, quantize, threshold scale has invertExtent method
- return {
- data: [],
- labels: []
- };
+ return [];
}
const labels = scale.range().map(d => {
@@ -64,67 +70,208 @@ const getQuantLegends = (scale, labelFormat) => {
return `${labelFormat(invert[0])} to ${labelFormat(invert[1])}`;
});
- return {
- data: scale.range(),
- labels
- };
+ const data = scale.range();
+
+ return labels.map((label, index) => ({
+ data: data[index],
+ label
+ }));
};
-type RangeType = {
- colorMap?: [string, string][];
- colorLegends?: {[key: string]: string};
- colors: string[];
+const StyledLegendRow = styled.div`
+ display: flex;
+ align-items: center;
+ height: 20px;
+`;
+
+export function ResetColorLabelFactory() {
+ return styled(Reset)`
+ color: ${props => props.theme.labelColorLT};
+ cursor: pointer;
+
+ :hover {
+ color: ${props => props.theme.panelHeaderIconHover};
+ }
+ `;
+}
+
+const StyleInlineInput = styled(InlineInput)`
+ font-size: 9.5px;
+ line-height: ${ROW_H}px;
+ height: ${ROW_H}px;
+ color: ${props => props.theme.textColor};
+ width: unset;
+ padding: 2px;
+ flex: 1;
+ margin: 0 ${GAP}px;
+ :hover {
+ height: ${ROW_H}px;
+ }
+`;
+
+export type LegendRowEditorProps = {
+ color: string;
+ label: string;
+ customLabel?: string;
+ onEdit: (newValue: string) => void;
+ disabled?: boolean;
};
+export function LegendRowEditorFactory() {
+ const LegendRowEditor: React.FC<LegendRowEditorProps> = ({
+ color,
+ label,
+ onEdit,
+ disabled = false
+ }) => {
+ const onChange = useCallback(event => onEdit(event.target.value), [onEdit]);
+ return (
+ <StyleInlineInput
+ type="text"
+ className="legend__label__title__editor"
+ value={label}
+ onClick={stopClickPropagation}
+ onChange={onChange}
+ disabled={disabled}
+ id={`${color}:input-legend-label`}
+ />
+ );
+ };
-interface ColorLegendProps {
- width: number;
- scaleType?: string;
- domain?: any[] | object;
- fieldType?: string | null;
- range?: RangeType;
- labelFormat?: (n: number) => string;
+ LegendRowEditor.displayName = 'LegendRowEditor';
+ return LegendRowEditor;
+}
+
+const LegendRowStyle = {
+ width: `${RECT_W}px`,
+ height: `${ROW_H}px`
+};
+
+export function LegendColorDisplayFactory() {
+ const LegendColorDisplay = ({color}) => {
+ const style = useMemo(
+ () => ({...LegendRowStyle, backgroundColor: color, marginRight: `${GAP}px`}),
+ [color]
+ );
+ return <div style={style} className="legend-row-color" />;
+ };
+
+ return LegendColorDisplay;
+}
+
+const StyledLabel = styled.div`
+ font-size: 10px;
+ color: ${props => props.theme.textColor};
+ padding-left: 2px;
+`;
+
+export type LegendRowProps = {
+ label: string;
+ customLabel?: string;
displayLabel?: boolean;
+ color: string;
+ onUpdateLabel?: (selectedColor: string, newLabel: string) => void;
+ onResetLabel?: (color: string) => void;
+ disableEdit?: boolean;
+};
+
+LegendRowFactory.deps = [LegendColorDisplayFactory, LegendRowEditorFactory, ResetColorLabelFactory];
+export function LegendRowFactory(
+ LegendColorDisplay: ReturnType<typeof LegendColorDisplayFactory>,
+ LegendRowEditor: ReturnType<typeof LegendRowEditorFactory>,
+ ResetColorLabel: ReturnType<typeof ResetColorLabelFactory>
+) {
+ const LegendRow: React.FC<LegendRowProps> = ({
+ label = '',
+ displayLabel,
+ color,
+ onUpdateLabel,
+ onResetLabel
+ }) => {
+ const onEdit = useCallback(
+ newLabel => onUpdateLabel && onUpdateLabel(color, newLabel),
+ [color, onUpdateLabel]
+ );
+ const onReset = useCallback(() => onResetLabel && onResetLabel(color), [color, onResetLabel]);
+ const value = displayLabel ? label.toString() : '';
+ return (
+ <StyledLegendRow>
+ <LegendColorDisplay color={color} />
+ {onUpdateLabel ? (
+ <LegendRowEditor disabled={!onUpdateLabel} label={value} color={color} onEdit={onEdit} />
+ ) : (
+ <StyledLabel>{value}</StyledLabel>
+ )}
+ {onResetLabel ? <ResetColorLabel onClick={onReset} height="16px" /> : null}
+ </StyledLegendRow>
+ );
+ };
+ LegendRow.displayName = 'LegendRow';
+ return LegendRow;
}
-export default class ColorLegend extends Component<ColorLegendProps> {
- domainSelector = props => props.domain;
- rangeSelector = props => props.range;
- labelFormatSelector = props => props.labelFormat;
- scaleTypeSelector = props => props.scaleType;
- fieldTypeSelector = props => props.fieldType;
-
- legendsSelector = createSelector(
- this.domainSelector,
- this.rangeSelector,
- this.scaleTypeSelector,
- this.labelFormatSelector,
- this.fieldTypeSelector,
- (domain, range, scaleType, labelFormat, fieldType) => {
- const empty = {
- data: [],
- labels: []
+const overrideColorLegends = (colorLegends, overrides) => {
+ const {data, labels} = overrides;
+
+ const newColorLegends = [...colorLegends];
+
+ data.forEach((datum, index) => {
+ const currentIndex = colorLegends.findIndex(d => d.data === datum);
+ if (currentIndex !== -1) {
+ newColorLegends[currentIndex] = {
+ label: labels[index],
+ data: datum,
+ override: true
};
+ newColorLegends[currentIndex].label = labels[index];
+ } else {
+ newColorLegends.push({
+ data: datum,
+ label: labels[index],
+ override: true
+ });
+ }
+ });
+
+ return newColorLegends;
+};
+
+type ColorLegendProps = {
+ scaleType: string;
+ domain: number[] | string[];
+ fieldType?: string | null;
+ range?: ColorRange | null;
+ labelFormat?: (n: any) => string;
+ displayLabel?: boolean;
+ disableEdit?: boolean;
+ onUpdateColorLegend?: (colorLegends: {[key: HexColor]: string}) => void;
+};
+
+ColorLegendFactory.deps = [LegendRowFactory];
+function ColorLegendFactory(LegendRow: ReturnType<typeof LegendRowFactory>) {
+ const ColorLegend: React.FC<ColorLegendProps> = ({
+ domain,
+ range,
+ labelFormat,
+ scaleType,
+ fieldType,
+ onUpdateColorLegend,
+ displayLabel = true,
+ disableEdit = false
+ }) => {
+ const {colorLegends} = range || {};
+
+ const legends = useMemo(() => {
+ let currentLegends: any[] = [];
if (!range) {
- return empty;
+ return currentLegends;
}
- if (range.colorLegends) {
- return {
- data: Object.keys(range.colorLegends),
- labels: Object.values(range.colorLegends)
- };
- } else if (Array.isArray(range.colorMap)) {
- return {
- data: range.colorMap.map(cm => cm[1]),
- labels: range.colorMap.map(cm => cm[0])
- };
- } else if (Array.isArray(range.colors)) {
+ if (Array.isArray(range.colors)) {
if (!domain || !scaleType) {
- return empty;
+ return currentLegends;
}
const scaleFunction = SCALE_FUNC[scaleType];
// color scale can only be quantize, quantile or ordinal
- // @ts-ignore fix d3 scale
const scale = scaleFunction().domain(domain).range(range.colors);
if (scaleType === SCALE_TYPES.ordinal) {
@@ -133,41 +280,69 @@ export default class ColorLegend extends Component<ColorLegendProps> {
const formatLabel = labelFormat || getQuantLabelFormat(scale.domain(), fieldType);
- return getQuantLegends(scale, formatLabel);
+ currentLegends = getQuantLegends(scale, formatLabel);
+ }
+
+ if (range.colorLegends && isObject(range.colorLegends)) {
+ // override labels with color legends
+ const data = Object.keys(range.colorLegends);
+ const labels = Object.values(range.colorLegends);
+
+ currentLegends = overrideColorLegends(currentLegends, {data, labels});
+ }
+
+ if (Array.isArray(range.colorMap)) {
+ const data = range.colorMap.map(cm => cm[1]);
+ const labels = range.colorMap.map(cm => cm[0]);
+
+ currentLegends = overrideColorLegends(currentLegends, {data, labels});
}
- return empty;
- }
- );
- render() {
- const {width, displayLabel = true} = this.props;
+ return currentLegends;
+ }, [domain, range, labelFormat, scaleType, fieldType]);
- const legends = this.legendsSelector(this.props);
- const height = legends.data.length * (ROW_H + GAP);
+ const onUpdateLabel = useCallback(
+ (color, newValue) => {
+ if (onUpdateColorLegend) {
+ onUpdateColorLegend({
+ ...colorLegends,
+ [color]: newValue
+ });
+ }
+ },
+ [onUpdateColorLegend, colorLegends]
+ );
+
+ const onResetLabel = useCallback(
+ color => {
+ /* eslint-disable no-unused-vars */
+ // @ts-ignore
+ const {[color]: _, ...rest} = colorLegends;
+ if (onUpdateColorLegend && rest) {
+ onUpdateColorLegend(rest);
+ }
+ /* eslint-enable no-unused-vars */
+ },
+ [onUpdateColorLegend, colorLegends]
+ );
return (
- <StyledLegend className="styled-color-legend">
- <svg width={width} height={height}>
- {legends.data.map((color, idx) => (
- <LegendRow
- key={idx}
- label={legends.labels[idx]}
- displayLabel={displayLabel}
- color={color}
- idx={idx}
- />
- ))}
- </svg>
+ <StyledLegend disableEdit={disableEdit}>
+ {legends.map((legend, i) => (
+ <LegendRow
+ key={`${legend.data}-${i}`}
+ label={legend.label}
+ displayLabel={displayLabel}
+ color={legend.data}
+ onUpdateLabel={!disableEdit ? onUpdateLabel : undefined}
+ onResetLabel={legend.override && !disableEdit ? onResetLabel : undefined}
+ />
+ ))}
</StyledLegend>
);
- }
+ };
+
+ return React.memo(ColorLegend);
}
-export const LegendRow = ({label = '', displayLabel, color, idx}) => (
- <g transform={`translate(0, ${idx * (ROW_H + GAP)})`}>
- <rect width={RECT_W} height={ROW_H} style={{fill: color}} />
- <text x={RECT_W + 8} y={ROW_H - 1}>
- {displayLabel ? label?.toString() ?? 'N/A' : ''}
- </text>
- </g>
-);
+export default ColorLegendFactory;
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index 9f80afaa5..f4bb919b7 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -140,10 +140,10 @@ export {
LayerLegendHeaderFactory,
LayerLegendContentFactory,
StyledMapControlLegend,
- LayerColorLegend,
+ LayerColorLegendFactory,
VisualChannelMetric,
LayerDefaultLegend,
- SingleColorLegend
+ SingleColorLegendFactory
} from './map/map-legend';
export {default as MapDrawPanelFactory} from './map/map-draw-panel';
export {default as SplitMapButtonFactory} from './map/split-map-button';
@@ -220,7 +220,7 @@ export {
} from './editor/feature-action-panel';
// Injector
-export {injector, provideRecipesToInjector, withState} from './injector';
+export * from './injector';
// Common Components
export {default as CloudTile} from './modals/cloud-tile';
@@ -246,7 +246,13 @@ export {default as Modal, ModalFooter, ModalTitle} from './common/modal';
export {default as AppLogo} from './common/logo';
export {default as Switch} from './common/switch';
export {default as Checkbox} from './common/checkbox';
-export {default as ColorLegend, LegendRow} from './common/color-legend';
+export {
+ default as ColorLegendFactory,
+ LegendRowFactory,
+ LegendColorDisplayFactory,
+ LegendRowEditorFactory,
+ ResetColorLabelFactory
+} from './common/color-legend';
export {default as EffectControlFactory} from './map/effects/effect-control';
export {default as LoadingSpinner} from './common/loading-spinner';
export {default as LoadingDialog} from './modals/loading-dialog';
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index 12deb4e26..2c16cc034 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -1037,6 +1037,7 @@ export default function MapContainerFactory(
onSetEditorMode={visStateActions.setEditorMode}
onSetLocale={uiStateActions.setLocale}
onToggleEditorVisibility={visStateActions.toggleEditorVisibility}
+ onLayerVisConfigChange={visStateActions.layerVisConfigChange}
mapHeight={mapState.height}
/>
{isSplitSelector(this.props) && <Droppable containerId={containerId} />}
diff --git a/src/components/src/map/map-control-panel.tsx b/src/components/src/map/map-control-panel.tsx
index 1a4ccaa34..798825787 100644
--- a/src/components/src/map/map-control-panel.tsx
+++ b/src/components/src/map/map-control-panel.tsx
@@ -50,6 +50,7 @@ const StyledMapControlPanelHeader = styled.div.attrs({
color: ${props => props.theme.titleTextColor};
position: relative;
box-sizing: border-box;
+ align-items: center;
button {
width: 18px;
@@ -101,14 +102,14 @@ const StyledIcon = styled(IconRoundSmall)`
:hover {
cursor: pointer;
background-color: transparent;
- color: ${props => props.theme.linkBtnColor};
+ color: ${props => props.theme.floatingBtnActColor};
}
`;
export type MapControlPanelProps = {
header?: string;
scale?: number;
- onClick: React.MouseEventHandler<HTMLDivElement>;
+ onClick?: React.MouseEventHandler<HTMLDivElement>;
onPinClick?: React.MouseEventHandler<HTMLDivElement>;
pinnable?: boolean;
disableClose?: boolean;
diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsx
index eb78f42a9..21a3522f9 100644
--- a/src/components/src/map/map-control.tsx
+++ b/src/components/src/map/map-control.tsx
@@ -13,7 +13,7 @@ import MapLegendPanelFactory from './map-legend-panel';
import MapDrawPanelFactory from './map-draw-panel';
import LocalePanelFactory from './locale-panel';
import {Layer} from '@kepler.gl/layers';
-import {Editor, MapControls, MapState} from '@kepler.gl/types';
+import {Editor, LayerVisConfig, MapControls, MapState} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {MapStateActions, UIStateActions} from '@kepler.gl/actions';
@@ -62,6 +62,7 @@ export type MapControlProps = {
onToggleMapControl: (control: string) => void;
onSetEditorMode: (mode: string) => void;
onToggleEditorVisibility: () => void;
+ onLayerVisConfigChange: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
top: number;
onSetLocale: typeof UIStateActions.setLocale;
locale: string;
diff --git a/src/components/src/map/map-legend-panel.tsx b/src/components/src/map/map-legend-panel.tsx
index 43f740e75..6c2c68ea8 100644
--- a/src/components/src/map/map-legend-panel.tsx
+++ b/src/components/src/map/map-legend-panel.tsx
@@ -11,7 +11,7 @@ import MapControlPanelFactory from './map-control-panel';
import MapLegendFactory from './map-legend';
import {createPortal} from 'react-dom';
import {DIMENSIONS} from '@kepler.gl/constants';
-import {MapControlItem, MapControls, MapState} from '@kepler.gl/types';
+import {LayerVisConfig, MapControlMapLegend, MapControls, MapState} from '@kepler.gl/types';
import {Layer} from '@kepler.gl/layers';
import {media} from '@kepler.gl/styles';
import {ActionHandler, toggleSplitMapViewport} from '@kepler.gl/actions';
@@ -70,6 +70,7 @@ export type MapLegendPanelProps = {
onToggleSplitMapViewport?: ActionHandler<typeof toggleSplitMapViewport>;
isViewportUnsyncAllowed?: boolean;
onClickControlBtn?: (e?: MouseEvent) => void;
+ onLayerVisConfigChange?: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
};
function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {
@@ -89,10 +90,11 @@ function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {
offsetRight,
onToggleSplitMapViewport,
onClickControlBtn,
- isViewportUnsyncAllowed = true
+ isViewportUnsyncAllowed = true,
+ onLayerVisConfigChange
}) => {
- const mapLegend = mapControls?.mapLegend || ({} as MapControlItem);
- const {active: isPinned} = mapLegend || {};
+ const mapLegend = mapControls?.mapLegend || ({} as MapControlMapLegend);
+ const {active: isPinned, disableEdit} = mapLegend || {};
const rootContext = useContext(RootContext);
const [isOpened, setIsOpened] = useState(false);
@@ -154,7 +156,12 @@ function MapLegendPanelFactory(MapControlTooltip, MapControlPanel, MapLegend) {
onToggleSplitMapViewport={onToggleSplitMapViewport}
isViewportUnsyncAllowed={isViewportUnsyncAllowed}
>
- <MapLegend layers={layers} mapState={mapState} />
+ <MapLegend
+ layers={layers}
+ mapState={mapState}
+ disableEdit={disableEdit}
+ onLayerVisConfigChange={onLayerVisConfigChange}
+ />
</MapControlPanel>
);
diff --git a/src/components/src/map/map-legend.tsx b/src/components/src/map/map-legend.tsx
index db87cb790..6c966edfe 100644
--- a/src/components/src/map/map-legend.tsx
+++ b/src/components/src/map/map-legend.tsx
@@ -1,15 +1,15 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {FC} from 'react';
+import React, {FC, useCallback} from 'react';
import styled from 'styled-components';
import {rgb} from 'd3-color';
-import ColorLegend from '../common/color-legend';
+import ColorLegendFactory from '../common/color-legend';
import RadiusLegend from '../common/radius-legend';
import {CHANNEL_SCALES, DIMENSIONS} from '@kepler.gl/constants';
import {FormattedMessage} from '@kepler.gl/localization';
import {Layer, LayerBaseConfig, VisualChannel, VisualChannelDescription} from '@kepler.gl/layers';
-import {MapState} from '@kepler.gl/types';
+import {LayerVisConfig, MapState, RGBColor} from '@kepler.gl/types';
interface StyledMapControlLegendProps {
width?: number;
@@ -43,10 +43,15 @@ export const StyledMapControlLegend = styled.div<StyledMapControlLegendProps>`
.legend--layer__title {
padding-right: ${props => props.theme.mapControl.padding}px;
+ margin-top: 4px;
}
+ .legend--layer__item {
+ padding-bottom: 4px;
+ }
.legend--layer_by {
color: ${props => props.theme.subtextColor};
+ margin-top: 4px;
}
.legend--layer_color_field {
@@ -74,7 +79,6 @@ export type LayerSizeLegendProps = {
name: string | undefined;
};
-/** @type {typeof import('./map-legend').LayerDefaultLegend} */
export const LayerDefaultLegend: React.FC<LayerSizeLegendProps> = ({label, name}) =>
label ? (
<div className="legend--layer_size-schema">
@@ -89,41 +93,69 @@ export const LayerDefaultLegend: React.FC<LayerSizeLegendProps> = ({label, name}
const SINGLE_COLOR_DOMAIN = [''];
export type SingleColorLegendProps = {
- width: number;
- color: string;
+ color: RGBColor;
};
-/** @type {typeof import('./map-legend').SingleColorLegend} */
-export const SingleColorLegend: React.FC<SingleColorLegendProps> = React.memo(({width, color}) => (
- <ColorLegend
- scaleType="ordinal"
- displayLabel={false}
- domain={SINGLE_COLOR_DOMAIN}
- fieldType={null}
- range={{colors: [rgb(...color).toString()]}}
- width={width}
- />
-));
-
-SingleColorLegend.displayName = 'SingleColorLegend';
+SingleColorLegendFactory.deps = [ColorLegendFactory];
+
+export function SingleColorLegendFactory(
+ ColorLegend: ReturnType<typeof ColorLegendFactory>
+): React.FC<SingleColorLegendProps> {
+ const SingleColorLegend: React.FC<SingleColorLegendProps> = ({color}) => (
+ <ColorLegend
+ scaleType="ordinal"
+ displayLabel={false}
+ domain={SINGLE_COLOR_DOMAIN}
+ fieldType={null}
+ range={{colors: [rgb(...color).toString()]}}
+ disableEdit={true}
+ />
+ );
+ SingleColorLegend.displayName = 'SingleColorLegend';
+ return React.memo(SingleColorLegend);
+}
export type LayerColorLegendProps = {
description: VisualChannelDescription;
config: LayerBaseConfig;
- width: number;
colorChannel: VisualChannel;
+ onLayerVisConfigChange?: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
+ layer: Layer;
+ disableEdit?: boolean;
};
-/** @type {typeof import('./map-legend').LayerColorLegend} */
-export const LayerColorLegend: React.FC<LayerColorLegendProps> = React.memo(
- ({description, config, width, colorChannel}) => {
+LayerColorLegendFactory.deps = [ColorLegendFactory, SingleColorLegendFactory];
+export function LayerColorLegendFactory(
+ ColorLegend: ReturnType<typeof ColorLegendFactory>,
+ SingleColorLegend: ReturnType<typeof SingleColorLegendFactory>
+) {
+ const LayerColorLegend: React.FC<LayerColorLegendProps> = ({
+ description,
+ config,
+ layer,
+ colorChannel,
+ disableEdit,
+ onLayerVisConfigChange
+ }) => {
const enableColorBy = description.measure;
const {scale, field, domain, range, property} = colorChannel;
const [colorScale, colorField, colorDomain] = [scale, field, domain].map(k => config[k]);
const colorRange = config.visConfig[range];
-
+ const onUpdateColorLegend = useCallback(
+ colorLegends => {
+ if (onLayerVisConfigChange) {
+ onLayerVisConfigChange(layer, {
+ [range]: {
+ ...colorRange,
+ colorLegends
+ }
+ });
+ }
+ },
+ [layer, onLayerVisConfigChange, colorRange, range]
+ );
return (
- <div>
+ <div className="legend--layer__item">
<div className="legend--layer_color-schema">
<div>
{enableColorBy ? <VisualChannelMetric name={enableColorBy} /> : null}
@@ -135,12 +167,12 @@ export const LayerColorLegend: React.FC<LayerColorLegendProps> = React.memo(
domain={colorDomain}
fieldType={(colorField && colorField.type) || 'real'}
range={colorRange}
- width={width}
+ onUpdateColorLegend={onUpdateColorLegend}
+ disableEdit={disableEdit}
/>
) : (
<SingleColorLegend
color={config.visConfig[property] || config[property] || config.color}
- width={width}
/>
)}
</div>
@@ -148,11 +180,11 @@ export const LayerColorLegend: React.FC<LayerColorLegendProps> = React.memo(
</div>
</div>
);
- }
-);
+ };
-// eslint-disable-next-line react/display-name
-LayerColorLegend.displayName = 'LayerColorLegend';
+ LayerColorLegend.displayName = 'LayerColorLegend';
+ return React.memo(LayerColorLegend);
+}
function getLayerRadiusScaleMetersToPixelsMultiplier(layer, mapState) {
// @ts-ignore this actually exist
@@ -185,7 +217,7 @@ export const LayerRadiusLegend: FC<LayerRadiusLegendProps> = React.memo(
}
return (
- <div className="legend--layer__item">
+ <div>
<div className="legend--layer_size-schema">
<div>
{enableSizeBy ? <VisualChannelMetric name={enableSizeBy} /> : null}
@@ -206,7 +238,6 @@ export const LayerRadiusLegend: FC<LayerRadiusLegendProps> = React.memo(
);
}
);
-LayerRadiusLegend.displayName = 'LayerRadiusLegend';
const isColorChannel = visualChannel =>
[CHANNEL_SCALES.color, CHANNEL_SCALES.colorAggr].includes(visualChannel.channelScaleType);
@@ -222,7 +253,6 @@ const isRadiusChannel = visualChannel =>
[CHANNEL_SCALES.radius].includes(visualChannel.channelScaleType);
export function LayerLegendHeaderFactory() {
- /** @type {typeof import('./map-legend').LayerLegendHeader }> */
const LayerLegendHeader: React.FC<LayerLegendHeaderProps> = ({options, layer}) => {
return options?.showLayerName !== false ? (
<div className="legend--layer_name">{layer.config.label}</div>
@@ -235,28 +265,51 @@ export type LayerLegendContentProps = {
layer: Layer;
containerW: number;
mapState?: MapState;
+ disableEdit?: boolean;
+ onLayerVisConfigChange?: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
};
-export function LayerLegendContentFactory() {
- /** @type {typeof import('./map-legend').LayerLegendContent }> */
- const LayerLegendContent: React.FC<LayerLegendContentProps> = ({layer, containerW, mapState}) => {
+LayerLegendContentFactory.deps = [LayerColorLegendFactory];
+
+export function LayerLegendContentFactory(
+ LayerColorLegend: ReturnType<typeof LayerColorLegendFactory>
+) {
+ const LayerLegendContent: React.FC<LayerLegendContentProps> = ({
+ layer,
+ containerW,
+ mapState,
+ disableEdit,
+ onLayerVisConfigChange
+ }) => {
const colorChannels = Object.values(layer.visualChannels).filter(isColorChannel);
const nonColorChannels = Object.values(layer.visualChannels).filter(vc => !isColorChannel(vc));
const width = containerW - 2 * DIMENSIONS.mapControl.padding;
+ // render color by chanel only
+ let colorChannelToRender = colorChannels.filter(
+ cc =>
+ (!cc.condition || cc.condition(layer.config)) &&
+ layer.getVisualChannelDescription(cc.key)?.measure
+ );
+ // if no color by chanel, render rest
+ if (!colorChannelToRender.length) {
+ colorChannelToRender = colorChannels.filter(
+ cc => !cc.condition || cc.condition(layer.config)
+ );
+ }
return (
<>
- {colorChannels.map(colorChannel =>
- !colorChannel.condition || colorChannel.condition(layer.config) ? (
- <LayerColorLegend
- key={colorChannel.key}
- description={layer.getVisualChannelDescription(colorChannel.key)}
- config={layer.config}
- width={width}
- colorChannel={colorChannel}
- />
- ) : null
- )}
+ {colorChannelToRender.map(colorChannel => (
+ <LayerColorLegend
+ key={colorChannel.key}
+ colorChannel={colorChannel}
+ config={layer.config}
+ description={layer.getVisualChannelDescription(colorChannel.key)}
+ layer={layer}
+ disableEdit={disableEdit}
+ onLayerVisConfigChange={onLayerVisConfigChange}
+ />
+ ))}
{nonColorChannels.map(visualChannel => {
const matchCondition = !visualChannel.condition || visualChannel.condition(layer.config);
const enabled = layer.config[visualChannel.field] || visualChannel.defaultMeasure;
@@ -298,12 +351,24 @@ export type MapLegendProps = {
options?: {
showLayerName?: boolean;
};
+ disableEdit?: boolean;
+ onLayerVisConfigChange?: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
};
MapLegendFactory.deps = [LayerLegendHeaderFactory, LayerLegendContentFactory];
-function MapLegendFactory(LayerLegendHeader, LayerLegendContent) {
- /** @type {typeof import('./map-legend').MapLegend }> */
- const MapLegend: React.FC<MapLegendProps> = ({layers = [], width, mapState, options}) => (
+
+function MapLegendFactory(
+ LayerLegendHeader: ReturnType<typeof LayerLegendHeaderFactory>,
+ LayerLegendContent: ReturnType<typeof LayerLegendContentFactory>
+) {
+ const MapLegend: React.FC<MapLegendProps> = ({
+ layers = [],
+ width,
+ mapState,
+ options,
+ disableEdit,
+ onLayerVisConfigChange
+ }) => (
<div
className="map-legend"
{...(mapState?.height && {
@@ -327,7 +392,13 @@ function MapLegendFactory(LayerLegendHeader, LayerLegendContent) {
width={containerW}
>
<LayerLegendHeader options={options} layer={layer} />
- <LayerLegendContent containerW={containerW} layer={layer} mapState={mapState} />
+ <LayerLegendContent
+ containerW={containerW}
+ layer={layer}
+ mapState={mapState}
+ disableEdit={disableEdit}
+ onLayerVisConfigChange={onLayerVisConfigChange}
+ />
</StyledMapControlLegend>
);
})}
diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.ts
index cd2a03466..dab56d2b1 100644
--- a/src/reducers/src/ui-state-updaters.ts
+++ b/src/reducers/src/ui-state-updaters.ts
@@ -86,6 +86,10 @@ const DEFAULT_MAP_CONTROLS_FEATURES: MapControlItem = {
activeMapIndex: 0
};
+const DEFAULT_MAP_LEGEND_CONTROL = {
+ ...DEFAULT_MAP_CONTROLS_FEATURES,
+ disableEdit: false
+};
/**
* A list of map control visibility and whether is it active.
* @memberof uiStateUpdaters
@@ -103,7 +107,10 @@ export const DEFAULT_MAP_CONTROLS: MapControls = (
).reduce(
(final, current) => ({
...final,
- [current]: DEFAULT_MAP_CONTROLS_FEATURES
+ [current]:
+ current === MAP_CONTROLS.mapLegend
+ ? DEFAULT_MAP_LEGEND_CONTROL
+ : DEFAULT_MAP_CONTROLS_FEATURES
}),
{} as MapControls
);
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index cbd732da9..9ad3521d3 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -364,9 +364,12 @@ export type MapControlItem = {
disableClose?: boolean;
activeMapIndex?: number;
};
+export type MapControlMapLegend = MapControlItem & {
+ disableEdit?: boolean;
+};
export type MapControls = {
visibleLayers?: MapControlItem;
- mapLegend?: MapControlItem;
+ mapLegend?: MapControlMapLegend;
toggle3d?: MapControlItem;
splitMap?: MapControlItem;
mapDraw?: MapControlItem;
diff --git a/test/browser/components/common/color-legend-test.js b/test/browser/components/common/color-legend-test.js
index e967ca62e..44184b00b 100644
--- a/test/browser/components/common/color-legend-test.js
+++ b/test/browser/components/common/color-legend-test.js
@@ -5,9 +5,12 @@ import React from 'react';
import test from 'tape';
import {mountWithTheme} from 'test/helpers/component-utils';
-import {ColorLegend, LegendRow} from '@kepler.gl/components';
+import {ColorLegendFactory, LegendRowFactory, appInjector} from '@kepler.gl/components';
-test('Components -> ColorLegend.render', t => {
+const ColorLegend = appInjector.get(ColorLegendFactory);
+const LegendRow = appInjector.get(LegendRowFactory);
+
+test('Components -> ColorLegend.render 1', t => {
t.doesNotThrow(() => {
mountWithTheme(<ColorLegend />);
}, 'Show not fail without props');
@@ -32,9 +35,9 @@ test('Components -> ColorLegend.render', t => {
let wrapper = mountWithTheme(<ColorLegend {...props} />);
t.equal(wrapper.find(LegendRow).length, 6, 'Should render 6 legends');
- const row1 = wrapper.find(LegendRow).at(0).find('rect').at(0).html();
+ const rect = wrapper.find(LegendRow).at(0).find('.legend-row-color').at(0);
- t.ok(row1.indexOf('fill: #5A1846'), 'should render color rect');
+ t.equal(rect.props().style.backgroundColor, '#5A1846', 'should render color rect');
props.scaleType = 'quantile';
wrapper = mountWithTheme(<ColorLegend {...props} />);
@@ -48,13 +51,14 @@ test('Components -> ColorLegend.render', t => {
props.scaleType = 'quantile';
wrapper = mountWithTheme(<ColorLegend {...props} />);
- const row1Txt = wrapper.find(LegendRow).at(0).find('text').at(0).text();
- t.equal(row1Txt, '', 'should not render text');
+ const row1Txt = wrapper.find(LegendRow).at(0).find('.legend__label__title__editor').at(0);
+
+ t.equal(row1Txt.props().value, '', 'should not render text');
t.end();
});
-test('Components -> ColorLegend.render', t => {
+test('Components -> ColorLegend.render 2', t => {
t.doesNotThrow(() => {
mountWithTheme(<ColorLegend />);
}, 'Show not fail without props');
@@ -78,10 +82,12 @@ test('Components -> ColorLegend.render', t => {
let wrapper = mountWithTheme(<ColorLegend {...props} />);
t.equal(wrapper.find(LegendRow).length, 5, 'Should render 5 legends');
- let row1 = wrapper.find(LegendRow).at(0).find('rect').at(0).html();
+ let row1 = wrapper.find(LegendRow).at(0);
+ let rect = row1.find('.legend-row-color').at(0);
+ let label = row1.find('.legend__label__title__editor').at(0);
- t.ok(row1.indexOf('fill: #C1C9CC'), 'should render color rect based on colorMap');
- t.ok(row1.indexOf('apple'), 'should render color text based on colorMap');
+ t.equal(rect.props().style.backgroundColor, '#C1C9CC', 'should render color rect');
+ t.equal(label.props().value, 'apple', 'should render color text based on colorMap');
props.range = {
colorLegends: {
@@ -95,9 +101,12 @@ test('Components -> ColorLegend.render', t => {
wrapper = mountWithTheme(<ColorLegend {...props} />);
t.equal(wrapper.find(LegendRow).length, 5, 'Should render 5 legends');
- row1 = wrapper.find(LegendRow).at(0).find('rect').at(0).html();
+ row1 = wrapper.find(LegendRow).at(0);
+ rect = row1.find('.legend-row-color').at(0);
+ label = row1.find('.legend__label__title__editor').at(0);
+
+ t.equal(rect.props().style.backgroundColor, '#DFB02F', 'should render color rect');
+ t.equal(label.props().value, 'Apple', 'should render color text based on colorMap');
- t.ok(row1.indexOf('fill: #DFB02F'), 'should render color rect based on colorMap');
- t.ok(row1.indexOf('Apple'), 'should render color text based on colorMap');
t.end();
});
diff --git a/test/browser/components/map/map-legend-test.js b/test/browser/components/map/map-legend-test.js
index 1aa7411d6..d218924f8 100644
--- a/test/browser/components/map/map-legend-test.js
+++ b/test/browser/components/map/map-legend-test.js
@@ -10,10 +10,10 @@ import cloneDeep from 'lodash.clonedeep';
import {
MapLegendFactory,
StyledMapControlLegend,
- LayerColorLegend,
VisualChannelMetric,
LayerDefaultLegend,
- SingleColorLegend,
+ SingleColorLegendFactory,
+ LayerColorLegendFactory,
appInjector
} from '@kepler.gl/components';
import {
@@ -25,6 +25,8 @@ import {
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
const MapLegend = appInjector.get(MapLegendFactory);
+const LayerColorLegend = appInjector.get(LayerColorLegendFactory);
+const SingleColorLegend = appInjector.get(SingleColorLegendFactory);
test('Components -> MapLegend.render', t => {
t.doesNotThrow(() => {
diff --git a/test/node/reducers/ui-state-test.js b/test/node/reducers/ui-state-test.js
index 000730a7a..dde3b4356 100644
--- a/test/node/reducers/ui-state-test.js
+++ b/test/node/reducers/ui-state-test.js
@@ -182,7 +182,9 @@ test('#uiStateReducer -> TOGGLE_MAP_CONTROL', t => {
mapLegend: {
...INITIAL_UI_STATE.mapControls.mapLegend,
active: !INITIAL_UI_STATE.mapControls.mapLegend.active,
- activeMapIndex: 0
+ activeMapIndex: 0,
+ disableEdit: false,
+ disableClose: false
}
}
};