Skip to content

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

feat: add point and line sketching to Draw on Map (#3639)

Igor Dykhta904671130e0d
diff --git a/SUMMARY.md b/SUMMARY.md
index d469506fd..489d50792 100644
--- a/SUMMARY.md
+++ b/SUMMARY.md
@@ -32,6 +32,7 @@
* [Layer Attributes](docs/user-guides/d-layer-attributes.md)
* [Color Palettes](docs/user-guides/l-color-attributes.md)
* [Filters](docs/user-guides/e-filters.md)
+ * [Draw on Map](docs/user-guides/draw-on-map.md)
* [Map Styles](docs/user-guides/f-map-styles.md)
* [Interactions](docs/user-guides/g-interactions.md)
* [Map Settings](docs/user-guides/m-map-settings.md)
diff --git a/docs/api-reference/actions/actions.md b/docs/api-reference/actions/actions.md
index 60a1a94fe..dee18c593 100644
--- a/docs/api-reference/actions/actions.md
+++ b/docs/api-reference/actions/actions.md
@@ -772,14 +772,14 @@ Returns **{type: ActionTypes.REORDER_LAYER, order: order}**
### setEditorMode
-Set the map mode
+Set the Draw on Map editor mode
- **ActionTypes**: [`ActionTypes.SET_EDITOR_MODE`][12]
- **Updaters**: [`visStateUpdaters.setEditorModeUpdater`][208]
**Parameters**
-- `mode` **[string][162]** one of EDITOR_MODES
+- `mode` **[string][162]** one of `EDITOR_MODES`: `EDIT`, `DRAW_POINT`, `DRAW_LINESTRING`, `DRAW_POLYGON`, `DRAW_RECTANGLE`
**Examples**
@@ -787,7 +787,7 @@ Set the map mode
import {setEditorMode} from '@kepler.gl/actions';
import {EDITOR_MODES} from '@kepler.gl/constants';
-this.props.dispatch(setEditorMode(EDITOR_MODES.DRAW_POLYGON));
+this.props.dispatch(setEditorMode(EDITOR_MODES.DRAW_LINESTRING));
```
### setFilter
diff --git a/docs/user-guides/README.md b/docs/user-guides/README.md
index 0be2b5f2a..8232f433b 100644
--- a/docs/user-guides/README.md
+++ b/docs/user-guides/README.md
@@ -48,6 +48,8 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da
#### [Filters](./e-filters.md)
+#### [Draw on Map](./draw-on-map.md)
+
#### [Map styles](./f-map-styles.md#map-styles)
* [Base map styles](./f-map-styles.md#base-map-styles)
* [Map layers](./f-map-styles.md#toggle-map-layers)
diff --git a/docs/user-guides/draw-on-map.md b/docs/user-guides/draw-on-map.md
new file mode 100644
index 000000000..a4b554de3
--- /dev/null
+++ b/docs/user-guides/draw-on-map.md
@@ -0,0 +1,74 @@
+# Draw on Map
+
+<!-- TOC -->
+ - [Open the drawing tools](#open-the-drawing-tools)
+ - [Drawing tools](#drawing-tools)
+ - [Select, move, and edit](#select-move-and-edit)
+ - [Edit properties](#edit-properties)
+ - [Filter layers](#filter-layers)
+ - [Copy and convert to a layer](#copy-and-convert-to-a-layer)
+ - [Disable sketch tools](#disable-sketch-tools)
+<!-- /TOC -->
+
+Draw on Map lets you sketch points, lines, polygons, and rectangles on the map. Sketches stay on the map until you delete them, convert them to a layer, or use a polygon or rectangle as a spatial filter.
+
+## Open the drawing tools
+
+Click the **Draw on Map** button in the map controls (top right of the map). A menu of drawing tools appears.
+
+Press **Escape** while a draw tool is active to return to **Select**.
+
+## Drawing tools
+
+| Tool | How to draw | Notes |
+| --- | --- | --- |
+| **Select** | Click a sketch to select it | Move and edit existing sketches |
+| **Point** | Click the map | Stays in point mode so you can add several points |
+| **Line** | Click to add vertices, double-click or press **Enter** to finish | Stays in line mode so you can draw several lines |
+| **Polygon** | Click to add vertices, click the first vertex (or double-click) to close | Sketch only until you apply it as a filter |
+| **Rectangle** | Click and drag, or click two opposite corners | Applied as a polygon filter when you finish drawing |
+
+## Select, move, and edit
+
+1. Choose **Select**, then click a sketch.
+2. Drag a **point** to move it.
+3. Drag the **body of a line** to move the whole line. Drag a vertex to reshape it. Click the line to insert a vertex.
+4. Drag the **interior of a polygon or rectangle** to move it. Drag a vertex to reshape it.
+
+Right-click a selected sketch for **Edit Properties**, **Copy Geometry**, and **Delete**. **Filter Layers** appears only for polygons and rectangles.
+
+## Edit properties
+
+Right-click a sketch and choose **Edit Properties** to add, change, or remove name/value pairs. These are stored as GeoJSON properties and become columns when you convert sketches to a layer.
+
+## Filter layers
+
+Polygons and rectangles can filter other layers so that only features inside the shape remain visible.
+
+- **Rectangle** becomes a filter as soon as you finish drawing it.
+- **Polygon** stays a sketch until you right-click it and choose **Filter Layers**, then pick the layers to filter.
+
+Filtered shapes use a dashed outline. A filter icon appears on the shape; click it to select the filter.
+
+Points and lines cannot be used as filters.
+
+If you turn off every filtered layer, the polygon returns to a sketch.
+
+## Copy and convert to a layer
+
+The drawing menu also includes:
+
+- **Copy all** — copies every sketch as a GeoJSON FeatureCollection.
+- **Convert to Layer** — turns the sketches into a GeoJSON dataset and layer named `Drawn Geometry` plus a number, then clears the sketches.
+
+## Disable sketch tools
+
+Point, Line, Copy all, Convert to Layer, and Edit Properties are enabled by default. Polygon and rectangle drawing stay available if you turn the extra tools off:
+
+```js
+import {initApplicationConfig} from '@kepler.gl/utils';
+
+initApplicationConfig({enableDrawOnMapSketches: false});
+```
+
+[Back to table of contents](README.md)
diff --git a/docs/user-guides/e-filters.md b/docs/user-guides/e-filters.md
index 7af6412a6..87a1d3e49 100644
--- a/docs/user-guides/e-filters.md
+++ b/docs/user-guides/e-filters.md
@@ -1,8 +1,10 @@
# Filters
-Add filters to your map to limit the data that is displayed. Filters must be based on the columns in your dataset.
+Add filters to your map to limit the data that is displayed. You can filter by a column in your dataset, or spatially with a polygon or rectangle drawn on the map.
-To add a filter:
+## Filter by column
+
+To add a column filter:
1. Select Filters from the right navigation bar.
![select filters](https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/image1.png "select filters")
@@ -15,6 +17,10 @@ To add a filter:
4. Your filter is applied to your map as soon as you specify the field and value.
5. Delete a filter anytime by clicking the __trashcan__ to the right of the filter you wish to delete.
-__Note__: filters apply to all layers in the same dataset on your map.
+__Note__: column filters apply to all layers in the same dataset on your map.
+
+## Filter by polygon or rectangle
+
+Use [Draw on Map](./draw-on-map.md) to sketch a rectangle (applied as a filter when you finish drawing) or a polygon (right-click, then **Filter Layers**). Only features inside the shape stay visible. Points and lines cannot be used as filters.
[Back to table of contents](README.md)
diff --git a/docs/user-guides/j-get-started.md b/docs/user-guides/j-get-started.md
index 10773712b..b6ea73c40 100644
--- a/docs/user-guides/j-get-started.md
+++ b/docs/user-guides/j-get-started.md
@@ -28,7 +28,7 @@ Learn more about [adding data layers](./b-kepler-gl-workflow/b-add-data-layers/a
![choose a dataset](https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/add-filter.png "choose a dataset")
-Add filters to your map to limit the data that is displayed. Filters must be based on the columns in your dataset. To create a new filter, open the Filter menu and click Add Filter. Note that filters apply to all layers and cannot be toggled on and off.
+Add filters to your map to limit the data that is displayed. You can filter by a column in your dataset, or spatially with a polygon or rectangle from [Draw on Map](./draw-on-map.md). To create a column filter, open the Filter menu and click Add Filter.
Learn more about [filters](./e-filters.md).
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index 5d19c35f6..ab2d20daf 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -206,10 +206,12 @@ export const ActionTypes = {
// geo-operations
SET_FEATURES: `${ACTION_PREFIX}SET_FEATURES`,
+ SET_EDITOR_FEATURE_PROPERTIES: `${ACTION_PREFIX}SET_EDITOR_FEATURE_PROPERTIES`,
SET_POLYGON_FILTER_LAYER: `${ACTION_PREFIX}SET_POLYGON_FILTER_LAYER`,
SET_POLYGON_FILTER_ALL_LAYERS: `${ACTION_PREFIX}SET_POLYGON_FILTER_ALL_LAYERS`,
DELETE_FEATURE: `${ACTION_PREFIX}DELETE_FEATURE`,
TOGGLE_EDITOR_VISIBILITY: `${ACTION_PREFIX}TOGGLE_EDITOR_VISIBILITY`,
+ CONVERT_EDITOR_FEATURES_TO_LAYER: `${ACTION_PREFIX}CONVERT_EDITOR_FEATURES_TO_LAYER`,
// storage
START_SAVE_STORAGE: `${ACTION_PREFIX}START_SAVE_STORAGE`
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index e9ac6dc79..1e5a1b4ca 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -1571,6 +1571,32 @@ export function loadFilesErr(
export type SetFeaturesUpdaterAction = {
features: Feature[];
};
+
+export type SetEditorFeaturePropertiesUpdaterAction = {
+ feature: Feature;
+ properties: Record<string, unknown>;
+};
+/**
+ * Set user-facing GeoJSON properties on a Draw on Map sketch.
+ * Editor-only keys such as `filterId` and `isClosed` are preserved.
+ * @memberof visStateActions
+ * @param feature
+ * @param properties
+ * @returns action
+ */
+export function setEditorFeatureProperties(
+ feature: Feature,
+ properties: Record<string, unknown>
+): Merge<
+ SetEditorFeaturePropertiesUpdaterAction,
+ {type: typeof ActionTypes.SET_EDITOR_FEATURE_PROPERTIES}
+> {
+ return {
+ type: ActionTypes.SET_EDITOR_FEATURE_PROPERTIES,
+ feature,
+ properties
+ };
+}
/**
* Store features to state
* @memberof visStateActions
@@ -1675,16 +1701,16 @@ export function deleteFeature(
export type SetEditorModeUpdaterAction = {
mode: string;
};
-/** Set the map mode
+/** Set the Draw on Map editor mode.
* @memberof visStateActions
- * @param mode one of EDITOR_MODES
+ * @param mode one of `EDITOR_MODES`: `EDIT`, `DRAW_POINT`, `DRAW_LINESTRING`, `DRAW_POLYGON`, `DRAW_RECTANGLE`
* @returns action
* @public
* @example
- * import {setMapMode} from '@kepler.gl/actions';
+ * import {setEditorMode} from '@kepler.gl/actions';
* import {EDITOR_MODES} from '@kepler.gl/constants';
*
- * this.props.dispatch(setMapMode(EDITOR_MODES.DRAW_POLYGON));
+ * this.props.dispatch(setEditorMode(EDITOR_MODES.DRAW_LINESTRING));
*/
export function setEditorMode(
mode: string
@@ -1729,6 +1755,28 @@ export function toggleEditorVisibility(): Merge<
};
}
+export type ConvertEditorFeaturesToLayerUpdaterAction = void;
+/**
+ * Convert editor sketch features into a GeoJSON dataset and layer, then clear the sketches.
+ * The new dataset/layer is labeled `Drawn Geometry` plus a two-digit number.
+ * No-ops when `enableDrawOnMapSketches` is false in application config.
+ * @memberof visStateActions
+ * @return action
+ * @public
+ * @example
+ * import {convertEditorFeaturesToLayer} from '@kepler.gl/actions';
+ *
+ * this.props.dispatch(convertEditorFeaturesToLayer());
+ */
+export function convertEditorFeaturesToLayer(): Merge<
+ ConvertEditorFeaturesToLayerUpdaterAction,
+ {type: typeof ActionTypes.CONVERT_EDITOR_FEATURES_TO_LAYER}
+> {
+ return {
+ type: ActionTypes.CONVERT_EDITOR_FEATURES_TO_LAYER
+ };
+}
+
type FileContent = {
fileName: string;
header: string[];
diff --git a/src/components/src/common/icons/draw-point.tsx b/src/components/src/common/icons/draw-point.tsx
new file mode 100644
index 000000000..ce1861c66
--- /dev/null
+++ b/src/components/src/common/icons/draw-point.tsx
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class DrawPoint extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'data-ex-icons-draw-point',
+ viewBox: '0 0 22 16'
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <circle cx="11" cy="8" r="5" stroke="currentColor" fill="transparent" strokeWidth="1.5" />
+ <circle cx="11" cy="8" r="2" />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/icons/index.tsx b/src/components/src/common/icons/index.tsx
index 78f1ae1cf..6070912a6 100644
--- a/src/components/src/common/icons/index.tsx
+++ b/src/components/src/common/icons/index.tsx
@@ -83,6 +83,8 @@ export {default as CodeAlt} from './code-alt';
export {default as Warning} from './warning';
export {default as WarningSign} from './warning-sign';
export {default as DrawPolygon} from './draw-polygon';
+export {default as DrawPoint} from './draw-point';
+export {default as LineString} from './line-string';
export {default as Polygon} from './polygon';
export {default as Rectangle} from './rectangle';
export {default as TimelineMarker} from './timeline-marker';
diff --git a/src/components/src/common/icons/line-string.tsx b/src/components/src/common/icons/line-string.tsx
new file mode 100644
index 000000000..4c798ff6c
--- /dev/null
+++ b/src/components/src/common/icons/line-string.tsx
@@ -0,0 +1,41 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class LineString extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'data-ex-icons-line-string',
+ viewBox: '0 0 22 16'
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <path d="M2 13L8 3L14 11L20 3" stroke="currentColor" fill="transparent" strokeWidth="1.5" />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 15C3.10457 15 4 14.1046 4 13C4 11.8954 3.10457 11 2 11C0.89543 11 0 11.8954 0 13C0 14.1046 0.89543 15 2 15Z"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M8 5C9.10457 5 10 4.10457 10 3C10 1.89543 9.10457 1 8 1C6.89543 1 6 1.89543 6 3C6 4.10457 6.89543 5 8 5Z"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M14 13C15.1046 13 16 12.1046 16 11C16 9.89543 15.1046 9 14 9C12.8954 9 12 9.89543 12 11C12 12.1046 12.8954 13 14 13Z"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M20 5C21.1046 5 22 4.10457 22 3C22 1.89543 21.1046 1 20 1C18.8954 1 18 1.89543 18 3C18 4.10457 18.8954 5 20 5Z"
+ />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/toolbar-item.tsx b/src/components/src/common/toolbar-item.tsx
index df51fb68d..21e3ac852 100644
--- a/src/components/src/common/toolbar-item.tsx
+++ b/src/components/src/common/toolbar-item.tsx
@@ -6,9 +6,11 @@ import styled from 'styled-components';
import classnames from 'classnames';
import {FormattedMessage} from '@kepler.gl/localization';
import {ComponentType, MouseEvent} from 'react';
+import TippyTooltip from './tippy-tooltip';
interface StyledDivProps {
$active?: boolean;
+ $disabled?: boolean;
}
const StyledDiv = styled.div.attrs(props => ({
@@ -26,6 +28,9 @@ const StyledDiv = styled.div.attrs(props => ({
border-radius: ${props => props.theme.toolbarItemBorderRaddius};
background-color: ${props =>
props.$active ? props.theme.toolbarItemBgdHover : props.theme.dropdownListBgd};
+ opacity: ${props => (props.$disabled ? 0.4 : 1)};
+ // Keep hover so tooltips still work when the action is disabled.
+ pointer-events: auto;
.toolbar-item__svg-container {
margin-bottom: 4px;
@@ -41,7 +46,7 @@ const StyledDiv = styled.div.attrs(props => ({
svg {
color: ${props => props.theme.toolbarItemIconHover};
}
- cursor: pointer;
+ cursor: ${props => (props.$disabled ? 'default' : 'pointer')};
}
`;
@@ -49,37 +54,63 @@ export type ToolbarItemProps = {
id?: string;
key?: string;
label: string;
+ tooltip?: string;
className?: string;
active?: boolean;
+ disabled?: boolean;
onClose?: () => void;
onClick: ((event: MouseEvent<HTMLDivElement>) => void) | null;
icon?: ComponentType<any>;
};
-const ToolbarItem = React.memo((props: ToolbarItemProps) => (
- <StyledDiv
- id={props.id}
- className={props.className}
- $active={props.active}
- onClick={e => {
- e.stopPropagation();
- e.preventDefault();
- if (typeof props.onClose === 'function') {
- props.onClose();
- }
- props.onClick?.(e);
- }}
- >
- {props.icon && (
- <div className="toolbar-item__svg-container">
- <props.icon />
+const ToolbarItem = React.memo((props: ToolbarItemProps) => {
+ const item = (
+ <StyledDiv
+ id={props.id}
+ className={props.className}
+ $active={props.active}
+ $disabled={props.disabled}
+ onClick={e => {
+ e.stopPropagation();
+ e.preventDefault();
+ if (props.disabled) {
+ return;
+ }
+ if (typeof props.onClose === 'function') {
+ props.onClose();
+ }
+ props.onClick?.(e);
+ }}
+ >
+ {props.icon && (
+ <div className="toolbar-item__svg-container">
+ <props.icon />
+ </div>
+ )}
+ <div className="toolbar-item__title">
+ <FormattedMessage id={props.label} />
</div>
- )}
- <div className="toolbar-item__title">
- <FormattedMessage id={props.label} />
- </div>
- </StyledDiv>
-));
+ </StyledDiv>
+ );
+
+ const tooltip = props.tooltip;
+ if (!tooltip) {
+ return item;
+ }
+
+ return (
+ <TippyTooltip
+ placement="left"
+ render={() => (
+ <div>
+ <FormattedMessage id={tooltip} />
+ </div>
+ )}
+ >
+ {item}
+ </TippyTooltip>
+ );
+});
ToolbarItem.displayName = 'ToolbarItem';
diff --git a/src/components/src/editor/editor.tsx b/src/components/src/editor/editor.tsx
index 34650ffea..c284c0bc8 100644
--- a/src/components/src/editor/editor.tsx
+++ b/src/components/src/editor/editor.tsx
@@ -44,6 +44,7 @@ interface EditorProps {
onSelect: (f: Feature | null) => any;
onSetEditorMode: (m: any) => void;
onDeleteFeature: (f: Feature) => any;
+ onSetFeatureProperties: (f: Feature, properties: Record<string, unknown>) => any;
onTogglePolygonFilter: (l: Layer, f: Feature) => any;
}
@@ -65,6 +66,7 @@ export default function EditorFactory(
currentFilter,
onClose,
onDeleteFeature,
+ onSetFeatureProperties,
onToggleLayer,
position
}) => {
@@ -82,6 +84,7 @@ export default function EditorFactory(
currentFilter={currentFilter}
onClose={onClose}
onDeleteFeature={onDeleteFeature}
+ onSetFeatureProperties={onSetFeatureProperties}
onToggleLayer={onToggleLayer}
position={position || null}
/>
@@ -139,21 +142,39 @@ export default function EditorFactory(
isInFocus = () => document.activeElement?.id === DECKGL_RENDER_LAYER;
+ isTypingTarget = (target: EventTarget | null) => {
+ const element = target as HTMLElement | null;
+ if (!element) {
+ return false;
+ }
+ const tagName = element.tagName;
+ return (
+ tagName === 'INPUT' ||
+ tagName === 'TEXTAREA' ||
+ tagName === 'SELECT' ||
+ Boolean(element.isContentEditable)
+ );
+ };
+
_onKeyPressed = (event: KeyboardEvent) => {
+ const isEscape = event.keyCode === KeyEvent.DOM_VK_ESCAPE || event.key === 'Escape';
+ if (isEscape && !this.isTypingTarget(event.target)) {
+ const drawing = EditorLayerUtils.isDrawingActive(true, this.props.editor.mode);
+ if (drawing) {
+ this.props.onSetEditorMode(EDITOR_MODES.EDIT);
+ this.props.onSelect(null);
+ } else if (this.isInFocus()) {
+ this.props.onSelect(null);
+ }
+ return;
+ }
+
if (this.isInFocus()) {
switch (event.keyCode) {
case KeyEvent.DOM_VK_DELETE:
case KeyEvent.DOM_VK_BACK_SPACE:
this._onDeleteSelectedFeature();
break;
- case KeyEvent.DOM_VK_ESCAPE:
- // reset active drawing
- if (EditorLayerUtils.isDrawingActive(true, this.props.editor.mode)) {
- this.props.onSetEditorMode(EDITOR_MODES.EDIT);
- }
-
- this.props.onSelect(null);
- break;
default:
break;
}
@@ -181,6 +202,10 @@ export default function EditorFactory(
}
};
+ _onSetFeatureProperties = (feature: Feature, properties: Record<string, unknown>) => {
+ this.props.onSetFeatureProperties(feature, properties);
+ };
+
render() {
const {className, datasets, editor, style, index} = this.props;
const {selectedFeature, selectionContext} = editor;
@@ -198,6 +223,9 @@ export default function EditorFactory(
currentFilter={currentFilter}
onClose={this._closeFeatureAction}
onDeleteFeature={this._onDeleteSelectedFeature}
+ onSetFeatureProperties={
+ this._onSetFeatureProperties as FeatureActionPanelProps['onSetFeatureProperties']
+ }
onToggleLayer={this._togglePolygonFilter}
position={position || null}
className={className}
diff --git a/src/components/src/editor/feature-action-panel.tsx b/src/components/src/editor/feature-action-panel.tsx
index 98edd0ba6..0f102c015 100644
--- a/src/components/src/editor/feature-action-panel.tsx
+++ b/src/components/src/editor/feature-action-panel.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {useCallback, useState, ComponentType} from 'react';
+import React, {useCallback, useEffect, useState, ComponentType} from 'react';
import {useIntl} from 'react-intl';
import copy from 'copy-to-clipboard';
import {useDismiss, useFloating, useInteractions} from '@floating-ui/react';
@@ -12,15 +12,20 @@ import {Layer} from '@kepler.gl/layers';
import {Filter} from '@kepler.gl/types';
import {Feature} from '@deck.gl-community/editable-layers';
import {Datasets} from '@kepler.gl/table';
-import {canApplyFeatureFilter} from '@kepler.gl/utils';
+import {canApplyFeatureFilter, getApplicationConfig} from '@kepler.gl/utils';
import ActionPanel, {ActionPanelItem} from '../common/action-panel';
-import {Trash, Layers, Copy, Checkmark} from '../common/icons';
+import {Trash, Layers, Copy, Checkmark, Edit} from '../common/icons';
+import FeaturePropertiesEditor from './feature-properties-editor';
const LAYOVER_OFFSET = 4;
const StyledActionsLayer = styled.div`
position: absolute;
+ display: flex;
+ flex-direction: row;
+ align-items: flex-start;
+ gap: 4px;
.layer-panel-item-disabled {
color: ${props => props.theme.textColor};
}
@@ -29,7 +34,8 @@ const defaultActionIcons = {
remove: Trash,
layer: Layers,
copy: Copy,
- copied: Checkmark
+ copied: Checkmark,
+ edit: Edit
};
PureFeatureActionPanelFactory.deps = [];
@@ -45,6 +51,7 @@ export interface FeatureActionPanelProps {
currentFilter?: Filter;
onToggleLayer: (layer: Layer) => void;
onDeleteFeature: () => void;
+ onSetFeatureProperties?: (feature: Feature, properties: Record<string, unknown>) => void;
onClose?: () => void;
children?: React.ReactNode;
actionIcons?: {
@@ -62,11 +69,13 @@ export function PureFeatureActionPanelFactory(): React.FC<FeatureActionPanelProp
currentFilter,
onToggleLayer,
onDeleteFeature,
+ onSetFeatureProperties,
actionIcons = defaultActionIcons,
children,
onClose
}: FeatureActionPanelProps) => {
const [copied, setCopied] = useState(false);
+ const [showProperties, setShowProperties] = useState(false);
const {layerId = []} = currentFilter || {};
const intl = useIntl();
@@ -87,11 +96,16 @@ export function PureFeatureActionPanelFactory(): React.FC<FeatureActionPanelProp
setCopied(true);
}, [selectedFeature?.geometry]);
+ useEffect(() => {
+ setShowProperties(false);
+ }, [selectedFeature?.id]);
+
if (!position) {
return null;
}
- const isFilterLayerDisabled = !canApplyFeatureFilter(selectedFeature as any);
+ const canFilterLayers = canApplyFeatureFilter(selectedFeature as any);
+ const enableSketches = getApplicationConfig().enableDrawOnMapSketches;
return (
<StyledActionsLayer
ref={refs.setFloating}
@@ -103,41 +117,53 @@ export function PureFeatureActionPanelFactory(): React.FC<FeatureActionPanelProp
}}
>
<ActionPanel>
- <ActionPanelItem
- className="editor-layers-list"
- label={intl.formatMessage({id: 'editor.filterLayer', defaultMessage: 'Filter layers'})}
- Icon={actionIcons.layer}
- isDisabled={isFilterLayerDisabled}
- tooltipText={
- isFilterLayerDisabled ? intl.formatMessage({id: 'editor.filterLayerDisabled'}) : null
- }
- >
- {layers.length ? (
- layers.map((layer, index) => (
+ {canFilterLayers ? (
+ <ActionPanelItem
+ className="editor-layers-list"
+ label={intl.formatMessage({
+ id: 'editor.filterLayer',
+ defaultMessage: 'Filter layers'
+ })}
+ Icon={actionIcons.layer}
+ >
+ {layers.length ? (
+ layers.map((layer, index) => (
+ <ActionPanelItem
+ key={index}
+ label={layer.config.label}
+ // @ts-ignore
+ color={datasets[layer.config.dataId].color}
+ isSelection={true}
+ isActive={layerId.includes(layer.id)}
+ onClick={() => onToggleLayer(layer)}
+ className="layer-panel-item"
+ />
+ ))
+ ) : (
<ActionPanelItem
- key={index}
- label={layer.config.label}
- // @ts-ignore
- color={datasets[layer.config.dataId].color}
- isSelection={true}
- isActive={layerId.includes(layer.id)}
- onClick={() => onToggleLayer(layer)}
- className="layer-panel-item"
+ key={'no-layers'}
+ label={intl.formatMessage({
+ id: 'editor.noLayersToFilter',
+ defaultMessage: 'No layers to filter'
+ })}
+ isSelection={false}
+ isActive={false}
+ className="layer-panel-item-disabled"
/>
- ))
- ) : (
- <ActionPanelItem
- key={'no-layers'}
- label={intl.formatMessage({
- id: 'editor.noLayersToFilter',
- defaultMessage: 'No layers to filter'
- })}
- isSelection={false}
- isActive={false}
- className="layer-panel-item-disabled"
- />
- )}
- </ActionPanelItem>
+ )}
+ </ActionPanelItem>
+ ) : null}
+ {enableSketches ? (
+ <ActionPanelItem
+ label={intl.formatMessage({
+ id: 'editor.editProperties',
+ defaultMessage: 'Edit Properties'
+ })}
+ className="edit-properties-panel-item"
+ Icon={actionIcons.edit}
+ onClick={() => setShowProperties(open => !open)}
+ />
+ ) : null}
<ActionPanelItem
label={intl.formatMessage({id: 'editor.copyGeometry', defaultMessage: 'Copy Geometry'})}
className="delete-panel-item"
@@ -152,6 +178,12 @@ export function PureFeatureActionPanelFactory(): React.FC<FeatureActionPanelProp
onClick={onDeleteFeature}
/>
</ActionPanel>
+ {enableSketches && showProperties ? (
+ <FeaturePropertiesEditor
+ selectedFeature={selectedFeature}
+ onSetFeatureProperties={onSetFeatureProperties}
+ />
+ ) : null}
</StyledActionsLayer>
);
};
diff --git a/src/components/src/editor/feature-properties-editor.tsx b/src/components/src/editor/feature-properties-editor.tsx
new file mode 100644
index 000000000..8ee2692d9
--- /dev/null
+++ b/src/components/src/editor/feature-properties-editor.tsx
@@ -0,0 +1,242 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, useEffect, useState} from 'react';
+import {useIntl} from 'react-intl';
+import styled from 'styled-components';
+import {Feature} from '@deck.gl-community/editable-layers';
+import {getUserFeatureProperties, isReservedEditorProperty} from '@kepler.gl/utils';
+
+import {Input} from '../common/styled-components';
+import {Trash} from '../common/icons';
+
+type PropertyRow = {
+ id: string;
+ name: string;
+ value: string;
+};
+
+type FeaturePropertiesEditorProps = {
+ selectedFeature: Feature | null;
+ onSetFeatureProperties?: (feature: Feature, properties: Record<string, unknown>) => void;
+};
+
+const StyledPropertiesEditor = styled.div`
+ background-color: ${props => props.theme.dropdownListBgd};
+ box-shadow: ${props => props.theme.dropdownListShadow};
+ color: ${props => props.theme.textColor};
+ min-width: 260px;
+ padding: 8px;
+ pointer-events: auto;
+`;
+
+const StyledHeader = styled.div`
+ display: grid;
+ grid-template-columns: 1fr 1fr 18px;
+ gap: 6px;
+ font-size: 11px;
+ line-height: 12px;
+ margin-bottom: 6px;
+ opacity: 0.7;
+ text-transform: none;
+`;
+
+const StyledRow = styled.div`
+ display: grid;
+ grid-template-columns: 1fr 1fr 18px;
+ gap: 6px;
+ align-items: center;
+ margin-bottom: 6px;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+`;
+
+const StyledPropertyInput = styled(Input)`
+ height: 24px;
+ font-size: 11px;
+ padding: 2px 6px;
+ text-transform: none;
+ width: 100%;
+
+ &:hover {
+ cursor: text;
+ }
+`;
+
+const StyledRemoveButton = styled.button`
+ align-items: center;
+ background: none;
+ border: 0;
+ color: ${props => props.theme.subtextColor};
+ cursor: pointer;
+ display: flex;
+ height: 18px;
+ justify-content: center;
+ padding: 0;
+ width: 18px;
+
+ &:hover {
+ color: ${props => props.theme.textColorHl};
+ }
+`;
+
+let rowCounter = 0;
+
+function createRow(name = '', value = ''): PropertyRow {
+ rowCounter += 1;
+ return {id: `property-row-${rowCounter}`, name, value};
+}
+
+function rowsFromFeature(feature: Feature | null): PropertyRow[] {
+ const properties = getUserFeatureProperties(feature as any);
+ const rows = Object.entries(properties).map(([name, value]) =>
+ createRow(name, value == null ? '' : String(value))
+ );
+ rows.push(createRow());
+ return rows;
+}
+
+function userPropertiesFromRows(rows: PropertyRow[]): Record<string, string> {
+ return rows.reduce<Record<string, string>>((acc, row) => {
+ const name = row.name.trim();
+ if (!name || isReservedEditorProperty(name)) {
+ return acc;
+ }
+ acc[name] = row.value;
+ return acc;
+ }, {});
+}
+
+function sameProperties(left: Record<string, unknown>, right: Record<string, unknown>): boolean {
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
+ for (const key of keys) {
+ if (String(left[key] ?? '') !== String(right[key] ?? '')) {
+ return false;
+ }
+ }
+ return true;
+}
+
+function ensureTrailingEmptyRow(rows: PropertyRow[]): PropertyRow[] {
+ const last = rows[rows.length - 1];
+ if (!last || last.name.trim() || last.value) {
+ return [...rows, createRow()];
+ }
+ return rows;
+}
+
+export default function FeaturePropertiesEditor({
+ selectedFeature,
+ onSetFeatureProperties
+}: FeaturePropertiesEditorProps) {
+ const intl = useIntl();
+ const [rows, setRows] = useState<PropertyRow[]>(() => rowsFromFeature(selectedFeature));
+
+ useEffect(() => {
+ setRows(rowsFromFeature(selectedFeature));
+ }, [selectedFeature?.id]);
+
+ const commitRows = useCallback(
+ (nextRows: PropertyRow[]) => {
+ if (!selectedFeature || !onSetFeatureProperties) {
+ return;
+ }
+ const properties = userPropertiesFromRows(nextRows);
+ if (sameProperties(getUserFeatureProperties(selectedFeature as any), properties)) {
+ return;
+ }
+ onSetFeatureProperties(selectedFeature, properties);
+ },
+ [onSetFeatureProperties, selectedFeature]
+ );
+
+ const updateRow = useCallback(
+ (id: string, patch: Partial<PropertyRow>, shouldCommit: boolean) => {
+ const nextRows = rows.map(row => (row.id === id ? {...row, ...patch} : row));
+ const withEmpty = shouldCommit ? ensureTrailingEmptyRow(nextRows) : nextRows;
+ setRows(withEmpty);
+ if (shouldCommit) {
+ commitRows(withEmpty);
+ }
+ },
+ [commitRows, rows]
+ );
+
+ const removeRow = useCallback(
+ (id: string) => {
+ const remaining = rows.filter(row => row.id !== id);
+ const nextRows = remaining.length ? ensureTrailingEmptyRow(remaining) : [createRow()];
+ setRows(nextRows);
+ commitRows(nextRows);
+ },
+ [commitRows, rows]
+ );
+
+ return (
+ <StyledPropertiesEditor
+ className="feature-properties-editor"
+ onMouseDown={event => event.stopPropagation()}
+ onClick={event => event.stopPropagation()}
+ >
+ <StyledHeader>
+ <span>{intl.formatMessage({id: 'editor.propertyName', defaultMessage: 'Property'})}</span>
+ <span>{intl.formatMessage({id: 'editor.propertyValue', defaultMessage: 'Value'})}</span>
+ </StyledHeader>
+ {rows.map(row => (
+ <StyledRow key={row.id}>
+ <StyledPropertyInput
+ className="feature-property-name"
+ secondary
+ value={row.name}
+ placeholder={intl.formatMessage({
+ id: 'editor.propertyName',
+ defaultMessage: 'Property'
+ })}
+ onChange={event => updateRow(row.id, {name: event.target.value}, false)}
+ onBlur={() => updateRow(row.id, {}, true)}
+ onKeyDown={event => {
+ if (event.key === 'Enter') {
+ event.currentTarget.blur();
+ }
+ }}
+ />
+ <StyledPropertyInput
+ className="feature-property-value"
+ secondary
+ value={row.value}
+ placeholder={intl.formatMessage({
+ id: 'editor.propertyValue',
+ defaultMessage: 'Value'
+ })}
+ onChange={event =>
+ updateRow(row.id, {value: event.target.value}, Boolean(row.name.trim()))
+ }
+ onBlur={() => updateRow(row.id, {}, true)}
+ onKeyDown={event => {
+ if (event.key === 'Enter') {
+ event.currentTarget.blur();
+ }
+ }}
+ />
+ {row.name.trim() || row.value ? (
+ <StyledRemoveButton
+ type="button"
+ className="feature-property-remove"
+ aria-label={intl.formatMessage({
+ id: 'editor.removeProperty',
+ defaultMessage: 'Remove property'
+ })}
+ onClick={() => removeRow(row.id)}
+ >
+ <Trash height="12px" />
+ </StyledRemoveButton>
+ ) : (
+ <span />
+ )}
+ </StyledRow>
+ ))}
+ </StyledPropertiesEditor>
+ );
+}
diff --git a/src/components/src/editor/filter-feature-badges.tsx b/src/components/src/editor/filter-feature-badges.tsx
new file mode 100644
index 000000000..a6c7d7cba
--- /dev/null
+++ b/src/components/src/editor/filter-feature-badges.tsx
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useMemo} from 'react';
+import {useIntl} from 'react-intl';
+import styled from 'styled-components';
+
+import {Filter, Feature} from '@kepler.gl/types';
+import {getFilterFeatureAnchor} from '@kepler.gl/utils';
+
+import {FilterFunnel} from '../common/icons';
+import {MapViewport, isPointVisibleOnGlobe} from '../annotations/annotation-utils';
+
+const BADGE_SIZE = 22;
+const BADGE_OFFSET_X = 6;
+const BADGE_OFFSET_Y = -BADGE_SIZE - 2;
+// Same blue as the editor polygon outline ([0x26, 0xb5, 0xf2]).
+const EDITOR_OUTLINE_COLOR = '#26b5f2';
+
+const BadgeLayer = styled.div`
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ z-index: 1;
+`;
+
+const FilterBadge = styled.button`
+ position: absolute;
+ width: ${BADGE_SIZE}px;
+ height: ${BADGE_SIZE}px;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 50%;
+ border: 1px solid ${EDITOR_OUTLINE_COLOR};
+ background-color: ${props => props.theme.panelBackground};
+ color: ${EDITOR_OUTLINE_COLOR};
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.35);
+ svg {
+ color: ${EDITOR_OUTLINE_COLOR};
+ stroke: ${EDITOR_OUTLINE_COLOR};
+ }
+ pointer-events: auto;
+ cursor: pointer;
+`;
+
+export type FilterFeatureBadgesProps = {
+ filters: Filter[];
+ viewport?: MapViewport | null;
+ isGlobeEnabled?: boolean;
+ onSelect?: (feature: Feature) => void;
+};
+
+function FilterFeatureBadges({
+ filters,
+ viewport,
+ isGlobeEnabled,
+ onSelect
+}: FilterFeatureBadgesProps) {
+ const intl = useIntl();
+ const badges = useMemo(() => {
+ if (!viewport?.project) {
+ return [];
+ }
+ return filters.reduce<
+ {id: string; x: number; y: number; feature: Feature}[]
+ >((acc, filter) => {
+ const feature = filter?.value as Feature | undefined;
+ if (!feature) {
+ return acc;
+ }
+ const anchor = getFilterFeatureAnchor(feature);
+ if (!anchor) {
+ return acc;
+ }
+ if (isGlobeEnabled && !isPointVisibleOnGlobe(anchor, viewport)) {
+ return acc;
+ }
+ const projected = viewport.project(anchor);
+ if (
+ !projected ||
+ !Number.isFinite(projected[0]) ||
+ !Number.isFinite(projected[1])
+ ) {
+ return acc;
+ }
+ acc.push({
+ id: String(feature.id || filter.id),
+ x: projected[0] + BADGE_OFFSET_X,
+ y: projected[1] + BADGE_OFFSET_Y,
+ feature
+ });
+ return acc;
+ }, []);
+ }, [filters, viewport, isGlobeEnabled]);
+
+ if (!badges.length) {
+ return null;
+ }
+
+ const polygonFilterLabel = intl.formatMessage({
+ id: 'editor.polygonFilter',
+ defaultMessage: 'Polygon filter'
+ });
+
+ return (
+ <BadgeLayer className="editor-filter-badges">
+ {badges.map(badge => (
+ <FilterBadge
+ key={badge.id}
+ type="button"
+ title={polygonFilterLabel}
+ aria-label={polygonFilterLabel}
+ style={{left: badge.x, top: badge.y}}
+ onClick={event => {
+ event.stopPropagation();
+ onSelect?.(badge.feature);
+ }}
+ >
+ <FilterFunnel height="12px" />
+ </FilterBadge>
+ ))}
+ </BadgeLayer>
+ );
+}
+
+export default React.memo(FilterFeatureBadges);
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index 86ceca616..60eb40f56 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -27,6 +27,7 @@ import {
} from './map/attribution';
import EditorFactory from './editor/editor';
+import FilterFeatureBadges from './editor/filter-feature-badges';
import {AnnotationOverlay} from './annotations';
// utils
@@ -1452,6 +1453,7 @@ export default function MapContainerFactory(
onSetLocale={uiStateActions.setLocale}
onSetTheme={uiStateActions.setTheme}
onToggleEditorVisibility={visStateActions.toggleEditorVisibility}
+ onConvertEditorFeaturesToLayer={visStateActions.convertEditorFeaturesToLayer}
onLayerVisConfigChange={visStateActions.layerVisConfigChange}
onToggleLayerVisibility={this._handleToggleLayerVisibility}
mapHeight={mapState.height}
@@ -1472,6 +1474,7 @@ export default function MapContainerFactory(
filters={this.polygonFiltersSelector(this.props)}
layers={layers}
onDeleteFeature={visStateActions.deleteFeature}
+ onSetFeatureProperties={visStateActions.setEditorFeatureProperties}
onSelect={visStateActions.setSelectedFeature}
onTogglePolygonFilter={visStateActions.setPolygonFilterLayer}
onSetEditorMode={visStateActions.setEditorMode}
@@ -1481,6 +1484,14 @@ export default function MapContainerFactory(
display: editor.visible ? 'block' : 'none'
}}
/>
+ {editor.visible ? (
+ <FilterFeatureBadges
+ filters={this.polygonFiltersSelector(this.props)}
+ viewport={this._getAnnotationViewport(mapState, internalViewState)}
+ isGlobeEnabled={Boolean(mapState.globe?.enabled)}
+ onSelect={visStateActions.setSelectedFeature}
+ />
+ ) : null}
<AnnotationOverlay
annotations={visState.annotations}
selectedAnnotationId={visState.selectedAnnotationId}
diff --git a/src/components/src/map/map-control-toolbar.tsx b/src/components/src/map/map-control-toolbar.tsx
index 12967d4b6..53543d958 100644
--- a/src/components/src/map/map-control-toolbar.tsx
+++ b/src/components/src/map/map-control-toolbar.tsx
@@ -21,6 +21,16 @@ function MapControlToolbar() {
width: 16px;
height: 16px;
margin-right: 10px;
+ flex-shrink: 0;
+ overflow: hidden;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+
+ svg {
+ width: 16px;
+ height: 16px;
+ }
}
.toolbar-item__title {
diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsx
index e17ff1070..cc469d4fe 100644
--- a/src/components/src/map/map-control.tsx
+++ b/src/components/src/map/map-control.tsx
@@ -70,6 +70,7 @@ export type MapControlProps = {
onToggleMapControl: (control: string) => void;
onSetEditorMode: (mode: string) => void;
onToggleEditorVisibility: () => void;
+ onConvertEditorFeaturesToLayer?: () => void;
onLayerVisConfigChange: (oldLayer: Layer, newVisConfig: Partial<LayerVisConfig>) => void;
onToggleLayerVisibility?: (layer: Layer) => void;
top: number;
diff --git a/src/components/src/map/map-draw-panel.tsx b/src/components/src/map/map-draw-panel.tsx
index 032f9fd34..1edd73c2d 100644
--- a/src/components/src/map/map-draw-panel.tsx
+++ b/src/components/src/map/map-draw-panel.tsx
@@ -3,9 +3,23 @@
import React, {useCallback} from 'react';
import classnames from 'classnames';
+import copy from 'copy-to-clipboard';
+import styled from 'styled-components';
import {EDITOR_MODES} from '@kepler.gl/constants';
-import {CursorClick, DrawPolygon, EyeSeen, EyeUnseen, Polygon, Rectangle} from '../common/icons';
+import {editorFeaturesToFeatureCollection, getApplicationConfig} from '@kepler.gl/utils';
+import {
+ Copy,
+ CursorClick,
+ DrawPoint,
+ DrawPolygon,
+ EyeSeen,
+ EyeUnseen,
+ Layers,
+ LineString,
+ Polygon,
+ Rectangle
+} from '../common/icons';
import {MapControlButton} from '../common/styled-components';
import ToolbarItem from '../common/toolbar-item';
import MapControlTooltipFactory from './map-control-tooltip';
@@ -13,6 +27,27 @@ import MapControlToolbarFactory from './map-control-toolbar';
import {Editor, MapControls} from '@kepler.gl/types';
import {BaseProps} from '../common/icons';
+const ToolbarSeparator = styled.div`
+ height: 1px;
+ margin: 4px 12px;
+ background-color: ${props => props.theme.panelHeaderIcon};
+ opacity: 0.2;
+`;
+
+const DrawControls = styled.div`
+ position: relative;
+
+ .convert-to-layer .toolbar-item__title {
+ flex: 1;
+ min-width: 0;
+ white-space: pre;
+ text-align: center;
+ line-height: 1.25;
+ overflow: hidden;
+ font-size: 11px;
+ }
+`;
+
MapDrawPanelFactory.deps = [MapControlTooltipFactory, MapControlToolbarFactory];
export type MapDrawPanelProps = {
@@ -21,6 +56,7 @@ export type MapDrawPanelProps = {
onToggleMapControl: (control: string) => void;
onSetEditorMode: (mode: string) => void;
onToggleEditorVisibility: () => void;
+ onConvertEditorFeaturesToLayer?: () => void;
actionIcons: {[id: string]: React.ComponentType<Partial<BaseProps>>};
};
@@ -34,7 +70,11 @@ function MapDrawPanelFactory(
polygon: DrawPolygon,
cursor: CursorClick,
innerPolygon: Polygon,
- rectangle: Rectangle
+ rectangle: Rectangle,
+ point: DrawPoint,
+ line: LineString,
+ copy: Copy,
+ layers: Layers
};
const MapDrawPanel: React.FC<MapDrawPanelProps> = React.memo(
@@ -43,20 +83,29 @@ function MapDrawPanelFactory(
mapControls,
onToggleMapControl,
onSetEditorMode,
+ onConvertEditorFeaturesToLayer,
actionIcons = defaultActionIcons
}) => {
const isActive = mapControls?.mapDraw?.active;
+ const hasSketchFeatures = Boolean(editor?.features?.length);
+ const enableSketches = getApplicationConfig().enableDrawOnMapSketches;
const onToggleMenuPanel = useCallback(() => {
if (!isActive) {
onSetEditorMode(EDITOR_MODES.DRAW_RECTANGLE);
}
onToggleMapControl('mapDraw');
}, [isActive, onToggleMapControl, onSetEditorMode]);
+ const onCopyAllGeometry = useCallback(() => {
+ if (!editor?.features?.length) {
+ return;
+ }
+ copy(JSON.stringify(editorFeaturesToFeatureCollection(editor.features)));
+ }, [editor?.features]);
if (!mapControls?.mapDraw?.show) {
return null;
}
return (
- <div className="map-draw-controls" style={{position: 'relative'}}>
+ <DrawControls className="map-draw-controls">
{isActive ? (
<MapControlToolbar $show={isActive}>
<ToolbarItem
@@ -66,6 +115,24 @@ function MapDrawPanelFactory(
icon={actionIcons.cursor}
active={editor.mode === EDITOR_MODES.EDIT}
/>
+ {enableSketches ? (
+ <ToolbarItem
+ className="draw-point"
+ onClick={() => onSetEditorMode(EDITOR_MODES.DRAW_POINT)}
+ label="toolbar.point"
+ icon={actionIcons.point}
+ active={editor.mode === EDITOR_MODES.DRAW_POINT}
+ />
+ ) : null}
+ {enableSketches ? (
+ <ToolbarItem
+ className="draw-line"
+ onClick={() => onSetEditorMode(EDITOR_MODES.DRAW_LINESTRING)}
+ label="toolbar.line"
+ icon={actionIcons.line}
+ active={editor.mode === EDITOR_MODES.DRAW_LINESTRING}
+ />
+ ) : null}
<ToolbarItem
className="draw-feature"
onClick={() => onSetEditorMode(EDITOR_MODES.DRAW_POLYGON)}
@@ -80,6 +147,27 @@ function MapDrawPanelFactory(
icon={actionIcons.rectangle}
active={editor.mode === EDITOR_MODES.DRAW_RECTANGLE}
/>
+ {enableSketches ? (
+ <>
+ <ToolbarSeparator />
+ <ToolbarItem
+ className="copy-all-geometry"
+ onClick={onCopyAllGeometry}
+ label="toolbar.copyAll"
+ tooltip="tooltip.copyAllSketches"
+ icon={actionIcons.copy}
+ disabled={!hasSketchFeatures}
+ />
+ <ToolbarItem
+ className="convert-to-layer"
+ onClick={() => onConvertEditorFeaturesToLayer?.()}
+ label="toolbar.convertToLayer"
+ tooltip="tooltip.convertToLayer"
+ icon={actionIcons.layers}
+ disabled={!hasSketchFeatures}
+ />
+ </>
+ ) : null}
</MapControlToolbar>
) : null}
<MapControlTooltip id="map-draw" message="tooltip.DrawOnMap">
@@ -94,7 +182,7 @@ function MapDrawPanelFactory(
<actionIcons.polygon height="18px" />
</MapControlButton>
</MapControlTooltip>
- </div>
+ </DrawControls>
);
}
);
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index cb08777b8..7726b1b1d 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -1288,9 +1288,18 @@ export const EDITOR_LAYER_PICKING_RADIUS = 6;
export const EDITOR_MODES = {
DRAW_POLYGON: 'DRAW_POLYGON',
DRAW_RECTANGLE: 'DRAW_RECTANGLE',
+ DRAW_LINESTRING: 'DRAW_LINESTRING',
+ DRAW_POINT: 'DRAW_POINT',
EDIT: 'EDIT_VERTEX'
};
+export const EDITOR_DRAW_MODES: string[] = [
+ EDITOR_MODES.DRAW_POLYGON,
+ EDITOR_MODES.DRAW_RECTANGLE,
+ EDITOR_MODES.DRAW_LINESTRING,
+ EDITOR_MODES.DRAW_POINT
+];
+
export const PLOT_TYPES = keyMirror({
histogram: null,
lineChart: null
diff --git a/src/layers/src/editor-layer/editor-layer-utils.ts b/src/layers/src/editor-layer/editor-layer-utils.ts
index a543a186e..f11e88477 100644
--- a/src/layers/src/editor-layer/editor-layer-utils.ts
+++ b/src/layers/src/editor-layer/editor-layer-utils.ts
@@ -2,7 +2,8 @@
// Copyright contributors to the kepler.gl project
import {Editor, Feature, FeatureSelectionContext, PickInfo} from '@kepler.gl/types';
-import {EDITOR_LAYER_ID, EDITOR_MODES} from '@kepler.gl/constants';
+import {EDITOR_DRAW_MODES, EDITOR_LAYER_ID, EDITOR_MODES} from '@kepler.gl/constants';
+import {isFilterFeature} from './feature-styles';
/**
* Returns true if drawing is active.
@@ -11,9 +12,7 @@ import {EDITOR_LAYER_ID, EDITOR_MODES} from '@kepler.gl/constants';
* @returs Returns true if drawing is active.
*/
export function isDrawingActive(editorMenuActive: boolean, mode: string): boolean {
- return (
- editorMenuActive && (mode === EDITOR_MODES.DRAW_POLYGON || mode === EDITOR_MODES.DRAW_RECTANGLE)
- );
+ return editorMenuActive && EDITOR_DRAW_MODES.includes(mode);
}
/**
@@ -52,13 +51,15 @@ export function onClick(
const drawingActive = isDrawingActive(editorMenuActive, editor.mode);
if (info?.layer?.id === EDITOR_LAYER_ID && info?.object) {
- const objectType = info.object.geometry?.type;
+ const isEditHandle = Boolean(
+ info.object.properties?.editHandleType || info.object.properties?.guideType
+ );
if (drawingActive) {
if (editor.selectedFeature) {
setSelectedFeature(null);
}
- } else if (objectType?.endsWith('Polygon') || objectType?.endsWith('Point')) {
+ } else {
let clickContext;
if (event.rightButton && Array.isArray(event.srcEvent?.point)) {
const {point} = event.srcEvent;
@@ -72,10 +73,10 @@ export function onClick(
};
}
- if (objectType?.endsWith('Polygon')) {
+ if (!isEditHandle && info.object.geometry) {
setSelectedFeature(info.object, clickContext);
} else {
- // don't select points
+ // Keep the current feature selected when clicking an edit handle
setSelectedFeature(editor.selectedFeature, clickContext);
}
}
@@ -165,6 +166,10 @@ export function getTooltip(
const tooltipText =
editor.mode === EDITOR_MODES.DRAW_RECTANGLE
? 'Click or drag to draw rectangle'
+ : editor.mode === EDITOR_MODES.DRAW_POINT
+ ? 'Click to add a point'
+ : editor.mode === EDITOR_MODES.DRAW_LINESTRING
+ ? 'Click to start a line. Double-click to finish'
: 'Click to start new feature';
return getTooltipObject(tooltipText, theme, {
@@ -178,7 +183,10 @@ export function getTooltip(
if (selectedFeature) {
if (!object || (object.id && object.id === selectedFeature.id)) {
- return getTooltipObject('Right click to view options\nDrag to move the feature', theme, {
+ const tooltipText = isFilterFeature(selectedFeature)
+ ? 'Filter region\nRight click to view options\nDrag to move the feature'
+ : 'Right click to view options\nDrag to move the feature';
+ return getTooltipObject(tooltipText, theme, {
leftOfCursor: closeToLeftEdge,
aboveCursor: closeToBottomEdge
});
@@ -186,10 +194,17 @@ export function getTooltip(
}
if (object?.properties?.editHandleType === 'intermediate') {
- return getTooltipObject('Click to insert a point', theme, {
- leftOfCursor: closeToLeftEdge,
- aboveCursor: closeToBottomEdge
- });
+ const isLine =
+ selectedFeature?.geometry?.type === 'LineString' ||
+ selectedFeature?.geometry?.type === 'MultiLineString';
+ return getTooltipObject(
+ isLine ? 'Drag to move the line\nClick to insert a point' : 'Click to insert a point',
+ theme,
+ {
+ leftOfCursor: closeToLeftEdge,
+ aboveCursor: closeToBottomEdge
+ }
+ );
}
if (object?.geometry?.type === 'Point' || object?.properties?.guideType === 'tentative') {
@@ -199,10 +214,16 @@ export function getTooltip(
});
}
- return getTooltipObject('Click to select the feature\nRight click to view options', theme, {
- leftOfCursor: closeToLeftEdge,
- aboveCursor: closeToBottomEdge
- });
+ return getTooltipObject(
+ isFilterFeature(object)
+ ? 'Click to select the filter\nRight click to view options'
+ : 'Click to select the feature\nRight click to view options',
+ theme,
+ {
+ leftOfCursor: closeToLeftEdge,
+ aboveCursor: closeToBottomEdge
+ }
+ );
}
return null;
diff --git a/src/layers/src/editor-layer/editor-layer.ts b/src/layers/src/editor-layer/editor-layer.ts
index e7ac38b0e..5a478a3ab 100644
--- a/src/layers/src/editor-layer/editor-layer.ts
+++ b/src/layers/src/editor-layer/editor-layer.ts
@@ -5,6 +5,8 @@ import {EditableGeoJsonLayer} from '@deck.gl-community/editable-layers';
import {Layer as DeckLayer, LayerProps as DeckLayerProps} from '@deck.gl/core';
import {
DrawPolygonMode,
+ DrawLineStringMode,
+ DrawPointMode,
TranslateMode,
CompositeMode,
GeoJsonEditMode
@@ -14,9 +16,10 @@ import {PathStyleExtension} from '@deck.gl/extensions';
import {EDITOR_LAYER_ID, EDITOR_MODES, EDITOR_LAYER_PICKING_RADIUS} from '@kepler.gl/constants';
import {Viewport, Editor, Feature, FeatureSelectionContext} from '@kepler.gl/types';
import {generateHashId} from '@kepler.gl/common-utils';
+import {getApplicationConfig} from '@kepler.gl/utils';
import {EDIT_TYPES} from './constants';
-import {LINE_STYLE, FEATURE_STYLE, EDIT_HANDLE_STYLE} from './feature-styles';
+import {LINE_STYLE, FEATURE_STYLE, EDIT_HANDLE_STYLE, getFeatureDashArray} from './feature-styles';
import {ModifyModeExtended} from './modify-mode-extended';
import {DrawRectangleModeExtended} from './draw-rectangle-mode-extended';
import {isDrawingActive} from './editor-layer-utils';
@@ -26,6 +29,12 @@ const DEFAULT_COMPOSITE_MODE = new CompositeMode([
new ModifyModeExtended() as unknown as GeoJsonEditMode
]);
+class DrawLineStringSketchMode extends DrawLineStringMode {
+ getTooltips() {
+ return [];
+ }
+}
+
export type GetEditorLayerProps = {
editorMenuActive: boolean;
editor: Editor;
@@ -64,6 +73,7 @@ export function getEditorLayer({
mapState
}: GetEditorLayerProps): DeckLayer<DeckLayerProps> {
const {mode: editorMode} = editor;
+ const sketchesEnabled = getApplicationConfig().enableDrawOnMapSketches;
let mode = DEFAULT_COMPOSITE_MODE;
if (editorMenuActive) {
@@ -71,8 +81,23 @@ export function getEditorLayer({
if (editorMode === EDITOR_MODES.DRAW_POLYGON) mode = DrawPolygonMode;
// @ts-ignore
else if (editorMode === EDITOR_MODES.DRAW_RECTANGLE) mode = DrawRectangleModeExtended;
+ // @ts-ignore
+ else if (sketchesEnabled && editorMode === EDITOR_MODES.DRAW_LINESTRING)
+ // @ts-ignore
+ mode = DrawLineStringSketchMode;
+ // @ts-ignore
+ else if (sketchesEnabled && editorMode === EDITOR_MODES.DRAW_POINT) mode = DrawPointMode;
}
+ const hasPointFeatures = featureCollection.features.some(
+ feature => feature.geometry?.type === 'Point' || feature.geometry?.type === 'MultiPoint'
+ );
+ // Point sketches need fill to be visible, including the tentative point while drawing.
+ const filled =
+ selectedFeatureIndexes.length > 0 ||
+ hasPointFeatures ||
+ (sketchesEnabled && editorMode === EDITOR_MODES.DRAW_POINT);
+
// @ts-ignore
return new EditableGeoJsonLayer({
id: EDITOR_LAYER_ID,
@@ -90,10 +115,7 @@ export function getEditorLayer({
},
pickingLineWidthExtraPixels: 5,
-
- // Only show fill when polygons are selected,
- // there is no way atm to enable fill for only one feature
- filled: selectedFeatureIndexes.length > 0,
+ filled,
onEdit: ({updatedData, editType}) => {
switch (editType) {
@@ -101,13 +123,22 @@ export function getEditorLayer({
const {features: _features} = updatedData;
if (_features.length) {
const lastFeature = _features[_features.length - 1];
- if (lastFeature.properties) lastFeature.properties.isClosed = true;
+ const geometryType = lastFeature.geometry?.type;
+ if (
+ lastFeature.properties &&
+ (geometryType === 'Polygon' || geometryType === 'MultiPolygon')
+ ) {
+ lastFeature.properties.isClosed = true;
+ }
+ if (!lastFeature.type) lastFeature.type = 'Feature';
lastFeature.id = generateHashId(6);
onSetFeatures(updatedData.features as unknown as Feature[]);
const isRectangle = lastFeature.properties?.shape === 'Rectangle';
if (isRectangle && onApplyPolygonFilterAll) {
onApplyPolygonFilterAll(lastFeature as unknown as Feature);
+ } else if (geometryType === 'Point' || geometryType === 'LineString') {
+ // Stay in draw mode so multiple sketches can be added in a row.
} else {
setSelectedFeature(lastFeature as unknown as Feature);
}
@@ -140,23 +171,23 @@ export function getEditorLayer({
else if (type === 'existing') return EDIT_HANDLE_STYLE.highlightMultiplier;
}
- // Note: highlight color affects even transparent filled polygons
- return selectedFeatureIndexes.length
- ? FEATURE_STYLE.highlightMultiplier
- : LINE_STYLE.highlightMultiplier;
+ // Polygons get a mostly transparent fill highlight. Using the opaque
+ // stroke color here paints a solid yellow background because GeoJsonLayer
+ // applies highlightColor to fill when the layer is filled (e.g. points).
+ const geomType = object?.geometry?.type;
+ if (geomType === 'Polygon' || geomType === 'MultiPolygon') {
+ return FEATURE_STYLE.highlightMultiplier;
+ }
+ if (geomType === 'LineString' || geomType === 'MultiLineString') {
+ return LINE_STYLE.highlightMultiplier;
+ }
+
+ return filled ? FEATURE_STYLE.highlightMultiplier : LINE_STYLE.highlightMultiplier;
},
extensions: [new PathStyleExtension({dash: true})],
dashGapPickable: true,
- getDashArray: feature => {
- if (feature?.properties?.guideType === 'tentative') {
- return LINE_STYLE.dashArray;
- }
-
- if (feature?.id === editor.selectedFeature?.id) return LINE_STYLE.solidArray;
-
- return LINE_STYLE.dashArray;
- },
+ getDashArray: getFeatureDashArray,
getLineColor: LINE_STYLE.getColor,
getFillColor: FEATURE_STYLE.getColor,
@@ -171,7 +202,10 @@ export function getEditorLayer({
getTentativeLineColor: LINE_STYLE.getTentativeLineColor,
// @ts-ignore
- getTentativeLineWidth: LINE_STYLE.getTentativeLineWidth,
+ getTentativeLineWidth:
+ sketchesEnabled && editorMode === EDITOR_MODES.DRAW_LINESTRING
+ ? LINE_STYLE.lineStringWidth
+ : LINE_STYLE.getTentativeLineWidth,
getTentativeFillColor: LINE_STYLE.getTentativeFillColor,
// Globe mode needs explicit depth testing so the editor overlay is occluded
diff --git a/src/layers/src/editor-layer/feature-styles.ts b/src/layers/src/editor-layer/feature-styles.ts
index c446f69e1..d87db4916 100644
--- a/src/layers/src/editor-layer/feature-styles.ts
+++ b/src/layers/src/editor-layer/feature-styles.ts
@@ -10,6 +10,8 @@ import {COLORS} from './constants';
const POINT_RADIUS = 5;
const STROKE_WIDTH_SELECTED = 2.5;
const STROKE_WIDTH_NOT_SELECTED = 2;
+const LINESTRING_WIDTH = 2;
+const LINESTRING_WIDTH_SELECTED = 3;
const STROKE_SOLID_ARRAY = [0, 0];
const STROKE_DASH_ARRAY = [4, 3];
@@ -17,6 +19,7 @@ const STROKE_DASH_ARRAY = [4, 3];
const ALPHA_0 = 0x00;
const ALPHA_005 = 0x0d;
const ALPHA_01 = 0x1a;
+const ALPHA_04 = 0x66;
const ALPHA_05 = 0x80;
const ALPHA_1 = 0xff;
@@ -26,6 +29,10 @@ const SECONDARY_COLOR_TRANSPARENT: RGBAColor = [...COLORS.SECONDARY, ALPHA_0];
const TENTATIVE_FEATURE_COLOR: RGBAColor = [...COLORS.SECONDARY, ALPHA_1];
const TENTATIVE_FEATURE_COLOR_TRANSPARENT: RGBAColor = [...COLORS.SECONDARY, ALPHA_005];
+export function isFilterFeature(feature?: Feature | null): boolean {
+ return Boolean(feature?.properties?.filterId);
+}
+
export const EDIT_HANDLE_STYLE = {
getRadius: POINT_RADIUS,
getFillColor: SECONDARY_COLOR_TRANSPARENT,
@@ -36,21 +43,44 @@ export const EDIT_HANDLE_STYLE = {
};
export const FEATURE_STYLE = {
- getColor: (feature: Feature, isSelected: boolean) =>
- isSelected ? PRIMARY_COLOR_TRANSPARENT : SECONDARY_COLOR_TRANSPARENT,
- highlightMultiplier: [...COLORS.HIGHLIGHT, ALPHA_01],
+ getColor: (feature: Feature, isSelected: boolean) => {
+ const isPoint = feature?.geometry?.type === 'Point' || feature?.geometry?.type === 'MultiPoint';
+ if (isPoint) {
+ return PRIMARY_COLOR;
+ }
+ return isSelected ? PRIMARY_COLOR_TRANSPARENT : SECONDARY_COLOR_TRANSPARENT;
+ },
+ highlightMultiplier: [...COLORS.HIGHLIGHT, ALPHA_04],
highlightMultiplierNone: SECONDARY_COLOR_TRANSPARENT
};
+function isLineFeature(feature?: Feature | null): boolean {
+ const type = feature?.geometry?.type;
+ return type === 'LineString' || type === 'MultiLineString';
+}
+
export const LINE_STYLE = {
getColor: (_feature: Feature, isSelected: boolean): RGBAColor =>
isSelected ? PRIMARY_COLOR : PRIMARY_COLOR,
- getWidth: (_feature: Feature, isSelected: boolean): number =>
- isSelected ? STROKE_WIDTH_SELECTED : STROKE_WIDTH_NOT_SELECTED,
+ getWidth: (feature: Feature, isSelected: boolean): number => {
+ if (isLineFeature(feature)) {
+ return isSelected ? LINESTRING_WIDTH_SELECTED : LINESTRING_WIDTH;
+ }
+ return isSelected ? STROKE_WIDTH_SELECTED : STROKE_WIDTH_NOT_SELECTED;
+ },
getTentativeLineColor: (): RGBAColor => TENTATIVE_FEATURE_COLOR,
- getTentativeLineWidth: (): number => STROKE_WIDTH_NOT_SELECTED,
+ getTentativeLineWidth: (feature?: Feature): number =>
+ isLineFeature(feature) ? LINESTRING_WIDTH : STROKE_WIDTH_NOT_SELECTED,
+ lineStringWidth: LINESTRING_WIDTH,
getTentativeFillColor: TENTATIVE_FEATURE_COLOR_TRANSPARENT,
dashArray: STROKE_DASH_ARRAY,
solidArray: STROKE_SOLID_ARRAY,
highlightMultiplier: [...COLORS.HIGHLIGHT, ALPHA_1]
};
+
+export function getFeatureDashArray(feature?: Feature | null): number[] {
+ if (feature?.properties?.guideType === 'tentative' || isFilterFeature(feature)) {
+ return LINE_STYLE.dashArray;
+ }
+ return LINE_STYLE.solidArray;
+}
diff --git a/src/layers/src/editor-layer/modify-mode-extended.ts b/src/layers/src/editor-layer/modify-mode-extended.ts
index 3e1ca6f0a..304a63233 100644
--- a/src/layers/src/editor-layer/modify-mode-extended.ts
+++ b/src/layers/src/editor-layer/modify-mode-extended.ts
@@ -14,6 +14,36 @@ import {EDITOR_LAYER_PICKING_RADIUS} from '@kepler.gl/constants';
const RIGHT_BUTTON = 2;
+function getIntermediateHandle(picks?: {isGuide?: boolean; object?: any}[]) {
+ return picks?.find(
+ pick =>
+ pick?.isGuide &&
+ pick?.object?.properties?.guideType === 'editHandle' &&
+ pick?.object?.properties?.editHandleType === 'intermediate'
+ )?.object;
+}
+
+function isLineStringType(type?: string) {
+ return type === 'LineString' || type === 'MultiLineString';
+}
+
+/**
+ * Dragging the body of a selected line currently hits the insert-vertex
+ * handle. Skip modify in that case so TranslateMode can move the whole line.
+ * Clicking the line still inserts a point via handleClick.
+ */
+function shouldTranslateLine(
+ picks: {isGuide?: boolean; object?: any}[] | undefined,
+ props: {data?: {features?: {geometry?: {type?: string}}[]}}
+) {
+ const handle = getIntermediateHandle(picks);
+ if (!handle) {
+ return false;
+ }
+ const feature = props?.data?.features?.[handle.properties.featureIndex];
+ return isLineStringType(feature?.geometry?.type);
+}
+
/**
* Show helper only when the point is close enough to the line.
*/
@@ -43,4 +73,33 @@ export class ModifyModeExtended extends ModifyMode {
}
super.handleClick(event, props);
}
+
+ handlePointerMove(event, props) {
+ if (shouldTranslateLine(event?.picks, props)) {
+ props.onUpdateCursor('move');
+ return;
+ }
+ super.handlePointerMove(event, props);
+ }
+
+ handleStartDragging(event, props) {
+ if (shouldTranslateLine(event?.picks, props)) {
+ return;
+ }
+ super.handleStartDragging(event, props);
+ }
+
+ handleDragging(event, props) {
+ if (shouldTranslateLine(event?.pointerDownPicks, props)) {
+ return;
+ }
+ super.handleDragging(event, props);
+ }
+
+ handleStopDragging(event, props) {
+ if (shouldTranslateLine(event?.pointerDownPicks, props)) {
+ return;
+ }
+ super.handleStopDragging(event, props);
+ }
}
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index 75fc077cf..8765a4b64 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -320,6 +320,8 @@ export default {
showLegend: 'mostra llegenda',
disable3DMap: 'Desactiva mapa 3D',
DrawOnMap: 'Dibuixa al mapa',
+ copyAllSketches: 'Copia tots els esbossos al porta-retalls com a GeoJSON',
+ convertToLayer: 'Converteix els esbossos en una capa GeoJSON i esborra el dibuix',
selectLocale: 'Selecciona configuració regional',
switchToLightTheme: 'Canvia al tema clar',
switchToDarkTheme: 'Canvia al tema fosc',
@@ -367,8 +369,12 @@ export default {
shareMapURL: 'Comparteix URL del mapa',
saveMap: 'Desa mapa',
select: 'selecciona',
+ point: 'punt',
+ line: 'línia',
polygon: 'polígon',
rectangle: 'rectangle',
+ copyAll: 'Copia-ho tot',
+ convertToLayer: 'Converteix\na capa',
hide: 'amaga',
show: 'mostra',
...LOCALES
@@ -377,6 +383,11 @@ export default {
filterLayer: 'Filtra capes',
filterLayerDisabled: 'Les geometries no poligonals no es poden utilitzar per filtrar',
copyGeometry: 'Copia geometria',
+ editProperties: 'Edita propietats',
+ propertyName: 'Propietat',
+ propertyValue: 'Valor',
+ removeProperty: 'Suprimeix la propietat',
+ polygonFilter: 'Filtre de polígon',
noLayersToFilter: 'No hi ha capes per filtrar'
},
exportVideoModal: {
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index 4ebfcfc72..7da4237a6 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -307,6 +307,8 @@ export default {
showLegend: '显示图例',
disable3DMap: '禁用 3D 地图',
DrawOnMap: '在地图上绘制',
+ copyAllSketches: '将所有草图以 GeoJSON 复制到剪贴板',
+ convertToLayer: '将草图转为 GeoJSON 图层并清除绘制',
selectLocale: '选择语言',
switchToLightTheme: '切换到浅色主题',
switchToDarkTheme: '切换到深色主题',
@@ -354,8 +356,12 @@ export default {
shareMapURL: '分享地图网址',
saveMap: '保存地图',
select: '选择',
+ point: '点',
+ line: '线',
polygon: 'polygon',
rectangle: 'rectangle',
+ copyAll: '复制全部',
+ convertToLayer: '转换为\n图层',
hide: '隐藏',
show: '显示',
...LOCALES
@@ -364,6 +370,11 @@ export default {
filterLayer: '过滤图层',
filterLayerDisabled: '非多边形几何图形不能用于过滤',
copyGeometry: '复制几何图形',
+ editProperties: '编辑属性',
+ propertyName: '属性',
+ propertyValue: '值',
+ removeProperty: '删除属性',
+ polygonFilter: '多边形过滤器',
noLayersToFilter: '没有可过滤的图层'
},
exportVideoModal: {
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index febdeb81c..ae59de441 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -369,6 +369,8 @@ export default {
viewMode: 'View Mode',
top: 'Top',
DrawOnMap: 'Draw on map',
+ copyAllSketches: 'Copy all sketches to the clipboard as GeoJSON',
+ convertToLayer: 'Turn sketches into a new GeoJSON layer and clear the drawing',
selectLocale: 'Select locale',
switchToLightTheme: 'Switch to light theme',
switchToDarkTheme: 'Switch to dark theme',
@@ -416,8 +418,12 @@ export default {
shareMapURL: 'Share Map URL',
saveMap: 'Save Map',
select: 'Select',
+ point: 'Point',
+ line: 'Line',
polygon: 'Polygon',
rectangle: 'Rectangle',
+ copyAll: 'Copy all',
+ convertToLayer: 'Convert to\nLayer',
hide: 'Hide',
show: 'Show',
...LOCALES
@@ -426,6 +432,11 @@ export default {
filterLayer: 'Filter Layers',
filterLayerDisabled: 'Non-polygon geometries cannot be used for filtering',
copyGeometry: 'Copy Geometry',
+ editProperties: 'Edit Properties',
+ propertyName: 'Property',
+ propertyValue: 'Value',
+ removeProperty: 'Remove property',
+ polygonFilter: 'Polygon filter',
noLayersToFilter: 'No layers to filter'
},
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index d6a0b75fe..ca59da752 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -321,6 +321,8 @@ export default {
showLegend: 'Mostrar leyenda',
disable3DMap: 'Desactivar mapa 3D',
DrawOnMap: 'Dibujar en el mapa',
+ copyAllSketches: 'Copiar todos los bocetos al portapapeles como GeoJSON',
+ convertToLayer: 'Convertir los bocetos en una capa GeoJSON y borrar el dibujo',
selectLocale: 'Seleccionar configuración regional',
switchToLightTheme: 'Cambiar a tema claro',
switchToDarkTheme: 'Cambiar a tema oscuro',
@@ -368,8 +370,12 @@ export default {
shareMapURL: 'Compartir el enlace del mapa',
saveMap: 'Guardar mapa',
select: 'selecciona',
+ point: 'punto',
+ line: 'línea',
polygon: 'polígono',
rectangle: 'rectángulo',
+ copyAll: 'Copiar todo',
+ convertToLayer: 'Convertir\na capa',
hide: 'esconder',
show: 'mostrar',
...LOCALES
@@ -378,6 +384,11 @@ export default {
filterLayer: 'Filtrar capas',
filterLayerDisabled: 'Las geometrías no poligonales no se pueden usar para filtrar',
copyGeometry: 'Copiar geometría',
+ editProperties: 'Editar propiedades',
+ propertyName: 'Propiedad',
+ propertyValue: 'Valor',
+ removeProperty: 'Quitar propiedad',
+ polygonFilter: 'Filtro de polígono',
noLayersToFilter: 'No hay capas para filtrar'
},
exportVideoModal: {
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index 6bebf44ae..571aba2d7 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -319,6 +319,8 @@ export default {
showLegend: 'Näytä selite',
disable3DMap: 'Poistu 3D-näkymästä',
DrawOnMap: 'Piirrä kartalle',
+ copyAllSketches: 'Kopioi kaikki luonnokset leikepöydälle GeoJSON-muodossa',
+ convertToLayer: 'Muunna luonnokset GeoJSON-tasoksi ja tyhjennä piirros',
selectLocale: 'Valitse kielisyys',
switchToLightTheme: 'Vaihda vaaleaan teemaan',
switchToDarkTheme: 'Vaihda tummaan teemaan',
@@ -366,8 +368,12 @@ export default {
shareMapURL: 'Jaa kartan URL',
saveMap: 'Tallenna kartta',
select: 'valitse',
+ point: 'piste',
+ line: 'viiva',
polygon: 'polygoni',
rectangle: 'nelikulmio',
+ copyAll: 'Kopioi kaikki',
+ convertToLayer: 'Muunna\ntasoksi',
hide: 'piilota',
show: 'näytä',
...LOCALES
@@ -376,6 +382,11 @@ export default {
filterLayer: 'Suodata tasoja',
filterLayerDisabled: 'Ei-monikulmiogeometrioita ei voi käyttää suodatukseen',
copyGeometry: 'Kopioi geometria',
+ editProperties: 'Muokkaa ominaisuuksia',
+ propertyName: 'Ominaisuus',
+ propertyValue: 'Arvo',
+ removeProperty: 'Poista ominaisuus',
+ polygonFilter: 'Polygonisuodatin',
noLayersToFilter: 'Ei tasoja suodatettavaksi'
},
exportVideoModal: {
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index 4094a2e2b..7ec5b1645 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -316,6 +316,8 @@ export default {
showLegend: '凡例を表示',
disable3DMap: '3D地図を無効化',
DrawOnMap: '地図上に図形を描画',
+ copyAllSketches: 'すべてのスケッチを GeoJSON としてクリップボードにコピー',
+ convertToLayer: 'スケッチを GeoJSON レイヤに変換し、描画をクリア',
selectLocale: '言語設定',
switchToLightTheme: 'ライトテーマに切り替え',
switchToDarkTheme: 'ダークテーマに切り替え',
@@ -364,8 +366,12 @@ export default {
shareMapURL: '地図のURLを共有',
saveMap: '地図を保存',
select: '選択',
+ point: 'ポイント',
+ line: 'ライン',
polygon: 'ポリゴン',
rectangle: '長方形',
+ copyAll: 'すべてコピー',
+ convertToLayer: 'レイヤに\n変換',
hide: '非表示',
show: '表示',
...LOCALES
@@ -374,6 +380,11 @@ export default {
filterLayer: 'レイヤをフィルタ',
filterLayerDisabled: 'ポリゴン以外のジオメトリはフィルタリングに使用できません',
copyGeometry: 'ジオメトリをコピー',
+ editProperties: 'プロパティを編集',
+ propertyName: 'プロパティ',
+ propertyValue: '値',
+ removeProperty: 'プロパティを削除',
+ polygonFilter: 'ポリゴンフィルタ',
noLayersToFilter: 'フィルタするレイヤがありません'
},
exportVideoModal: {
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index babaee6dd..8211b7df9 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -321,6 +321,8 @@ export default {
showLegend: 'mostrar legenda',
disable3DMap: 'Desabilitar Mapa 3D',
DrawOnMap: 'Desenhar no mapa',
+ copyAllSketches: 'Copiar todos os esboços para a área de transferência como GeoJSON',
+ convertToLayer: 'Transformar os esboços em uma camada GeoJSON e limpar o desenho',
selectLocale: 'Selecionar língua',
switchToLightTheme: 'Mudar para tema claro',
switchToDarkTheme: 'Mudar para tema escuro',
@@ -368,8 +370,12 @@ export default {
shareMapURL: 'Compartilhar URL do Mapa',
saveMap: 'Salvar Mapa',
select: 'selecionar',
+ point: 'ponto',
+ line: 'linha',
polygon: 'polígono',
rectangle: 'retângulo',
+ copyAll: 'Copiar tudo',
+ convertToLayer: 'Converter\nem camada',
hide: 'esconder',
show: 'mostrar',
...LOCALES
@@ -378,6 +384,11 @@ export default {
filterLayer: 'Filtrar camadas',
filterLayerDisabled: 'Geometrias não poligonais não podem ser usadas para filtragem',
copyGeometry: 'Copiar geometria',
+ editProperties: 'Editar propriedades',
+ propertyName: 'Propriedade',
+ propertyValue: 'Valor',
+ removeProperty: 'Remover propriedade',
+ polygonFilter: 'Filtro de polígono',
noLayersToFilter: 'Sem camadas para filtrar'
},
exportVideoModal: {
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index 034a8af6b..b2a887dd2 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -318,6 +318,8 @@ export default {
showLegend: 'Показать легенду',
disable3DMap: 'Отключить 3D Карту',
DrawOnMap: 'Рисовать на карте',
+ copyAllSketches: 'Скопировать все наброски в буфер обмена как GeoJSON',
+ convertToLayer: 'Преобразовать наброски в слой GeoJSON и очистить рисунок',
selectLocale: 'Выберите регион',
switchToLightTheme: 'Переключить на светлую тему',
switchToDarkTheme: 'Переключить на тёмную тему',
@@ -367,8 +369,12 @@ export default {
exportVideo: 'Экспорт видео',
saveMap: 'Сохарнить Карту',
select: 'Выбрать',
+ point: 'Точка',
+ line: 'Линия',
polygon: 'Многоугольник',
rectangle: 'Квадрат',
+ copyAll: 'Копировать всё',
+ convertToLayer: 'Преобразовать\nв слой',
hide: 'Скрыть',
show: 'Показать',
...LOCALES
@@ -377,6 +383,11 @@ export default {
filterLayer: 'Слои фильтров',
filterLayerDisabled: 'Неполигональные геометрии нельзя использовать для фильтрации',
copyGeometry: 'Копировать геометрию',
+ editProperties: 'Изменить свойства',
+ propertyName: 'Свойство',
+ propertyValue: 'Значение',
+ removeProperty: 'Удалить свойство',
+ polygonFilter: 'Полигональный фильтр',
noLayersToFilter: 'Нет слоев для фильтрации'
},
exportVideoModal: {
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index d4875b523..6d62d7a38 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -59,6 +59,9 @@ import {
computeSplitMapLayers,
adjustValueToFilterDomain,
errorNotification,
+ editorFeaturesToFeatureCollection,
+ mergeUserFeatureProperties,
+ toSketchFeature,
featureToFilterValue,
filterDatasetCPU,
generatePolygonFilter,
@@ -130,9 +133,11 @@ import {
} from './vis-state-merger';
import KeplerGLSchema, {Merger, PostMergerPayload, VisState} from '@kepler.gl/schemas';
+import {processGeojson} from '@kepler.gl/processors';
import {
Filter,
+ Feature,
InteractionConfig,
AnimationConfig,
FilterAnimationConfig,
@@ -3674,14 +3679,24 @@ export function updateAnimationDomain<S extends VisState>(state: S): S {
export const setEditorModeUpdater = (
state: VisState,
{mode}: VisStateActions.SetEditorModeUpdaterAction
-): VisState => ({
- ...state,
- editor: {
- ...state.editor,
- mode,
- selectedFeature: null
+): VisState => {
+ const sketchesEnabled = getApplicationConfig().enableDrawOnMapSketches;
+ if (
+ !sketchesEnabled &&
+ (mode === EDITOR_MODES.DRAW_POINT || mode === EDITOR_MODES.DRAW_LINESTRING)
+ ) {
+ return state;
}
-});
+
+ return {
+ ...state,
+ editor: {
+ ...state.editor,
+ mode,
+ selectedFeature: null
+ }
+ };
+};
// const featureToFilterValue = (feature) => ({...feature, id: feature.id});
/**
@@ -3738,6 +3753,78 @@ export function setFeaturesUpdater(
return newState;
}
+function findEditorFeature(state: VisState, feature?: Feature | null): Feature | null {
+ if (!feature?.id) {
+ return feature || null;
+ }
+ if (state.editor.selectedFeature?.id === feature.id) {
+ return state.editor.selectedFeature;
+ }
+ const fromEditor = state.editor.features.find(item => item.id === feature.id);
+ if (fromEditor) {
+ return fromEditor;
+ }
+ const filterId = getFilterIdInFeature(feature);
+ if (filterId) {
+ const filter = state.filters.find(item => item.id === filterId);
+ if (filter?.value) {
+ return filter.value;
+ }
+ }
+ return feature;
+}
+
+/**
+ * Set user-facing GeoJSON properties on a sketch or polygon-filter feature.
+ * @memberof visStateUpdaters
+ */
+export function setEditorFeaturePropertiesUpdater(
+ state: VisState,
+ {feature, properties}: VisStateActions.SetEditorFeaturePropertiesUpdaterAction
+): VisState {
+ if (!getApplicationConfig().enableDrawOnMapSketches) {
+ return state;
+ }
+
+ const source = findEditorFeature(state, feature);
+ if (!source?.id) {
+ return state;
+ }
+
+ const nextFeature = mergeUserFeatureProperties(source, properties);
+ const filterId = getFilterIdInFeature(nextFeature);
+ const nextEditor = {
+ ...state.editor,
+ features: filterId
+ ? state.editor.features
+ : state.editor.features.map(item => (item.id === nextFeature.id ? nextFeature : item)),
+ selectedFeature:
+ state.editor.selectedFeature?.id === nextFeature.id
+ ? nextFeature
+ : state.editor.selectedFeature
+ };
+
+ const nextState = {
+ ...state,
+ editor: nextEditor
+ };
+
+ if (!filterId) {
+ return nextState;
+ }
+
+ const filterIdx = state.filters.findIndex(item => item.id === filterId);
+ if (filterIdx < 0) {
+ return nextState;
+ }
+
+ return setFilterUpdater(nextState, {
+ idx: filterIdx,
+ prop: 'value',
+ value: featureToFilterValue(nextFeature, filterId)
+ });
+}
+
/**
* Set the current selected feature
* @memberof uiStateUpdaters
@@ -3854,6 +3941,20 @@ export function setPolygonFilterLayerUpdater(
? // if layer is included, remove it
layerId.filter(l => l !== layer.id)
: [...layerId, layer.id];
+
+ // Last layer removed: turn the filter polygon back into a sketch
+ if (!newLayerId.length) {
+ const sketchFeature = toSketchFeature(feature);
+ const stateWithoutFilter = removeFilterUpdater(newState, {idx: filterIdx});
+ return {
+ ...stateWithoutFilter,
+ editor: {
+ ...stateWithoutFilter.editor,
+ features: [...stateWithoutFilter.editor.features, sketchFeature],
+ selectedFeature: sketchFeature
+ }
+ };
+ }
} else {
// if we haven't create the polygon filter, create it
const newFilter = generatePolygonFilter([], feature);
@@ -4046,6 +4147,69 @@ export function toggleEditorVisibilityUpdater(
};
}
+/**
+ * Convert editor sketch features into a GeoJSON dataset/layer and clear the sketches.
+ */
+export function convertEditorFeaturesToLayerUpdater(
+ state: VisState,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _action: VisStateActions.ConvertEditorFeaturesToLayerUpdaterAction
+): VisState {
+ if (!getApplicationConfig().enableDrawOnMapSketches) {
+ return state;
+ }
+
+ const features = state.editor.features;
+ if (!features.length) {
+ return state;
+ }
+
+ let data;
+ try {
+ data = processGeojson(editorFeaturesToFeatureCollection(features));
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return withTask(
+ state,
+ ACTION_TASK_ADD_NOTIFICATION().map(() =>
+ addNotification(
+ errorNotification({
+ message: `Failed to convert drawn geometry to a layer: ${message}`,
+ id: 'convert-editor-features'
+ })
+ )
+ )
+ );
+ }
+
+ const clearedState: VisState = {
+ ...state,
+ editor: {
+ ...state.editor,
+ features: [],
+ selectedFeature: null,
+ mode: EDITOR_MODES.EDIT
+ }
+ };
+
+ const labelId = Math.floor(Math.random() * 90) + 10;
+
+ return updateVisDataUpdater(clearedState, {
+ datasets: {
+ info: {
+ id: `drawn-geometry-${generateHashId(6)}`,
+ label: `Drawn Geometry ${labelId}`
+ },
+ data
+ },
+ options: {
+ keepExistingConfig: true,
+ centerMap: false,
+ autoCreateLayers: true
+ }
+ });
+}
+
export function setFilterAnimationTimeConfigUpdater(
state: VisState,
{idx, config}: VisStateActions.SetFilterAnimationTimeConfigAction
diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.ts
index 1fb2b0056..5e99082fd 100644
--- a/src/reducers/src/vis-state.ts
+++ b/src/reducers/src/vis-state.ts
@@ -129,6 +129,8 @@ const actionHandler = {
[ActionTypes.SET_FEATURES]: visStateUpdaters.setFeaturesUpdater,
+ [ActionTypes.SET_EDITOR_FEATURE_PROPERTIES]: visStateUpdaters.setEditorFeaturePropertiesUpdater,
+
[ActionTypes.DELETE_FEATURE]: visStateUpdaters.deleteFeatureUpdater,
[ActionTypes.SET_POLYGON_FILTER_LAYER]: visStateUpdaters.setPolygonFilterLayerUpdater,
@@ -141,6 +143,9 @@ const actionHandler = {
[ActionTypes.TOGGLE_EDITOR_VISIBILITY]: visStateUpdaters.toggleEditorVisibilityUpdater,
+ [ActionTypes.CONVERT_EDITOR_FEATURES_TO_LAYER]:
+ visStateUpdaters.convertEditorFeaturesToLayerUpdater,
+
[ActionTypes.TOGGLE_FILTER_FEATURE]: visStateUpdaters.toggleFilterFeatureUpdater,
[ActionTypes.APPLY_CPU_FILTER]: visStateUpdaters.applyCPUFilterUpdater,
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 2e54357eb..5bd5d0eba 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -152,6 +152,13 @@ export type KeplerApplicationConfig = {
/** Whether to enable the annotations feature. Enabled by default. */
enableAnnotations?: boolean;
+ /**
+ * Whether to enable extended Draw on Map sketch tools: Point, Line, Copy all,
+ * Convert to Layer, and Edit Properties.
+ * Polygon and rectangle drawing remain available when this is disabled. Enabled by default.
+ */
+ enableDrawOnMapSketches?: boolean;
+
/** Whether to show the map navigation control (zoom buttons and compass). Enabled by default. */
enableMapNavigationControl?: boolean;
@@ -281,6 +288,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableAnnotations: true,
+ enableDrawOnMapSketches: true,
+
enableMapNavigationControl: true,
enableMapScale: true,
diff --git a/src/utils/src/editor-feature-utils.ts b/src/utils/src/editor-feature-utils.ts
new file mode 100644
index 000000000..5b5723aab
--- /dev/null
+++ b/src/utils/src/editor-feature-utils.ts
@@ -0,0 +1,170 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {Feature} from '@kepler.gl/types';
+
+const EDITOR_INTERNAL_PROPERTIES = new Set([
+ 'isClosed',
+ 'filterId',
+ 'bbox',
+ 'isVisible',
+ 'guideType',
+ 'editHandleType',
+ 'shape',
+ 'renderType'
+]);
+
+export function isReservedEditorProperty(key: string): boolean {
+ return EDITOR_INTERNAL_PROPERTIES.has(key);
+}
+
+/**
+ * GeoJSON properties that should survive copy / convert, excluding editor internals.
+ */
+export function getUserFeatureProperties(feature?: Feature | null): Record<string, unknown> {
+ if (!feature) {
+ return {};
+ }
+ return (sanitizeEditorFeature(feature).properties || {}) as Record<string, unknown>;
+}
+
+/**
+ * Replace user-facing properties while preserving editor-only keys.
+ */
+export function mergeUserFeatureProperties(
+ feature: Feature,
+ userProperties: Record<string, unknown> = {}
+): Feature {
+ const internalProperties = Object.entries(feature.properties || {}).reduce<
+ Record<string, unknown>
+ >((acc, [key, value]) => {
+ if (EDITOR_INTERNAL_PROPERTIES.has(key)) {
+ acc[key] = value;
+ }
+ return acc;
+ }, {});
+
+ const nextUserProperties = Object.entries(userProperties).reduce<Record<string, unknown>>(
+ (acc, [key, value]) => {
+ const name = typeof key === 'string' ? key.trim() : '';
+ if (!name || EDITOR_INTERNAL_PROPERTIES.has(name)) {
+ return acc;
+ }
+ acc[name] = value;
+ return acc;
+ },
+ {}
+ );
+
+ return {
+ ...feature,
+ properties: {
+ ...internalProperties,
+ ...nextUserProperties
+ }
+ };
+}
+
+export type EditorFeatureCollection = {
+ type: 'FeatureCollection';
+ features: Feature[];
+};
+
+/**
+ * Strip editor-only properties so copied / converted GeoJSON is usable as data.
+ */
+export function sanitizeEditorFeature(feature: Feature): Feature {
+ const properties = Object.entries(feature.properties || {}).reduce<Record<string, unknown>>(
+ (acc, [key, value]) => {
+ if (!EDITOR_INTERNAL_PROPERTIES.has(key)) {
+ acc[key] = value;
+ }
+ return acc;
+ },
+ {}
+ );
+
+ return {
+ type: 'Feature',
+ id: feature.id,
+ properties,
+ geometry: feature.geometry
+ };
+}
+
+/**
+ * Convert editor sketch features into a GeoJSON FeatureCollection.
+ */
+export function editorFeaturesToFeatureCollection(
+ features: Feature[] = []
+): EditorFeatureCollection {
+ return {
+ type: 'FeatureCollection',
+ features: features.filter(feature => Boolean(feature?.geometry)).map(sanitizeEditorFeature)
+ };
+}
+
+/**
+ * Convert a polygon-filter feature back into an editor sketch.
+ */
+export function toSketchFeature(feature: Feature): Feature {
+ const properties = {...(feature.properties || {})};
+ delete properties.filterId;
+ return {
+ ...feature,
+ properties
+ };
+}
+
+/**
+ * Map position for a filter badge: the vertex nearest the north-east bbox corner.
+ */
+export function getFilterFeatureAnchor(feature: Feature): [number, number] | null {
+ const geometry = feature?.geometry;
+ if (!geometry) {
+ return null;
+ }
+
+ let ring: number[][] | undefined;
+ if (geometry.type === 'Polygon') {
+ ring = geometry.coordinates?.[0];
+ } else if (geometry.type === 'MultiPolygon') {
+ ring = geometry.coordinates?.[0]?.[0];
+ }
+
+ if (!Array.isArray(ring) || !ring.length) {
+ const bbox = feature.properties?.bbox;
+ if (
+ Array.isArray(bbox) &&
+ bbox.length >= 4 &&
+ Number.isFinite(bbox[2]) &&
+ Number.isFinite(bbox[3])
+ ) {
+ return [bbox[2], bbox[3]];
+ }
+ return null;
+ }
+
+ let maxLng = -Infinity;
+ let maxLat = -Infinity;
+ for (const coord of ring) {
+ if (coord[0] > maxLng) maxLng = coord[0];
+ if (coord[1] > maxLat) maxLat = coord[1];
+ }
+ if (!Number.isFinite(maxLng) || !Number.isFinite(maxLat)) {
+ return null;
+ }
+
+ let nearest = ring[0];
+ let best = Infinity;
+ for (const coord of ring) {
+ const dx = coord[0] - maxLng;
+ const dy = coord[1] - maxLat;
+ const dist = dx * dx + dy * dy;
+ if (dist < best) {
+ best = dist;
+ nearest = coord;
+ }
+ }
+ return [nearest[0], nearest[1]];
+}
diff --git a/src/utils/src/index.ts b/src/utils/src/index.ts
index 46a180b75..df90ae725 100644
--- a/src/utils/src/index.ts
+++ b/src/utils/src/index.ts
@@ -146,6 +146,8 @@ export {
} from './data-container-utils';
export * from './filter-utils';
export type {FilterChanged, FilterResult, dataValueAccessor} from './filter-utils';
+export * from './editor-feature-utils';
+export type {EditorFeatureCollection} from './editor-feature-utils';
export {
colorMapToColorBreaks,
diff --git a/test/browser/components/editor/feature-action-panel-test.js b/test/browser/components/editor/feature-action-panel-test.js
index c64b551de..046f22054 100644
--- a/test/browser/components/editor/feature-action-panel-test.js
+++ b/test/browser/components/editor/feature-action-panel-test.js
@@ -65,3 +65,60 @@ test('FeatureActionPanel -> display layers', t => {
t.end();
});
+
+test('FeatureActionPanel -> edit properties', t => {
+ const selectedFeature = {
+ type: 'Feature',
+ id: 'point-1',
+ properties: {},
+ geometry: {type: 'Point', coordinates: [0, 0]}
+ };
+ const onSetFeatureProperties = sinon.spy();
+ const wrapper = mountWithTheme(
+ <IntlWrapper>
+ <FeatureActionPanel
+ className="action-item-test"
+ layers={[]}
+ datasets={{}}
+ selectedFeature={selectedFeature}
+ onToggleLayer={() => {}}
+ onDeleteFeature={() => {}}
+ onSetFeatureProperties={onSetFeatureProperties}
+ position={{x: 0, y: 0}}
+ />
+ </IntlWrapper>
+ );
+
+ t.equal(
+ wrapper.find('.feature-properties-editor').length,
+ 0,
+ 'Properties editor should be hidden until requested'
+ );
+
+ wrapper.find('.edit-properties-panel-item').simulate('click');
+ wrapper.update();
+
+ t.ok(
+ wrapper.find('.feature-properties-editor').length,
+ 'Clicking Edit Properties should open the properties table'
+ );
+
+ wrapper
+ .find('.feature-property-name')
+ .at(0)
+ .simulate('change', {target: {value: 'name'}});
+ wrapper.update();
+ wrapper
+ .find('.feature-property-value')
+ .at(0)
+ .simulate('change', {target: {value: 'Park'}});
+
+ t.ok(onSetFeatureProperties.called, 'Should save properties when a named row has a value');
+ t.deepEqual(
+ onSetFeatureProperties.lastCall.args[1],
+ {name: 'Park'},
+ 'Should pass user properties without editor internals'
+ );
+
+ t.end();
+});
diff --git a/test/browser/components/map/map-control-test.js b/test/browser/components/map/map-control-test.js
index 9eaeb80c5..8d1b40512 100644
--- a/test/browser/components/map/map-control-test.js
+++ b/test/browser/components/map/map-control-test.js
@@ -297,8 +297,8 @@ test('MapControlFactory - show panels', t => {
t.equal(wrapper.find(MapControlToolbar).length, 1, 'should render 1 MapControlToolbar');
t.equal(
wrapper.find(MapControlToolbar).at(0).find(ToolbarItem).length,
- 3,
- 'should render 3 ToolbarItem'
+ 7,
+ 'should render 7 ToolbarItem'
);
// show locale
diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.js
index f5491b442..8c059883e 100644
--- a/test/node/reducers/vis-state-test.js
+++ b/test/node/reducers/vis-state-test.js
@@ -34,7 +34,8 @@ import {
getAnimatableVisibleLayers,
getDefaultFilter,
histogramFromDomain,
- TileTimeInterval
+ TileTimeInterval,
+ initApplicationConfig
} from '@kepler.gl/utils';
import {
ALL_FIELD_TYPES,
@@ -5103,6 +5104,33 @@ test('#visStateReducer -> POLYGON: Create polygon filter', t => {
t.end();
});
+test('#visStateReducer -> POLYGON: unselecting all layers returns sketch', t => {
+ const initialState = CloneDeep(StateWFiles.visState);
+ const layer = initialState.layers[0];
+ let state = reducer(initialState, VisStateActions.setFeatures([mockPolygonFeature]));
+ state = reducer(state, VisStateActions.setSelectedFeature(mockPolygonFeature));
+ state = reducer(state, VisStateActions.setPolygonFilterLayer(layer, mockPolygonFeature));
+
+ t.equal(state.filters.length, 1, 'Should create a polygon filter');
+ t.equal(state.editor.features.length, 0, 'Sketch should move into the filter');
+
+ const filterFeature = state.filters[0].value;
+ state = reducer(state, VisStateActions.setPolygonFilterLayer(layer, filterFeature));
+
+ t.equal(state.filters.length, 0, 'Should remove the filter when no layers remain');
+ t.equal(state.editor.features.length, 1, 'Should return the polygon to sketches');
+ t.notOk(
+ state.editor.features[0].properties.filterId,
+ 'Returned sketch should not be a filter'
+ );
+ t.equal(
+ state.editor.selectedFeature.id,
+ mockPolygonFeature.id,
+ 'Should keep the polygon selected'
+ );
+ t.end();
+});
+
test('#visStateReducer -> POLYGON: Toggle filter feature', t => {
const state = {
...INITIAL_VIS_STATE
@@ -5914,6 +5942,178 @@ test('#uiStateReducer -> SET_FEATURES/SET_SELECTED_FEATURE/DELETE_FEATURE', t =>
t.end();
});
+test('#visStateReducer -> SET_FEATURES line keeps draw mode', t => {
+ let state = reducer(
+ INITIAL_VIS_STATE,
+ VisStateActions.setEditorMode(EDITOR_MODES.DRAW_LINESTRING)
+ );
+ state = reducer(
+ state,
+ VisStateActions.setFeatures([
+ {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {},
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ }
+ }
+ ])
+ );
+
+ t.equal(
+ state.editor.mode,
+ EDITOR_MODES.DRAW_LINESTRING,
+ 'Line sketches should stay in line drawing mode'
+ );
+ t.equal(state.editor.features.length, 1, 'Should store the line sketch');
+ t.end();
+});
+
+test('#visStateReducer -> CONVERT_EDITOR_FEATURES_TO_LAYER', t => {
+ const emptyState = reducer(INITIAL_VIS_STATE, VisStateActions.convertEditorFeaturesToLayer());
+ t.equal(emptyState, INITIAL_VIS_STATE, 'Should no-op when there are no sketch features');
+
+ const lineFeature = {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {isClosed: false},
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ }
+ };
+
+ let state = {
+ ...INITIAL_VIS_STATE,
+ editor: {
+ ...INITIAL_VIS_STATE.editor,
+ features: [lineFeature],
+ selectedFeature: lineFeature,
+ mode: EDITOR_MODES.DRAW_LINESTRING
+ }
+ };
+
+ state = reducer(state, VisStateActions.convertEditorFeaturesToLayer());
+ t.deepEqual(state.editor.features, [], 'Should clear sketch features after convert');
+ t.equal(state.editor.selectedFeature, null, 'Should clear selected feature after convert');
+ t.equal(state.editor.mode, EDITOR_MODES.EDIT, 'Should switch to select mode after convert');
+
+ const tasks = drainTasksForTesting();
+ t.ok(
+ /Drawn Geometry \d{2}/.test(JSON.stringify(tasks)),
+ 'Converted layer should be named Drawn Geometry plus a two-digit number'
+ );
+ t.end();
+});
+
+test('#visStateReducer -> CONVERT_EDITOR_FEATURES_TO_LAYER disabled by config', t => {
+ initApplicationConfig({enableDrawOnMapSketches: false});
+
+ try {
+ const lineFeature = {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {},
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ }
+ };
+ const startState = {
+ ...INITIAL_VIS_STATE,
+ editor: {
+ ...INITIAL_VIS_STATE.editor,
+ features: [lineFeature],
+ selectedFeature: lineFeature
+ }
+ };
+
+ const nextState = reducer(startState, VisStateActions.convertEditorFeaturesToLayer());
+ t.equal(nextState, startState, 'Should no-op convert when draw-on-map sketches are disabled');
+
+ const ignoredMode = reducer(startState, VisStateActions.setEditorMode(EDITOR_MODES.DRAW_POINT));
+ t.equal(
+ ignoredMode.editor.mode,
+ startState.editor.mode,
+ 'Should ignore point draw mode when sketches are disabled'
+ );
+
+ const ignoredProperties = reducer(
+ startState,
+ VisStateActions.setEditorFeatureProperties(lineFeature, {name: 'route'})
+ );
+ t.equal(
+ ignoredProperties,
+ startState,
+ 'Should ignore edit properties when sketches are disabled'
+ );
+ } finally {
+ initApplicationConfig({enableDrawOnMapSketches: true});
+ }
+
+ t.end();
+});
+
+test('#visStateReducer -> SET_EDITOR_FEATURE_PROPERTIES', t => {
+ const pointFeature = {
+ type: 'Feature',
+ id: 'point-1',
+ properties: {isClosed: false},
+ geometry: {type: 'Point', coordinates: [0, 0]}
+ };
+
+ let state = {
+ ...INITIAL_VIS_STATE,
+ editor: {
+ ...INITIAL_VIS_STATE.editor,
+ features: [pointFeature],
+ selectedFeature: pointFeature
+ }
+ };
+
+ state = reducer(
+ state,
+ VisStateActions.setEditorFeatureProperties(pointFeature, {
+ name: 'Stop',
+ filterId: 'nope',
+ isClosed: true
+ })
+ );
+
+ t.equal(state.editor.features[0].properties.name, 'Stop', 'Should store user properties');
+ t.equal(
+ state.editor.selectedFeature.properties.name,
+ 'Stop',
+ 'Should keep the selected feature in sync'
+ );
+ t.equal(
+ state.editor.features[0].properties.isClosed,
+ false,
+ 'Should preserve editor-only properties'
+ );
+ t.notOk(
+ state.editor.features[0].properties.filterId,
+ 'Should ignore reserved keys from the payload'
+ );
+
+ state = reducer(state, VisStateActions.setEditorFeatureProperties(pointFeature, {}));
+ t.notOk(state.editor.features[0].properties.name, 'Should remove user properties when cleared');
+ t.equal(state.editor.features[0].properties.isClosed, false, 'Should keep editor-only properties');
+
+ t.end();
+});
+
test('#visStateReducer -> APPLY_CPU_FILTER has multi datasets', t => {
const initialState = CloneDeep(StateWFilters.visState);
const previousDataset1 = initialState.datasets[testCsvDataId];
diff --git a/test/node/utils/editor-feature-utils-test.js b/test/node/utils/editor-feature-utils-test.js
new file mode 100644
index 000000000..1d3cd56dc
--- /dev/null
+++ b/test/node/utils/editor-feature-utils-test.js
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {
+ editorFeaturesToFeatureCollection,
+ sanitizeEditorFeature,
+ toSketchFeature,
+ getFilterFeatureAnchor,
+ getUserFeatureProperties,
+ mergeUserFeatureProperties
+} from '@kepler.gl/utils';
+
+test('editor-feature-utils -> sanitizeEditorFeature', t => {
+ const feature = {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {
+ isClosed: true,
+ filterId: 'abc',
+ bbox: {xmin: 0, xmax: 1, ymin: 0, ymax: 1},
+ name: 'route'
+ },
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ }
+ };
+
+ t.deepEqual(
+ sanitizeEditorFeature(feature),
+ {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {name: 'route'},
+ geometry: feature.geometry
+ },
+ 'Should keep geometry and drop editor-only properties'
+ );
+ t.end();
+});
+
+test('editor-feature-utils -> editorFeaturesToFeatureCollection', t => {
+ const point = {
+ id: 'point-1',
+ properties: {isClosed: false},
+ geometry: {type: 'Point', coordinates: [10, 20]}
+ };
+ const line = {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {},
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ }
+ };
+ const withoutGeometry = {
+ id: 'empty',
+ properties: {},
+ geometry: null
+ };
+
+ t.deepEqual(
+ editorFeaturesToFeatureCollection([point, line, withoutGeometry]),
+ {
+ type: 'FeatureCollection',
+ features: [
+ {
+ type: 'Feature',
+ id: 'point-1',
+ properties: {},
+ geometry: point.geometry
+ },
+ {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {},
+ geometry: line.geometry
+ }
+ ]
+ },
+ 'Should wrap sketch features as a FeatureCollection and skip invalid geometries'
+ );
+ t.end();
+});
+
+test('editor-feature-utils -> toSketchFeature', t => {
+ const feature = {
+ type: 'Feature',
+ id: 'poly-1',
+ properties: {
+ isClosed: true,
+ filterId: 'filter-1',
+ name: 'keep-me'
+ },
+ geometry: {type: 'Polygon', coordinates: []}
+ };
+
+ t.deepEqual(
+ toSketchFeature(feature).properties,
+ {isClosed: true, name: 'keep-me'},
+ 'Should drop filterId so the polygon becomes a sketch again'
+ );
+ t.end();
+});
+
+test('editor-feature-utils -> getFilterFeatureAnchor', t => {
+ const feature = {
+ type: 'Feature',
+ id: 'poly-1',
+ properties: {},
+ geometry: {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [0, 0],
+ [4, 0],
+ [4, 3],
+ [0, 3],
+ [0, 0]
+ ]
+ ]
+ }
+ };
+
+ t.deepEqual(
+ getFilterFeatureAnchor(feature),
+ [4, 3],
+ 'Should use the north-east vertex for the filter badge'
+ );
+ t.end();
+});
+
+test('editor-feature-utils -> getUserFeatureProperties / mergeUserFeatureProperties', t => {
+ const feature = {
+ type: 'Feature',
+ id: 'line-1',
+ properties: {
+ isClosed: false,
+ filterId: 'keep-internal',
+ name: 'route'
+ },
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ }
+ };
+
+ t.deepEqual(
+ getUserFeatureProperties(feature),
+ {name: 'route'},
+ 'Should return only user-facing properties'
+ );
+
+ t.deepEqual(
+ mergeUserFeatureProperties(feature, {name: 'updated', capacity: '12', filterId: 'nope'})
+ .properties,
+ {
+ isClosed: false,
+ filterId: 'keep-internal',
+ name: 'updated',
+ capacity: '12'
+ },
+ 'Should replace user properties and ignore reserved keys'
+ );
+
+ t.deepEqual(
+ mergeUserFeatureProperties(feature, {}).properties,
+ {isClosed: false, filterId: 'keep-internal'},
+ 'Should drop previous user properties when the next set is empty'
+ );
+
+ t.end();
+});
diff --git a/test/node/utils/editor-utils-test.js b/test/node/utils/editor-utils-test.js
index 7cebf6d9b..f67921669 100644
--- a/test/node/utils/editor-utils-test.js
+++ b/test/node/utils/editor-utils-test.js
@@ -25,6 +25,16 @@ test('editorLayerUtils -> isDrawingActive', t => {
true,
'Should return true for activated editor UI and draw mode'
);
+ t.equal(
+ EditorLayerUtils.isDrawingActive(true, EDITOR_MODES.DRAW_LINESTRING),
+ true,
+ 'Should return true for line drawing mode'
+ );
+ t.equal(
+ EditorLayerUtils.isDrawingActive(true, EDITOR_MODES.DRAW_POINT),
+ true,
+ 'Should return true for point drawing mode'
+ );
t.end();
});
@@ -89,6 +99,26 @@ test('editorLayerUtils -> getTooltip', t => {
'Should return a tooltip as drawing is active and started'
);
+ t.equal(
+ EditorLayerUtils.getTooltip(info, {
+ editor: {...editor, mode: EDITOR_MODES.DRAW_POINT},
+ theme: {},
+ editorMenuActive: true
+ })?.text,
+ 'Click to add a point',
+ 'Should return a tooltip for point drawing'
+ );
+
+ t.equal(
+ EditorLayerUtils.getTooltip(info, {
+ editor: {...editor, mode: EDITOR_MODES.DRAW_LINESTRING},
+ theme: {},
+ editorMenuActive: true
+ })?.text,
+ 'Click to start a line. Double-click to finish',
+ 'Should return a tooltip for line drawing'
+ );
+
info.layer.id = EDITOR_LAYER_ID;
t.deepEqual(
@@ -100,6 +130,19 @@ test('editorLayerUtils -> getTooltip', t => {
'Should return a tooltip for selected feature'
);
+ t.equal(
+ EditorLayerUtils.getTooltip(
+ {...info, object: {id: 1, properties: {filterId: 'filter-1'}}},
+ {
+ editor: {...editor, selectedFeature: {id: 1, properties: {filterId: 'filter-1'}}},
+ theme: {},
+ editorMenuActive: false
+ }
+ )?.text,
+ 'Filter region\nRight click to view options\nDrag to move the feature',
+ 'Should return a tooltip for selected filter'
+ );
+
t.equal(
EditorLayerUtils.getTooltip(
{...info, object: {geometry: {type: 'Point'}}},
@@ -127,6 +170,22 @@ test('editorLayerUtils -> getTooltip', t => {
'Should return a tooltip for hovered lines'
);
+ t.equal(
+ EditorLayerUtils.getTooltip(
+ {...info, object: {properties: {editHandleType: 'intermediate'}}},
+ {
+ editor: {
+ ...editor,
+ selectedFeature: {id: 'line-1', geometry: {type: 'LineString'}}
+ },
+ theme: {},
+ editorMenuActive: false
+ }
+ )?.text,
+ 'Drag to move the line\nClick to insert a point',
+ 'Should return a tooltip for hovered line sketches'
+ );
+
t.equal(
EditorLayerUtils.getTooltip(info, {editor, theme: {}, editorMenuActive: false})?.text,
'Click to select the feature\nRight click to view options',
@@ -234,6 +293,62 @@ test('editorLayerUtils -> onClick', t => {
t.end();
});
+test('editorLayerUtils -> onClick selects LineString', t => {
+ const {editor} = INITIAL_VIS_STATE;
+ const calls = [];
+ const setSelectedFeature = (feature, context) => {
+ calls.push({feature, context});
+ };
+ const lineFeature = {
+ id: 'line-1',
+ geometry: {
+ type: 'LineString',
+ coordinates: [
+ [0, 0],
+ [1, 1]
+ ]
+ },
+ properties: {}
+ };
+
+ t.equal(
+ EditorLayerUtils.onClick(
+ {layer: {id: EDITOR_LAYER_ID}, object: lineFeature},
+ {rightButton: true, srcEvent: {point: [10, 20]}},
+ {editor, editorMenuActive: false, onLayerClick: () => {}, setSelectedFeature}
+ ),
+ true,
+ 'Should handle click on a line feature'
+ );
+ t.equal(calls[0].feature, lineFeature, 'Should select the line feature');
+ t.equal(calls[0].context.rightClick, true, 'Should include right-click context');
+ t.end();
+});
+
+test('editorLayerUtils -> onClick does not select edit handles', t => {
+ const selectedFeature = {id: 'poly-1'};
+ const editor = {...INITIAL_VIS_STATE.editor, selectedFeature};
+ const calls = [];
+ const setSelectedFeature = feature => {
+ calls.push(feature);
+ };
+
+ EditorLayerUtils.onClick(
+ {
+ layer: {id: EDITOR_LAYER_ID},
+ object: {
+ geometry: {type: 'Point', coordinates: [0, 0]},
+ properties: {editHandleType: 'existing'}
+ }
+ },
+ {},
+ {editor, editorMenuActive: false, onLayerClick: () => {}, setSelectedFeature}
+ );
+
+ t.equal(calls[0], selectedFeature, 'Should keep the currently selected feature');
+ t.end();
+});
+
test('editorLayerUtils -> getEditorLayer', t => {
const {editor} = INITIAL_VIS_STATE;
@@ -253,3 +368,98 @@ test('editorLayerUtils -> getEditorLayer', t => {
t.end();
});
+
+test('editorLayerUtils -> filter polygons are styled differently from sketches', t => {
+ const sketch = {
+ id: 'sketch-1',
+ properties: {},
+ geometry: {type: 'Polygon', coordinates: []}
+ };
+ const filterFeature = {
+ id: 'filter-1',
+ properties: {filterId: 'poly-filter'},
+ geometry: {type: 'Polygon', coordinates: []}
+ };
+ const editorLayer = getEditorLayer({
+ editorMenuActive: false,
+ editor: INITIAL_VIS_STATE.editor,
+ onSetFeatures: VisStateActions.setFeatures,
+ setSelectedFeature: VisStateActions.setSelectedFeature,
+ featureCollection: {
+ features: [sketch, filterFeature],
+ type: 'FeatureCollection'
+ },
+ selectedFeatureIndexes: [],
+ viewport: null
+ });
+
+ t.deepEqual(
+ editorLayer.props.getDashArray(sketch),
+ [0, 0],
+ 'Sketch polygons should use a solid outline'
+ );
+ t.deepEqual(
+ editorLayer.props.getDashArray(filterFeature),
+ [4, 3],
+ 'Filter polygons should use a dashed outline'
+ );
+ t.notOk(
+ editorLayer.props.filled,
+ 'Filter polygons should stay outline-only when nothing is selected'
+ );
+ t.equal(
+ editorLayer.props.getFillColor(filterFeature, false)[3],
+ editorLayer.props.getFillColor(sketch, false)[3],
+ 'Filter and sketch fills should match when unselected'
+ );
+ t.equal(
+ editorLayer.props.highlightColor({object: filterFeature})[3],
+ 0x66,
+ 'Unselected polygon hover should use a semi-transparent yellow fill'
+ );
+
+ const layerWithPoint = getEditorLayer({
+ editorMenuActive: false,
+ editor: INITIAL_VIS_STATE.editor,
+ onSetFeatures: VisStateActions.setFeatures,
+ setSelectedFeature: VisStateActions.setSelectedFeature,
+ featureCollection: {
+ features: [
+ filterFeature,
+ {id: 'point-1', properties: {}, geometry: {type: 'Point', coordinates: [0, 0]}}
+ ],
+ type: 'FeatureCollection'
+ },
+ selectedFeatureIndexes: [],
+ viewport: null
+ });
+ t.ok(layerWithPoint.props.filled, 'Point sketches should enable fill so points are visible');
+ t.equal(
+ layerWithPoint.props.highlightColor({object: filterFeature})[3],
+ 0x66,
+ 'Polygon hover should stay semi-transparent even when point sketches enable fill'
+ );
+
+ const lineFeature = {
+ id: 'line-1',
+ properties: {},
+ geometry: {type: 'LineString', coordinates: [[0, 0], [1, 1]]}
+ };
+ t.equal(
+ editorLayer.props.getLineWidth(sketch, false),
+ 2,
+ 'Polygon sketches should keep the existing outline width'
+ );
+ t.equal(
+ editorLayer.props.getLineWidth(lineFeature, false),
+ 2,
+ 'Unselected line sketches should match the default stroke width'
+ );
+ t.equal(
+ editorLayer.props.getLineWidth(lineFeature, true),
+ 3,
+ 'Selected line sketches should use a thicker stroke so they stay visible'
+ );
+
+ t.end();
+});
diff --git a/test/node/utils/index.js b/test/node/utils/index.js
index 1c126b09c..0958ec375 100644
--- a/test/node/utils/index.js
+++ b/test/node/utils/index.js
@@ -21,6 +21,7 @@ import './export-utils-test';
import './s2-utils-test';
import './a5-utils-test';
import './editor-utils-test';
+import './editor-feature-utils-test';
import './kepler-gl-utils-test';
import './timeline-test';
import './timeline-zoom-test';