Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(camera): add saved view bookmarks (#3859)
Igor Dykhta07e5a8d892c4
diff --git a/AGENTS.md b/AGENTS.mdindex dac4d9bf7..a30926181 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -34,6 +34,8 @@ Read the implementation you will edit and its nearest test first. Look for a patAfter the behavior is implemented, add or update a test when that behavior can be observed. Test the behavior the task describes, including the empty, missing, or invalid input that motivated the change. Assert on behavior, not implementation details. Do not weaken an assertion to make a test pass.+Do not add tests that merely freeze incidental UI copy, typography, dimensions, or styling. Tests should protect meaningful behavior, accessibility contracts, state transitions, or actual regressions; meaningful UI and accessibility tests remain appropriate.+Skip the test when nothing observable changed (types, comments, copy, build config) or the change cannot be tested. Say which one in the PR.- Extend the nearest existing test file before adding a new one.diff --git a/docs/user-guides/README.md b/docs/user-guides/README.mdindex 793bcdffe..4246d36f1 100644--- a/docs/user-guides/README.md+++ b/docs/user-guides/README.md@@ -65,6 +65,8 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da* [Tooltips](./g-interactions.md#tooltips)* [Brushing](./g-interactions.md#brushing)* [Display Coordinates](./g-interactions.md#display-coordinates)+* [Bookmarks](./g-interactions.md#bookmarks)+* [Fade on Zoom](./g-interactions.md#fade-on-zoom)#### [Map Settings](./m-map-settings.md)* [View maps in 3d](./m-map-settings.md#view-maps-in-3d)diff --git a/docs/user-guides/g-interactions.md b/docs/user-guides/g-interactions.mdindex c4a9ff442..f29b0fd1a 100644--- a/docs/user-guides/g-interactions.md+++ b/docs/user-guides/g-interactions.md@@ -4,6 +4,8 @@- [Tooltips](#tooltips)- [Brushing](#brushing)- [Display Coordinates](#display-coordinates)+ - [Bookmarks](#bookmarks)+ - [Fade on Zoom](#fade-on-zoom)<!-- /TOC -->You can toggle customization options on your map, including tooltips, brush highlighting, map imagery (water, parks, etc.), and more.@@ -17,7 +19,7 @@ To toggle customization options on your map:2. Click the switch next to the options you wish to activate/deactivate.-There are three types of interactions to choose from: __Tooltip__, __Brushing__ and __Coordinate__. Note that only one of tooltip and brushing can be on at a time.+Alongside **Tooltip**, **Brushing**, and **Coordinate**, use **Bookmarks** to return to saved map views and **Fade on Zoom** to control visibility by zoom level. Only one of tooltip and brushing can be on at a time.## Tooltipstooltip displays metrics when hovering over a data point. You can choose which fields are displayed from the tooltip config menu.@@ -58,3 +60,75 @@ Tip: click a point to pin the tooltip info to the map. To unpin the tooltip, preWhen then on coordinate, a panel contains latitude and longitude will follow your mouse[Back to table of contents](README.md)+++## Bookmarks++Bookmarks save the map center, zoom, bearing (rotation), and pitch (tilt). They change the camera view without restoring a separate set of layers, filters, or data. You can create bookmarks even before adding a dataset.++### Capture and manage views++1. Open **Interactions → Bookmarks** by clicking its header.+2. Pan, zoom, rotate, and tilt the map to compose a view, then click **+ Add Bookmark**.+3. Edit the name directly in the bookmark's header.++Hover over a bookmark header to reveal its controls, or use **Tab** to reach them with the keyboard:++| Control | Action |+| --- | --- |+| **Go to** | Smoothly move the map to the saved view. Bookmarks must be enabled. |+| **Copy coordinates** | Copy the saved center as `latitude, longitude` in decimal degrees, rounded to six decimal places. Copying does not move the map. Successful copying is silent; a failure displays a message. |+| **Update view** | Replace this bookmark's camera with the current map view, keeping its name and position in the list. |+| **Delete** | Remove this bookmark. |++Drag the handle at the left of a bookmark header to reorder it. The handle appears on header hover or keyboard focus. To reorder with the keyboard, focus the handle, press **Space**, use **Up/Down**, then press **Space** again to drop it. **Escape** cancels the reorder.++### Use the floating panel++Bookmarks are off by default, including when opening older configurations. Enable the **Bookmarks** switch to show saved bookmarks on the map. The panel appears once there is at least one bookmark and stays usable when the sidebar is closed. Click a bookmark row to visit its view. Its overlaid **Copy coordinates** button appears when that row is hovered or a control in the row has keyboard focus.++Click the floating panel's **×** to hide it and turn off the **Bookmarks** switch. Turn the switch on again to reopen it. Closing or disabling the panel does not delete bookmarks; you can still edit them in the sidebar. Collapsing the sidebar section is independent of this switch.++On desktop, drag the title bar labeled **Bookmarks** to move the panel. Drag either the top or bottom edge handle to resize its height. The minimum height fits the title and one bookmark; additional bookmarks remain available by scrolling. With the keyboard, focus the title bar or a resize handle, press **Space**, use the arrow keys, and press **Space** again to finish. The copy and close controls work independently of dragging.++### Saved views and supported modes++Saved map configurations retain bookmark names, order, and camera views when loaded in a version that supports Bookmarks. Configurations without bookmarks still load normally. The Bookmarks switch is a UI preference, separate from these saved views; loading views does not turn it on automatically or reset an explicitly enabled UI preference.++Bookmark editing and navigation support a single 2D or 3D Mercator map. In globe or split-map mode, the floating panel is hidden and bookmark editing is unavailable. Return to a single Mercator map to use the saved views again.++[Back to table of contents](README.md)++## Fade on Zoom++Fade on Zoom changes the opacity of selected layers and annotations as you zoom. Each controller applies one fade range to its selected targets.++1. Open **Interactions → Fade on zoom** by clicking its header or settings icon.+2. Click **+ Add controller**.+3. In **Layers and annotations**, select one or more targets. A target can belong to only one controller; remove it from its current controller before assigning it to another.+4. Adjust the four handles on the controller's graph, then turn on the **Fade on zoom** switch to apply the effect. Adding or editing a controller does not turn the switch on automatically.++### Set the zoom range++The graph runs from zoom **0** to **24**. Drag a handle horizontally to change its zoom level. The four handles stay in order; moving one past a neighbor moves that neighbor too.++| Handle | Meaning as you zoom in | Initial value |+| --- | --- | --- |+| **Appear** | The target is invisible at and below this zoom, then starts fading in. | 1 |+| **Full start** | The fade-in ends and the target reaches its normal opacity. | 3 |+| **Full end** | The target starts fading out from its normal opacity. | 8 |+| **Disappear** | The target is invisible at and above this zoom. | 12 |++Opacity changes linearly between **Appear** and **Full start**, stays at the normal value through **Full end**, then falls to zero at **Disappear**. For example, with values **2, 4, 8, 10**, zoom 3 applies half the normal opacity, zooms 4–8 use the normal opacity, and zoom 9 applies half again. Zooming out follows the same range in reverse.++When the two fade-in handles coincide, the target switches on immediately above **Appear**, provided **Disappear** is higher. When the two fade-out handles coincide, it switches off at **Disappear**. The target remains invisible at the outer boundaries. If **Appear** and **Disappear** coincide, all four handles coincide and the target stays invisible at every zoom.++Focus a handle and use the arrow keys to adjust it by **0.1** zoom levels, or hold **Shift** for steps of **1**. The vertical marker shows the current map zoom.++### Manage controllers++Use multiple controllers for groups that need different zoom ranges. Remove a target from the selector to stop applying that controller to it, or use the controller's trash icon to delete the controller. Deleting a controller leaves its layers and annotations on the map.++Turning off **Fade on zoom** keeps the controllers but stops applying their fades. Unassigned targets retain their normal appearance. For layers, the fade multiplies the existing opacity setting; it does not replace it or turn a hidden layer on. Controller targets, ranges, and the enabled state are retained in saved map configurations.++[Back to table of contents](README.md)diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex 8f2ccef12..016213c0f 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -155,6 +155,9 @@ export const ActionTypes = {UPDATE_CHART: `${ACTION_PREFIX}UPDATE_CHART`,REMOVE_CHART: `${ACTION_PREFIX}REMOVE_CHART`,+ // camera bookmarks+ SET_CAMERA_BOOKMARKS: `${ACTION_PREFIX}SET_CAMERA_BOOKMARKS`,+// annotationsADD_ANNOTATION: `${ACTION_PREFIX}ADD_ANNOTATION`,REMOVE_ANNOTATION: `${ACTION_PREFIX}REMOVE_ANNOTATION`,diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.tsindex 2c54d29ff..935160dd0 100644--- a/src/actions/src/vis-state-actions.ts+++ b/src/actions/src/vis-state-actions.ts@@ -31,7 +31,8 @@ import {LayerOrder,LayerOrderGroup,ProtoDataset,- ChartConfig+ ChartConfig,+ CameraBookmark} from '@kepler.gl/types';import {createAction} from '@reduxjs/toolkit';@@ -851,6 +852,9 @@ export function removeChart(};}+/** Replace the ordered collection of saved camera bookmarks. */+export const setCameraBookmarks = createAction<CameraBookmark[]>(ActionTypes.SET_CAMERA_BOOKMARKS);+// Annotation Actionsexport type AddAnnotationUpdaterAction = {diff --git a/src/components/src/camera-navigation.ts b/src/components/src/camera-navigation.tsnew file mode 100644index 000000000..fcab02fa2--- /dev/null+++ b/src/components/src/camera-navigation.ts@@ -0,0 +1,9 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {FlyToInterpolator} from '@deck.gl/core';+import {CameraSnapshot} from '@kepler.gl/types';++export function cameraTransition(camera: CameraSnapshot) {+ return {...camera, transitionDuration: 1000, transitionInterpolator: new FlyToInterpolator()};+}diff --git a/src/components/src/hooks/use-legend-position.ts b/src/components/src/hooks/use-legend-position.tsindex 5deb5dff5..96eb3af35 100644--- a/src/components/src/hooks/use-legend-position.ts+++ b/src/components/src/hooks/use-legend-position.ts@@ -100,6 +100,7 @@ export default function useLegendPosition({const contentHeight = settings?.contentHeight ?? -1;const positionStyles = useMemo(() => ({[pos.anchorX]: pos.x, [pos.anchorY]: pos.y}), [pos]);const startHeightRef = useRef(0);+ const minHeightRef = useRef(MIN_CONTENT_HEIGHT);const sidePanelWidth = theme.sidePanel?.width || 0;// Calculate dynamic max content height based on map root dimensions@@ -123,6 +124,10 @@ export default function useLegendPosition({const content = legendContentRef.current?.querySelector('.map-control__panel-content');if (content instanceof HTMLElement) {startHeightRef.current = content.offsetHeight;+ // Keep resizing in sync with each panel's rendered minimum.+ const minHeight = parseFloat(window.getComputedStyle(content).minHeight);+ minHeightRef.current =+ Number.isFinite(minHeight) && minHeight > 0 ? minHeight : MIN_CONTENT_HEIGHT;}// eslint-disable-next-line react-hooks/exhaustive-deps}, []);@@ -150,7 +155,7 @@ export default function useLegendPosition({const signedDelta = edge === 'top' ? -deltaY : deltaY;const nextHeight = Math.min(maxHeight,- Math.max(MIN_CONTENT_HEIGHT, startHeightRef.current + signedDelta)+ Math.max(minHeightRef.current, startHeightRef.current + signedDelta));const nextSettings: Partial<MapLegendControlSettings> = {contentHeight: nextHeight};// Keep the opposite edge fixed when CSS anchoring would otherwise move it.diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsxindex b23ae923a..e3dc7cbd3 100644--- a/src/components/src/kepler-gl.tsx+++ b/src/components/src/kepler-gl.tsx@@ -53,6 +53,7 @@ import {import SidePanelFactory from './side-panel';import MapContainerFactory from './map-container';import MapsLayoutFactory from './maps-layout';+import {MapViewStateContextProvider} from './map-view-state-context';import BottomWidgetFactory from './bottom-widget';import ModalContainerFactory from './modal-container';import PlotContainerFactory from './plot-container';@@ -234,6 +235,7 @@ export const sidePanelSelector = (props: KeplerGLProps, availableProviders, filtfilters: props.visState.filters,layers: props.visState.layers,annotations: props.visState.annotations,+ cameraBookmarks: props.visState.cameraBookmarks,layerOrder: props.visState.layerOrder,layerClasses: props.visState.layerClasses,interactionConfig: props.visState.interactionConfig,@@ -728,18 +730,21 @@ function KeplerGlFactory(datasets={visState.datasets}refreshDataset={this.props.visStateActions.refreshDataset}/>- <DndContext visState={visState}>- {!uiState.readOnly && !readOnly && <SidePanel {...sideFields} />}- <MapsLayout- className="maps"- mapState={this.props.mapState}- onSetSwipeComparePercentage={- this.props.mapStateActions.setSwipeComparePercentage- }- >- {mapContainers}- </MapsLayout>- </DndContext>+ <MapViewStateContextProvider mapState={this.props.mapState}>+ <DndContext visState={visState}>+ {!uiState.readOnly && !readOnly && <SidePanel {...sideFields} />}+ <MapsLayout+ provideViewState={false}+ className="maps"+ mapState={this.props.mapState}+ onSetSwipeComparePercentage={+ this.props.mapStateActions.setSwipeComparePercentage+ }+ >+ {mapContainers}+ </MapsLayout>+ </DndContext>+ </MapViewStateContextProvider>{isExportingImage && <PlotContainer {...plotContainerFields} />}{/* 1 geocoder: single mode OR split mode and synced viewports */}{!isViewportDisjointed(this.props) && interactionConfig.geocoder.enabled && (diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 9f5afa25b..551a62d90 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -1668,6 +1668,7 @@ export default function MapContainerFactory({showMapControl && (<MapControlmapState={mapState}+ cameraBookmarks={visState.cameraBookmarks}mapStateActions={mapStateActions}datasets={datasets}availableLocales={LOCALE_CODES_ARRAY}@@ -1708,6 +1709,7 @@ export default function MapContainerFactory(hideInvisibleLayers={Boolean(interactionConfig.legend?.config?.hideInvisibleLayers)}mapHeight={mapState.height}setMapControlSettings={uiStateActions.setMapControlSettings}+ setMapControlVisibility={uiStateActions.setMapControlVisibility}activeSidePanel={activeSidePanel}splitMaps={this.props.visState.splitMaps}onToggleLayerForMap={visStateActions.toggleLayerForMap}diff --git a/src/components/src/map-view-state-context.spec.tsx b/src/components/src/map-view-state-context.spec.tsxnew file mode 100644index 000000000..6da4b0b0b--- /dev/null+++ b/src/components/src/map-view-state-context.spec.tsx@@ -0,0 +1,66 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useContext} from 'react';+import {fireEvent, render, screen} from '@testing-library/react';+import {updateMap} from '@kepler.gl/actions';+import {INITIAL_MAP_STATE, mapStateUpdaters} from '@kepler.gl/reducers';+import {MapState} from '@kepler.gl/types';+import {cameraTransition} from './camera-navigation';+import {MapViewStateContext, MapViewStateContextProvider} from './map-view-state-context';++const camera = {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45};++function setup() {+ const read = jest.fn();+ function Consumer() {+ const {getInternalViewState, setInternalViewState} = useContext(MapViewStateContext);+ read(getInternalViewState());+ return (+ <button type="button" onClick={() => setInternalViewState(camera)}>+ Move map+ </button>+ );+ }+ const tree = (mapState: MapState) => (+ <MapViewStateContextProvider mapState={mapState}>+ <Consumer />+ </MapViewStateContextProvider>+ );+ const {rerender} = render(tree(INITIAL_MAP_STATE));+ return {read, sync: (mapState: MapState) => rerender(tree(mapState))};+}++test('passes bookmark transition settings through the provider to the map consumer', () => {+ const {read, sync} = setup();+ const viewport = cameraTransition(camera);+ sync(mapStateUpdaters.updateMapUpdater(INITIAL_MAP_STATE, updateMap(viewport)));+ expect(read.mock.lastCall[0]).toMatchObject(viewport);+ expect(read.mock.lastCall[0].transitionInterpolator).toBe(viewport.transitionInterpolator);+});++test('preserves an explicit zero-duration update and removes absent transition settings', () => {+ const {read, sync} = setup();+ const animated = mapStateUpdaters.updateMapUpdater(+ INITIAL_MAP_STATE,+ updateMap(cameraTransition(camera))+ );+ sync(animated);+ sync(+ mapStateUpdaters.updateMapUpdater(+ animated,+ updateMap({...camera, zoom: 8, transitionDuration: 0})+ )+ );+ expect(read.mock.lastCall[0]).toMatchObject({zoom: 8, transitionDuration: 0});+ sync({...INITIAL_MAP_STATE, ...camera, zoom: 9});+ expect(read.mock.lastCall[0].transitionDuration).toBeUndefined();+ expect(read.mock.lastCall[0].transitionInterpolator).toBeUndefined();+});++test('acknowledging the current live view does not restart a saved transition', () => {+ const {read, sync} = setup();+ fireEvent.click(screen.getByRole('button', {name: 'Move map'}));+ sync(mapStateUpdaters.updateMapUpdater(INITIAL_MAP_STATE, updateMap(cameraTransition(camera))));+ expect(read.mock.lastCall[0]).toEqual(camera);+});diff --git a/src/components/src/map-view-state-context.tsx b/src/components/src/map-view-state-context.tsxindex c573908af..a361e5a63 100644--- a/src/components/src/map-view-state-context.tsx+++ b/src/components/src/map-view-state-context.tsx@@ -13,6 +13,8 @@ type MapViewState = {maxPitch?: number;minZoom?: number;maxZoom?: number;+ transitionDuration?: number;+ transitionInterpolator?: object;};import {pickViewportPropsFromMapState} from '@kepler.gl/reducers';@@ -61,7 +63,15 @@ export const MapViewStateContextProvider = ({setViewStates(mapState.splitMapViewports as MapState[]);}} else if (hasChanged(primaryState, mapState)) {- setViewStates([pickViewportPropsFromMapState(mapState)] as MapState[]);+ // External navigation carries transient deck.gl options that the viewport picker omits.+ // Keep them for rendering, but exclude them from equality above so live-view echoes+ // do not restart an animation.+ setViewStates([+ {+ ...pickViewportPropsFromMapState(mapState),+ ...pick(mapState, ['transitionDuration', 'transitionInterpolator'])+ }+ ] as MapState[]);}// Only update internalViewState when viewState changes// eslint-disable-next-line react-hooks/exhaustive-depsdiff --git a/src/components/src/map/camera-bookmark-control.spec.tsx b/src/components/src/map/camera-bookmark-control.spec.tsxnew file mode 100644index 000000000..f5731e365--- /dev/null+++ b/src/components/src/map/camera-bookmark-control.spec.tsx@@ -0,0 +1,826 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {fireEvent, screen, within, waitFor} from '@testing-library/react';+import copy from 'copy-to-clipboard';+import {ThemeProvider} from 'styled-components';+import {MapStateActions, UIStateActions, VisStateActions} from '@kepler.gl/actions';+import {INITIAL_MAP_STATE, INITIAL_UI_STATE, uiStateUpdaters} from '@kepler.gl/reducers';+import {theme} from '@kepler.gl/styles';+import {renderWithTheme, IntlWrapper} from 'test/helpers/component-jest-utils';+import CameraBookmarkControl from './camera-bookmark-control';+import {RootContext} from '../context';+import CameraBookmarks from '../side-panel/interaction-panel/camera-bookmarks';+import {DraggableLegend} from './map-legend-panel';+import MapControlPanelFactory from './map-control-panel';++jest.mock('copy-to-clipboard', () => jest.fn(() => true));+const camera = {longitude: 10.12345678, latitude: 20.98765432, zoom: 6, bearing: 30, pitch: 45};+const bookmarks = [{id: 'home', name: 'Home', camera}];+const enabledMapControls = {+ ...INITIAL_UI_STATE.mapControls,+ cameraBookmarks: {...INITIAL_UI_STATE.mapControls.cameraBookmarks, show: true, active: true}+};+const legacyMapControls = {...INITIAL_UI_STATE.mapControls};+delete legacyMapControls.cameraBookmarks;++const pointerEventDescriptor = Object.getOwnPropertyDescriptor(window, 'PointerEvent');+beforeAll(() => {+ class TestPointerEvent extends MouseEvent {+ pointerId = 1;+ isPrimary = true;+ pointerType = 'mouse';+ }+ Object.defineProperty(window, 'PointerEvent', {configurable: true, value: TestPointerEvent});+});+afterAll(() => {+ if (pointerEventDescriptor) Object.defineProperty(window, 'PointerEvent', pointerEventDescriptor);+ else Reflect.deleteProperty(window, 'PointerEvent');+});++function setup(props = {}) {+ const updateMap = jest.fn();+ const settings = jest.fn();+ const visibility = jest.fn();+ const result = renderWithTheme(+ <IntlWrapper>+ <CameraBookmarkControl+ bookmarks={bookmarks}+ mapState={INITIAL_MAP_STATE}+ mapStateActions={{...MapStateActions, updateMap}}+ mapControls={enabledMapControls}+ setMapControlSettings={settings}+ setMapControlVisibility={visibility}+ {...props}+ />+ </IntlWrapper>+ );+ return {...result, updateMap, settings, visibility};+}++test('shows named rows with location icons and preserves animated navigation', () => {+ const {updateMap} = setup();+ const row = screen.getByRole('button', {name: 'Home'});+ expect(row).toHaveTextContent('Home');+ expect(row.querySelector('svg')).not.toBeNull();+ expect(screen.queryByRole('button', {name: '1'})).toBeNull();+ fireEvent.click(row);+ expect(updateMap).toHaveBeenCalledWith(+ expect.objectContaining({...camera, transitionDuration: 1000})+ );+ expect(screen.getByRole('navigation', {name: 'Bookmarks'})).toBeInTheDocument();+});++test('copies the existing latitude/longitude format without a success message or navigation', () => {+ const {updateMap} = setup();+ const copyButton = screen.getByRole('button', {name: 'Copy coordinates: Home'});+ expect(copyButton.querySelector('svg')).toHaveAttribute('height', '14px');+ expect(copyButton).toHaveStyle({width: '28px', height: '28px'});+ fireEvent.click(copyButton);+ expect(copy).toHaveBeenCalledWith('20.987654, 10.123457');+ expect(+ within(screen.getByRole('navigation', {name: 'Bookmarks'})).getByRole('status')+ ).toBeEmptyDOMElement();+ expect(updateMap).not.toHaveBeenCalled();+});++test.each([1, 3])('fits one bookmark at minimum height and keeps %i rows scrollable', count => {+ const rows = Array.from({length: count}, (_, index) => ({+ ...bookmarks[0],+ id: `bookmark-${index}`,+ name: `Bookmark ${index + 1}`+ }));+ const {updateMap, visibility, settings} = setup({+ bookmarks: rows,+ mapControls: {+ ...INITIAL_UI_STATE.mapControls,+ cameraBookmarks: {show: true, active: true, settings: {contentHeight: 48}}+ }+ });+ const navigation = screen.getByRole('navigation', {name: 'Bookmarks'});+ const content = navigation.closest('.map-control__panel-content') as HTMLElement;+ const panel = navigation.closest('.draggable-legend') as HTMLElement;+ const header = panel.querySelector('.map-control__panel-header') as HTMLElement;+ const row = screen.getByRole('button', {name: rows[0].name}).parentElement as HTMLElement;+ const rowStyle = getComputedStyle(row);+ const padding = getComputedStyle(navigation);+ const requiredHeight =+ parseFloat(rowStyle.height) ++ parseFloat(rowStyle.marginBottom) ++ parseFloat(padding.paddingTop) ++ parseFloat(padding.paddingBottom);+ expect(requiredHeight).toBe(48);+ expect(content).toHaveStyle({+ height: `${requiredHeight}px`,+ minHeight: `${requiredHeight}px`,+ overflowY: 'auto'+ });+ expect(header).toHaveStyle({height: '32px'});+ expect(panel).toHaveStyle({borderWidth: '1px'});+ expect(screen.getByRole('button', {name: 'Move Bookmarks'})).toHaveStyle({cursor: 'move'});+ for (const handle of screen.getAllByRole('button', {name: 'Resize Bookmarks'})) {+ expect(handle).toHaveStyle({height: '12px'});+ expect(content).not.toContainElement(handle);+ }+ expect(within(navigation).getAllByRole('button')).toHaveLength(count * 2);+ const last = rows[count - 1];+ const copyButton = screen.getByRole('button', {name: `Copy coordinates: ${last.name}`});+ expect(copyButton).toHaveStyle({height: rowStyle.height, position: 'absolute'});+ copyButton.focus();+ expect(copyButton).toHaveFocus();+ fireEvent.click(copyButton);+ expect(copy).toHaveBeenCalledWith('20.987654, 10.123457');+ expect(updateMap).not.toHaveBeenCalled();+ expect(within(navigation).getByRole('status')).toBeEmptyDOMElement();+ fireEvent.click(screen.getByRole('button', {name: last.name}));+ expect(updateMap).toHaveBeenCalledTimes(1);+ const close = header.querySelector('.close-map-control-item') as HTMLElement;+ expect(content).not.toContainElement(close);+ fireEvent.click(close);+ expect(visibility).toHaveBeenCalledWith('cameraBookmarks', false);+ expect(settings).not.toHaveBeenCalled();+});++test('fills the row with a Layer-style bookmark and an independent overlaid copy control', () => {+ const name = 'A long bookmark name that needs to remain readable in a narrow floating panel';+ const {updateMap} = setup({bookmarks: [{...bookmarks[0], name}]});+ const navigate = screen.getByRole('button', {name});+ const copyButton = screen.getByRole('button', {name: `Copy coordinates: ${name}`});+ const row = navigate.parentElement as HTMLElement;+ const restoreStyles = emulatePointerStyles();+ try {+ expect(row).toHaveStyle({+ position: 'relative',+ width: '100%',+ backgroundColor: theme.panelBackground,+ borderRadius: theme.panelHeaderBorderRadius,+ color: theme.textColor+ });+ expect(navigate).toHaveStyle({+ boxSizing: 'border-box',+ width: '100%',+ height: '100%',+ paddingRight: '40px',+ background: 'transparent'+ });+ expect(navigate).toHaveAttribute('title', name);+ expect(navigate.querySelector('span')).toHaveStyle({+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap'+ });+ expect(copyButton.parentElement).toBe(row);+ expect(navigate.querySelector('button')).toBeNull();+ expect(copyButton).toHaveStyle({+ position: 'absolute',+ right: '4px',+ color: theme.panelHeaderIcon+ });++ row.setAttribute('data-test-hover', '');+ expect(row).toHaveStyle({backgroundColor: theme.panelBackgroundHover});+ copyButton.setAttribute('data-test-hover', '');+ expect(copyButton).toHaveStyle({color: theme.panelHeaderIconHover});+ fireEvent.click(copyButton);+ expect(copy).toHaveBeenCalledWith('20.987654, 10.123457');+ expect(updateMap).not.toHaveBeenCalled();++ navigate.focus();+ navigate.setAttribute('data-test-focus-visible', '');+ expect(navigate).toHaveStyle({outline: `2px solid ${theme.activeColor}`});+ fireEvent.click(navigate);+ expect(updateMap).toHaveBeenCalledTimes(1);+ copyButton.focus();+ copyButton.setAttribute('data-test-focus-visible', '');+ expect(copyButton).toHaveStyle({outline: `2px solid ${theme.activeColor}`});+ } finally {+ restoreStyles();+ }+});++// JSDOM does not evaluate pointer media queries or pointer/focus pseudo-classes reliably.+// Enable the emitted fine-pointer CSS and model states with equal-specificity attributes.+function emulatePointerStyles() {+ const pointerStyles = document.createElement('style');+ pointerStyles.textContent = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter((rule): rule is CSSMediaRule => rule.type === CSSRule.MEDIA_RULE)+ .filter(+ rule =>+ /hover\s*:\s*hover/.test(rule.conditionText) &&+ /pointer\s*:\s*fine/.test(rule.conditionText)+ )+ .flatMap(rule => Array.from(rule.cssRules))+ .map(rule => rule.cssText)+ .join('\n');+ document.head.appendChild(pointerStyles);+ const stateRules = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter((rule): rule is CSSStyleRule => rule.type === CSSRule.STYLE_RULE)+ .filter(rule => /:hover|:focus-visible|:focus-within/.test(rule.selectorText))+ .map(rule => ({rule, selector: rule.selectorText}));+ stateRules.forEach(({rule, selector}) => {+ rule.selectorText = selector+ .replace(/:hover/g, '[data-test-hover]')+ .replace(/:focus-visible/g, '[data-test-focus-visible]')+ .replace(/:focus-within/g, '[data-test-focus-within]');+ });+ // JSDOM can let later base rules override more-specific ancestor state rules.+ const stateStyles = document.createElement('style');+ stateStyles.textContent = stateRules.map(({rule}) => rule.cssText).join('\n');+ document.head.appendChild(stateStyles);+ return () => {+ stateRules.forEach(({rule, selector}) => {+ rule.selectorText = selector;+ });+ stateStyles.remove();+ pointerStyles.remove();+ };+}++test('reveals copying only for its hovered or keyboard-focused row without shifting layout', () => {+ setup({bookmarks: [...bookmarks, {...bookmarks[0], id: 'work', name: 'Work'}]});+ const homeCopy = screen.getByRole('button', {name: 'Copy coordinates: Home'});+ const workCopy = screen.getByRole('button', {name: 'Copy coordinates: Work'});+ const workNavigate = screen.getByRole('button', {name: 'Work'});+ const homeRow = homeCopy.parentElement as HTMLElement;+ const panel = homeCopy.closest('.camera-bookmark-panel') as HTMLElement;+ const restoreStyles = emulatePointerStyles();+ const expectCopyState = (button: HTMLElement, visible: boolean) =>+ expect(button).toHaveStyle({+ opacity: visible ? '1' : '0',+ pointerEvents: visible ? 'auto' : 'none',+ position: 'absolute',+ right: '4px',+ width: '28px',+ height: '28px'+ });+ try {+ expectCopyState(homeCopy, false);+ expectCopyState(workCopy, false);+ fireEvent.mouseEnter(panel);+ panel.setAttribute('data-test-hover', '');+ expectCopyState(homeCopy, false);+ expectCopyState(workCopy, false);++ fireEvent.mouseEnter(homeRow);+ homeRow.setAttribute('data-test-hover', '');+ expectCopyState(homeCopy, true);+ expectCopyState(workCopy, false);+ homeCopy.focus(); // Model native pointer focus, which fireEvent.click does not provide.+ homeRow.setAttribute('data-test-focus-within', '');+ fireEvent.click(homeCopy);+ expect(copy).toHaveBeenLastCalledWith('20.987654, 10.123457');+ fireEvent.mouseLeave(homeRow);+ homeRow.removeAttribute('data-test-hover');+ expect(homeCopy).toHaveFocus();+ expectCopyState(homeCopy, false);+ expectCopyState(workCopy, false);++ homeCopy.setAttribute('data-test-focus-visible', '');+ expectCopyState(homeCopy, true);+ homeCopy.removeAttribute('data-test-focus-visible');+ workNavigate.focus();+ workNavigate.setAttribute('data-test-focus-visible', '');+ expectCopyState(homeCopy, false);+ expectCopyState(workCopy, true);+ workCopy.focus();+ workNavigate.removeAttribute('data-test-focus-visible');+ workCopy.setAttribute('data-test-focus-visible', '');+ expect(workCopy).toHaveFocus();+ expectCopyState(workCopy, true);+ fireEvent.click(workCopy);+ expect(copy).toHaveBeenLastCalledWith('20.987654, 10.123457');+ expect(+ within(screen.getByRole('navigation', {name: 'Bookmarks'})).getByRole('status')+ ).toBeEmptyDOMElement();+ } finally {+ restoreStyles();+ }+});++test('reports clipboard failure and clears it after a successful retry', () => {+ jest.mocked(copy).mockReturnValueOnce(false);+ setup();+ fireEvent.click(screen.getByRole('button', {name: 'Copy coordinates: Home'}));+ expect(+ within(screen.getByRole('navigation', {name: 'Bookmarks'})).getByRole('status')+ ).toHaveTextContent('Could not copy coordinates');+ fireEvent.click(screen.getByRole('button', {name: 'Copy coordinates: Home'}));+ expect(copy).toHaveBeenLastCalledWith('20.987654, 10.123457');+ expect(+ within(screen.getByRole('navigation', {name: 'Bookmarks'})).getByRole('status')+ ).toBeEmptyDOMElement();+});++test.each([INITIAL_UI_STATE.mapControls, legacyMapControls, enabledMapControls])(+ 'default/legacy controls can opt in, close and reopen without deleting bookmarks: %p',+ initialControls => {+ const commit = jest.fn();+ const visibility = jest.fn();+ function Harness() {+ const [uiState, setUiState] = React.useState({...INITIAL_UI_STATE, mapControls: initialControls});+ const setMapControlVisibility: typeof UIStateActions.setMapControlVisibility = (id, show) => {+ visibility(id, show);+ const action = UIStateActions.setMapControlVisibility(id, show);+ setUiState(state => uiStateUpdaters.setMapControlVisibilityUpdater(state, action));+ return action;+ };+ return (+ <>+ <CameraBookmarks+ bookmarks={bookmarks}+ enabled={uiState.mapControls.cameraBookmarks?.show}+ mapState={INITIAL_MAP_STATE}+ mapStateActions={MapStateActions}+ uiStateActions={{...UIStateActions, setMapControlVisibility}}+ visStateActions={{+ ...VisStateActions,+ setCameraBookmarks: Object.assign(commit, VisStateActions.setCameraBookmarks)+ }}+ />+ <CameraBookmarkControl+ bookmarks={bookmarks}+ mapState={INITIAL_MAP_STATE}+ mapStateActions={MapStateActions}+ mapControls={uiState.mapControls}+ setMapControlSettings={UIStateActions.setMapControlSettings}+ setMapControlVisibility={setMapControlVisibility}+ />+ </>+ );+ }+ renderWithTheme(+ <IntlWrapper>+ <Harness />+ </IntlWrapper>+ );+ const toggle = screen.getByRole('checkbox', {name: 'Enable bookmarks'});+ if (initialControls.cameraBookmarks?.show !== true) {+ expect(toggle).not.toBeChecked();+ expect(screen.queryByRole('navigation', {name: 'Bookmarks'})).toBeNull();+ fireEvent.click(toggle);+ expect(visibility).toHaveBeenLastCalledWith('cameraBookmarks', true);+ }+ const panel = screen.getByRole('navigation', {name: 'Bookmarks'}).closest('.map-control-panel');+ const close = panel?.querySelector('.map-control__panel-header .close-map-control-item');+ expect(close).toBeInTheDocument();+ expect(toggle).toBeChecked();+ fireEvent.click(close as HTMLElement);+ expect(visibility).toHaveBeenLastCalledWith('cameraBookmarks', false);+ expect(screen.queryByRole('navigation', {name: 'Bookmarks'})).toBeNull();+ expect(toggle).not.toBeChecked();++ fireEvent.click(toggle);+ expect(visibility).toHaveBeenLastCalledWith('cameraBookmarks', true);+ expect(toggle).toBeChecked();+ expect(screen.getByRole('navigation', {name: 'Bookmarks'})).toBeInTheDocument();+ expect(screen.getByRole('button', {name: 'Home'})).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', {name: 'Bookmarks'}));+ expect(screen.getByRole('textbox', {name: 'Bookmark name 1'})).toHaveValue('Home');+ expect(commit).not.toHaveBeenCalled();+ }+);++test('uses the legend drag and resize surface with independent position settings', () => {+ setup({+ mapControls: {+ ...INITIAL_UI_STATE.mapControls,+ cameraBookmarks: {+ show: true,+ active: true,+ settings: {position: {x: 80, y: 40, anchorX: 'right', anchorY: 'top'}, contentHeight: 180}+ }+ }+ });+ const move = screen.getByLabelText('Move Bookmarks');+ expect(move).toHaveTextContent('Bookmarks');+ expect(move.closest('.map-control__panel-header')).not.toBeNull();+ expect(move.closest('.draggable-legend')?.querySelector('.legend-move-handle')).toBeNull();+ expect(screen.getAllByLabelText('Resize Bookmarks')).toHaveLength(2);+ expect(move.closest('.draggable-legend')).toHaveStyle({right: '80px', top: '40px'});+});++test.each([+ ['mapLegend', 'legend'],+ ['cameraBookmarks', 'Bookmarks']+])('matches the top resize surface at the bottom edge for %s', (controlId, label) => {+ const MapControlPanel = MapControlPanelFactory();+ const activeColor = '#345678';+ renderWithTheme(+ <ThemeProvider theme={{...theme, activeColor}}>+ <DraggableLegend+ controlId={controlId}+ label={label}+ isSidePanelShown={false}+ mapControls={enabledMapControls}+ setMapControlSettings={jest.fn()}+ mapState={INITIAL_MAP_STATE}+ >+ <MapControlPanel header="header.layerLegend">+ <div>Scrollable panel content</div>+ </MapControlPanel>+ </DraggableLegend>+ </ThemeProvider>+ );+ const [top, bottom] = screen.getAllByRole('button', {name: `Resize ${label}`});+ const panel = bottom.closest('.draggable-legend') as HTMLElement;+ const topSurface = top.parentElement;+ const content = panel.querySelector('.map-control__panel-content');+ const restoreStyles = emulatePointerStyles();+ try {+ for (const handle of [top, bottom]) {+ expect(handle).toHaveStyle({width: '32px', height: '12px', cursor: 'ns-resize'});+ expect(handle.querySelector('svg')).toHaveAttribute('height', '12px');+ expect(handle).toHaveAttribute('tabindex', '0');+ }+ expect(topSurface).toHaveStyle({+ backgroundColor: activeColor,+ borderRadius: '4px',+ height: '12px',+ top: '0px',+ transform: 'translate(-50%, -50%)'+ });+ expect(bottom).toHaveStyle({+ backgroundColor: activeColor,+ borderRadius: '4px',+ bottom: '0px',+ left: '50%',+ transform: 'translate(-50%, 50%)',+ opacity: '0',+ pointerEvents: 'none'+ });+ expect(bottom.closest('.map-control__panel-content')).toBeNull();+ expect(content).toHaveStyle({minHeight: '100px', overflowY: 'auto'});+ expect(screen.getByRole('button', {name: `Move ${label}`})).toHaveStyle({cursor: 'move'});++ panel.setAttribute('data-test-hover', '');+ expect(bottom).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ expect(topSurface).toHaveStyle({opacity: '1'});+ panel.removeAttribute('data-test-hover');+ expect(bottom).toHaveStyle({opacity: '0', pointerEvents: 'none'});+ bottom.focus();+ panel.setAttribute('data-test-focus-within', '');+ expect(bottom).toHaveFocus();+ expect(bottom).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ } finally {+ restoreStyles();+ }+});++function setupFloatingPanel(controlId: string, label: string) {+ const MapControlPanel = MapControlPanelFactory();+ const root = document.createElement('div');+ root.className = 'kepler-gl';+ document.body.appendChild(root);+ const rect = {+ x: 0,+ y: 0,+ left: 0,+ top: 0,+ width: 1000,+ height: 800,+ right: 1000,+ bottom: 800,+ toJSON: () => ({})+ };+ root.getBoundingClientRect = () => rect;+ const settings = jest.fn();+ const close = jest.fn();+ const pin = jest.fn();+ const contentAction = jest.fn();+ renderWithTheme(+ <DraggableLegend+ controlId={controlId}+ label={label}+ isSidePanelShown={false}+ mapControls={enabledMapControls}+ setMapControlSettings={settings}+ mapState={{...INITIAL_MAP_STATE, width: 1000, height: 800}}+ >+ <MapControlPanel+ header={controlId === 'mapLegend' ? 'header.layerLegend' : 'camera.bookmarks'}+ onClick={close}+ onPinClick={pin}+ pinnable+ >+ <button onClick={contentAction}>Content action</button>+ </MapControlPanel>+ </DraggableLegend>,+ {container: root}+ );+ const move = screen.getByRole('button', {name: `Move ${label}`});+ const panel = move.closest('.draggable-legend') as HTMLElement;+ panel.getBoundingClientRect = () => {+ const translation = /translate3d\(([-\d.]+)px, ([-\d.]+)px/.exec(panel.style.transform);+ const x = 600 + Number(translation?.[1] || 0);+ const y = 40 + Number(translation?.[2] || 0);+ return {+ ...rect,+ x,+ y,+ left: x,+ top: y,+ width: 300,+ height: 214,+ right: x + 300,+ bottom: y + 214+ };+ };+ Object.defineProperty(panel.querySelector('.map-control__panel-content'), 'offsetHeight', {+ value: 180+ });+ screen.getAllByRole('button', {name: `Resize ${label}`}).forEach((handle, index) => {+ const y = index === 0 ? 34 : 248;+ handle.getBoundingClientRect = () => ({+ ...rect,+ x: 734,+ y,+ left: 734,+ top: y,+ width: 32,+ height: 12,+ right: 766,+ bottom: y + 12+ });+ });+ return {move, panel, settings, close, pin, contentAction};+}++async function waitForPointerClickRelease() {+ // dnd-kit briefly suppresses document clicks after pointer drops; let it clean up+ // before the next test exercises unrelated click actions.+ const clickReleased = jest.fn();+ document.addEventListener('click', clickReleased, {once: true});+ await waitFor(() => {+ fireEvent.click(document);+ expect(clickReleased).toHaveBeenCalledTimes(1);+ });+}++test.each([+ ['mapLegend', 'legend'],+ ['cameraBookmarks', 'Bookmarks']+])('moves %s from its title with pointer and keyboard', async (controlId, label) => {+ const {move, panel, settings} = setupFloatingPanel(controlId, label);+ expect(move).toHaveStyle({flex: '1', height: '32px', cursor: 'move'});+ // JSDOM does not expose touch-action in computed styles; inspect its emitted rule.+ const titleRules = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter((rule): rule is CSSStyleRule => rule.type === CSSRule.STYLE_RULE)+ .filter(rule => move.matches(rule.selectorText));+ expect(titleRules.some(rule => rule.style.getPropertyValue('touch-action') === 'none')).toBe(+ true+ );+ expect(move).toHaveAttribute('tabindex', '0');+ expect(panel.querySelector('.legend-top-handles')?.children).toHaveLength(1);+ expect(move.querySelector('.close-map-control-item')).toBeNull();+ fireEvent.pointerDown(move, {button: 0, clientX: 650, clientY: 55});+ await waitFor(() => expect(move).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.pointerMove(document, {clientX: 675, clientY: 80});+ await waitFor(() => expect(panel).toHaveStyle({transform: 'translate3d(25px, 25px, 0)'}));+ fireEvent.pointerUp(document);+ await waitFor(() => expect(move).not.toHaveAttribute('aria-pressed', 'true'));+ expect(settings).toHaveBeenLastCalledWith(controlId, {+ position: {x: 75, y: 65, anchorX: 'right', anchorY: 'top'}+ });++ settings.mockClear();+ move.focus();+ fireEvent.keyDown(move, {code: 'Space'});+ await waitFor(() => expect(move).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.keyDown(document, {code: 'ArrowRight'});+ await waitFor(() => expect(panel).toHaveStyle({transform: 'translate3d(25px, 0px, 0)'}));+ fireEvent.keyDown(document, {code: 'Space'});+ await waitFor(() => expect(move).not.toHaveAttribute('aria-pressed', 'true'));+ expect(move).toHaveFocus();+ expect(settings).toHaveBeenLastCalledWith(controlId, {+ position: {x: 75, y: 40, anchorX: 'right', anchorY: 'top'}+ });+ expect(+ settings.mock.calls.every(([id, value]) => id === controlId && !('contentHeight' in value))+ ).toBe(true);+ await waitForPointerClickRelease();+});++test.each([+ ['mapLegend', 'legend'],+ ['cameraBookmarks', 'Bookmarks']+])('keeps %s controls and resizing separate from title dragging', async (controlId, label) => {+ const {move, panel, settings, close, pin, contentAction} = setupFloatingPanel(controlId, label);+ const header = move.closest('.map-control__panel-header') as HTMLElement;+ for (const target of [+ header.querySelector('.close-map-control-item'),+ header.querySelector('.pin-map-control-item'),+ screen.getByRole('button', {name: 'Content action'}),+ panel.querySelector('.map-control__panel-content')+ ]) {+ expect(target).not.toBeNull();+ fireEvent.pointerDown(target as Element, {button: 0, clientX: 650, clientY: 55});+ fireEvent.pointerMove(document, {clientX: 675, clientY: 80});+ fireEvent.pointerUp(document);+ fireEvent.click(target as Element);+ fireEvent.keyDown(target as Element, {code: 'Space'});+ expect(move).not.toHaveAttribute('aria-pressed', 'true');+ }+ expect(close).toHaveBeenCalledTimes(1);+ expect(pin).toHaveBeenCalledTimes(1);+ expect(contentAction).toHaveBeenCalledTimes(1);+ expect(settings).not.toHaveBeenCalled();++ const handles = screen.getAllByRole('button', {name: `Resize ${label}`});+ for (const [index, handle] of handles.entries()) {+ settings.mockClear();+ handle.focus();+ fireEvent.keyDown(handle, {code: 'Space'});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ expect(move).not.toHaveAttribute('aria-pressed', 'true');+ fireEvent.keyDown(document, {code: index === 0 ? 'ArrowUp' : 'ArrowDown'});+ await waitFor(() =>+ expect(settings).toHaveBeenCalledWith(+ controlId,+ expect.objectContaining({contentHeight: 205})+ )+ );+ expect(panel.style.transform).toBe('');+ fireEvent.keyDown(document, {code: 'Space'});+ await waitFor(() => expect(handle).not.toHaveAttribute('aria-pressed', 'true'));++ settings.mockClear();+ const pointerY = handle.getBoundingClientRect().top + 6;+ fireEvent.pointerDown(handle, {button: 0, clientX: 750, clientY: pointerY});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.pointerMove(document, {+ clientX: 750,+ clientY: pointerY + (index === 0 ? -20 : 20)+ });+ await waitFor(() =>+ expect(settings).toHaveBeenCalledWith(+ controlId,+ expect.objectContaining({contentHeight: 200})+ )+ );+ expect(move).not.toHaveAttribute('aria-pressed', 'true');+ expect(panel.style.transform).toBe('');+ fireEvent.pointerUp(document);+ await waitFor(() => expect(handle).not.toHaveAttribute('aria-pressed', 'true'));+ }+ await waitForPointerClickRelease();+});++test.each([false, true])('keeps ordinary and export headers static (export=%s)', isExport => {+ const MapControlPanel = MapControlPanelFactory();+ renderWithTheme(<MapControlPanel header="header.layerLegend" isExport={isExport} />);+ expect(screen.queryByRole('button', {name: /Move /})).toBeNull();+ expect(document.querySelector('.map-control__panel-drag-title')).toBeNull();+});++test('bookmark copy, navigation and close do not activate title dragging', () => {+ const {updateMap, visibility, settings} = setup();+ const move = screen.getByRole('button', {name: 'Move Bookmarks'});+ const copyButton = screen.getByRole('button', {name: 'Copy coordinates: Home'});+ const navigate = screen.getByRole('button', {name: 'Home'});+ const close = move.parentElement?.querySelector('.close-map-control-item') as Element;+ for (const target of [copyButton, navigate, close]) {+ fireEvent.pointerDown(target, {button: 0, clientX: 20, clientY: 20});+ fireEvent.pointerMove(document, {clientX: 40, clientY: 40});+ fireEvent.pointerUp(document);+ fireEvent.click(target);+ expect(move).not.toHaveAttribute('aria-pressed', 'true');+ }+ expect(copy).toHaveBeenCalledWith('20.987654, 10.123457');+ expect(updateMap).toHaveBeenCalledTimes(1);+ expect(visibility).toHaveBeenCalledWith('cameraBookmarks', false);+ expect(settings).not.toHaveBeenCalled();+});++test.each([+ {isExport: true},+ {mapState: {...INITIAL_MAP_STATE, isSplit: true}},+ {mapState: {...INITIAL_MAP_STATE, globe: {...INITIAL_MAP_STATE.globe!, enabled: true}}},+ {bookmarks: []},+ {mapControls: {cameraBookmarks: {show: false, active: true}}},+ {mapControls: INITIAL_UI_STATE.mapControls},+ {mapControls: undefined},+ {mapControls: legacyMapControls},+ {mapControls: {cameraBookmarks: {active: true}}}+])('hides the panel for unavailable or disabled views: %p', props => {+ setup(props);+ expect(screen.queryByRole('navigation')).toBeNull();+});++test.each(['top', 'bottom'])('keyboard %s resize stops at one bookmark height', async edge => {+ const root = document.createElement('div');+ root.className = 'kepler-gl';+ document.body.appendChild(root);+ const rect = {+ x: 0,+ y: 0,+ left: 0,+ top: 0,+ width: 1000,+ height: 800,+ right: 1000,+ bottom: 800,+ toJSON: () => ({})+ };+ root.getBoundingClientRect = () => rect;+ const settings = jest.fn();+ const {unmount} = renderWithTheme(+ <IntlWrapper>+ <RootContext.Provider value={{current: root}}>+ <CameraBookmarkControl+ bookmarks={bookmarks}+ mapState={{...INITIAL_MAP_STATE, width: 1000, height: 800}}+ mapStateActions={MapStateActions}+ mapControls={enabledMapControls}+ setMapControlSettings={settings}+ />+ </RootContext.Provider>+ </IntlWrapper>+ );+ const panel = root.querySelector('.draggable-legend') as HTMLElement;+ panel.getBoundingClientRect = () => ({+ ...rect,+ x: 600,+ y: 40,+ left: 600,+ top: 40,+ width: 300,+ height: 214,+ right: 900,+ bottom: 254+ });+ Object.defineProperty(panel.querySelector('.map-control__panel-content'), 'offsetHeight', {+ value: 180+ });+ expect(panel.querySelector('.map-control__panel-content')).toHaveStyle({minHeight: '48px'});+ const handle = screen.getAllByRole('button', {name: 'Resize Bookmarks'})[edge === 'top' ? 0 : 1];+ const handleY = edge === 'top' ? 34 : 248;+ handle.getBoundingClientRect = () => ({+ ...rect,+ x: 734,+ y: handleY,+ left: 734,+ top: handleY,+ width: 32,+ height: 12,+ right: 766,+ bottom: handleY + 12+ });+ handle.focus();+ fireEvent.keyDown(handle, {code: 'Space'});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.keyDown(document, {code: edge === 'top' ? 'ArrowUp' : 'ArrowDown'});+ await waitFor(() =>+ expect(settings).toHaveBeenCalledWith(+ 'cameraBookmarks',+ expect.objectContaining({contentHeight: 205})+ )+ );+ fireEvent.keyDown(document, {code: 'Space'});+ await waitFor(() => expect(handle).not.toHaveAttribute('aria-pressed', 'true'));+ fireEvent.keyDown(handle, {code: 'Space'});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ for (let step = 0; step < 6; step++) {+ fireEvent.keyDown(document, {code: edge === 'top' ? 'ArrowDown' : 'ArrowUp'});+ }+ await waitFor(() =>+ expect(settings).toHaveBeenCalledWith(+ 'cameraBookmarks',+ expect.objectContaining({contentHeight: 48})+ )+ );+ fireEvent.keyDown(document, {code: 'Space'});+ expect(settings.mock.calls.every(([id]) => id === 'cameraBookmarks')).toBe(true);+ unmount();+ root.remove();+});++test('mounts the floating panel inside its map root after the initial ref attaches', () => {+ function Harness() {+ const root = React.useRef<HTMLDivElement>(null);+ return (+ <RootContext.Provider value={root}>+ <div ref={root} data-testid="map-root">+ <CameraBookmarkControl+ bookmarks={bookmarks}+ mapState={INITIAL_MAP_STATE}+ mapStateActions={MapStateActions}+ mapControls={enabledMapControls}+ setMapControlSettings={jest.fn()}+ />+ </div>+ </RootContext.Provider>+ );+ }+ renderWithTheme(+ <IntlWrapper>+ <Harness />+ </IntlWrapper>+ );+ expect(screen.getByTestId('map-root')).toContainElement(+ screen.getByRole('button', {name: 'Home'})+ );+});diff --git a/src/components/src/map/camera-bookmark-control.tsx b/src/components/src/map/camera-bookmark-control.tsxnew file mode 100644index 000000000..69b8628ef--- /dev/null+++ b/src/components/src/map/camera-bookmark-control.tsx@@ -0,0 +1,222 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useContext, useEffect, useState} from 'react';+import {createPortal} from 'react-dom';+import styled from 'styled-components';+import {useIntl} from 'react-intl';+import copy from 'copy-to-clipboard';+import {CameraBookmark, MapControls, MapState} from '@kepler.gl/types';+import {MapStateActions, UIStateActions} from '@kepler.gl/actions';+import {breakPointValues} from '@kepler.gl/styles';+import {hasPortableWidth} from '@kepler.gl/utils';+import {StyledPanelHeader} from '../common/styled-components';+import {LocationMarker, Copy} from '../common/icons';+import {RootContext} from '../context';+import {cameraTransition} from '../camera-navigation';+import {DraggableLegend} from './map-legend-panel';+import MapControlPanelFactory from './map-control-panel';+import {formatMapCoordinate} from './coordinate-info';++const ROW_HEIGHT = 28;+const ROW_GAP = 4;+const ROWS_PADDING = 8;+const MIN_CONTENT_HEIGHT = ROW_HEIGHT + ROW_GAP + ROWS_PADDING * 2;++const MapControlPanel = styled(MapControlPanelFactory())`+ .map-control__panel-content {+ min-height: ${MIN_CONTENT_HEIGHT}px;+ }+`;+const Rows = styled.nav`+ padding: ${ROWS_PADDING}px;+`;+const Row = styled(StyledPanelHeader)`+ position: relative;+ width: 100%;+ height: ${ROW_HEIGHT}px;+ min-width: 0;+ margin-bottom: ${ROW_GAP}px;+ padding: 0;+ border: 0;+ color: ${props => props.theme.textColor};+ &:hover {+ background-color: ${props => props.theme.panelBackgroundHover};+ }+ @media (hover: hover) and (pointer: fine) {+ .camera-bookmark-copy {+ opacity: 0;+ pointer-events: none;+ }+ &:hover .camera-bookmark-copy,+ &:has(:focus-visible) .camera-bookmark-copy {+ opacity: 1;+ pointer-events: auto;+ }+ }+`;+const NavigateButton = styled.button`+ box-sizing: border-box;+ display: flex;+ align-items: center;+ width: 100%;+ height: 100%;+ min-width: 0;+ justify-content: flex-start;+ gap: 8px;+ padding: 0 40px 0 9px;+ border: 0;+ border-radius: inherit;+ background: transparent;+ color: inherit;+ font-family: ${props => props.theme.btnFontFamily};+ font-size: ${props => props.theme.primaryBtnFontSizeSmall};+ font-weight: 500;+ line-height: 14px;+ text-align: left;+ cursor: pointer;+ outline: 0;+ &:focus-visible {+ outline: 2px solid ${props => props.theme.activeColor};+ }+ svg {+ flex: 0 0 auto;+ }+ span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+`;+const CopyButton = styled(NavigateButton)`+ position: absolute;+ top: 0;+ right: 4px;+ width: 28px;+ height: ${ROW_HEIGHT}px;+ justify-content: center;+ padding: 0;+ color: ${props => props.theme.panelHeaderIcon};+ &:hover {+ color: ${props => props.theme.panelHeaderIconHover};+ }+ &:disabled {+ cursor: default;+ opacity: 0.3;+ }+ svg {+ margin: 0;+ }+`;+const Status = styled.div`+ color: ${props => props.theme.textColor};+ font-size: 11px;+`;++export default function CameraBookmarkControl({+ bookmarks = [],+ mapState,+ mapStateActions,+ mapControls,+ setMapControlSettings,+ setMapControlVisibility,+ activeSidePanel,+ isExport+}: {+ bookmarks?: CameraBookmark[];+ mapState?: MapState;+ mapStateActions?: typeof MapStateActions;+ mapControls?: MapControls;+ setMapControlSettings?: typeof UIStateActions.setMapControlSettings;+ setMapControlVisibility?: typeof UIStateActions.setMapControlVisibility;+ activeSidePanel?: string | null;+ isExport?: boolean;+}) {+ const intl = useIntl();+ const root = useContext(RootContext);+ const [status, setStatus] = useState('');+ const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);+ useEffect(() => {+ // Resolve after refs attach so an initial render stays inside its own map root.+ setPortalContainer(root?.current ?? document.body);+ }, [root]);+ const message = (key: string, fallback: string) =>+ intl.formatMessage({id: `camera.${key}`, defaultMessage: fallback});+ if (+ !bookmarks.length ||+ !mapState ||+ !mapStateActions ||+ isExport ||+ mapState.isSplit ||+ mapState.globe?.enabled ||+ mapControls?.cameraBookmarks?.show !== true+ )+ return null;++ const title = message('bookmarks', 'Bookmarks');+ const panel = (+ <MapControlPanel+ header="camera.bookmarks"+ disableClose={!setMapControlVisibility}+ onClick={event => {+ event.preventDefault();+ setMapControlVisibility?.('cameraBookmarks', false);+ }}+ className="camera-bookmark-panel"+ >+ <Rows aria-label={title}>+ {bookmarks.map((bookmark, index) => {+ const name = bookmark.name || `${message('bookmark', 'Bookmark')} ${index + 1}`;+ const coordinates = formatMapCoordinate([+ bookmark.camera.longitude,+ bookmark.camera.latitude+ ]);+ const copyLabel = `${message('copyCoordinates', 'Copy coordinates')}: ${name}`;+ return (+ <Row key={bookmark.id}>+ <NavigateButton+ type="button"+ title={name}+ onClick={() => mapStateActions.updateMap(cameraTransition(bookmark.camera))}+ >+ <LocationMarker height="16px" aria-hidden="true" />+ <span>{name}</span>+ </NavigateButton>+ <CopyButton+ className="camera-bookmark-copy"+ type="button"+ aria-label={copyLabel}+ title={copyLabel}+ disabled={!coordinates}+ onClick={() => {+ const copied = coordinates && copy(coordinates);+ setStatus(copied ? '' : message('copyFailed', 'Could not copy coordinates'));+ }}+ >+ <Copy height="14px" aria-hidden="true" />+ </CopyButton>+ </Row>+ );+ })}+ <Status role="status" aria-live="polite">+ {status}+ </Status>+ </Rows>+ </MapControlPanel>+ );++ if (!setMapControlSettings || hasPortableWidth(breakPointValues)) return panel;+ return createPortal(+ <DraggableLegend+ controlId="cameraBookmarks"+ label={title}+ isSidePanelShown={Boolean(activeSidePanel)}+ mapControls={mapControls || {}}+ setMapControlSettings={setMapControlSettings}+ mapState={mapState}+ >+ {panel}+ </DraggableLegend>,+ portalContainer ?? root?.current ?? document.body+ );+}diff --git a/src/components/src/map/map-control-panel.tsx b/src/components/src/map/map-control-panel.tsxindex 6ac77b042..eeec99f1a 100644--- a/src/components/src/map/map-control-panel.tsx+++ b/src/components/src/map/map-control-panel.tsx@@ -1,7 +1,8 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React, {useCallback} from 'react';+import React, {createContext, useCallback, useContext} from 'react';+import type {useDraggable} from '@dnd-kit/core';import styled from 'styled-components';import {FormattedMessage} from '@kepler.gl/localization';import {CenterFlexbox, IconRoundSmall} from '../common/styled-components';@@ -12,6 +13,14 @@ import {ActionHandler, toggleSplitMapViewport} from '@kepler.gl/actions';import {MapSplitMode} from '@kepler.gl/constants';import classNames from 'classnames';+// Internal wiring for floating panels; ordinary and exported headers stay static.+export const MapControlPanelDragContext = createContext<+ | (Pick<ReturnType<typeof useDraggable>, 'attributes' | 'listeners' | 'setActivatorNodeRef'> & {+ label: string;+ })+ | null+>(null);+const StyledMapControlPanel = styled.div`background-color: ${props => props.theme.mapPanelBackgroundColor};box-sizing: border-box;@@ -58,12 +67,36 @@ const StyledMapControlPanelHeader = styled.div.attrs({box-sizing: border-box;align-items: center;- button {+ button:not(.map-control__panel-drag-title) {width: 18px;height: 18px;}`;+const StyledDragTitle = styled.button.attrs({className: 'map-control__panel-drag-title'})`+ flex: 1;+ min-width: 0;+ height: 32px;+ margin: -6px 0 -6px -12px;+ padding: 6px 12px;+ border: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ text-align: left;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ cursor: move;+ touch-action: none;+ user-select: none;+ outline: none;+ &:focus-visible {+ outline: 2px solid ${props => props.theme.activeColor};+ outline-offset: -2px;+ }+`;+const StyledMapControlPanelHeaderSplitViewportsTools = styled(StyledMapControlPanelHeader).attrs({className: 'map-control__panel-split-viewport-tools'})`@@ -138,6 +171,7 @@ function MapControlPanelFactory() {isViewportUnsyncAllowed,className = 'map-control-panel'}) => {+ const drag = useContext(MapControlPanelDragContext);const {isViewportSynced, isZoomLocked} = mapState || {};const onUnlockViewportChange = useCallback(() => {onToggleSplitMapViewport?.({isViewportSynced: !isViewportSynced});@@ -185,6 +219,16 @@ function MapControlPanelFactory() {{(isExport && logoComponent ? (logoComponent+ ) : header && drag && !isExport ? (+ <StyledDragTitle+ type="button"+ ref={drag.setActivatorNodeRef}+ {...drag.attributes}+ {...drag.listeners}+ aria-label={`Move ${drag.label}`}+ >+ <FormattedMessage id={header} />+ </StyledDragTitle>) : header ? (<span style={{verticalAlign: 'middle'}}><FormattedMessage id={header} />diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsxindex 460352973..8b228868c 100644--- a/src/components/src/map/map-control.tsx+++ b/src/components/src/map/map-control.tsx@@ -4,6 +4,7 @@import React from 'react';import styled from 'styled-components';import KeplerGlLogo from '../common/logo';+import CameraBookmarkControl from './camera-bookmark-control';// factoriesimport SplitMapButtonFactory from './split-map-button';@@ -15,6 +16,7 @@ import ThemeToggleButtonFactory from './theme-toggle-button';import MapNavigationControlFactory from './map-navigation-control';import {Layer} from '@kepler.gl/layers';import {+ CameraBookmark,Editor,LayerVisConfig,LayerOrder,@@ -92,8 +94,10 @@ export type MapControlProps = {themeName?: string;logoComponent?: React.FC | React.ReactNode;isExport?: boolean;+ cameraBookmarks?: CameraBookmark[];setMapControlSettings: typeof UIStateActions.setMapControlSettings;+ setMapControlVisibility?: typeof UIStateActions.setMapControlVisibility;activeSidePanel: string | null;// optional@@ -177,6 +181,16 @@ function MapControlFactory(};return (<StyledMapControl className="map-control" $top={top}>+ <CameraBookmarkControl+ bookmarks={restProps.cameraBookmarks}+ mapControls={restProps.mapControls}+ setMapControlSettings={restProps.setMapControlSettings}+ setMapControlVisibility={restProps.setMapControlVisibility}+ activeSidePanel={restProps.activeSidePanel}+ mapState={mapState}+ mapStateActions={mapStateActions}+ isExport={restProps.isExport}+ />{actionComponents.map((ActionComponent, index) => (<ActionComponent key={index} className="map-control-action" {...actionComponentProps} />))}diff --git a/src/components/src/map/map-legend-panel.tsx b/src/components/src/map/map-legend-panel.tsxindex d338001e5..02b58b183 100644--- a/src/components/src/map/map-legend-panel.tsx+++ b/src/components/src/map/map-legend-panel.tsx@@ -31,11 +31,11 @@ import {import {hasPortableWidth} from '@kepler.gl/utils';import {MapLegendControlSettings} from '@kepler.gl/types';-import {Legend, DraggableDots, HorizontalResizeHandle} from '../common/icons';+import {Legend, HorizontalResizeHandle} from '../common/icons';import {MapControlButton} from '../common/styled-components';import {RootContext} from '../context';import useLegendPosition from '../hooks/use-legend-position';-import MapControlPanelFactory from './map-control-panel';+import MapControlPanelFactory, {MapControlPanelDragContext} from './map-control-panel';import MapControlTooltipFactory from './map-control-tooltip';import MapLegendFactory from './map-legend';import {restrictToWindowEdges} from '@dnd-kit/modifiers';@@ -65,18 +65,24 @@ const StyledDraggableLegendContent = styled.div<{background-color: transparent;}&:hover,+ &:focus-within,&.is-dragging {.legend-top-handles,- .legend-move-handle,.legend-resize-handle {opacity: 1;}- .legend-move-handle,.legend-resize-handle {pointer-events: auto;}border-color: ${props => props.theme.activeColor};}+ @media (hover: none), (pointer: coarse) {+ .legend-top-handles,+ .legend-resize-handle {+ opacity: 1;+ pointer-events: auto;+ }+ }.map-control__panel-content {max-height: ${props =>props.$maxContentHeight ? `${props.$maxContentHeight}px` : 'calc(100vh - 100px)'};@@ -102,23 +108,11 @@ const StyledTopHandles = styled.div`top: 0;left: 50%;transform: translate(-50%, -50%);- height: 16px;+ height: 12px;border-radius: 4px;background-color: ${props => props.theme.activeColor};`;-const StyledMoveHandle = styled.div`- pointer-events: none;- display: flex;- flex-direction: column;- align-items: center;- justify-content: center;- width: 48px;- height: 16px;- cursor: move;- border-left: 1px solid rgba(255, 255, 255, 0.25);-`;-const StyledTopResizeHandle = styled.div`pointer-events: none;display: flex;@@ -126,28 +120,21 @@ const StyledTopResizeHandle = styled.div`align-items: center;justify-content: center;width: 32px;- height: 16px;+ height: 12px;cursor: ns-resize;color: #f7f8fa;`;-const StyledResizeHandle = styled.div`- pointer-events: none;+const StyledResizeHandle = styled(StyledTopResizeHandle)`opacity: 0;transition: opacity 0.2s ease-in-out;position: absolute;- display: flex;- flex-direction: column;- align-items: center;- color: #f7f8fa;z-index: 2;bottom: 0;left: 50%;- transform: translate(-50%, -50%);- width: 48px;- height: 16px;+ transform: translate(-50%, 50%);border-radius: 4px;- cursor: ns-resize;+ background-color: ${props => props.theme.activeColor};`;const StyledFixedLegendContent = styled.div<{$contentHeight?: number}>`@@ -178,10 +165,11 @@ type DraggableLegendContentProps = {maxContentHeight?: number;positionStyles: Record<string, unknown>;children: React.ReactNode;+ label: string;};const DraggableLegendContent = forwardRef((props: DraggableLegendContentProps, ref) => {- const {positionStyles, children, contentHeight, maxContentHeight} = props;+ const {positionStyles, children, contentHeight, maxContentHeight, label} = props;const draggableMove = useDraggable({id: DRAG_MOVE_ID});const draggableResize = useDraggable({id: DRAG_RESIZE_ID});const draggableResizeTop = useDraggable({id: DRAG_RESIZE_TOP_ID});@@ -195,36 +183,37 @@ const DraggableLegendContent = forwardRef((props: DraggableLegendContentProps, rstyle={{...positionStyles, transform: CSS.Translate.toString(draggableMove.transform)}}$contentHeight={contentHeight}$maxContentHeight={maxContentHeight}- {...draggableMove.attributes}>- {children}+ <MapControlPanelDragContext.Provider+ value={{+ attributes: draggableMove.attributes,+ listeners: draggableMove.listeners,+ setActivatorNodeRef: draggableMove.setActivatorNodeRef,+ label+ }}+ >+ {children}+ </MapControlPanelDragContext.Provider>{isDragging ? <div className="legend-input-block" /> : null}<StyledTopHandles className="legend-top-handles"><StyledTopResizeHandleclassName="legend-resize-handle legend-resize-handle--top"- aria-label="Resize legend"+ aria-label={`Resize ${label}`}ref={draggableResizeTop.setNodeRef}{...draggableResizeTop.attributes}{...draggableResizeTop.listeners}>- <HorizontalResizeHandle height="16px" />+ <HorizontalResizeHandle height="12px" /></StyledTopResizeHandle>- <StyledMoveHandle- className="legend-move-handle"- aria-label="Move legend"- {...draggableMove.listeners}- >- <DraggableDots height="16px" />- </StyledMoveHandle></StyledTopHandles><StyledResizeHandleclassName="legend-resize-handle"- aria-label="Resize legend"+ aria-label={`Resize ${label}`}ref={draggableResize.setNodeRef}{...draggableResize.attributes}{...draggableResize.listeners}>- <HorizontalResizeHandle height="16px" />+ <HorizontalResizeHandle height="12px" /></StyledResizeHandle></StyledDraggableLegendContent>);@@ -235,23 +224,27 @@ type DraggableLegendProps = PropsWithChildren<{mapControls: MapControls;setMapControlSettings: typeof setMapControlSettings;mapState?: MapState;+ controlId?: string;+ label?: string;}>;-const DraggableLegend = withTheme(+export const DraggableLegend = withTheme(({isSidePanelShown,children,mapControls,setMapControlSettings,mapState,+ controlId = 'mapLegend',+ label = 'legend',theme}: DraggableLegendProps & {theme: any}) => {- const settings = mapControls?.mapLegend?.settings;+ const settings = (mapControls?.[controlId] as MapControlMapLegend)?.settings;const legendContentRef = useRef<HTMLElement>(null);const onChangeSettings = useCallback(- newSettings => setMapControlSettings('mapLegend', newSettings),- [setMapControlSettings]+ newSettings => setMapControlSettings(controlId, newSettings),+ [setMapControlSettings, controlId]);const {positionStyles, updatePosition, startResize, resize, contentHeight, maxContentHeight} =useLegendPosition({@@ -301,6 +294,7 @@ const DraggableLegend = withTheme(><DraggableLegendContentref={legendContentRef}+ label={label}positionStyles={positionStyles}contentHeight={contentHeight}maxContentHeight={maxContentHeight}diff --git a/src/components/src/maps-layout.tsx b/src/components/src/maps-layout.tsxindex f17e62591..759ae8f34 100644--- a/src/components/src/maps-layout.tsx+++ b/src/components/src/maps-layout.tsx@@ -44,6 +44,8 @@ MapsLayoutFactory.deps = [];interface MapsLayoutProps {mapState: MapState;+ /** Use the surrounding provider when the sidebar shares the live camera. */+ provideViewState?: boolean;className?: string;children?: React.ReactNode;onSetSwipeComparePercentage?: (payload: {percentage: number}) => void;@@ -52,6 +54,7 @@ interface MapsLayoutProps {export default function MapsLayoutFactory(): React.ComponentType<MapsLayoutProps> {const MapsLayout: React.FC<MapsLayoutProps> = ({mapState,+ provideViewState = true,className,children,onSetSwipeComparePercentage@@ -106,32 +109,36 @@ export default function MapsLayoutFactory(): React.ComponentType<MapsLayoutPropsoverflow: 'hidden' as const};+ const maps = isSwipe ? (+ <>+ <MapWrapper key={1}>{childrenArray[1]}</MapWrapper>+ <MapWrapper key={0} style={splitMapStyle}>+ {childrenArray[0]}+ </MapWrapper>+ {containerMounted && containerElementRef.current && (+ <>+ {isSwiping && <SwipeInputBlock />}+ <LayoutSplitter+ mode={LayoutSplitterMode.VERTICAL}+ referenceElement={containerElementRef.current}+ percentageSplit={internalPercentage}+ onMove={handleMove}+ onRelease={handleRelease}+ />+ </>+ )}+ </>+ ) : (+ childrenArray+ );+return (<Outer className={className} ref={containerElementRef}>- <MapViewStateContextProvider mapState={mapState}>- {isSwipe ? (- <>- <MapWrapper key={1}>{childrenArray[1]}</MapWrapper>- <MapWrapper key={0} style={splitMapStyle}>- {childrenArray[0]}- </MapWrapper>- {containerMounted && containerElementRef.current && (- <>- {isSwiping && <SwipeInputBlock />}- <LayoutSplitter- mode={LayoutSplitterMode.VERTICAL}- referenceElement={containerElementRef.current}- percentageSplit={internalPercentage}- onMove={handleMove}- onRelease={handleRelease}- />- </>- )}- </>- ) : (- childrenArray- )}- </MapViewStateContextProvider>+ {provideViewState ? (+ <MapViewStateContextProvider mapState={mapState}>{maps}</MapViewStateContextProvider>+ ) : (+ maps+ )}</Outer>);};diff --git a/src/components/src/side-panel.tsx b/src/components/src/side-panel.tsxindex 44ac97a8c..206afcabb 100644--- a/src/components/src/side-panel.tsx+++ b/src/components/src/side-panel.tsx@@ -119,6 +119,7 @@ export default function SidePanelFactory(filters,layers,annotations = [],+ cameraBookmarks,layerBlending,overlayBlending,layerClasses,@@ -243,6 +244,7 @@ export default function SidePanelFactory(filters={filters}layers={layers}annotations={annotations}+ cameraBookmarks={cameraBookmarks}layerClasses={layerClasses}layerOrder={layerOrder}layerBlending={layerBlending}@@ -261,6 +263,7 @@ export default function SidePanelFactory(visStateActions={visStateActions}mapLegendActive={Boolean(uiState.mapControls?.mapLegend?.active)}mapInfo={mapInfo}+ cameraBookmarksEnabled={uiState.mapControls?.cameraBookmarks?.show === true}mapInfoShow={uiState.mapControls?.mapInfo?.show !== false}mapInfoActive={uiState.mapControls?.mapInfo?.active !== false}panelMetadata={currentPanel}diff --git a/src/components/src/side-panel/interaction-manager.tsx b/src/components/src/side-panel/interaction-manager.tsxindex e4bcc05d5..cda038c0b 100644--- a/src/components/src/side-panel/interaction-manager.tsx+++ b/src/components/src/side-panel/interaction-manager.tsx@@ -4,8 +4,16 @@import React from 'react';import {useIntl} from 'react-intl';-import {Annotation, InteractionConfig, LayerOrder, MapInfo, MapState} from '@kepler.gl/types';-import {UIStateActions, VisStateActions} from '@kepler.gl/actions';+import {+ Annotation,+ CameraBookmark,+ InteractionConfig,+ LayerOrder,+ MapInfo,+ MapState+} from '@kepler.gl/types';+import {MapStateActions, UIStateActions, VisStateActions} from '@kepler.gl/actions';+import CameraBookmarks from './interaction-panel/camera-bookmarks';import {Datasets} from '@kepler.gl/table';import {Layer} from '@kepler.gl/layers';@@ -46,6 +54,9 @@ type InteractionManagerProps = {mapInfoShow?: boolean;mapInfoActive?: boolean;mapState?: MapState;+ cameraBookmarks?: CameraBookmark[];+ cameraBookmarksEnabled?: boolean;+ mapStateActions?: typeof MapStateActions;actionIcons?: {settings?: PanelHeaderActionIcon;};@@ -83,6 +94,9 @@ function InteractionManagerFactory(mapInfoShow,mapInfoActive,mapState,+ cameraBookmarks,+ cameraBookmarksEnabled,+ mapStateActions,actionIcons,interactionConfigIcons}) => {@@ -159,6 +173,14 @@ function InteractionManagerFactory();})}{interactionConfig.geocoder ? null : mapInfoPanel}+ <CameraBookmarks+ bookmarks={cameraBookmarks}+ enabled={cameraBookmarksEnabled}+ uiStateActions={uiStateActions}+ mapState={mapState}+ mapStateActions={mapStateActions}+ visStateActions={visStateActions}+ /></div>);};diff --git a/src/components/src/side-panel/interaction-panel/camera-bookmarks.spec.tsx b/src/components/src/side-panel/interaction-panel/camera-bookmarks.spec.tsxnew file mode 100644index 000000000..2821d38f6--- /dev/null+++ b/src/components/src/side-panel/interaction-panel/camera-bookmarks.spec.tsx@@ -0,0 +1,647 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useState} from 'react';+import {fireEvent, screen, waitFor, within} from '@testing-library/react';+import copy from 'copy-to-clipboard';+import {IntlProvider} from 'react-intl';+import {MapStateActions, VisStateActions, UIStateActions} from '@kepler.gl/actions';+import {INITIAL_MAP_STATE} from '@kepler.gl/reducers';+import {CameraBookmark} from '@kepler.gl/types';+import {theme} from '@kepler.gl/styles';+import {renderWithTheme, IntlWrapper} from 'test/helpers/component-jest-utils';+import CameraBookmarks from './camera-bookmarks';+import {MapViewStateContext} from '../../map-view-state-context';+import ZoomOpacityConfigFactory from './zoom-opacity-config';+import PanelHeaderActionFactory from '../panel-header-action';++jest.mock('copy-to-clipboard', () => jest.fn(() => true));+const camera = {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45};+const initial = [{id: 'first', name: 'Home', camera}];++function setup(+ bookmarks: CameraBookmark[] = [],+ mapState = {...INITIAL_MAP_STATE, ...camera},+ liveCamera?: typeof camera+) {+ const updateMap = jest.fn();+ const commit = jest.fn();+ const toggle = jest.fn();+ function Harness() {+ const [items, setItems] = useState(bookmarks);+ const [enabled, setEnabled] = useState(true);+ return (+ <CameraBookmarks+ bookmarks={items}+ enabled={enabled}+ uiStateActions={{+ ...UIStateActions,+ setMapControlVisibility: (id, show) => {+ toggle(id, show);+ setEnabled(show);+ return UIStateActions.setMapControlVisibility(id, show);+ }+ }}+ mapState={mapState}+ mapStateActions={{...MapStateActions, updateMap}}+ visStateActions={{+ ...VisStateActions,+ setCameraBookmarks: Object.assign((value: CameraBookmark[]) => {+ commit(value);+ setItems(value);+ return VisStateActions.setCameraBookmarks(value);+ }, VisStateActions.setCameraBookmarks)+ }}+ />+ );+ }+ renderWithTheme(+ <IntlWrapper>+ <MapViewStateContext.Provider+ value={{+ getInternalViewState: () => liveCamera || mapState,+ setInternalViewState: jest.fn()+ }}+ >+ <Harness />+ </MapViewStateContext.Provider>+ </IntlWrapper>+ );+ fireEvent.click(screen.getByRole('button', {name: 'Bookmarks'}));+ return {commit, updateMap, toggle};+}++test('captures, renames and deletes a bookmark without datasets', () => {+ const {commit} = setup();+ fireEvent.click(screen.getByRole('button', {name: 'Add Bookmark'}));+ expect(commit.mock.lastCall[0][0]).toEqual({id: expect.any(String), name: 'Bookmark 1', camera});+ fireEvent.change(screen.getByRole('textbox', {name: 'Bookmark name 1'}), {+ target: {value: 'My view'}+ });+ expect(commit.mock.lastCall[0][0].name).toBe('My view');+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));+ expect(commit.mock.lastCall[0]).toEqual([]);+});++test('updates the saved view and navigates with bearing and pitch', () => {+ const current = {...INITIAL_MAP_STATE, ...camera, zoom: 9, bearing: 80, pitch: 60};+ const {commit, updateMap} = setup(initial, current);+ fireEvent.click(screen.getByRole('button', {name: 'Update view'}));+ expect(commit.mock.lastCall[0][0].camera).toEqual({...camera, zoom: 9, bearing: 80, pitch: 60});+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));+ expect(updateMap).toHaveBeenCalledWith(+ expect.objectContaining({+ zoom: 9,+ bearing: 80,+ pitch: 60,+ transitionDuration: 1000,+ transitionInterpolator: expect.any(Object)+ })+ );+});++test('uses a short hint and matches Add controller sizing without forcing a single row', () => {+ setup();+ const ZoomOpacityConfig = ZoomOpacityConfigFactory(PanelHeaderActionFactory());+ const {container} = renderWithTheme(+ <IntlWrapper>+ <ZoomOpacityConfig layers={[]} visStateActions={VisStateActions} />+ </IntlWrapper>+ );+ fireEvent.click(container.querySelector('.interaction-zoom-opacity__header') as Element);+ const hint = screen.getByText('Save views to revisit later.');+ const add = screen.getByRole('button', {name: 'Add Bookmark'});+ const addController = screen.getByRole('button', {name: 'Add controller'});+ expect(hint.nextElementSibling).toBe(add);+ expect(hint).toHaveStyle({fontSize: '11px', lineHeight: '1.4', marginBottom: '12px'});+ expect(getComputedStyle(hint).whiteSpace).not.toBe('nowrap');+ for (const property of [+ 'background-color',+ 'color',+ 'font-size',+ 'font-family',+ 'font-weight',+ 'line-height',+ 'padding',+ 'border-radius'+ ]) {+ expect(getComputedStyle(add).getPropertyValue(property)).toBe(+ getComputedStyle(addController).getPropertyValue(property)+ );+ }+ expect(add).toHaveStyle({+ display: 'inline-flex',+ padding: '6px 9px',+ fontSize: '10px',+ lineHeight: '14px',+ maxWidth: '100%',+ boxSizing: 'border-box',+ whiteSpace: 'normal'+ });+ const plus = add.querySelector('.data-ex-icons-add');+ expect(plus).toHaveAttribute('height', '12px');+ expect(plus).toHaveAttribute('aria-hidden', 'true');+ expect(plus).toHaveStyle({marginRight: '6px', flexShrink: '0'});+ expect(add.querySelector('span')).toHaveStyle({minWidth: '0', overflowWrap: 'anywhere'});+ add.focus();+ expect(add).toHaveFocus();+ expect(add).toHaveAttribute('type', 'button');+});++test('keeps the hint and add action localized with wrapping for longer labels', () => {+ const commit = jest.fn();+ const label = 'Ajouter un signet pour cette vue';+ const hint = 'Enregistrez des vues pour les retrouver plus tard.';+ renderWithTheme(+ <IntlProvider+ locale="fr"+ messages={{'camera.captureBookmark': label, 'camera.bookmarksHint': hint}}+ >+ <CameraBookmarks+ mapState={{...INITIAL_MAP_STATE, ...camera}}+ visStateActions={{+ ...VisStateActions,+ setCameraBookmarks: Object.assign(commit, VisStateActions.setCameraBookmarks)+ }}+ />+ </IntlProvider>+ );+ fireEvent.click(screen.getByRole('button', {name: 'Bookmarks'}));+ expect(screen.getByText(hint)).toBeInTheDocument();+ const add = screen.getByRole('button', {name: label});+ expect(add).toHaveStyle({whiteSpace: 'normal', maxWidth: '100%'});+ fireEvent.click(add);+ expect(commit).toHaveBeenCalledWith([expect.objectContaining({camera})]);+});++test('keeps unsupported split-map editing unavailable', () => {+ setup(initial, {...INITIAL_MAP_STATE, isSplit: true});+ expect(screen.getByText('Use a single 2D or 3D map to edit camera views.')).toBeInTheDocument();+ expect(screen.queryByRole('button', {name: 'Add Bookmark'})).toBeNull();+});++test('captures and updates the live camera when Redux has not caught up', () => {+ const liveCamera = {...camera, longitude: 80, zoom: 12};+ const {commit} = setup(initial, {...INITIAL_MAP_STATE, ...camera}, liveCamera);+ // Change the live view after rendering: capture must read at click time.+ liveCamera.zoom = 13;+ fireEvent.click(screen.getByRole('button', {name: 'Update view'}));+ expect(commit.mock.lastCall[0][0].camera).toEqual(liveCamera);+ fireEvent.click(screen.getByRole('button', {name: 'Add Bookmark'}));+ expect(commit.mock.lastCall[0][1].camera).toEqual(liveCamera);+});++test('enabling is independent of collapse and preserves saved bookmarks', () => {+ const {commit, toggle, updateMap} = setup(initial);+ const header = screen.getByRole('button', {name: 'Bookmarks'});+ expect(header).toHaveAttribute('aria-expanded', 'true');+ fireEvent.click(screen.getByRole('checkbox', {name: 'Enable bookmarks'}));+ expect(toggle).toHaveBeenLastCalledWith('cameraBookmarks', false);+ expect(header).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByRole('button', {name: 'Go to'})).toBeDisabled();+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));+ expect(updateMap).not.toHaveBeenCalled();+ expect(commit).not.toHaveBeenCalled();+ fireEvent.click(header);+ fireEvent.click(screen.getByRole('checkbox', {name: 'Enable bookmarks'}));+ expect(header).toHaveAttribute('aria-expanded', 'false');+ expect(screen.getByRole('checkbox', {name: 'Enable bookmarks'})).toBeChecked();+ fireEvent.click(header);+ expect(screen.getByRole('textbox', {name: 'Bookmark name 1'})).toHaveValue('Home');+});++test('icon actions retain accessible names, tooltips, focus and fixed row space', () => {+ setup(initial);+ expect(screen.queryByRole('button', {name: 'Up'})).toBeNull();+ expect(screen.queryByRole('button', {name: 'Down'})).toBeNull();+ for (const name of ['Go to', 'Copy coordinates', 'Update view', 'Delete']) {+ const button = screen.getByRole('button', {name});+ expect(button).toHaveAttribute('title', name);+ expect(button.querySelector('.panel--header__action__component')).not.toBeNull();+ expect(button.querySelector('.__react_component_tooltip')).toHaveTextContent(name);+ expect(button.querySelector('svg')).not.toBeNull();+ }+ const goTo = screen.getByRole('button', {name: 'Go to'});+ goTo.focus();+ expect(goTo).toHaveFocus();+ expect(goTo.closest('.bookmark-actions')).toBeInTheDocument();+});++test('copies each saved view with pointer or keyboard focus without navigating or dragging', () => {+ measureRows();+ const saved = [+ {...initial[0], camera: {...camera, longitude: 10.12345678, latitude: 20.98765432}},+ pair[1]+ ];+ const {commit, updateMap} = setup(saved);+ const [homeCopy, workCopy] = screen.getAllByRole('button', {name: 'Copy coordinates'});+ fireEvent.pointerDown(homeCopy, {button: 0, clientX: 180, clientY: 18});+ fireEvent.pointerMove(document, {clientX: 180, clientY: 60});+ fireEvent.pointerUp(document);+ fireEvent.click(homeCopy);+ expect(copy).toHaveBeenLastCalledWith('20.987654, 10.123457');+ workCopy.focus();+ fireEvent.keyDown(workCopy, {key: ' ', code: 'Space'});+ fireEvent.keyUp(workCopy, {key: ' ', code: 'Space'});+ fireEvent.click(workCopy); // Native buttons activate on keyboard release in the browser.+ expect(copy).toHaveBeenLastCalledWith('20.000000, 40.000000');+ expect(workCopy).toHaveFocus();+ expect(screen.getByRole('status', {name: 'Copy coordinates'})).toBeEmptyDOMElement();+ expect(commit).not.toHaveBeenCalled();+ expect(updateMap).not.toHaveBeenCalled();+ for (const name of ['Home', 'Work']) {+ expect(screen.getByRole('button', {name: `Reorder bookmark: ${name}`})).not.toHaveAttribute(+ 'aria-pressed'+ );+ }+});++test('reports copy failure and silently clears it after a successful retry', () => {+ jest.mocked(copy).mockReturnValueOnce(false);+ setup(initial);+ fireEvent.click(screen.getByRole('button', {name: 'Copy coordinates'}));+ expect(screen.getByRole('status', {name: 'Copy coordinates'})).toHaveTextContent(+ 'Could not copy coordinates'+ );+ fireEvent.click(screen.getByRole('button', {name: 'Copy coordinates'}));+ expect(copy).toHaveBeenLastCalledWith('20.000000, 10.000000');+ expect(screen.getByRole('status', {name: 'Copy coordinates'})).toBeEmptyDOMElement();+});++test('does not offer copying invalid saved coordinates', () => {+ jest.mocked(copy).mockClear();+ setup([{...initial[0], camera: {...camera, longitude: NaN}}]);+ const button = screen.getByRole('button', {name: 'Copy coordinates'});+ expect(button).toBeDisabled();+ fireEvent.click(button);+ expect(copy).not.toHaveBeenCalled();+});++test('copy actions follow their own row hover and keyboard focus without sticky pointer focus', () => {+ const {commit, updateMap} = setup(pair);+ const [homeCopy, workCopy] = screen.getAllByRole('button', {name: 'Copy coordinates'});+ const homeRow = homeCopy.closest('.bookmark-row') as HTMLElement;+ const homeActions = homeCopy.closest('.bookmark-actions');+ const workActions = workCopy.closest('.bookmark-actions');+ const restoreStyles = emulatePointerStyles();+ try {+ expect(homeActions).toHaveStyle({opacity: '0', pointerEvents: 'none'});+ expect(workActions).toHaveStyle({opacity: '0', pointerEvents: 'none'});+ fireEvent.mouseEnter(homeRow);+ homeRow.setAttribute('data-test-hover', '');+ expect(homeActions).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ expect(workActions).toHaveStyle({opacity: '0', pointerEvents: 'none'});+ homeCopy.focus();+ homeRow.setAttribute('data-test-focus-within', '');+ fireEvent.click(homeCopy);+ fireEvent.mouseLeave(homeRow);+ homeRow.removeAttribute('data-test-hover');+ expect(homeCopy).toHaveFocus();+ expect(homeActions).toHaveStyle({opacity: '0', pointerEvents: 'none'});++ workCopy.focus();+ workCopy.setAttribute('data-test-focus-visible', '');+ expect(workCopy).toHaveStyle({outline: `2px solid ${theme.activeColor}`});+ expect(workActions).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ expect(homeActions).toHaveStyle({opacity: '0', pointerEvents: 'none'});+ fireEvent.click(workCopy);+ expect(copy).toHaveBeenLastCalledWith('20.000000, 40.000000');+ expect(commit).not.toHaveBeenCalled();+ expect(updateMap).not.toHaveBeenCalled();+ } finally {+ restoreStyles();+ }+});++test('multiple maps have independent switch and content identifiers', () => {+ const toggles = [jest.fn(), jest.fn()];+ renderWithTheme(+ <IntlWrapper>+ {toggles.map((toggle, index) => (+ <CameraBookmarks+ key={index}+ bookmarks={initial}+ mapState={INITIAL_MAP_STATE}+ visStateActions={VisStateActions}+ uiStateActions={{...UIStateActions, setMapControlVisibility: toggle}}+ />+ ))}+ </IntlWrapper>+ );+ const switches = screen.getAllByRole('checkbox', {name: 'Enable bookmarks'});+ expect(switches[0].id).not.toBe(switches[1].id);+ switches.forEach(toggle => expect(toggle).not.toBeChecked());+ fireEvent.click(switches[1].closest('label')!);+ expect(toggles[0]).not.toHaveBeenCalled();+ expect(toggles[1]).toHaveBeenCalledWith('cameraBookmarks', true);+ const headers = screen.getAllByRole('button', {name: 'Bookmarks'});+ headers.forEach(header => fireEvent.click(header));+ expect(headers[0].getAttribute('aria-controls')).not.toBe(+ headers[1].getAttribute('aria-controls')+ );+ headers.forEach(header =>+ expect(document.getElementById(header.getAttribute('aria-controls')!)).toBeInTheDocument()+ );+});++const pointerEventDescriptor = Object.getOwnPropertyDescriptor(window, 'PointerEvent');+beforeAll(() => {+ class TestPointerEvent extends MouseEvent {+ pointerId = 1;+ isPrimary = true;+ pointerType = 'mouse';+ }+ Object.defineProperty(window, 'PointerEvent', {configurable: true, value: TestPointerEvent});+});+afterAll(() => {+ if (pointerEventDescriptor) Object.defineProperty(window, 'PointerEvent', pointerEventDescriptor);+ else Reflect.deleteProperty(window, 'PointerEvent');+});+afterEach(() => jest.restoreAllMocks());++function measureRows() {+ const original = HTMLElement.prototype.getBoundingClientRect;+ jest+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')+ .mockImplementation(function (this: HTMLElement) {+ if (!this.classList.contains('bookmark-row')) return original.call(this);+ const rows = Array.from(this.parentElement?.querySelectorAll('.bookmark-row') || []);+ const top = rows.indexOf(this) * 42;+ return {+ x: 0,+ y: top,+ top,+ left: 0,+ right: 280,+ bottom: top + 36,+ width: 280,+ height: 36,+ toJSON: () => ({})+ };+ });+}++const pair = [...initial, {id: 'second', name: 'Work', camera: {...camera, longitude: 40}}];++test('uses the existing Settings action and keeps header controls independent', () => {+ const {toggle} = setup(initial);+ const expand = screen.getByRole('button', {name: 'Bookmarks'});+ expect(expand.querySelector('.panel--header__action .data-ex-icons-settings')).not.toBeNull();+ expect(expand.querySelector('.data-ex-icons-arrow_up, .data-ex-icons-arrow_down')).toBeNull();+ expand.focus();+ expect(expand).toHaveFocus();+ fireEvent.click(expand);+ expect(expand).toHaveAttribute('aria-expanded', 'false');+ fireEvent.click(screen.getByText('Bookmarks', {selector: '.side-panel-panel__header__title'}));+ expect(expand).toHaveAttribute('aria-expanded', 'true');+ expect(toggle).not.toHaveBeenCalled();+ expect(+ screen.getByRole('textbox', {name: 'Bookmark name 1'}).closest('.bookmark-row')+ ).toHaveStyle({+ height: '36px'+ });+});++// JSDOM does not evaluate pointer media queries or pointer/focus pseudo-classes reliably.+// Enable the emitted fine-pointer rules and model states with equal-specificity attributes.+function emulatePointerStyles() {+ const pointerStyles = document.createElement('style');+ pointerStyles.textContent = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter((rule): rule is CSSMediaRule => rule.type === CSSRule.MEDIA_RULE)+ .filter(+ rule =>+ /hover\s*:\s*hover/.test(rule.conditionText) &&+ /pointer\s*:\s*fine/.test(rule.conditionText)+ )+ .flatMap(rule => Array.from(rule.cssRules))+ .map(rule => rule.cssText)+ .join('\n');+ document.head.appendChild(pointerStyles);+ const stateRules = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter((rule): rule is CSSStyleRule => rule.type === CSSRule.STYLE_RULE)+ .filter(rule => /:hover|:focus-visible|:focus-within/.test(rule.selectorText))+ .map(rule => ({rule, selector: rule.selectorText}));+ stateRules.forEach(({rule, selector}) => {+ rule.selectorText = selector+ .replace(/:hover/g, '[data-test-hover]')+ .replace(/:focus-visible/g, '[data-test-focus-visible]')+ .replace(/:focus-within/g, '[data-test-focus-within]');+ });+ return () => {+ stateRules.forEach(({rule, selector}) => {+ rule.selectorText = selector;+ });+ pointerStyles.remove();+ };+}++test('shows the toggle outline only for keyboard focus in either enabled state', () => {+ const {toggle} = setup(initial);+ const checkbox = screen.getByRole('checkbox', {name: 'Enable bookmarks'}) as HTMLInputElement;+ const wrapper = checkbox.closest('.kg-checkbox') as HTMLElement;+ const header = screen.getByRole('button', {name: 'Bookmarks'});+ for (const enabled of [false, true]) {+ fireEvent.click(checkbox);+ checkbox.focus();+ const restoreStyles = emulatePointerStyles();+ try {+ wrapper.setAttribute('data-test-focus-within', '');+ expect(checkbox.checked).toBe(enabled);+ expect(toggle).toHaveBeenLastCalledWith('cameraBookmarks', enabled);+ expect(checkbox).toHaveFocus();+ expect(wrapper).not.toHaveStyle({outline: `2px solid ${theme.activeColor}`});+ expect(wrapper).toHaveStyle({marginLeft: '0', marginRight: `-${theme.switchLabelMargin}px`});+ expect(wrapper.parentElement).toHaveStyle({gap: '24px', marginRight: '-10px'});+ expect(header).toHaveAttribute('aria-expanded', 'true');++ checkbox.setAttribute('data-test-focus-visible', '');+ expect(wrapper).toHaveStyle({outline: `2px solid ${theme.activeColor}`});+ checkbox.removeAttribute('data-test-focus-visible');+ } finally {+ restoreStyles();+ }+ }+ fireEvent.click(header);+ expect(header).toHaveAttribute('aria-expanded', 'false');+ expect(checkbox).toBeChecked();+});++test('reveals the light layer-style handle only on header hover or keyboard focus', () => {+ setup(initial);+ const handle = screen.getByRole('button', {name: 'Reorder bookmark: Home'});+ const row = handle.closest('.bookmark-row') as HTMLElement;+ const restoreStyles = emulatePointerStyles();+ row.setAttribute('data-test-hover', '');+ row.removeAttribute('data-test-hover');+ try {+ expect(handle).toHaveStyle({opacity: '0'});+ // Like Layer headers, the normal handle color is inherited from its text container.+ expect(row).toHaveStyle({color: theme.textColor});+ row.setAttribute('data-test-hover', '');+ expect(handle).toHaveStyle({opacity: '1'});+ expect(row).toHaveStyle({color: theme.textColor});+ handle.setAttribute('data-test-hover', '');+ expect(handle).toHaveStyle({color: theme.textColorHl, cursor: 'move'});+ handle.removeAttribute('data-test-hover');+ row.removeAttribute('data-test-hover');+ expect(handle).toHaveStyle({opacity: '0'});+ handle.focus();+ handle.setAttribute('data-test-focus-visible', '');+ expect(handle).toHaveFocus();+ expect(handle).toHaveStyle({opacity: '1'});+ } finally {+ restoreStyles();+ }+});++test('keyboard drag reorders stable bookmark IDs and Escape cancels without saving', async () => {+ measureRows();+ const {commit} = setup(pair);+ const colors = pair.map(item => bookmarkRowColor(item.name));+ expect(colors[0]).not.toBe(colors[1]);+ const handle = screen.getByRole('button', {name: 'Reorder bookmark: Home'});+ handle.focus();+ fireEvent.keyDown(handle, {key: ' ', code: 'Space'});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.keyDown(document, {key: 'ArrowDown', code: 'ArrowDown'});+ fireEvent.keyDown(document, {key: ' ', code: 'Space'});+ await waitFor(() => expect(commit).toHaveBeenCalledWith([pair[1], pair[0]]));+ expect(screen.getByRole('textbox', {name: 'Bookmark name 1'})).toHaveValue('Work');+ expect(handle).toHaveFocus();+ expect(pair.map(item => bookmarkRowColor(item.name))).toEqual(colors);+ commit.mockClear();+ fireEvent.keyDown(handle, {key: ' ', code: 'Space'});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.keyDown(document, {key: 'ArrowUp', code: 'ArrowUp'});+ fireEvent.keyDown(document, {key: 'Escape', code: 'Escape'});+ expect(commit).not.toHaveBeenCalled();+ expect(screen.getByRole('textbox', {name: 'Bookmark name 1'})).toHaveValue('Work');+});++test('pointer dragging from the handle reorders and an outside drop leaves the order unchanged', async () => {+ measureRows();+ const {commit, updateMap} = setup(pair);+ const handle = screen.getByRole('button', {name: 'Reorder bookmark: Home'});+ fireEvent.pointerDown(handle, {button: 0, clientX: 10, clientY: 18});+ fireEvent.pointerMove(document, {clientX: 10, clientY: 24});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.pointerMove(document, {clientX: 10, clientY: 60});+ fireEvent.pointerUp(document, {clientX: 10, clientY: 60});+ await waitFor(() => expect(commit).toHaveBeenCalledWith([pair[1], pair[0]]));+ commit.mockClear();+ fireEvent.pointerDown(handle, {button: 0, clientX: 10, clientY: 60});+ fireEvent.pointerMove(document, {clientX: 10, clientY: 66});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.pointerMove(document, {clientX: 500, clientY: 500});+ fireEvent.pointerUp(document, {clientX: 500, clientY: 500});+ expect(commit).not.toHaveBeenCalled();+ expect(screen.getByRole('textbox', {name: 'Bookmark name 1'})).toHaveValue('Work');+ // Dnd-kit briefly suppresses the click after a drag; actions work once it releases capture.+ await waitFor(() => {+ fireEvent.click(screen.getAllByRole('button', {name: 'Go to'})[0]);+ expect(updateMap).toHaveBeenCalledTimes(1);+ });+});++test('hides actions after a pointer reorder and mouse leave while retaining keyboard access', async () => {+ measureRows();+ const {commit, updateMap} = setup(pair);+ const handle = screen.getByRole('button', {name: 'Reorder bookmark: Work'});+ const row = handle.closest('.bookmark-row') as HTMLElement;+ const actions = row.querySelector('.bookmark-actions');+ const restoreStyles = emulatePointerStyles();+ try {+ fireEvent.mouseEnter(row);+ row.setAttribute('data-test-hover', '');+ fireEvent.pointerDown(handle, {button: 0, clientX: 10, clientY: 60});+ // fireEvent does not perform the browser's native pointer-focus default action.+ handle.focus();+ row.setAttribute('data-test-focus-within', '');+ fireEvent.pointerMove(document, {clientX: 10, clientY: 54});+ await waitFor(() => expect(handle).toHaveAttribute('aria-pressed', 'true'));+ fireEvent.pointerMove(document, {clientX: 10, clientY: 18});+ fireEvent.pointerUp(document, {clientX: 10, clientY: 18});+ await waitFor(() => expect(commit).toHaveBeenCalledWith([pair[1], pair[0]]));+ expect(actions).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ fireEvent.mouseLeave(row);+ row.removeAttribute('data-test-hover');+ expect(handle).toHaveFocus();+ expect(handle).toHaveStyle({opacity: '0'});+ expect(actions).toHaveStyle({opacity: '0', pointerEvents: 'none'});++ handle.setAttribute('data-test-focus-visible', '');+ expect(handle).toHaveStyle({opacity: '1'});+ expect(actions).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ const goTo = within(row).getByRole('button', {name: 'Go to'});+ goTo.focus();+ handle.removeAttribute('data-test-focus-visible');+ goTo.setAttribute('data-test-focus-visible', '');+ expect(goTo).toHaveFocus();+ expect(actions).toHaveStyle({opacity: '1', pointerEvents: 'auto'});+ // Wait for dnd-kit's post-drag click suppression to release before the next test.+ await waitFor(() => {+ fireEvent.click(goTo);+ expect(updateMap).toHaveBeenCalledTimes(1);+ });+ } finally {+ restoreStyles();+ }+});++test('editing names and using action icons never activates dragging', () => {+ measureRows();+ const {commit, updateMap} = setup(pair);+ const name = screen.getByRole('textbox', {name: 'Bookmark name 1'});+ fireEvent.pointerDown(name, {button: 0, clientX: 50, clientY: 18});+ fireEvent.pointerMove(document, {clientX: 50, clientY: 60});+ fireEvent.pointerUp(document);+ fireEvent.change(name, {target: {value: 'Renamed'}});+ expect(commit).toHaveBeenLastCalledWith([{...pair[0], name: 'Renamed'}, pair[1]]);+ commit.mockClear();+ const navigate = screen.getAllByRole('button', {name: 'Go to'})[0];+ fireEvent.pointerDown(navigate, {button: 0, clientX: 180, clientY: 18});+ fireEvent.pointerMove(document, {clientX: 180, clientY: 60});+ fireEvent.pointerUp(document);+ fireEvent.click(navigate);+ expect(updateMap).toHaveBeenCalledTimes(1);+ expect(commit).not.toHaveBeenCalled();+ expect(screen.getByRole('button', {name: 'Reorder bookmark: Renamed'})).not.toHaveAttribute(+ 'aria-pressed'+ );+ expect(screen.getByRole('textbox', {name: 'Bookmark name 1'})).toHaveValue('Renamed');+});++function bookmarkRowColor(name: string) {+ const row = screen+ .getByRole('button', {name: `Reorder bookmark: ${name}`})+ .closest('.bookmark-row');+ // JSDOM cannot compute the existing layer header's multiline rgb() border shorthand.+ // Inspect the emitted CSS rule to verify the same visible 3px color marker instead.+ const border = Array.from(document.styleSheets)+ .flatMap(sheet => Array.from(sheet.cssRules))+ .filter((rule): rule is CSSStyleRule => rule.type === CSSRule.STYLE_RULE)+ .filter(rule => row?.matches(rule.selectorText))+ .map(rule => rule.style.getPropertyValue('border-left'))+ .find(Boolean);+ expect(border).toMatch(/^3px solid rgb\(\s*\d+,\s*\d+,\s*\d+\s*\)$/);+ return border?.replace(/\s+/g, ' ');+}++test('bookmark colors survive edits and panel reopening without entering saved data', () => {+ const {commit} = setup(pair);+ const colors = pair.map(item => bookmarkRowColor(item.name));+ fireEvent.change(screen.getByRole('textbox', {name: 'Bookmark name 1'}), {+ target: {value: 'Renamed'}+ });+ expect(commit).toHaveBeenLastCalledWith([{...pair[0], name: 'Renamed'}, pair[1]]);+ expect(bookmarkRowColor('Renamed')).toBe(colors[0]);+ fireEvent.click(screen.getAllByRole('button', {name: 'Delete'})[1]);+ expect(commit).toHaveBeenLastCalledWith([{...pair[0], name: 'Renamed'}]);+ expect(bookmarkRowColor('Renamed')).toBe(colors[0]);+ const header = screen.getByRole('button', {name: 'Bookmarks'});+ fireEvent.click(header);+ fireEvent.click(header);+ expect(bookmarkRowColor('Renamed')).toBe(colors[0]);+});diff --git a/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsx b/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsxnew file mode 100644index 000000000..3e663b391--- /dev/null+++ b/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsx@@ -0,0 +1,390 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useContext, useId, useState} from 'react';+import styled from 'styled-components';+import {useIntl} from 'react-intl';+import copy from 'copy-to-clipboard';+import {CameraBookmark, MapState} from '@kepler.gl/types';+import {MapStateActions, VisStateActions, UIStateActions} from '@kepler.gl/actions';+import {generateHashId} from '@kepler.gl/common-utils';+import {getCameraSnapshot, hexToRgb} from '@kepler.gl/utils';+import {DataVizColors} from '@kepler.gl/constants';+import {Button, InlineInput, PanelContent, StyledPanelHeader} from '../../common/styled-components';+import {+ DndContext,+ PointerSensor,+ KeyboardSensor,+ closestCenter,+ pointerWithin,+ useSensor,+ useSensors+} from '@dnd-kit/core';+import {+ arrayMove,+ SortableContext,+ sortableKeyboardCoordinates,+ useSortable,+ verticalListSortingStrategy+} from '@dnd-kit/sortable';+import {CSS} from '@dnd-kit/utilities';+import {DND_MODIFIERS} from '../../common/dnd-layer-items';+import {DragHandle} from '../layer-panel/layer-panel-header';+import PanelHeaderActionFactory from '../panel-header-action';+import {LocationMarker, Replace, Delete, MapPin, VertDots, Copy, Add} from '../../common/icons';+import CameraPanelHeader, {CameraPanel, CameraIconButton} from './camera-panel-header';+import {cameraTransition} from '../../camera-navigation';+import {MapViewStateContext} from '../../map-view-state-context';+import {Hint} from './zoom-opacity-config';+import {formatMapCoordinate} from '../../map/coordinate-info';++const PanelHeaderAction = PanelHeaderActionFactory();+const bookmarkColors = Object.values(DataVizColors).map(hexToRgb);++// Derive a display-only color from the stable ID; never add it to saved bookmark data.+function bookmarkColor(id: string) {+ const hash = Array.from(id).reduce((value, char) => (value * 31 + char.charCodeAt(0)) >>> 0, 0);+ return bookmarkColors[hash % bookmarkColors.length];+}+const BookmarkList = styled.div`+ display: flex;+ flex-direction: column;+ gap: 6px;+ margin-top: 8px;+`;+const BookmarkRow = styled(StyledPanelHeader)`+ height: 36px;+ position: relative;+ padding: 0 8px 0 4px;+ gap: 4px;+ color: ${props => props.theme.textColor};+ &:hover {+ background-color: ${props => props.theme.panelBackgroundHover};+ .bookmark__drag-handle {+ opacity: 1;+ }+ }+ .bookmark__drag-handle {+ flex: 0 0 20px;+ touch-action: none;+ &:focus-visible {+ opacity: 1;+ outline: 2px solid ${props => props.theme.activeColor};+ }+ &[aria-pressed='true'] {+ cursor: grabbing;+ }+ }+ @media (hover: hover) and (pointer: fine) {+ .bookmark-actions {+ opacity: 0;+ pointer-events: none;+ }+ &:hover .bookmark-actions,+ &:has(:focus-visible) .bookmark-actions {+ opacity: 1;+ pointer-events: auto;+ }+ }+ input {+ flex: 1;+ min-width: 0;+ width: 0;+ margin: 0;+ }+`;+const Actions = styled.div`+ display: flex;+ flex: 0 0 auto;+ align-items: center;+ height: 24px;+ gap: 2px;+`;+const ActionButton = styled(CameraIconButton)`+ width: 20px;+ height: 24px;+`;+const AddBookmarkButton = styled(Button)`+ box-sizing: border-box;+ max-width: 100%;+ white-space: normal;+ svg {+ flex-shrink: 0;+ }+ span {+ min-width: 0;+ overflow-wrap: anywhere;+ }+`;++function SortableBookmark({+ bookmark,+ index,+ bookmarks,+ panelId,+ enabled,+ canNavigate,+ canCapture,+ onNavigate,+ onCopy,+ onUpdate,+ onChange+}: {+ bookmark: CameraBookmark;+ index: number;+ bookmarks: CameraBookmark[];+ panelId: string;+ enabled: boolean;+ canNavigate: boolean;+ canCapture: boolean;+ onNavigate: (bookmark: CameraBookmark) => void;+ onCopy: (coordinates: string | null) => void;+ onUpdate: (bookmark: CameraBookmark) => void;+ onChange: (bookmarks: CameraBookmark[]) => void;+}) {+ const intl = useIntl();+ const message = (key: string, fallback: string) =>+ intl.formatMessage({id: `camera.${key}`, defaultMessage: fallback});+ const {+ attributes,+ listeners,+ setNodeRef,+ setActivatorNodeRef,+ transform,+ transition,+ isDragging+ } = useSortable({id: bookmark.id});+ const reorderLabel = `${message('reorderBookmark', 'Reorder bookmark')}: ${bookmark.name}`;+ const coordinates = formatMapCoordinate([bookmark.camera.longitude, bookmark.camera.latitude]);+ const actions = [+ {+ key: 'goTo',+ label: message('goTo', 'Go to'),+ Icon: LocationMarker,+ disabled: !enabled || !canNavigate,+ onClick: () => onNavigate(bookmark)+ },+ {+ key: 'copyCoordinates',+ label: message('copyCoordinates', 'Copy coordinates'),+ Icon: Copy,+ disabled: !coordinates,+ onClick: () => onCopy(coordinates)+ },+ {+ key: 'updateView',+ label: message('updateView', 'Update view'),+ Icon: Replace,+ disabled: !canCapture,+ onClick: () => onUpdate(bookmark)+ },+ {+ key: 'delete',+ label: message('delete', 'Delete'),+ Icon: Delete,+ onClick: () => onChange(bookmarks.filter(item => item.id !== bookmark.id))+ }+ ];+ return (+ <BookmarkRow+ ref={setNodeRef}+ className="bookmark-row"+ data-bookmark-id={bookmark.id}+ labelRCGColorValues={bookmarkColor(bookmark.id)}+ style={{+ transform: CSS.Transform.toString(transform),+ transition,+ opacity: isDragging ? 0.5 : 1,+ zIndex: isDragging ? 1 : undefined+ }}+ >+ <DragHandle+ className="bookmark__drag-handle"+ listeners={{+ ...attributes,+ ...listeners,+ ref: setActivatorNodeRef,+ 'aria-label': reorderLabel,+ title: reorderLabel+ }}+ >+ <VertDots height="20px" aria-hidden="true" />+ </DragHandle>+ <InlineInput+ aria-label={`${message('bookmarkName', 'Bookmark name')} ${index + 1}`}+ value={bookmark.name}+ onChange={event =>+ onChange(+ bookmarks.map(item =>+ item.id === bookmark.id ? {...item, name: event.target.value} : item+ )+ )+ }+ />+ <Actions className="bookmark-actions">+ {actions.map(({key, label, Icon, disabled, onClick}) => (+ <ActionButton+ key={key}+ aria-label={label}+ title={label}+ type="button"+ disabled={disabled}+ onClick={onClick}+ >+ <PanelHeaderAction+ id={`${panelId}-${bookmark.id}-${key}`}+ tooltip={`camera.${key}`}+ flush+ disabled={disabled}+ IconComponent={Icon}+ />+ </ActionButton>+ ))}+ </Actions>+ </BookmarkRow>+ );+}++export type CameraBookmarksProps = {+ bookmarks?: CameraBookmark[];+ enabled?: boolean;+ uiStateActions?: typeof UIStateActions;+ mapState?: MapState;+ mapStateActions?: typeof MapStateActions;+ visStateActions: typeof VisStateActions;+};++export default function CameraBookmarks({+ bookmarks = [],+ enabled = false,+ uiStateActions,+ mapState,+ mapStateActions,+ visStateActions+}: CameraBookmarksProps) {+ const panelId = `camera-bookmarks-${useId()}`;+ const [open, setOpen] = useState(false);+ const [copyStatus, setCopyStatus] = useState('');+ const intl = useIntl();+ const message = (key: string, fallback: string) =>+ intl.formatMessage({id: `camera.${key}`, defaultMessage: fallback});+ const supported = mapState && !mapState.isSplit && !mapState.globe?.enabled;+ const {getInternalViewState} = useContext(MapViewStateContext);+ const readCamera = () => getCameraSnapshot(getInternalViewState()) || getCameraSnapshot(mapState);+ const commit = visStateActions.setCameraBookmarks;+ const sensors = useSensors(+ useSensor(PointerSensor, {activationConstraint: {distance: 4}}),+ useSensor(KeyboardSensor, {coordinateGetter: sortableKeyboardCoordinates})+ );++ return (+ <CameraPanel className="interaction-panel interaction-camera-bookmarks">+ <CameraPanelHeader+ id={panelId}+ title={message('bookmarks', 'Bookmarks')}+ enableLabel={message('enableBookmarks', 'Enable bookmarks')}+ Icon={MapPin}+ open={open}+ enabled={enabled}+ onToggleOpen={() => setOpen(!open)}+ onToggleEnabled={+ uiStateActions+ ? () => uiStateActions.setMapControlVisibility('cameraBookmarks', !enabled)+ : undefined+ }+ />+ {open && (+ <PanelContent id={`${panelId}-content`}>+ {!supported ? (+ <p>{message('singleMap', 'Use a single 2D or 3D map to edit camera views.')}</p>+ ) : (+ <>+ <Hint>{message('bookmarksHint', 'Save views to revisit later.')}</Hint>+ <AddBookmarkButton+ type="button"+ secondary+ small+ disabled={!readCamera()}+ onClick={() => {+ const camera = readCamera();+ if (camera)+ commit([+ ...bookmarks,+ {+ id: generateHashId(6),+ name: `${message('bookmark', 'Bookmark')} ${bookmarks.length + 1}`,+ camera+ }+ ]);+ }}+ >+ <Add height="12px" aria-hidden="true" />+ <span>{message('captureBookmark', 'Add Bookmark')}</span>+ </AddBookmarkButton>+ <DndContext+ id={panelId}+ sensors={sensors}+ modifiers={DND_MODIFIERS}+ collisionDetection={args =>+ args.pointerCoordinates ? pointerWithin(args) : closestCenter(args)+ }+ onDragEnd={({active, over}) => {+ if (!over || active.id === over.id) return;+ const from = bookmarks.findIndex(item => item.id === active.id);+ const to = bookmarks.findIndex(item => item.id === over.id);+ if (from >= 0 && to >= 0) commit(arrayMove(bookmarks, from, to));+ }}+ >+ <SortableContext+ items={bookmarks.map(bookmark => bookmark.id)}+ strategy={verticalListSortingStrategy}+ >+ <BookmarkList>+ {bookmarks.map((bookmark, index) => (+ <SortableBookmark+ key={bookmark.id}+ bookmark={bookmark}+ index={index}+ bookmarks={bookmarks}+ panelId={panelId}+ enabled={enabled}+ canNavigate={Boolean(mapStateActions)}+ canCapture={Boolean(readCamera())}+ onChange={commit}+ onNavigate={item =>+ mapStateActions?.updateMap(cameraTransition(item.camera))+ }+ onCopy={coordinates => {+ const copied = coordinates && copy(coordinates);+ setCopyStatus(+ copied ? '' : message('copyFailed', 'Could not copy coordinates')+ );+ }}+ onUpdate={item => {+ const camera = readCamera();+ if (camera)+ commit(+ bookmarks.map(saved =>+ saved.id === item.id ? {...saved, camera} : saved+ )+ );+ }}+ />+ ))}+ </BookmarkList>+ </SortableContext>+ </DndContext>+ <div+ role="status"+ aria-live="polite"+ aria-label={message('copyCoordinates', 'Copy coordinates')}+ >+ {copyStatus}+ </div>+ </>+ )}+ </PanelContent>+ )}+ </CameraPanel>+ );+}diff --git a/src/components/src/side-panel/interaction-panel/camera-panel-header.tsx b/src/components/src/side-panel/interaction-panel/camera-panel-header.tsxnew file mode 100644index 000000000..d0e485220--- /dev/null+++ b/src/components/src/side-panel/interaction-panel/camera-panel-header.tsx@@ -0,0 +1,110 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import styled from 'styled-components';+import {Settings} from '../../common/icons';+import Switch from '../../common/switch';+import PanelHeaderActionFactory from '../panel-header-action';+import {HeaderActions} from './map-info-config';+import {+ PanelHeaderContent,+ PanelHeaderTitle,+ StyledPanelHeader+} from '../../common/styled-components';++const PanelHeaderAction = PanelHeaderActionFactory();++export const CameraPanel = styled.section`+ padding-bottom: 6px;+`;++// Keep the existing panel action's layout and colors, with a keyboard-operable target.+export const CameraIconButton = styled.button`+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ cursor: pointer;+ &:focus-visible {+ outline: 2px solid ${props => props.theme.activeColor};+ }+ &:disabled {+ cursor: default;+ }+`;++const AccessibleHeaderActions = styled(HeaderActions)`+ .camera-toggle-label {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip-path: inset(50%);+ }+ .kg-checkbox:has(:focus-visible) {+ outline: 2px solid ${props => props.theme.activeColor};+ }+`;++export default function CameraPanelHeader({+ id,+ title,+ enableLabel,+ open,+ enabled,+ onToggleOpen,+ onToggleEnabled,+ Icon+}: {+ id: string;+ title: string;+ enableLabel: string;+ open: boolean;+ enabled: boolean;+ onToggleOpen: () => void;+ onToggleEnabled?: () => void;+ Icon: React.ElementType;+}) {+ return (+ <StyledPanelHeader className={open ? 'is-open' : undefined} onClick={onToggleOpen}>+ <PanelHeaderContent>+ <div className="icon">+ <Icon height="16px" aria-hidden="true" />+ </div>+ <div>+ <PanelHeaderTitle>{title}</PanelHeaderTitle>+ </div>+ </PanelHeaderContent>+ <AccessibleHeaderActions onClick={event => event.stopPropagation()}>+ <CameraIconButton+ type="button"+ aria-label={title}+ aria-expanded={open}+ aria-controls={`${id}-content`}+ onClick={onToggleOpen}+ >+ <PanelHeaderAction+ id={`${id}-config`}+ className={open ? 'is-open' : undefined}+ tooltip="tooltip.interactionSettings"+ active={open}+ flush+ IconComponent={Settings}+ />+ </CameraIconButton>+ <Switch+ id={`${id}-toggle`}+ secondary+ checked={enabled}+ disabled={!onToggleEnabled}+ label={<span className="camera-toggle-label">{enableLabel}</span>}+ onChange={onToggleEnabled}+ />+ </AccessibleHeaderActions>+ </StyledPanelHeader>+ );+}diff --git a/src/components/src/side-panel/interaction-panel/map-info-config.tsx b/src/components/src/side-panel/interaction-panel/map-info-config.tsxindex f42f0d3d9..6a32b3273 100644--- a/src/components/src/side-panel/interaction-panel/map-info-config.tsx+++ b/src/components/src/side-panel/interaction-panel/map-info-config.tsx@@ -30,7 +30,7 @@ const StyledMapInfoPanel = styled.div`padding-bottom: 6px;`;-const HeaderActions = styled.div`+export const HeaderActions = styled.div`display: flex;align-items: center;gap: 24px;diff --git a/src/components/src/side-panel/interaction-panel/zoom-opacity-config.tsx b/src/components/src/side-panel/interaction-panel/zoom-opacity-config.tsxindex 66e5b5d81..0f747781f 100644--- a/src/components/src/side-panel/interaction-panel/zoom-opacity-config.tsx+++ b/src/components/src/side-panel/interaction-panel/zoom-opacity-config.tsx@@ -27,7 +27,7 @@ import ZoomOpacitySlider from './zoom-opacity-slider';import ItemSelector from '../../common/item-selector/item-selector';import {ChickletButton, ChickletTag} from '../../common/item-selector/chickleted-input';import {ListItemProps} from '../../common/item-selector/dropdown-list';-import {AnnotationText, Delete, Settings, ZoomIn} from '../../common/icons';+import {Add, AnnotationText, Delete, Settings, ZoomIn} from '../../common/icons';import PanelHeaderActionFactory, {PanelHeaderActionIcon} from '../panel-header-action';import Switch from '../../common/switch';import {@@ -58,7 +58,7 @@ const HeaderActions = styled.div`}`;-const Hint = styled.div`+export const Hint = styled.div`color: ${props => props.theme.subtextColor};font-size: 11px;line-height: 1.4;@@ -375,6 +375,7 @@ function ZoomOpacityConfigFactory(className="interaction-zoom-opacity__add"onClick={onAddController}>+ <Add height="12px" aria-hidden="true" /><FormattedMessage id="interactions.fadeOnZoomAdd" /></Button>{controllers.map(controller => {diff --git a/src/components/src/types.ts b/src/components/src/types.tsindex 148ef788a..ec52524f2 100644--- a/src/components/src/types.ts+++ b/src/components/src/types.ts@@ -6,6 +6,7 @@ import {MapStyle} from '@kepler.gl/reducers';import {Layer, LayerClassesType} from '@kepler.gl/layers';import {Annotation,+ CameraBookmark,Filter,InteractionConfig,MapState,@@ -39,6 +40,7 @@ export type SidePanelProps = {overlayBlending?: string;layers: Layer[];annotations?: Annotation[];+ cameraBookmarks?: CameraBookmark[];layerClasses: LayerClassesType;layerOrder: LayerOrder;mapStyle: MapStyle;diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 0d659bc63..ea6d70080 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -1043,8 +1043,7 @@ ${'```'}legendHideInvisible: 'Hide hidden layers in legend',legendAllLayers: 'All Layers',fadeOnZoom: 'Fade on zoom',- fadeOnZoomHint:- 'Fade layers and annotations as the map zooms. Configure a zoom range to show them.',+ fadeOnZoomHint: 'Set a zoom range to fade layers and annotations.',fadeOnZoomAdd: 'Add controller',fadeOnZoomLayers: 'Layers and annotations',fadeOnZoomAppear: 'Appear',@@ -1053,6 +1052,24 @@ ${'```'}fadeOnZoomDisappear: 'Disappear',fadeOnZoomDelete: 'Remove controller'},+ camera: {+ enableBookmarks: 'Enable bookmarks',+ copyCoordinates: 'Copy coordinates',+ copiedCoordinates: 'Coordinates copied',+ copyFailed: 'Could not copy coordinates',+ bookmarks: 'Bookmarks',+ bookmark: 'Bookmark',+ bookmarkName: 'Bookmark name',+ reorderBookmark: 'Reorder bookmark',+ captureBookmark: 'Add Bookmark',+ bookmarksHint: 'Save views to revisit later.',+ singleMap: 'Use a single 2D or 3D map to edit camera views.',+ goTo: 'Go to',+ updateView: 'Update view',+ up: 'Up',+ down: 'Down',+ delete: 'Delete'+ },layerBlending: {title: 'Layer Blending',additive: 'additive',diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.tsindex b2073cc6f..0f2777965 100644--- a/src/reducers/src/ui-state-updaters.ts+++ b/src/reducers/src/ui-state-updaters.ts@@ -127,6 +127,13 @@ export const DEFAULT_MAP_CONTROLS: MapControls = {}),{} as MapControls),+ // Camera controls are UI preferences; saved camera snapshots remain independent.+ cameraBookmarks: {+ ...DEFAULT_MAP_CONTROLS_FEATURES,+ show: false,+ active: true,+ settings: {position: {x: 60, y: 20, anchorX: 'right', anchorY: 'top'}, contentHeight: -1}+ },// Open by default so a saved title shows on load. An empty map still hides the card.mapInfo: {...DEFAULT_MAP_CONTROLS_FEATURES,@@ -497,7 +504,10 @@ export const setMapControlVisibilityUpdater = (state: UiState,{payload: {panelId, show}}: UIStateActions.setMapControlVisibilityUpdaterAction): UiState => {- if (!state.mapControls?.[panelId]) {+ const mapControl =+ state.mapControls?.[panelId] ??+ (panelId === 'cameraBookmarks' ? DEFAULT_MAP_CONTROLS.cameraBookmarks : undefined);+ if (!mapControl) {return state;}@@ -506,7 +516,7 @@ export const setMapControlVisibilityUpdater = (mapControls: {...state.mapControls,[panelId]: {- ...state.mapControls[panelId],+ ...mapControl,show: Boolean(show)}}@@ -526,7 +536,10 @@ export const setMapControlSettingsUpdater = (state: UiState,{payload: {panelId, settings}}: UIStateActions.setMapControlSettingsUpdaterAction): UiState => {- const mapControl = state.mapControls?.[panelId] as MapControlMapLegend | undefined;+ const mapControl = (state.mapControls?.[panelId] ??+ (panelId === 'cameraBookmarks'+ ? DEFAULT_MAP_CONTROLS.cameraBookmarks+ : undefined)) as MapControlMapLegend | undefined;if (!mapControl) {return state;}diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.tsindex 01a9f9901..4a6c1d0b3 100644--- a/src/reducers/src/vis-state-merger.ts+++ b/src/reducers/src/vis-state-merger.ts@@ -7,6 +7,7 @@ import flattenDeep from 'es-toolkit/compat/flattenDeep';import deepmerge from 'deepmerge';import {arrayInsert,+ normalizeCameraBookmarks,combineSplitMapsByIndex,getInitialMapLayersForSplitMap,applyFiltersToDatasets,@@ -1490,6 +1491,16 @@ function getValueWithHighestOccurrence<T>(arr: T[]): T | null {}export const VIS_STATE_MERGERS: VisStateMergers<any> = [+ {+ prop: 'cameraBookmarks',+ merge: (state, bookmarks) => ({+ ...state,+ cameraBookmarks: normalizeCameraBookmarks([+ ...(state.cameraBookmarks || []),+ ...normalizeCameraBookmarks(bookmarks)+ ])+ })+ },{merge: mergeLayers,prop: 'layers',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 3f5b5dc97..4b246c381 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -60,6 +60,7 @@ import {// Utilsimport {FILTER_UPDATER_PROPS,+ normalizeCameraBookmarks,addNewLayersToSplitMap,snapToMarks,applyFilterFieldName,@@ -444,6 +445,9 @@ export const INITIAL_VIS_STATE: VisState = {charts: [],chartsToBeMerged: [],+ // camera bookmarks+ cameraBookmarks: [],+// annotationsannotations: [],annotationsToBeMerged: [],@@ -3405,6 +3409,11 @@ export const resetMapConfigUpdater = (state: VisState): VisState => ({initialState: state.initialState});+export const setCameraBookmarksUpdater = (+ state: VisState,+ action: ReturnType<typeof VisStateActions.setCameraBookmarks>+): VisState => ({...state, cameraBookmarks: normalizeCameraBookmarks(action.payload)});+/*** Propagate `visState` reducer with a new configuration. Current config will be override.* @memberof visStateUpdaters@@ -3426,7 +3435,9 @@ export const receiveMapConfigUpdater = (const {keepExistingConfig} = options;// reset config if keepExistingConfig is falsy- let mergedState = !keepExistingConfig ? resetMapConfigUpdater(state) : state;+ let mergedState = !keepExistingConfig+ ? {...resetMapConfigUpdater(state), cameraBookmarks: []}+ : state;for (const merger of state.mergers) {if (isValidMerger(merger) && hasPropsToMerge(config.visState, merger.prop)) {mergedState = merger.merge(@@ -7208,7 +7219,8 @@ export function replaceDatasetDepsInState<T extends VisState>(let replacedState = accuState;savedProps.forEach((propValue, i) => {- if (propValue == null) {+ // Camera snapshots never reference datasets, even when a dataset ID is "id".+ if (propValue == null || props[i] === 'cameraBookmarks') {return;}const mergerOptions = {diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.tsindex f016ab5c1..e667dc9e1 100644--- a/src/reducers/src/vis-state.ts+++ b/src/reducers/src/vis-state.ts@@ -10,6 +10,7 @@ import * as visStateUpdaters from './vis-state-updaters';* It is used to generate documentation*/const actionHandler = {+ [ActionTypes.SET_CAMERA_BOOKMARKS]: visStateUpdaters.setCameraBookmarksUpdater,[ActionTypes.ADD_FILTER]: visStateUpdaters.addFilterUpdater,[ActionTypes.CREATE_OR_UPDATE_FILTER]: visStateUpdaters.createOrUpdateFilterUpdater,diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.tsindex 52a50e013..4d48bee17 100644--- a/src/schemas/src/vis-state-schema.ts+++ b/src/schemas/src/vis-state-schema.ts@@ -7,6 +7,7 @@ import {LAYER_VIS_CONFIGS, FILTER_VIEW_TYPES} from '@kepler.gl/constants';import {migrateLegacyScenegraphVisConfig} from '@kepler.gl/layers';import {colorRangeBackwardCompatibility,+ normalizeCameraBookmarks,isFilterValidToSave,findById,isPlainObject@@ -16,6 +17,7 @@ import Schema from './schema';import cloneDeep from 'es-toolkit/compat/cloneDeep';import {AddDataToMapOptions,+ CameraBookmark,AnimationConfig,Editor,FileLoading,@@ -59,6 +61,7 @@ export type modifiedType = {};export interface VisState {+ cameraBookmarks: CameraBookmark[];mapInfo: MapInfo;layers: Layer[];layerData: any[];@@ -1051,7 +1054,21 @@ export const propertiesV0 = {overlayBlending: null};+class CameraBookmarksSchema extends Schema {+ key = 'cameraBookmarks';++ save(value: unknown) {+ const bookmarks = normalizeCameraBookmarks(value);+ return bookmarks.length ? {[this.key]: bookmarks} : {};+ }++ load(value: unknown) {+ return {[this.key]: normalizeCameraBookmarks(value)};+ }+}+export const propertiesV1 = {+ cameraBookmarks: new CameraBookmarksSchema(),filters: new FilterSchemaV0({version: VERSIONS.v1,properties: filterPropsV1diff --git a/src/types/camera.d.ts b/src/types/camera.d.tsnew file mode 100644index 000000000..f5505fc9a--- /dev/null+++ b/src/types/camera.d.ts@@ -0,0 +1,17 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++/** A saved Mercator view, independent of viewport size and animation state. */+export type CameraSnapshot = {+ longitude: number;+ latitude: number;+ zoom: number;+ bearing: number;+ pitch: number;+};++export type CameraBookmark = {+ id: string;+ name: string;+ camera: CameraSnapshot;+};diff --git a/src/types/index.d.ts b/src/types/index.d.tsindex 5349a28a1..3318e11a1 100644--- a/src/types/index.d.ts+++ b/src/types/index.d.ts@@ -11,5 +11,6 @@ export * from './effects';export * from './charts';export * from './annotations';export * from './datasets';+export * from './camera';export * as StacTypes from './stac';diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.tsindex 14b25da1f..dcef6407d 100644--- a/src/types/schemas.d.ts+++ b/src/types/schemas.d.ts@@ -7,6 +7,7 @@ import {Filter, InteractionConfig, AnimationConfig, SplitMap, Feature} from './rimport {LayerTextLabel} from './layers';import {ChartConfig} from './charts';+import {CameraBookmark} from './camera';export type SavedFilter = {dataId: Filter['dataId'];@@ -116,6 +117,7 @@ export type SavedEditor = {};export type SavedVisState = {+ cameraBookmarks?: CameraBookmark[];filters: SavedFilter[];layers: SavedLayer[];effects: SavedEffect[];@@ -133,6 +135,7 @@ export type SavedVisState = {// Min saved config can be passed to addDataToMapexport type MinSavedVisStateV1 = {+ cameraBookmarks?: CameraBookmark[];filters?: MinSavedFilter[];layers?: MinSavedLayer[];effects?: SavedEffect[];@@ -146,6 +149,7 @@ export type MinSavedVisStateV1 = {};export type ParsedVisState = {+ cameraBookmarks?: CameraBookmark[];layers?: ParsedLayer[];effects?: ParsedEffect[];charts?: ChartConfig[];diff --git a/src/utils/src/camera-utils.spec.ts b/src/utils/src/camera-utils.spec.tsnew file mode 100644index 000000000..e05d861ae--- /dev/null+++ b/src/utils/src/camera-utils.spec.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {getCameraSnapshot, normalizeCameraBookmarks} from './camera-utils';++const camera = {longitude: 179, latitude: 40, zoom: 4, bearing: 350, pitch: 45};++describe('camera bookmarks', () => {+ test('copies the five camera fields without retaining viewport or transition state', () => {+ const snapshot = getCameraSnapshot({...camera, width: 800, transitionDuration: 1000});+ expect(snapshot).toEqual(camera);+ expect(snapshot).not.toBe(camera);+ });++ test.each([+ null,+ {},+ {...camera, zoom: NaN},+ {...camera, longitude: Infinity},+ {...camera, latitude: 91},+ {...camera, pitch: -1},+ {...camera, pitch: 91}+ ])('rejects invalid cameras: %p', value => expect(getCameraSnapshot(value)).toBeNull());++ test('normalizes missing input, invalid entries and duplicate IDs without changing order', () => {+ expect(normalizeCameraBookmarks(undefined)).toEqual([]);+ expect(normalizeCameraBookmarks({})).toEqual([]);+ const first = {id: 'one', name: 'First', camera};+ expect(+ normalizeCameraBookmarks([+ null,+ {id: 'invalid', name: 'Bad', camera: {}},+ first,+ {...first, name: 'Duplicate'},+ {id: 'two', name: 'Second', camera},+ {...first, id: ''},+ {...first, name: 42}+ ])+ ).toEqual([first, {id: 'two', name: 'Second', camera}]);+ });+});diff --git a/src/utils/src/camera-utils.ts b/src/utils/src/camera-utils.tsnew file mode 100644index 000000000..66ae0f8c8--- /dev/null+++ b/src/utils/src/camera-utils.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {CameraBookmark, CameraSnapshot} from '@kepler.gl/types';++/** Copy only the saved camera fields; never retain transitions or viewport dimensions. */+export function getCameraSnapshot(value: unknown): CameraSnapshot | null {+ if (!value || typeof value !== 'object') return null;+ const {longitude, latitude, zoom, bearing, pitch} = value as CameraSnapshot;+ if (+ ![longitude, latitude, zoom, bearing, pitch].every(Number.isFinite) ||+ Math.abs(latitude) > 90 ||+ pitch < 0 ||+ pitch > 90+ ) {+ return null;+ }+ return {longitude, latitude, zoom, bearing, pitch};+}++/** Validate imported bookmarks, preserving order and the first occurrence of each ID. */+export function normalizeCameraBookmarks(value: unknown): CameraBookmark[] {+ if (!Array.isArray(value)) return [];+ const ids = new Set<string>();+ const bookmarks: CameraBookmark[] = [];+ for (const item of value) {+ if (+ !item ||+ typeof item.id !== 'string' ||+ !item.id.trim() ||+ typeof item.name !== 'string' ||+ ids.has(item.id)+ )+ continue;+ const camera = getCameraSnapshot(item.camera);+ if (!camera) continue;+ ids.add(item.id);+ bookmarks.push({id: item.id, name: item.name, camera});+ }+ return bookmarks;+}diff --git a/src/utils/src/index.ts b/src/utils/src/index.tsindex 68a31faec..5ce2308e3 100644--- a/src/utils/src/index.ts+++ b/src/utils/src/index.ts@@ -2,6 +2,7 @@// Copyright contributors to the kepler.gl project// UTILS+export {getCameraSnapshot, normalizeCameraBookmarks} from './camera-utils';export {colorMaybeToRGB,diff --git a/test/browser/components/hooks/use-legend-position.spec.js b/test/browser/components/hooks/use-legend-position.spec.jsindex cb78a2c11..f8c30af9b 100644--- a/test/browser/components/hooks/use-legend-position.spec.js+++ b/test/browser/components/hooks/use-legend-position.spec.js@@ -136,6 +136,55 @@ describe('useLegendPosition', () => {}});+ describe.each(['top', 'bottom'])('%s-edge minimum', edge => {+ test.each([+ ['48px', 48],+ ['100px', 100],+ ['auto', 100],+ ['0px', 100]+ ])('uses the panel CSS minimum %s with a safe fallback', (minHeight, expected) => {+ const onChangeSettings = jest.fn();+ const legendContent = setupResizeFixture({+ contentHeight: 150,+ legendRect: {top: 100, left: 20, bottom: 284, right: 210},+ rootRect: {top: 0, left: 0, bottom: 600, right: 800}+ });+ const content = legendContent.querySelector('.map-control__panel-content');+ content.style.minHeight = minHeight;+ const {result} = renderHook(() =>+ useLegendPosition({+ legendContentRef: {current: legendContent},+ isSidePanelShown: false,+ settings: {+ position: {x: 20, y: 100, anchorX: 'left', anchorY: 'top'},+ contentHeight: 150+ },+ onChangeSettings,+ theme: THEME+ })+ );+ act(() => {+ result.current.startResize();+ result.current.resize(edge === 'top' ? 500 : -500, edge);+ });+ expect(onChangeSettings).toHaveBeenLastCalledWith({+ contentHeight: expected,+ ...(edge === 'top'+ ? {position: {x: 20, y: 250 - expected, anchorX: 'left', anchorY: 'top'}}+ : {})+ });+ // A subsequent gesture reads the panel's current layout again.+ content.style.minHeight = '64px';+ act(() => {+ result.current.startResize();+ result.current.resize(edge === 'top' ? 500 : -500, edge);+ });+ expect(onChangeSettings).toHaveBeenLastCalledWith(+ expect.objectContaining({contentHeight: 64})+ );+ });+ });+test('top-edge resize grows a bottom-anchored legend without moving it', () => {const onChangeSettings = jest.fn();const legendContent = setupResizeFixture({diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.jsindex 551281078..592bcf284 100644--- a/test/node/reducers/composer-state-test.js+++ b/test/node/reducers/composer-state-test.js@@ -871,6 +871,85 @@ test('#composerStateReducer - replaceDataInMapUpdater: same dataId', t => {t.end();});+test('#composerStateReducer - dataset replacement preserves data-independent bookmarks', t => {+ const bookmarks = [+ {id: 'first', name: 'Home', camera: {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45}},+ {id: 'second', name: 'Away', camera: {longitude: -20, latitude: 30, zoom: 8, bearing: 0, pitch: 0}}+ ];+ for (const [dataId, replacementId] of [+ ['id', 'id'],+ ['id', 'replacement'],+ ['ordinary-dataset', 'id'],+ ['name', 'name'],+ ['camera', 'camera'],+ ['ordinary-dataset', 'ordinary-dataset']+ ]) {+ const data = {+ fields: [{name: 'value', type: 'integer', format: '', analyzerType: 'INT'}],+ rows: [[1]]+ };+ const dataset = new KeplerTable({info: {id: dataId, label: 'Original'}});+ dataset.importData({data});+ const initial = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;+ const state = {+ ...initial,+ visState: {...initial.visState, cameraBookmarks: bookmarks, datasets: {[dataId]: dataset}}+ };+ const next = replaceDataInMapUpdater(state, {+ payload: {+ datasetToReplaceId: dataId,+ datasetToUse: {+ info: {id: replacementId, label: 'Replacement'},+ data: {...data, rows: [[2], [3]]}+ },+ options: {centerMap: false}+ }+ });+ const result = {...next, visState: applyExistingDatasetTasks(visStateReducer, next.visState)};+ t.equal(+ result.visState.datasets[replacementId].dataContainer.numRows(),+ 2,+ `${dataId}: replaces rows`+ );+ t.deepEqual(result.visState.cameraBookmarks, bookmarks, `${dataId}: preserves every saved view`);+ t.deepEqual(+ KeplerGlSchema.getConfigToSave(result).config.visState.cameraBookmarks,+ bookmarks,+ `${dataId}: subsequent saves retain bookmarks`+ );+ }+ t.end();+});++test('#composerStateReducer - loading saved bookmarks does not opt in or reset UI visibility', t => {+ const initial = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;+ const bookmarks = [+ {id: 'home', name: 'Home', camera: {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45}}+ ];+ const config = KeplerGlSchema.getConfigToSave({+ ...initial,+ visState: {...initial.visState, cameraBookmarks: bookmarks}+ });+ const {cameraBookmarks, ...legacyControls} = initial.uiState.mapControls;+ for (const controls of [+ initial.uiState.mapControls,+ legacyControls,+ {...legacyControls, cameraBookmarks: {...cameraBookmarks, show: true}}+ ]) {+ const state = {...initial, uiState: {...initial.uiState, mapControls: controls}};+ const loaded = addDataToMapUpdater(state, {+ payload: {datasets: [], config, options: {centerMap: false}}+ });+ t.deepEqual(loaded.visState.cameraBookmarks, bookmarks, 'restores saved views');+ t.equal(+ loaded.uiState.mapControls.cameraBookmarks?.show === true,+ controls.cameraBookmarks?.show === true,+ 'loading views preserves explicit opt-in and leaves default/missing controls off'+ );+ }+ t.end();+});+test('#composerStateReducer - replaceDataInMapUpdater: replacing a dataset with no layers before the previous replace merges', t => {const noLayersId = 'dataset_without_layers';const state = keplerGlReducer({}, registerEntry({id: 'test'})).test;diff --git a/test/node/reducers/ui-state-test.js b/test/node/reducers/ui-state-test.jsindex 4d7e5aa3c..dc28479b4 100644--- a/test/node/reducers/ui-state-test.js+++ b/test/node/reducers/ui-state-test.js@@ -14,6 +14,8 @@ import {setExportVideoSetting,toggleMapControl,setMapControlVisibility,+ setMapControlSettings,+ receiveMapConfig,setExportSelectedDataset,setExportDataType,setExportFiltered,@@ -520,3 +522,90 @@ test('#uiStateReducer -> SET_EXPORT_VIDEO_SETTING', t => {t.end();});++test('#uiStateReducer -> bookmark visibility preserves navigation layout settings', t => {+ const state = reducer(INITIAL_UI_STATE, setMapControlVisibility('cameraBookmarks', false));+ t.equal(state.mapControls.cameraBookmarks.show, false, 'hides bookmark navigation');+ t.deepEqual(+ state.mapControls.cameraBookmarks.settings,+ INITIAL_UI_STATE.mapControls.cameraBookmarks.settings,+ 'keeps drag/resize settings'+ );+ t.deepEqual(+ state.mapControls.mapLegend,+ INITIAL_UI_STATE.mapControls.mapLegend,+ 'does not alter the layer legend'+ );+ const shown = reducer(state, setMapControlVisibility('cameraBookmarks', true));+ t.equal(shown.mapControls.cameraBookmarks.show, true, 'can show it again');+ t.end();+});++test('#uiStateReducer -> bookmarks default off and legacy controls can opt in', t => {+ const {cameraBookmarks, ...legacyControls} = INITIAL_UI_STATE.mapControls;+ t.equal(cameraBookmarks.show, false, 'default bookmark visibility is off');+ const initialStates = [+ reducer(undefined, {}),+ uiStateReducerFactory({mapControls: legacyControls})(undefined, {}),+ reducer(INITIAL_UI_STATE, keplerGlInit({initialUiState: {mapControls: legacyControls}}))+ ];+ for (const initial of initialStates) {+ t.equal(+ initial.mapControls.cameraBookmarks?.show === true,+ false,+ 'missing/default visibility is off'+ );+ for (const config of [{}, {uiState: {}}, {uiState: {mapControls: {}}}]) {+ const loaded = reducer(initial, receiveMapConfig(config));+ t.equal(loaded.mapControls.cameraBookmarks?.show === true, false, 'legacy load does not opt in');+ }+ const positioned = reducer(+ initial,+ setMapControlSettings('cameraBookmarks', {contentHeight: 80})+ );+ t.equal(+ positioned.mapControls.cameraBookmarks.show,+ false,+ 'settings alone do not enable bookmarks'+ );+ t.equal(+ positioned.mapControls.cameraBookmarks.settings.contentHeight,+ 80,+ 'legacy settings updates work'+ );+ const enabled = reducer(initial, setMapControlVisibility('cameraBookmarks', true));+ t.equal(enabled.mapControls.cameraBookmarks.show, true, 'legacy control can be enabled directly');+ const moved = reducer(enabled, setMapControlSettings('cameraBookmarks', {contentHeight: 90}));+ t.equal(moved.mapControls.cameraBookmarks.show, true, 'settings preserve explicit opt-in');+ const disabled = reducer(moved, setMapControlVisibility('cameraBookmarks', false));+ t.equal(disabled.mapControls.cameraBookmarks.show, false, 'can disable it again');+ t.equal(+ disabled.mapControls.cameraBookmarks.settings.contentHeight,+ 90,+ 'disable keeps layout settings'+ );+ t.deepEqual(disabled.mapControls.mapLegend, initial.mapControls.mapLegend, 'legend is unchanged');+ }+ t.end();+});++test('#uiStateReducer -> explicit bookmark opt-in survives initialization and legacy loads', t => {+ const mapControls = {+ ...INITIAL_UI_STATE.mapControls,+ cameraBookmarks: {...INITIAL_UI_STATE.mapControls.cameraBookmarks, show: true}+ };+ for (const initial of [+ uiStateReducerFactory({mapControls})(undefined, {}),+ reducer(INITIAL_UI_STATE, keplerGlInit({initialUiState: {mapControls}}))+ ]) {+ t.equal(initial.mapControls.cameraBookmarks.show, true, 'honors explicit enabled state');+ for (const config of [{}, {uiState: {}}, {uiState: {mapControls: {}}}]) {+ t.equal(+ reducer(initial, receiveMapConfig(config)).mapControls.cameraBookmarks.show,+ true,+ 'missing saved preference does not reset explicit opt-in'+ );+ }+ }+ t.end();+});diff --git a/test/node/reducers/vis-state-merger-test.js b/test/node/reducers/vis-state-merger-test.jsindex d468e4d72..c436479c9 100644--- a/test/node/reducers/vis-state-merger-test.js+++ b/test/node/reducers/vis-state-merger-test.js@@ -32,11 +32,60 @@ import {receiveMapConfig,addDataToMap,registerEntry,+ setCameraBookmarks,setLayerAnimationTimeConfig} from '@kepler.gl/actions';import {createDataContainer, findById} from '@kepler.gl/utils';+test('#visState camera bookmarks -> replace, merge, validate and reset', t => {+ const camera = {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45};+ const first = {id: 'first', name: 'First', camera};+ const second = {id: 'second', name: 'Second', camera};+ const base = visStateReducer(undefined, setCameraBookmarks([first]));+ camera.zoom = 99;+ t.equal(base.cameraBookmarks[0].camera.zoom, 6, 'owns the captured snapshot');+ const incoming = {+ visState: {cameraBookmarks: [{...first, name: 'Changed'}, second, second, null]}+ };+ const merged = visStateReducer(base, receiveMapConfig(incoming, {keepExistingConfig: true}));+ t.deepEqual(+ merged.cameraBookmarks.map(item => item.name),+ ['First', 'Second'],+ 'keeps existing IDs, appends unique new IDs'+ );+ const preserved = visStateReducer(+ merged,+ receiveMapConfig({visState: {}}, {keepExistingConfig: true})+ );+ t.deepEqual(+ preserved.cameraBookmarks,+ merged.cameraBookmarks,+ 'missing additive content preserves bookmarks'+ );+ const replaced = visStateReducer(base, receiveMapConfig({visState: {cameraBookmarks: [second]}}));+ t.deepEqual(replaced.cameraBookmarks, [second], 'normal load replaces bookmarks');+ const reset = visStateReducer(base, receiveMapConfig({visState: {}}));+ t.deepEqual(reset.cameraBookmarks, [], 'normal legacy load clears previous bookmarks');+ const seeded = {...base, initialState: {cameraBookmarks: [first]}};+ t.deepEqual(+ visStateReducer(seeded, receiveMapConfig({visState: {cameraBookmarks: [second]}})).cameraBookmarks,+ [second],+ 'normal load replaces host-provided initial bookmarks'+ );+ t.deepEqual(+ visStateReducer(seeded, receiveMapConfig({visState: {}})).cameraBookmarks,+ [],+ 'normal legacy load clears host-provided initial bookmarks'+ );+ t.deepEqual(+ visStateReducer(base, setCameraBookmarks([])).cameraBookmarks,+ [],+ 'supports deleting every bookmark'+ );+ t.end();+});+// fixturesimport {savedStateV0,diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.jsindex 01ccb9670..ce981a25d 100644--- a/test/node/schemas/vis-state-schema-test.js+++ b/test/node/schemas/vis-state-schema-test.js@@ -46,6 +46,44 @@ const expectedVisStateEntries = ['joins'];+test('#visStateSchema -> camera bookmarks are optional and persist only authored fields', t => {+ const camera = {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45};+ const bookmarks = [+ {id: 'second', name: 'Second', camera},+ {id: 'first', name: 'First', camera: {...camera, zoom: 8}}+ ];+ const state = cloneDeep(StateWFilesFiltersLayerColor);+ const empty = SchemaManager.getConfigToSave(state);+ t.notOk('cameraBookmarks' in empty.config.visState, 'omits unused bookmarks');+ t.notOk(+ 'cameraBookmarks' in SchemaManager.parseSavedConfig(empty).visState,+ 'old maps need no bookmarks'+ );+ state.visState.cameraBookmarks = bookmarks.map(bookmark => ({+ ...bookmark,+ selected: true,+ camera: {...bookmark.camera, width: 800, transitionDuration: 1000}+ }));+ const saved = SchemaManager.getConfigToSave(state);+ t.deepEqual(+ saved.config.visState.cameraBookmarks,+ bookmarks,+ 'saves names/order and only camera values'+ );+ t.deepEqual(+ SchemaManager.parseSavedConfig(saved).visState.cameraBookmarks,+ bookmarks,+ 'round trips'+ );+ saved.config.visState.cameraBookmarks.push(null, {id: 'invalid', camera: {}});+ t.deepEqual(+ SchemaManager.parseSavedConfig(saved).visState.cameraBookmarks,+ bookmarks,+ 'ignores invalid entries'+ );+ t.end();+});+test('#visStateSchema -> v1 -> save layers', t => {const initialState = cloneDeep(StateWFilesFiltersLayerColor);