Skip to content

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

feat: layer groups (#3488)

Igor Dykhtad384cf531840
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index de21eddd4..85fc70228 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -64,6 +64,12 @@ export const ActionTypes = {
REMOVE_LAYER: `${ACTION_PREFIX}REMOVE_LAYER`,
REMOVE_DATASET: `${ACTION_PREFIX}REMOVE_DATASET`,
REORDER_LAYER: `${ACTION_PREFIX}REORDER_LAYER`,
+ ADD_LAYER_GROUP: `${ACTION_PREFIX}ADD_LAYER_GROUP`,
+ REMOVE_LAYER_GROUP: `${ACTION_PREFIX}REMOVE_LAYER_GROUP`,
+ UPDATE_LAYER_GROUP: `${ACTION_PREFIX}UPDATE_LAYER_GROUP`,
+ ADD_LAYER_TO_LAYER_GROUP: `${ACTION_PREFIX}ADD_LAYER_TO_LAYER_GROUP`,
+ REMOVE_LAYER_FROM_LAYER_GROUP: `${ACTION_PREFIX}REMOVE_LAYER_FROM_LAYER_GROUP`,
+ SWAP_LAYER_ORDER_ENTRIES: `${ACTION_PREFIX}SWAP_LAYER_ORDER_ENTRIES`,
SET_FILTER: `${ACTION_PREFIX}SET_FILTER`,
SET_FILTER_ANIMATION_TIME: `${ACTION_PREFIX}SET_FILTER_ANIMATION_TIME`,
SET_FILTER_ANIMATION_TIME_CONFIG: `${ACTION_PREFIX}SET_FILTER_ANIMATION_TIME_CONFIG`,
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 2ad91bb59..1ca0e91ad 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -25,7 +25,9 @@ import {
AnnotationPropsPartial,
SyncTimelineMode,
AnimationConfig,
- FilterAnimationConfig
+ FilterAnimationConfig,
+ LayerOrder,
+ LayerOrderGroup
} from '@kepler.gl/types';
import {createAction} from '@reduxjs/toolkit';
@@ -517,7 +519,7 @@ export function addLayer(
}
export type ReorderLayerUpdaterAction = {
- order: string[];
+ order: LayerOrder;
};
/**
* Reorder layer, order is an array of layer indexes, index 0 will be the one at the bottom
@@ -532,7 +534,7 @@ export type ReorderLayerUpdaterAction = {
* this.props.dispatch(reorderLayer([`layers[1].id`, `layers[0].id`, `layers[2].id`, `layers[3].id`]));
*/
export function reorderLayer(
- order: string[]
+ order: LayerOrder
): Merge<ReorderLayerUpdaterAction, {type: typeof ActionTypes.REORDER_LAYER}> {
return {
type: ActionTypes.REORDER_LAYER,
@@ -540,6 +542,97 @@ export function reorderLayer(
};
}
+export type AddLayerGroupUpdaterAction = {
+ id?: string;
+ label?: string;
+ isVisible?: boolean;
+ layerOrder?: string[];
+ isIncludedInLegend?: boolean;
+};
+
+export function addLayerGroup(
+ payload: AddLayerGroupUpdaterAction
+): Merge<AddLayerGroupUpdaterAction, {type: typeof ActionTypes.ADD_LAYER_GROUP}> {
+ return {
+ type: ActionTypes.ADD_LAYER_GROUP,
+ ...payload
+ };
+}
+
+export type RemoveLayerGroupUpdaterAction = {
+ id: string;
+};
+
+export function removeLayerGroup(
+ payload: RemoveLayerGroupUpdaterAction
+): Merge<RemoveLayerGroupUpdaterAction, {type: typeof ActionTypes.REMOVE_LAYER_GROUP}> {
+ return {
+ type: ActionTypes.REMOVE_LAYER_GROUP,
+ ...payload
+ };
+}
+
+export type UpdateLayerGroupUpdaterAction = {
+ id: string;
+ options: Partial<Omit<LayerOrderGroup, 'id'>>;
+};
+
+export function updateLayerGroup(
+ payload: UpdateLayerGroupUpdaterAction
+): Merge<UpdateLayerGroupUpdaterAction, {type: typeof ActionTypes.UPDATE_LAYER_GROUP}> {
+ return {
+ type: ActionTypes.UPDATE_LAYER_GROUP,
+ ...payload
+ };
+}
+
+export type AddLayerToLayerGroupUpdaterAction = {
+ layerGroupId: string;
+ layerId: string;
+};
+
+export function addLayerToLayerGroup(
+ payload: AddLayerToLayerGroupUpdaterAction
+): Merge<AddLayerToLayerGroupUpdaterAction, {type: typeof ActionTypes.ADD_LAYER_TO_LAYER_GROUP}> {
+ return {
+ type: ActionTypes.ADD_LAYER_TO_LAYER_GROUP,
+ ...payload
+ };
+}
+
+export type RemoveLayerFromLayerGroupUpdaterAction = {
+ layerGroupId: string;
+ layerId: string;
+};
+
+export function removeLayerFromLayerGroup(
+ payload: RemoveLayerFromLayerGroupUpdaterAction
+): Merge<
+ RemoveLayerFromLayerGroupUpdaterAction,
+ {type: typeof ActionTypes.REMOVE_LAYER_FROM_LAYER_GROUP}
+> {
+ return {
+ type: ActionTypes.REMOVE_LAYER_FROM_LAYER_GROUP,
+ ...payload
+ };
+}
+
+export type SwapLayerOrderEntriesUpdaterAction = {
+ originLayerId: string;
+ destinationLayerId?: string;
+ originLayerGroupId?: string;
+ destinationLayerGroupId?: string;
+};
+
+export function swapLayerOrderEntries(
+ payload: SwapLayerOrderEntriesUpdaterAction
+): Merge<SwapLayerOrderEntriesUpdaterAction, {type: typeof ActionTypes.SWAP_LAYER_ORDER_ENTRIES}> {
+ return {
+ type: ActionTypes.SWAP_LAYER_ORDER_ENTRIES,
+ ...payload
+ };
+}
+
export type RemoveFilterUpdaterAction = {
idx: number;
};
diff --git a/src/components/src/common/dnd-layer-items.ts b/src/components/src/common/dnd-layer-items.ts
index ff7111a8a..6d9e6d7a6 100644
--- a/src/components/src/common/dnd-layer-items.ts
+++ b/src/components/src/common/dnd-layer-items.ts
@@ -9,6 +9,11 @@ export const DND_EMPTY_MODIFIERS: Modifiers = [];
export const SORTABLE_SIDE_PANEL_TYPE = 'root';
export const DROPPABLE_MAP_CONTAINER_TYPE = 'map';
export const SORTABLE_LAYER_TYPE = 'layer';
+export const SORTABLE_LAYER_GROUP_TYPE = 'layerGroup';
+export const SORTABLE_LAYER_GROUP_DROPPABLE_TYPE = 'droppable-layer-group';
export const SORTABLE_EFFECT_PANEL_TYPE = 'root';
export const SORTABLE_EFFECT_TYPE = 'effect';
+
+export const SORTABLE_LAYER_END_PLACEHOLDER = '__layer-end-placeholder__';
+export const SORTABLE_LAYER_END_TYPE = 'layer-end-placeholder';
diff --git a/src/components/src/common/icons/folder.tsx b/src/components/src/common/icons/folder.tsx
new file mode 100644
index 000000000..238bf3d7a
--- /dev/null
+++ b/src/components/src/common/icons/folder.tsx
@@ -0,0 +1,27 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class Folder extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ viewBox: '0 0 24 24',
+ predefinedClassName: 'data-ex-icons-folder'
+ };
+
+ render() {
+ return (
+ <Base
+ {...this.props}
+ style={{fill: 'none', stroke: 'currentcolor'}}
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ >
+ <path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z" />
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/icons/index.tsx b/src/components/src/common/icons/index.tsx
index a94d10669..78f1ae1cf 100644
--- a/src/components/src/common/icons/index.tsx
+++ b/src/components/src/common/icons/index.tsx
@@ -43,6 +43,7 @@ export {default as File} from './file';
export {default as Files} from './files';
export {default as FileType} from './file-type';
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 Hash} from './hash';
diff --git a/src/components/src/dnd-context.tsx b/src/components/src/dnd-context.tsx
index e49ab9029..c29218b06 100644
--- a/src/components/src/dnd-context.tsx
+++ b/src/components/src/dnd-context.tsx
@@ -3,12 +3,21 @@
import React, {useCallback, useMemo, PropsWithChildren} from 'react';
import styled from 'styled-components';
-import {DndContext as DndKitContext, DragOverlay} from '@dnd-kit/core';
+import {
+ DndContext as DndKitContext,
+ DragOverlay,
+ closestCenter,
+ pointerWithin,
+ CollisionDetection
+} from '@dnd-kit/core';
import Console from 'global/console';
import {VisState} from '@kepler.gl/schemas';
+import {LayerOrderGroup} from '@kepler.gl/types';
+import {Layer} from '@kepler.gl/layers';
import LayerPanelHeaderFactory from './side-panel/layer-panel/layer-panel-header';
+import LayerGroupHeaderFactory from './side-panel/layer-panel/layer-group-header';
import useDndLayers from './hooks/use-dnd-layers';
import useDndEffects from './hooks/use-dnd-effects';
@@ -16,7 +25,10 @@ import {
DND_MODIFIERS,
DND_EMPTY_MODIFIERS,
SORTABLE_LAYER_TYPE,
- SORTABLE_EFFECT_TYPE
+ SORTABLE_LAYER_GROUP_TYPE,
+ SORTABLE_LAYER_END_TYPE,
+ SORTABLE_EFFECT_TYPE,
+ SORTABLE_LAYER_GROUP_DROPPABLE_TYPE
} from './common/dnd-layer-items';
export type DndContextProps = PropsWithChildren<{
@@ -34,10 +46,61 @@ export const DragItem = styled.div`
const nop = () => undefined;
-DndContextFactory.deps = [LayerPanelHeaderFactory];
+/**
+ * Hybrid collision detection: uses closestCenter for sortable items (stable reordering
+ * without flickering) and pointerWithin for group droppable containers (reliable drop
+ * detection even when group is the last item). When dragging a group, only root-level
+ * sortable items are considered to prevent flickering from nested items.
+ */
+const layerGroupCollisionDetection: CollisionDetection = args => {
+ const activeType = args.active.data?.current?.type;
+
+ // When dragging a group, only consider root-level sortable items (no parent)
+ if (activeType === SORTABLE_LAYER_GROUP_TYPE) {
+ const filteredArgs = {
+ ...args,
+ droppableContainers: args.droppableContainers.filter(container => {
+ const type = container.data?.current?.type;
+ return (
+ type === SORTABLE_LAYER_GROUP_TYPE ||
+ type === SORTABLE_LAYER_END_TYPE ||
+ (type === SORTABLE_LAYER_TYPE && !container.data?.current?.parent)
+ );
+ })
+ };
+ return closestCenter(filteredArgs);
+ }
+
+ const closestCenterCollisions = closestCenter(args);
+ const pointerCollisions = pointerWithin(args);
+
+ const groupDroppable = pointerCollisions.find(c => {
+ const type = c.data?.droppableContainer?.data?.current?.type;
+ return type === SORTABLE_LAYER_GROUP_DROPPABLE_TYPE;
+ });
+
+ if (groupDroppable && closestCenterCollisions.length === 0) {
+ return [groupDroppable];
+ }
+
+ if (groupDroppable) {
+ const hasNonGroupSortable = closestCenterCollisions.some(c => {
+ const type = c.data?.droppableContainer?.data?.current?.type;
+ return type !== SORTABLE_LAYER_GROUP_DROPPABLE_TYPE && type !== SORTABLE_LAYER_END_TYPE;
+ });
+ if (!hasNonGroupSortable) {
+ return [groupDroppable];
+ }
+ }
+
+ return closestCenterCollisions;
+};
+
+DndContextFactory.deps = [LayerPanelHeaderFactory, LayerGroupHeaderFactory];
function DndContextFactory(
- LayerPanelHeader: ReturnType<typeof LayerPanelHeaderFactory>
+ LayerPanelHeader: ReturnType<typeof LayerPanelHeaderFactory>,
+ LayerGroupHeader: ReturnType<typeof LayerGroupHeaderFactory>
): React.FC<DndContextProps> {
const LayerPanelOverlay = ({layer, datasets}) => {
const color =
@@ -70,7 +133,7 @@ function DndContextFactory(
const {datasets, layerOrder, layers, effects, effectOrder, splitMaps} = visState;
const {
- activeLayer,
+ activeElement,
onDragStart: onLayerDragStart,
onDragEnd: onLayerDragEnd
} = useDndLayers(layers, layerOrder);
@@ -82,11 +145,15 @@ function DndContextFactory(
const isSplit = useMemo(() => splitMaps?.length > 1, [splitMaps]);
const dndModifiers = useMemo(() => (isSplit ? DND_EMPTY_MODIFIERS : DND_MODIFIERS), [isSplit]);
+ const activeElementType = activeElement?.[0];
+ const activeElementObject = activeElement?.[1];
+
const onDragStart = useCallback(
event => {
const activeType = event.active.data?.current?.type;
switch (activeType) {
case SORTABLE_LAYER_TYPE:
+ case SORTABLE_LAYER_GROUP_TYPE:
onLayerDragStart(event);
break;
case SORTABLE_EFFECT_TYPE:
@@ -104,6 +171,7 @@ function DndContextFactory(
const activeType = event.active.data?.current?.type;
switch (activeType) {
case SORTABLE_LAYER_TYPE:
+ case SORTABLE_LAYER_GROUP_TYPE:
onLayerDragEnd(event);
break;
case SORTABLE_EFFECT_TYPE:
@@ -117,15 +185,25 @@ function DndContextFactory(
);
return (
- <DndKitContext onDragStart={onDragStart} onDragEnd={onDragEnd} modifiers={dndModifiers}>
+ <DndKitContext
+ onDragStart={onDragStart}
+ onDragEnd={onDragEnd}
+ modifiers={dndModifiers}
+ collisionDetection={layerGroupCollisionDetection}
+ >
{children}
- {activeLayer ? (
- <DragOverlay modifiers={dndModifiers} dropAnimation={null}>
+ <DragOverlay modifiers={dndModifiers} dropAnimation={null}>
+ {activeElementType === 'layer' && activeElementObject ? (
+ <DragItem>
+ <LayerPanelOverlay layer={activeElementObject as Layer} datasets={datasets} />
+ </DragItem>
+ ) : null}
+ {activeElementType === 'layerGroup' && activeElementObject ? (
<DragItem>
- <LayerPanelOverlay layer={activeLayer} datasets={datasets} />
+ <LayerGroupHeader layerGroup={activeElementObject as LayerOrderGroup} />
</DragItem>
- </DragOverlay>
- ) : null}
+ ) : null}
+ </DragOverlay>
</DndKitContext>
);
};
diff --git a/src/components/src/geocoder-panel.tsx b/src/components/src/geocoder-panel.tsx
index 4f2a287a3..242afa1cd 100644
--- a/src/components/src/geocoder-panel.tsx
+++ b/src/components/src/geocoder-panel.tsx
@@ -14,7 +14,7 @@ import {
GEOCODER_ICON_COLOR,
GEOCODER_ICON_SIZE
} from '@kepler.gl/constants';
-import {AddDataToMapOptions, MapState, ProtoDataset, UiState, Viewport} from '@kepler.gl/types';
+import {AddDataToMapOptions, LayerOrder, MapState, ProtoDataset, UiState, Viewport} from '@kepler.gl/types';
import {ActionHandler, removeDataset, updateMap, updateVisData} from '@kepler.gl/actions';
import Geocoder, {Result} from './geocoder/geocoder';
@@ -51,11 +51,11 @@ const ICON_LAYER = {
}
};
-function generateConfig(layerOrder) {
+function generateConfig() {
return {
visState: {
layers: [ICON_LAYER],
- layerOrder: [ICON_LAYER.id, ...layerOrder]
+ layerOrder: [ICON_LAYER.id]
}
};
}
@@ -137,7 +137,7 @@ interface GeocoderPanelProps {
updateVisData: ActionHandler<typeof updateVisData>;
removeDataset: ActionHandler<typeof removeDataset>;
updateMap: ActionHandler<typeof updateMap>;
- layerOrder: string[];
+ layerOrder: LayerOrder;
limitSearch?: boolean;
transitionDuration?: MapViewState['transitionDuration'];
@@ -155,7 +155,6 @@ export default function GeocoderPanelFactory(): React.FC<GeocoderPanelProps> {
updateVisData,
removeDataset,
updateMap,
- layerOrder,
limitSearch = false,
transitionDuration = 3000,
width,
@@ -178,7 +177,7 @@ export default function GeocoderPanelFactory(): React.FC<GeocoderPanelProps> {
const updateVisDataPayload = getUpdateVisDataPayload(lat, lon, text);
if (updateVisDataPayload) {
removeGeocoderDataset();
- updateVisData(...updateVisDataPayload, generateConfig(layerOrder));
+ updateVisData(...updateVisDataPayload, generateConfig());
}
const bounds = bbox || [
@@ -214,7 +213,6 @@ export default function GeocoderPanelFactory(): React.FC<GeocoderPanelProps> {
},
[
index,
- layerOrder,
mapState,
removeGeocoderDataset,
transitionDuration,
diff --git a/src/components/src/hooks/use-dnd-layers.tsx b/src/components/src/hooks/use-dnd-layers.tsx
index f4d8780fe..a683524aa 100644
--- a/src/components/src/hooks/use-dnd-layers.tsx
+++ b/src/components/src/hooks/use-dnd-layers.tsx
@@ -4,90 +4,176 @@
import {useCallback, useState} from 'react';
import {useDispatch} from 'react-redux';
import {DragEndEvent, DragStartEvent} from '@dnd-kit/core';
-import {layerConfigChange, reorderLayer, toggleLayerForMap} from '@kepler.gl/actions';
+import {reorderLayer, toggleLayerForMap} from '@kepler.gl/actions';
import {
DROPPABLE_MAP_CONTAINER_TYPE,
SORTABLE_LAYER_TYPE,
- SORTABLE_SIDE_PANEL_TYPE
+ SORTABLE_LAYER_GROUP_TYPE,
+ SORTABLE_LAYER_GROUP_DROPPABLE_TYPE,
+ SORTABLE_LAYER_END_TYPE
} from '../common/dnd-layer-items';
-import {reorderLayerOrder} from '@kepler.gl/reducers';
+import {
+ reorderLayerOrder,
+ getLayerGroupFromLayerOrder,
+ getIndexFromLayerEntryId,
+ addLayerOrGroupToLayerOrder,
+ removeElementFromLayerOrder,
+ updateLayerGroupInLayerOrder
+} from '@kepler.gl/reducers';
import {Layer} from '@kepler.gl/layers';
+import {LayerOrderGroup, LayerOrder, LayerOrderHierarchyEntry} from '@kepler.gl/types';
-type DndEffectsHook = {
- activeLayer: Layer | undefined;
+type DndLayersHook = {
+ activeElement: LayerOrderHierarchyEntry | undefined;
onDragStart: (event: DragStartEvent) => void;
onDragEnd: (event: DragEndEvent) => void;
};
-const useDndLayers: (layers: Layer[], layerOrder: string[]) => DndEffectsHook = (
+const useDndLayers: (layers: Layer[], layerOrder: LayerOrder) => DndLayersHook = (
layers,
layerOrder
) => {
const dispatch = useDispatch();
- const [activeLayer, setActiveLayer]: [
- activeEffect: Layer | undefined,
- setActiveEffect: (effect: Layer | undefined) => void
- ] = useState();
+ const [activeElement, setActiveElement] = useState<LayerOrderHierarchyEntry | undefined>();
const onDragStart = useCallback(
- event => {
+ (event: DragStartEvent) => {
const {active} = event;
- const newActiveLayer = layers.find(layer => layer.id === active.id);
- if (newActiveLayer) {
- setActiveLayer(newActiveLayer);
- if (newActiveLayer?.config.isConfigActive) {
- dispatch(layerConfigChange(newActiveLayer, {isConfigActive: false}));
+ const activeType = event.active.data.current?.type;
+
+ if (!activeType) {
+ return;
+ }
+
+ switch (activeType) {
+ case SORTABLE_LAYER_TYPE: {
+ const activeLayer = layers.find(l => l.id === active.id);
+ if (activeLayer) {
+ setActiveElement(['layer', activeLayer]);
+ }
+ break;
}
+ case SORTABLE_LAYER_GROUP_TYPE: {
+ const activeLayerGroup = getLayerGroupFromLayerOrder(layerOrder, active.id as string);
+ if (activeLayerGroup) {
+ setActiveElement(['layerGroup', activeLayerGroup as LayerOrderGroup]);
+ }
+ break;
+ }
+ default:
+ break;
}
},
- [dispatch, layers]
+ [layerOrder, layers]
);
+ // eslint-disable-next-line complexity
const onDragEnd = useCallback(
- event => {
+ (event: DragEndEvent) => {
const {active, over} = event;
-
- const {id: activeLayerId} = active;
+ const activeId = active.id as string;
+ const overId = over?.id as string | null;
+ const activeParent = active.data?.current?.parent;
+ const activeType = active.data?.current?.type;
+ const overParent = over?.data?.current?.parent;
const overType = over?.data?.current?.type;
+ setActiveElement(undefined);
- if (!overType) {
- setActiveLayer(undefined);
+ if (!overId) {
+ if (activeParent && activeType === SORTABLE_LAYER_TYPE) {
+ let newLayerOrder = removeElementFromLayerOrder(layerOrder, activeId);
+ newLayerOrder = addLayerOrGroupToLayerOrder(newLayerOrder, activeId, newLayerOrder.length);
+ dispatch(reorderLayer(newLayerOrder));
+ }
return;
}
- switch (overType) {
- // moving layers into maps
- case DROPPABLE_MAP_CONTAINER_TYPE: {
- const mapIndex = over.data.current?.index ?? 0;
- dispatch(toggleLayerForMap(mapIndex, activeLayerId));
- break;
+ if (overType === DROPPABLE_MAP_CONTAINER_TYPE) {
+ if (activeType === SORTABLE_LAYER_TYPE) {
+ const mapIndex = over?.data.current?.index ?? 0;
+ dispatch(toggleLayerForMap(mapIndex, activeId));
}
- // swaping layers
- case SORTABLE_LAYER_TYPE: {
- const newLayerOrder = reorderLayerOrder(layerOrder, activeLayerId, over.id);
+ return;
+ }
+
+ if (overType === SORTABLE_LAYER_END_TYPE) {
+ const groupObj = getLayerGroupFromLayerOrder(layerOrder, activeId);
+ let newLayerOrder = removeElementFromLayerOrder(layerOrder, activeId);
+ newLayerOrder = addLayerOrGroupToLayerOrder(
+ newLayerOrder,
+ groupObj ?? activeId,
+ newLayerOrder.length
+ );
+ dispatch(reorderLayer(newLayerOrder));
+ return;
+ }
+
+ // swap layers at same level
+ if (activeParent?.id === overParent?.id) {
+ if (!activeParent) {
+ const newLayerOrder = reorderLayerOrder(layerOrder, activeId, overId);
+ dispatch(reorderLayer(newLayerOrder));
+ } else {
+ const currentLayerGroup = activeParent as LayerOrderGroup;
+ const newGroupLayerOrder = reorderLayerOrder(
+ currentLayerGroup.layerOrder,
+ activeId,
+ overId
+ );
+ const newLayerGroup = {
+ ...currentLayerGroup,
+ layerOrder: newGroupLayerOrder
+ };
+ const newLayerOrder = updateLayerGroupInLayerOrder(layerOrder, newLayerGroup);
dispatch(reorderLayer(newLayerOrder));
- break;
}
- // moving layers within side panel
- case SORTABLE_SIDE_PANEL_TYPE:
- // move layer to the end of the list
- dispatch(
- reorderLayer(
- reorderLayerOrder(layerOrder, activeLayerId, layerOrder[layerOrder.length - 1])
+ return;
+ }
+
+ // move into a group (either empty group droppable or onto a layer inside group)
+ if (overType === SORTABLE_LAYER_GROUP_DROPPABLE_TYPE || overParent) {
+ if (activeType === SORTABLE_LAYER_TYPE) {
+ const currentLayerGroup = overParent
+ ? overParent
+ : getLayerGroupFromLayerOrder(layerOrder, overId);
+
+ if (!currentLayerGroup) return;
+
+ const overIndex =
+ overType === SORTABLE_LAYER_GROUP_DROPPABLE_TYPE
+ ? 0
+ : getIndexFromLayerEntryId(currentLayerGroup.layerOrder, overId);
+
+ const newLayerGroup = {
+ ...currentLayerGroup,
+ layerOrder: addLayerOrGroupToLayerOrder(
+ currentLayerGroup.layerOrder,
+ activeId,
+ overIndex
)
- );
- break;
- default:
- break;
+ };
+
+ let newLayerOrder = removeElementFromLayerOrder(layerOrder, activeId);
+ newLayerOrder = updateLayerGroupInLayerOrder(newLayerOrder, newLayerGroup);
+ dispatch(reorderLayer(newLayerOrder));
+ }
+ return;
}
- setActiveLayer(undefined);
+ // moving layer/group onto root
+ if (!overParent) {
+ const groupObj = getLayerGroupFromLayerOrder(layerOrder, activeId as string);
+ let newLayerOrder = removeElementFromLayerOrder(layerOrder, activeId);
+ const overIndex = over?.data.current?.sortable?.index ?? 0;
+ newLayerOrder = addLayerOrGroupToLayerOrder(newLayerOrder, groupObj ?? activeId, overIndex);
+ dispatch(reorderLayer(newLayerOrder));
+ }
},
[dispatch, layerOrder]
);
- return {activeLayer, onDragStart, onDragEnd};
+ return {activeElement, onDragStart, onDragEnd};
};
export default useDndLayers;
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index cd6404bb1..b8536bed5 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -125,6 +125,7 @@ export {
export * from './side-panel/layer-panel/dimension-scale-selector';
export {default as LayerListFactory} from './side-panel/layer-panel/layer-list';
+export {default as LayerGroupHeaderFactory} from './side-panel/layer-panel/layer-group-header';
export * from './side-panel/layer-panel/vis-config-by-field-selector';
export {default as PanelViewListToggleFactory} from './side-panel/panel-view-list-toggle';
export {default as DatasetInfoFactory} from './side-panel/common/dataset-info';
@@ -491,6 +492,8 @@ export {
SORTABLE_LAYER_TYPE,
SORTABLE_EFFECT_TYPE,
SORTABLE_SIDE_PANEL_TYPE,
+ SORTABLE_LAYER_GROUP_TYPE,
+ SORTABLE_LAYER_GROUP_DROPPABLE_TYPE,
DND_MODIFIERS,
DND_EMPTY_MODIFIERS
} from './common/dnd-layer-items';
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index e29510be2..30ce56071 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -1273,7 +1273,7 @@ export default function MapContainerFactory(
sidePanelWidth
} = this.props;
- const {layers, datasets, editor, interactionConfig} = visState;
+ const {layers, datasets, editor, interactionConfig, layerOrder} = visState;
const layersToRender = this.layersToRenderSelector(this.props);
const layersForDeck = this.layersForDeckSelector(this.props);
@@ -1350,6 +1350,7 @@ export default function MapContainerFactory(
primary={Boolean(primary)}
isExport={isExport}
layers={layers}
+ layerOrder={layerOrder}
layersToRender={layersToRender}
mapIndex={index || 0}
mapControls={mapControls}
diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsx
index 78407b81b..2e9d4eff9 100644
--- a/src/components/src/map/map-control.tsx
+++ b/src/components/src/map/map-control.tsx
@@ -13,7 +13,7 @@ import MapDrawPanelFactory from './map-draw-panel';
import LocalePanelFactory from './locale-panel';
import MapNavigationControlFactory from './map-navigation-control';
import {Layer} from '@kepler.gl/layers';
-import {Editor, LayerVisConfig, MapControls, MapState} from '@kepler.gl/types';
+import {Editor, LayerVisConfig, LayerOrder, MapControls, MapState} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {MapStateActions, UIStateActions} from '@kepler.gl/actions';
import {getApplicationConfig} from '@kepler.gl/utils';
@@ -48,6 +48,7 @@ export type MapControlProps = {
isSplit: boolean;
primary: boolean;
layers: Layer[];
+ layerOrder?: LayerOrder;
layersToRender: {[key: string]: boolean};
mapIndex: number;
mapControls: MapControls;
diff --git a/src/components/src/map/map-legend-panel.tsx b/src/components/src/map/map-legend-panel.tsx
index c2f806713..a63e6dc00 100644
--- a/src/components/src/map/map-legend-panel.tsx
+++ b/src/components/src/map/map-legend-panel.tsx
@@ -22,7 +22,7 @@ import {ActionHandler, setMapControlSettings, toggleSplitMapViewport} from '@kep
import {MapSplitMode} from '@kepler.gl/constants';
import {Layer} from '@kepler.gl/layers';
import {breakPointValues} from '@kepler.gl/styles';
-import {LayerVisConfig, MapControlMapLegend, MapControls, MapState} from '@kepler.gl/types';
+import {LayerVisConfig, LayerOrder, MapControlMapLegend, MapControls, MapState} from '@kepler.gl/types';
import {hasPortableWidth} from '@kepler.gl/utils';
import {MapLegendControlSettings} from '@kepler.gl/types';
@@ -313,6 +313,7 @@ interface MapLegendPanelIcons {
export type MapLegendPanelProps = {
theme: any;
layers: ReadonlyArray<Layer>;
+ layerOrder?: LayerOrder;
scale: number;
onToggleMapControl: (control: string) => void;
isExport: boolean;
@@ -350,6 +351,7 @@ const defaultActionIcons = {
const MapLegendPanelComponent = ({
layers,
+ layerOrder,
mapControls,
scale,
onToggleMapControl,
@@ -421,6 +423,7 @@ const MapLegendPanelComponent = ({
>
<MapLegend
layers={layers}
+ layerOrder={layerOrder}
mapState={mapState}
disableEdit={disableEdit}
isExport={isExport}
diff --git a/src/components/src/map/map-legend.tsx b/src/components/src/map/map-legend.tsx
index 933d49f2c..f0fbd7658 100644
--- a/src/components/src/map/map-legend.tsx
+++ b/src/components/src/map/map-legend.tsx
@@ -11,10 +11,11 @@ import RadiusLegend from '../common/radius-legend';
import {CHANNEL_SCALES, DIMENSIONS} from '@kepler.gl/constants';
import {FormattedMessage} from '@kepler.gl/localization';
import {Layer, LayerBaseConfig, VisualChannel, VisualChannelDescription} from '@kepler.gl/layers';
-import {LayerVisConfig, MapState, RGBColor} from '@kepler.gl/types';
+import {LayerVisConfig, LayerOrder, MapState, RGBColor} from '@kepler.gl/types';
import {getDistanceScales} from 'viewport-mercator-project';
import {ArrowDown, ArrowRight, EyeSeen, EyeUnseen} from '../common/icons';
import PanelHeaderActionFactory from '../side-panel/panel-header-action';
+import {getFlatLayerOrder} from '@kepler.gl/reducers';
interface StyledMapControlLegendProps {
width?: number;
@@ -538,6 +539,7 @@ export function LayerLegendContentFactory(
export type MapLegendProps = {
layers?: ReadonlyArray<Layer>;
+ layerOrder?: LayerOrder;
width?: number;
mapState?: MapState;
options?: {
@@ -625,6 +627,7 @@ function MapLegendFactory(
const MapLegend: React.FC<MapLegendProps> = ({
layers = [],
+ layerOrder,
width,
mapState,
options,
@@ -636,43 +639,53 @@ function MapLegendFactory(
isSplit,
splitMaps,
actionIcons = defaultActionIcons
- }) => (
- <div className="map-legend">
- {layers.map((layer, index) => {
- if (!layer.isValidToSave() || layer.config.hidden) {
- return null;
- }
- const containerW = width || DIMENSIONS.mapControl.width;
-
- const isLayerVisible =
- isSplit && splitMaps && splitMaps.length > 1
- ? layer.config.isVisible &&
- (Boolean(splitMaps[0]?.layers?.[layer.id]) ||
- Boolean(splitMaps[1]?.layers?.[layer.id]))
- : layer.config.isVisible;
-
- return (
- <LayerLegendItem
- key={layer.id}
- layer={layer}
- containerW={containerW}
- isLast={index === layers.length - 1}
- isLayerVisible={isLayerVisible}
- isExport={isExport}
- options={options}
- mapState={mapState}
- disableEdit={disableEdit}
- onLayerVisConfigChange={onLayerVisConfigChange}
- onToggleLayerVisibility={onToggleLayerVisibility}
- onMapToggleLayer={onMapToggleLayer}
- isSplit={isSplit}
- splitMaps={splitMaps}
- actionIcons={actionIcons}
- />
- );
- })}
- </div>
- );
+ }) => {
+ const orderedLayers = layerOrder
+ ? getFlatLayerOrder(layerOrder).reduce<Layer[]>((acc, id) => {
+ const layer = layers.find(l => l.id === id);
+ if (layer) acc.push(layer);
+ return acc;
+ }, [])
+ : layers;
+
+ return (
+ <div className="map-legend">
+ {orderedLayers.map((layer, index) => {
+ if (!layer.isValidToSave() || layer.config.hidden) {
+ return null;
+ }
+ const containerW = width || DIMENSIONS.mapControl.width;
+
+ const isLayerVisible =
+ isSplit && splitMaps && splitMaps.length > 1
+ ? layer.config.isVisible &&
+ (Boolean(splitMaps[0]?.layers?.[layer.id]) ||
+ Boolean(splitMaps[1]?.layers?.[layer.id]))
+ : layer.config.isVisible;
+
+ return (
+ <LayerLegendItem
+ key={layer.id}
+ layer={layer}
+ containerW={containerW}
+ isLast={index === orderedLayers.length - 1}
+ isLayerVisible={isLayerVisible}
+ isExport={isExport}
+ options={options}
+ mapState={mapState}
+ disableEdit={disableEdit}
+ onLayerVisConfigChange={onLayerVisConfigChange}
+ onToggleLayerVisibility={onToggleLayerVisibility}
+ onMapToggleLayer={onMapToggleLayer}
+ isSplit={isSplit}
+ splitMaps={splitMaps}
+ actionIcons={actionIcons}
+ />
+ );
+ })}
+ </div>
+ );
+ };
MapLegend.displayName = 'MapLegend';
diff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsx
index 5567504a4..0a7ec3983 100644
--- a/src/components/src/side-panel/layer-manager.tsx
+++ b/src/components/src/side-panel/layer-manager.tsx
@@ -22,9 +22,11 @@ import {LAYER_BLENDINGS, OVERLAY_BLENDINGS, PANEL_VIEW_TOGGLES} from '@kepler.gl
import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {UIStateActions, VisStateActions, MapStateActions, ActionHandler} from '@kepler.gl/actions';
import {SidePanelItem} from '../types';
-import {PanelListView} from '@kepler.gl/types';
+import {PanelListView, LayerOrder} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {getApplicationConfig} from '@kepler.gl/utils';
+import PanelHeaderActionFactory from './panel-header-action';
+import {Folder} from '../common/icons';
type LayerBlendingSelectorProps = {
layerBlending: string;
@@ -41,7 +43,7 @@ type OverlayBlendingSelectorProps = {
type LayerManagerProps = {
datasets: Datasets;
layers: Layer[];
- layerOrder: string[];
+ layerOrder: LayerOrder;
layerClasses: LayerClassesType;
layerBlending: string;
overlayBlending: string;
@@ -143,7 +145,8 @@ LayerManagerFactory.deps = [
PanelTitleFactory,
DatasetSectionFactory,
AddLayerButtonFactory,
- InfoHelperFactory
+ InfoHelperFactory,
+ PanelHeaderActionFactory
];
function LayerManagerFactory(
@@ -153,7 +156,8 @@ function LayerManagerFactory(
PanelTitle: ReturnType<typeof PanelTitleFactory>,
DatasetSection: ReturnType<typeof DatasetSectionFactory>,
AddLayerButton: ReturnType<typeof AddLayerButtonFactory>,
- InfoHelper: ReturnType<typeof InfoHelperFactory>
+ InfoHelper: ReturnType<typeof InfoHelperFactory>,
+ PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>
) {
const LayerManager: React.FC<LayerManagerProps> = ({
layers,
@@ -183,6 +187,10 @@ function LayerManagerFactory(
[addLayer]
);
+ const onAddGroup = useCallback(() => {
+ visStateActions.addLayerGroup({});
+ }, [visStateActions]);
+
const onTogglePanelListView = useCallback(
(listView: string) => {
togglePanelListView({panelId: 'layer', listView});
@@ -196,6 +204,7 @@ function LayerManagerFactory(
const enableRasterTileLayer = getApplicationConfig().enableRasterTileLayer;
const enableWMSLayer = getApplicationConfig().enableWMSLayer;
const enableFlowLayer = getApplicationConfig().enableFlowLayer;
+ const enableLayerGroups = getApplicationConfig().enableLayerGroups;
const filteredLayerClasses = useMemo(() => {
let filteredClasses = layerClasses;
@@ -234,6 +243,15 @@ function LayerManagerFactory(
className="layer-manager-title"
title={intl.formatMessage({id: panelMetadata.label})}
>
+ {enableLayerGroups ? (
+ <PanelHeaderAction
+ className="layer-group__create"
+ id="new-layer-group"
+ onClick={onAddGroup}
+ IconComponent={Folder}
+ tooltip="Create layer group"
+ />
+ ) : null}
<AddLayerButton datasets={datasets} onAdd={onAddLayer} />
</PanelTitle>
</SidePanelSection>
diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx
index 8a1b4e08a..1dee72136 100644
--- a/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx
+++ b/src/components/src/side-panel/layer-panel/dataset-layer-group.tsx
@@ -7,11 +7,12 @@ import DatasetLayerSectionFactory from './dataset-layer-section';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {UIStateActions, VisStateActions, ActionHandler, MapStateActions} from '@kepler.gl/actions';
import {KeplerTable, Datasets} from '@kepler.gl/table';
+import {LayerOrder} from '@kepler.gl/types';
type DatasetLayerGroupProps = {
datasets: Datasets;
layers: Layer[];
- layerOrder: string[];
+ layerOrder: LayerOrder;
layerClasses: LayerClassesType;
showDeleteDataset: boolean;
removeDataset: ActionHandler<typeof UIStateActions.openDeleteModal>;
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 f73dfabdc..62f7737dd 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
@@ -10,12 +10,13 @@ import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {UIStateActions, ActionHandler, VisStateActions, MapStateActions} from '@kepler.gl/actions';
import {KeplerTable, Datasets} from '@kepler.gl/table';
import {getApplicationConfig} from '@kepler.gl/utils';
+import {LayerOrder} from '@kepler.gl/types';
type DatasetLayerSectionProps = {
datasets: Datasets;
dataset: KeplerTable;
layers: Layer[];
- layerOrder: string[];
+ layerOrder: LayerOrder;
layerClasses: LayerClassesType;
showDeleteDataset: boolean;
showDatasetTable: ActionHandler<typeof VisStateActions.showDatasetTable>;
diff --git a/src/components/src/side-panel/layer-panel/layer-group-header.tsx b/src/components/src/side-panel/layer-panel/layer-group-header.tsx
new file mode 100644
index 000000000..f50b2f1fc
--- /dev/null
+++ b/src/components/src/side-panel/layer-panel/layer-group-header.tsx
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, useState, useEffect, useRef} from 'react';
+import {useDispatch} from 'react-redux';
+import styled from 'styled-components';
+
+import {updateLayerGroup, removeLayerGroup} from '@kepler.gl/actions';
+import {LayerOrderGroup} from '@kepler.gl/types';
+import {getFlatLayerOrder} from '@kepler.gl/reducers';
+
+import {StyledPanelHeader, InlineInput} from '../../common/styled-components';
+import {DragHandle} from './layer-panel-header';
+import {VertDots, EyeSeen, EyeUnseen, Trash, ArrowDown, ArrowRight} from '../../common/icons';
+import PanelHeaderActionFactory from '../panel-header-action';
+
+const GROUP_COLORS = [
+ '#4BA9C9',
+ '#E8A838',
+ '#8BC58B',
+ '#D67AB1',
+ '#7B8FF7',
+ '#F2726F',
+ '#56C4A0',
+ '#C9A84B'
+];
+
+function getGroupColor(id: string): string {
+ let hash = 0;
+ for (let i = 0; i < id.length; i++) {
+ hash = ((hash << 5) - hash + id.charCodeAt(i)) | 0;
+ }
+ return GROUP_COLORS[Math.abs(hash) % GROUP_COLORS.length];
+}
+
+const RemoveAction = styled.div`
+ display: flex;
+ opacity: 0;
+ transition: opacity 0.15s ease;
+ .panel--header__action {
+ height: 16px;
+ }
+`;
+
+const Container = styled(StyledPanelHeader)`
+ position: relative;
+ height: ${props => props.theme.layerPanelHeaderHeight}px;
+ justify-content: space-between;
+ color: ${props => props.theme.textColor};
+ padding-right: 10px;
+ align-items: center;
+ overflow: hidden;
+
+ border: 1px solid ${props => props.theme.panelBackgroundHover};
+
+ &:hover {
+ cursor: pointer;
+ background-color: ${props => props.theme.panelBackgroundHover};
+ .layer__drag-handle {
+ opacity: 1;
+ }
+ ${RemoveAction} {
+ opacity: 1;
+ }
+ }
+`;
+
+const CornerTriangle = styled.div<{$color: string}>`
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 0;
+ height: 0;
+ border-style: solid;
+ border-width: ${props => Math.round(props.theme.layerPanelHeaderHeight / 3)}px
+ ${props => Math.round(props.theme.layerPanelHeaderHeight / 3)}px 0 0;
+ border-color: ${props => props.$color} transparent transparent transparent;
+`;
+
+const Actions = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 0;
+ height: 16px;
+ .panel--header__action {
+ height: 16px;
+ }
+`;
+
+const LeftSection = styled.div`
+ display: flex;
+ align-items: center;
+ flex-grow: 1;
+ overflow: hidden;
+`;
+
+const GroupLabelInput = styled(InlineInput)`
+ margin-left: 4px;
+ font-weight: 500;
+`;
+
+const ConfirmationBar = styled.div`
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 6px 12px;
+ background-color: ${props => props.theme.panelBackgroundHover};
+ border: 1px solid ${props => props.theme.panelBackgroundHover};
+ border-top: none;
+ font-size: 11px;
+ color: ${props => props.theme.textColor};
+ gap: 8px;
+`;
+
+const ConfirmButton = styled.button`
+ background: ${props => props.theme.secondaryBtnBgd};
+ color: ${props => props.theme.secondaryBtnColor};
+ border: none;
+ border-radius: 2px;
+ padding: 3px 8px;
+ font-size: 11px;
+ cursor: pointer;
+ &:hover {
+ background: ${props => props.theme.secondaryBtnBgdHover};
+ }
+`;
+
+export type LayerGroupHeaderProps = {
+ layerGroup: LayerOrderGroup;
+ isLayerGroupContentOpen?: boolean;
+ onToggleLayerGroupContent?: () => void;
+ listeners?: any;
+ className?: string;
+};
+
+LayerGroupHeaderFactory.deps = [PanelHeaderActionFactory];
+
+function LayerGroupHeaderFactory(
+ PanelHeaderAction: ReturnType<typeof PanelHeaderActionFactory>
+): React.FC<LayerGroupHeaderProps> {
+ const LayerGroupHeader: React.FC<LayerGroupHeaderProps> = ({
+ layerGroup,
+ onToggleLayerGroupContent,
+ isLayerGroupContentOpen,
+ listeners,
+ className
+ }) => {
+ const {id, label} = layerGroup;
+ const dispatch = useDispatch();
+ const [showConfirmation, setShowConfirmation] = useState(false);
+ const confirmRef = useRef<HTMLDivElement>(null);
+
+ const layerCount = getFlatLayerOrder(layerGroup.layerOrder).length;
+
+ useEffect(() => {
+ if (!showConfirmation) return;
+ const handleClickOutside = (e: MouseEvent) => {
+ if (confirmRef.current && !confirmRef.current.contains(e.target as Node)) {
+ setShowConfirmation(false);
+ }
+ };
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, [showConfirmation]);
+
+ const onUpdateLabel = useCallback(
+ event => {
+ dispatch(updateLayerGroup({id, options: {label: event.target.value}}));
+ },
+ [dispatch, id]
+ );
+
+ const onToggleVisibility = useCallback(() => {
+ dispatch(updateLayerGroup({id, options: {isVisible: !layerGroup.isVisible}}));
+ }, [dispatch, id, layerGroup.isVisible]);
+
+ const onDelete = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ if (layerCount > 0) {
+ setShowConfirmation(true);
+ } else {
+ dispatch(removeLayerGroup({id}));
+ }
+ },
+ [dispatch, id, layerCount]
+ );
+
+ const onConfirmDelete = useCallback(
+ (e: React.MouseEvent) => {
+ e.stopPropagation();
+ dispatch(removeLayerGroup({id}));
+ setShowConfirmation(false);
+ },
+ [dispatch, id]
+ );
+
+ const VisibilityIcon = layerGroup.isVisible ? EyeSeen : EyeUnseen;
+ const CollapseIcon = isLayerGroupContentOpen ? ArrowDown : ArrowRight;
+
+ const stopPropagation = useCallback((e: React.MouseEvent) => {
+ e.stopPropagation();
+ }, []);
+
+ return (
+ <div>
+ <Container className={className} onClick={onToggleLayerGroupContent}>
+ <CornerTriangle $color={getGroupColor(id)} />
+ <LeftSection>
+ <DragHandle className="layer__drag-handle" listeners={listeners}>
+ <VertDots height="20px" />
+ </DragHandle>
+ <GroupLabelInput
+ type="text"
+ value={label}
+ onClick={stopPropagation}
+ onChange={onUpdateLabel}
+ id={`${id}:input-group-label`}
+ />
+ </LeftSection>
+ <Actions onClick={stopPropagation}>
+ <RemoveAction>
+ <PanelHeaderAction
+ className="layer-group__delete"
+ id={`${id}-delete`}
+ tooltip="Remove group"
+ onClick={onDelete}
+ IconComponent={Trash}
+ />
+ </RemoveAction>
+ <PanelHeaderAction
+ className="layer-group__visibility-toggle"
+ id={`${id}-visibility`}
+ tooltip="Toggle group visibility"
+ onClick={onToggleVisibility}
+ IconComponent={VisibilityIcon}
+ />
+ <PanelHeaderAction
+ className="layer-group__section-toggle"
+ id={`${id}-collapse`}
+ tooltip="Toggle group content"
+ onClick={onToggleLayerGroupContent}
+ IconComponent={CollapseIcon}
+ />
+ </Actions>
+ </Container>
+ {showConfirmation ? (
+ <ConfirmationBar ref={confirmRef} onClick={stopPropagation}>
+ <span>Remove group with layers?</span>
+ <ConfirmButton onClick={onConfirmDelete}>Remove</ConfirmButton>
+ </ConfirmationBar>
+ ) : null}
+ </div>
+ );
+ };
+
+ return LayerGroupHeader;
+}
+
+export default LayerGroupHeaderFactory;
diff --git a/src/components/src/side-panel/layer-panel/layer-list.tsx b/src/components/src/side-panel/layer-panel/layer-list.tsx
index fcc6617fd..c0f58f3ae 100644
--- a/src/components/src/side-panel/layer-panel/layer-list.tsx
+++ b/src/components/src/side-panel/layer-panel/layer-list.tsx
@@ -1,26 +1,41 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React, {useMemo} from 'react';
+import React, {useMemo, useCallback, useState} from 'react';
import styled from 'styled-components';
import classnames from 'classnames';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {Datasets} from '@kepler.gl/table';
import {UIStateActions, VisStateActions, MapStateActions} from '@kepler.gl/actions';
+import {LayerOrderGroup, LayerOrder, LayerOrderHierarchy} from '@kepler.gl/types';
-import {useSortable, SortableContext, verticalListSortingStrategy} from '@dnd-kit/sortable';
+import {useDroppable} from '@dnd-kit/core';
+import {
+ useSortable,
+ SortableContext,
+ verticalListSortingStrategy,
+ defaultAnimateLayoutChanges
+} from '@dnd-kit/sortable';
import {CSS} from '@dnd-kit/utilities';
import LayerPanelFactory from './layer-panel';
-import {findById} from '@kepler.gl/utils';
+import LayerGroupHeaderFactory from './layer-group-header';
+import {buildLayerOrderHierarchy} from '@kepler.gl/reducers';
import {dataTestIds} from '@kepler.gl/constants';
import {SplitMap} from '@kepler.gl/types';
-import {SORTABLE_LAYER_TYPE, SORTABLE_SIDE_PANEL_TYPE} from '../../common/dnd-layer-items';
+import {
+ SORTABLE_LAYER_TYPE,
+ SORTABLE_SIDE_PANEL_TYPE,
+ SORTABLE_LAYER_GROUP_TYPE,
+ SORTABLE_LAYER_GROUP_DROPPABLE_TYPE,
+ SORTABLE_LAYER_END_PLACEHOLDER,
+ SORTABLE_LAYER_END_TYPE
+} from '../../common/dnd-layer-items';
export type LayerListProps = {
datasets: Datasets;
layers: Layer[];
- layerOrder: string[];
+ layerOrder: LayerOrder;
layerClasses: LayerClassesType;
isSortable?: boolean;
splitMap?: SplitMap;
@@ -29,10 +44,10 @@ export type LayerListProps = {
mapStateActions: typeof MapStateActions;
};
-export type LayerListFactoryDeps = [typeof LayerPanelFactory];
-
-// make sure the element is always visible while is being dragged
-// item being dragged is appended in body, here to reset its global style
+export type LayerListFactoryDeps = [
+ typeof LayerPanelFactory,
+ typeof LayerGroupHeaderFactory
+];
const Container = styled.div`
display: flex;
@@ -40,6 +55,18 @@ const Container = styled.div`
gap: 8px;
`;
+const animateLayoutChanges = args => {
+ const {isSorting, wasDragging} = args;
+ if (isSorting || wasDragging) {
+ return false;
+ }
+ return defaultAnimateLayoutChanges(args);
+};
+
+const EndPlaceholder = styled.div`
+ height: 4px;
+`;
+
interface SortableStyledItemProps {
$transition?: string;
$transform?: string;
@@ -70,21 +97,93 @@ const SortableStyledItem = styled.div<SortableStyledItemProps>`
}
`;
-const INITIAL_LAYERS_TO_SHOW: Layer[] = [];
+const CollapsibleGroupContent = styled.div<{$isOver?: boolean}>`
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ padding: 4px 0;
+ min-height: 32px;
+ background-color: ${props => (props.$isOver ? props.theme.panelBackgroundHover : 'transparent')};
+ transition: background-color 0.15s ease;
+`;
+
+const CollapsedDropZone = styled.div<{$isOver?: boolean}>`
+ min-height: 4px;
+ background-color: ${props => (props.$isOver ? props.theme.activeColor : 'transparent')};
+ transition: background-color 0.15s ease, min-height 0.15s ease;
+ ${props => props.$isOver && 'min-height: 24px;'}
+`;
+
+const EmptyLayerGroup = styled.div`
+ display: flex;
+ font-size: 11px;
+ align-items: center;
+ justify-content: center;
+ min-height: 28px;
+ border: 1px dashed ${props => props.theme.labelColor};
+ border-radius: 4px;
+ margin-top: 4px;
+ color: ${props => props.theme.subtextColor};
+`;
+
+const TREE_TILE_WIDTH = 10;
+const TREE_TILE_BORDER_WIDTH = 1;
+
+const StyledColumn = styled.div<{$isLast?: boolean}>`
+ border-left: ${props => (props.$isLast ? 0 : 1)}px dashed ${props => props.theme.labelColor};
+`;
+
+const TreeTile = styled.div<{$isLast?: boolean}>`
+ width: ${TREE_TILE_WIDTH}px;
+ border-bottom: 1px dashed ${props => props.theme.labelColor};
+ height: ${props => (props.theme.layerPanelHeaderHeight || 32) / 2}px;
+ margin-top: 2px;
+ border-left: ${props => (props.$isLast ? 1 : 0)}px dashed ${props => props.theme.labelColor};
+`;
+
+const NestedLayerContainer = styled.div`
+ display: flex;
+`;
+
+const NestedLayerContent = styled.div`
+ width: calc(100% - ${TREE_TILE_WIDTH + TREE_TILE_BORDER_WIDTH}px);
+ padding-top: 8px;
+`;
+
+LayerListFactory.deps = [LayerPanelFactory, LayerGroupHeaderFactory];
-LayerListFactory.deps = [LayerPanelFactory];
+function LayerListFactory(
+ LayerPanel: ReturnType<typeof LayerPanelFactory>,
+ LayerGroupHeader: ReturnType<typeof LayerGroupHeaderFactory>
+) {
+ const NestedLayer: React.FC<{children: React.ReactNode; isLast?: boolean}> = ({
+ children,
+ isLast
+ }) => (
+ <NestedLayerContainer>
+ <StyledColumn $isLast={isLast}>
+ <TreeTile $isLast={isLast} />
+ </StyledColumn>
+ <NestedLayerContent>{children}</NestedLayerContent>
+ </NestedLayerContainer>
+ );
-function LayerListFactory(LayerPanel: ReturnType<typeof LayerPanelFactory>) {
- // By wrapping layer panel using a sortable element we don't have to implement the drag and drop logic into the panel itself;
- // Developers can provide any layer panel implementation and it will still be sortable
- const SortableItem = ({layer, idx, panelProps, layerActions, disabled}) => {
+ const SortableLayerItem = ({layer, idx, panelProps, layerActions, disabled, parent}: {
+ layer: Layer;
+ idx: number;
+ panelProps: any;
+ layerActions: any;
+ disabled?: boolean;
+ parent?: LayerOrderGroup;
+ }) => {
const {attributes, listeners, setNodeRef, isDragging, transform, transition} = useSortable({
id: layer.id,
data: {
type: SORTABLE_LAYER_TYPE,
- parent: SORTABLE_SIDE_PANEL_TYPE
+ parent
},
- disabled
+ disabled,
+ animateLayoutChanges
});
return (
@@ -113,6 +212,101 @@ function LayerListFactory(LayerPanel: ReturnType<typeof LayerPanelFactory>) {
);
};
+ const SortableGroupItem: React.FC<{
+ layerGroup: LayerOrderGroup;
+ layers: Layer[];
+ panelProps: any;
+ layerActions: any;
+ disabled?: boolean;
+ }> = ({layerGroup, layers, panelProps, layerActions, disabled}) => {
+ const {attributes, isDragging, listeners, setNodeRef, transform, transition} = useSortable({
+ id: layerGroup.id,
+ data: {type: SORTABLE_LAYER_GROUP_TYPE},
+ disabled,
+ animateLayoutChanges
+ });
+
+ const layerEntriesToShow = buildLayerOrderHierarchy(layerGroup.layerOrder, layers);
+ const dndItems = layerEntriesToShow.map(entry => entry[1].id ?? entry[1]);
+
+ const [isSectionOpen, setIsSectionOpen] = useState(true);
+ const onToggle = useCallback(() => setIsSectionOpen(prev => !prev), []);
+
+ const style = useMemo(
+ () => ({
+ transform: CSS.Transform.toString(transform),
+ transition,
+ opacity: isDragging ? 0.5 : 1
+ }),
+ [isDragging, transform, transition]
+ );
+
+ const {isOver, setNodeRef: droppableSetNodeRef} = useDroppable({
+ id: `droppable-layer-group-content-${layerGroup.id}`,
+ data: {
+ type: SORTABLE_LAYER_GROUP_DROPPABLE_TYPE,
+ parent: layerGroup
+ }
+ });
+
+ const isOpen = useMemo(() => isSectionOpen && !isDragging, [isSectionOpen, isDragging]);
+
+ return (
+ <div style={style}>
+ <div ref={setNodeRef} {...attributes}>
+ <LayerGroupHeader
+ layerGroup={layerGroup}
+ onToggleLayerGroupContent={onToggle}
+ isLayerGroupContentOpen={isSectionOpen}
+ listeners={listeners}
+ />
+ </div>
+ {isOpen ? (
+ <CollapsibleGroupContent ref={droppableSetNodeRef} $isOver={isOver}>
+ {layerEntriesToShow.length ? (
+ <SortableContext
+ id={`sortable-group-${layerGroup.id}`}
+ items={dndItems}
+ strategy={verticalListSortingStrategy}
+ >
+ {layerEntriesToShow.map(([type, nestedEntry], index) =>
+ type === 'layer' ? (
+ <NestedLayer
+ key={nestedEntry.id}
+ isLast={index === layerEntriesToShow.length - 1}
+ >
+ <SortableLayerItem
+ layer={nestedEntry as Layer}
+ idx={layers.findIndex(l => l?.id === nestedEntry.id)}
+ panelProps={panelProps}
+ layerActions={layerActions}
+ disabled={disabled}
+ parent={layerGroup}
+ />
+ </NestedLayer>
+ ) : null
+ )}
+ </SortableContext>
+ ) : (
+ <EmptyLayerGroup>Drag layer here</EmptyLayerGroup>
+ )}
+ </CollapsibleGroupContent>
+ ) : (
+ <CollapsedDropZone ref={droppableSetNodeRef} $isOver={isOver} />
+ )}
+ </div>
+ );
+ };
+
+ const SortableEndPlaceholder = () => {
+ const {setNodeRef} = useSortable({
+ id: SORTABLE_LAYER_END_PLACEHOLDER,
+ data: {type: SORTABLE_LAYER_END_TYPE},
+ animateLayoutChanges
+ });
+ return <EndPlaceholder ref={setNodeRef} />;
+ };
+
const LayerList: React.FC<LayerListProps> = props => {
const {
layers,
@@ -127,19 +321,16 @@ function LayerListFactory(LayerPanel: ReturnType<typeof LayerPanelFactory>) {
} = props;
const {toggleModal: openModal} = uiStateActions;
- const layersToShow = useMemo(() => {
- return layerOrder.reduce((acc, layerId) => {
- const layer = findById(layerId)(layers.filter(Boolean));
- if (!layer) {
- return acc;
- }
- return !layer.config.hidden ? [...acc, layer] : acc;
- }, INITIAL_LAYERS_TO_SHOW);
- }, [layers, layerOrder]);
+ const layerEntriesToShow: LayerOrderHierarchy = useMemo(
+ () => buildLayerOrderHierarchy(layerOrder, layers),
+ [layerOrder, layers]
+ );
const sidePanelDndItems = useMemo(() => {
- return layersToShow.map(({id}) => id);
- }, [layersToShow]);
+ const items = layerEntriesToShow.map(entry => entry[1].id ?? entry[1]);
+ items.push(SORTABLE_LAYER_END_PLACEHOLDER);
+ return items;
+ }, [layerEntriesToShow]);
const layerTypeOptions = useMemo(
() =>
@@ -190,17 +381,28 @@ function LayerListFactory(LayerPanel: ReturnType<typeof LayerPanelFactory>) {
strategy={verticalListSortingStrategy}
disabled={!isSortable}
>
- {/* warning: containerId should be similar to the first key in dndItems defined in kepler-gl.js*/}
- {layersToShow.map(layer => (
- <SortableItem
- key={layer.id}
- layer={layer}
- idx={layers.findIndex(l => l?.id === layer.id)}
- panelProps={panelProps}
- layerActions={layerActions}
- disabled={!isSortable}
- />
- ))}
+ {layerEntriesToShow.map(([type, item]) =>
+ type === 'layer' ? (
+ <SortableLayerItem
+ key={item.id}
+ layer={item as Layer}
+ idx={layers.findIndex(l => l?.id === item.id)}
+ panelProps={panelProps}
+ layerActions={layerActions}
+ disabled={!isSortable}
+ />
+ ) : (
+ <SortableGroupItem
+ key={(item as LayerOrderGroup).id}
+ layerGroup={item as LayerOrderGroup}
+ layers={layers}
+ panelProps={panelProps}
+ layerActions={layerActions}
+ disabled={!isSortable}
+ />
+ )
+ )}
+ <SortableEndPlaceholder />
</SortableContext>
</Container>
);
diff --git a/src/components/src/types.ts b/src/components/src/types.ts
index 2e55fd560..77c18425c 100644
--- a/src/components/src/types.ts
+++ b/src/components/src/types.ts
@@ -4,7 +4,7 @@
import React, {HTMLAttributes, PropsWithChildren} from 'react';
import {MapStyle} from '@kepler.gl/reducers';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
-import {Filter, InteractionConfig, UiState} from '@kepler.gl/types';
+import {Filter, InteractionConfig, UiState, LayerOrder} from '@kepler.gl/types';
import {
MapStyleActions,
@@ -32,7 +32,7 @@ export type SidePanelProps = {
overlayBlending?: string;
layers: Layer[];
layerClasses: LayerClassesType;
- layerOrder: string[];
+ layerOrder: LayerOrder;
mapStyle: MapStyle;
mapInfo: {title?: string; description?: string};
width: number;
diff --git a/src/layers/src/mapbox-utils.ts b/src/layers/src/mapbox-utils.ts
index f0ea0afb9..4676baa18 100644
--- a/src/layers/src/mapbox-utils.ts
+++ b/src/layers/src/mapbox-utils.ts
@@ -4,7 +4,8 @@
import Layer, {OVERLAY_TYPE_CONST} from './base-layer';
import {Feature} from 'geojson';
-import {findById} from '@kepler.gl/utils';
+import {isPlainObject} from '@kepler.gl/utils';
+import {LayerOrderGroup, LayerOrder} from '@kepler.gl/types';
/**
* This function will convert layers to mapbox layers
@@ -17,18 +18,26 @@ import {findById} from '@kepler.gl/utils';
export function generateMapboxLayers(
layers: Layer[] = [],
layerData: any[] = [],
- layerOrder: string[] = [],
+ layerOrder: LayerOrder = [],
layersToRender: {[key: string]: boolean} = {}
): {[key: string]: Layer} {
if (layerData.length > 0) {
return layerOrder
.slice()
.reverse()
- .filter(layerId => {
- const layer = findById(layerId)(layers);
- return layer?.overlayType === OVERLAY_TYPE_CONST.mapboxgl && layersToRender[layerId];
- })
- .reduce((acc, layerId) => {
+ .reduce((acc, element) => {
+ if (isPlainObject(element)) {
+ const layerGroup = element as LayerOrderGroup;
+ if (!layerGroup.isVisible) {
+ return acc;
+ }
+ return {
+ ...acc,
+ ...generateMapboxLayers(layers, layerData, layerGroup.layerOrder, layersToRender)
+ };
+ }
+
+ const layerId = element as string;
const layerIndex = layers.findIndex(l => l.id === layerId);
if (layerIndex === -1) {
return acc;
diff --git a/src/reducers/src/layer-utils.ts b/src/reducers/src/layer-utils.ts
index d6154deeb..59750c4b1 100644
--- a/src/reducers/src/layer-utils.ts
+++ b/src/reducers/src/layer-utils.ts
@@ -17,7 +17,12 @@ import {
FeatureSelectionContext,
BindedLayerCallbacks,
LayerCallbacks,
- Viewport
+ Viewport,
+ LayerOrderGroup,
+ LayerOrder,
+ LayerOrderEntry,
+ FlatLayerOrder,
+ LayerOrderHierarchy
} from '@kepler.gl/types';
import {
FindDefaultLayerPropsReturnValue,
@@ -30,8 +35,8 @@ import {
import KeplerTable from '@kepler.gl/table';
import {VisState} from '@kepler.gl/schemas';
-import {isFunction, getMapLayersFromSplitMaps, DataRow} from '@kepler.gl/utils';
-import {arrayMove} from '@kepler.gl/common-utils';
+import {isFunction, getMapLayersFromSplitMaps, DataRow, isPlainObject} from '@kepler.gl/utils';
+import {arrayMove, generateHashId} from '@kepler.gl/common-utils';
import {ThreeDBuildingLayer} from '@kepler.gl/deckgl-layers';
@@ -411,6 +416,79 @@ export function bindLayerCallbacks(
);
}
+function computeDeckLayersFromLayerOrder(
+ layerOrder: LayerOrder,
+ layers: Layer[],
+ layerData: any[],
+ currentLayersForDeck: {[key: string]: boolean},
+ renderProps: {
+ datasets: any;
+ hoverInfo: any;
+ clicked: any;
+ mapState: any;
+ interactionConfig: any;
+ animationConfig: any;
+ mapLayers: any;
+ hasShadowEffect: boolean;
+ },
+ layerCallbacks?: any
+): any[] {
+ const {datasets, hoverInfo, clicked, mapState, interactionConfig, animationConfig, mapLayers, hasShadowEffect} = renderProps;
+ return layerOrder
+ .slice()
+ .reverse()
+ .reduce((overlays, element) => {
+ if (isPlainObject(element)) {
+ const layerGroup = element as LayerOrderGroup;
+ if (!layerGroup.isVisible) {
+ return overlays;
+ }
+ return overlays.concat(
+ computeDeckLayersFromLayerOrder(
+ layerGroup.layerOrder,
+ layers,
+ layerData,
+ currentLayersForDeck,
+ renderProps,
+ layerCallbacks
+ )
+ );
+ }
+ const layerId = element as string;
+ if (!currentLayersForDeck[layerId]) {
+ return overlays;
+ }
+ const layerIndex = layers.findIndex(({id}) => id === layerId);
+ if (layerIndex === -1) {
+ return overlays;
+ }
+ const bindedLayerCallbacks = layerCallbacks
+ ? bindLayerCallbacks(layerCallbacks, layerIndex)
+ : {};
+ const layer = layers[layerIndex];
+ const data = layerData[layerIndex];
+ const layerOverlay = renderDeckGlLayer(
+ {
+ datasets,
+ layer,
+ layerIndex,
+ data,
+ hoverInfo,
+ clicked,
+ mapState,
+ interactionConfig,
+ animationConfig,
+ mapLayers,
+ experimentalContext: {
+ hasShadowEffect
+ }
+ },
+ bindedLayerCallbacks
+ );
+ return overlays.concat(layerOverlay || []);
+ }, [] as any[]);
+}
+
// eslint-disable-next-line complexity
export function computeDeckLayers(
{visState, mapState, mapStyle}: any,
@@ -448,9 +526,31 @@ export function computeDeckLayers(
dataLayers = layerOrder
.slice()
.reverse()
- .filter(id => currentLayersForDeck[id])
- .reduce((overlays, layerId) => {
+ .reduce((overlays, element) => {
+ if (isPlainObject(element)) {
+ const layerGroup = element as LayerOrderGroup;
+ if (!layerGroup.isVisible) {
+ return overlays;
+ }
+ return overlays.concat(
+ computeDeckLayersFromLayerOrder(
+ layerGroup.layerOrder,
+ layers,
+ layerData,
+ currentLayersForDeck,
+ {datasets, hoverInfo, clicked, mapState, interactionConfig, animationConfig, mapLayers, hasShadowEffect},
+ layerCallbacks
+ )
+ );
+ }
+ const layerId = element as string;
+ if (!currentLayersForDeck[layerId]) {
+ return overlays;
+ }
const layerIndex = layers.findIndex(({id}) => id === layerId);
+ if (layerIndex === -1) {
+ return overlays;
+ }
const bindedLayerCallbacks = layerCallbacks
? bindLayerCallbacks(layerCallbacks, layerIndex)
: {};
@@ -519,21 +619,220 @@ export function getLayerOrderFromLayers<T extends {id: string}>(layers: T[]): st
return layers.map(({id}) => id);
}
+// --- Layer Group Utilities ---
+
+export function getNewLayerGroup(props?: Partial<LayerOrderGroup>): LayerOrderGroup {
+ return {
+ id: props?.id ?? generateHashId(6),
+ label: props?.label ?? 'New group',
+ isVisible: props?.isVisible ?? true,
+ layerOrder: props?.layerOrder ?? [],
+ isIncludedInLegend: props?.isIncludedInLegend ?? true
+ };
+}
+
+export function addLayerOrGroupToLayerOrder(
+ layerOrder: LayerOrder,
+ element: LayerOrderEntry,
+ atIndex?: number
+): LayerOrder {
+ const idx = atIndex ?? 0;
+ const result = [...layerOrder];
+ result.splice(idx, 0, element);
+ return result;
+}
+
+export function removeElementFromLayerOrder(
+ layerOrder: LayerOrder,
+ element: LayerOrderEntry
+): LayerOrder {
+ if (!layerOrder) return [];
+ const elementId = typeof element === 'string' ? element : element.id;
+ let newLayerOrder = layerOrder.filter(entry => {
+ if (isPlainObject(entry)) {
+ return (entry as LayerOrderGroup).id !== elementId;
+ }
+ return entry !== elementId;
+ });
+
+ newLayerOrder = newLayerOrder.map(entry => {
+ if (isPlainObject(entry)) {
+ const group = entry as LayerOrderGroup;
+ return {
+ ...group,
+ layerOrder: removeElementFromLayerOrder(group.layerOrder, elementId)
+ };
+ }
+ return entry;
+ });
+
+ return newLayerOrder;
+}
+
+export function getLayerGroupFromLayerOrder(
+ layerOrder: LayerOrder,
+ layerGroupId: string
+): LayerOrderGroup | undefined {
+ let group: LayerOrderGroup | undefined;
+ for (let i = 0; i < layerOrder.length && !group; i++) {
+ const entry = layerOrder[i];
+ if (isPlainObject(entry)) {
+ const grp = entry as LayerOrderGroup;
+ group =
+ grp.id === layerGroupId ? grp : getLayerGroupFromLayerOrder(grp.layerOrder, layerGroupId);
+ }
+ }
+ return group;
+}
+
+/**
+ * Find the parent group that contains a given layer ID.
+ * Returns undefined if the layer is at the root level.
+ */
+export function findParentGroupForLayer(
+ layerOrder: LayerOrder,
+ layerId: string
+): LayerOrderGroup | undefined {
+ for (const entry of layerOrder) {
+ if (isPlainObject(entry)) {
+ const group = entry as LayerOrderGroup;
+ if (group.layerOrder.some(e => typeof e === 'string' && e === layerId)) {
+ return group;
+ }
+ const nested = findParentGroupForLayer(group.layerOrder, layerId);
+ if (nested) return nested;
+ }
+ }
+ return undefined;
+}
+
+export function getIndexFromLayerEntryId(layerOrder: LayerOrder, layerEntryId: string): number {
+ return layerOrder.findIndex(entry =>
+ isPlainObject(entry) ? (entry as LayerOrderGroup).id === layerEntryId : entry === layerEntryId
+ );
+}
+
+export function isLayerPresentInLayerOrder(layerOrder: LayerOrder, layerId: string): boolean {
+ let found = false;
+ for (let i = 0; i < layerOrder.length && !found; i++) {
+ const entry = layerOrder[i];
+ if (isPlainObject(entry)) {
+ found = isLayerPresentInLayerOrder((entry as LayerOrderGroup).layerOrder, layerId);
+ } else {
+ found = layerId === entry;
+ }
+ }
+ return found;
+}
+
+export function replaceLayerEntryInLayerOrder(
+ layerOrder: LayerOrder,
+ oldEntry: LayerOrderEntry,
+ newEntry: LayerOrderEntry
+): LayerOrder {
+ const oldEntryId = typeof oldEntry === 'string' ? oldEntry : oldEntry.id;
+ return layerOrder.map(entry => {
+ if (typeof entry === 'string') {
+ return entry === oldEntryId ? newEntry : entry;
+ } else if (isPlainObject(entry)) {
+ const grp = entry as LayerOrderGroup;
+ if (grp.id === oldEntryId) {
+ return newEntry;
+ }
+ return {
+ ...grp,
+ layerOrder: replaceLayerEntryInLayerOrder(grp.layerOrder, oldEntry, newEntry)
+ };
+ }
+ return entry;
+ });
+}
+
+export function updateLayerGroupInLayerOrder(
+ layerOrder: LayerOrder,
+ newLayerGroup: LayerOrderGroup
+): LayerOrder {
+ return layerOrder.map(entry => {
+ if (isPlainObject(entry)) {
+ const grp = entry as LayerOrderGroup;
+ if (grp.id === newLayerGroup.id) {
+ return newLayerGroup;
+ }
+ return {
+ ...grp,
+ layerOrder: updateLayerGroupInLayerOrder(grp.layerOrder, newLayerGroup)
+ };
+ }
+ return entry;
+ });
+}
+
+export function getFlatLayerOrder(layerOrder: LayerOrder): FlatLayerOrder {
+ return layerOrder.reduce((acc, orderEntry) => {
+ if (isPlainObject(orderEntry)) {
+ return [...acc, ...getFlatLayerOrder((orderEntry as LayerOrderGroup).layerOrder)];
+ }
+ return [...acc, orderEntry as string];
+ }, [] as FlatLayerOrder);
+}
+
+export function buildLayerOrderHierarchy(
+ layerOrder: LayerOrder,
+ layers?: Layer[] | readonly Layer[]
+): LayerOrderHierarchy {
+ const validLayers = layers?.filter(Boolean);
+ return layerOrder.reduce((acc, element) => {
+ if (isPlainObject(element)) {
+ return [...acc, ['layerGroup', element as LayerOrderGroup] as const];
+ }
+ const layer = validLayers?.find(l => l.id === element);
+ if (!layer || layer.config.hidden) {
+ return acc;
+ }
+ return [...acc, ['layer', layer] as const];
+ }, [] as LayerOrderHierarchy);
+}
+
+export function removeGhostLayerFromLayerOrder(
+ layerOrder: LayerOrder,
+ layers: {id: string}[]
+): LayerOrder {
+ return layerOrder.reduce((acc, entry) => {
+ if (typeof entry === 'string') {
+ if (layers.find(l => l.id === entry)) {
+ acc.push(entry);
+ }
+ } else {
+ const grp = entry as LayerOrderGroup;
+ if (grp.layerOrder) {
+ acc.push({
+ ...grp,
+ layerOrder: removeGhostLayerFromLayerOrder(grp.layerOrder, layers)
+ });
+ }
+ }
+ return acc;
+ }, [] as LayerOrder);
+}
+
export function reorderLayerOrder(
layerOrder: VisState['layerOrder'],
originLayerId: string,
destinationLayerId: string
): VisState['layerOrder'] {
- const activeIndex = layerOrder.indexOf(originLayerId);
- const overIndex = layerOrder.indexOf(destinationLayerId);
+ const activeIndex = getIndexFromLayerEntryId(layerOrder, originLayerId);
+ const overIndex = getIndexFromLayerEntryId(layerOrder, destinationLayerId);
+ if (activeIndex === -1 || overIndex === -1) {
+ return layerOrder;
+ }
return arrayMove(layerOrder, activeIndex, overIndex);
}
export function addLayerToLayerOrder(
layerOrder: VisState['layerOrder'],
layerId: string
-): string[] {
+): LayerOrder {
return [layerId, ...layerOrder];
}
diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.ts
index f31dbd2c5..abbbcc6b7 100644
--- a/src/reducers/src/vis-state-merger.ts
+++ b/src/reducers/src/vis-state-merger.ts
@@ -11,7 +11,8 @@ import {
applyFiltersToDatasets,
validateFiltersUpdateDatasets,
findById,
- aggregate
+ aggregate,
+ isPlainObject
} from '@kepler.gl/utils';
import {Layer} from '@kepler.gl/layers';
@@ -41,7 +42,9 @@ import {
LayerColumn,
ParsedFilter,
NestedPartial,
- SavedAnimationConfig
+ SavedAnimationConfig,
+ LayerOrder,
+ LayerOrderGroup
} from '@kepler.gl/types';
import {KeplerTable, Datasets, assignGpuChannels, resetFilterGpuMode} from '@kepler.gl/table';
@@ -297,13 +300,25 @@ export function mergeLayers<S extends VisState>(
preserveLayerOrder
);
- return {
+ let mergedState: S = {
...state,
layers: newLayers,
layerOrder: newLayerOrder,
preserveLayerOrder,
layerToBeMerged: [...state.layerToBeMerged, ...unmerged]
};
+
+ // Apply pending layerOrder with groups if layers are now available
+ if (mergedState.layerOrderToBeMerged && mergedState.layers.length > 0) {
+ const savedOrder = mergedState.layerOrderToBeMerged;
+ mergedState = mergeLayerOrder(mergedState, savedOrder);
+ // Keep savedLayerOrder available for future deferred layers
+ if (mergedState.layerToBeMerged.length > 0) {
+ mergedState = {...mergedState, layerOrderToBeMerged: savedOrder};
+ }
+ }
+
+ return mergedState;
}
export function insertLayerAtRightOrder(
@@ -315,9 +330,9 @@ export function insertLayerAtRightOrder(
if (!layersToInsert?.length) {
return {newLayers: currentLayers, newLayerOrder: currentOrder};
}
- // perservedOrder ['a', 'b', 'c'];
- // layerOrder ['a', 'b', 'c']
+
const currentLayerQueue = currentOrder
+ .filter(entry => typeof entry === 'string')
.map(id => findById(id)(currentLayers))
.filter(layer => Boolean(layer));
const newLayers = currentLayers.concat(layersToInsert);
@@ -328,15 +343,130 @@ export function insertLayerAtRightOrder(
true
);
- // reconstruct layerOrder after insert
- const newLayerOrder = getLayerOrderFromLayers(newLayerOrderQueue);
+ const newFlatLayerOrder = getLayerOrderFromLayers(newLayerOrderQueue);
+
+ // If no groups exist in current order, just use the new flat order
+ const hasGroups = currentOrder.some(entry => isPlainObject(entry));
+ if (!hasGroups) {
+ return {
+ newLayerOrder: newFlatLayerOrder,
+ newLayers
+ };
+ }
+
+ // Rebuild layerOrder preserving groups in their relative positions.
+ // Replace each string entry with its updated position from newFlatLayerOrder,
+ // and keep groups as-is.
+ const existingFlatIds = new Set(
+ currentOrder.filter(entry => typeof entry === 'string') as string[]
+ );
+ const newInsertedIds = newFlatLayerOrder.filter(id => !existingFlatIds.has(id));
+
+ // Rebuild: walk through currentOrder, replace string entries with their
+ // new position equivalents from newFlatLayerOrder, then append any newly inserted layers
+ const result: LayerOrder = [];
+ const flatQueue = [...newFlatLayerOrder.filter(id => existingFlatIds.has(id))];
+ let flatIdx = 0;
+ for (const entry of currentOrder) {
+ if (isPlainObject(entry)) {
+ result.push(entry as LayerOrderGroup);
+ } else {
+ // Replace with corresponding entry from reordered flat list
+ if (flatIdx < flatQueue.length) {
+ result.push(flatQueue[flatIdx]);
+ flatIdx++;
+ }
+ }
+ }
+
+ // Append any newly inserted layers at the front (they are new)
return {
- newLayerOrder,
+ newLayerOrder: [...newInsertedIds, ...result],
newLayers
};
}
+/**
+ * Merge saved layerOrder with current state to restore layer groups.
+ * Called after layers have been merged. If the saved config contains a layerOrder
+ * with groups, this replaces the flat layerOrder with the saved hierarchical one,
+ * filtering out any layer IDs that don't exist in the current state.
+ */
+export function mergeLayerOrder<S extends VisState>(
+ state: S,
+ savedLayerOrder?: any[],
+ fromConfig?: boolean
+): S {
+ if (!savedLayerOrder || !Array.isArray(savedLayerOrder) || savedLayerOrder.length === 0) {
+ return state;
+ }
+
+ // Check if the saved layerOrder contains any groups
+ const hasGroups = savedLayerOrder.some(entry => isPlainObject(entry));
+ if (!hasGroups) {
+ // No groups - the layer merger already handled ordering via preserveLayerOrder
+ return state;
+ }
+
+ // If layers haven't been merged yet, store for later
+ if (state.layers.length === 0) {
+ return {
+ ...state,
+ layerOrderToBeMerged: savedLayerOrder
+ };
+ }
+
+ // Build a set of valid layer IDs from current state
+ const validLayerIds = new Set(state.layers.map(l => l.id));
+
+ // Recursively filter the saved layerOrder to only include valid layers
+ function filterLayerOrder(order: any[]): LayerOrder {
+ const result: LayerOrder = [];
+ for (const entry of order) {
+ if (isPlainObject(entry)) {
+ const group = entry as LayerOrderGroup;
+ const filteredGroupOrder = filterLayerOrder(group.layerOrder);
+ // Keep the group even if empty (user may want the empty group)
+ result.push({
+ ...group,
+ layerOrder: filteredGroupOrder
+ });
+ } else if (typeof entry === 'string' && validLayerIds.has(entry)) {
+ result.push(entry);
+ }
+ }
+ return result;
+ }
+
+ const restoredLayerOrder = filterLayerOrder(savedLayerOrder);
+
+ // Find any layers in the current state that aren't in the restored order
+ // (could happen if layers were added between save and load)
+ const layerIdsInRestored = new Set<string>();
+ function collectIds(order: any[]) {
+ for (const entry of order) {
+ if (isPlainObject(entry)) {
+ collectIds((entry as LayerOrderGroup).layerOrder);
+ } else if (typeof entry === 'string') {
+ layerIdsInRestored.add(entry);
+ }
+ }
+ }
+ collectIds(restoredLayerOrder);
+
+ // Add any missing layers at the top
+ const missingLayers = state.layers
+ .filter(l => !layerIdsInRestored.has(l.id))
+ .map(l => l.id);
+
+ return {
+ ...state,
+ layerOrder: [...missingLayers, ...restoredLayerOrder],
+ layerOrderToBeMerged: null
+ };
+}
+
/**
* Merge interactions with saved config
*
@@ -1159,6 +1289,10 @@ export const VIS_STATE_MERGERS: VisStateMergers<any> = [
toMergeProp: 'layerToBeMerged',
preserveOrder: 'preserveLayerOrder'
},
+ {
+ merge: mergeLayerOrder,
+ prop: 'layerOrder'
+ },
{
merge: mergeFilters,
prop: 'filters',
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index d3c06cb23..681361368 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -77,7 +77,7 @@ import {
isSideFilter,
getApplicationConfig
} from '@kepler.gl/utils';
-import {generateHashId, toArray} from '@kepler.gl/common-utils';
+import {generateHashId, toArray, arrayMove} from '@kepler.gl/common-utils';
// Mergers
import {
ANIMATION_WINDOW,
@@ -158,7 +158,16 @@ import {
calculateLayerData,
findDefaultLayer,
getLayerOrderFromLayers,
- mergeLayerVisConfigForNewDatasets
+ mergeLayerVisConfigForNewDatasets,
+ getNewLayerGroup,
+ addLayerOrGroupToLayerOrder,
+ removeElementFromLayerOrder,
+ getLayerGroupFromLayerOrder,
+ findParentGroupForLayer,
+ getIndexFromLayerEntryId,
+ updateLayerGroupInLayerOrder,
+ getFlatLayerOrder,
+ replaceLayerEntryInLayerOrder
} from './layer-utils';
import {getPropValueToMerger, hasPropsToMerge} from './merger-handler';
import {mergeDatasetsByOrder} from './vis-state-merger';
@@ -299,6 +308,7 @@ export const INITIAL_VIS_STATE: VisState = {
layerData: [],
layerToBeMerged: [],
layerOrder: [],
+ layerOrderToBeMerged: null,
// filters
filters: [],
@@ -1021,9 +1031,7 @@ export function layerTypeChangeUpdater(
// update layerOrder with new id
newState = {
...newState,
- layerOrder: newState.layerOrder.map(layerId =>
- layerId === oldLayer.id ? newLayer.id : layerId
- )
+ layerOrder: replaceLayerEntryInLayerOrder(newState.layerOrder, oldLayer.id, newLayer.id)
};
return newState;
@@ -1888,7 +1896,7 @@ export function removeLayerUpdater<T extends VisState>(
...state,
layers: filterOutById(layerToRemove.id)(layers),
layerData: removeElementAtIndex(idx)(layerData),
- layerOrder: layerOrder.filter(layerId => layerId !== layerToRemove.id),
+ layerOrder: removeElementFromLayerOrder(layerOrder, layerToRemove.id),
clicked: layerToRemove.isLayerHovered(clicked) ? undefined : clicked,
hoverInfo: layerToRemove.isLayerHovered(hoverInfo) ? undefined : hoverInfo,
splitMaps: removeLayerFromSplitMaps(state.splitMaps, layerToRemove)
@@ -1911,6 +1919,263 @@ export const reorderLayerUpdater = (
layerOrder: order
});
+/**
+ * Add a new layer group
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const addLayerGroupUpdater = (
+ state: VisState,
+ action: VisStateActions.AddLayerGroupUpdaterAction
+): VisState => {
+ const layerGroup = getNewLayerGroup(action);
+ let newLayerOrder = [...state.layerOrder];
+
+ if (action.layerOrder) {
+ action.layerOrder.forEach(layerId => {
+ newLayerOrder = removeElementFromLayerOrder(newLayerOrder, layerId as string);
+ });
+ }
+
+ return {
+ ...state,
+ layerOrder: addLayerOrGroupToLayerOrder(newLayerOrder, layerGroup)
+ };
+};
+
+/**
+ * Remove a layer group and all layers within it
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const removeLayerGroupUpdater = (
+ state: VisState,
+ action: VisStateActions.RemoveLayerGroupUpdaterAction
+): VisState => {
+ const {id} = action;
+ const layerGroupToRemove = getLayerGroupFromLayerOrder(state.layerOrder, id);
+ if (!layerGroupToRemove) {
+ return state;
+ }
+
+ const layerIdsToRemove = getFlatLayerOrder(layerGroupToRemove.layerOrder);
+ let newState = {...state};
+
+ layerIdsToRemove.forEach(layerId => {
+ const idx = newState.layers.findIndex(l => l.id === layerId);
+ if (idx >= 0) {
+ newState = removeLayerUpdater(newState, {id: layerId});
+ }
+ });
+
+ const newLayerOrder = removeElementFromLayerOrder(newState.layerOrder, layerGroupToRemove);
+ return {
+ ...newState,
+ layerOrder: newLayerOrder
+ };
+};
+
+/**
+ * Update a layer group (label, visibility, layer membership)
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const updateLayerGroupUpdater = (
+ state: VisState,
+ action: VisStateActions.UpdateLayerGroupUpdaterAction
+): VisState => {
+ const {id, options} = action;
+ const layerGroup = getLayerGroupFromLayerOrder(state.layerOrder, id);
+ if (!layerGroup) {
+ return state;
+ }
+
+ let newState = {...state};
+
+ if (options.layerOrder) {
+ newState.layerOrder = [...layerGroup.layerOrder, ...newState.layerOrder];
+ options.layerOrder.forEach(layerId => {
+ newState.layerOrder = removeElementFromLayerOrder(
+ newState.layerOrder,
+ layerId as string
+ );
+ });
+ }
+
+ const newLayerGroup = {
+ ...layerGroup,
+ ...options
+ };
+
+ if (newLayerGroup.isVisible !== layerGroup.isVisible) {
+ const layerIds = getFlatLayerOrder(newLayerGroup.layerOrder);
+ newState = newState.layers.reduce((acc, layer) => {
+ if (layerIds.includes(layer.id)) {
+ return layerConfigChangeUpdater(acc, {
+ oldLayer: layer,
+ newConfig: {isVisible: newLayerGroup.isVisible}
+ });
+ }
+ return acc;
+ }, newState);
+ }
+
+ const newLayerOrder = updateLayerGroupInLayerOrder(newState.layerOrder, newLayerGroup);
+ return {
+ ...newState,
+ layerOrder: newLayerOrder
+ };
+};
+
+/**
+ * Add a layer to a layer group
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const addLayerToLayerGroupUpdater = (
+ state: VisState,
+ action: VisStateActions.AddLayerToLayerGroupUpdaterAction
+): VisState => {
+ const {layerGroupId, layerId} = action;
+ const layerGroup = getLayerGroupFromLayerOrder(state.layerOrder, layerGroupId);
+ const layer = state.layers.find(l => l.id === layerId);
+ if (!layerGroup || !layer) {
+ return state;
+ }
+
+ if (layerGroup.layerOrder.find(entry => entry === layerId)) {
+ return state;
+ }
+
+ const newGroupLayerOrder = addLayerOrGroupToLayerOrder(layerGroup.layerOrder, layerId);
+ return updateLayerGroupUpdater(state, {
+ id: layerGroupId,
+ options: {layerOrder: newGroupLayerOrder}
+ });
+};
+
+/**
+ * Remove a layer from a layer group
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const removeLayerFromLayerGroupUpdater = (
+ state: VisState,
+ action: VisStateActions.RemoveLayerFromLayerGroupUpdaterAction
+): VisState => {
+ const {layerGroupId, layerId} = action;
+ const layerGroup = getLayerGroupFromLayerOrder(state.layerOrder, layerGroupId);
+ if (!layerGroup) {
+ return state;
+ }
+
+ const newLayerGroupOrder = removeElementFromLayerOrder(layerGroup.layerOrder, layerId);
+ return updateLayerGroupUpdater(state, {
+ id: layerGroupId,
+ options: {layerOrder: newLayerGroupOrder}
+ });
+};
+
+/**
+ * Swap layer order entries between root and groups
+ * @memberof visStateUpdaters
+ * @public
+ */
+// eslint-disable-next-line complexity
+export const swapLayerOrderEntriesUpdater = (
+ state: VisState,
+ action: VisStateActions.SwapLayerOrderEntriesUpdaterAction
+): VisState => {
+ const {originLayerId, destinationLayerId, originLayerGroupId, destinationLayerGroupId} = action;
+
+ if (!originLayerGroupId && !destinationLayerGroupId) {
+ const originIndex = state.layerOrder.findIndex(entry =>
+ typeof entry === 'string' ? entry === originLayerId : entry.id === originLayerId
+ );
+ if (destinationLayerId && originIndex !== -1) {
+ const destinationIndex = state.layerOrder.findIndex(entry =>
+ typeof entry === 'string' ? entry === destinationLayerId : entry.id === destinationLayerId
+ );
+ if (destinationIndex !== -1) {
+ const newLayerOrder = arrayMove(state.layerOrder, originIndex, destinationIndex);
+ return {...state, layerOrder: newLayerOrder};
+ }
+ }
+ }
+
+ if (originLayerGroupId && !destinationLayerGroupId) {
+ let newLayerOrder = removeElementFromLayerOrder(state.layerOrder, originLayerId);
+ if (destinationLayerId) {
+ const destinationIndex = newLayerOrder.findIndex(entry =>
+ typeof entry === 'string' ? entry === destinationLayerId : false
+ );
+ newLayerOrder.splice(destinationIndex === -1 ? 0 : destinationIndex, 0, originLayerId);
+ } else {
+ newLayerOrder = [...newLayerOrder, originLayerId];
+ }
+ return {...state, layerOrder: newLayerOrder};
+ }
+
+ if (originLayerGroupId && destinationLayerGroupId) {
+ if (originLayerGroupId === destinationLayerGroupId) {
+ const layerGroup = getLayerGroupFromLayerOrder(state.layerOrder, originLayerGroupId);
+ if (!layerGroup) return state;
+ const originIndex = layerGroup.layerOrder.findIndex(entry =>
+ typeof entry === 'string' ? entry === originLayerId : entry.id === originLayerId
+ );
+ if (originIndex === -1) return state;
+ if (destinationLayerId) {
+ const destIndex = layerGroup.layerOrder.findIndex(entry =>
+ typeof entry === 'string' ? entry === destinationLayerId : entry.id === destinationLayerId
+ );
+ if (destIndex === -1) return state;
+ const newGroupLayerOrder = arrayMove(layerGroup.layerOrder, originIndex, destIndex);
+ const newLayerOrder = updateLayerGroupInLayerOrder(state.layerOrder, {
+ ...layerGroup,
+ layerOrder: newGroupLayerOrder
+ });
+ return {...state, layerOrder: newLayerOrder};
+ }
+ return state;
+ }
+
+ // Cross-group move: remove from origin, then add to destination
+ const layerOrder = removeElementFromLayerOrder(state.layerOrder, originLayerId);
+ let newState = addLayerToLayerGroupUpdater(
+ {...state, layerOrder},
+ {layerId: originLayerId, layerGroupId: destinationLayerGroupId}
+ );
+
+ if (destinationLayerId) {
+ const layerGroup = getLayerGroupFromLayerOrder(newState.layerOrder, destinationLayerGroupId);
+ if (!layerGroup) return state;
+ const originIndex = layerGroup.layerOrder.findIndex(entry => entry === originLayerId);
+ const destIndex = layerGroup.layerOrder.findIndex(entry => entry === destinationLayerId);
+ if (originIndex !== -1 && destIndex !== -1) {
+ const newGroupLayerOrder = arrayMove(layerGroup.layerOrder, originIndex, destIndex);
+ newState = {
+ ...newState,
+ layerOrder: updateLayerGroupInLayerOrder(newState.layerOrder, {
+ ...layerGroup,
+ layerOrder: newGroupLayerOrder
+ })
+ };
+ }
+ }
+ return newState;
+ }
+
+ if (!originLayerGroupId && destinationLayerGroupId) {
+ const layerOrder = removeElementFromLayerOrder(state.layerOrder, originLayerId);
+ return addLayerToLayerGroupUpdater(
+ {...state, layerOrder},
+ {layerId: originLayerId, layerGroupId: destinationLayerGroupId}
+ );
+ }
+
+ return state;
+};
+
/**
* duplicate layer
* @memberof visStateUpdaters
@@ -1932,7 +2197,7 @@ export const duplicateLayerUpdater = (
const {layers} = state;
const original = layers[idx];
- const originalLayerOrderIdx = state.layerOrder.findIndex(lid => lid === original.id);
+ const originalLayerOrderIdx = getIndexFromLayerEntryId(state.layerOrder, original.id);
let newLabel = `Copy of ${original.config.label}`;
let postfix = 0;
// eslint-disable-next-line no-loop-func
@@ -1954,14 +2219,30 @@ export const duplicateLayerUpdater = (
let nextState = addLayerUpdater(state, {config: loadedLayer});
// retrieve newly created layer
const newLayer = nextState.layers[nextState.layers.length - 1];
- // update layer order with newLyaer.id
- const newLayerOrder = arrayInsert(
- nextState.layerOrder.slice(1, nextState.layerOrder.length),
- originalLayerOrderIdx,
- newLayer.id
- );
- nextState = reorderLayerUpdater(nextState, {order: newLayerOrder});
+ // Check if the original layer is inside a group
+ const parentGroup = findParentGroupForLayer(state.layerOrder, original.id);
+
+ if (parentGroup) {
+ // Layer is inside a group - remove the prepended id from root and insert into the group
+ const layerOrderWithoutPrepended = nextState.layerOrder.slice(1);
+ const idxInGroup = parentGroup.layerOrder.findIndex(e => e === original.id);
+ const newGroupLayerOrder = arrayInsert(parentGroup.layerOrder, idxInGroup, newLayer.id);
+ const updatedGroup = {...parentGroup, layerOrder: newGroupLayerOrder};
+ const newLayerOrder = updateLayerGroupInLayerOrder(
+ layerOrderWithoutPrepended,
+ updatedGroup
+ );
+ nextState = reorderLayerUpdater(nextState, {order: newLayerOrder});
+ } else {
+ // Layer is at root level - use original index-based insertion
+ const newLayerOrder = arrayInsert(
+ nextState.layerOrder.slice(1, nextState.layerOrder.length),
+ originalLayerOrderIdx,
+ newLayer.id
+ );
+ nextState = reorderLayerUpdater(nextState, {order: newLayerOrder});
+ }
return updateAnimationDomain(nextState);
};
diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.ts
index 29acda538..1fb2b0056 100644
--- a/src/reducers/src/vis-state.ts
+++ b/src/reducers/src/vis-state.ts
@@ -72,6 +72,18 @@ const actionHandler = {
[ActionTypes.REORDER_LAYER]: visStateUpdaters.reorderLayerUpdater,
+ [ActionTypes.ADD_LAYER_GROUP]: visStateUpdaters.addLayerGroupUpdater,
+
+ [ActionTypes.REMOVE_LAYER_GROUP]: visStateUpdaters.removeLayerGroupUpdater,
+
+ [ActionTypes.UPDATE_LAYER_GROUP]: visStateUpdaters.updateLayerGroupUpdater,
+
+ [ActionTypes.ADD_LAYER_TO_LAYER_GROUP]: visStateUpdaters.addLayerToLayerGroupUpdater,
+
+ [ActionTypes.REMOVE_LAYER_FROM_LAYER_GROUP]: visStateUpdaters.removeLayerFromLayerGroupUpdater,
+
+ [ActionTypes.SWAP_LAYER_ORDER_ENTRIES]: visStateUpdaters.swapLayerOrderEntriesUpdater,
+
[ActionTypes.RESET_MAP_CONFIG]: visStateUpdaters.resetMapConfigUpdater,
[ActionTypes.SET_FILTER]: visStateUpdaters.setFilterUpdater,
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index 0fe7c71bd..3ceebc428 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -4,7 +4,7 @@
import pick from 'lodash/pick';
import {VERSIONS} from './versions';
import {LAYER_VIS_CONFIGS, FILTER_VIEW_TYPES} from '@kepler.gl/constants';
-import {colorRangeBackwardCompatibility, isFilterValidToSave, findById} from '@kepler.gl/utils';
+import {colorRangeBackwardCompatibility, isFilterValidToSave, findById, isPlainObject} from '@kepler.gl/utils';
import {notNullorUndefined} from '@kepler.gl/common-utils';
import Schema from './schema';
import cloneDeep from 'lodash/cloneDeep';
@@ -16,6 +16,7 @@ import {
FileLoadingProgress,
Filter,
InteractionConfig,
+ LayerOrder,
MapInfo,
ParsedFilter,
ParsedLayer,
@@ -54,7 +55,8 @@ export interface VisState {
layers: Layer[];
layerData: any[];
layerToBeMerged: any[];
- layerOrder: string[];
+ layerOrder: LayerOrder;
+ layerOrderToBeMerged: any[] | null;
effects: Effect[];
effectOrder: string[];
annotations: Annotation[];
@@ -576,9 +578,23 @@ export class LayerSchemaV0 extends Schema {
const [visState] = parents.slice(-1);
return {
- [this.key as 'layers']: visState.layerOrder.reduce((saved, layerId) => {
- // save layers according to their rendering order
- const layer = findById(layerId)(layers);
+ [this.key as 'layers']: visState.layerOrder.reduce((saved, entry) => {
+ if (isPlainObject(entry)) {
+ const group = entry as Record<string, unknown>;
+ const groupLayerOrder = group.layerOrder as any[];
+ if (groupLayerOrder) {
+ groupLayerOrder.forEach(nestedEntry => {
+ if (typeof nestedEntry === 'string') {
+ const layer = findById(nestedEntry)(layers);
+ if (layer?.isValidToSave()) {
+ saved.push(this.savePropertiesOrApplySchema(layer).layers);
+ }
+ }
+ });
+ }
+ return saved;
+ }
+ const layer = findById(entry as string)(layers);
if (layer?.isValidToSave()) {
saved.push(this.savePropertiesOrApplySchema(layer).layers);
}
@@ -966,7 +982,8 @@ export const propertiesV1 = {
visible: null
},
key: 'editor'
- })
+ }),
+ layerOrder: null
};
export class VisStateSchemaV1 extends Schema {
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index 1a0110ed1..289c2ea78 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -255,6 +255,20 @@ export type SplitMap = {
layers: SplitMapLayers;
};
+export type LayerOrderGroup = {
+ id: string;
+ label: string;
+ isVisible: boolean;
+ layerOrder: LayerOrder;
+ isIncludedInLegend: boolean;
+};
+
+export type LayerOrderEntry = string | LayerOrderGroup;
+export type LayerOrder = LayerOrderEntry[];
+export type FlatLayerOrder = string[];
+export type LayerOrderHierarchyEntry = ['layer', any] | ['layerGroup', LayerOrderGroup];
+export type LayerOrderHierarchy = LayerOrderHierarchyEntry[];
+
/** See "Locale aware formats" at https://momentjs.com/docs/#/parsing/string-format/ */
export type AnimationConfigTimeFormat = 'L' | 'L LT' | 'L LTS';
diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.ts
index 81f8ec5a0..0e0fce7ce 100644
--- a/src/types/schemas.d.ts
+++ b/src/types/schemas.d.ts
@@ -107,6 +107,7 @@ export type SavedVisState = {
splitMaps: SplitMap[];
animationConfig: SavedAnimationConfig;
editor?: SavedEditor;
+ layerOrder?: any[];
};
// Min saved config can be passed to addDataToMap
@@ -132,6 +133,7 @@ export type ParsedVisState = {
overlayBlending?: string;
splitMaps?: SplitMap[];
animationConfig?: Partial<SavedAnimationConfig>;
+ layerOrder?: any[];
};
export type ParsedUiState = {
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 19fcb9c4e..2ce588f09 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -128,6 +128,9 @@ export type KeplerApplicationConfig = {
/** Whether to enable the swipe compare mode in split map view. Enabled by default. */
enableSwipeMode?: boolean;
+ /** Whether to enable the layer groups feature. Enabled by default. */
+ enableLayerGroups?: boolean;
+
/**
* Custom SVG icons to be made available in the icon layer.
* These icons will be merged with the default icons fetched from CDN.
@@ -237,6 +240,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableSwipeMode: true,
+ enableLayerGroups: true,
+
customIcons: [],
customIconUrl: ''
diff --git a/test/browser/components/geocoder-panel-test.js b/test/browser/components/geocoder-panel-test.js
index c22eb2e8d..b99a556f6 100644
--- a/test/browser/components/geocoder-panel-test.js
+++ b/test/browser/components/geocoder-panel-test.js
@@ -122,7 +122,7 @@ test('GeocoderPanel - render', t => {
}
}
],
- layerOrder: ['geocoder_layer', 'layer_1', 'layer_2']
+ layerOrder: ['geocoder_layer']
}
}
];
diff --git a/test/browser/components/hooks/use-dnd-layers.spec.js b/test/browser/components/hooks/use-dnd-layers.spec.js
index 0315d024d..1d4ea5aaf 100644
--- a/test/browser/components/hooks/use-dnd-layers.spec.js
+++ b/test/browser/components/hooks/use-dnd-layers.spec.js
@@ -4,21 +4,19 @@
import {renderHook, act} from '@testing-library/react';
import {useDispatch} from 'react-redux';
import {useDndLayers} from '@kepler.gl/components';
-import {layerConfigChange, reorderLayer, toggleLayerForMap} from '@kepler.gl/actions';
+import {reorderLayer, toggleLayerForMap} from '@kepler.gl/actions';
import {
DROPPABLE_MAP_CONTAINER_TYPE,
SORTABLE_LAYER_TYPE,
- SORTABLE_SIDE_PANEL_TYPE
+ SORTABLE_LAYER_GROUP_DROPPABLE_TYPE
} from '@kepler.gl/components/common/dnd-layer-items';
import {reorderLayerOrder} from '@kepler.gl/reducers';
-// Mock useDispatch hook
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useDispatch: jest.fn()
}));
-// Mock dependencies
jest.mock('@kepler.gl/actions', () => ({
...jest.requireActual('@kepler.gl/actions'),
layerConfigChange: jest.fn(),
@@ -27,17 +25,18 @@ jest.mock('@kepler.gl/actions', () => ({
}));
jest.mock('@kepler.gl/reducers', () => ({
+ ...jest.requireActual('@kepler.gl/reducers'),
reorderLayerOrder: jest.fn()
}));
describe('useDndLayers', () => {
const layers = [
- {id: 1, name: 'Layer 1', config: {isConfigActive: false}},
- {id: 2, name: 'Layer 2', config: {isConfigActive: false}},
- {id: 3, name: 'Layer 3', config: {isConfigActive: false}}
+ {id: '1', name: 'Layer 1', config: {isConfigActive: false}},
+ {id: '2', name: 'Layer 2', config: {isConfigActive: false}},
+ {id: '3', name: 'Layer 3', config: {isConfigActive: false}}
];
- const layerOrder = [2, 1, 3];
+ const layerOrder = ['2', '1', '3'];
const dispatchMock = jest.fn();
@@ -48,7 +47,6 @@ describe('useDndLayers', () => {
afterEach(() => {
useDispatch.mockReset();
dispatchMock.mockReset();
- layerConfigChange.mockReset();
reorderLayer.mockReset();
toggleLayerForMap.mockReset();
reorderLayerOrder.mockReset();
@@ -57,69 +55,62 @@ describe('useDndLayers', () => {
test('should initialize with correct initial state', () => {
const {result} = renderHook(() => useDndLayers(layers, layerOrder));
- expect(result.current.activeLayer).toBeUndefined();
+ expect(result.current.activeElement).toBeUndefined();
expect(result.current.onDragStart).toBeInstanceOf(Function);
expect(result.current.onDragEnd).toBeInstanceOf(Function);
});
- test('onDragStart should update activeLayer and dispatch layerConfigChange if config is active', () => {
- const currentLayers = [
- {id: 1, name: 'Layer 1', config: {isConfigActive: false}},
- {id: 2, name: 'Layer 2', config: {isConfigActive: true}},
- {id: 3, name: 'Layer 3', config: {isConfigActive: false}}
- ];
- const {result} = renderHook(() => useDndLayers(currentLayers, layerOrder));
+ test('onDragStart should update activeElement for layer type', () => {
+ const {result} = renderHook(() => useDndLayers(layers, layerOrder));
const event = {
- active: {id: 2}
+ active: {id: '2', data: {current: {type: SORTABLE_LAYER_TYPE}}}
};
act(() => {
result.current.onDragStart(event);
});
- expect(result.current.activeLayer).toEqual(currentLayers[1]);
- expect(dispatchMock).toHaveBeenCalledTimes(1);
- expect(layerConfigChange).toHaveBeenCalledWith(currentLayers[1], {isConfigActive: false});
+ expect(result.current.activeElement).toEqual(['layer', layers[1]]);
});
- test('onDragStart should not dispatch layerConfigChange if config is not active', () => {
+ test('onDragStart should not set activeElement if type is not provided', () => {
const {result} = renderHook(() => useDndLayers(layers, layerOrder));
const event = {
- active: {id: 1}
+ active: {id: '1', data: {current: {}}}
};
act(() => {
result.current.onDragStart(event);
});
- expect(result.current.activeLayer).toEqual(layers[0]);
- expect(dispatchMock).not.toHaveBeenCalled();
- expect(layerConfigChange).not.toHaveBeenCalled();
+ expect(result.current.activeElement).toBeUndefined();
});
- test('onDragEnd should reset activeLayer if overType is not defined', () => {
+ test('onDragEnd should reset activeElement if overId is null and no parent', () => {
const {result} = renderHook(() => useDndLayers(layers, layerOrder));
const event = {
- active: {id: 2},
- over: {}
+ active: {id: '2', data: {current: {type: SORTABLE_LAYER_TYPE}}},
+ over: null
};
act(() => {
result.current.onDragEnd(event);
});
- expect(result.current.activeLayer).toBeUndefined();
+ expect(result.current.activeElement).toBeUndefined();
+ expect(dispatchMock).not.toHaveBeenCalled();
});
test('onDragEnd should dispatch toggleLayerForMap when overType is DROPPABLE_MAP_CONTAINER_TYPE', () => {
const {result} = renderHook(() => useDndLayers(layers, layerOrder));
const event = {
- active: {id: 1},
+ active: {id: '1', data: {current: {type: SORTABLE_LAYER_TYPE}}},
over: {
+ id: 'map-0',
data: {
current: {
type: DROPPABLE_MAP_CONTAINER_TYPE,
@@ -134,24 +125,26 @@ describe('useDndLayers', () => {
});
expect(dispatchMock).toHaveBeenCalledTimes(1);
- expect(toggleLayerForMap).toHaveBeenCalledWith(1, 1);
+ expect(toggleLayerForMap).toHaveBeenCalledWith(1, '1');
});
- test('onDragEnd should dispatch reorderLayer when overType is SORTABLE_LAYER_TYPE', () => {
+ test('onDragEnd should dispatch reorderLayer when dropping layer at same level', () => {
const {result} = renderHook(() => useDndLayers(layers, layerOrder));
const event = {
- active: {id: 2},
+ active: {id: '2', data: {current: {type: SORTABLE_LAYER_TYPE, parent: undefined}}},
over: {
+ id: '1',
data: {
current: {
- type: SORTABLE_LAYER_TYPE
+ type: SORTABLE_LAYER_TYPE,
+ parent: undefined
}
}
}
};
- const newLayerOrder = [1, 2, 3];
+ const newLayerOrder = ['1', '2', '3'];
reorderLayerOrder.mockReturnValue(newLayerOrder);
act(() => {
@@ -162,40 +155,78 @@ describe('useDndLayers', () => {
expect(reorderLayer).toHaveBeenCalledWith(newLayerOrder);
});
- test('onDragEnd should dispatch reorderLayer when overType is SORTABLE_SIDE_PANEL_TYPE', () => {
- const {result} = renderHook(() => useDndLayers(layers, layerOrder));
+ test('onDragEnd should reorder within same group even with different parent object instances', () => {
+ const layerGroup = {id: 'group1', label: 'Group 1', isVisible: true, layerOrder: ['2', '3']};
+ const layerOrderWithGroup = ['1', layerGroup];
+
+ const {result} = renderHook(() => useDndLayers(layers, layerOrderWithGroup));
+
+ const newGroupOrder = ['3', '2'];
+ reorderLayerOrder.mockReturnValue(newGroupOrder);
const event = {
- active: {id: 2},
+ active: {id: '2', data: {current: {type: SORTABLE_LAYER_TYPE, parent: {id: 'group1', label: 'Group 1', isVisible: true, layerOrder: ['2', '3']}}}},
over: {
+ id: '3',
data: {
current: {
- type: SORTABLE_SIDE_PANEL_TYPE
+ type: SORTABLE_LAYER_TYPE,
+ parent: {id: 'group1', label: 'Group 1', isVisible: true, layerOrder: ['2', '3']}
}
}
}
};
- const newLayerOrder = [1, 3, 2];
- reorderLayerOrder.mockReturnValue(newLayerOrder);
+ act(() => {
+ result.current.onDragEnd(event);
+ });
+
+ expect(dispatchMock).toHaveBeenCalledTimes(1);
+ expect(reorderLayer).toHaveBeenCalled();
+ expect(reorderLayerOrder).toHaveBeenCalledWith(layerGroup.layerOrder, '2', '3');
+ });
+
+ test('onDragEnd should dispatch reorderLayer when moving layer into a group', () => {
+ const layerGroup = {id: 'group1', label: 'Group 1', isVisible: true, layerOrder: ['3']};
+ const layerOrderWithGroup = ['2', '1', layerGroup];
+
+ const {result} = renderHook(() => useDndLayers(layers, layerOrderWithGroup));
+
+ const event = {
+ active: {id: '2', data: {current: {type: SORTABLE_LAYER_TYPE, parent: undefined}}},
+ over: {
+ id: 'group1',
+ data: {
+ current: {
+ type: SORTABLE_LAYER_GROUP_DROPPABLE_TYPE
+ }
+ }
+ }
+ };
act(() => {
result.current.onDragEnd(event);
});
expect(dispatchMock).toHaveBeenCalledTimes(1);
- expect(reorderLayer).toHaveBeenCalledWith(newLayerOrder);
+ expect(reorderLayer).toHaveBeenCalled();
});
- test('onDragEnd should do nothing if overType does not match any case', () => {
- const {result} = renderHook(() => useDndLayers(layers, layerOrder));
+ test('onDragEnd should not dispatch if overType is unknown and parents differ without group droppable', () => {
+ const layerGroup1 = {id: 'group1', label: 'Group 1', isVisible: true, layerOrder: ['2']};
+ const layerGroup2 = {id: 'group2', label: 'Group 2', isVisible: true, layerOrder: ['3']};
+ const layerOrderWithGroups = ['1', layerGroup1, layerGroup2];
+
+ const {result} = renderHook(() => useDndLayers(layers, layerOrderWithGroups));
const event = {
- active: {id: 2},
+ active: {id: '1', data: {current: {type: SORTABLE_LAYER_TYPE, parent: undefined}}},
over: {
+ id: 'unknown',
data: {
current: {
- type: 'UNKNOWN_TYPE'
+ type: 'UNKNOWN_TYPE',
+ parent: layerGroup2
}
}
}
@@ -205,8 +236,6 @@ describe('useDndLayers', () => {
result.current.onDragEnd(event);
});
- expect(dispatchMock).not.toHaveBeenCalled();
- expect(reorderLayer).not.toHaveBeenCalled();
expect(toggleLayerForMap).not.toHaveBeenCalled();
});
});
diff --git a/test/node/reducers/index.js b/test/node/reducers/index.js
index 0f3c79cf7..4e895c2d4 100644
--- a/test/node/reducers/index.js
+++ b/test/node/reducers/index.js
@@ -16,3 +16,7 @@ import './annotation-merger-test';
// test annotation updaters
import './annotation-updater-test';
+
+// test layer groups
+import './layer-group-test';
+import './layer-group-updaters-test';
diff --git a/test/node/reducers/layer-group-test.js b/test/node/reducers/layer-group-test.js
new file mode 100644
index 000000000..24ae2d2a5
--- /dev/null
+++ b/test/node/reducers/layer-group-test.js
@@ -0,0 +1,491 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {
+ getNewLayerGroup,
+ addLayerOrGroupToLayerOrder,
+ removeElementFromLayerOrder,
+ getLayerGroupFromLayerOrder,
+ findParentGroupForLayer,
+ getIndexFromLayerEntryId,
+ isLayerPresentInLayerOrder,
+ replaceLayerEntryInLayerOrder,
+ updateLayerGroupInLayerOrder,
+ getFlatLayerOrder,
+ buildLayerOrderHierarchy,
+ removeGhostLayerFromLayerOrder,
+ reorderLayerOrder,
+ insertLayerAtRightOrder,
+ mergeLayerOrder
+} from '@kepler.gl/reducers';
+
+// ============================================================================
+// Test Fixtures
+// ============================================================================
+
+const GROUP_1 = {
+ id: 'group_1',
+ label: 'Group 1',
+ isVisible: true,
+ isIncludedInLegend: true,
+ layerOrder: ['layer_a', 'layer_b']
+};
+
+const GROUP_2 = {
+ id: 'group_2',
+ label: 'Group 2',
+ isVisible: true,
+ isIncludedInLegend: true,
+ layerOrder: ['layer_c']
+};
+
+const NESTED_GROUP = {
+ id: 'nested_group',
+ label: 'Nested Group',
+ isVisible: true,
+ isIncludedInLegend: true,
+ layerOrder: ['layer_d']
+};
+
+const GROUP_WITH_NESTED = {
+ id: 'group_nested',
+ label: 'Group With Nested',
+ isVisible: true,
+ isIncludedInLegend: true,
+ layerOrder: [NESTED_GROUP, 'layer_e']
+};
+
+const MOCK_LAYER_ORDER = ['layer_0', GROUP_1, GROUP_2, 'layer_f'];
+
+const COMPLEX_LAYER_ORDER = ['layer_0', GROUP_WITH_NESTED, GROUP_2, 'layer_f'];
+
+// ============================================================================
+// getNewLayerGroup
+// ============================================================================
+
+test('layerGroupUtils -> getNewLayerGroup -> default values', t => {
+ const group = getNewLayerGroup({});
+ t.ok(group.id, 'should generate an id');
+ t.equal(group.label, 'New group', 'should have default label');
+ t.equal(group.isVisible, true, 'should be visible by default');
+ t.equal(group.isIncludedInLegend, true, 'should be in legend by default');
+ t.deepEqual(group.layerOrder, [], 'should have empty layerOrder');
+ t.end();
+});
+
+test('layerGroupUtils -> getNewLayerGroup -> custom values', t => {
+ const group = getNewLayerGroup({
+ id: 'custom_id',
+ label: 'My Group',
+ isVisible: false,
+ layerOrder: ['layer_1'],
+ isIncludedInLegend: false
+ });
+ t.equal(group.id, 'custom_id', 'should use provided id');
+ t.equal(group.label, 'My Group', 'should use provided label');
+ t.equal(group.isVisible, false, 'should use provided visibility');
+ t.deepEqual(group.layerOrder, ['layer_1'], 'should use provided layerOrder');
+ t.equal(group.isIncludedInLegend, false, 'should use provided legend setting');
+ t.end();
+});
+
+// ============================================================================
+// addLayerOrGroupToLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> addLayerOrGroupToLayerOrder -> add layer id', t => {
+ const result = addLayerOrGroupToLayerOrder(['layer_1', 'layer_2'], 'layer_3');
+ t.deepEqual(result, ['layer_3', 'layer_1', 'layer_2'], 'should prepend layer id');
+ t.end();
+});
+
+test('layerGroupUtils -> addLayerOrGroupToLayerOrder -> add group', t => {
+ const newGroup = {id: 'g1', label: 'G1', isVisible: true, isIncludedInLegend: true, layerOrder: []};
+ const result = addLayerOrGroupToLayerOrder(['layer_1'], newGroup);
+ t.equal(result.length, 2, 'should add group');
+ t.deepEqual(result[0], newGroup, 'should prepend group');
+ t.equal(result[1], 'layer_1', 'should keep existing entry');
+ t.end();
+});
+
+// ============================================================================
+// removeElementFromLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> removeElementFromLayerOrder -> remove top-level layer', t => {
+ const result = removeElementFromLayerOrder(MOCK_LAYER_ORDER, 'layer_0');
+ t.equal(result.length, 3, 'should remove one entry');
+ t.deepEqual(result[0], GROUP_1, 'should keep group_1');
+ t.end();
+});
+
+test('layerGroupUtils -> removeElementFromLayerOrder -> remove layer inside group', t => {
+ const result = removeElementFromLayerOrder(MOCK_LAYER_ORDER, 'layer_a');
+ const group1 = result.find(e => typeof e !== 'string' && e.id === 'group_1');
+ t.ok(group1, 'group_1 should still exist');
+ t.deepEqual(group1.layerOrder, ['layer_b'], 'should remove layer_a from group');
+ t.end();
+});
+
+test('layerGroupUtils -> removeElementFromLayerOrder -> remove group by object', t => {
+ const result = removeElementFromLayerOrder(MOCK_LAYER_ORDER, GROUP_1);
+ t.equal(result.length, 3, 'should remove the group');
+ t.equal(result[0], 'layer_0', 'first entry should be layer_0');
+ t.end();
+});
+
+test('layerGroupUtils -> removeElementFromLayerOrder -> remove nested layer', t => {
+ const result = removeElementFromLayerOrder(COMPLEX_LAYER_ORDER, 'layer_d');
+ const parentGroup = result.find(e => typeof e !== 'string' && e.id === 'group_nested');
+ const nestedGroup = parentGroup.layerOrder.find(e => typeof e !== 'string' && e.id === 'nested_group');
+ t.deepEqual(nestedGroup.layerOrder, [], 'should remove layer_d from nested group');
+ t.end();
+});
+
+// ============================================================================
+// getLayerGroupFromLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> getLayerGroupFromLayerOrder -> find top-level group', t => {
+ const group = getLayerGroupFromLayerOrder(MOCK_LAYER_ORDER, 'group_1');
+ t.deepEqual(group, GROUP_1, 'should find group_1');
+ t.end();
+});
+
+test('layerGroupUtils -> getLayerGroupFromLayerOrder -> find nested group', t => {
+ const group = getLayerGroupFromLayerOrder(COMPLEX_LAYER_ORDER, 'nested_group');
+ t.deepEqual(group, NESTED_GROUP, 'should find nested_group');
+ t.end();
+});
+
+test('layerGroupUtils -> getLayerGroupFromLayerOrder -> not found', t => {
+ const group = getLayerGroupFromLayerOrder(MOCK_LAYER_ORDER, 'nonexistent');
+ t.equal(group, undefined, 'should return undefined for missing group');
+ t.end();
+});
+
+// ============================================================================
+// findParentGroupForLayer
+// ============================================================================
+
+test('layerGroupUtils -> findParentGroupForLayer -> layer in top-level group', t => {
+ const parent = findParentGroupForLayer(MOCK_LAYER_ORDER, 'layer_a');
+ t.equal(parent.id, 'group_1', 'should find group_1 as parent');
+ t.end();
+});
+
+test('layerGroupUtils -> findParentGroupForLayer -> layer at root', t => {
+ const parent = findParentGroupForLayer(MOCK_LAYER_ORDER, 'layer_0');
+ t.equal(parent, undefined, 'should return undefined for root-level layer');
+ t.end();
+});
+
+test('layerGroupUtils -> findParentGroupForLayer -> layer in nested group', t => {
+ const parent = findParentGroupForLayer(COMPLEX_LAYER_ORDER, 'layer_d');
+ t.equal(parent.id, 'nested_group', 'should find nested_group as parent');
+ t.end();
+});
+
+// ============================================================================
+// getIndexFromLayerEntryId
+// ============================================================================
+
+test('layerGroupUtils -> getIndexFromLayerEntryId -> find string entry', t => {
+ const idx = getIndexFromLayerEntryId(MOCK_LAYER_ORDER, 'layer_0');
+ t.equal(idx, 0, 'should find layer_0 at index 0');
+ t.end();
+});
+
+test('layerGroupUtils -> getIndexFromLayerEntryId -> find group entry', t => {
+ const idx = getIndexFromLayerEntryId(MOCK_LAYER_ORDER, 'group_1');
+ t.equal(idx, 1, 'should find group_1 at index 1');
+ t.end();
+});
+
+test('layerGroupUtils -> getIndexFromLayerEntryId -> not found', t => {
+ const idx = getIndexFromLayerEntryId(MOCK_LAYER_ORDER, 'nonexistent');
+ t.equal(idx, -1, 'should return -1 for missing entry');
+ t.end();
+});
+
+// ============================================================================
+// isLayerPresentInLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> isLayerPresentInLayerOrder -> root layer', t => {
+ t.ok(isLayerPresentInLayerOrder(MOCK_LAYER_ORDER, 'layer_0'), 'should find root layer');
+ t.end();
+});
+
+test('layerGroupUtils -> isLayerPresentInLayerOrder -> layer in group', t => {
+ t.ok(isLayerPresentInLayerOrder(MOCK_LAYER_ORDER, 'layer_a'), 'should find layer inside group');
+ t.end();
+});
+
+test('layerGroupUtils -> isLayerPresentInLayerOrder -> layer in nested group', t => {
+ t.ok(isLayerPresentInLayerOrder(COMPLEX_LAYER_ORDER, 'layer_d'), 'should find layer in nested group');
+ t.end();
+});
+
+test('layerGroupUtils -> isLayerPresentInLayerOrder -> missing layer', t => {
+ t.notOk(isLayerPresentInLayerOrder(MOCK_LAYER_ORDER, 'nonexistent'), 'should not find missing layer');
+ t.end();
+});
+
+// ============================================================================
+// replaceLayerEntryInLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> replaceLayerEntryInLayerOrder -> replace string entry', t => {
+ const result = replaceLayerEntryInLayerOrder(MOCK_LAYER_ORDER, 'layer_0', 'layer_new');
+ t.equal(result[0], 'layer_new', 'should replace layer_0 with layer_new');
+ t.equal(result.length, MOCK_LAYER_ORDER.length, 'should keep same length');
+ t.end();
+});
+
+test('layerGroupUtils -> replaceLayerEntryInLayerOrder -> replace layer inside group', t => {
+ const result = replaceLayerEntryInLayerOrder(MOCK_LAYER_ORDER, 'layer_a', 'layer_replaced');
+ const group1 = result.find(e => typeof e !== 'string' && e.id === 'group_1');
+ t.deepEqual(group1.layerOrder, ['layer_replaced', 'layer_b'], 'should replace layer inside group');
+ t.end();
+});
+
+// ============================================================================
+// updateLayerGroupInLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> updateLayerGroupInLayerOrder -> update top-level group', t => {
+ const updatedGroup = {...GROUP_1, label: 'Updated Label'};
+ const result = updateLayerGroupInLayerOrder(MOCK_LAYER_ORDER, updatedGroup);
+ const found = result.find(e => typeof e !== 'string' && e.id === 'group_1');
+ t.equal(found.label, 'Updated Label', 'should update group label');
+ t.end();
+});
+
+test('layerGroupUtils -> updateLayerGroupInLayerOrder -> update nested group', t => {
+ const updatedNested = {...NESTED_GROUP, label: 'Updated Nested'};
+ const result = updateLayerGroupInLayerOrder(COMPLEX_LAYER_ORDER, updatedNested);
+ const parentGroup = result.find(e => typeof e !== 'string' && e.id === 'group_nested');
+ const nested = parentGroup.layerOrder.find(e => typeof e !== 'string' && e.id === 'nested_group');
+ t.equal(nested.label, 'Updated Nested', 'should update nested group label');
+ t.end();
+});
+
+// ============================================================================
+// getFlatLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> getFlatLayerOrder -> flat order', t => {
+ const result = getFlatLayerOrder(['layer_1', 'layer_2', 'layer_3']);
+ t.deepEqual(result, ['layer_1', 'layer_2', 'layer_3'], 'should return same array for flat order');
+ t.end();
+});
+
+test('layerGroupUtils -> getFlatLayerOrder -> with groups', t => {
+ const result = getFlatLayerOrder(MOCK_LAYER_ORDER);
+ t.deepEqual(
+ result,
+ ['layer_0', 'layer_a', 'layer_b', 'layer_c', 'layer_f'],
+ 'should flatten groups into layer ids'
+ );
+ t.end();
+});
+
+test('layerGroupUtils -> getFlatLayerOrder -> nested groups', t => {
+ const result = getFlatLayerOrder(COMPLEX_LAYER_ORDER);
+ t.deepEqual(
+ result,
+ ['layer_0', 'layer_d', 'layer_e', 'layer_c', 'layer_f'],
+ 'should flatten nested groups'
+ );
+ t.end();
+});
+
+// ============================================================================
+// buildLayerOrderHierarchy
+// ============================================================================
+
+test('layerGroupUtils -> buildLayerOrderHierarchy -> builds correct structure', t => {
+ const mockLayers = [
+ {id: 'layer_0', config: {hidden: false}},
+ {id: 'layer_a', config: {hidden: false}},
+ {id: 'layer_b', config: {hidden: false}},
+ {id: 'layer_c', config: {hidden: false}},
+ {id: 'layer_f', config: {hidden: false}}
+ ];
+ const result = buildLayerOrderHierarchy(MOCK_LAYER_ORDER, mockLayers);
+
+ t.equal(result.length, 4, 'should have 4 top-level entries');
+ t.deepEqual(result[0], ['layer', mockLayers[0]], 'first entry should be layer_0');
+ t.equal(result[1][0], 'layerGroup', 'second entry should be a layerGroup');
+ t.equal(result[1][1].id, 'group_1', 'second entry should be group_1');
+ t.equal(result[2][0], 'layerGroup', 'third entry should be a layerGroup');
+ t.equal(result[2][1].id, 'group_2', 'third entry should be group_2');
+ t.deepEqual(result[3], ['layer', mockLayers[4]], 'fourth entry should be layer_f');
+ t.end();
+});
+
+// ============================================================================
+// removeGhostLayerFromLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> removeGhostLayerFromLayerOrder -> removes missing layers', t => {
+ const validLayers = [{id: 'layer_0'}, {id: 'layer_a'}, {id: 'layer_f'}];
+ const result = removeGhostLayerFromLayerOrder(MOCK_LAYER_ORDER, validLayers);
+ const flatResult = getFlatLayerOrder(result);
+ const validIds = validLayers.map(l => l.id);
+ t.ok(flatResult.every(id => validIds.includes(id)), 'should only contain valid layer ids');
+ t.notOk(flatResult.includes('layer_b'), 'should not contain layer_b');
+ t.notOk(flatResult.includes('layer_c'), 'should not contain layer_c');
+ t.end();
+});
+
+test('layerGroupUtils -> removeGhostLayerFromLayerOrder -> preserves groups', t => {
+ const validLayers = [{id: 'layer_0'}, {id: 'layer_a'}, {id: 'layer_b'}, {id: 'layer_c'}, {id: 'layer_f'}];
+ const result = removeGhostLayerFromLayerOrder(MOCK_LAYER_ORDER, validLayers);
+ t.equal(result.length, MOCK_LAYER_ORDER.length, 'should keep all entries when all layers valid');
+ t.end();
+});
+
+// ============================================================================
+// reorderLayerOrder
+// ============================================================================
+
+test('layerGroupUtils -> reorderLayerOrder -> simple flat reorder', t => {
+ const order = ['a', 'b', 'c'];
+ const result = reorderLayerOrder(order, 'a', 'c');
+ t.deepEqual(result, ['b', 'c', 'a'], 'should move a to position of c');
+ t.end();
+});
+
+test('layerGroupUtils -> reorderLayerOrder -> reorder groups', t => {
+ const group = {
+ id: 'g1', label: 'G', isVisible: true, isIncludedInLegend: true,
+ layerOrder: ['x', 'y', 'z']
+ };
+ const order = ['a', group, 'b'];
+ const result = reorderLayerOrder(order, 'g1', 'b');
+ t.equal(result[0], 'a', 'a should stay at index 0');
+ t.equal(result[1], 'b', 'b should move to index 1');
+ t.deepEqual(result[2], group, 'group should move to index 2');
+ t.end();
+});
+
+test('layerGroupUtils -> reorderLayerOrder -> no-op for missing entry', t => {
+ const order = ['a', 'b', 'c'];
+ const result = reorderLayerOrder(order, 'nonexistent', 'a');
+ t.deepEqual(result, order, 'should return same order for missing entry');
+ t.end();
+});
+
+// ============================================================================
+// insertLayerAtRightOrder (with groups)
+// ============================================================================
+
+test('layerGroupUtils -> insertLayerAtRightOrder -> preserves groups', t => {
+ const currentLayers = [{id: 'layer_1'}, {id: 'layer_2'}];
+ const group = {
+ id: 'g1', label: 'G', isVisible: true, isIncludedInLegend: true,
+ layerOrder: ['layer_1']
+ };
+ const currentOrder = [group, 'layer_2'];
+
+ const {newLayerOrder, newLayers} = insertLayerAtRightOrder(
+ currentLayers,
+ [{id: 'layer_3'}],
+ currentOrder,
+ ['layer_3', 'layer_2']
+ );
+
+ t.equal(newLayers.length, 3, 'should have 3 layers total');
+ const hasGroup = newLayerOrder.some(e => typeof e !== 'string' && e.id === 'g1');
+ t.ok(hasGroup, 'should preserve the group in layerOrder');
+ t.end();
+});
+
+test('layerGroupUtils -> insertLayerAtRightOrder -> no groups flat behavior', t => {
+ const currentLayers = [{id: 'a'}];
+ const currentOrder = ['a'];
+
+ const {newLayerOrder, newLayers} = insertLayerAtRightOrder(
+ currentLayers,
+ [{id: 'b'}],
+ currentOrder,
+ ['b', 'a']
+ );
+
+ t.equal(newLayers.length, 2, 'should have 2 layers');
+ t.deepEqual(newLayerOrder, ['b', 'a'], 'should insert b before a per preservedOrder');
+ t.end();
+});
+
+// ============================================================================
+// mergeLayerOrder (restore groups from saved config)
+// ============================================================================
+
+test('layerGroupUtils -> mergeLayerOrder -> no saved layerOrder', t => {
+ const state = {layers: [{id: 'a'}, {id: 'b'}], layerOrder: ['a', 'b']};
+ const result = mergeLayerOrder(state, undefined);
+ t.equal(result, state, 'should return state unchanged');
+ t.end();
+});
+
+test('layerGroupUtils -> mergeLayerOrder -> flat saved layerOrder (no groups)', t => {
+ const state = {layers: [{id: 'a'}, {id: 'b'}], layerOrder: ['a', 'b']};
+ const result = mergeLayerOrder(state, ['b', 'a']);
+ t.equal(result, state, 'should return state unchanged when no groups in saved order');
+ t.end();
+});
+
+test('layerGroupUtils -> mergeLayerOrder -> restores groups from saved config', t => {
+ const savedLayerOrder = [
+ {
+ id: 'g1', label: 'My Group', isVisible: true, isIncludedInLegend: true,
+ layerOrder: ['a', 'b']
+ },
+ 'c'
+ ];
+ const state = {layers: [{id: 'a'}, {id: 'b'}, {id: 'c'}], layerOrder: ['a', 'b', 'c']};
+ const result = mergeLayerOrder(state, savedLayerOrder);
+
+ t.equal(result.layerOrder.length, 2, 'should have 2 top-level entries (group + layer)');
+ const group = result.layerOrder.find(e => typeof e !== 'string' && e.id === 'g1');
+ t.ok(group, 'should restore the group');
+ t.deepEqual(group.layerOrder, ['a', 'b'], 'should restore layer membership');
+ t.equal(result.layerOrder[1], 'c', 'should keep ungrouped layer');
+ t.end();
+});
+
+test('layerGroupUtils -> mergeLayerOrder -> filters out deleted layers', t => {
+ const savedLayerOrder = [
+ {
+ id: 'g1', label: 'Group', isVisible: true, isIncludedInLegend: true,
+ layerOrder: ['a', 'deleted_layer']
+ },
+ 'b'
+ ];
+ const state = {layers: [{id: 'a'}, {id: 'b'}], layerOrder: ['a', 'b']};
+ const result = mergeLayerOrder(state, savedLayerOrder);
+
+ const group = result.layerOrder.find(e => typeof e !== 'string' && e.id === 'g1');
+ t.deepEqual(group.layerOrder, ['a'], 'should filter out deleted_layer from group');
+ t.end();
+});
+
+test('layerGroupUtils -> mergeLayerOrder -> adds missing layers at top', t => {
+ const savedLayerOrder = [
+ {
+ id: 'g1', label: 'Group', isVisible: true, isIncludedInLegend: true,
+ layerOrder: ['a']
+ }
+ ];
+ const state = {layers: [{id: 'a'}, {id: 'new_layer'}], layerOrder: ['a', 'new_layer']};
+ const result = mergeLayerOrder(state, savedLayerOrder);
+
+ t.ok(
+ result.layerOrder.includes('new_layer'),
+ 'should include new_layer that was not in saved config'
+ );
+ t.end();
+});
diff --git a/test/node/reducers/layer-group-updaters-test.js b/test/node/reducers/layer-group-updaters-test.js
new file mode 100644
index 000000000..bf0a4de2a
--- /dev/null
+++ b/test/node/reducers/layer-group-updaters-test.js
@@ -0,0 +1,383 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape-catch';
+import CloneDeep from 'lodash/cloneDeep';
+
+import {VisStateActions} from '@kepler.gl/actions';
+import {
+ visStateReducer as reducer,
+ INITIAL_VIS_STATE,
+ getFlatLayerOrder,
+ getLayerGroupFromLayerOrder,
+ findParentGroupForLayer
+} from '@kepler.gl/reducers';
+
+import {StateWFilesFiltersLayerColor} from 'test/helpers/mock-state';
+
+// ============================================================================
+// Helpers
+// ============================================================================
+
+function createStateWithLayers() {
+ // Use real state from mock with 3 layers
+ const state = CloneDeep(StateWFilesFiltersLayerColor.visState);
+ return state;
+}
+
+function createStateWithGroup() {
+ const state = createStateWithLayers();
+ const layer0Id = state.layers[0].id;
+ const layer1Id = state.layers[1].id;
+ const layer2Id = state.layers[2].id;
+
+ // Manually set up a group structure:
+ // layerOrder: [group_1(layer0, layer1), layer2]
+ const group = {
+ id: 'test_group_1',
+ label: 'Test Group',
+ isVisible: true,
+ isIncludedInLegend: true,
+ layerOrder: [layer0Id, layer1Id]
+ };
+ state.layerOrder = [group, layer2Id];
+ return state;
+}
+
+// ============================================================================
+// ADD_LAYER_GROUP
+// ============================================================================
+
+test('#visStateReducer -> ADD_LAYER_GROUP -> empty group', t => {
+ const state = createStateWithLayers();
+ const initialOrderLength = state.layerOrder.length;
+
+ const nextState = reducer(state, VisStateActions.addLayerGroup({}));
+
+ t.equal(
+ nextState.layerOrder.length,
+ initialOrderLength + 1,
+ 'should add one entry to layerOrder'
+ );
+
+ const addedEntry = nextState.layerOrder[0];
+ t.equal(typeof addedEntry, 'object', 'first entry should be a group object');
+ t.equal(addedEntry.label, 'New group', 'should have default label');
+ t.equal(addedEntry.isVisible, true, 'should be visible');
+ t.deepEqual(addedEntry.layerOrder, [], 'should have empty layerOrder');
+ t.end();
+});
+
+test('#visStateReducer -> ADD_LAYER_GROUP -> with custom properties', t => {
+ const state = createStateWithLayers();
+
+ const nextState = reducer(
+ state,
+ VisStateActions.addLayerGroup({
+ id: 'custom_group',
+ label: 'Custom Group',
+ isVisible: false
+ })
+ );
+
+ const addedEntry = nextState.layerOrder[0];
+ t.equal(addedEntry.id, 'custom_group', 'should use custom id');
+ t.equal(addedEntry.label, 'Custom Group', 'should use custom label');
+ t.equal(addedEntry.isVisible, false, 'should use custom visibility');
+ t.end();
+});
+
+test('#visStateReducer -> ADD_LAYER_GROUP -> with existing layers', t => {
+ const state = createStateWithLayers();
+ const layer0Id = state.layers[0].id;
+ const layer1Id = state.layers[1].id;
+
+ const nextState = reducer(
+ state,
+ VisStateActions.addLayerGroup({
+ id: 'new_group',
+ layerOrder: [layer0Id, layer1Id]
+ })
+ );
+
+ // The layers should be removed from root and placed inside the group
+ const group = nextState.layerOrder.find(e => typeof e !== 'string' && e.id === 'new_group');
+ t.ok(group, 'should have the new group');
+ t.deepEqual(group.layerOrder, [layer0Id, layer1Id], 'group should contain the layers');
+
+ // The layers should not exist at root level
+ const rootStrings = nextState.layerOrder.filter(e => typeof e === 'string');
+ t.notOk(rootStrings.includes(layer0Id), 'layer0 should not be at root');
+ t.notOk(rootStrings.includes(layer1Id), 'layer1 should not be at root');
+ t.end();
+});
+
+// ============================================================================
+// REMOVE_LAYER_GROUP
+// ============================================================================
+
+test('#visStateReducer -> REMOVE_LAYER_GROUP -> removes group and its layers', t => {
+ const state = createStateWithGroup();
+ const initialLayerCount = state.layers.length;
+ const layer0Id = state.layers[0].id;
+ const layer1Id = state.layers[1].id;
+
+ const nextState = reducer(state, VisStateActions.removeLayerGroup({id: 'test_group_1'}));
+
+ // Group should be gone
+ const group = nextState.layerOrder.find(e => typeof e !== 'string' && e.id === 'test_group_1');
+ t.notOk(group, 'group should be removed');
+
+ // Layers inside group should be removed
+ t.notOk(nextState.layers.find(l => l.id === layer0Id), 'layer0 should be removed');
+ t.notOk(nextState.layers.find(l => l.id === layer1Id), 'layer1 should be removed');
+
+ // Layer count should decrease
+ t.equal(nextState.layers.length, initialLayerCount - 2, 'should have 2 fewer layers');
+ t.end();
+});
+
+test('#visStateReducer -> REMOVE_LAYER_GROUP -> nonexistent group returns same state', t => {
+ const state = createStateWithGroup();
+ const nextState = reducer(state, VisStateActions.removeLayerGroup({id: 'nonexistent'}));
+ t.equal(nextState, state, 'should return same state for missing group');
+ t.end();
+});
+
+// ============================================================================
+// UPDATE_LAYER_GROUP
+// ============================================================================
+
+test('#visStateReducer -> UPDATE_LAYER_GROUP -> update label', t => {
+ const state = createStateWithGroup();
+
+ const nextState = reducer(
+ state,
+ VisStateActions.updateLayerGroup({id: 'test_group_1', options: {label: 'Renamed Group'}})
+ );
+
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.equal(group.label, 'Renamed Group', 'should update label');
+ t.end();
+});
+
+test('#visStateReducer -> UPDATE_LAYER_GROUP -> toggle visibility cascades to layers', t => {
+ const state = createStateWithGroup();
+ const layer0Id = state.layers[0].id;
+ const layer1Id = state.layers[1].id;
+
+ // Make sure layers start visible
+ state.layers[0].config.isVisible = true;
+ state.layers[1].config.isVisible = true;
+
+ const nextState = reducer(
+ state,
+ VisStateActions.updateLayerGroup({id: 'test_group_1', options: {isVisible: false}})
+ );
+
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.equal(group.isVisible, false, 'group should be hidden');
+
+ const l0 = nextState.layers.find(l => l.id === layer0Id);
+ const l1 = nextState.layers.find(l => l.id === layer1Id);
+ t.equal(l0.config.isVisible, false, 'layer0 should be hidden');
+ t.equal(l1.config.isVisible, false, 'layer1 should be hidden');
+ t.end();
+});
+
+test('#visStateReducer -> UPDATE_LAYER_GROUP -> nonexistent group returns same state', t => {
+ const state = createStateWithGroup();
+ const nextState = reducer(
+ state,
+ VisStateActions.updateLayerGroup({id: 'nonexistent', options: {label: 'X'}})
+ );
+ t.equal(nextState, state, 'should return same state');
+ t.end();
+});
+
+// ============================================================================
+// ADD_LAYER_TO_LAYER_GROUP
+// ============================================================================
+
+test('#visStateReducer -> ADD_LAYER_TO_LAYER_GROUP -> adds layer to group', t => {
+ const state = createStateWithGroup();
+ const layer2Id = state.layers[2].id;
+
+ const nextState = reducer(
+ state,
+ VisStateActions.addLayerToLayerGroup({layerGroupId: 'test_group_1', layerId: layer2Id})
+ );
+
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.ok(group.layerOrder.includes(layer2Id), 'layer2 should be in the group');
+
+ // layer2 should be removed from root
+ const rootStrings = nextState.layerOrder.filter(e => typeof e === 'string');
+ t.notOk(rootStrings.includes(layer2Id), 'layer2 should not be at root');
+ t.end();
+});
+
+test('#visStateReducer -> ADD_LAYER_TO_LAYER_GROUP -> already in group is no-op', t => {
+ const state = createStateWithGroup();
+ const layer0Id = state.layers[0].id;
+
+ const nextState = reducer(
+ state,
+ VisStateActions.addLayerToLayerGroup({layerGroupId: 'test_group_1', layerId: layer0Id})
+ );
+
+ // Should be unchanged since layer0 is already in the group
+ t.equal(nextState, state, 'should return same state when layer already in group');
+ t.end();
+});
+
+test('#visStateReducer -> ADD_LAYER_TO_LAYER_GROUP -> invalid group returns same state', t => {
+ const state = createStateWithGroup();
+ const layer2Id = state.layers[2].id;
+
+ const nextState = reducer(
+ state,
+ VisStateActions.addLayerToLayerGroup({layerGroupId: 'nonexistent', layerId: layer2Id})
+ );
+
+ t.equal(nextState, state, 'should return same state for invalid group');
+ t.end();
+});
+
+// ============================================================================
+// REMOVE_LAYER_FROM_LAYER_GROUP
+// ============================================================================
+
+test('#visStateReducer -> REMOVE_LAYER_FROM_LAYER_GROUP -> removes layer from group', t => {
+ const state = createStateWithGroup();
+ const layer0Id = state.layers[0].id;
+
+ const nextState = reducer(
+ state,
+ VisStateActions.removeLayerFromLayerGroup({layerGroupId: 'test_group_1', layerId: layer0Id})
+ );
+
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.notOk(group.layerOrder.includes(layer0Id), 'layer0 should be removed from group');
+
+ // Layer should still exist in state.layers (not deleted)
+ t.ok(nextState.layers.find(l => l.id === layer0Id), 'layer should still exist');
+ t.end();
+});
+
+// ============================================================================
+// SWAP_LAYER_ORDER_ENTRIES
+// ============================================================================
+
+test('#visStateReducer -> SWAP_LAYER_ORDER_ENTRIES -> root to root', t => {
+ const state = createStateWithLayers();
+ const layer0Id = state.layers[0].id;
+ const layer2Id = state.layers[2].id;
+
+ // Assume layerOrder is [layer2, layer0, layer1] (default from mock)
+ const firstEntry = state.layerOrder[0];
+ const lastEntry = state.layerOrder[state.layerOrder.length - 1];
+
+ const nextState = reducer(
+ state,
+ VisStateActions.swapLayerOrderEntries({
+ originLayerId: typeof firstEntry === 'string' ? firstEntry : firstEntry.id,
+ destinationLayerId: typeof lastEntry === 'string' ? lastEntry : lastEntry.id
+ })
+ );
+
+ // First and last should be swapped
+ t.equal(nextState.layerOrder[nextState.layerOrder.length - 1], firstEntry, 'origin moved to destination');
+ t.end();
+});
+
+test('#visStateReducer -> SWAP_LAYER_ORDER_ENTRIES -> group to root', t => {
+ const state = createStateWithGroup();
+ const layer0Id = state.layers[0].id;
+ const layer2Id = state.layers[2].id;
+
+ // layerOrder: [group(layer0, layer1), layer2]
+ const nextState = reducer(
+ state,
+ VisStateActions.swapLayerOrderEntries({
+ originLayerId: layer0Id,
+ destinationLayerId: layer2Id,
+ originLayerGroupId: 'test_group_1'
+ })
+ );
+
+ // layer0 should now be at root level
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.notOk(
+ group.layerOrder.includes(layer0Id),
+ 'layer0 should be removed from group'
+ );
+ t.ok(
+ nextState.layerOrder.some(e => e === layer0Id),
+ 'layer0 should be at root level'
+ );
+ t.end();
+});
+
+test('#visStateReducer -> SWAP_LAYER_ORDER_ENTRIES -> root to group', t => {
+ const state = createStateWithGroup();
+ const layer2Id = state.layers[2].id;
+
+ // layerOrder: [group(layer0, layer1), layer2]
+ const nextState = reducer(
+ state,
+ VisStateActions.swapLayerOrderEntries({
+ originLayerId: layer2Id,
+ destinationLayerGroupId: 'test_group_1'
+ })
+ );
+
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.ok(
+ group.layerOrder.includes(layer2Id),
+ 'layer2 should be moved into the group'
+ );
+ t.end();
+});
+
+// ============================================================================
+// DUPLICATE_LAYER (with groups)
+// ============================================================================
+
+test('#visStateReducer -> DUPLICATE_LAYER -> layer inside group', t => {
+ const state = createStateWithGroup();
+ const layer0Id = state.layers[0].id;
+
+ const nextState = reducer(state, VisStateActions.duplicateLayer(0));
+
+ // New layer should be in the same group
+ const newLayer = nextState.layers[nextState.layers.length - 1];
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+
+ t.ok(group, 'group should still exist');
+ t.ok(
+ group.layerOrder.includes(newLayer.id),
+ 'duplicated layer should be inside the same group'
+ );
+ t.end();
+});
+
+// ============================================================================
+// REMOVE_LAYER (with groups)
+// ============================================================================
+
+test('#visStateReducer -> REMOVE_LAYER -> layer inside group', t => {
+ const state = createStateWithGroup();
+ const layer0Id = state.layers[0].id;
+
+ const nextState = reducer(state, VisStateActions.removeLayer(layer0Id));
+
+ // Layer should be removed from state
+ t.notOk(nextState.layers.find(l => l.id === layer0Id), 'layer should be removed');
+
+ // Layer should be removed from group
+ const group = getLayerGroupFromLayerOrder(nextState.layerOrder, 'test_group_1');
+ t.ok(group, 'group should still exist');
+ t.notOk(group.layerOrder.includes(layer0Id), 'layer should be removed from group');
+ t.end();
+});
diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.js
index 6ec67fdb1..3141acb61 100644
--- a/test/node/schemas/vis-state-schema-test.js
+++ b/test/node/schemas/vis-state-schema-test.js
@@ -39,7 +39,8 @@ const expectedVisStateEntries = [
'overlayBlending',
'splitMaps',
'animationConfig',
- 'editor'
+ 'editor',
+ 'layerOrder'
];
test('#visStateSchema -> v1 -> save layers', t => {