Skip to content

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

feat: dataset operations as an optional base for frequent geometry ops (#3746)

Igor Dykhta39540fd0e3d7
diff --git a/docs/table-of-contents.json b/docs/table-of-contents.json
index 4e12d56df..f2985d818 100644
--- a/docs/table-of-contents.json
+++ b/docs/table-of-contents.json
@@ -21,7 +21,8 @@
{"entry": "docs/user-guides/j-get-started"},
{"entry": "docs/user-guides/k-save-and-export"},
{"entry": "docs/user-guides/l-color-attributes"},
- {"entry": "docs/user-guides/m-map-settings"}
+ {"entry": "docs/user-guides/m-map-settings"},
+ {"entry": "docs/user-guides/dataset-operations"}
]
},
{
diff --git a/docs/user-guides/README.md b/docs/user-guides/README.md
index b6c544dfc..e97d73624 100644
--- a/docs/user-guides/README.md
+++ b/docs/user-guides/README.md
@@ -86,3 +86,5 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da
* [Export Video](./k-save-and-export.md#export-video)
#### [FAQ](./i-FAQ.md)
+
+#### [Dataset operations](./dataset-operations.md)
diff --git a/docs/user-guides/dataset-operations.md b/docs/user-guides/dataset-operations.md
new file mode 100644
index 000000000..9da6c7029
--- /dev/null
+++ b/docs/user-guides/dataset-operations.md
@@ -0,0 +1,65 @@
+# Dataset operations
+
+Use dataset operations to create a new table from data already on the map. Results are added as regular datasets (with automatic layers when geometry is present). Parent tables are not modified.
+
+Open the **⋯** menu on a local dataset in the Layers catalog to:
+
+- **Group by** one column and aggregate the rest
+- **Join** two tables on a shared key (left, inner, or full)
+- **Spatial join** a **target dataset** to a **join dataset** with a spatial join operation (intersects, equals, crosses, overlaps, within, touches)
+
+Operations run entirely in the browser. They are available for local (and remote file) tables, and are hidden for vector tiles, raster tiles, WMS, and 3D tiles.
+
+## Group by
+
+Create one output row per unique value in the grouping column. Remaining columns are aggregated.
+
+The panel is arranged like this:
+
+1. **Group by field** — column that defines the groups
+2. **Aggregation Rules** — aggregation per remaining column (`COUNT`, `SUM`, `MEAN`, `MIN`, `MAX`, `MEDIAN`, `UNIQUE`, `MERGE`)
+
+Numeric fields default to **MEAN**, strings to **UNIQUE**, geometry (`geojson` / `point`) to **MERGE**, others to **COUNT**. **MERGE** keeps location by combining features in each group into a MultiPolygon, MultiPoint, or GeometryCollection. Name the result and click **Run**.
+
+## Attribute join
+
+Join two datasets on matching key values. The panel is arranged like this:
+
+1. **Left** — left dataset, join key, and columns to include
+2. **Join Type** — left, inner, or full
+3. **Right** — right dataset, join key, and columns to include
+
+- **Left** keeps every row from the left table and fills unmatched right columns with empty values.
+- **Inner** keeps only rows with a match.
+- **Full** keeps unmatched rows from both tables.
+
+Null keys never match. Duplicate keys produce one output row per match. Right-side columns are prefixed with the right dataset name when names collide.
+
+## Spatial join
+
+Each **target** feature becomes one output row. Matching **join** features are aggregated onto that row (including a `count` of matches).
+
+The panel is arranged like this:
+
+1. **Target Dataset** — output rows and target geometry
+2. **Join Operation** — spatial predicate
+3. **Join Dataset** — features to match and aggregate
+
+Choose a **Join Operation**:
+
+| Predicate | Match when |
+| --- | --- |
+| Intersects | Geometries share any interior or boundary |
+| Equals | Geometries occupy the same space |
+| Crosses | Geometries share interior space but neither contains the other (typically a line vs polygon/line) |
+| Overlaps | Same-dimension geometries share interior space and neither contains the other |
+| Within | Target is completely inside join |
+| Touches | Geometries share a boundary but not their interiors |
+
+Distance joins and geometry merge are not included. For SQL predicates, use the [SQL/DuckDB Data Explorer](./sql-data-explorer.md).
+
+## Saving maps
+
+Result tables are snapshots. Deleting a source dataset does not remove the result. Re-running an operation with the same result name replaces that table so existing layers keep their bindings.
+
+Disable the UI with `enableDatasetOps: false` in `initApplicationConfig`.
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index 7cb54c062..be8e421ff 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -120,6 +120,16 @@ export const ActionTypes = {
REFRESH_DATASET_SUCCESS: `${ACTION_PREFIX}REFRESH_DATASET_SUCCESS`,
REFRESH_DATASET_ERROR: `${ACTION_PREFIX}REFRESH_DATASET_ERROR`,
REFRESH_DATASET_PROGRESS: `${ACTION_PREFIX}REFRESH_DATASET_PROGRESS`,
+ ADD_GROUP_BY: `${ACTION_PREFIX}ADD_GROUP_BY`,
+ SET_GROUP_BY_CONFIG: `${ACTION_PREFIX}SET_GROUP_BY_CONFIG`,
+ RUN_GROUP_BY: `${ACTION_PREFIX}RUN_GROUP_BY`,
+ ADD_JOIN: `${ACTION_PREFIX}ADD_JOIN`,
+ SET_JOIN_CONFIG: `${ACTION_PREFIX}SET_JOIN_CONFIG`,
+ RUN_JOIN: `${ACTION_PREFIX}RUN_JOIN`,
+ ADD_SPATIAL_JOIN: `${ACTION_PREFIX}ADD_SPATIAL_JOIN`,
+ SET_SPATIAL_JOIN_CONFIG: `${ACTION_PREFIX}SET_SPATIAL_JOIN_CONFIG`,
+ RUN_SPATIAL_JOIN: `${ACTION_PREFIX}RUN_SPATIAL_JOIN`,
+ REMOVE_DATASET_OP: `${ACTION_PREFIX}REMOVE_DATASET_OP`,
ADD_TO_DATASET: `${ACTION_PREFIX}ADD_TO_DATASET`,
REMOVE_FROM_DATASET: `${ACTION_PREFIX}REMOVE_FROM_DATASET`,
ADD_EFFECT: `${ACTION_PREFIX}ADD_EFFECT`,
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 6f16d0935..77a853fc9 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -5,7 +5,7 @@
import {default as ActionTypes} from './action-types';
import {FileCacheItem} from '@kepler.gl/processors';
import {Layer, LayerBaseConfig} from '@kepler.gl/layers';
-import {KeplerTable} from '@kepler.gl/table';
+import {GroupByOp, JoinOp, KeplerTable} from '@kepler.gl/table';
import {
AddDataToMapPayload,
ViewportPadding,
@@ -2380,13 +2380,148 @@ export type CreateNewDatasetSuccessPayload = {
progressIds?: string[];
};
-/**
- * Called when a new dataset is created successfully via async table methods
- * @memberof visStateActions
- * @param payload
- * @param payload.results - results of promises.allSettlted
- * @returns
- */
+export type AddGroupByUpdaterAction = {
+ dataId: string;
+};
+
+export function addGroupBy(
+ dataId: string
+): Merge<AddGroupByUpdaterAction, {type: typeof ActionTypes.ADD_GROUP_BY}> {
+ return {
+ type: ActionTypes.ADD_GROUP_BY,
+ dataId
+ };
+}
+
+export type SetGroupByConfigUpdaterAction = {
+ id: string;
+ config: Partial<GroupByOp>;
+};
+
+export function setGroupByConfig(
+ id: string,
+ config: Partial<GroupByOp>
+): Merge<SetGroupByConfigUpdaterAction, {type: typeof ActionTypes.SET_GROUP_BY_CONFIG}> {
+ return {
+ type: ActionTypes.SET_GROUP_BY_CONFIG,
+ id,
+ config
+ };
+}
+
+export type RunGroupByUpdaterAction = {
+ id: string;
+};
+
+export function runGroupBy(
+ id: string
+): Merge<RunGroupByUpdaterAction, {type: typeof ActionTypes.RUN_GROUP_BY}> {
+ return {
+ type: ActionTypes.RUN_GROUP_BY,
+ id
+ };
+}
+
+export type AddJoinUpdaterAction = {
+ dataId: string;
+ implementation?: JoinOp['implementation'];
+};
+
+export function addJoin(
+ dataId: string,
+ implementation: JoinOp['implementation'] = 'simple'
+): Merge<AddJoinUpdaterAction, {type: typeof ActionTypes.ADD_JOIN}> {
+ return {
+ type: ActionTypes.ADD_JOIN,
+ dataId,
+ implementation
+ };
+}
+
+export type SetJoinConfigUpdaterAction = {
+ id: string;
+ config: Partial<JoinOp>;
+};
+
+export function setJoinConfig(
+ id: string,
+ config: Partial<JoinOp>
+): Merge<SetJoinConfigUpdaterAction, {type: typeof ActionTypes.SET_JOIN_CONFIG}> {
+ return {
+ type: ActionTypes.SET_JOIN_CONFIG,
+ id,
+ config
+ };
+}
+
+export type RunJoinUpdaterAction = {
+ id: string;
+};
+
+export function runJoin(
+ id: string
+): Merge<RunJoinUpdaterAction, {type: typeof ActionTypes.RUN_JOIN}> {
+ return {
+ type: ActionTypes.RUN_JOIN,
+ id
+ };
+}
+
+export type AddSpatialJoinUpdaterAction = {
+ dataId: string;
+};
+
+export function addSpatialJoin(
+ dataId: string
+): Merge<AddSpatialJoinUpdaterAction, {type: typeof ActionTypes.ADD_SPATIAL_JOIN}> {
+ return {
+ type: ActionTypes.ADD_SPATIAL_JOIN,
+ dataId
+ };
+}
+
+export type SetSpatialJoinConfigUpdaterAction = {
+ id: string;
+ config: Partial<JoinOp>;
+};
+
+export function setSpatialJoinConfig(
+ id: string,
+ config: Partial<JoinOp>
+): Merge<SetSpatialJoinConfigUpdaterAction, {type: typeof ActionTypes.SET_SPATIAL_JOIN_CONFIG}> {
+ return {
+ type: ActionTypes.SET_SPATIAL_JOIN_CONFIG,
+ id,
+ config
+ };
+}
+
+export type RunSpatialJoinUpdaterAction = {
+ id: string;
+};
+
+export function runSpatialJoin(
+ id: string
+): Merge<RunSpatialJoinUpdaterAction, {type: typeof ActionTypes.RUN_SPATIAL_JOIN}> {
+ return {
+ type: ActionTypes.RUN_SPATIAL_JOIN,
+ id
+ };
+}
+
+export type RemoveDatasetOpUpdaterAction = {
+ id: string;
+};
+
+export function removeDatasetOp(
+ id: string
+): Merge<RemoveDatasetOpUpdaterAction, {type: typeof ActionTypes.REMOVE_DATASET_OP}> {
+ return {
+ type: ActionTypes.REMOVE_DATASET_OP,
+ id
+ };
+}
+
export const createNewDatasetSuccess = createAction<CreateNewDatasetSuccessPayload>(
ActionTypes.CREATE_NEW_DATASET_SUCCESS
);
diff --git a/src/common-utils/src/h3-utils.ts b/src/common-utils/src/h3-utils.ts
index a19cf70da..38a74f990 100644
--- a/src/common-utils/src/h3-utils.ts
+++ b/src/common-utils/src/h3-utils.ts
@@ -1,11 +1,18 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import {getResolution, isValidCell, cellToLatLng, cellToBoundary} from 'h3-js';
+import {
+ getResolution,
+ isValidCell,
+ cellToLatLng,
+ cellToBoundary,
+ latLngToCell,
+ cellToParent
+} from 'h3-js';
import type {H3Index} from 'h3-js';
import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
-export {getResolution, isValidCell};
+export {getResolution, isValidCell, latLngToCell, cellToParent};
export {getResolution as h3GetResolution, isValidCell as h3IsValid};
export type Centroid = [number, number];
diff --git a/src/common-utils/src/index.ts b/src/common-utils/src/index.ts
index 599301594..ce82e617c 100644
--- a/src/common-utils/src/index.ts
+++ b/src/common-utils/src/index.ts
@@ -7,5 +7,13 @@ export * from './string';
export * from './url';
export * from './promise';
-export {getCentroid, getHexFields, h3IsValid, idToPolygonGeo} from './h3-utils';
+export {
+ getCentroid,
+ getHexFields,
+ h3IsValid,
+ idToPolygonGeo,
+ latLngToCell,
+ cellToParent,
+ h3GetResolution
+} from './h3-utils';
export type {Centroid} from './h3-utils';
diff --git a/src/components/src/common/icons/grouping.tsx b/src/components/src/common/icons/grouping.tsx
new file mode 100644
index 000000000..d98955c72
--- /dev/null
+++ b/src/components/src/common/icons/grouping.tsx
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class Grouping extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ viewBox: '0 0 16 16',
+ predefinedClassName: 'data-ex-icons-grouping'
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M6 5H10C11.6569 5 13 6.34315 13 8C13 9.65685 11.6569 11 10 11H6C4.34315 11 3 9.65685 3 8C3 6.34315 4.34315 5 6 5ZM2 8C2 5.79086 3.79086 4 6 4H10C12.2091 4 14 5.79086 14 8C14 10.2091 12.2091 12 10 12H6C3.79086 12 2 10.2091 2 8ZM7 8C7 8.55228 6.55228 9 6 9C5.44772 9 5 8.55228 5 8C5 7.44772 5.44772 7 6 7C6.55228 7 7 7.44772 7 8ZM11 8C11 8.55228 10.5523 9 10 9C9.44772 9 9 8.55228 9 8C9 7.44772 9.44772 7 10 7C10.5523 7 11 7.44772 11 8Z"
+ />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/icons/index.tsx b/src/components/src/common/icons/index.tsx
index aa08526f6..cfe25080f 100644
--- a/src/components/src/common/icons/index.tsx
+++ b/src/components/src/common/icons/index.tsx
@@ -46,12 +46,14 @@ export {default as FilterFunnel} from './filter-funnel';
export {default as Folder} from './folder';
export {default as FreeWindow} from './free-window';
export {default as Gear} from './gear';
+export {default as Grouping} from './grouping';
export {default as Hash} from './hash';
export {default as Help} from './help';
export {default as Histogram} from './histogram';
export {default as HorizontalResizeHandle} from './horizontal-resize-handle';
export {default as IconWrapper} from './base';
export {default as Info} from './info';
+export {default as Join} from './join';
export {default as Layers} from './layers';
export {default as LeftArrow} from './left-arrow';
export {default as Legend} from './legend';
@@ -75,8 +77,10 @@ export {default as Speed} from './speed';
export {default as SquareSelect} from './square-select';
export {default as Settings} from './settings';
export {default as Search} from './search';
+export {default as SpatialJoin} from './spatial-join';
export {default as Split} from './split';
export {default as Trash} from './trash';
+export {default as Overflow} from './overflow';
export {default as VertDots} from './vert-dots';
export {default as VertThreeDots} from './vert-three-dots';
export {default as CodeAlt} from './code-alt';
diff --git a/src/components/src/common/icons/join.tsx b/src/components/src/common/icons/join.tsx
new file mode 100644
index 000000000..5fb501e14
--- /dev/null
+++ b/src/components/src/common/icons/join.tsx
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class Join extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ viewBox: '0 0 23 16',
+ predefinedClassName: 'data-ex-icons-join'
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M1.53333 8C1.53333 4.43687 4.39374 1.54839 7.92222 1.54839C8.63773 1.54839 9.32576 1.66716 9.96805 1.88625C8.24794 3.35373 7.15558 5.54805 7.15558 8C7.15558 10.452 8.24794 12.6463 9.96805 14.1138C9.32576 14.3328 8.63773 14.4516 7.92222 14.4516C4.39374 14.4516 1.53333 11.5631 1.53333 8ZM11.5 15.1396C10.4253 15.6899 9.20963 16 7.92222 16C3.5469 16 0 12.4183 0 8C0 3.58172 3.5469 0 7.92222 0C9.20963 0 10.4253 0.3101 11.5 0.860368C12.5747 0.3101 13.7904 0 15.0778 0C19.4531 0 23 3.58172 23 8C23 12.4183 19.4531 16 15.0778 16C13.7904 16 12.5747 15.6899 11.5 15.1396ZM13.032 1.88625C13.6743 1.66716 14.3623 1.54839 15.0778 1.54839C18.6063 1.54839 21.4667 4.43687 21.4667 8C21.4667 11.5631 18.6063 14.4516 15.0778 14.4516C14.3623 14.4516 13.6743 14.3328 13.032 14.1138C14.7521 12.6463 15.8444 10.452 15.8444 8C15.8444 5.54805 14.7521 3.35373 13.032 1.88625ZM11.5 2.65412C13.1963 3.81402 14.3111 5.77554 14.3111 8C14.3111 10.2245 13.1963 12.186 11.5 13.3459C9.80376 12.186 8.68891 10.2245 8.68891 8C8.68891 5.77554 9.80376 3.81402 11.5 2.65412Z"
+ />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/icons/overflow.tsx b/src/components/src/common/icons/overflow.tsx
new file mode 100644
index 000000000..1144e6113
--- /dev/null
+++ b/src/components/src/common/icons/overflow.tsx
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class Overflow extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ viewBox: '0 0 24 24',
+ predefinedClassName: 'data-ex-icons-overflow'
+ };
+
+ render() {
+ return (
+ <Base
+ {...this.props}
+ style={{fill: 'none', stroke: 'currentcolor'}}
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <circle cx="12" cy="5" r="1" />
+ <circle cx="12" cy="12" r="1" />
+ <circle cx="12" cy="19" r="1" />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/icons/spatial-join.tsx b/src/components/src/common/icons/spatial-join.tsx
new file mode 100644
index 000000000..b70bc3e89
--- /dev/null
+++ b/src/components/src/common/icons/spatial-join.tsx
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class SpatialJoin extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ viewBox: '0 0 12 14',
+ predefinedClassName: 'data-ex-icons-spatial-join'
+ };
+
+ render() {
+ return (
+ <Base {...this.props}>
+ <path d="M5.50649 3.8381C5.96792 4.30074 5.96792 5.05082 5.50649 5.51346C5.04506 5.9761 4.29693 5.9761 3.8355 5.51346C3.37406 5.05082 3.37406 4.30074 3.8355 3.8381C4.29693 3.37546 5.04506 3.37546 5.50649 3.8381Z" />
+ <path d="M4.50649 7.8381C4.96792 8.30074 4.96792 9.05082 4.50649 9.51346C4.04506 9.9761 3.29693 9.9761 2.8355 9.51346C2.37406 9.05082 2.37406 8.30074 2.8355 7.8381C3.29693 7.37546 4.04506 7.37546 4.50649 7.8381Z" />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M8.18158 5.9998C8.83243 5.9998 9.36316 6.53191 9.36316 7.18447C9.36316 7.83682 8.83243 8.36914 8.18158 8.36914C7.53072 8.36914 7 7.83703 7 7.18447C7.0002 6.53191 7.53093 5.9998 8.18158 5.9998Z"
+ />
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M5.55821 0.122043L0.441785 3.16722C0.308114 3.24678 0.19699 3.36105 0.119479 3.49866C0.0419683 3.63627 0.000774673 3.79241 0 3.95153V10.0452C0.000217459 10.2049 0.0411474 10.3617 0.118686 10.4999C0.196225 10.6381 0.307648 10.7529 0.441786 10.8328L5.55821 13.878C5.69253 13.9579 5.8449 14 6 14C6.1551 14 6.30747 13.9579 6.44179 13.878L11.5582 10.8328C11.6921 10.7531 11.8034 10.6385 11.8809 10.5006C11.9584 10.3627 11.9995 10.2062 12 10.0468V3.95482C11.9998 3.79514 11.9589 3.63832 11.8813 3.50009C11.8038 3.36185 11.6924 3.24706 11.5582 3.16722L6.44179 0.122043C6.30747 0.042094 6.1551 0 6 0C5.8449 0 5.69253 0.042094 5.55821 0.122043ZM11 3.9987L6 1.02282L1 3.9987V10.0013L6 12.9772L11 10.0013V3.9987Z"
+ />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index 281ee1980..1e6af3840 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -137,6 +137,10 @@ export {default as DatasetInfoFactory} from './side-panel/common/dataset-info';
export {default as DatasetTagFactory} from './side-panel/common/dataset-tag';
export {default as DatasetTitleFactory} from './side-panel/common/dataset-title';
export {default as SourceDataCatalogFactory} from './side-panel/common/source-data-catalog';
+export {default as DatasetOpsPanelsFactory} from './side-panel/dataset-ops/dataset-ops-panels';
+export {default as GroupByPanelFactory} from './side-panel/dataset-ops/group-by-panel';
+export {default as JoinPanelFactory} from './side-panel/dataset-ops/join-panel';
+export {default as SpatialJoinPanelFactory} from './side-panel/dataset-ops/spatial-join-panel';
export {default as SourceDataSelectorFactory} from './side-panel/common/source-data-selector';
export {default as FilterManagerFactory} from './side-panel/filter-manager';
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index 2cabb06af..65c71cddb 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -238,6 +238,8 @@ export const sidePanelSelector = (props: KeplerGLProps, availableProviders, filt
mapInfo: props.visState.mapInfo,
layerBlending: props.visState.layerBlending,
overlayBlending: props.visState.overlayBlending,
+ groupBys: props.visState.groupBys,
+ joins: props.visState.joins,
width: props.sidePanelWidth ?? DEFAULT_KEPLER_GL_PROPS.sidePanelWidth,
availableProviders,
diff --git a/src/components/src/side-panel.tsx b/src/components/src/side-panel.tsx
index 4f3bf3669..597d09f0c 100644
--- a/src/components/src/side-panel.tsx
+++ b/src/components/src/side-panel.tsx
@@ -26,21 +26,32 @@ import FilterManagerFactory from './side-panel/filter-manager';
import InteractionManagerFactory from './side-panel/interaction-manager';
import MapManagerFactory from './side-panel/map-manager';
import CustomPanelsFactory from './side-panel/custom-panel';
+import DatasetOpsPanelsFactory, {
+ hasActiveDatasetOp
+} from './side-panel/dataset-ops/dataset-ops-panels';
import styled from 'styled-components';
import {SidePanelProps, SidePanelItem} from './types';
-export const StyledSidePanelContent = styled.div`
+export const StyledSidePanelContent = styled.div<{$fill?: boolean}>`
${props => props.theme.sidePanelScrollBar};
flex-grow: 1;
+ min-width: 0;
+ min-height: 0;
padding: ${props => props.theme.sidePanelInnerPadding}px;
- overflow-y: scroll;
+ overflow-y: ${props => (props.$fill ? 'hidden' : 'scroll')};
overflow-x: hidden;
+ display: ${props => (props.$fill ? 'flex' : 'block')};
+ flex-direction: column;
.side-panel__content__inner {
display: flex;
height: 100%;
+ width: 100%;
+ min-width: 0;
flex-direction: column;
+ flex: ${props => (props.$fill ? '1' : 'initial')};
+ min-height: 0;
}
`;
@@ -52,7 +63,8 @@ SidePanelFactory.deps = [
FilterManagerFactory,
InteractionManagerFactory,
MapManagerFactory,
- CustomPanelsFactory
+ CustomPanelsFactory,
+ DatasetOpsPanelsFactory
];
/**
@@ -66,7 +78,8 @@ export default function SidePanelFactory(
FilterManager: ReturnType<typeof FilterManagerFactory>,
InteractionManager: ReturnType<typeof InteractionManagerFactory>,
MapManager: ReturnType<typeof MapManagerFactory>,
- CustomPanels: ReturnType<typeof CustomPanelsFactory>
+ CustomPanels: ReturnType<typeof CustomPanelsFactory>,
+ DatasetOpsPanels: ReturnType<typeof DatasetOpsPanelsFactory>
) {
// inject components
const SIDEBAR_COMPONENTS = {
@@ -122,7 +135,9 @@ export default function SidePanelFactory(
uiStateActions,
visStateActions,
version,
- width
+ width,
+ groupBys,
+ joins
} = props;
const {openDeleteModal, toggleModal, toggleSidePanel} = uiStateActions;
const {activeSidePanel} = uiState;
@@ -173,6 +188,7 @@ export default function SidePanelFactory(
any
>;
const PanelComponent = currentPanel?.component;
+ const datasetOpOpen = hasActiveDatasetOp(groupBys, joins);
return (
<Sidebar
@@ -200,49 +216,62 @@ export default function SidePanelFactory(
/>
{/* the next two components should be moved into one */}
{/* but i am keeping them because of backward compatibility */}
- <PanelToggle
- panels={panels}
- activePanel={activeSidePanel}
- togglePanel={uiStateActions.toggleSidePanel}
- />
- <StyledSidePanelContent className="side-panel__content">
+ {datasetOpOpen ? null : (
+ <PanelToggle
+ panels={panels}
+ activePanel={activeSidePanel}
+ togglePanel={uiStateActions.toggleSidePanel}
+ />
+ )}
+ <StyledSidePanelContent className="side-panel__content" $fill={datasetOpOpen}>
<div className="side-panel__content__inner">
- {PanelComponent ? (
- <PanelComponent
+ {datasetOpOpen ? (
+ <DatasetOpsPanels
datasets={datasets}
- filters={filters}
- layers={layers}
- layerClasses={layerClasses}
- layerOrder={layerOrder}
- layerBlending={layerBlending}
- overlayBlending={overlayBlending}
- mapStyle={mapStyle}
- mapState={mapState}
- mapStyleActions={mapStyleActions}
- mapStateActions={mapStateActions}
- interactionConfig={interactionConfig}
- removeDataset={onRemoveDataset}
- showDatasetTable={onShowDatasetTable}
- updateTableColor={onUpdateTableColor}
- showAddDataModal={onShowAddDataModal}
- showAddMapStyleModal={onShowAddMapStyleModal}
- uiStateActions={uiStateActions}
+ groupBys={groupBys}
+ joins={joins}
visStateActions={visStateActions}
- panelMetadata={currentPanel}
- panelListView={
- currentPanel?.id === 'layer'
- ? uiState.layerPanelListView
- : currentPanel?.id === 'filter'
- ? uiState.filterPanelListView
- : null
- }
/>
- ) : null}
- <CustomPanels
- {...customPanelProps}
- activeSidePanel={activeSidePanel}
- updateTableColor={onUpdateTableColor}
- />
+ ) : (
+ <>
+ {PanelComponent ? (
+ <PanelComponent
+ datasets={datasets}
+ filters={filters}
+ layers={layers}
+ layerClasses={layerClasses}
+ layerOrder={layerOrder}
+ layerBlending={layerBlending}
+ overlayBlending={overlayBlending}
+ mapStyle={mapStyle}
+ mapState={mapState}
+ mapStyleActions={mapStyleActions}
+ mapStateActions={mapStateActions}
+ interactionConfig={interactionConfig}
+ removeDataset={onRemoveDataset}
+ showDatasetTable={onShowDatasetTable}
+ updateTableColor={onUpdateTableColor}
+ showAddDataModal={onShowAddDataModal}
+ showAddMapStyleModal={onShowAddMapStyleModal}
+ uiStateActions={uiStateActions}
+ visStateActions={visStateActions}
+ panelMetadata={currentPanel}
+ panelListView={
+ currentPanel?.id === 'layer'
+ ? uiState.layerPanelListView
+ : currentPanel?.id === 'filter'
+ ? uiState.filterPanelListView
+ : null
+ }
+ />
+ ) : null}
+ <CustomPanels
+ {...customPanelProps}
+ activeSidePanel={activeSidePanel}
+ updateTableColor={onUpdateTableColor}
+ />
+ </>
+ )}
</div>
</StyledSidePanelContent>
</Sidebar>
diff --git a/src/components/src/side-panel/common/dataset-tag.tsx b/src/components/src/side-panel/common/dataset-tag.tsx
index 5662f9b3f..fe90d9b73 100644
--- a/src/components/src/side-panel/common/dataset-tag.tsx
+++ b/src/components/src/side-panel/common/dataset-tag.tsx
@@ -18,14 +18,16 @@ const DatasetTagWrapper = styled.div`
color: ${props => props.theme.textColor};
font-size: 11px;
letter-spacing: 0.2px;
- overflow: auto;
- display: flex;
+ min-width: 0;
+ overflow: hidden;
align-items: center;
.dataset-color {
flex-shrink: 0;
}
.dataset-name {
+ min-width: 0;
+ flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
diff --git a/src/components/src/side-panel/common/dataset-title.tsx b/src/components/src/side-panel/common/dataset-title.tsx
index f5c15ba30..9b34fd5b0 100644
--- a/src/components/src/side-panel/common/dataset-title.tsx
+++ b/src/components/src/side-panel/common/dataset-title.tsx
@@ -7,8 +7,8 @@ import {useIntl} from 'react-intl';
import {FormattedMessage} from '@kepler.gl/localization';
import {Table} from '@kepler.gl/layers';
-import {CenterFlexbox, Tooltip} from '../../common/styled-components';
-import {ArrowRight, Clock, Trash, WarningSign} from '../../common/icons';
+import {Tooltip} from '../../common/styled-components';
+import {Clock, WarningSign} from '../../common/icons';
import {DatasetType} from '@kepler.gl/constants';
import DatasetTagFactory from './dataset-tag';
import CustomPicker from '../layer-panel/custom-picker';
@@ -16,16 +16,26 @@ import {Portaled} from '../..';
import {rgbToHex} from '@kepler.gl/utils';
import {openDeleteModal, VisStateActions, ActionHandler} from '@kepler.gl/actions';
import {RGBColor} from '@kepler.gl/types';
-import {StyledDatasetTitleProps, RemoveDatasetProps, ShowDataTableProps} from './types';
+import {StyledDatasetTitleProps, ShowDataTableProps} from './types';
+import DatasetOpsMenu from '../dataset-ops/dataset-ops-menu';
const StyledDatasetTitle = styled.div<StyledDatasetTitleProps>`
color: ${props => props.theme.textColor};
display: flex;
align-items: center;
+ justify-content: space-between;
+ gap: 8px;
- .source-data-arrow {
- height: 16px;
+ .source-data-tag {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
}
+
+ .dataset-action {
+ color: ${props => props.theme.panelHeaderIcon};
+ }
+
&:hover {
cursor: ${props => (props.$clickable ? 'pointer' : 'auto')};
@@ -34,20 +44,37 @@ const StyledDatasetTitle = styled.div<StyledDatasetTitleProps>`
}
.dataset-action {
- color: ${props => props.theme.textColor};
opacity: 1;
}
.dataset-action:hover {
- color: ${props => props.theme.textColorHl};
+ color: ${props => props.theme.panelHeaderIconHover};
}
}
`;
-const DataTagAction = styled.div`
- margin-left: 12px;
+const DatasetTitleHeader = styled.div<{$clickable?: boolean}>`
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ flex: 1;
+ overflow: hidden;
+ cursor: ${props => (props.$clickable ? 'pointer' : 'auto')};
+`;
+
+const DatasetAction = styled.div`
+ display: flex;
+ align-items: center;
+ flex-shrink: 0;
+ position: relative;
+`;
+
+const DataTagAction = styled.div<{$alwaysVisible?: boolean}>`
+ margin-left: 8px;
+ width: 16px;
height: 16px;
- opacity: 0;
+ flex-shrink: 0;
+ opacity: ${props => (props.$alwaysVisible ? 1 : 0)};
`;
const DataTagActionButton = styled.button`
@@ -98,10 +125,18 @@ export type DatasetTitleProps = {
updateTableColor: ActionHandler<typeof VisStateActions.updateTableColor>;
removeDataset?: ActionHandler<typeof openDeleteModal>;
onToggleRefreshSettings?: () => void;
+ addGroupBy?: ActionHandler<typeof VisStateActions.addGroupBy>;
+ addJoin?: ActionHandler<typeof VisStateActions.addJoin>;
+ addSpatialJoin?: ActionHandler<typeof VisStateActions.addSpatialJoin>;
};
const ShowDataTable = ({id, showDatasetTable}: ShowDataTableProps) => (
- <DataTagAction className="dataset-action show-data-table" data-tip data-for={`data-table-${id}`}>
+ <DataTagAction
+ $alwaysVisible
+ className="dataset-action show-data-table"
+ data-tip
+ data-for={`data-table-${id}`}
+ >
<Table
height="16px"
onClick={e => {
@@ -141,27 +176,6 @@ const RefreshDatasetSettings = ({id, onToggle}: {id: string; onToggle?: () => vo
);
};
-const RemoveDataset = ({datasetKey, removeDataset}: RemoveDatasetProps) => (
- <DataTagAction
- className="dataset-action remove-dataset"
- data-tip
- data-for={`delete-${datasetKey}`}
- >
- <Trash
- height="16px"
- onClick={e => {
- e.stopPropagation();
- removeDataset?.(datasetKey);
- }}
- />
- <Tooltip id={`delete-${datasetKey}`} effect="solid" type="error">
- <span>
- <FormattedMessage id={'datasetTitle.removeDataset'} />
- </span>
- </Tooltip>
- </DataTagAction>
-);
-
const RefreshErrorIcon = ({id, message}: {id: string; message: string}) => (
<StyledRefreshError
className="dataset-refresh-error"
@@ -182,6 +196,11 @@ const RefreshErrorIcon = ({id, message}: {id: string; message: string}) => (
</StyledRefreshError>
);
+const DatasetTitleRoot = styled.div`
+ min-width: 0;
+ overflow: hidden;
+`;
+
DatasetTitleFactory.deps = [DatasetTagFactory];
export default function DatasetTitleFactory(
@@ -194,14 +213,21 @@ export default function DatasetTitleFactory(
removeDataset,
dataset,
updateTableColor,
- onToggleRefreshSettings
+ onToggleRefreshSettings,
+ addGroupBy,
+ addJoin,
+ addSpatialJoin
}) => {
const [displayColorPicker, setDisplayColorPicker] = useState(false);
const root = useRef(null);
const datasetId = dataset.id;
- const _handleClick = useCallback(() => {
- setDisplayColorPicker(!displayColorPicker);
- }, [setDisplayColorPicker, displayColorPicker]);
+ const _handleClick = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ setDisplayColorPicker(!displayColorPicker);
+ },
+ [setDisplayColorPicker, displayColorPicker]
+ );
const _handleClosePicker = useCallback(() => {
setDisplayColorPicker(false);
@@ -230,42 +256,49 @@ export default function DatasetTitleFactory(
const refreshError = dataset.metadata?.refreshError;
return (
- <div className="custom-palette-panel" ref={root}>
+ <DatasetTitleRoot className="custom-palette-panel" ref={root}>
<StyledDatasetTitle
className="source-data-title"
$clickable={Boolean(showDatasetTable || onTitleClick)}
>
- <DatasetTag
- dataset={dataset}
- onClick={_onClickTitle}
- updateTableColor={updateTableColor}
- onClickSquare={_handleClick}
- />
+ <DatasetTitleHeader $clickable={Boolean(showDatasetTable || onTitleClick)}>
+ <DatasetTag
+ dataset={dataset}
+ onClick={_onClickTitle}
+ updateTableColor={updateTableColor}
+ onClickSquare={_handleClick}
+ />
+ {refreshError ? <RefreshErrorIcon id={datasetId} message={refreshError} /> : null}
+ </DatasetTitleHeader>
<Portaled
isOpened={displayColorPicker !== false}
left={110}
top={-50}
onClose={_handleClosePicker}
>
- <CustomPicker color={rgbToHex(dataset.color)} onChange={_handleCustomPicker} />
+ <div onClick={e => e.stopPropagation()} onMouseDown={e => e.stopPropagation()}>
+ <CustomPicker color={rgbToHex(dataset.color)} onChange={_handleCustomPicker} />
+ </div>
</Portaled>
- {showDatasetTable ? (
- <CenterFlexbox className="source-data-arrow">
- <ArrowRight height="12px" />
- </CenterFlexbox>
- ) : null}
- {refreshError ? <RefreshErrorIcon id={datasetId} message={refreshError} /> : null}
- {showDatasetTable && !dataset.disableDataOperation ? (
- <ShowDataTable id={datasetId} showDatasetTable={showDatasetTable} />
- ) : null}
- {onToggleRefreshSettings && isRemote ? (
- <RefreshDatasetSettings id={datasetId} onToggle={onToggleRefreshSettings} />
- ) : null}
- {showDeleteDataset ? (
- <RemoveDataset datasetKey={datasetId} removeDataset={removeDataset} />
- ) : null}
+ <DatasetAction>
+ {showDatasetTable && !dataset.disableDataOperation ? (
+ <ShowDataTable id={datasetId} showDatasetTable={showDatasetTable} />
+ ) : null}
+ <DatasetOpsMenu
+ datasetId={datasetId}
+ dataset={dataset}
+ addGroupBy={addGroupBy}
+ addJoin={addJoin}
+ addSpatialJoin={addSpatialJoin}
+ showDeleteDataset={showDeleteDataset}
+ removeDataset={removeDataset}
+ />
+ {onToggleRefreshSettings && isRemote ? (
+ <RefreshDatasetSettings id={datasetId} onToggle={onToggleRefreshSettings} />
+ ) : null}
+ </DatasetAction>
</StyledDatasetTitle>
- </div>
+ </DatasetTitleRoot>
);
};
diff --git a/src/components/src/side-panel/common/source-data-catalog.tsx b/src/components/src/side-panel/common/source-data-catalog.tsx
index c5f42ac23..1ec0521ae 100644
--- a/src/components/src/side-panel/common/source-data-catalog.tsx
+++ b/src/components/src/side-panel/common/source-data-catalog.tsx
@@ -39,6 +39,9 @@ export type SourceDataCatalogProps = {
removeDataset?: ActionHandler<typeof openDeleteModal>;
refreshDataset?: ActionHandler<typeof VisStateActions.refreshDataset>;
updateDatasetProps?: ActionHandler<typeof VisStateActions.updateDatasetProps>;
+ addGroupBy?: ActionHandler<typeof VisStateActions.addGroupBy>;
+ addJoin?: ActionHandler<typeof VisStateActions.addJoin>;
+ addSpatialJoin?: ActionHandler<typeof VisStateActions.addSpatialJoin>;
};
SourceDataCatalogFactory.deps = [DatasetTitleFactory, DatasetInfoFactory];
@@ -55,7 +58,10 @@ function SourceDataCatalogFactory(
updateTableColor,
showDeleteDataset = false,
refreshDataset,
- updateDatasetProps
+ updateDatasetProps,
+ addGroupBy,
+ addJoin,
+ addSpatialJoin
}: SourceDataCatalogProps) => {
const [openRefreshSettingsId, setOpenRefreshSettingsId] = useState<string | null>(null);
@@ -79,6 +85,9 @@ function SourceDataCatalogFactory(
dataset={dataset}
onTitleClick={onTitleClick}
updateTableColor={updateTableColor}
+ addGroupBy={addGroupBy}
+ addJoin={addJoin}
+ addSpatialJoin={addSpatialJoin}
onToggleRefreshSettings={
(refreshDataset || updateDatasetProps) &&
dataset.type === DatasetType.EXTERNALLY_HOSTED
diff --git a/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx b/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx
new file mode 100644
index 000000000..8c2477670
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/dataset-op-panel.tsx
@@ -0,0 +1,380 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useState} from 'react';
+import styled from 'styled-components';
+import {FormattedMessage} from '@kepler.gl/localization';
+
+import {RGBColor} from '@kepler.gl/types';
+
+import {Button, Input, PanelLabel, SidePanelSection, Tooltip} from '../../common/styled-components';
+import {ArrowLeft, ArrowRight, Help} from '../../common/icons';
+
+export const DATASET_OPS_ACCENT: RGBColor = [85, 88, 219];
+
+const Panel = styled.div`
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-width: 0;
+ min-height: 0;
+ height: 100%;
+ width: 100%;
+ color: ${props => props.theme.textColor};
+`;
+
+const BackButton = styled(Button)`
+ flex-shrink: 0;
+ padding: 0;
+ margin-bottom: 12px;
+ justify-content: flex-start;
+
+ svg {
+ margin-right: 6px;
+ }
+`;
+
+const Header = styled.div<{hasDescription?: boolean}>`
+ display: flex;
+ align-items: center;
+ flex-shrink: 0;
+ margin-bottom: ${props => (props.hasDescription ? '8px' : '12px')};
+`;
+
+const TitleRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ svg {
+ flex-shrink: 0;
+ color: ${props => props.theme.subtextColor};
+ }
+`;
+
+const Title = styled.div`
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1.2;
+`;
+
+const Description = styled.div.attrs({
+ className: 'dataset-ops-panel__description'
+})`
+ flex-shrink: 0;
+ font-size: 12px;
+ line-height: 1.4;
+ color: ${props => props.theme.textColor};
+ margin-bottom: 16px;
+`;
+
+const HelpButton = styled.span.attrs({
+ className: 'dataset-ops-panel__help'
+})`
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ line-height: 0;
+ color: ${props => props.theme.labelColor};
+ cursor: pointer;
+ svg {
+ display: block;
+ }
+ &:hover {
+ color: ${props => props.theme.textColorHl};
+ }
+`;
+
+const HelpText = styled.div`
+ max-width: 240px;
+ line-height: 1.4;
+ white-space: normal;
+ text-align: left;
+`;
+
+const CollapsibleHeader = styled.div.attrs({
+ className: 'dataset-ops-collapsible__header'
+})<{isOpen?: boolean}>`
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ font-size: 12px;
+ color: ${props => props.theme.subtextColor};
+ margin-bottom: 6px;
+ cursor: pointer;
+ svg.collapsible-arrow {
+ margin-left: 4px;
+ transition: transform 0.2s ease;
+ transform: rotate(${props => (props.isOpen ? 90 : 0)}deg);
+ }
+`;
+
+const CollapsibleTitle = styled.span`
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ line-height: 12px;
+`;
+
+const SelectAllButton = styled.span.attrs({
+ className: 'dataset-ops-collapsible__select-all'
+})`
+ margin-left: auto;
+ color: ${props => props.theme.activeColor};
+ font-size: 11px;
+`;
+
+export function CollapsibleSection({
+ titleId,
+ helpId,
+ selectAll,
+ onToggleSelectAll,
+ children
+}: {
+ titleId: string;
+ helpId?: string;
+ selectAll?: boolean;
+ onToggleSelectAll?: () => void;
+ children: React.ReactNode;
+}) {
+ const [open, setOpen] = useState(false);
+ return (
+ <SidePanelSection className="dataset-ops-collapsible">
+ <CollapsibleHeader isOpen={open} onClick={() => setOpen(!open)}>
+ <CollapsibleTitle>
+ <FormattedMessage id={titleId} />
+ {helpId ? <DatasetOpHelp helpId={helpId} /> : null}
+ </CollapsibleTitle>
+ <ArrowRight className="collapsible-arrow" height="12px" />
+ {open && onToggleSelectAll ? (
+ <SelectAllButton
+ onClick={event => {
+ event.stopPropagation();
+ onToggleSelectAll();
+ }}
+ >
+ <FormattedMessage id={selectAll ? 'datasetOps.unselectAll' : 'datasetOps.selectAll'} />
+ </SelectAllButton>
+ ) : null}
+ </CollapsibleHeader>
+ {open ? children : null}
+ </SidePanelSection>
+ );
+}
+
+export function DatasetOpHelp({helpId}: {helpId: string}) {
+ const tooltipId = `${helpId.replace(/\./g, '-')}-help`;
+ return (
+ <HelpButton
+ data-tip
+ data-for={tooltipId}
+ aria-label="Help"
+ onClick={event => event.stopPropagation()}
+ >
+ <Help height="12px" />
+ <Tooltip id={tooltipId} effect="solid" place="right">
+ <HelpText>
+ <FormattedMessage id={helpId} />
+ </HelpText>
+ </Tooltip>
+ </HelpButton>
+ );
+}
+
+const Body = styled.div.attrs({
+ className: 'dataset-ops-panel__body'
+})`
+ flex: 1;
+ min-height: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
+ ${props => props.theme.sidePanelScrollBar};
+`;
+
+const Error = styled.div`
+ color: ${props => props.theme.errorColor};
+ font-size: 11px;
+ margin-bottom: 8px;
+`;
+
+const Actions = styled.div`
+ display: flex;
+ justify-content: flex-end;
+ gap: 8px;
+ flex-shrink: 0;
+ padding-top: 12px;
+`;
+
+/** Column lists scroll with the panel body so the dialog stays within the side panel. */
+export const ScrollableColumnList = styled.div.attrs({
+ className: 'dataset-ops-column-list'
+})`
+ overflow-x: hidden;
+ padding-right: 4px;
+`;
+
+export const DatasetOpsSection = styled.div<{sectionColor?: RGBColor}>`
+ border-left: 2px solid
+ ${props =>
+ props.sectionColor ? `rgb(${props.sectionColor.join(',')})` : props.theme.activeColor};
+ padding-left: 8px;
+ margin-bottom: 12px;
+
+ .data-source-selector .side-panel-panel__label {
+ display: none;
+ }
+ .data-source-selector {
+ margin-bottom: 8px;
+ }
+`;
+
+export const DatasetOpsSectionTitle = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+ font-size: 12px;
+ font-weight: 500;
+`;
+
+export const DatasetOpsFieldRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+ > :first-child {
+ flex: 1;
+ min-width: 0;
+ }
+`;
+
+export const DatasetOpsAggRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-bottom: 6px;
+`;
+
+export const DatasetOpsFieldName = styled.div`
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 12px;
+`;
+
+export const AggregationSelector = styled.div.attrs({
+ className: 'dataset-ops-aggregation-selector'
+})`
+ flex: 0 0 108px;
+ width: 108px;
+ min-width: 108px;
+ overflow: hidden;
+
+ .item-selector {
+ width: 100%;
+ min-width: 0;
+ }
+
+ .item-selector__dropdown {
+ width: 100%;
+ box-sizing: border-box;
+ }
+
+ .item-selector__dropdown__value {
+ min-width: 0;
+ flex: 1;
+ }
+`;
+
+export function DatasetOpPanel({
+ titleId,
+ titleHelpId,
+ titleIcon,
+ descriptionId,
+ error,
+ onClose,
+ onRun,
+ canRun,
+ children
+}: {
+ titleId: string;
+ titleHelpId?: string;
+ titleIcon?: React.ReactNode;
+ descriptionId?: string;
+ error?: string | null;
+ onClose: () => void;
+ onRun: () => void;
+ canRun: boolean;
+ children: React.ReactNode;
+}) {
+ return (
+ <Panel className="dataset-ops-panel">
+ <BackButton className="dataset-ops-panel__back" link type="button" onClick={onClose}>
+ <ArrowLeft height="16px" />
+ <FormattedMessage id="datasetOps.back" />
+ </BackButton>
+ <Header hasDescription={Boolean(descriptionId)}>
+ <TitleRow>
+ {titleIcon}
+ <Title>
+ <FormattedMessage id={titleId} />
+ </Title>
+ {titleHelpId ? <DatasetOpHelp helpId={titleHelpId} /> : null}
+ </TitleRow>
+ </Header>
+ {descriptionId ? (
+ <Description>
+ <FormattedMessage id={descriptionId} />
+ </Description>
+ ) : null}
+ {error ? <Error>{error}</Error> : null}
+ <Body>{children}</Body>
+ <Actions>
+ <Button secondary small type="button" onClick={onClose}>
+ <FormattedMessage id="datasetOps.cancel" />
+ </Button>
+ <Button small type="button" disabled={!canRun} onClick={onRun}>
+ <FormattedMessage id="datasetOps.run" />
+ </Button>
+ </Actions>
+ </Panel>
+ );
+}
+
+export function ResultNameInput({
+ value,
+ onChange
+}: {
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ return (
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.resultName" />
+ </PanelLabel>
+ <Input type="text" value={value} onChange={e => onChange(e.target.value)} />
+ </SidePanelSection>
+ );
+}
+
+export function fieldNameFromSelector(value: unknown): string | null {
+ if (!value) {
+ return null;
+ }
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return fieldNameFromSelector(value[0]);
+ }
+ if (typeof value === 'object' && value && 'name' in value) {
+ return String((value as {name: unknown}).name);
+ }
+ return null;
+}
+
+export default DatasetOpPanel;
diff --git a/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx
new file mode 100644
index 000000000..ed7fde5cd
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.spec.tsx
@@ -0,0 +1,342 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import {fireEvent} from '@testing-library/react';
+import {Datasets} from '@kepler.gl/table';
+import {Field} from '@kepler.gl/types';
+import {initApplicationConfig} from '@kepler.gl/utils';
+import {renderWithTheme} from 'test/helpers/component-jest-utils';
+import {DatasetOpsMenu} from './dataset-ops-menu';
+import GroupByPanelFactory from './group-by-panel';
+import DatasetOpPanel, {CollapsibleSection, fieldNameFromSelector} from './dataset-op-panel';
+
+function MockFieldSelector({
+ fields,
+ value,
+ onSelect
+}: {
+ fields: {name: string}[];
+ value?: string | null;
+ onSelect: (value: string) => void;
+}) {
+ return (
+ <select
+ aria-label="group-by-field"
+ value={value || ''}
+ onChange={event => onSelect(event.target.value)}
+ >
+ <option value="">Select</option>
+ {fields.map(field => (
+ <option key={field.name} value={field.name}>
+ {field.name}
+ </option>
+ ))}
+ </select>
+ );
+}
+
+describe('DatasetOpsMenu', () => {
+ beforeEach(() => {
+ initApplicationConfig({enableDatasetOps: true});
+ });
+
+ afterEach(() => {
+ initApplicationConfig({enableDatasetOps: true});
+ });
+
+ test('shows group-by and join actions for local datasets', () => {
+ const addGroupBy = jest.fn();
+ const {container} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="cities"
+ dataset={{type: 'local'}}
+ addGroupBy={addGroupBy}
+ addJoin={jest.fn()}
+ addSpatialJoin={jest.fn()}
+ />
+ );
+
+ const toggle = container.querySelector('.dataset-ops-menu__toggle') as HTMLButtonElement;
+ expect(toggle.getAttribute('data-for')).toBe('dataset-ops-cities');
+ expect(toggle.querySelector('svg')?.getAttribute('height')).toBe('16px');
+ expect(container.querySelector('#dataset-ops-cities')).toBeTruthy();
+
+ fireEvent.click(toggle);
+ fireEvent.click(document.querySelector('.dataset-ops-menu__group-by') as HTMLButtonElement);
+ expect(addGroupBy).toHaveBeenCalledWith('cities');
+ });
+
+ test('moves remove dataset into the more settings menu', () => {
+ const removeDataset = jest.fn();
+ const {container} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="cities"
+ dataset={{type: 'local'}}
+ addGroupBy={jest.fn()}
+ addJoin={jest.fn()}
+ addSpatialJoin={jest.fn()}
+ showDeleteDataset
+ removeDataset={removeDataset}
+ />
+ );
+
+ fireEvent.click(container.querySelector('.dataset-ops-menu__toggle') as HTMLElement);
+ fireEvent.click(document.querySelector('.dataset-ops-menu__remove') as HTMLButtonElement);
+ expect(removeDataset).toHaveBeenCalledWith('cities');
+ });
+
+ test('shows a delete-only overflow menu for vector tiles', () => {
+ const removeDataset = jest.fn();
+ const {container} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="tiles"
+ dataset={{type: 'vector-tile'}}
+ addGroupBy={jest.fn()}
+ addJoin={jest.fn()}
+ addSpatialJoin={jest.fn()}
+ showDeleteDataset
+ removeDataset={removeDataset}
+ />
+ );
+
+ fireEvent.click(container.querySelector('.dataset-ops-menu__toggle') as HTMLElement);
+ expect(document.querySelector('.dataset-ops-menu__group-by')).toBeNull();
+ expect(document.querySelector('.dataset-ops-menu__join')).toBeNull();
+ expect(document.querySelector('.dataset-ops-menu__spatial-join')).toBeNull();
+ fireEvent.click(document.querySelector('.dataset-ops-menu__remove') as HTMLButtonElement);
+ expect(removeDataset).toHaveBeenCalledWith('tiles');
+ });
+
+ test('hides menu for vector tiles and when ops are disabled', () => {
+ const {container: tiles} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="tiles"
+ dataset={{type: 'vector-tile'}}
+ addGroupBy={jest.fn()}
+ addJoin={jest.fn()}
+ addSpatialJoin={jest.fn()}
+ />
+ );
+ expect(tiles.querySelector('.dataset-ops-menu__toggle')).toBeNull();
+
+ initApplicationConfig({enableDatasetOps: false});
+ const {container: disabled} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="cities"
+ dataset={{type: 'local'}}
+ addGroupBy={jest.fn()}
+ addJoin={jest.fn()}
+ addSpatialJoin={jest.fn()}
+ />
+ );
+ expect(disabled.querySelector('.dataset-ops-menu__toggle')).toBeNull();
+
+ const removeDataset = jest.fn();
+ const {container: deleteOnly} = renderWithTheme(
+ <DatasetOpsMenu
+ datasetId="cities"
+ dataset={{type: 'local'}}
+ addGroupBy={jest.fn()}
+ addJoin={jest.fn()}
+ addSpatialJoin={jest.fn()}
+ showDeleteDataset
+ removeDataset={removeDataset}
+ />
+ );
+ expect(deleteOnly.querySelector('.dataset-ops-menu__toggle')).toBeNull();
+ expect(document.querySelector('.dataset-ops-menu__group-by')).toBeNull();
+ fireEvent.click(deleteOnly.querySelector('.dataset-ops-menu__remove') as HTMLElement);
+ expect(removeDataset).toHaveBeenCalledWith('cities');
+ });
+});
+
+describe('GroupByPanel field selection', () => {
+ test('fieldNameFromSelector reads string and field objects', () => {
+ expect(fieldNameFromSelector('region')).toBe('region');
+ expect(fieldNameFromSelector({name: 'pop'})).toBe('pop');
+ expect(fieldNameFromSelector(['city'])).toBe('city');
+ });
+
+ test('selecting a grouping field updates the op config', () => {
+ const GroupByPanel = GroupByPanelFactory(MockFieldSelector as any);
+ const setGroupByConfig = jest.fn();
+ const {getByLabelText} = renderWithTheme(
+ <GroupByPanel
+ op={{
+ id: 'op-1',
+ dataId: 'cities',
+ fieldName: null,
+ aggregations: {pop: 'sum'},
+ resultId: 'out',
+ resultLabel: 'cities grouped',
+ isConfigActive: true
+ }}
+ datasets={
+ {
+ cities: {
+ id: 'cities',
+ label: 'cities',
+ fields: [
+ {name: 'region', displayName: 'region', type: 'string'},
+ {name: 'pop', displayName: 'pop', type: 'integer'}
+ ] as Field[]
+ }
+ } as unknown as Datasets
+ }
+ setGroupByConfig={setGroupByConfig}
+ runGroupBy={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+
+ fireEvent.change(getByLabelText('group-by-field'), {target: {value: 'region'}});
+ expect(setGroupByConfig).toHaveBeenCalledWith(
+ 'op-1',
+ expect.objectContaining({fieldName: 'region'})
+ );
+ });
+
+ test('aggregation columns stay in the scrollable panel body', () => {
+ const GroupByPanel = GroupByPanelFactory(MockFieldSelector as any);
+ const fields = Array.from({length: 24}, (_, i) => ({
+ name: `col_${i}`,
+ displayName: `col_${i}`,
+ type: 'integer'
+ })) as Field[];
+ const {container} = renderWithTheme(
+ <GroupByPanel
+ op={{
+ id: 'op-1',
+ dataId: 'wide',
+ fieldName: 'col_0',
+ aggregations: {},
+ resultId: 'out',
+ resultLabel: 'wide grouped',
+ isConfigActive: true
+ }}
+ datasets={{wide: {id: 'wide', label: 'wide', fields}} as unknown as Datasets}
+ setGroupByConfig={jest.fn()}
+ runGroupBy={jest.fn()}
+ removeDatasetOp={jest.fn()}
+ />
+ );
+
+ fireEvent.click(container.querySelector('.dataset-ops-collapsible__header') as HTMLElement);
+
+ const list = container.querySelector('.dataset-ops-column-list') as HTMLElement;
+ const body = container.querySelector('.dataset-ops-panel__body') as HTMLElement;
+ expect(list).toBeTruthy();
+ expect(list.children.length).toBe(23);
+ expect(body).toBeTruthy();
+ expect(getComputedStyle(body).overflowY).toBe('auto');
+ });
+});
+
+describe('DatasetOpPanel help', () => {
+ test('shows a help control when titleHelpId is provided', () => {
+ const {container, getByLabelText} = renderWithTheme(
+ <DatasetOpPanel
+ titleId="datasetOps.spatialJoin"
+ titleHelpId="datasetOps.spatialJoinHelp"
+ onClose={jest.fn()}
+ onRun={jest.fn()}
+ canRun={false}
+ >
+ <div />
+ </DatasetOpPanel>
+ );
+
+ expect(getByLabelText('Help')).toBeTruthy();
+ expect(container.querySelector('.dataset-ops-panel__help')).toBeTruthy();
+ });
+
+ test('omits the help control when titleHelpId is not provided', () => {
+ const {queryByLabelText} = renderWithTheme(
+ <DatasetOpPanel titleId="datasetOps.groupBy" onClose={jest.fn()} onRun={jest.fn()} canRun>
+ <div />
+ </DatasetOpPanel>
+ );
+ expect(queryByLabelText('Help')).toBeNull();
+ });
+
+ test('shows description text instead of title help when descriptionId is provided', () => {
+ const {container, queryByLabelText} = renderWithTheme(
+ <DatasetOpPanel
+ titleId="datasetOps.spatialJoin"
+ descriptionId="datasetOps.spatialJoinHelp"
+ onClose={jest.fn()}
+ onRun={jest.fn()}
+ canRun={false}
+ >
+ <div />
+ </DatasetOpPanel>
+ );
+
+ expect(queryByLabelText('Help')).toBeNull();
+ expect(container.querySelector('.dataset-ops-panel__description')).toBeTruthy();
+ expect(container.querySelector('.data-ex-icons-spatial-join')).toBeNull();
+ });
+
+ test('shows join description text when descriptionId is provided', () => {
+ const {container, queryByLabelText} = renderWithTheme(
+ <DatasetOpPanel
+ titleId="datasetOps.join"
+ descriptionId="datasetOps.joinHelp"
+ onClose={jest.fn()}
+ onRun={jest.fn()}
+ canRun={false}
+ >
+ <div />
+ </DatasetOpPanel>
+ );
+
+ expect(queryByLabelText('Help')).toBeNull();
+ expect(container.querySelector('.dataset-ops-panel__description')).toBeTruthy();
+ });
+});
+
+describe('CollapsibleSection', () => {
+ test('hides content until the header is clicked', () => {
+ const {container, getByText} = renderWithTheme(
+ <CollapsibleSection titleId="datasetOps.columnsToInclude">
+ <div className="collapsed-body">columns</div>
+ </CollapsibleSection>
+ );
+
+ expect(container.querySelector('.collapsed-body')).toBeNull();
+ fireEvent.click(container.querySelector('.dataset-ops-collapsible__header') as HTMLElement);
+ expect(container.querySelector('.collapsed-body')).toBeTruthy();
+ expect(getByText('columns')).toBeTruthy();
+ });
+});
+
+describe('DatasetOpPanel layout', () => {
+ test('keeps the form in a scrollable body', () => {
+ const {container} = renderWithTheme(
+ <DatasetOpPanel titleId="datasetOps.spatialJoin" onClose={jest.fn()} onRun={jest.fn()} canRun>
+ <div className="form-content">form</div>
+ </DatasetOpPanel>
+ );
+
+ const body = container.querySelector('.dataset-ops-panel__body') as HTMLElement;
+ expect(body).toBeTruthy();
+ expect(body.querySelector('.form-content')).toBeTruthy();
+ expect(getComputedStyle(body).overflowY).toBe('auto');
+ });
+
+ test('shows a back button instead of a close icon', () => {
+ const onClose = jest.fn();
+ const {container, queryByLabelText} = renderWithTheme(
+ <DatasetOpPanel titleId="datasetOps.spatialJoin" onClose={onClose} onRun={jest.fn()} canRun>
+ <div />
+ </DatasetOpPanel>
+ );
+
+ expect(queryByLabelText('Close')).toBeNull();
+ const back = container.querySelector('.dataset-ops-panel__back') as HTMLButtonElement;
+ expect(back).toBeTruthy();
+ fireEvent.click(back);
+ expect(onClose).toHaveBeenCalled();
+ });
+});
diff --git a/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx
new file mode 100644
index 000000000..573931fac
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/dataset-ops-menu.tsx
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, useState} from 'react';
+import styled from 'styled-components';
+import {useIntl} from 'react-intl';
+import {FormattedMessage} from '@kepler.gl/localization';
+import {getApplicationConfig} from '@kepler.gl/utils';
+import {isTabularDatasetForOps} from '@kepler.gl/table';
+import {VisStateActions, ActionHandler, openDeleteModal} from '@kepler.gl/actions';
+
+import {BaseProps, Grouping, Join, Overflow, SpatialJoin, Trash} from '../../common/icons';
+import {Tooltip} from '../../common/styled-components';
+import Portaled from '../../common/portaled';
+
+const MenuToggle = styled.div`
+ margin-left: 8px;
+ width: 16px;
+ height: 16px;
+ flex-shrink: 0;
+ color: ${props => props.theme.panelHeaderIcon};
+ cursor: pointer;
+
+ &:hover {
+ color: ${props => props.theme.panelHeaderIconHover};
+ }
+`;
+
+const PortalAnchor = styled.div`
+ position: absolute;
+ top: 0;
+ right: 0;
+ width: 0;
+ height: 16px;
+ pointer-events: none;
+`;
+
+const Menu = styled.div`
+ min-width: 160px;
+ width: max-content;
+ background: ${props => props.theme.dropdownListBgd};
+ box-shadow: ${props => props.theme.tooltipBoxShadow};
+ border-radius: 4px;
+ overflow: hidden;
+`;
+
+const MenuItem = styled.button`
+ display: flex;
+ align-items: center;
+ width: 100%;
+ height: 32px;
+ padding: 0 8px;
+ border: 0;
+ background: transparent;
+ color: ${props => props.theme.textColor};
+ text-align: left;
+ cursor: pointer;
+ font-size: 12px;
+ line-height: 18px;
+ white-space: nowrap;
+
+ &:hover {
+ background: ${props => props.theme.dropdownListHighlightBg};
+ }
+`;
+
+const MenuItemIcon = styled.span`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 18px;
+ height: 18px;
+ margin-right: 6px;
+ flex-shrink: 0;
+ color: ${props => props.theme.subtextColor};
+`;
+
+const MenuSeparator = styled.div`
+ border-top: 1px solid ${props => props.theme.dropdownListHighlightBg};
+`;
+
+type MenuAction = {
+ className: string;
+ labelId: string;
+ Icon: React.ComponentType<Partial<BaseProps>>;
+ iconHeight: string;
+ onClick: () => void;
+};
+
+export type DatasetOpsMenuProps = {
+ datasetId: string;
+ dataset: {type?: string; disableDataOperation?: boolean};
+ addGroupBy?: ActionHandler<typeof VisStateActions.addGroupBy>;
+ addJoin?: ActionHandler<typeof VisStateActions.addJoin>;
+ addSpatialJoin?: ActionHandler<typeof VisStateActions.addSpatialJoin>;
+ showDeleteDataset?: boolean;
+ removeDataset?: ActionHandler<typeof openDeleteModal>;
+};
+
+export function DatasetOpsMenu({
+ datasetId,
+ dataset,
+ addGroupBy,
+ addJoin,
+ addSpatialJoin,
+ showDeleteDataset,
+ removeDataset
+}: DatasetOpsMenuProps) {
+ const intl = useIntl();
+ const [open, setOpen] = useState(false);
+ const opsEnabled = getApplicationConfig().enableDatasetOps !== false;
+ const showOps =
+ opsEnabled &&
+ isTabularDatasetForOps(dataset) &&
+ Boolean(addGroupBy || addJoin || addSpatialJoin);
+ const showRemove = Boolean(showDeleteDataset && removeDataset);
+ const tooltipId = `dataset-ops-${datasetId}`;
+ const tooltipLabel = intl.formatMessage({id: 'datasetTitle.moreSettings'});
+
+ const onSelect = useCallback(
+ (fn?: (id: string) => void) => {
+ fn?.(datasetId);
+ setOpen(false);
+ },
+ [datasetId]
+ );
+
+ if (!showOps && !showRemove) {
+ return null;
+ }
+
+ if (!opsEnabled && showRemove) {
+ const removeTooltipId = `remove-dataset-${datasetId}`;
+ const removeLabel = intl.formatMessage({id: 'datasetTitle.removeDataset'});
+ return (
+ <MenuToggle
+ className="dataset-action dataset-ops-menu__remove"
+ data-tip
+ data-for={removeTooltipId}
+ role="button"
+ aria-label={removeLabel}
+ onClick={e => {
+ e.stopPropagation();
+ removeDataset?.(datasetId);
+ }}
+ >
+ <Trash height="16px" />
+ <Tooltip id={removeTooltipId} effect="solid">
+ <span>
+ <FormattedMessage id="datasetTitle.removeDataset" />
+ </span>
+ </Tooltip>
+ </MenuToggle>
+ );
+ }
+
+ const opItems: MenuAction[] = [];
+ if (showOps && addGroupBy) {
+ opItems.push({
+ className: 'dataset-ops-menu__group-by',
+ labelId: 'datasetOps.groupBy',
+ Icon: Grouping,
+ iconHeight: '18px',
+ onClick: () => onSelect(addGroupBy)
+ });
+ }
+ if (showOps && addJoin) {
+ opItems.push({
+ className: 'dataset-ops-menu__join',
+ labelId: 'datasetOps.join',
+ Icon: Join,
+ iconHeight: '14px',
+ onClick: () => onSelect(() => addJoin(datasetId))
+ });
+ }
+ if (showOps && addSpatialJoin) {
+ opItems.push({
+ className: 'dataset-ops-menu__spatial-join',
+ labelId: 'datasetOps.spatialJoin',
+ Icon: SpatialJoin,
+ iconHeight: '14px',
+ onClick: () => onSelect(addSpatialJoin)
+ });
+ }
+
+ return (
+ <>
+ <MenuToggle
+ className="dataset-action dataset-ops-menu dataset-ops-menu__toggle"
+ data-tip
+ data-for={tooltipId}
+ role="button"
+ aria-label={tooltipLabel}
+ onClick={e => {
+ e.stopPropagation();
+ setOpen(value => !value);
+ }}
+ >
+ <Overflow height="16px" />
+ <Tooltip id={tooltipId} effect="solid">
+ <span>
+ <FormattedMessage id="datasetTitle.moreSettings" />
+ </span>
+ </Tooltip>
+ </MenuToggle>
+ <Portaled
+ component={PortalAnchor}
+ isOpened={open}
+ left={0}
+ top={0}
+ onClose={() => setOpen(false)}
+ >
+ <Menu>
+ {opItems.map(item => (
+ <MenuItem
+ key={item.className}
+ className={item.className}
+ type="button"
+ onClick={item.onClick}
+ >
+ <MenuItemIcon>
+ <item.Icon height={item.iconHeight} />
+ </MenuItemIcon>
+ <FormattedMessage id={item.labelId} />
+ </MenuItem>
+ ))}
+ {opItems.length > 0 && showRemove ? <MenuSeparator /> : null}
+ {showRemove ? (
+ <MenuItem
+ className="dataset-ops-menu__remove"
+ type="button"
+ onClick={() => onSelect(removeDataset)}
+ >
+ <MenuItemIcon>
+ <Trash height="16px" />
+ </MenuItemIcon>
+ <FormattedMessage id="datasetTitle.removeDataset" />
+ </MenuItem>
+ ) : null}
+ </Menu>
+ </Portaled>
+ </>
+ );
+}
+
+export default DatasetOpsMenu;
diff --git a/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx b/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx
new file mode 100644
index 000000000..8844a69d2
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/dataset-ops-panels.tsx
@@ -0,0 +1,96 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import styled from 'styled-components';
+import {GroupByOp, JoinOp} from '@kepler.gl/table';
+import {Datasets} from '@kepler.gl/table';
+import {VisStateActions} from '@kepler.gl/actions';
+import {getApplicationConfig} from '@kepler.gl/utils';
+
+import GroupByPanelFactory from './group-by-panel';
+import JoinPanelFactory from './join-panel';
+import SpatialJoinPanelFactory from './spatial-join-panel';
+
+const Panels = styled.div.attrs({
+ className: 'dataset-ops-panels'
+})`
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+ height: 100%;
+`;
+
+DatasetOpsPanelsFactory.deps = [GroupByPanelFactory, JoinPanelFactory, SpatialJoinPanelFactory];
+
+export type DatasetOpsPanelsProps = {
+ datasets: Datasets;
+ groupBys?: GroupByOp[];
+ joins?: JoinOp[];
+ visStateActions: typeof VisStateActions;
+};
+
+export function hasActiveDatasetOp(groupBys: GroupByOp[] = [], joins: JoinOp[] = []): boolean {
+ return Boolean(groupBys.some(op => op.isConfigActive) || joins.some(op => op.isConfigActive));
+}
+
+function DatasetOpsPanelsFactory(
+ GroupByPanel: ReturnType<typeof GroupByPanelFactory>,
+ JoinPanel: ReturnType<typeof JoinPanelFactory>,
+ SpatialJoinPanel: ReturnType<typeof SpatialJoinPanelFactory>
+) {
+ const DatasetOpsPanels: React.FC<DatasetOpsPanelsProps> = ({
+ datasets,
+ groupBys = [],
+ joins = [],
+ visStateActions
+ }) => {
+ if (getApplicationConfig().enableDatasetOps === false) {
+ return null;
+ }
+
+ const activeGroupBy = groupBys.find(op => op.isConfigActive);
+ const activeJoin = joins.find(op => op.isConfigActive && op.implementation !== 'spatial');
+ const activeSpatial = joins.find(op => op.isConfigActive && op.implementation === 'spatial');
+ if (!activeGroupBy && !activeJoin && !activeSpatial) {
+ return null;
+ }
+
+ return (
+ <Panels>
+ {activeGroupBy ? (
+ <GroupByPanel
+ op={activeGroupBy}
+ datasets={datasets}
+ setGroupByConfig={visStateActions.setGroupByConfig}
+ runGroupBy={visStateActions.runGroupBy}
+ removeDatasetOp={visStateActions.removeDatasetOp}
+ />
+ ) : null}
+ {activeJoin ? (
+ <JoinPanel
+ op={activeJoin}
+ datasets={datasets}
+ setJoinConfig={visStateActions.setJoinConfig}
+ runJoin={visStateActions.runJoin}
+ removeDatasetOp={visStateActions.removeDatasetOp}
+ />
+ ) : null}
+ {activeSpatial ? (
+ <SpatialJoinPanel
+ op={activeSpatial}
+ datasets={datasets}
+ setSpatialJoinConfig={visStateActions.setSpatialJoinConfig}
+ runSpatialJoin={visStateActions.runSpatialJoin}
+ removeDatasetOp={visStateActions.removeDatasetOp}
+ />
+ ) : null}
+ </Panels>
+ );
+ };
+
+ return DatasetOpsPanels;
+}
+
+export default DatasetOpsPanelsFactory;
diff --git a/src/components/src/side-panel/dataset-ops/group-by-panel.tsx b/src/components/src/side-panel/dataset-ops/group-by-panel.tsx
new file mode 100644
index 000000000..23565cdd3
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/group-by-panel.tsx
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import {FormattedMessage} from '@kepler.gl/localization';
+import {
+ DatasetOpAggregation,
+ GroupByOp,
+ aggregationOptionsForField,
+ defaultAggregationForField,
+ defaultAggregationsForFields,
+ isDatasetOpsAggregationField
+} from '@kepler.gl/table';
+import {Datasets} from '@kepler.gl/table';
+import {VisStateActions, ActionHandler} from '@kepler.gl/actions';
+
+import FieldSelectorFactory from '../../common/field-selector';
+import ItemSelector from '../../common/item-selector/item-selector';
+import {PanelLabel, SidePanelSection} from '../../common/styled-components';
+import {Grouping} from '../../common/icons';
+import DatasetOpPanel, {
+ AggregationSelector,
+ CollapsibleSection,
+ DatasetOpHelp,
+ DatasetOpsAggRow,
+ DatasetOpsFieldName,
+ DatasetOpsFieldRow,
+ DatasetOpsSection,
+ ResultNameInput,
+ ScrollableColumnList,
+ fieldNameFromSelector
+} from './dataset-op-panel';
+
+GroupByPanelFactory.deps = [FieldSelectorFactory];
+
+function GroupByPanelFactory(FieldSelector: ReturnType<typeof FieldSelectorFactory>) {
+ const GroupByPanel: React.FC<{
+ op: GroupByOp;
+ datasets: Datasets;
+ setGroupByConfig: ActionHandler<typeof VisStateActions.setGroupByConfig>;
+ runGroupBy: ActionHandler<typeof VisStateActions.runGroupBy>;
+ removeDatasetOp: ActionHandler<typeof VisStateActions.removeDatasetOp>;
+ }> = ({op, datasets, setGroupByConfig, runGroupBy, removeDatasetOp}) => {
+ const dataset = datasets[op.dataId];
+ if (!dataset) {
+ return null;
+ }
+
+ const aggregationFields = dataset.fields.filter(
+ field => field.name !== op.fieldName && isDatasetOpsAggregationField(field)
+ );
+ const allAggregationsSelected = Boolean(
+ aggregationFields.length && aggregationFields.every(field => op.aggregations[field.name])
+ );
+
+ const onSelectField = (value: unknown) => {
+ const fieldName = fieldNameFromSelector(value);
+ const aggregations = {...op.aggregations};
+ if (fieldName) {
+ delete aggregations[fieldName];
+ }
+ setGroupByConfig(op.id, {fieldName, aggregations});
+ };
+
+ const onToggleAgg = (fieldName: string, enabled: boolean, technique: DatasetOpAggregation) => {
+ const aggregations = {...op.aggregations};
+ if (enabled) {
+ aggregations[fieldName] = technique;
+ } else {
+ delete aggregations[fieldName];
+ }
+ setGroupByConfig(op.id, {aggregations});
+ };
+
+ return (
+ <DatasetOpPanel
+ titleId="datasetOps.groupBy"
+ titleIcon={<Grouping height="20px" />}
+ descriptionId="datasetOps.groupByHelp"
+ error={op.error}
+ onClose={() => removeDatasetOp(op.id)}
+ onRun={() => runGroupBy(op.id)}
+ canRun={Boolean(op.fieldName)}
+ >
+ <DatasetOpsSection sectionColor={dataset.color}>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.groupByField" />
+ </PanelLabel>
+ <DatasetOpsFieldRow>
+ <FieldSelector
+ fields={dataset.fields}
+ value={op.fieldName}
+ onSelect={onSelectField}
+ erasable={false}
+ />
+ <DatasetOpHelp helpId="datasetOps.groupByFieldHelp" />
+ </DatasetOpsFieldRow>
+ </SidePanelSection>
+ <CollapsibleSection
+ titleId="datasetOps.aggregationRules"
+ helpId="datasetOps.aggregationRulesHelp"
+ selectAll={allAggregationsSelected}
+ onToggleSelectAll={() =>
+ setGroupByConfig(op.id, {
+ aggregations: allAggregationsSelected
+ ? {}
+ : defaultAggregationsForFields(dataset.fields, op.fieldName ? [op.fieldName] : [])
+ })
+ }
+ >
+ <ScrollableColumnList>
+ {aggregationFields.map(field => {
+ const options = aggregationOptionsForField(field);
+ const selected = op.aggregations[field.name];
+ const selectedOption =
+ options.find(option => option.id === selected) ||
+ options.find(option => option.id === defaultAggregationForField(field)) ||
+ options[0] ||
+ null;
+ return (
+ <DatasetOpsAggRow key={field.name}>
+ <input
+ type="checkbox"
+ checked={Boolean(selected)}
+ onChange={e =>
+ onToggleAgg(
+ field.name,
+ e.target.checked,
+ selected || defaultAggregationForField(field)
+ )
+ }
+ />
+ <DatasetOpsFieldName>{field.displayName || field.name}</DatasetOpsFieldName>
+ <AggregationSelector>
+ <ItemSelector
+ options={options}
+ selectedItems={selectedOption}
+ displayOption={option => option.id}
+ getOptionValue={option => option.id}
+ onChange={value =>
+ onToggleAgg(field.name, true, String(value) as DatasetOpAggregation)
+ }
+ disabled={!selected}
+ searchable={false}
+ multiSelect={false}
+ size="small"
+ />
+ </AggregationSelector>
+ </DatasetOpsAggRow>
+ );
+ })}
+ </ScrollableColumnList>
+ </CollapsibleSection>
+ </DatasetOpsSection>
+ <ResultNameInput
+ value={op.resultLabel}
+ onChange={resultLabel => setGroupByConfig(op.id, {resultLabel})}
+ />
+ </DatasetOpPanel>
+ );
+ };
+
+ return GroupByPanel;
+}
+
+export default GroupByPanelFactory;
diff --git a/src/components/src/side-panel/dataset-ops/join-panel.tsx b/src/components/src/side-panel/dataset-ops/join-panel.tsx
new file mode 100644
index 000000000..f4edd5175
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/join-panel.tsx
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import styled from 'styled-components';
+import {FormattedMessage} from '@kepler.gl/localization';
+import {AttributeJoinType, JoinOp, isTabularDatasetForOps} from '@kepler.gl/table';
+import {Datasets} from '@kepler.gl/table';
+import {VisStateActions, ActionHandler} from '@kepler.gl/actions';
+import {Field} from '@kepler.gl/types';
+
+import FieldSelectorFactory from '../../common/field-selector';
+import SourceDataSelectorFactory from '../common/source-data-selector';
+import {PanelLabel, SidePanelSection, Tooltip} from '../../common/styled-components';
+import {Join} from '../../common/icons';
+import DatasetOpPanel, {
+ CollapsibleSection,
+ DATASET_OPS_ACCENT,
+ DatasetOpHelp,
+ DatasetOpsAggRow,
+ DatasetOpsFieldName,
+ DatasetOpsFieldRow,
+ DatasetOpsSection,
+ DatasetOpsSectionTitle,
+ ResultNameInput,
+ ScrollableColumnList,
+ fieldNameFromSelector
+} from './dataset-op-panel';
+import {JOIN_TYPE_ICONS} from './join-type-icons';
+
+const JOIN_TYPES: {id: AttributeJoinType; helpId: string}[] = [
+ {id: 'LEFT', helpId: 'datasetOps.joinType.leftHelp'},
+ {id: 'INNER', helpId: 'datasetOps.joinType.innerHelp'},
+ {id: 'FULL', helpId: 'datasetOps.joinType.fullHelp'}
+];
+
+const JoinTypeRow = styled.div`
+ display: flex;
+ align-items: center;
+
+ ${DatasetOpsSectionTitle} {
+ margin-bottom: 0;
+ }
+`;
+
+const JoinTypeTiles = styled.div`
+ flex: 1;
+ display: flex;
+ justify-content: flex-end;
+`;
+
+const JoinTypeTile = styled.button.attrs({
+ type: 'button',
+ className: 'dataset-ops-join-type-tile'
+})<{$selected?: boolean}>`
+ width: 40px;
+ height: 28px;
+ padding: 0;
+ margin-left: 8px;
+ border-radius: 4px;
+ border: 1px solid ${props => (props.$selected ? props.theme.activeColor : 'transparent')};
+ background: transparent;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ color: ${props => props.theme.textColor};
+
+ .join-type-tooltip {
+ max-width: 180px;
+ text-align: left;
+ white-space: normal;
+ }
+`;
+
+function selectedColumnNames(fields: Field[], selected?: string[]): string[] {
+ return selected ?? fields.map(field => field.name);
+}
+
+function ColumnsToInclude({
+ fields,
+ selected,
+ onChange
+}: {
+ fields: Field[];
+ selected?: string[];
+ onChange: (columns: string[]) => void;
+}) {
+ const selectedNames = new Set(selectedColumnNames(fields, selected));
+ const allSelected = fields.every(field => selectedNames.has(field.name));
+ return (
+ <CollapsibleSection
+ titleId="datasetOps.columnsToInclude"
+ helpId="datasetOps.columnsToIncludeHelp"
+ selectAll={allSelected}
+ onToggleSelectAll={() => onChange(allSelected ? [] : fields.map(field => field.name))}
+ >
+ <ScrollableColumnList>
+ {fields.map(field => {
+ const checked = selectedNames.has(field.name);
+ return (
+ <DatasetOpsAggRow key={field.name}>
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={() =>
+ onChange(
+ fields
+ .map(item => item.name)
+ .filter(name => (name === field.name ? !checked : selectedNames.has(name)))
+ )
+ }
+ />
+ <DatasetOpsFieldName>{field.displayName || field.name}</DatasetOpsFieldName>
+ </DatasetOpsAggRow>
+ );
+ })}
+ </ScrollableColumnList>
+ </CollapsibleSection>
+ );
+}
+
+JoinPanelFactory.deps = [FieldSelectorFactory, SourceDataSelectorFactory];
+
+function JoinPanelFactory(
+ FieldSelector: ReturnType<typeof FieldSelectorFactory>,
+ SourceDataSelector: ReturnType<typeof SourceDataSelectorFactory>
+) {
+ const JoinPanel: React.FC<{
+ op: JoinOp;
+ datasets: Datasets;
+ setJoinConfig: ActionHandler<typeof VisStateActions.setJoinConfig>;
+ runJoin: ActionHandler<typeof VisStateActions.runJoin>;
+ removeDatasetOp: ActionHandler<typeof VisStateActions.removeDatasetOp>;
+ }> = ({op, datasets, setJoinConfig, runJoin, removeDatasetOp}) => {
+ const left = datasets[op.leftDataId];
+ const right = op.rightDataId ? datasets[op.rightDataId] : undefined;
+ const tabularDatasets = Object.fromEntries(
+ Object.entries(datasets).filter(([, dataset]) => isTabularDatasetForOps(dataset))
+ );
+ const leftDatasets = Object.fromEntries(
+ Object.entries(tabularDatasets).filter(([id]) => id !== op.rightDataId)
+ );
+ const rightDatasets = Object.fromEntries(
+ Object.entries(tabularDatasets).filter(([id]) => id !== op.leftDataId)
+ );
+
+ if (!left) {
+ return null;
+ }
+
+ const onSelectLeftDataset = (value: unknown) => {
+ const dataId = typeof value === 'string' ? value : null;
+ if (!dataId || dataId === op.leftDataId) {
+ return;
+ }
+ const nextLeft = datasets[dataId];
+ if (!nextLeft) {
+ return;
+ }
+ setJoinConfig(op.id, {
+ leftDataId: dataId,
+ leftField: null,
+ leftColumns: undefined
+ });
+ };
+
+ return (
+ <DatasetOpPanel
+ titleId="datasetOps.join"
+ titleIcon={<Join height="20px" />}
+ descriptionId="datasetOps.joinHelp"
+ error={op.error}
+ onClose={() => removeDatasetOp(op.id)}
+ onRun={() => runJoin(op.id)}
+ canRun={Boolean(op.rightDataId && op.leftField && op.rightField)}
+ >
+ <DatasetOpsSection sectionColor={left.color}>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.leftDataset" />
+ <DatasetOpHelp helpId="datasetOps.leftDatasetHelp" />
+ </DatasetOpsSectionTitle>
+ <SourceDataSelector
+ datasets={leftDatasets}
+ dataId={op.leftDataId}
+ onSelect={onSelectLeftDataset}
+ defaultValue="Select a dataset"
+ />
+ {right ? (
+ <>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.leftKey" />
+ </PanelLabel>
+ <DatasetOpsFieldRow>
+ <FieldSelector
+ fields={left.fields}
+ value={op.leftField}
+ onSelect={value =>
+ setJoinConfig(op.id, {leftField: fieldNameFromSelector(value)})
+ }
+ erasable={false}
+ />
+ <DatasetOpHelp helpId="datasetOps.leftFieldHelp" />
+ </DatasetOpsFieldRow>
+ </SidePanelSection>
+ <ColumnsToInclude
+ fields={left.fields}
+ selected={op.leftColumns}
+ onChange={leftColumns => setJoinConfig(op.id, {leftColumns})}
+ />
+ </>
+ ) : null}
+ </DatasetOpsSection>
+
+ <DatasetOpsSection sectionColor={DATASET_OPS_ACCENT}>
+ <JoinTypeRow>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.joinTypeLabel" />
+ </DatasetOpsSectionTitle>
+ <JoinTypeTiles>
+ {JOIN_TYPES.map(option => {
+ const Icon = JOIN_TYPE_ICONS[option.id];
+ const tooltipId = `dataset-ops-join-type-${op.id}-${option.id}`;
+ return (
+ <JoinTypeTile
+ key={option.id}
+ $selected={op.type === option.id}
+ data-tip
+ data-for={tooltipId}
+ aria-label={option.id}
+ onClick={() => setJoinConfig(op.id, {type: option.id})}
+ >
+ <Icon height="20px" />
+ <Tooltip id={tooltipId} effect="solid">
+ <div className="join-type-tooltip">
+ <FormattedMessage id={option.helpId} />
+ </div>
+ </Tooltip>
+ </JoinTypeTile>
+ );
+ })}
+ </JoinTypeTiles>
+ </JoinTypeRow>
+ </DatasetOpsSection>
+
+ <DatasetOpsSection sectionColor={right?.color}>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.rightDataset" />
+ <DatasetOpHelp helpId="datasetOps.rightDatasetHelp" />
+ </DatasetOpsSectionTitle>
+ <SourceDataSelector
+ datasets={rightDatasets}
+ dataId={op.rightDataId}
+ onSelect={value => {
+ const dataId = typeof value === 'string' ? value : null;
+ if (!dataId || !datasets[dataId]) {
+ return;
+ }
+ setJoinConfig(op.id, {
+ rightDataId: dataId,
+ rightField: null,
+ rightColumns: undefined
+ });
+ }}
+ defaultValue="Select a dataset"
+ />
+ {right ? (
+ <>
+ <SidePanelSection>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.rightKey" />
+ </PanelLabel>
+ <DatasetOpsFieldRow>
+ <FieldSelector
+ fields={right.fields}
+ value={op.rightField}
+ onSelect={value =>
+ setJoinConfig(op.id, {rightField: fieldNameFromSelector(value)})
+ }
+ erasable={false}
+ />
+ <DatasetOpHelp helpId="datasetOps.rightFieldHelp" />
+ </DatasetOpsFieldRow>
+ </SidePanelSection>
+ <ColumnsToInclude
+ fields={right.fields}
+ selected={op.rightColumns}
+ onChange={rightColumns => setJoinConfig(op.id, {rightColumns})}
+ />
+ </>
+ ) : null}
+ </DatasetOpsSection>
+
+ <ResultNameInput
+ value={op.resultLabel}
+ onChange={resultLabel => setJoinConfig(op.id, {resultLabel})}
+ />
+ </DatasetOpPanel>
+ );
+ };
+
+ return JoinPanel;
+}
+
+export default JoinPanelFactory;
diff --git a/src/components/src/side-panel/dataset-ops/join-type-icons.tsx b/src/components/src/side-panel/dataset-ops/join-type-icons.tsx
new file mode 100644
index 000000000..7e3b60e9a
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/join-type-icons.tsx
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {ComponentType} from 'react';
+import {AttributeJoinType} from '@kepler.gl/table';
+
+import Base, {BaseProps} from '../../common/icons/base';
+
+const SECONDARY = '#F7F8FA';
+const ACCENT = '#5558DB';
+
+function JoinTypeIcon({
+ className,
+ children,
+ ...props
+}: Partial<BaseProps> & {className: string; children: React.ReactNode}) {
+ return (
+ <Base viewBox="0 0 20 12" height="20px" predefinedClassName={className} {...props}>
+ {children}
+ </Base>
+ );
+}
+
+export const JoinLeftIcon: ComponentType<Partial<BaseProps>> = props => (
+ <JoinTypeIcon className="data-ex-icons-join-left" {...props}>
+ <circle cx="14" cy="6.125" r="6" fill={SECONDARY} />
+ <circle opacity="0.6" cx="6" cy="6.125" r="6" fill={ACCENT} />
+ </JoinTypeIcon>
+);
+
+export const JoinInnerIcon: ComponentType<Partial<BaseProps>> = props => (
+ <JoinTypeIcon className="data-ex-icons-join-inner" {...props}>
+ <circle cx="14" cy="6.125" r="6" fill={SECONDARY} />
+ <circle cx="6" cy="6.125" r="6" fill={SECONDARY} />
+ <path
+ opacity="0.8"
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M10 10.5972C11.2275 9.49857 12 7.902 12 6.125C12 4.348 11.2275 2.75143 10 1.65279C8.7725 2.75143 8 4.348 8 6.125C8 7.902 8.7725 9.49857 10 10.5972Z"
+ fill={ACCENT}
+ />
+ </JoinTypeIcon>
+);
+
+export const JoinFullIcon: ComponentType<Partial<BaseProps>> = props => (
+ <JoinTypeIcon className="data-ex-icons-join-full" {...props}>
+ <circle opacity="0.8" cx="14" cy="6.125" r="6" fill={ACCENT} />
+ <circle opacity="0.8" cx="6" cy="6.125" r="6" fill={ACCENT} />
+ </JoinTypeIcon>
+);
+
+export const JOIN_TYPE_ICONS: Record<AttributeJoinType, ComponentType<Partial<BaseProps>>> = {
+ LEFT: JoinLeftIcon,
+ INNER: JoinInnerIcon,
+ FULL: JoinFullIcon
+};
diff --git a/src/components/src/side-panel/dataset-ops/spatial-join-panel.tsx b/src/components/src/side-panel/dataset-ops/spatial-join-panel.tsx
new file mode 100644
index 000000000..4e79188e1
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/spatial-join-panel.tsx
@@ -0,0 +1,429 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useMemo} from 'react';
+import styled from 'styled-components';
+import {useIntl} from 'react-intl';
+import {FormattedMessage} from '@kepler.gl/localization';
+import {
+ DatasetOpAggregation,
+ JoinOp,
+ SPATIAL_JOIN_PREDICATE_OPTIONS,
+ SpatialGeoSource,
+ SpatialJoinPredicate,
+ aggregationOptionsForField,
+ defaultAggregationForField,
+ defaultAggregationsForFields,
+ fieldNamesForGeoSource,
+ isDatasetOpsAggregationField,
+ isTabularDatasetForOps,
+ suggestSpatialGeo
+} from '@kepler.gl/table';
+import {Datasets} from '@kepler.gl/table';
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {VisStateActions, ActionHandler} from '@kepler.gl/actions';
+import {Field} from '@kepler.gl/types';
+
+import SourceDataSelectorFactory from '../common/source-data-selector';
+import ItemSelector from '../../common/item-selector/item-selector';
+import {PanelLabel, SidePanelSection} from '../../common/styled-components';
+import LayerTypeDropdownListFactory from '../layer-panel/layer-type-dropdown-list';
+import LayerTypeListItemFactory, {
+ LayerTypeListItemProps
+} from '../layer-panel/layer-type-list-item';
+import {SpatialJoin} from '../../common/icons';
+import DatasetOpPanel, {
+ AggregationSelector,
+ CollapsibleSection,
+ DATASET_OPS_ACCENT,
+ DatasetOpHelp,
+ DatasetOpsAggRow,
+ DatasetOpsFieldName,
+ DatasetOpsSection,
+ DatasetOpsSectionTitle,
+ ResultNameInput,
+ ScrollableColumnList
+} from './dataset-op-panel';
+import {SPATIAL_JOIN_PREDICATE_ICONS} from './spatial-join-predicate-icons';
+
+const GeometryHeader = styled.div`
+ margin-bottom: 4px;
+`;
+
+const PredicateValue = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ > :first-child {
+ flex: 1;
+ min-width: 0;
+ }
+ .item-selector .item-selector__dropdown {
+ padding: 4px 10px;
+ }
+ .item-selector__dropdown__value .layer-type-selector__item__label {
+ max-width: none;
+ text-align: left;
+ }
+`;
+
+const PredicateListItemWrap = styled.div`
+ .layer-type-selector__item__icon {
+ width: 56px;
+ height: 56px;
+ align-items: center;
+ justify-content: center;
+ }
+`;
+
+const JOIN_OPERATION_COLOR = DATASET_OPS_ACCENT;
+
+type GeoOption = {id: string; label: string; geo: SpatialGeoSource};
+
+function geoOptionsForFields(fields: Field[]): GeoOption[] {
+ const options: GeoOption[] = [];
+ fields.forEach(field => {
+ if (field.type === ALL_FIELD_TYPES.geojson || field.type === ALL_FIELD_TYPES.point) {
+ options.push({
+ id: `geojson:${field.name}`,
+ label: field.displayName || field.name,
+ geo: {kind: 'geojson', fieldName: field.name}
+ });
+ }
+ if (field.type === ALL_FIELD_TYPES.h3) {
+ options.push({
+ id: `h3:${field.name}`,
+ label: field.displayName || field.name,
+ geo: {kind: 'h3', fieldName: field.name}
+ });
+ }
+ });
+ const suggested = suggestSpatialGeo(fields);
+ if (suggested?.kind === 'latlng') {
+ options.push({
+ id: `latlng:${suggested.latField}:${suggested.lngField}`,
+ label: `${suggested.latField}, ${suggested.lngField}`,
+ geo: suggested
+ });
+ }
+ return options;
+}
+
+function optionIdForGeo(geo?: SpatialGeoSource | null): string | null {
+ if (!geo) {
+ return null;
+ }
+ if (geo.kind === 'latlng') {
+ return `latlng:${geo.latField}:${geo.lngField}`;
+ }
+ return `${geo.kind}:${geo.fieldName}`;
+}
+
+function includeableFields(fields: Field[], geo?: SpatialGeoSource | null): Field[] {
+ const skip = new Set(geo ? fieldNamesForGeoSource(geo) : []);
+ return fields.filter(field => !skip.has(field.name));
+}
+
+SpatialJoinPanelFactory.deps = [
+ SourceDataSelectorFactory,
+ LayerTypeListItemFactory,
+ LayerTypeDropdownListFactory
+];
+
+function SpatialJoinPanelFactory(
+ SourceDataSelector: ReturnType<typeof SourceDataSelectorFactory>,
+ LayerTypeListItem: ReturnType<typeof LayerTypeListItemFactory>,
+ LayerTypeDropdownList: ReturnType<typeof LayerTypeDropdownListFactory>
+) {
+ const PredicateListItem = (props: LayerTypeListItemProps) => (
+ <PredicateListItemWrap>
+ <LayerTypeListItem {...props} />
+ </PredicateListItemWrap>
+ );
+ const SpatialJoinPanel: React.FC<{
+ op: JoinOp;
+ datasets: Datasets;
+ setSpatialJoinConfig: ActionHandler<typeof VisStateActions.setSpatialJoinConfig>;
+ runSpatialJoin: ActionHandler<typeof VisStateActions.runSpatialJoin>;
+ removeDatasetOp: ActionHandler<typeof VisStateActions.removeDatasetOp>;
+ }> = ({op, datasets, setSpatialJoinConfig, runSpatialJoin, removeDatasetOp}) => {
+ const intl = useIntl();
+ const left = datasets[op.leftDataId];
+ const right = op.rightDataId ? datasets[op.rightDataId] : undefined;
+ const tabularDatasets = Object.fromEntries(
+ Object.entries(datasets).filter(([, dataset]) => isTabularDatasetForOps(dataset))
+ );
+ const targetDatasets = Object.fromEntries(
+ Object.entries(tabularDatasets).filter(([id]) => id !== op.rightDataId)
+ );
+ const joinDatasets = Object.fromEntries(
+ Object.entries(tabularDatasets).filter(([id]) => id !== op.leftDataId)
+ );
+ const predicate = op.predicate || 'intersects';
+ const predicateOptions = useMemo(
+ () =>
+ SPATIAL_JOIN_PREDICATE_OPTIONS.map(option => ({
+ id: option.id,
+ label: intl.formatMessage({id: option.labelId}),
+ icon: SPATIAL_JOIN_PREDICATE_ICONS[option.id]
+ })),
+ [intl]
+ );
+ if (!left) {
+ return null;
+ }
+
+ const leftOptions = geoOptionsForFields(left.fields);
+ const rightOptions = right ? geoOptionsForFields(right.fields) : [];
+ const selectedPredicate =
+ predicateOptions.find(option => option.id === predicate) || predicateOptions[0];
+ const leftIncludeFields = includeableFields(left.fields, op.leftGeo);
+ const selectedLeftColumns = new Set(
+ op.leftColumns ?? leftIncludeFields.map(field => field.name)
+ );
+ const allLeftSelected = leftIncludeFields.every(field => selectedLeftColumns.has(field.name));
+ const aggregationFields = right ? right.fields.filter(isDatasetOpsAggregationField) : [];
+ const allAggregationsSelected = Boolean(
+ aggregationFields.length && aggregationFields.every(field => op.aggregations[field.name])
+ );
+
+ const onSelectTargetDataset = (value: unknown) => {
+ const dataId = typeof value === 'string' ? value : null;
+ if (!dataId || dataId === op.leftDataId) {
+ return;
+ }
+ const nextLeft = datasets[dataId];
+ if (!nextLeft) {
+ return;
+ }
+ setSpatialJoinConfig(op.id, {
+ leftDataId: dataId,
+ leftGeo: suggestSpatialGeo(nextLeft.fields),
+ leftColumns: undefined
+ });
+ };
+
+ return (
+ <DatasetOpPanel
+ titleId="datasetOps.spatialJoin"
+ titleIcon={<SpatialJoin height="20px" />}
+ descriptionId="datasetOps.spatialJoinHelp"
+ error={op.error}
+ onClose={() => removeDatasetOp(op.id)}
+ onRun={() => runSpatialJoin(op.id)}
+ canRun={Boolean(op.rightDataId && op.leftGeo && op.rightGeo)}
+ >
+ <DatasetOpsSection sectionColor={left.color}>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.targetDataset" />
+ <DatasetOpHelp helpId="datasetOps.targetDatasetHelp" />
+ </DatasetOpsSectionTitle>
+ <SourceDataSelector
+ datasets={targetDatasets}
+ dataId={op.leftDataId}
+ onSelect={onSelectTargetDataset}
+ defaultValue="Select a dataset"
+ />
+ <SidePanelSection>
+ <GeometryHeader>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.geometryColumn" />
+ </PanelLabel>
+ </GeometryHeader>
+ <ItemSelector
+ options={leftOptions}
+ selectedItems={
+ leftOptions.find(option => option.id === optionIdForGeo(op.leftGeo)) || null
+ }
+ displayOption={option => option.label}
+ getOptionValue={option => option.id}
+ onChange={value => {
+ const option = leftOptions.find(item => item.id === value);
+ setSpatialJoinConfig(op.id, {leftGeo: option?.geo || null});
+ }}
+ searchable={false}
+ multiSelect={false}
+ />
+ </SidePanelSection>
+ <CollapsibleSection
+ titleId="datasetOps.columnsToInclude"
+ helpId="datasetOps.columnsToIncludeHelp"
+ selectAll={allLeftSelected}
+ onToggleSelectAll={() =>
+ setSpatialJoinConfig(op.id, {
+ leftColumns: allLeftSelected ? [] : leftIncludeFields.map(field => field.name)
+ })
+ }
+ >
+ <ScrollableColumnList>
+ {leftIncludeFields.map(field => {
+ const checked = selectedLeftColumns.has(field.name);
+ return (
+ <DatasetOpsAggRow key={field.name}>
+ <input
+ type="checkbox"
+ checked={checked}
+ onChange={() => {
+ const next = leftIncludeFields
+ .map(item => item.name)
+ .filter(name =>
+ name === field.name ? !checked : selectedLeftColumns.has(name)
+ );
+ setSpatialJoinConfig(op.id, {leftColumns: next});
+ }}
+ />
+ <DatasetOpsFieldName>{field.displayName || field.name}</DatasetOpsFieldName>
+ </DatasetOpsAggRow>
+ );
+ })}
+ </ScrollableColumnList>
+ </CollapsibleSection>
+ </DatasetOpsSection>
+
+ <DatasetOpsSection sectionColor={JOIN_OPERATION_COLOR}>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.joinOperation" />
+ <DatasetOpHelp helpId="datasetOps.joinOperationHelp" />
+ </DatasetOpsSectionTitle>
+ <PredicateValue>
+ <ItemSelector
+ options={predicateOptions}
+ selectedItems={selectedPredicate}
+ multiSelect={false}
+ displayOption={option => option.label}
+ getOptionValue={option => option.id}
+ filterOption="label"
+ onChange={value =>
+ setSpatialJoinConfig(op.id, {predicate: String(value) as SpatialJoinPredicate})
+ }
+ searchable={false}
+ DropDownLineItemRenderComponent={PredicateListItem}
+ DropDownRenderComponent={LayerTypeDropdownList}
+ />
+ </PredicateValue>
+ </DatasetOpsSection>
+
+ <DatasetOpsSection sectionColor={right?.color}>
+ <DatasetOpsSectionTitle>
+ <FormattedMessage id="datasetOps.joinDataset" />
+ <DatasetOpHelp helpId="datasetOps.joinDatasetHelp" />
+ </DatasetOpsSectionTitle>
+ <SourceDataSelector
+ datasets={joinDatasets}
+ dataId={op.rightDataId}
+ onSelect={value => {
+ const dataId = typeof value === 'string' ? value : null;
+ if (!dataId) {
+ return;
+ }
+ const nextRight = datasets[dataId];
+ setSpatialJoinConfig(op.id, {
+ rightDataId: dataId,
+ rightGeo: nextRight ? suggestSpatialGeo(nextRight.fields) : null,
+ aggregations: nextRight ? defaultAggregationsForFields(nextRight.fields) : {}
+ });
+ }}
+ defaultValue="Select a dataset"
+ />
+ {right ? (
+ <SidePanelSection>
+ <GeometryHeader>
+ <PanelLabel>
+ <FormattedMessage id="datasetOps.geometryColumn" />
+ </PanelLabel>
+ </GeometryHeader>
+ <ItemSelector
+ options={rightOptions}
+ selectedItems={
+ rightOptions.find(option => option.id === optionIdForGeo(op.rightGeo)) || null
+ }
+ displayOption={option => option.label}
+ getOptionValue={option => option.id}
+ onChange={value => {
+ const option = rightOptions.find(item => item.id === value);
+ setSpatialJoinConfig(op.id, {rightGeo: option?.geo || null});
+ }}
+ searchable={false}
+ multiSelect={false}
+ />
+ </SidePanelSection>
+ ) : null}
+ {right ? (
+ <CollapsibleSection
+ titleId="datasetOps.aggregationRules"
+ helpId="datasetOps.columnsToIncludeHelp"
+ selectAll={allAggregationsSelected}
+ onToggleSelectAll={() =>
+ setSpatialJoinConfig(op.id, {
+ aggregations: allAggregationsSelected
+ ? {}
+ : defaultAggregationsForFields(right.fields)
+ })
+ }
+ >
+ <ScrollableColumnList>
+ {aggregationFields.map(field => {
+ const options = aggregationOptionsForField(field);
+ const selected = op.aggregations[field.name];
+ const selectedOption =
+ options.find(option => option.id === selected) ||
+ options.find(option => option.id === defaultAggregationForField(field)) ||
+ options[0] ||
+ null;
+ return (
+ <DatasetOpsAggRow key={field.name}>
+ <input
+ type="checkbox"
+ checked={Boolean(selected)}
+ onChange={e => {
+ const aggregations = {...op.aggregations};
+ if (e.target.checked) {
+ aggregations[field.name] =
+ selected || defaultAggregationForField(field);
+ } else {
+ delete aggregations[field.name];
+ }
+ setSpatialJoinConfig(op.id, {aggregations});
+ }}
+ />
+ <DatasetOpsFieldName>{field.displayName || field.name}</DatasetOpsFieldName>
+ <AggregationSelector>
+ <ItemSelector
+ options={options}
+ selectedItems={selectedOption}
+ displayOption={option => option.id}
+ getOptionValue={option => option.id}
+ onChange={value =>
+ setSpatialJoinConfig(op.id, {
+ aggregations: {
+ ...op.aggregations,
+ [field.name]: String(value) as DatasetOpAggregation
+ }
+ })
+ }
+ disabled={!selected}
+ searchable={false}
+ multiSelect={false}
+ size="small"
+ />
+ </AggregationSelector>
+ </DatasetOpsAggRow>
+ );
+ })}
+ </ScrollableColumnList>
+ </CollapsibleSection>
+ ) : null}
+ </DatasetOpsSection>
+
+ <ResultNameInput
+ value={op.resultLabel}
+ onChange={resultLabel => setSpatialJoinConfig(op.id, {resultLabel})}
+ />
+ </DatasetOpPanel>
+ );
+ };
+
+ return SpatialJoinPanel;
+}
+
+export default SpatialJoinPanelFactory;
diff --git a/src/components/src/side-panel/dataset-ops/spatial-join-predicate-icons.tsx b/src/components/src/side-panel/dataset-ops/spatial-join-predicate-icons.tsx
new file mode 100644
index 000000000..85dee8169
--- /dev/null
+++ b/src/components/src/side-panel/dataset-ops/spatial-join-predicate-icons.tsx
@@ -0,0 +1,74 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {ComponentType} from 'react';
+import Base, {BaseProps} from '../../common/icons/base';
+import {SpatialJoinPredicate} from '@kepler.gl/table';
+
+const SECONDARY = '#F7F8FA';
+
+function PredicateIcon({
+ className,
+ children,
+ ...props
+}: Partial<BaseProps> & {className: string; children: React.ReactNode}) {
+ return (
+ <Base viewBox="0 0 42 42" height="16px" predefinedClassName={className} {...props}>
+ {children}
+ </Base>
+ );
+}
+
+export const PredicateIntersectsIcon: ComponentType<Partial<BaseProps>> = props => (
+ <PredicateIcon className="dataset-ops-predicate-intersects" {...props}>
+ <path d="M24 6L36 13V27L24 34L12 27V13Z" fill="currentColor" opacity="0.9" />
+ <path d="M18 12L30 19V31L18 38L6 31V19Z" fill={SECONDARY} opacity="0.92" />
+ </PredicateIcon>
+);
+
+export const PredicateEqualsIcon: ComponentType<Partial<BaseProps>> = props => (
+ <PredicateIcon className="dataset-ops-predicate-equals" {...props}>
+ <path d="M21 7L33 14V28L21 35L9 28V14Z" fill="currentColor" opacity="0.9" />
+ <path d="M21 11L29 16V26L21 31L13 26V16Z" fill={SECONDARY} />
+ </PredicateIcon>
+);
+
+export const PredicateCrossesIcon: ComponentType<Partial<BaseProps>> = props => (
+ <PredicateIcon className="dataset-ops-predicate-crosses" {...props}>
+ <path d="M21 6L34 14V28L21 36L8 28V14Z" fill="currentColor" opacity="0.9" />
+ <path d="M8 30L34 12" stroke={SECONDARY} strokeWidth="3" strokeLinecap="round" fill="none" />
+ </PredicateIcon>
+);
+
+export const PredicateOverlapsIcon: ComponentType<Partial<BaseProps>> = props => (
+ <PredicateIcon className="dataset-ops-predicate-overlaps" {...props}>
+ <path d="M16 8L28 15V27L16 34L4 27V15Z" fill="currentColor" opacity="0.9" />
+ <path d="M26 8L38 15V27L26 34L14 27V15Z" fill={SECONDARY} opacity="0.92" />
+ </PredicateIcon>
+);
+
+export const PredicateWithinIcon: ComponentType<Partial<BaseProps>> = props => (
+ <PredicateIcon className="dataset-ops-predicate-within" {...props}>
+ <path d="M21 4L35 12V28L21 36L7 28V12Z" fill={SECONDARY} opacity="0.92" />
+ <path d="M21 14L28 18V26L21 30L14 26V18Z" fill="currentColor" />
+ </PredicateIcon>
+);
+
+export const PredicateTouchesIcon: ComponentType<Partial<BaseProps>> = props => (
+ <PredicateIcon className="dataset-ops-predicate-touches" {...props}>
+ <path d="M14 8L24 14V26L14 32L4 26V14Z" fill="currentColor" opacity="0.9" />
+ <path d="M28 10L38 16V28L28 34L18 28V16Z" fill={SECONDARY} opacity="0.92" />
+ </PredicateIcon>
+);
+
+export const SPATIAL_JOIN_PREDICATE_ICONS: Record<
+ SpatialJoinPredicate,
+ ComponentType<Partial<BaseProps>>
+> = {
+ intersects: PredicateIntersectsIcon,
+ equals: PredicateEqualsIcon,
+ crosses: PredicateCrossesIcon,
+ overlaps: PredicateOverlapsIcon,
+ within: PredicateWithinIcon,
+ touches: PredicateTouchesIcon
+};
diff --git a/src/components/src/side-panel/filter-manager.tsx b/src/components/src/side-panel/filter-manager.tsx
index 143fabfa9..aa2c88363 100644
--- a/src/components/src/side-panel/filter-manager.tsx
+++ b/src/components/src/side-panel/filter-manager.tsx
@@ -154,6 +154,9 @@ function FilterManagerFactory(
showDeleteDataset={showDeleteDataset}
refreshDataset={visStateActions.refreshDataset}
updateDatasetProps={visStateActions.updateDatasetProps}
+ addGroupBy={visStateActions.addGroupBy}
+ addJoin={visStateActions.addJoin}
+ addSpatialJoin={visStateActions.addSpatialJoin}
/>
<FilterList
filtersByIndex={filtersByIndex}
@@ -229,7 +232,8 @@ function FilterManagerFactory(
removeDataset,
showDeleteDataset: true,
refreshDataset: visStateActions.refreshDataset,
- updateDatasetProps: visStateActions.updateDatasetProps
+ updateDatasetProps: visStateActions.updateDatasetProps,
+ visStateActions
};
return (
diff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsx
index 13872a623..ae16eff90 100644
--- a/src/components/src/side-panel/layer-manager.tsx
+++ b/src/components/src/side-panel/layer-manager.tsx
@@ -263,6 +263,7 @@ function LayerManagerFactory(
showAddDataModal={showAddDataModal}
refreshDataset={visStateActions.refreshDataset}
updateDatasetProps={visStateActions.updateDatasetProps}
+ visStateActions={visStateActions}
/>
<SidePanelDivider />
<SidePanelSection>
diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx
index 1ff14ee51..6589ed2b0 100644
--- a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx
+++ b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx
@@ -122,6 +122,9 @@ function DatasetLayerSectionFactory(
showDeleteDataset={showDeleteDataset}
refreshDataset={visStateActions.refreshDataset}
updateDatasetProps={visStateActions.updateDatasetProps}
+ addGroupBy={visStateActions.addGroupBy}
+ addJoin={visStateActions.addJoin}
+ addSpatialJoin={visStateActions.addSpatialJoin}
/>
<LayerList
datasets={datasets}
diff --git a/src/components/src/side-panel/layer-panel/dataset-section.tsx b/src/components/src/side-panel/layer-panel/dataset-section.tsx
index da80175b8..f377b8d70 100644
--- a/src/components/src/side-panel/layer-panel/dataset-section.tsx
+++ b/src/components/src/side-panel/layer-panel/dataset-section.tsx
@@ -8,7 +8,7 @@ import {Add} from '../../common/icons';
import {Button} from '../../common/styled-components';
import SourceDataCatalogFactory from '../common/source-data-catalog';
-import {UIStateActions, VisStateActions, ActionHandler} from '@kepler.gl/actions';
+import {UIStateActions, VisStateActions, ActionHandler, ActionHandlers} from '@kepler.gl/actions';
import {Datasets} from '@kepler.gl/table';
type AddDataButtonProps = {
@@ -26,6 +26,7 @@ type DatasetSectionProps = {
showAddDataModal: () => void;
refreshDataset?: ActionHandler<typeof VisStateActions.refreshDataset>;
updateDatasetProps?: ActionHandler<typeof VisStateActions.updateDatasetProps>;
+ visStateActions?: ActionHandlers<typeof VisStateActions>;
};
const StyledDatasetTitle = styled.div<{$showDatasetList?: boolean}>`
@@ -77,7 +78,8 @@ function DatasetSectionFactory(
showDatasetList,
showAddDataModal,
refreshDataset,
- updateDatasetProps
+ updateDatasetProps,
+ visStateActions
} = props;
const datasetCount = Object.keys(datasets).length;
@@ -96,6 +98,9 @@ function DatasetSectionFactory(
showDeleteDataset={showDeleteDataset}
refreshDataset={refreshDataset}
updateDatasetProps={updateDatasetProps}
+ addGroupBy={visStateActions?.addGroupBy}
+ addJoin={visStateActions?.addJoin}
+ addSpatialJoin={visStateActions?.addSpatialJoin}
/>
)}
</StyledDatasetSection>
diff --git a/src/components/src/side-panel/side-bar.tsx b/src/components/src/side-panel/side-bar.tsx
index 311680ca5..6503ed229 100644
--- a/src/components/src/side-panel/side-bar.tsx
+++ b/src/components/src/side-panel/side-bar.tsx
@@ -43,6 +43,7 @@ const SideBarContainer = styled.div<{left: number}>`
left: ${props => props.left}px;
align-items: stretch;
flex-grow: 1;
+ min-width: 0;
`;
const SideBarInner = styled.div`
@@ -51,6 +52,8 @@ const SideBarInner = styled.div`
display: flex;
flex-direction: column;
height: 100%;
+ width: 100%;
+ min-width: 0;
border-left: ${props => props.theme.sidePanelBorder}px solid
${props => props.theme.sidePanelBorderColor};
`;
@@ -111,7 +114,7 @@ function SidebarFactory(CollapseButton: ReturnType<typeof CollapseButtonFactory>
<StyledSidePanelContainer width={isOpen ? width : 0} className="side-panel--container">
<SideBarContainer
className="side-bar"
- style={{width: `${width}px`}}
+ style={{width: `${width}px`, maxWidth: `${width}px`}}
left={horizontalOffset}
>
{isOpen ? (
diff --git a/src/components/src/types.ts b/src/components/src/types.ts
index cf70fc9fd..5cac5d0a2 100644
--- a/src/components/src/types.ts
+++ b/src/components/src/types.ts
@@ -12,7 +12,7 @@ import {
MapStateActions,
UIStateActions
} from '@kepler.gl/actions';
-import {Datasets} from '@kepler.gl/table';
+import {Datasets, GroupByOp, JoinOp} from '@kepler.gl/table';
export type BaseComponentProps = PropsWithChildren<HTMLAttributes<unknown>>;
@@ -38,6 +38,8 @@ export type SidePanelProps = {
mapInfo: {title?: string; description?: string};
width: number;
datasets: Datasets;
+ groupBys?: GroupByOp[];
+ joins?: JoinOp[];
uiStateActions: typeof UIStateActions;
visStateActions: typeof VisStateActions;
mapStateActions: typeof MapStateActions;
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 59cbb1880..d4005b09f 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -388,6 +388,7 @@ export default {
},
datasetTitle: {
showDataTable: 'Show data table',
+ moreSettings: 'More settings',
removeDataset: 'Remove dataset',
refreshDataset: 'Refresh dataset',
refreshFailed: 'Refresh failed',
@@ -400,6 +401,88 @@ export default {
refresh15m: '15 min',
refreshCustom: 'Custom'
},
+ datasetOps: {
+ groupBy: 'Group By',
+ groupByHelp:
+ 'Create groups to combine data based on a selected field. Result will be added as a new dataset.',
+ groupByField: 'Group by field',
+ groupByFieldHelp: 'Select the field used to create groups.',
+ aggregations: 'Aggregations',
+ aggregationRules: 'Aggregation Rules',
+ aggregationRulesHelp: 'Describe aggregation rules for combining data in each column.',
+ join: 'Join',
+ joinHelp:
+ 'Combine rows from two datasets based on a common field. Result will be added as a new dataset.',
+ spatialJoin: 'Spatial Join',
+ spatialJoinHelp:
+ 'Combines columns from one dataset to another based on their spatial relationship. To perform spatial join, select geo columns in both datasets and select the type of spatial join operation to perform. The results will be a new joined dataset.',
+ columnsToInclude: 'Columns to include',
+ columnsToIncludeHelp: 'Select and modify columns to be included in the joined dataset.',
+ selectAll: 'Select All',
+ unselectAll: 'Unselect All',
+ resultName: 'Result name',
+ back: 'Back',
+ run: 'Run',
+ cancel: 'Cancel',
+ leftKey: 'Left key',
+ rightKey: 'Right key',
+ leftDataset: 'Left',
+ leftDatasetHelp: 'Select dataset to join on the left',
+ leftFieldHelp: 'Select common field of the left dataset',
+ rightDataset: 'Right',
+ rightDatasetHelp: 'Select dataset to join on the right',
+ rightFieldHelp: 'Select common field of the right dataset',
+ joinTypeLabel: 'Join Type',
+ targetDataset: 'Target Dataset',
+ targetDatasetHelp:
+ 'Select the dataset that will keep one output row per feature. Matching features from the join dataset are aggregated onto that row.',
+ joinDataset: 'Join Dataset',
+ joinDatasetHelp:
+ 'Select the dataset that will be combined into the target dataset based on the spatial relationship.',
+ joinOperation: 'Join Operation',
+ joinOperationHelp:
+ 'Intersects: they share any space. Within: target is completely inside join. Equals: they occupy the same space. Crosses: they share some interior points but not all. Overlaps: they share space and neither contains the other. Touches: they share a boundary but not interiors.',
+ geometryColumn: 'Geometry Column',
+ leftGeometry: 'Left geometry',
+ rightGeometry: 'Right geometry',
+ predicate: 'Predicate',
+ predicateOption: {
+ intersects: 'Intersects',
+ equals: 'Equals',
+ crosses: 'Crosses',
+ overlaps: 'Overlaps',
+ within: 'Within',
+ touches: 'Touches'
+ },
+ predicateHelp: {
+ intersects: 'True when the geometries share any interior or boundary.',
+ equals: 'True when the geometries occupy the same space.',
+ crosses:
+ 'True when the geometries share interior space but neither contains the other, typically a line crossing a polygon or another line.',
+ overlaps:
+ 'True when the geometries share interior space, have the same dimension, and neither contains the other.',
+ within: 'True when the target geometry is completely inside the join geometry.',
+ touches: 'True when the geometries share a boundary but not their interiors.'
+ },
+ joinType: {
+ left: 'Left',
+ inner: 'Inner',
+ full: 'Full',
+ leftHelp: 'Left Join: Returns all rows from the left, and the matched rows from the right.',
+ innerHelp: 'Inner Join: Returns rows that have matching values in both.',
+ fullHelp: 'Full Join: Returns all rows when there is a match in either left or right.'
+ },
+ aggregation: {
+ count: 'Count',
+ sum: 'Sum',
+ average: 'Mean',
+ maximum: 'Max',
+ minimum: 'Min',
+ median: 'Median',
+ countUnique: 'Unique',
+ merge: 'Merge'
+ }
+ },
datasetInfo: {
rowCount: '{rowCount} rows',
vectorTile: 'Vector tile',
diff --git a/src/reducers/src/dataset-ops-updaters.spec.ts b/src/reducers/src/dataset-ops-updaters.spec.ts
new file mode 100644
index 000000000..592594e7d
--- /dev/null
+++ b/src/reducers/src/dataset-ops-updaters.spec.ts
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {VisStateActions} from '@kepler.gl/actions';
+import {KeplerTable} from '@kepler.gl/table';
+import SchemaManager, {VisState} from '@kepler.gl/schemas';
+import {drainTasksForTesting, succeedTaskWithValues} from '@kepler.gl/tasks';
+
+import visStateReducer from './vis-state';
+import {INITIAL_VIS_STATE} from './vis-state-updaters';
+
+const reduceVisState = visStateReducer as (state: VisState, action: unknown) => VisState;
+
+function makeTable(id: string, fields: {name: string; type: string}[], rows: any[][]) {
+ const table = new KeplerTable({
+ info: {id, label: id, type: 'local'},
+ color: [0, 0, 0]
+ });
+ table.updateSchema({
+ fields: fields.map(field => ({
+ name: field.name,
+ type: field.type,
+ analyzerType: field.type
+ })),
+ rows
+ });
+ return table;
+}
+
+function flushCreateTableTasks(state: VisState) {
+ const tasks = drainTasksForTesting();
+ return tasks.reduce((nextState, task) => {
+ if (!String(task.label || '').includes('CREATE_TABLE_TASK')) {
+ return nextState;
+ }
+ const tables = (Array.isArray(task.payload) ? task.payload : [task.payload]).map(payload => {
+ const table = new KeplerTable({info: payload.info, color: payload.color, ...payload.opts});
+ table.updateSchema(payload.data);
+ return table;
+ });
+ return reduceVisState(nextState, succeedTaskWithValues(task, tables));
+ }, state);
+}
+
+describe('dataset ops vis-state', () => {
+ beforeEach(() => {
+ drainTasksForTesting();
+ });
+
+ test('runGroupBy adds a derived dataset', () => {
+ const cities = makeTable(
+ 'cities',
+ [
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer}
+ ],
+ [
+ ['west', 10],
+ ['west', 20],
+ ['east', 40]
+ ]
+ );
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {cities}
+ };
+
+ state = reduceVisState(state, VisStateActions.addGroupBy('cities'));
+ expect(state.groupBys).toHaveLength(1);
+ const opId = state.groupBys[0].id;
+
+ state = reduceVisState(
+ state,
+ VisStateActions.setGroupByConfig(opId, {
+ fieldName: 'region',
+ aggregations: {pop: 'sum'}
+ })
+ );
+ state = reduceVisState(state, VisStateActions.runGroupBy(opId));
+ state = flushCreateTableTasks(state);
+
+ const resultId = state.groupBys[0].resultId;
+ expect(state.datasets[resultId]).toBeTruthy();
+ expect(state.datasets[resultId].metadata.derivedDataset).toEqual({
+ type: 'groupBy',
+ sourceDataIds: ['cities'],
+ operationId: opId
+ });
+ expect(state.datasets[resultId].dataContainer.numRows()).toBe(2);
+ });
+
+ test('delete parent keeps derived child snapshot', () => {
+ const cities = makeTable(
+ 'cities',
+ [
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer}
+ ],
+ [['west', 10]]
+ );
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {cities}
+ };
+ state = reduceVisState(state, VisStateActions.addGroupBy('cities'));
+ const op = state.groupBys[0];
+ state = reduceVisState(
+ state,
+ VisStateActions.setGroupByConfig(op.id, {
+ fieldName: 'region',
+ aggregations: {pop: 'sum'}
+ })
+ );
+ state = reduceVisState(state, VisStateActions.runGroupBy(op.id));
+ state = flushCreateTableTasks(state);
+
+ expect(Object.keys(state.datasets)).toHaveLength(2);
+ state = reduceVisState(state, VisStateActions.removeDataset('cities'));
+ expect(state.datasets.cities).toBeUndefined();
+ expect(state.datasets[op.resultId]).toBeTruthy();
+ expect(state.groupBys).toHaveLength(0);
+ });
+
+ test('addGroupBy uses a short random result name', () => {
+ const cities = makeTable(
+ 'cities',
+ [{name: 'region', type: ALL_FIELD_TYPES.string}],
+ [['west']]
+ );
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {cities}
+ };
+ state = reduceVisState(state, VisStateActions.addGroupBy('cities'));
+ expect(state.groupBys[0].resultLabel).toMatch(/^group-by-\d{2}$/);
+ });
+
+ test('addJoin uses a short random result name', () => {
+ const cities = makeTable('cities', [{name: 'id', type: ALL_FIELD_TYPES.string}], [['1']]);
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {cities}
+ };
+ state = reduceVisState(state, VisStateActions.addJoin('cities'));
+ expect(state.joins[0].resultLabel).toMatch(/^join-dataset-\d{2}$/);
+ });
+
+ test('setSpatialJoinConfig updates the predicate', () => {
+ const polys = makeTable('polys', [{name: 'geom', type: ALL_FIELD_TYPES.geojson}], []);
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {polys}
+ };
+ state = reduceVisState(state, VisStateActions.addSpatialJoin('polys'));
+ const op = state.joins[0];
+ expect(state.joins[0].predicate).toBe('intersects');
+ expect(state.joins[0].resultLabel).toBe(`spatial-join-${state.joins[0].resultId}`);
+ state = reduceVisState(
+ state,
+ VisStateActions.setSpatialJoinConfig(op.id, {predicate: 'within'})
+ );
+ expect(state.joins[0].predicate).toBe('within');
+ });
+
+ test('delete spatial join source keeps result snapshot', () => {
+ const polygon = {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [-10, -10],
+ [10, -10],
+ [10, 10],
+ [-10, 10],
+ [-10, -10]
+ ]
+ ]
+ };
+ const polys = makeTable(
+ 'polys',
+ [
+ {name: 'name', type: ALL_FIELD_TYPES.string},
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson}
+ ],
+ [['west', polygon]]
+ );
+ const pts = makeTable(
+ 'pts',
+ [
+ {name: 'lat', type: ALL_FIELD_TYPES.real},
+ {name: 'lng', type: ALL_FIELD_TYPES.real},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ [[0, 0, 10]]
+ );
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {polys, pts}
+ };
+ state = reduceVisState(state, VisStateActions.addSpatialJoin('polys'));
+ const op = state.joins[0];
+ state = reduceVisState(
+ state,
+ VisStateActions.setSpatialJoinConfig(op.id, {
+ rightDataId: 'pts',
+ leftGeo: {kind: 'geojson', fieldName: 'geom'},
+ rightGeo: {kind: 'latlng', latField: 'lat', lngField: 'lng'},
+ aggregations: {value: 'sum'}
+ })
+ );
+ state = reduceVisState(state, VisStateActions.runSpatialJoin(op.id));
+ state = flushCreateTableTasks(state);
+
+ expect(state.datasets[op.resultId]).toBeTruthy();
+ state = reduceVisState(state, VisStateActions.removeDataset('pts'));
+ expect(state.datasets.pts).toBeUndefined();
+ expect(state.datasets.polys).toBeTruthy();
+ expect(state.datasets[op.resultId]).toBeTruthy();
+ expect(state.joins).toHaveLength(0);
+ });
+
+ test('save/load roundtrip keeps derivedDataset metadata and drafts', () => {
+ const cities = makeTable(
+ 'cities',
+ [
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer}
+ ],
+ [['west', 10]]
+ );
+ let state: VisState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {cities}
+ };
+ state = reduceVisState(state, VisStateActions.addGroupBy('cities'));
+ const op = state.groupBys[0];
+ state = reduceVisState(
+ state,
+ VisStateActions.setGroupByConfig(op.id, {
+ fieldName: 'region',
+ aggregations: {pop: 'sum'}
+ })
+ );
+ state = reduceVisState(state, VisStateActions.runGroupBy(op.id));
+ state = flushCreateTableTasks(state);
+
+ const saved = SchemaManager.save({
+ visState: state,
+ mapState: {},
+ mapStyle: {},
+ uiState: {}
+ });
+ const derived = saved.datasets.find(dataset => dataset.data.id === op.resultId);
+ const derivedMeta = derived?.data.metadata as
+ | {derivedDataset?: {type?: string} | null}
+ | undefined;
+ expect(derivedMeta?.derivedDataset?.type).toBe('groupBy');
+ expect(saved.config.config.visState.groupBys?.[0].fieldName).toBe('region');
+ });
+});
diff --git a/src/reducers/src/dataset-ops-updaters.ts b/src/reducers/src/dataset-ops-updaters.ts
new file mode 100644
index 000000000..a27784fbd
--- /dev/null
+++ b/src/reducers/src/dataset-ops-updaters.ts
@@ -0,0 +1,302 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {generateHashId} from '@kepler.gl/common-utils';
+import {
+ defaultAggregationsForFields,
+ groupByDataset,
+ isTabularDatasetForOps,
+ joinDatasets,
+ spatialJoinDatasets,
+ suggestSpatialGeo,
+ GroupByOp,
+ JoinOp
+} from '@kepler.gl/table';
+import {ProtoDataset} from '@kepler.gl/types';
+import {VisStateActions} from '@kepler.gl/actions';
+import {VisState} from '@kepler.gl/schemas';
+
+export type DerivedDatasetOpResult = {
+ state: VisState;
+ proto?: ProtoDataset;
+};
+
+function deactivateOps<T extends {isConfigActive?: boolean}>(ops: T[]): T[] {
+ return ops.map(op => ({...op, isConfigActive: false}));
+}
+
+function randomTwoDigitSuffix(): string {
+ return String(Math.floor(Math.random() * 100)).padStart(2, '0');
+}
+
+function defaultGroupByLabel(): string {
+ return `group-by-${randomTwoDigitSuffix()}`;
+}
+
+function defaultJoinLabel(): string {
+ return `join-dataset-${randomTwoDigitSuffix()}`;
+}
+
+function defaultSpatialJoinLabel(resultId: string): string {
+ return `spatial-join-${resultId}`;
+}
+
+export function addGroupByUpdater(
+ state: VisState,
+ action: VisStateActions.AddGroupByUpdaterAction
+): VisState {
+ const dataset = state.datasets[action.dataId];
+ if (!isTabularDatasetForOps(dataset)) {
+ return state;
+ }
+ const id = generateHashId(6);
+ const resultId = generateHashId(6);
+ const op: GroupByOp = {
+ id,
+ dataId: action.dataId,
+ fieldName: null,
+ aggregations: defaultAggregationsForFields(dataset.fields),
+ resultId,
+ resultLabel: defaultGroupByLabel(),
+ isConfigActive: true,
+ error: null
+ };
+ return {
+ ...state,
+ groupBys: [...deactivateOps(state.groupBys), op],
+ joins: deactivateOps(state.joins)
+ };
+}
+
+export function setGroupByConfigUpdater(
+ state: VisState,
+ action: VisStateActions.SetGroupByConfigUpdaterAction
+): VisState {
+ return {
+ ...state,
+ groupBys: state.groupBys.map(op =>
+ op.id === action.id ? {...op, ...action.config, error: action.config.error ?? null} : op
+ )
+ };
+}
+
+export function executeGroupBy(
+ state: VisState,
+ action: VisStateActions.RunGroupByUpdaterAction
+): DerivedDatasetOpResult {
+ const op = state.groupBys.find(item => item.id === action.id);
+ const dataset = op ? state.datasets[op.dataId] : undefined;
+ if (!op || !dataset || !op.fieldName) {
+ return {
+ state: setGroupByConfigUpdater(state, {
+ id: action.id,
+ config: {error: 'Select a grouping field'}
+ })
+ };
+ }
+
+ try {
+ const proto = groupByDataset(dataset, {
+ fieldName: op.fieldName,
+ aggregations: op.aggregations,
+ label: op.resultLabel,
+ resultId: op.resultId,
+ operationId: op.id
+ });
+ return {
+ state: {
+ ...state,
+ groupBys: state.groupBys.map(item =>
+ item.id === op.id ? {...item, isConfigActive: false, error: null} : item
+ )
+ },
+ proto
+ };
+ } catch (error) {
+ return {
+ state: setGroupByConfigUpdater(state, {
+ id: action.id,
+ config: {error: error instanceof Error ? error.message : String(error)}
+ })
+ };
+ }
+}
+
+export function addJoinUpdater(
+ state: VisState,
+ action: VisStateActions.AddJoinUpdaterAction
+): VisState {
+ const dataset = state.datasets[action.dataId];
+ if (!isTabularDatasetForOps(dataset)) {
+ return state;
+ }
+ const implementation = action.implementation || 'simple';
+ const id = generateHashId(6);
+ const resultId = generateHashId(6);
+ const op: JoinOp = {
+ id,
+ implementation,
+ leftDataId: action.dataId,
+ rightDataId: null,
+ leftField: null,
+ rightField: null,
+ type: 'LEFT',
+ aggregations: {},
+ leftGeo: implementation === 'spatial' ? suggestSpatialGeo(dataset.fields) : null,
+ rightGeo: null,
+ predicate: implementation === 'spatial' ? 'intersects' : undefined,
+ resultId,
+ resultLabel:
+ implementation === 'spatial' ? defaultSpatialJoinLabel(resultId) : defaultJoinLabel(),
+ isConfigActive: true,
+ error: null
+ };
+ return {
+ ...state,
+ joins: [...deactivateOps(state.joins), op],
+ groupBys: deactivateOps(state.groupBys)
+ };
+}
+
+export function setJoinConfigUpdater(
+ state: VisState,
+ action: VisStateActions.SetJoinConfigUpdaterAction
+): VisState {
+ return {
+ ...state,
+ joins: state.joins.map(op =>
+ op.id === action.id ? {...op, ...action.config, error: action.config.error ?? null} : op
+ )
+ };
+}
+
+export function executeJoin(
+ state: VisState,
+ action: VisStateActions.RunJoinUpdaterAction
+): DerivedDatasetOpResult {
+ const op = state.joins.find(item => item.id === action.id && item.implementation !== 'spatial');
+ const left = op ? state.datasets[op.leftDataId] : undefined;
+ const right = op?.rightDataId ? state.datasets[op.rightDataId] : undefined;
+ if (!op || !left || !right || !op.leftField || !op.rightField) {
+ return {
+ state: setJoinConfigUpdater(state, {
+ id: action.id,
+ config: {error: 'Select datasets and join keys'}
+ })
+ };
+ }
+
+ try {
+ const proto = joinDatasets(left, right, {
+ leftField: op.leftField,
+ rightField: op.rightField,
+ type: op.type,
+ leftColumns: op.leftColumns,
+ rightColumns: op.rightColumns,
+ label: op.resultLabel,
+ resultId: op.resultId,
+ operationId: op.id
+ });
+ return {
+ state: {
+ ...state,
+ joins: state.joins.map(item =>
+ item.id === op.id ? {...item, isConfigActive: false, error: null} : item
+ )
+ },
+ proto
+ };
+ } catch (error) {
+ return {
+ state: setJoinConfigUpdater(state, {
+ id: action.id,
+ config: {error: error instanceof Error ? error.message : String(error)}
+ })
+ };
+ }
+}
+
+export function addSpatialJoinUpdater(
+ state: VisState,
+ action: VisStateActions.AddSpatialJoinUpdaterAction
+): VisState {
+ return addJoinUpdater(state, {dataId: action.dataId, implementation: 'spatial'});
+}
+
+export function setSpatialJoinConfigUpdater(
+ state: VisState,
+ action: VisStateActions.SetSpatialJoinConfigUpdaterAction
+): VisState {
+ return setJoinConfigUpdater(state, action);
+}
+
+export function executeSpatialJoin(
+ state: VisState,
+ action: VisStateActions.RunSpatialJoinUpdaterAction
+): DerivedDatasetOpResult {
+ const op = state.joins.find(item => item.id === action.id && item.implementation === 'spatial');
+ const left = op ? state.datasets[op.leftDataId] : undefined;
+ const right = op?.rightDataId ? state.datasets[op.rightDataId] : undefined;
+ if (!op || !left || !right || !op.leftGeo || !op.rightGeo) {
+ return {
+ state: setJoinConfigUpdater(state, {
+ id: action.id,
+ config: {error: 'Select datasets and geometry fields'}
+ })
+ };
+ }
+
+ try {
+ const proto = spatialJoinDatasets(left, right, {
+ leftGeo: op.leftGeo,
+ rightGeo: op.rightGeo,
+ aggregations: op.aggregations,
+ leftColumns: op.leftColumns,
+ predicate: op.predicate || 'intersects',
+ label: op.resultLabel,
+ resultId: op.resultId,
+ operationId: op.id
+ });
+ return {
+ state: {
+ ...state,
+ joins: state.joins.map(item =>
+ item.id === op.id ? {...item, isConfigActive: false, error: null} : item
+ )
+ },
+ proto
+ };
+ } catch (error) {
+ return {
+ state: setJoinConfigUpdater(state, {
+ id: action.id,
+ config: {error: error instanceof Error ? error.message : String(error)}
+ })
+ };
+ }
+}
+
+export function removeDatasetOpUpdater(
+ state: VisState,
+ action: VisStateActions.RemoveDatasetOpUpdaterAction
+): VisState {
+ return {
+ ...state,
+ groupBys: state.groupBys.filter(op => op.id !== action.id),
+ joins: state.joins.filter(op => op.id !== action.id)
+ };
+}
+
+export function removeOpsForDatasets(state: VisState, dataIds: string[]): VisState {
+ const ids = new Set(dataIds);
+ return {
+ ...state,
+ groupBys: state.groupBys.filter(op => !ids.has(op.dataId) && !ids.has(op.resultId)),
+ joins: state.joins.filter(
+ op =>
+ !ids.has(op.leftDataId) &&
+ !(op.rightDataId && ids.has(op.rightDataId)) &&
+ !ids.has(op.resultId)
+ )
+ };
+}
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index 93957ffc3..5ea8ff57a 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -203,6 +203,19 @@ import {
} from './layer-utils';
import {getPropValueToMerger, hasPropsToMerge} from './merger-handler';
import {mergeDatasetsByOrder} from './vis-state-merger';
+import {
+ addGroupByUpdater,
+ addJoinUpdater,
+ addSpatialJoinUpdater,
+ executeGroupBy,
+ executeJoin,
+ executeSpatialJoin,
+ removeDatasetOpUpdater,
+ removeOpsForDatasets,
+ setGroupByConfigUpdater,
+ setJoinConfigUpdater,
+ setSpatialJoinConfigUpdater
+} from './dataset-ops-updaters';
import {
fixEffectOrder,
getAnimatableVisibleLayers,
@@ -350,6 +363,8 @@ export const INITIAL_VIS_STATE: VisState = {
// a collection of multiple dataset
datasets: {},
editingDataset: undefined,
+ groupBys: [],
+ joins: [],
// effects
effects: [],
@@ -2886,38 +2901,43 @@ export function removeDatasetUpdater<T extends VisState>(
state: T,
action: VisStateActions.RemoveDatasetUpdaterAction
): T {
- // extract dataset key
const {dataId: datasetKey} = action;
const {datasets} = state;
- // check if dataset is present
+ if (!datasets[datasetKey]) {
+ return state;
+ }
+
+ // Derived tables are snapshots: keep them when a source dataset is deleted.
+ // Only drop in-progress group-by / join drafts that referenced this dataset.
+ const nextState = removeOpsForDatasets(state, [datasetKey]) as T;
+ return removeSingleDatasetUpdater(nextState, datasetKey);
+}
+
+function removeSingleDatasetUpdater<T extends VisState>(state: T, datasetKey: string): T {
+ const {datasets} = state;
if (!datasets[datasetKey]) {
return state;
}
const {
layers,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
- datasets: {[datasetKey]: dataset, ...newDatasets}
+ datasets: {[datasetKey]: _dataset, ...newDatasets}
} = state;
const layersToRemove = layers.filter(l => l.config.dataId === datasetKey).map(l => l.id);
- // remove layers and datasets
let newState = layersToRemove.reduce((accu, id) => removeLayerUpdater(accu, {id}), {
...state,
datasets: newDatasets
});
- // update filters
const filters: Filter[] = [];
for (const filter of newState.filters) {
const valueIndex = filter.dataId.indexOf(datasetKey);
if (valueIndex >= 0 && filter.dataId.length > 1) {
- // only remove one synced dataset from the filter
filters.push(_removeFilterDataIdAtValueIndex(filter, valueIndex, datasets));
} else if (valueIndex < 0) {
- // leave the filter as is
filters.push(filter);
}
}
@@ -6015,12 +6035,10 @@ function defaultReplaceParentDatasetIds(value: any, dataId: string, dataIdToRepl
// Find datasetIds derived a saved visState Property;
function findChildDatasetIds(value) {
if (Array.isArray(value)) {
- // for layers, filters, call defaultReplaceParentDatasetIds on each item in array
const childDataIds = value.map(findChildDatasetIds).filter(d => d);
return childDataIds.length ? childDataIds : null;
}
- // child data id usually stores in the derived dataset info
return value?.newDataset?.info.id || null;
}
@@ -6224,3 +6242,67 @@ function replacePropValueInState(
}
return nextState;
}
+
+const DATASET_OP_ADD_OPTIONS = {
+ autoCreateLayers: true,
+ centerMap: false,
+ keepExistingConfig: true
+};
+
+function applyDerivedProtoDataset(state: VisState, proto: ProtoDataset): VisState {
+ const resultId = proto.info.id;
+ if (!resultId) {
+ return state;
+ }
+ if (state.datasets[resultId]) {
+ const nextState = updateDatasetUpdater(state, {dataId: resultId, data: proto.data});
+ const existing = nextState.datasets[resultId];
+ if (!existing) {
+ return nextState;
+ }
+ existing.metadata = {
+ ...existing.metadata,
+ ...proto.metadata
+ };
+ existing.label = proto.info.label || existing.label;
+ return nextState;
+ }
+ return updateVisDataUpdater(state, {
+ datasets: proto,
+ options: DATASET_OP_ADD_OPTIONS
+ });
+}
+
+export function runGroupByUpdater(
+ state: VisState,
+ action: VisStateActions.RunGroupByUpdaterAction
+): VisState {
+ const {state: nextState, proto} = executeGroupBy(state, action);
+ return proto ? applyDerivedProtoDataset(nextState, proto) : nextState;
+}
+
+export function runJoinUpdater(
+ state: VisState,
+ action: VisStateActions.RunJoinUpdaterAction
+): VisState {
+ const {state: nextState, proto} = executeJoin(state, action);
+ return proto ? applyDerivedProtoDataset(nextState, proto) : nextState;
+}
+
+export function runSpatialJoinUpdater(
+ state: VisState,
+ action: VisStateActions.RunSpatialJoinUpdaterAction
+): VisState {
+ const {state: nextState, proto} = executeSpatialJoin(state, action);
+ return proto ? applyDerivedProtoDataset(nextState, proto) : nextState;
+}
+
+export {
+ addGroupByUpdater,
+ addJoinUpdater,
+ addSpatialJoinUpdater,
+ removeDatasetOpUpdater,
+ setGroupByConfigUpdater,
+ setJoinConfigUpdater,
+ setSpatialJoinConfigUpdater
+};
diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.ts
index f397c9d7e..07b5dabdf 100644
--- a/src/reducers/src/vis-state.ts
+++ b/src/reducers/src/vis-state.ts
@@ -224,7 +224,18 @@ const actionHandler = {
[ActionTypes.SET_LOADING_INDICATOR]: visStateUpdaters.setLoadingIndicatorUpdater,
- [ActionTypes.SET_LOADING_PROGRESS]: visStateUpdaters.setLoadingProgressUpdater
+ [ActionTypes.SET_LOADING_PROGRESS]: visStateUpdaters.setLoadingProgressUpdater,
+
+ [ActionTypes.ADD_GROUP_BY]: visStateUpdaters.addGroupByUpdater,
+ [ActionTypes.SET_GROUP_BY_CONFIG]: visStateUpdaters.setGroupByConfigUpdater,
+ [ActionTypes.RUN_GROUP_BY]: visStateUpdaters.runGroupByUpdater,
+ [ActionTypes.ADD_JOIN]: visStateUpdaters.addJoinUpdater,
+ [ActionTypes.SET_JOIN_CONFIG]: visStateUpdaters.setJoinConfigUpdater,
+ [ActionTypes.RUN_JOIN]: visStateUpdaters.runJoinUpdater,
+ [ActionTypes.ADD_SPATIAL_JOIN]: visStateUpdaters.addSpatialJoinUpdater,
+ [ActionTypes.SET_SPATIAL_JOIN_CONFIG]: visStateUpdaters.setSpatialJoinConfigUpdater,
+ [ActionTypes.RUN_SPATIAL_JOIN]: visStateUpdaters.runSpatialJoinUpdater,
+ [ActionTypes.REMOVE_DATASET_OP]: visStateUpdaters.removeDatasetOpUpdater
};
// construct vis-state reducer
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index 4c20d8a73..cbb68d561 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -38,7 +38,7 @@ import {
Annotation,
ChartConfig
} from '@kepler.gl/types';
-import {Datasets} from '@kepler.gl/table';
+import {Datasets, GroupByOp, JoinOp} from '@kepler.gl/table';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {Loader} from '@loaders.gl/loader-utils';
import KeplerGLSchema from './schema-manager';
@@ -75,6 +75,8 @@ export interface VisState {
filterToBeMerged: any[];
datasets: Datasets;
editingDataset: string | undefined;
+ groupBys: GroupByOp[];
+ joins: JoinOp[];
interactionConfig: InteractionConfig;
interactionToBeMerged: any;
layerBlending: string;
@@ -1065,7 +1067,9 @@ export const propertiesV1 = {
},
key: 'editor'
}),
- layerOrder: null
+ layerOrder: null,
+ groupBys: null,
+ joins: null
};
export class VisStateSchemaV1 extends Schema {
diff --git a/src/table/package.json b/src/table/package.json
index 6ba0e98fa..fadcfa16c 100644
--- a/src/table/package.json
+++ b/src/table/package.json
@@ -35,6 +35,11 @@
"@kepler.gl/utils": "3.3.0-alpha.15",
"@loaders.gl/mvt": "^4.4.1",
"@loaders.gl/pmtiles": "^4.4.1",
+ "@turf/boolean-crosses": "^7.2.0",
+ "@turf/boolean-equal": "^7.2.0",
+ "@turf/boolean-intersects": "^7.2.0",
+ "@turf/boolean-overlap": "^7.2.0",
+ "@turf/boolean-touches": "^7.2.0",
"@types/d3-array": "^2.8.0",
"d3-array": "^2.8.0",
"es-toolkit": "^1.39.10",
diff --git a/src/table/src/dataset-ops.spec.ts b/src/table/src/dataset-ops.spec.ts
new file mode 100644
index 000000000..463be7227
--- /dev/null
+++ b/src/table/src/dataset-ops.spec.ts
@@ -0,0 +1,460 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {latLngToCell} from '@kepler.gl/common-utils';
+
+import KeplerTable from './kepler-table';
+import {
+ DATASET_OPS_AGGREGATIONS,
+ aggregationOptionsForField,
+ defaultAggregationsForFields,
+ groupByDataset,
+ isDatasetOpsAggregationField,
+ isTabularDatasetForOps,
+ joinDatasets,
+ spatialJoinDatasets
+} from './dataset-ops';
+
+function makeTable({
+ id,
+ fields,
+ rows,
+ type = 'local'
+}: {
+ id: string;
+ fields: {name: string; type: string}[];
+ rows: any[][];
+ type?: string;
+}) {
+ const table = new KeplerTable({
+ info: {id, label: id, type},
+ color: [0, 0, 0]
+ });
+ table.updateSchema({
+ fields: fields.map(field => ({
+ name: field.name,
+ type: field.type,
+ analyzerType: field.type
+ })),
+ rows
+ });
+ return table;
+}
+
+const square = (west: number, south: number, east: number, north: number) => ({
+ type: 'Feature',
+ properties: {},
+ geometry: {
+ type: 'Polygon',
+ coordinates: [
+ [
+ [west, south],
+ [east, south],
+ [east, north],
+ [west, north],
+ [west, south]
+ ]
+ ]
+ }
+});
+
+describe('dataset-ops engine', () => {
+ test('groupByDataset aggregates numeric and unique string values', () => {
+ const dataset = makeTable({
+ id: 'cities',
+ fields: [
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer},
+ {name: 'name', type: ALL_FIELD_TYPES.string}
+ ],
+ rows: [
+ ['west', 10, 'a'],
+ ['west', 20, 'b'],
+ ['east', 40, 'c']
+ ]
+ });
+
+ const result = groupByDataset(dataset, {
+ fieldName: 'region',
+ aggregations: {
+ pop: DATASET_OPS_AGGREGATIONS.sum,
+ name: DATASET_OPS_AGGREGATIONS.countUnique
+ },
+ resultId: 'cities-grouped',
+ operationId: 'gb-1'
+ });
+
+ expect(result.info.id).toBe('cities-grouped');
+ expect(result.metadata.derivedDataset).toEqual({
+ type: 'groupBy',
+ sourceDataIds: ['cities'],
+ operationId: 'gb-1'
+ });
+ expect(result.data.fields.map(f => f.name)).toEqual(['region', 'pop_sum', 'name_countUnique']);
+ const byRegion = Object.fromEntries(result.data.rows.map(row => [row[0], row]));
+ expect(byRegion.west).toEqual(['west', 30, 2]);
+ expect(byRegion.east).toEqual(['east', 40, 1]);
+ });
+
+ test('groupByDataset keeps null groups distinct from the string __null__', () => {
+ const dataset = makeTable({
+ id: 'cities',
+ fields: [
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ [null, 1],
+ [null, 2],
+ ['__null__', 10],
+ ['__null__', 20],
+ ['west', 3]
+ ]
+ });
+
+ const result = groupByDataset(dataset, {
+ fieldName: 'region',
+ aggregations: {pop: DATASET_OPS_AGGREGATIONS.sum}
+ });
+
+ const byRegion = Object.fromEntries(
+ result.data.rows.map(row => [row[0] === null ? 'null' : String(row[0]), row])
+ );
+ expect(result.data.rows).toHaveLength(3);
+ expect(byRegion.null).toEqual([null, 3]);
+ expect(byRegion.__null__).toEqual(['__null__', 30]);
+ expect(byRegion.west).toEqual(['west', 3]);
+ });
+
+ test('groupByDataset merges geojson geometries so the result stays mappable', () => {
+ const dataset = makeTable({
+ id: 'shapes',
+ fields: [
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson}
+ ],
+ rows: [
+ ['west', square(-10, -10, 0, 0)],
+ ['west', square(0, 0, 10, 10)],
+ ['east', square(20, -10, 40, 10)]
+ ]
+ });
+
+ const result = groupByDataset(dataset, {
+ fieldName: 'region',
+ aggregations: {geom: DATASET_OPS_AGGREGATIONS.merge}
+ });
+
+ expect(result.data.fields.map(field => ({name: field.name, type: field.type}))).toEqual([
+ {name: 'region', type: ALL_FIELD_TYPES.string},
+ {name: 'geom_merge', type: ALL_FIELD_TYPES.geojson}
+ ]);
+ const byRegion = Object.fromEntries(result.data.rows.map(row => [row[0], row[1]]));
+ expect(byRegion.west.geometry.type).toBe('MultiPolygon');
+ expect(byRegion.west.geometry.coordinates).toHaveLength(2);
+ expect(byRegion.east.geometry.type).toBe('Polygon');
+ });
+
+ test('joinDatasets supports LEFT, INNER, and FULL with null keys', () => {
+ const left = makeTable({
+ id: 'orders',
+ fields: [
+ {name: 'id', type: ALL_FIELD_TYPES.string},
+ {name: 'city', type: ALL_FIELD_TYPES.string}
+ ],
+ rows: [
+ ['1', 'sf'],
+ ['2', null],
+ ['3', 'nyc']
+ ]
+ });
+ const right = makeTable({
+ id: 'cities',
+ fields: [
+ {name: 'city', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ ['sf', 100],
+ ['la', 50]
+ ]
+ });
+
+ const leftJoin = joinDatasets(left, right, {
+ leftField: 'city',
+ rightField: 'city',
+ type: 'LEFT',
+ resultId: 'left-join'
+ });
+ expect(leftJoin.data.rows).toHaveLength(3);
+ expect(leftJoin.data.rows[0][3]).toBe(100);
+ expect(leftJoin.data.rows[1][3]).toBeNull();
+ expect(leftJoin.data.rows[2][3]).toBeNull();
+
+ const innerJoin = joinDatasets(left, right, {
+ leftField: 'city',
+ rightField: 'city',
+ type: 'INNER'
+ });
+ expect(innerJoin.data.rows).toHaveLength(1);
+ expect(innerJoin.data.rows[0][0]).toBe('1');
+
+ const fullJoin = joinDatasets(left, right, {
+ leftField: 'city',
+ rightField: 'city',
+ type: 'FULL'
+ });
+ expect(fullJoin.data.rows).toHaveLength(4);
+ expect(fullJoin.data.rows.some(row => row[0] === null && row[3] === 50)).toBe(true);
+ expect(fullJoin.metadata.derivedDataset.type).toBe('join');
+ expect(fullJoin.metadata.derivedDataset.sourceDataIds).toEqual(['orders', 'cities']);
+ });
+
+ test('joinDatasets leftColumns and rightColumns omit unselected fields', () => {
+ const left = makeTable({
+ id: 'orders',
+ fields: [
+ {name: 'id', type: ALL_FIELD_TYPES.string},
+ {name: 'city', type: ALL_FIELD_TYPES.string}
+ ],
+ rows: [['1', 'sf']]
+ });
+ const right = makeTable({
+ id: 'cities',
+ fields: [
+ {name: 'city', type: ALL_FIELD_TYPES.string},
+ {name: 'pop', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [['sf', 100]]
+ });
+
+ const result = joinDatasets(left, right, {
+ leftField: 'city',
+ rightField: 'city',
+ type: 'LEFT',
+ leftColumns: ['city'],
+ rightColumns: []
+ });
+ expect(result.data.fields.map(field => field.name)).toEqual(['city']);
+ expect(result.data.rows[0]).toEqual(['sf']);
+ });
+
+ test('spatialJoinDatasets joins points contained by polygons', () => {
+ const polygons = makeTable({
+ id: 'polys',
+ fields: [
+ {name: 'name', type: ALL_FIELD_TYPES.string},
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson}
+ ],
+ rows: [
+ ['west', square(-10, -10, 10, 10)],
+ ['east', square(20, -10, 40, 10)]
+ ]
+ });
+ const points = makeTable({
+ id: 'pts',
+ fields: [
+ {name: 'lat', type: ALL_FIELD_TYPES.real},
+ {name: 'lng', type: ALL_FIELD_TYPES.real},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ [0, 0, 10],
+ [0, 30, 5],
+ [50, 50, 99]
+ ]
+ });
+
+ const result = spatialJoinDatasets(polygons, points, {
+ leftGeo: {kind: 'geojson', fieldName: 'geom'},
+ rightGeo: {kind: 'latlng', latField: 'lat', lngField: 'lng'},
+ aggregations: {value: DATASET_OPS_AGGREGATIONS.sum},
+ resultId: 'pip'
+ });
+
+ expect(result.data.rows).toHaveLength(2);
+ expect(result.data.rows[0][2]).toBe(1);
+ expect(result.data.rows[0][3]).toBe(10);
+ expect(result.data.rows[1][2]).toBe(1);
+ expect(result.data.rows[1][3]).toBe(5);
+ expect(result.metadata.derivedDataset.type).toBe('spatialJoin');
+ });
+
+ test('spatialJoinDatasets leftColumns omits unselected attributes and keeps geometry', () => {
+ const polygons = makeTable({
+ id: 'polys',
+ fields: [
+ {name: 'name', type: ALL_FIELD_TYPES.string},
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson}
+ ],
+ rows: [['west', square(-10, -10, 10, 10)]]
+ });
+ const points = makeTable({
+ id: 'pts',
+ fields: [
+ {name: 'lat', type: ALL_FIELD_TYPES.real},
+ {name: 'lng', type: ALL_FIELD_TYPES.real},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [[0, 0, 10]]
+ });
+
+ const result = spatialJoinDatasets(polygons, points, {
+ leftGeo: {kind: 'geojson', fieldName: 'geom'},
+ rightGeo: {kind: 'latlng', latField: 'lat', lngField: 'lng'},
+ aggregations: {value: DATASET_OPS_AGGREGATIONS.sum},
+ leftColumns: []
+ });
+
+ expect(result.data.fields.map(field => field.name)).toEqual(['geom', 'count', 'value_sum']);
+ expect(result.data.rows[0]).toHaveLength(3);
+ });
+
+ test('spatialJoinDatasets joins points contained by H3 cells', () => {
+ const cell = latLngToCell(37.77, -122.42, 8);
+ const hexes = makeTable({
+ id: 'hexes',
+ fields: [
+ {name: 'hex', type: ALL_FIELD_TYPES.h3},
+ {name: 'label', type: ALL_FIELD_TYPES.string}
+ ],
+ rows: [[cell, 'sf']]
+ });
+ const points = makeTable({
+ id: 'pts',
+ fields: [
+ {name: 'lat', type: ALL_FIELD_TYPES.real},
+ {name: 'lng', type: ALL_FIELD_TYPES.real},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ [37.77, -122.42, 3],
+ [0, 0, 1]
+ ]
+ });
+
+ const result = spatialJoinDatasets(hexes, points, {
+ leftGeo: {kind: 'h3', fieldName: 'hex'},
+ rightGeo: {kind: 'latlng', latField: 'lat', lngField: 'lng'},
+ aggregations: {value: DATASET_OPS_AGGREGATIONS.sum}
+ });
+
+ expect(result.data.rows[0][2]).toBe(1);
+ expect(result.data.rows[0][3]).toBe(3);
+ });
+
+ test('spatialJoinDatasets joins polygons whose centroid is inside the left polygon', () => {
+ const left = makeTable({
+ id: 'outer',
+ fields: [{name: 'geom', type: ALL_FIELD_TYPES.geojson}],
+ rows: [[square(-10, -10, 10, 10)]]
+ });
+ const right = makeTable({
+ id: 'inner',
+ fields: [
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ [square(-1, -1, 1, 1), 4],
+ [square(40, 40, 50, 50), 8]
+ ]
+ });
+
+ const result = spatialJoinDatasets(left, right, {
+ leftGeo: {kind: 'geojson', fieldName: 'geom'},
+ rightGeo: {kind: 'geojson', fieldName: 'geom'},
+ aggregations: {value: DATASET_OPS_AGGREGATIONS.sum}
+ });
+
+ expect(result.data.rows[0][1]).toBe(1);
+ expect(result.data.rows[0][2]).toBe(4);
+ });
+
+ test('spatialJoinDatasets intersects overlapping polygons and not disjoint ones', () => {
+ const left = makeTable({
+ id: 'left',
+ fields: [{name: 'geom', type: ALL_FIELD_TYPES.geojson}],
+ rows: [[square(-10, -10, 10, 10)]]
+ });
+ const right = makeTable({
+ id: 'right',
+ fields: [
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [
+ [square(0, 0, 20, 20), 3],
+ [square(40, 40, 50, 50), 9]
+ ]
+ });
+
+ const result = spatialJoinDatasets(left, right, {
+ leftGeo: {kind: 'geojson', fieldName: 'geom'},
+ rightGeo: {kind: 'geojson', fieldName: 'geom'},
+ aggregations: {value: DATASET_OPS_AGGREGATIONS.sum},
+ predicate: 'intersects'
+ });
+
+ expect(result.data.rows[0][1]).toBe(1);
+ expect(result.data.rows[0][2]).toBe(3);
+ });
+
+ test('spatialJoinDatasets within matches when the target is inside the join geometry', () => {
+ const inner = makeTable({
+ id: 'inner',
+ fields: [{name: 'geom', type: ALL_FIELD_TYPES.geojson}],
+ rows: [[square(-1, -1, 1, 1)]]
+ });
+ const outer = makeTable({
+ id: 'outer',
+ fields: [
+ {name: 'geom', type: ALL_FIELD_TYPES.geojson},
+ {name: 'value', type: ALL_FIELD_TYPES.integer}
+ ],
+ rows: [[square(-10, -10, 10, 10), 7]]
+ });
+
+ const result = spatialJoinDatasets(inner, outer, {
+ leftGeo: {kind: 'geojson', fieldName: 'geom'},
+ rightGeo: {kind: 'geojson', fieldName: 'geom'},
+ aggregations: {value: DATASET_OPS_AGGREGATIONS.sum},
+ predicate: 'within'
+ });
+
+ expect(result.data.rows[0][1]).toBe(1);
+ expect(result.data.rows[0][2]).toBe(7);
+ });
+
+ test('isTabularDatasetForOps skips tiles and disabled datasets', () => {
+ expect(isTabularDatasetForOps({type: 'local'})).toBe(true);
+ expect(isTabularDatasetForOps({type: ''})).toBe(true);
+ expect(isTabularDatasetForOps({type: 'vector-tile'})).toBe(false);
+ expect(isTabularDatasetForOps({type: 'local', disableDataOperation: true})).toBe(false);
+ });
+
+ test('aggregation options depend on field type', () => {
+ const ids = (type: string) => aggregationOptionsForField({type}).map(option => option.id);
+
+ expect(ids(ALL_FIELD_TYPES.integer)).toEqual([
+ 'count',
+ 'sum',
+ 'average',
+ 'maximum',
+ 'minimum',
+ 'median',
+ 'countUnique'
+ ]);
+ expect(ids(ALL_FIELD_TYPES.boolean)).toEqual(['count', 'sum', 'average', 'countUnique']);
+ expect(ids(ALL_FIELD_TYPES.string)).toEqual(['count', 'countUnique']);
+ expect(ids(ALL_FIELD_TYPES.timestamp)).toEqual(['count', 'maximum', 'minimum', 'countUnique']);
+ expect(ids(ALL_FIELD_TYPES.geojson)).toEqual(['merge', 'count', 'countUnique']);
+ expect(isDatasetOpsAggregationField({type: ALL_FIELD_TYPES.real})).toBe(true);
+ expect(isDatasetOpsAggregationField({type: ALL_FIELD_TYPES.boolean})).toBe(true);
+ expect(isDatasetOpsAggregationField({type: ALL_FIELD_TYPES.geojson})).toBe(true);
+ expect(
+ defaultAggregationsForFields([{name: 'geom', type: ALL_FIELD_TYPES.geojson} as any])
+ ).toEqual({geom: 'merge'});
+ });
+});
diff --git a/src/table/src/dataset-ops/aggregations.ts b/src/table/src/dataset-ops/aggregations.ts
new file mode 100644
index 000000000..ba9b94bca
--- /dev/null
+++ b/src/table/src/dataset-ops/aggregations.ts
@@ -0,0 +1,138 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {Field} from '@kepler.gl/types';
+import {aggregate} from '@kepler.gl/utils';
+import {notNullorUndefined} from '@kepler.gl/common-utils';
+
+import {DATASET_OPS_AGGREGATIONS, DatasetOpAggregation} from './types';
+import {mergeGeometries} from './geometry';
+
+export const DATASET_OPS_AGGREGATION_OPTIONS: {id: DatasetOpAggregation; labelId: string}[] = [
+ {id: DATASET_OPS_AGGREGATIONS.merge, labelId: 'datasetOps.aggregation.merge'},
+ {id: DATASET_OPS_AGGREGATIONS.count, labelId: 'datasetOps.aggregation.count'},
+ {id: DATASET_OPS_AGGREGATIONS.sum, labelId: 'datasetOps.aggregation.sum'},
+ {id: DATASET_OPS_AGGREGATIONS.average, labelId: 'datasetOps.aggregation.average'},
+ {id: DATASET_OPS_AGGREGATIONS.maximum, labelId: 'datasetOps.aggregation.maximum'},
+ {id: DATASET_OPS_AGGREGATIONS.minimum, labelId: 'datasetOps.aggregation.minimum'},
+ {id: DATASET_OPS_AGGREGATIONS.median, labelId: 'datasetOps.aggregation.median'},
+ {id: DATASET_OPS_AGGREGATIONS.countUnique, labelId: 'datasetOps.aggregation.countUnique'}
+];
+
+const NUMERIC_FIELD_TYPES = new Set<string>([ALL_FIELD_TYPES.integer, ALL_FIELD_TYPES.real]);
+const CATEGORICAL_FIELD_TYPES = new Set<string>([ALL_FIELD_TYPES.string, ALL_FIELD_TYPES.h3]);
+const TIME_FIELD_TYPES = new Set<string>([ALL_FIELD_TYPES.timestamp, ALL_FIELD_TYPES.date]);
+
+export function aggregationIdsForFieldType(type?: string): DatasetOpAggregation[] {
+ if (type && NUMERIC_FIELD_TYPES.has(type)) {
+ return [
+ DATASET_OPS_AGGREGATIONS.count,
+ DATASET_OPS_AGGREGATIONS.sum,
+ DATASET_OPS_AGGREGATIONS.average,
+ DATASET_OPS_AGGREGATIONS.maximum,
+ DATASET_OPS_AGGREGATIONS.minimum,
+ DATASET_OPS_AGGREGATIONS.median,
+ DATASET_OPS_AGGREGATIONS.countUnique
+ ];
+ }
+ if (type === ALL_FIELD_TYPES.boolean) {
+ return [
+ DATASET_OPS_AGGREGATIONS.count,
+ DATASET_OPS_AGGREGATIONS.sum,
+ DATASET_OPS_AGGREGATIONS.average,
+ DATASET_OPS_AGGREGATIONS.countUnique
+ ];
+ }
+ if (type && TIME_FIELD_TYPES.has(type)) {
+ return [
+ DATASET_OPS_AGGREGATIONS.count,
+ DATASET_OPS_AGGREGATIONS.maximum,
+ DATASET_OPS_AGGREGATIONS.minimum,
+ DATASET_OPS_AGGREGATIONS.countUnique
+ ];
+ }
+ if (type && CATEGORICAL_FIELD_TYPES.has(type)) {
+ return [DATASET_OPS_AGGREGATIONS.count, DATASET_OPS_AGGREGATIONS.countUnique];
+ }
+ if (type === ALL_FIELD_TYPES.geojson || type === ALL_FIELD_TYPES.point) {
+ return [
+ DATASET_OPS_AGGREGATIONS.merge,
+ DATASET_OPS_AGGREGATIONS.count,
+ DATASET_OPS_AGGREGATIONS.countUnique
+ ];
+ }
+ return [DATASET_OPS_AGGREGATIONS.count];
+}
+
+export function aggregationOptionsForField(field: {
+ type?: string;
+}): typeof DATASET_OPS_AGGREGATION_OPTIONS {
+ const allowed = new Set(aggregationIdsForFieldType(field.type));
+ return DATASET_OPS_AGGREGATION_OPTIONS.filter(option => allowed.has(option.id));
+}
+
+export function isDatasetOpsAggregationField(field: {type?: string}): boolean {
+ return aggregationIdsForFieldType(field.type).length > 1;
+}
+
+export function defaultAggregationForField(field: Field): DatasetOpAggregation {
+ const allowed = aggregationIdsForFieldType(field.type);
+ if (field.type === ALL_FIELD_TYPES.integer || field.type === ALL_FIELD_TYPES.real) {
+ return DATASET_OPS_AGGREGATIONS.average;
+ }
+ if (field.type === ALL_FIELD_TYPES.string || field.type === ALL_FIELD_TYPES.h3) {
+ return DATASET_OPS_AGGREGATIONS.countUnique;
+ }
+ if (field.type === ALL_FIELD_TYPES.geojson || field.type === ALL_FIELD_TYPES.point) {
+ return DATASET_OPS_AGGREGATIONS.merge;
+ }
+ return allowed[0];
+}
+
+export function defaultAggregationsForFields(
+ fields: Field[],
+ excludeNames: string[] = []
+): Record<string, DatasetOpAggregation> {
+ const excluded = new Set(excludeNames);
+ const aggregations: Record<string, DatasetOpAggregation> = {};
+ fields.forEach(field => {
+ if (!excluded.has(field.name) && isDatasetOpsAggregationField(field)) {
+ aggregations[field.name] = defaultAggregationForField(field);
+ }
+ });
+ return aggregations;
+}
+
+export function aggregateValues(values: unknown[], technique: DatasetOpAggregation): unknown {
+ if (technique === DATASET_OPS_AGGREGATIONS.merge) {
+ return mergeGeometries(values);
+ }
+ const defined = values.filter(notNullorUndefined);
+ if (technique === DATASET_OPS_AGGREGATIONS.count) {
+ return values.length;
+ }
+ if (!defined.length) {
+ return null;
+ }
+ return aggregate(defined, technique);
+}
+
+export function resultFieldType(technique: DatasetOpAggregation, sourceType?: string): string {
+ if (technique === DATASET_OPS_AGGREGATIONS.merge) {
+ return ALL_FIELD_TYPES.geojson;
+ }
+ if (
+ technique === DATASET_OPS_AGGREGATIONS.count ||
+ technique === DATASET_OPS_AGGREGATIONS.countUnique
+ ) {
+ return ALL_FIELD_TYPES.integer;
+ }
+ if (
+ technique === DATASET_OPS_AGGREGATIONS.average ||
+ technique === DATASET_OPS_AGGREGATIONS.median
+ ) {
+ return ALL_FIELD_TYPES.real;
+ }
+ return sourceType || ALL_FIELD_TYPES.real;
+}
diff --git a/src/table/src/dataset-ops/geometry.ts b/src/table/src/dataset-ops/geometry.ts
new file mode 100644
index 000000000..bd032f60c
--- /dev/null
+++ b/src/table/src/dataset-ops/geometry.ts
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {cellToParent, h3GetResolution, h3IsValid, latLngToCell} from '@kepler.gl/common-utils';
+import {isInPolygon} from '@kepler.gl/utils';
+import type {Feature, Geometry, Position} from 'geojson';
+
+function isLngLat(pos: unknown): pos is Position {
+ return (
+ Array.isArray(pos) &&
+ pos.length >= 2 &&
+ Number.isFinite(Number(pos[0])) &&
+ Number.isFinite(Number(pos[1]))
+ );
+}
+
+function collectPositions(node: unknown, out: number[][]): void {
+ if (isLngLat(node)) {
+ out.push([Number(node[0]), Number(node[1])]);
+ return;
+ }
+ if (Array.isArray(node)) {
+ for (const child of node) {
+ collectPositions(child, out);
+ }
+ }
+}
+
+export function parseGeometry(raw: unknown): Feature | null {
+ if (raw == null) {
+ return null;
+ }
+ if (typeof raw === 'string') {
+ try {
+ return parseGeometry(JSON.parse(raw));
+ } catch {
+ return null;
+ }
+ }
+ if (isLngLat(raw)) {
+ return {
+ type: 'Feature',
+ geometry: {type: 'Point', coordinates: [Number(raw[0]), Number(raw[1])]},
+ properties: {}
+ };
+ }
+ if (typeof raw !== 'object') {
+ return null;
+ }
+ const value = raw as {type?: string; geometry?: Geometry; coordinates?: unknown};
+ if (value.type === 'Feature' && value.geometry) {
+ return raw as Feature;
+ }
+ if (value.type && value.coordinates) {
+ return {type: 'Feature', geometry: raw as Geometry, properties: {}};
+ }
+ return null;
+}
+
+export function getLngLat(feature: Feature | null): [number, number] | null {
+ if (!feature?.geometry) {
+ return null;
+ }
+ if (feature.geometry.type === 'Point' && isLngLat(feature.geometry.coordinates)) {
+ return [Number(feature.geometry.coordinates[0]), Number(feature.geometry.coordinates[1])];
+ }
+ return getCentroidLngLat(feature);
+}
+
+function asFeature(geometry: Geometry): Feature {
+ return {type: 'Feature', geometry, properties: {}};
+}
+
+function flattenGeometry(geometry: Geometry): Geometry[] {
+ if (geometry.type === 'GeometryCollection') {
+ return geometry.geometries.flatMap(flattenGeometry);
+ }
+ return [geometry];
+}
+
+/**
+ * Combine geometries in a group into one GeoJSON Feature so the result stays mappable.
+ * Same-type inputs become Multi* geometries; mixed types become a GeometryCollection.
+ */
+export function mergeGeometries(values: unknown[]): Feature | null {
+ const geometries = values
+ .map(value => parseGeometry(value)?.geometry)
+ .filter((geometry): geometry is Geometry => Boolean(geometry))
+ .flatMap(flattenGeometry);
+ if (!geometries.length) {
+ return null;
+ }
+ if (geometries.length === 1) {
+ return asFeature(geometries[0]);
+ }
+
+ const type = geometries[0].type;
+ const sameType = geometries.every(geometry => geometry.type === type);
+ if (sameType && type === 'Polygon') {
+ return asFeature({
+ type: 'MultiPolygon',
+ coordinates: geometries.map(
+ geometry => (geometry as Geometry & {type: 'Polygon'}).coordinates
+ )
+ });
+ }
+ if (sameType && type === 'MultiPolygon') {
+ return asFeature({
+ type: 'MultiPolygon',
+ coordinates: geometries.flatMap(
+ geometry => (geometry as Geometry & {type: 'MultiPolygon'}).coordinates
+ )
+ });
+ }
+ if (sameType && type === 'Point') {
+ return asFeature({
+ type: 'MultiPoint',
+ coordinates: geometries.map(geometry => (geometry as Geometry & {type: 'Point'}).coordinates)
+ });
+ }
+ if (sameType && type === 'MultiPoint') {
+ return asFeature({
+ type: 'MultiPoint',
+ coordinates: geometries.flatMap(
+ geometry => (geometry as Geometry & {type: 'MultiPoint'}).coordinates
+ )
+ });
+ }
+ if (sameType && type === 'LineString') {
+ return asFeature({
+ type: 'MultiLineString',
+ coordinates: geometries.map(
+ geometry => (geometry as Geometry & {type: 'LineString'}).coordinates
+ )
+ });
+ }
+ if (sameType && type === 'MultiLineString') {
+ return asFeature({
+ type: 'MultiLineString',
+ coordinates: geometries.flatMap(
+ geometry => (geometry as Geometry & {type: 'MultiLineString'}).coordinates
+ )
+ });
+ }
+ return asFeature({type: 'GeometryCollection', geometries});
+}
+
+export function getCentroidLngLat(feature: Feature | null): [number, number] | null {
+ const geometry = feature?.geometry;
+ if (!geometry || geometry.type === 'GeometryCollection') {
+ return null;
+ }
+ const positions: number[][] = [];
+ collectPositions((geometry as {coordinates: unknown}).coordinates, positions);
+ if (!positions.length) {
+ return null;
+ }
+ let sumLng = 0;
+ let sumLat = 0;
+ for (const pos of positions) {
+ sumLng += pos[0];
+ sumLat += pos[1];
+ }
+ return [sumLng / positions.length, sumLat / positions.length];
+}
+
+export function isPolygonFeature(feature: Feature | null): boolean {
+ const type = feature?.geometry?.type;
+ return type === 'Polygon' || type === 'MultiPolygon';
+}
+
+export function polygonContainsPoint(polygon: Feature, lngLat: [number, number]): boolean {
+ return isInPolygon(lngLat, polygon);
+}
+
+export function h3ContainsPoint(h3Index: unknown, lngLat: [number, number]): boolean {
+ if (!h3IsValid(String(h3Index))) {
+ return false;
+ }
+ const cell = String(h3Index);
+ const resolution = h3GetResolution(cell);
+ return latLngToCell(lngLat[1], lngLat[0], resolution) === cell;
+}
+
+export function h3ContainsH3(leftIndex: unknown, rightIndex: unknown): boolean {
+ const left = String(leftIndex);
+ const right = String(rightIndex);
+ if (!h3IsValid(left) || !h3IsValid(right)) {
+ return false;
+ }
+ if (left === right) {
+ return true;
+ }
+ const leftRes = h3GetResolution(left);
+ const rightRes = h3GetResolution(right);
+ if (rightRes <= leftRes) {
+ return false;
+ }
+ return cellToParent(right, leftRes) === left;
+}
diff --git a/src/table/src/dataset-ops/group-by.ts b/src/table/src/dataset-ops/group-by.ts
new file mode 100644
index 000000000..305ef2e05
--- /dev/null
+++ b/src/table/src/dataset-ops/group-by.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {generateHashId} from '@kepler.gl/common-utils';
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {ProtoDataset} from '@kepler.gl/types';
+
+import {aggregateValues, resultFieldType} from './aggregations';
+import {copyFieldAs, makeResultProtoDataset, uniqueColumnName} from './proto-dataset';
+import {findFieldByName, rowCount, rowValue} from './table-helpers';
+import {DatasetOpsTable, GroupByDatasetConfig} from './types';
+
+const NULL_GROUP_KEY = Symbol('dataset-ops-null-group');
+
+function groupMapKey(key: unknown): string | symbol {
+ return key === null || key === undefined ? NULL_GROUP_KEY : String(key);
+}
+
+export function groupByDataset(
+ dataset: DatasetOpsTable,
+ config: GroupByDatasetConfig
+): ProtoDataset {
+ const groupField = findFieldByName(dataset.fields, config.fieldName);
+ if (!groupField) {
+ throw new Error(`Group-by field "${config.fieldName}" was not found`);
+ }
+
+ const aggregationEntries = Object.entries(config.aggregations).filter(
+ ([fieldName]) => fieldName !== groupField.name
+ );
+ const grouped = new Map<string | symbol, {key: unknown; indexes: number[]}>();
+ const n = rowCount(dataset);
+
+ for (let i = 0; i < n; i++) {
+ const key = rowValue(dataset, i, groupField);
+ const mapKey = groupMapKey(key);
+ const existing = grouped.get(mapKey);
+ if (existing) {
+ existing.indexes.push(i);
+ } else {
+ grouped.set(mapKey, {key: key ?? null, indexes: [i]});
+ }
+ }
+
+ const usedNames = new Set<string>();
+ const fields = [copyFieldAs(groupField, uniqueColumnName(groupField.name, usedNames))];
+ const aggMeta = aggregationEntries.map(([fieldName, technique]) => {
+ const sourceField = findFieldByName(dataset.fields, fieldName);
+ if (!sourceField) {
+ throw new Error(`Aggregation field "${fieldName}" was not found`);
+ }
+ const name = uniqueColumnName(`${fieldName}_${technique}`, usedNames);
+ fields.push({
+ name,
+ type: resultFieldType(technique, sourceField.type),
+ analyzerType:
+ technique === 'count' || technique === 'countUnique'
+ ? ALL_FIELD_TYPES.integer
+ : sourceField.analyzerType || sourceField.type
+ });
+ return {sourceField, technique};
+ });
+
+ const rows = Array.from(grouped.values()).map(({key, indexes}) => {
+ const row: unknown[] = [key];
+ for (const {sourceField, technique} of aggMeta) {
+ const values = indexes.map(index => rowValue(dataset, index, sourceField));
+ row.push(aggregateValues(values, technique));
+ }
+ return row;
+ });
+
+ return makeResultProtoDataset({
+ source: dataset,
+ type: 'groupBy',
+ operationId: config.operationId || generateHashId(6),
+ label: config.label || `group-by-${config.resultId || generateHashId(6)}`,
+ resultId: config.resultId,
+ fields,
+ rows
+ });
+}
diff --git a/src/table/src/dataset-ops/index.ts b/src/table/src/dataset-ops/index.ts
new file mode 100644
index 000000000..8a4f54661
--- /dev/null
+++ b/src/table/src/dataset-ops/index.ts
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export * from './types';
+export * from './aggregations';
+export * from './geometry';
+export * from './table-helpers';
+export * from './group-by';
+export * from './join';
+export * from './spatial-join';
+export {makeResultProtoDataset} from './proto-dataset';
+
+import {groupByDataset} from './group-by';
+import {joinDatasets} from './join';
+import {spatialJoinDatasets} from './spatial-join';
+import {DatasetOpsEngine} from './types';
+
+export const inMemoryDatasetOpsEngine: DatasetOpsEngine = {
+ groupByDataset,
+ joinDatasets,
+ spatialJoinDatasets
+};
diff --git a/src/table/src/dataset-ops/join.ts b/src/table/src/dataset-ops/join.ts
new file mode 100644
index 000000000..3e323036c
--- /dev/null
+++ b/src/table/src/dataset-ops/join.ts
@@ -0,0 +1,111 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {generateHashId} from '@kepler.gl/common-utils';
+import {ProtoDataset} from '@kepler.gl/types';
+
+import {copyFieldAs, makeResultProtoDataset, uniqueColumnName} from './proto-dataset';
+import {findFieldByName, rowCount, rowValue} from './table-helpers';
+import {DatasetOpsTable, JoinDatasetConfig} from './types';
+
+function joinKey(value: unknown): string | null {
+ if (value === null || value === undefined || value === '') {
+ return null;
+ }
+ return String(value);
+}
+
+export function joinDatasets(
+ left: DatasetOpsTable,
+ right: DatasetOpsTable,
+ config: JoinDatasetConfig
+): ProtoDataset {
+ const leftField = findFieldByName(left.fields, config.leftField);
+ const rightField = findFieldByName(right.fields, config.rightField);
+ if (!leftField || !rightField) {
+ throw new Error('Join key fields were not found on both datasets');
+ }
+
+ const leftColumnNames =
+ config.leftColumns === undefined ? left.fields.map(f => f.name) : config.leftColumns;
+ const rightColumnNames =
+ config.rightColumns === undefined ? right.fields.map(f => f.name) : config.rightColumns;
+ const leftColumns = leftColumnNames
+ .map(name => findFieldByName(left.fields, name))
+ .filter((field): field is NonNullable<typeof field> => Boolean(field));
+ const rightColumns = rightColumnNames
+ .map(name => findFieldByName(right.fields, name))
+ .filter((field): field is NonNullable<typeof field> => Boolean(field));
+
+ const usedNames = new Set<string>();
+ const fields = [
+ ...leftColumns.map(field => copyFieldAs(field, uniqueColumnName(field.name, usedNames))),
+ ...rightColumns.map(field =>
+ copyFieldAs(field, uniqueColumnName(`${right.label}_${field.name}`, usedNames))
+ )
+ ];
+
+ const rightByKey = new Map<string, number[]>();
+ const nRight = rowCount(right);
+ for (let i = 0; i < nRight; i++) {
+ const key = joinKey(rowValue(right, i, rightField));
+ if (key === null) {
+ continue;
+ }
+ const indexes = rightByKey.get(key);
+ if (indexes) {
+ indexes.push(i);
+ } else {
+ rightByKey.set(key, [i]);
+ }
+ }
+
+ const matchedRight = new Set<number>();
+ const rows: unknown[][] = [];
+ const nLeft = rowCount(left);
+
+ const pushRow = (leftIndex: number | null, rightIndex: number | null) => {
+ const row: unknown[] = [];
+ for (const field of leftColumns) {
+ row.push(leftIndex === null ? null : rowValue(left, leftIndex, field));
+ }
+ for (const field of rightColumns) {
+ row.push(rightIndex === null ? null : rowValue(right, rightIndex, field));
+ }
+ rows.push(row);
+ };
+
+ for (let i = 0; i < nLeft; i++) {
+ const key = joinKey(rowValue(left, i, leftField));
+ const matches = key === null ? undefined : rightByKey.get(key);
+ if (!matches?.length) {
+ if (config.type !== 'INNER') {
+ pushRow(i, null);
+ }
+ continue;
+ }
+ for (const rightIndex of matches) {
+ matchedRight.add(rightIndex);
+ pushRow(i, rightIndex);
+ }
+ }
+
+ if (config.type === 'FULL') {
+ for (let i = 0; i < nRight; i++) {
+ if (!matchedRight.has(i)) {
+ pushRow(null, i);
+ }
+ }
+ }
+
+ return makeResultProtoDataset({
+ source: left,
+ extraSources: [right],
+ type: 'join',
+ operationId: config.operationId || generateHashId(6),
+ label: config.label || `join-dataset-${config.resultId || generateHashId(6)}`,
+ resultId: config.resultId,
+ fields,
+ rows
+ });
+}
diff --git a/src/table/src/dataset-ops/proto-dataset.ts b/src/table/src/dataset-ops/proto-dataset.ts
new file mode 100644
index 000000000..f1e706e9a
--- /dev/null
+++ b/src/table/src/dataset-ops/proto-dataset.ts
@@ -0,0 +1,70 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {generateHashId} from '@kepler.gl/common-utils';
+import {ProtoDataset, ProtoDatasetField} from '@kepler.gl/types';
+
+import {DatasetOpsTable, DerivedDatasetMetadata} from './types';
+
+export function uniqueColumnName(name: string, used: Set<string>): string {
+ if (!used.has(name)) {
+ used.add(name);
+ return name;
+ }
+ let i = 1;
+ let next = `${name}_${i}`;
+ while (used.has(next)) {
+ i += 1;
+ next = `${name}_${i}`;
+ }
+ used.add(next);
+ return next;
+}
+
+export function makeResultProtoDataset({
+ source,
+ extraSources = [],
+ type,
+ operationId,
+ label,
+ resultId,
+ fields,
+ rows
+}: {
+ source: DatasetOpsTable;
+ extraSources?: DatasetOpsTable[];
+ type: DerivedDatasetMetadata['type'];
+ operationId: string;
+ label: string;
+ resultId?: string;
+ fields: ProtoDatasetField[];
+ rows: any[][];
+}): ProtoDataset {
+ const id = resultId || generateHashId(6);
+ return {
+ info: {
+ id,
+ label
+ },
+ data: {fields, rows},
+ metadata: {
+ derivedDataset: {
+ type,
+ sourceDataIds: [source.id, ...extraSources.map(table => table.id)],
+ operationId
+ }
+ }
+ };
+}
+
+export function copyFieldAs(
+ field: {name: string; type: string; analyzerType?: string},
+ name: string
+): ProtoDatasetField {
+ return {
+ name,
+ type: field.type,
+ analyzerType: field.analyzerType || field.type || ALL_FIELD_TYPES.string
+ };
+}
diff --git a/src/table/src/dataset-ops/spatial-join.ts b/src/table/src/dataset-ops/spatial-join.ts
new file mode 100644
index 000000000..f680b333d
--- /dev/null
+++ b/src/table/src/dataset-ops/spatial-join.ts
@@ -0,0 +1,295 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {getCentroid, generateHashId, h3IsValid, idToPolygonGeo} from '@kepler.gl/common-utils';
+import {ALL_FIELD_TYPES} from '@kepler.gl/constants';
+import {Field, ProtoDataset} from '@kepler.gl/types';
+import {booleanCrosses} from '@turf/boolean-crosses';
+import {booleanEqual} from '@turf/boolean-equal';
+import {booleanIntersects} from '@turf/boolean-intersects';
+import {booleanOverlap} from '@turf/boolean-overlap';
+import {booleanTouches} from '@turf/boolean-touches';
+import type {Feature} from 'geojson';
+
+import {aggregateValues, resultFieldType} from './aggregations';
+import {
+ getCentroidLngLat,
+ getLngLat,
+ h3ContainsH3,
+ h3ContainsPoint,
+ isPolygonFeature,
+ parseGeometry,
+ polygonContainsPoint
+} from './geometry';
+import {copyFieldAs, makeResultProtoDataset, uniqueColumnName} from './proto-dataset';
+import {findFieldByName, rowCount, rowValue} from './table-helpers';
+import {
+ DatasetOpsTable,
+ SpatialGeoSource,
+ SpatialJoinDatasetConfig,
+ SpatialJoinPredicate,
+ SPATIAL_JOIN_PREDICATES,
+ fieldNamesForGeoSource
+} from './types';
+
+export type ParsedSpatialValue =
+ | {kind: 'polygon'; feature: NonNullable<ReturnType<typeof parseGeometry>>}
+ | {kind: 'point'; lngLat: [number, number]}
+ | {kind: 'h3'; index: string}
+ | null;
+
+export function suggestSpatialGeo(fields: Field[]): SpatialGeoSource | null {
+ const geojson = fields.find(field => field.type === ALL_FIELD_TYPES.geojson);
+ if (geojson) {
+ return {kind: 'geojson', fieldName: geojson.name};
+ }
+ const h3 = fields.find(field => field.type === ALL_FIELD_TYPES.h3);
+ if (h3) {
+ return {kind: 'h3', fieldName: h3.name};
+ }
+ const lat = fields.find(
+ field =>
+ /lat/i.test(field.name) &&
+ (field.type === ALL_FIELD_TYPES.real || field.type === ALL_FIELD_TYPES.integer)
+ );
+ const lng = fields.find(
+ field =>
+ /(lng|lon|long)/i.test(field.name) &&
+ (field.type === ALL_FIELD_TYPES.real || field.type === ALL_FIELD_TYPES.integer)
+ );
+ if (lat && lng) {
+ return {kind: 'latlng', latField: lat.name, lngField: lng.name};
+ }
+ const point = fields.find(field => field.type === ALL_FIELD_TYPES.point);
+ if (point) {
+ return {kind: 'geojson', fieldName: point.name};
+ }
+ return null;
+}
+
+function readSpatialValue(
+ dataset: DatasetOpsTable,
+ rowIndex: number,
+ geo: SpatialGeoSource
+): ParsedSpatialValue {
+ if (geo.kind === 'latlng') {
+ const latField = findFieldByName(dataset.fields, geo.latField);
+ const lngField = findFieldByName(dataset.fields, geo.lngField);
+ if (!latField || !lngField) {
+ return null;
+ }
+ const lat = Number(rowValue(dataset, rowIndex, latField));
+ const lng = Number(rowValue(dataset, rowIndex, lngField));
+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
+ return null;
+ }
+ return {kind: 'point', lngLat: [lng, lat]};
+ }
+
+ const field = findFieldByName(dataset.fields, geo.fieldName);
+ if (!field) {
+ return null;
+ }
+ const raw = rowValue(dataset, rowIndex, field);
+ if (geo.kind === 'h3') {
+ return h3IsValid(String(raw)) ? {kind: 'h3', index: String(raw)} : null;
+ }
+
+ const feature = parseGeometry(raw);
+ if (!feature) {
+ return null;
+ }
+ if (isPolygonFeature(feature)) {
+ return {kind: 'polygon', feature};
+ }
+ const lngLat = getLngLat(feature);
+ return lngLat ? {kind: 'point', lngLat} : null;
+}
+
+export function leftContainsRight(left: ParsedSpatialValue, right: ParsedSpatialValue): boolean {
+ if (!left || !right) {
+ return false;
+ }
+ if (left.kind === 'polygon' && right.kind === 'point') {
+ return polygonContainsPoint(left.feature, right.lngLat);
+ }
+ if (left.kind === 'polygon' && right.kind === 'polygon') {
+ const centroid = getCentroidLngLat(right.feature);
+ return Boolean(centroid && polygonContainsPoint(left.feature, centroid));
+ }
+ if (left.kind === 'polygon' && right.kind === 'h3') {
+ const centroid = getCentroid({id: right.index});
+ return Boolean(centroid && polygonContainsPoint(left.feature, centroid));
+ }
+ if (left.kind === 'h3' && right.kind === 'point') {
+ return h3ContainsPoint(left.index, right.lngLat);
+ }
+ if (left.kind === 'h3' && right.kind === 'h3') {
+ return h3ContainsH3(left.index, right.index);
+ }
+ if (left.kind === 'h3' && right.kind === 'polygon') {
+ const centroid = getCentroidLngLat(right.feature);
+ return Boolean(centroid && h3ContainsPoint(left.index, centroid));
+ }
+ return false;
+}
+
+function pointFeature(lngLat: [number, number]): Feature {
+ return {
+ type: 'Feature',
+ geometry: {type: 'Point', coordinates: lngLat},
+ properties: {}
+ };
+}
+
+function h3ToPolygonFeature(index: string): Feature | null {
+ const feature = idToPolygonGeo({id: index}, {isClosed: true}) as Feature | null;
+ const ring = feature?.geometry?.type === 'Polygon' ? feature.geometry.coordinates[0] : null;
+ if (!feature || !ring?.length) {
+ return null;
+ }
+ const first = ring[0];
+ const last = ring[ring.length - 1];
+ if (first[0] !== last[0] || first[1] !== last[1]) {
+ ring.push(first);
+ }
+ return feature;
+}
+
+function toFeature(value: ParsedSpatialValue): Feature | null {
+ if (!value) {
+ return null;
+ }
+ if (value.kind === 'polygon') {
+ return value.feature;
+ }
+ if (value.kind === 'point') {
+ return pointFeature(value.lngLat);
+ }
+ return h3ToPolygonFeature(value.index);
+}
+
+function turfMatch(
+ fn: (a: Feature, b: Feature) => boolean,
+ left: ParsedSpatialValue,
+ right: ParsedSpatialValue
+): boolean {
+ const leftFeature = toFeature(left);
+ const rightFeature = toFeature(right);
+ if (!leftFeature || !rightFeature) {
+ return false;
+ }
+ try {
+ return Boolean(fn(leftFeature, rightFeature));
+ } catch {
+ return false;
+ }
+}
+
+export function geometriesMatchPredicate(
+ left: ParsedSpatialValue,
+ right: ParsedSpatialValue,
+ predicate: SpatialJoinPredicate = SPATIAL_JOIN_PREDICATES.intersects
+): boolean {
+ switch (predicate) {
+ case SPATIAL_JOIN_PREDICATES.within:
+ return leftContainsRight(right, left);
+ case SPATIAL_JOIN_PREDICATES.equals:
+ if (left?.kind === 'h3' && right?.kind === 'h3') {
+ return left.index === right.index;
+ }
+ if (left?.kind === 'point' && right?.kind === 'point') {
+ return left.lngLat[0] === right.lngLat[0] && left.lngLat[1] === right.lngLat[1];
+ }
+ return turfMatch(booleanEqual, left, right);
+ case SPATIAL_JOIN_PREDICATES.crosses:
+ return turfMatch(booleanCrosses, left, right);
+ case SPATIAL_JOIN_PREDICATES.overlaps:
+ return turfMatch(booleanOverlap, left, right);
+ case SPATIAL_JOIN_PREDICATES.touches:
+ return turfMatch(booleanTouches, left, right);
+ case SPATIAL_JOIN_PREDICATES.intersects:
+ default:
+ return (
+ leftContainsRight(left, right) ||
+ leftContainsRight(right, left) ||
+ turfMatch(booleanIntersects, left, right)
+ );
+ }
+}
+
+export function spatialJoinDatasets(
+ left: DatasetOpsTable,
+ right: DatasetOpsTable,
+ config: SpatialJoinDatasetConfig
+): ProtoDataset {
+ const nLeft = rowCount(left);
+ const nRight = rowCount(right);
+ const predicate = config.predicate || SPATIAL_JOIN_PREDICATES.intersects;
+ const rightValues = Array.from({length: nRight}, (_, i) =>
+ readSpatialValue(right, i, config.rightGeo)
+ );
+
+ const usedNames = new Set<string>();
+ const geoNames = new Set(fieldNamesForGeoSource(config.leftGeo));
+ const includedLeft =
+ config.leftColumns === undefined
+ ? left.fields
+ : left.fields.filter(
+ field => geoNames.has(field.name) || config.leftColumns?.includes(field.name)
+ );
+ const leftFields = includedLeft.map(field =>
+ copyFieldAs(field, uniqueColumnName(field.name, usedNames))
+ );
+ const aggregationEntries = Object.entries(config.aggregations);
+ const aggMeta = aggregationEntries.map(([fieldName, technique]) => {
+ const sourceField = findFieldByName(right.fields, fieldName);
+ if (!sourceField) {
+ throw new Error(`Spatial join aggregation field "${fieldName}" was not found`);
+ }
+ const name = uniqueColumnName(`${fieldName}_${technique}`, usedNames);
+ return {sourceField, technique, name};
+ });
+
+ const fields = [
+ ...leftFields,
+ {
+ name: uniqueColumnName('count', usedNames),
+ type: ALL_FIELD_TYPES.integer,
+ analyzerType: ALL_FIELD_TYPES.integer
+ },
+ ...aggMeta.map(({name, technique, sourceField}) => ({
+ name,
+ type: resultFieldType(technique, sourceField.type),
+ analyzerType: sourceField.analyzerType || sourceField.type
+ }))
+ ];
+
+ const rows = Array.from({length: nLeft}, (_, leftIndex) => {
+ const leftValue = readSpatialValue(left, leftIndex, config.leftGeo);
+ const matched: number[] = [];
+ for (let rightIndex = 0; rightIndex < nRight; rightIndex++) {
+ if (geometriesMatchPredicate(leftValue, rightValues[rightIndex], predicate)) {
+ matched.push(rightIndex);
+ }
+ }
+ const row: unknown[] = includedLeft.map(field => rowValue(left, leftIndex, field));
+ row.push(matched.length);
+ for (const {sourceField, technique} of aggMeta) {
+ const values = matched.map(index => rowValue(right, index, sourceField));
+ row.push(aggregateValues(values, technique));
+ }
+ return row;
+ });
+
+ return makeResultProtoDataset({
+ source: left,
+ extraSources: [right],
+ type: 'spatialJoin',
+ operationId: config.operationId || generateHashId(6),
+ label: config.label || `spatial-join-${config.resultId || generateHashId(6)}`,
+ resultId: config.resultId,
+ fields,
+ rows
+ });
+}
diff --git a/src/table/src/dataset-ops/table-helpers.ts b/src/table/src/dataset-ops/table-helpers.ts
new file mode 100644
index 000000000..b1982b788
--- /dev/null
+++ b/src/table/src/dataset-ops/table-helpers.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {DatasetType} from '@kepler.gl/constants';
+import {Field} from '@kepler.gl/types';
+
+import {DatasetOpsTable} from './types';
+
+const TABULAR_TYPES = new Set<string>([DatasetType.LOCAL, DatasetType.EXTERNALLY_HOSTED, '']);
+
+export function isTabularDatasetForOps(
+ dataset?: {
+ type?: string;
+ disableDataOperation?: boolean;
+ } | null
+): boolean {
+ if (!dataset || dataset.disableDataOperation) {
+ return false;
+ }
+ const type = dataset.type ?? '';
+ return TABULAR_TYPES.has(type);
+}
+
+export function findFieldByName(
+ fields: Field[],
+ name: string | null | undefined
+): Field | undefined {
+ if (!name) {
+ return undefined;
+ }
+ return fields.find(field => field.name === name);
+}
+
+export function rowValue(dataset: DatasetOpsTable, rowIndex: number, field: Field): unknown {
+ return dataset.dataContainer.valueAt(rowIndex, field.fieldIdx);
+}
+
+export function rowCount(dataset: DatasetOpsTable): number {
+ return dataset.dataContainer.numRows();
+}
diff --git a/src/table/src/dataset-ops/types.ts b/src/table/src/dataset-ops/types.ts
new file mode 100644
index 000000000..d0abd9684
--- /dev/null
+++ b/src/table/src/dataset-ops/types.ts
@@ -0,0 +1,148 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {AGGREGATION_TYPES} from '@kepler.gl/constants';
+import {Field, ProtoDataset, RGBColor} from '@kepler.gl/types';
+import {DataContainerInterface} from '@kepler.gl/utils';
+
+export const DATASET_OPS_AGGREGATIONS = {
+ count: AGGREGATION_TYPES.count,
+ sum: AGGREGATION_TYPES.sum,
+ average: AGGREGATION_TYPES.average,
+ maximum: AGGREGATION_TYPES.maximum,
+ minimum: AGGREGATION_TYPES.minimum,
+ median: AGGREGATION_TYPES.median,
+ countUnique: AGGREGATION_TYPES.countUnique,
+ merge: 'merge'
+} as const;
+
+export type DatasetOpAggregation =
+ (typeof DATASET_OPS_AGGREGATIONS)[keyof typeof DATASET_OPS_AGGREGATIONS];
+
+export type DerivedDatasetType = 'groupBy' | 'join' | 'spatialJoin';
+
+export type DerivedDatasetMetadata = {
+ type: DerivedDatasetType;
+ sourceDataIds: string[];
+ operationId: string;
+};
+
+export type DatasetOpsTable = {
+ id: string;
+ label: string;
+ color: RGBColor;
+ fields: Field[];
+ dataContainer: DataContainerInterface;
+ type?: string;
+ disableDataOperation?: boolean;
+ metadata?: Record<string, any>;
+};
+
+export type GroupByDatasetConfig = {
+ fieldName: string;
+ aggregations: Record<string, DatasetOpAggregation>;
+ label?: string;
+ resultId?: string;
+ operationId?: string;
+};
+
+export type AttributeJoinType = 'LEFT' | 'INNER' | 'FULL';
+
+export type JoinDatasetConfig = {
+ leftField: string;
+ rightField: string;
+ type: AttributeJoinType;
+ leftColumns?: string[];
+ rightColumns?: string[];
+ label?: string;
+ resultId?: string;
+ operationId?: string;
+};
+
+export type SpatialGeoSource =
+ | {kind: 'geojson'; fieldName: string}
+ | {kind: 'h3'; fieldName: string}
+ | {kind: 'latlng'; latField: string; lngField: string};
+
+export function fieldNamesForGeoSource(geo: SpatialGeoSource): string[] {
+ return geo.kind === 'latlng' ? [geo.latField, geo.lngField] : [geo.fieldName];
+}
+
+export const SPATIAL_JOIN_PREDICATES = {
+ intersects: 'intersects',
+ equals: 'equals',
+ crosses: 'crosses',
+ overlaps: 'overlaps',
+ within: 'within',
+ touches: 'touches'
+} as const;
+
+export type SpatialJoinPredicate =
+ (typeof SPATIAL_JOIN_PREDICATES)[keyof typeof SPATIAL_JOIN_PREDICATES];
+
+export const SPATIAL_JOIN_PREDICATE_OPTIONS: {id: SpatialJoinPredicate; labelId: string}[] = [
+ {id: 'intersects', labelId: 'datasetOps.predicateOption.intersects'},
+ {id: 'equals', labelId: 'datasetOps.predicateOption.equals'},
+ {id: 'crosses', labelId: 'datasetOps.predicateOption.crosses'},
+ {id: 'overlaps', labelId: 'datasetOps.predicateOption.overlaps'},
+ {id: 'within', labelId: 'datasetOps.predicateOption.within'},
+ {id: 'touches', labelId: 'datasetOps.predicateOption.touches'}
+];
+
+export type SpatialJoinDatasetConfig = {
+ leftGeo: SpatialGeoSource;
+ rightGeo: SpatialGeoSource;
+ aggregations: Record<string, DatasetOpAggregation>;
+ leftColumns?: string[];
+ predicate?: SpatialJoinPredicate;
+ label?: string;
+ resultId?: string;
+ operationId?: string;
+};
+
+export type GroupByOp = {
+ id: string;
+ dataId: string;
+ fieldName: string | null;
+ aggregations: Record<string, DatasetOpAggregation>;
+ resultId: string;
+ resultLabel: string;
+ isConfigActive: boolean;
+ error?: string | null;
+};
+
+export type JoinImplementation = 'simple' | 'spatial';
+
+export type JoinOp = {
+ id: string;
+ implementation: JoinImplementation;
+ leftDataId: string;
+ rightDataId: string | null;
+ leftField: string | null;
+ rightField: string | null;
+ type: AttributeJoinType;
+ leftColumns?: string[];
+ rightColumns?: string[];
+ leftGeo?: SpatialGeoSource | null;
+ rightGeo?: SpatialGeoSource | null;
+ predicate?: SpatialJoinPredicate;
+ aggregations: Record<string, DatasetOpAggregation>;
+ resultId: string;
+ resultLabel: string;
+ isConfigActive: boolean;
+ error?: string | null;
+};
+
+export type DatasetOpsEngine = {
+ groupByDataset: (dataset: DatasetOpsTable, config: GroupByDatasetConfig) => ProtoDataset;
+ joinDatasets: (
+ left: DatasetOpsTable,
+ right: DatasetOpsTable,
+ config: JoinDatasetConfig
+ ) => ProtoDataset;
+ spatialJoinDatasets: (
+ left: DatasetOpsTable,
+ right: DatasetOpsTable,
+ config: SpatialJoinDatasetConfig
+ ) => ProtoDataset;
+};
diff --git a/src/table/src/index.ts b/src/table/src/index.ts
index c650a5cee..87e2aee87 100644
--- a/src/table/src/index.ts
+++ b/src/table/src/index.ts
@@ -27,3 +27,4 @@ export * from './tileset/wms-utils';
export * from './tileset/tileset-utils';
export * from './tileset/vector-tile-utils';
export * from './tileset/raster-tile-utils';
+export * from './dataset-ops';
diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.ts
index 69c6c171b..dacd83778 100644
--- a/src/types/schemas.d.ts
+++ b/src/types/schemas.d.ts
@@ -113,6 +113,8 @@ export type SavedVisState = {
animationConfig: SavedAnimationConfig;
editor?: SavedEditor;
layerOrder?: any[];
+ groupBys?: any[];
+ joins?: any[];
};
// Min saved config can be passed to addDataToMap
@@ -140,6 +142,8 @@ export type ParsedVisState = {
splitMaps?: SplitMap[];
animationConfig?: Partial<SavedAnimationConfig>;
layerOrder?: any[];
+ groupBys?: any[];
+ joins?: any[];
};
export type ParsedUiState = {
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 5d7e6b01e..dce81d84b 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -226,6 +226,9 @@ export type KeplerApplicationConfig = {
/** Whether to show column statistics in the data table modal. Enabled by default. */
enableColumnStats?: boolean;
+ /** Group-by, attribute join, and simple spatial join UI on local datasets. Enabled by default. */
+ enableDatasetOps?: boolean;
+
/**
* Whether to show the charts map-control panel (big number, bar, line,
* heatmap, pivot table, tooltip charts, and chart cross-filters).
@@ -432,6 +435,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableColumnStats: true,
+ enableDatasetOps: true,
+
enableChartsPanel: true,
enableJsonEditors: true,
diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.js
index 1c07fd108..f371d2747 100644
--- a/test/node/schemas/vis-state-schema-test.js
+++ b/test/node/schemas/vis-state-schema-test.js
@@ -40,7 +40,9 @@ const expectedVisStateEntries = [
'splitMaps',
'animationConfig',
'editor',
- 'layerOrder'
+ 'layerOrder',
+ 'groupBys',
+ 'joins'
];
test('#visStateSchema -> v1 -> save layers', t => {
diff --git a/yarn.lock b/yarn.lock
index 6738f205b..6d8244d2b 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -4477,6 +4477,11 @@ __metadata:
"@kepler.gl/utils": "npm:3.3.0-alpha.15"
"@loaders.gl/mvt": "npm:^4.4.1"
"@loaders.gl/pmtiles": "npm:^4.4.1"
+ "@turf/boolean-crosses": "npm:^7.2.0"
+ "@turf/boolean-equal": "npm:^7.2.0"
+ "@turf/boolean-intersects": "npm:^7.2.0"
+ "@turf/boolean-overlap": "npm:^7.2.0"
+ "@turf/boolean-touches": "npm:^7.2.0"
"@types/d3-array": "npm:^2.8.0"
d3-array: "npm:^2.8.0"
es-toolkit: "npm:^1.39.10"
@@ -9181,6 +9186,18 @@ __metadata:
languageName: node
linkType: hard
+"@turf/bbox@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/bbox@npm:7.4.0"
+ dependencies:
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/meta": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/3828964cf0d7269a2e63a427420d8ad97237f82389157deaac50e660301ab354178cb2d96a6aa3ce2399ab60d11298a420dbda15a74d1bc21ebfbec0e4aa5793
+ languageName: node
+ linkType: hard
+
"@turf/bbox@npm:^7.2.0":
version: 7.2.0
resolution: "@turf/bbox@npm:7.2.0"
@@ -9227,6 +9244,22 @@ __metadata:
languageName: node
linkType: hard
+"@turf/boolean-crosses@npm:^7.2.0":
+ version: 7.4.0
+ resolution: "@turf/boolean-crosses@npm:7.4.0"
+ dependencies:
+ "@turf/boolean-equal": "npm:7.4.0"
+ "@turf/boolean-point-in-polygon": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@turf/line-intersect": "npm:7.4.0"
+ "@turf/polygon-to-line": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/c438a21ace6aad944ea37bab952bc3844c12fe7a32faf632196632546e61e38818fc0bb92a1629ae436d742701ab0fc9e467dcb97200661a8f9c5b07efa28d2c
+ languageName: node
+ linkType: hard
+
"@turf/boolean-disjoint@npm:7.4.0":
version: 7.4.0
resolution: "@turf/boolean-disjoint@npm:7.4.0"
@@ -9242,6 +9275,20 @@ __metadata:
languageName: node
linkType: hard
+"@turf/boolean-equal@npm:7.4.0, @turf/boolean-equal@npm:^7.2.0":
+ version: 7.4.0
+ resolution: "@turf/boolean-equal@npm:7.4.0"
+ dependencies:
+ "@turf/clean-coords": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ geojson-equality-ts: "npm:^1.0.2"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/afda26b4025bac9c9bbca8389f085faa224775e09891341175c5fc62d970665ff0985eb6fcc9673ad999e58e719095c21350771e12c551352b451c70a5c794de
+ languageName: node
+ linkType: hard
+
"@turf/boolean-intersects@npm:^7.2.0":
version: 7.4.0
resolution: "@turf/boolean-intersects@npm:7.4.0"
@@ -9253,6 +9300,22 @@ __metadata:
languageName: node
linkType: hard
+"@turf/boolean-overlap@npm:^7.2.0":
+ version: 7.4.0
+ resolution: "@turf/boolean-overlap@npm:7.4.0"
+ dependencies:
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@turf/line-intersect": "npm:7.4.0"
+ "@turf/line-overlap": "npm:7.4.0"
+ "@turf/meta": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ geojson-equality-ts: "npm:^1.0.2"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/0abb26cf794e534f4e9e3400a147ada0dea30d357646acf8bcbb15216444caca1c6f1bcbce2ce925deb1ffdf1b0cbe0f51c8e56675fcbbc7c7e5ab6267285b27
+ languageName: node
+ linkType: hard
+
"@turf/boolean-point-in-polygon@npm:7.3.4, @turf/boolean-point-in-polygon@npm:^7.2.0":
version: 7.3.4
resolution: "@turf/boolean-point-in-polygon@npm:7.3.4"
@@ -9291,6 +9354,32 @@ __metadata:
languageName: node
linkType: hard
+"@turf/boolean-point-on-line@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/boolean-point-on-line@npm:7.4.0"
+ dependencies:
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/7cb6b6c70e3cea967eccdcb7cfa4c38b0f66450630665e7cc8906ee1f4eb8cfc58ba804d88b5b8768de630ce6059870ee29b6e109e900afd2b88a95984d9e8bd
+ languageName: node
+ linkType: hard
+
+"@turf/boolean-touches@npm:^7.2.0":
+ version: 7.4.0
+ resolution: "@turf/boolean-touches@npm:7.4.0"
+ dependencies:
+ "@turf/boolean-point-in-polygon": "npm:7.4.0"
+ "@turf/boolean-point-on-line": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/5f92f92d3547b9fe063cfeebf4b17d3c6a10d83a327b47ca0c402997fdea8964d3bc0b6843a2cd1f9c92133e08848a566713f5a12db16b069251f550063d853a
+ languageName: node
+ linkType: hard
+
"@turf/boolean-within@npm:^7.2.0":
version: 7.3.4
resolution: "@turf/boolean-within@npm:7.3.4"
@@ -9359,6 +9448,19 @@ __metadata:
languageName: node
linkType: hard
+"@turf/clean-coords@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/clean-coords@npm:7.4.0"
+ dependencies:
+ "@turf/boolean-point-on-line": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/2572c0df64eed37c885bd6b427c169afd8673e2e833ae35f9308f9df34afe21bf5928a064a29466164fd2953e939c13738bf61eb2ff243c7c6d4da0cf5a8497b
+ languageName: node
+ linkType: hard
+
"@turf/clone@npm:7.3.4, @turf/clone@npm:^7.2.0":
version: 7.3.4
resolution: "@turf/clone@npm:7.3.4"
@@ -9416,6 +9518,18 @@ __metadata:
languageName: node
linkType: hard
+"@turf/distance@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/distance@npm:7.4.0"
+ dependencies:
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/0f372ede39894995df9a98383769411b86be1c4f23ca746bf00d138073c464f36e35b40265189a1b3dfc9559592b3b20458389176102a5045c2f67d3cf685227
+ languageName: node
+ linkType: hard
+
"@turf/ellipse@npm:^7.2.0":
version: 7.3.4
resolution: "@turf/ellipse@npm:7.3.4"
@@ -9445,6 +9559,20 @@ __metadata:
languageName: node
linkType: hard
+"@turf/geojson-rbush@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/geojson-rbush@npm:7.4.0"
+ dependencies:
+ "@turf/bbox": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/meta": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ rbush: "npm:^3.0.1"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/a73f4f79c49c10444702dc98b20e75d24312b321b066fc214231f4ce508195c5aea53fa724a8aa0ab2f9ab2ab9927d5fdf35fce80b82fdbf429c406dd4a53d70
+ languageName: node
+ linkType: hard
+
"@turf/helpers@npm:7.3.4":
version: 7.3.4
resolution: "@turf/helpers@npm:7.3.4"
@@ -9571,6 +9699,25 @@ __metadata:
languageName: node
linkType: hard
+"@turf/line-overlap@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/line-overlap@npm:7.4.0"
+ dependencies:
+ "@turf/bbox": "npm:7.4.0"
+ "@turf/boolean-point-on-line": "npm:7.4.0"
+ "@turf/geojson-rbush": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@turf/line-segment": "npm:7.4.0"
+ "@turf/meta": "npm:7.4.0"
+ "@turf/nearest-point-on-line": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ fast-deep-equal: "npm:^3.1.3"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/4dfc8cf8fc30d6a63faf07c254eff149141b2c4a8307bfbc202530ca8b8d0f5f1b7dd46ab439126c391ba7efdf5af87f476dd82e6fb64a5368aee6a9a9f965c5
+ languageName: node
+ linkType: hard
+
"@turf/line-segment@npm:7.3.4":
version: 7.3.4
resolution: "@turf/line-segment@npm:7.3.4"
@@ -9584,6 +9731,19 @@ __metadata:
languageName: node
linkType: hard
+"@turf/line-segment@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/line-segment@npm:7.4.0"
+ dependencies:
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@turf/meta": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/7ea8036858adf78da867242d39bc34533c5d663255fee5bb638fd2729c8c3c0265ef5d763aa6b4f1b806c3f2b3a7223666592a85635d6d981a4e90fbd410ae4a
+ languageName: node
+ linkType: hard
+
"@turf/line-split@npm:7.3.4":
version: 7.3.4
resolution: "@turf/line-split@npm:7.3.4"
@@ -9672,6 +9832,20 @@ __metadata:
languageName: node
linkType: hard
+"@turf/nearest-point-on-line@npm:7.4.0":
+ version: 7.4.0
+ resolution: "@turf/nearest-point-on-line@npm:7.4.0"
+ dependencies:
+ "@turf/distance": "npm:7.4.0"
+ "@turf/helpers": "npm:7.4.0"
+ "@turf/invariant": "npm:7.4.0"
+ "@turf/meta": "npm:7.4.0"
+ "@types/geojson": "npm:^7946.0.10"
+ tslib: "npm:^2.8.1"
+ checksum: 10c0/e610757bbdc83f74830dc3c130d0e5bd20144a1e2a3183264896e6fec83d571e44fc4f38b18cef4bb4be4627a964420b75c9c8e7e13d9e164b067d6ec18d3c23
+ languageName: node
+ linkType: hard
+
"@turf/point-to-line-distance@npm:^7.2.0":
version: 7.3.4
resolution: "@turf/point-to-line-distance@npm:7.3.4"
@@ -18550,6 +18724,15 @@ __metadata:
languageName: node
linkType: hard
+"geojson-equality-ts@npm:^1.0.2":
+ version: 1.0.2
+ resolution: "geojson-equality-ts@npm:1.0.2"
+ dependencies:
+ "@types/geojson": "npm:^7946.0.14"
+ checksum: 10c0/f582c6a549673f238b1eb450511e7be222ded8af039924fd21d03ab201de003a5b1769c44b35ca59406533322165520d7aea77e7e1011722259a1485edb30e24
+ languageName: node
+ linkType: hard
+
"geojson-vt@npm:^3.2.1":
version: 3.2.1
resolution: "geojson-vt@npm:3.2.1"