Skip to content

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

feat(camera): add basic tour editor and playback (#3861)

Igor Dykhta2294135a450d
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index e3dc7cbd3..76af21e5b 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -236,6 +236,7 @@ export const sidePanelSelector = (props: KeplerGLProps, availableProviders, filt
layers: props.visState.layers,
annotations: props.visState.annotations,
cameraBookmarks: props.visState.cameraBookmarks,
+ cameraTour: props.visState.cameraTour,
layerOrder: props.visState.layerOrder,
layerClasses: props.visState.layerClasses,
interactionConfig: props.visState.interactionConfig,
diff --git a/src/components/src/side-panel.tsx b/src/components/src/side-panel.tsx
index 206afcabb..b31cbcbae 100644
--- a/src/components/src/side-panel.tsx
+++ b/src/components/src/side-panel.tsx
@@ -120,6 +120,7 @@ export default function SidePanelFactory(
layers,
annotations = [],
cameraBookmarks,
+ cameraTour,
layerBlending,
overlayBlending,
layerClasses,
@@ -245,6 +246,7 @@ export default function SidePanelFactory(
layers={layers}
annotations={annotations}
cameraBookmarks={cameraBookmarks}
+ cameraTour={cameraTour}
layerClasses={layerClasses}
layerOrder={layerOrder}
layerBlending={layerBlending}
@@ -263,6 +265,7 @@ export default function SidePanelFactory(
visStateActions={visStateActions}
mapLegendActive={Boolean(uiState.mapControls?.mapLegend?.active)}
mapInfo={mapInfo}
+ cameraTourEnabled={uiState.mapControls?.cameraTour?.show !== false}
cameraBookmarksEnabled={uiState.mapControls?.cameraBookmarks?.show === true}
mapInfoShow={uiState.mapControls?.mapInfo?.show !== false}
mapInfoActive={uiState.mapControls?.mapInfo?.active !== false}
diff --git a/src/components/src/side-panel/interaction-manager.tsx b/src/components/src/side-panel/interaction-manager.tsx
index cda038c0b..d3fbdc507 100644
--- a/src/components/src/side-panel/interaction-manager.tsx
+++ b/src/components/src/side-panel/interaction-manager.tsx
@@ -7,13 +7,16 @@ import {useIntl} from 'react-intl';
import {
Annotation,
CameraBookmark,
+ CameraTour,
InteractionConfig,
LayerOrder,
MapInfo,
MapState
} from '@kepler.gl/types';
import {MapStateActions, UIStateActions, VisStateActions} from '@kepler.gl/actions';
+import {getApplicationConfig} from '@kepler.gl/utils';
import CameraBookmarks from './interaction-panel/camera-bookmarks';
+import CameraTourConfig from './interaction-panel/camera-tour-config';
import {Datasets} from '@kepler.gl/table';
import {Layer} from '@kepler.gl/layers';
@@ -56,6 +59,8 @@ type InteractionManagerProps = {
mapState?: MapState;
cameraBookmarks?: CameraBookmark[];
cameraBookmarksEnabled?: boolean;
+ cameraTour?: CameraTour | null;
+ cameraTourEnabled?: boolean;
mapStateActions?: typeof MapStateActions;
actionIcons?: {
settings?: PanelHeaderActionIcon;
@@ -96,12 +101,15 @@ function InteractionManagerFactory(
mapState,
cameraBookmarks,
cameraBookmarksEnabled,
+ cameraTour,
+ cameraTourEnabled,
mapStateActions,
actionIcons,
interactionConfigIcons
}) => {
const {interactionConfigChange: onConfigChange, setColumnDisplayFormat} = visStateActions;
const intl = useIntl();
+ const {enableCameraBookmarks, enableCameraTour} = getApplicationConfig();
const mapInfoPanel = (
<MapInfoConfig
key="mapInfo"
@@ -173,14 +181,27 @@ function InteractionManagerFactory(
);
})}
{interactionConfig.geocoder ? null : mapInfoPanel}
- <CameraBookmarks
- bookmarks={cameraBookmarks}
- enabled={cameraBookmarksEnabled}
- uiStateActions={uiStateActions}
- mapState={mapState}
- mapStateActions={mapStateActions}
- visStateActions={visStateActions}
- />
+ {enableCameraBookmarks && (
+ <CameraBookmarks
+ bookmarks={cameraBookmarks}
+ enabled={cameraBookmarksEnabled}
+ uiStateActions={uiStateActions}
+ mapState={mapState}
+ mapStateActions={mapStateActions}
+ visStateActions={visStateActions}
+ />
+ )}
+ {enableCameraTour && (
+ <CameraTourConfig
+ tour={cameraTour}
+ enabled={cameraTourEnabled}
+ uiStateActions={uiStateActions}
+ bookmarks={cameraBookmarks}
+ mapState={mapState}
+ mapStateActions={mapStateActions}
+ visStateActions={visStateActions}
+ />
+ )}
</div>
);
};
diff --git a/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsx b/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsx
index 3e663b391..3902454c8 100644
--- a/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsx
+++ b/src/components/src/side-panel/interaction-panel/camera-bookmarks.tsx
@@ -164,13 +164,6 @@ function SortableBookmark({
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'),
@@ -178,6 +171,13 @@ function SortableBookmark({
disabled: !canCapture,
onClick: () => onUpdate(bookmark)
},
+ {
+ key: 'copyCoordinates',
+ label: message('copyCoordinates', 'Copy coordinates'),
+ Icon: Copy,
+ disabled: !coordinates,
+ onClick: () => onCopy(coordinates)
+ },
{
key: 'delete',
label: message('delete', 'Delete'),
diff --git a/src/components/src/side-panel/interaction-panel/camera-tour-config.spec.tsx b/src/components/src/side-panel/interaction-panel/camera-tour-config.spec.tsx
new file mode 100644
index 000000000..411b7fcf3
--- /dev/null
+++ b/src/components/src/side-panel/interaction-panel/camera-tour-config.spec.tsx
@@ -0,0 +1,937 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useRef, useState} from 'react';
+import {act, fireEvent, screen, waitFor, within} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {MapStateActions, UIStateActions, VisStateActions} from '@kepler.gl/actions';
+import {INITIAL_MAP_STATE, INITIAL_UI_STATE} from '@kepler.gl/reducers';
+import {CameraBookmark, CameraTour} from '@kepler.gl/types';
+import {evaluateCameraTour} from '@kepler.gl/utils';
+import {renderWithTheme, IntlWrapper} from 'test/helpers/component-jest-utils';
+import {MapViewStateContext} from '../../map-view-state-context';
+import {RootContext} from '../../context';
+import CameraTourConfig from './camera-tour-config';
+import CameraBookmarks from './camera-bookmarks';
+import CameraBookmarkControl from '../../map/camera-bookmark-control';
+
+const camera = {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45};
+const tour: CameraTour = {
+ stops: [
+ {id: 'home', name: 'Home', camera, holdDurationMs: 1000, travelDurationMs: 2000},
+ {
+ id: 'work',
+ name: 'Work',
+ camera: {...camera, longitude: 50, zoom: 10},
+ holdDurationMs: 1000,
+ travelDurationMs: 9999
+ }
+ ]
+};
+
+function setup(
+ initial: CameraTour | null = tour,
+ options: {
+ bookmarks?: CameraBookmark[];
+ mapState?: typeof INITIAL_MAP_STATE;
+ liveCamera?: typeof camera;
+ floatingBookmarks?: boolean;
+ bookmarksEnabled?: boolean;
+ } = {}
+) {
+ const updateMap = jest.fn();
+ const commit = jest.fn();
+ const toggle = jest.fn();
+ let updateBookmarks: React.Dispatch<React.SetStateAction<CameraBookmark[]>>;
+ const mapState = options.mapState || {...INITIAL_MAP_STATE, ...camera};
+ function Harness() {
+ const root = useRef<HTMLDivElement>(null);
+ const [value, setValue] = useState(initial);
+ const [bookmarks, setBookmarks] = useState(options.bookmarks || []);
+ updateBookmarks = setBookmarks;
+ const [enabled, setEnabled] = useState(true);
+ return (
+ <RootContext.Provider value={root}>
+ <div ref={root}>
+ <div className="maps">
+ <button type="button">Map surface</button>
+ </div>
+ <div className="geocoder-panel">
+ <input aria-label="Search map" />
+ </div>
+ <CameraBookmarks
+ bookmarks={[{id: 'saved', name: 'Saved view', camera}]}
+ enabled={options.bookmarksEnabled === true}
+ mapState={mapState}
+ mapStateActions={{...MapStateActions, updateMap}}
+ visStateActions={VisStateActions}
+ />
+ {options.floatingBookmarks && (
+ <CameraBookmarkControl
+ bookmarks={[{id: 'saved', name: 'Saved view', camera}]}
+ mapState={mapState}
+ mapStateActions={{...MapStateActions, updateMap}}
+ mapControls={{
+ ...INITIAL_UI_STATE.mapControls,
+ cameraBookmarks: {
+ ...INITIAL_UI_STATE.mapControls.cameraBookmarks,
+ active: true,
+ show: options.bookmarksEnabled === true
+ }
+ }}
+ setMapControlSettings={jest.fn()}
+ />
+ )}
+ <CameraTourConfig
+ tour={value}
+ enabled={enabled}
+ uiStateActions={{
+ ...UIStateActions,
+ setMapControlVisibility: Object.assign((control: string, show: boolean) => {
+ toggle(control, show);
+ setEnabled(show);
+ return UIStateActions.setMapControlVisibility(control, show);
+ }, UIStateActions.setMapControlVisibility)
+ }}
+ bookmarks={bookmarks}
+ mapState={mapState}
+ mapStateActions={{...MapStateActions, updateMap}}
+ visStateActions={{
+ ...VisStateActions,
+ setCameraTour: Object.assign((next: CameraTour | null) => {
+ commit(next);
+ setValue(next);
+ return VisStateActions.setCameraTour(next);
+ }, VisStateActions.setCameraTour)
+ }}
+ />
+ </div>
+ </RootContext.Provider>
+ );
+ }
+ const rendered = renderWithTheme(
+ <IntlWrapper>
+ <MapViewStateContext.Provider
+ value={{
+ getInternalViewState: () => options.liveCamera || mapState,
+ setInternalViewState: jest.fn()
+ }}
+ >
+ <Harness />
+ </MapViewStateContext.Provider>
+ </IntlWrapper>
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Camera animation'}));
+ return {
+ ...rendered,
+ updateMap,
+ commit,
+ toggle,
+ changeBookmarks: (bookmarks: CameraBookmark[]) => act(() => updateBookmarks(bookmarks))
+ };
+}
+
+let callbacks: Map<number, FrameRequestCallback>;
+let nextFrame: number;
+beforeEach(() => {
+ callbacks = new Map();
+ nextFrame = 0;
+ jest.spyOn(window, 'requestAnimationFrame').mockImplementation(callback => {
+ callbacks.set(++nextFrame, callback);
+ return nextFrame;
+ });
+ jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(id => {
+ callbacks.delete(id);
+ });
+ jest.spyOn(performance, 'now').mockReturnValue(0);
+});
+afterEach(() => jest.restoreAllMocks());
+
+function frame(time: number) {
+ const pending = [...callbacks.values()];
+ callbacks.clear();
+ act(() => pending.forEach(callback => callback(time)));
+}
+
+test('captures the live view, renames it and removes the last stop without datasets', () => {
+ const liveCamera = {...camera};
+ const {commit} = setup(null, {liveCamera});
+ expect(screen.queryByRole('menu')).toBeNull();
+ liveCamera.zoom = 12;
+ fireEvent.click(screen.getByRole('button', {name: 'Add stop'}));
+ expect(commit.mock.lastCall[0].stops[0].camera).toEqual(liveCamera);
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('2 s');
+ fireEvent.change(screen.getByRole('textbox', {name: 'Stop name'}), {
+ target: {value: 'New view'}
+ });
+ expect(commit.mock.lastCall[0].stops[0].name).toBe('New view');
+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
+ expect(commit.mock.lastCall[0]).toBeNull();
+});
+
+test('copies bookmarks and updates a stop from the current view without modifying the bookmark', () => {
+ const bookmark = {
+ id: 'bookmark',
+ name: 'A long saved view over the eastern waterfront and harbour',
+ camera: {...camera}
+ };
+ const liveCamera = {...camera, bearing: 80, pitch: 60};
+ const {commit} = setup(null, {bookmarks: [bookmark], liveCamera});
+ fireEvent.click(screen.getByRole('button', {name: 'Add stop'}));
+ fireEvent.click(screen.getByTitle(bookmark.name));
+ const saved = commit.mock.lastCall[0].stops[0];
+ expect(saved.name).toBe(bookmark.name);
+ expect(saved.camera).toEqual(bookmark.camera);
+ expect(saved.camera).not.toBe(bookmark.camera);
+ bookmark.camera.zoom = 20;
+ expect(saved.camera.zoom).toBe(6);
+ liveCamera.pitch = 70;
+ fireEvent.click(screen.getByRole('button', {name: 'Pick current location'}));
+ expect(commit.mock.lastCall[0].stops[0].camera).toEqual(liveCamera);
+ expect(bookmark.camera.pitch).toBe(45);
+});
+
+test('Add stop menu selects bookmarks by ID with the keyboard and supports repeated choices', async () => {
+ const user = userEvent.setup();
+ const bookmarks = [
+ {id: 'current', name: 'Same saved view', camera},
+ {id: 'second', name: 'Same saved view', camera: {...camera, longitude: 50}}
+ ];
+ const {commit, updateMap} = setup(null, {bookmarks});
+ const button = screen.getByRole('button', {name: 'Add stop'});
+ const chooseSecond = async () => {
+ button.focus();
+ await user.keyboard('{Enter}{ArrowDown}{ArrowDown}{Enter}');
+ };
+ await chooseSecond();
+ expect(commit.mock.lastCall[0].stops[0].camera).toEqual(bookmarks[1].camera);
+ expect(button).toHaveFocus();
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ await chooseSecond();
+ const stops = commit.mock.lastCall[0].stops;
+ expect(stops).toHaveLength(2);
+ expect(stops[1].camera).toEqual(bookmarks[1].camera);
+ expect(stops[1].id).not.toBe(stops[0].id);
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('menu dismissal never adds a stop and restores trigger focus', async () => {
+ const user = userEvent.setup();
+ const {commit} = setup(null, {bookmarks: [{id: 'saved', name: 'Saved', camera}]});
+ const button = screen.getByRole('button', {name: 'Add stop'});
+ button.focus();
+ await user.keyboard(' ');
+ expect(screen.getByRole('menu')).toBeInTheDocument();
+ await user.keyboard('{Escape}');
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(button).toHaveFocus();
+ await user.keyboard('{ArrowDown}');
+ await user.keyboard('{Tab}');
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(button).toHaveFocus();
+ await user.click(button);
+ await user.click(document.querySelector('.ReactModal__Overlay') as HTMLElement);
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(button).toHaveFocus();
+ expect(commit).not.toHaveBeenCalled();
+});
+
+test('Current view captures the live camera at selection and interrupts playback', () => {
+ const liveCamera = {...camera};
+ const {commit, updateMap} = setup(tour, {
+ liveCamera,
+ bookmarks: [{id: 'saved', name: 'Saved', camera}]
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ updateMap.mockClear(); // Playback applies the initial frame when Play is pressed.
+ fireEvent.click(screen.getByRole('button', {name: 'Add stop'}));
+ expect(commit).not.toHaveBeenCalled();
+ liveCamera.zoom = 15;
+ fireEvent.click(screen.getByRole('menuitem', {name: 'Current view'}));
+ expect(commit.mock.lastCall[0].stops[2].camera).toEqual(liveCamera);
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ frame(1000);
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('menu keeps focused bookmark identity through changes and closes when bookmarks disappear', async () => {
+ const user = userEvent.setup();
+ const first = {id: 'first', name: 'First', camera};
+ const second = {id: 'second', name: 'Second', camera: {...camera, zoom: 10}};
+ const {commit, changeBookmarks} = setup(null, {bookmarks: [first, second]});
+ const button = screen.getByRole('button', {name: 'Add stop'});
+ await user.click(button);
+ await user.keyboard('{End}');
+ expect(screen.getByRole('menuitem', {name: 'Second'})).toHaveFocus();
+ changeBookmarks([{...second, name: 'Renamed', camera: {...camera, zoom: 12}}, first]);
+ expect(screen.getByRole('menuitem', {name: 'Renamed'})).toHaveFocus();
+ await user.keyboard('{Enter}');
+ expect(commit.mock.lastCall[0].stops[0]).toMatchObject({name: 'Renamed', camera: {zoom: 12}});
+ await user.click(button);
+ await user.keyboard('{End}');
+ changeBookmarks([second]);
+ expect(screen.getByRole('menuitem', {name: 'Current view'})).toHaveFocus();
+ changeBookmarks([]);
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(button).toHaveFocus();
+ changeBookmarks([first]);
+ expect(screen.queryByRole('menu')).toBeNull();
+ changeBookmarks([]);
+ await user.click(button);
+ expect(commit.mock.lastCall[0].stops).toHaveLength(2);
+});
+
+test('long bookmark lists remain keyboard reachable and preserve their full names', async () => {
+ const user = userEvent.setup();
+ const bookmarks = Array.from({length: 45}, (_, index) => ({
+ id: `saved-${index}`,
+ name: `A long saved view of the waterfront and harbour number ${index}`,
+ camera: {...camera, longitude: index}
+ }));
+ const {commit} = setup(null, {bookmarks});
+ await user.click(screen.getByRole('button', {name: 'Add stop'}));
+ await user.keyboard('{End}{Enter}');
+ expect(commit.mock.lastCall[0].stops[0]).toMatchObject({
+ name: bookmarks[44].name,
+ camera: bookmarks[44].camera
+ });
+});
+
+test('unavailable capture is disabled while saved sources and disabled-tour authoring remain usable', async () => {
+ const user = userEvent.setup();
+ const invalidCamera = {...camera, zoom: NaN};
+ const {commit, changeBookmarks} = setup(null, {
+ liveCamera: invalidCamera,
+ mapState: {...INITIAL_MAP_STATE, ...invalidCamera},
+ bookmarks: [{id: 'saved', name: 'Saved', camera}]
+ });
+ fireEvent.click(screen.getByRole('checkbox', {name: 'Enable camera animation'}));
+ await user.click(screen.getByRole('button', {name: 'Add stop'}));
+ expect(screen.getByRole('menuitem', {name: 'Current view'})).toBeDisabled();
+ expect(screen.getByRole('menuitem', {name: 'Saved'})).toHaveFocus();
+ await user.keyboard('{Enter}');
+ expect(commit.mock.lastCall[0].stops[0].camera).toEqual(camera);
+ changeBookmarks([]);
+ expect(screen.getByRole('button', {name: 'Add stop'})).toBeDisabled();
+});
+
+test('duplicates and deletes the addressed stop while preserving selection and total duration', () => {
+ const {commit, updateMap} = setup();
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('4 s');
+ fireEvent.click(screen.getByRole('button', {name: 'Duplicate'}));
+ const duplicate = commit.mock.lastCall[0].stops[1];
+ expect(duplicate.id).not.toBe('home');
+ expect(duplicate.camera).toEqual(camera);
+ expect(duplicate.camera).not.toBe(camera);
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('7 s');
+ expect(screen.getByRole('button', {name: 'Stop 2: Home'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(screen.getByRole('button', {name: 'Stop 2: Home'})).toHaveFocus();
+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveFocus();
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(commit.mock.lastCall[0]).toEqual(tour);
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('4 s');
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('edits hold and travel in seconds and rejects invalid or unsafe total durations', () => {
+ const {commit} = setup();
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Hold (s)'}), {
+ target: {value: '1.5'}
+ });
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Travel to next (s)'}), {
+ target: {value: '3.5'}
+ });
+ expect(commit.mock.lastCall[0].stops[0]).toMatchObject({
+ holdDurationMs: 1500,
+ travelDurationMs: 3500
+ });
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('6 s');
+ commit.mockClear();
+ for (const value of ['-1', '', '9007199254740']) {
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Hold (s)'}), {target: {value}});
+ }
+ expect(commit).not.toHaveBeenCalled();
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('6 s');
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 2: Work'}));
+ expect(screen.queryByRole('spinbutton', {name: 'Travel to next (s)'})).toBeNull();
+ expect(screen.getByRole('spinbutton', {name: 'Hold (s)'})).toHaveValue(1);
+ expect(commit).not.toHaveBeenCalled();
+});
+
+test('scrubbing and playback evaluate the same camera at the same timestamp', () => {
+ const {updateMap} = setup();
+ fireEvent.change(screen.getByRole('slider', {name: 'Camera tour time'}), {
+ target: {value: '1500'}
+ });
+ const expected = {...evaluateCameraTour(tour, 1500), transitionDuration: 0};
+ expect(updateMap).toHaveBeenLastCalledWith(expected);
+ fireEvent.click(screen.getByRole('button', {name: 'Restart'}));
+ expect(updateMap).toHaveBeenLastCalledWith({...camera, transitionDuration: 0});
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ frame(1500);
+ expect(updateMap).toHaveBeenLastCalledWith(expected);
+ expect(screen.getByLabelText('Elapsed time')).toHaveTextContent('1.5 s');
+ fireEvent.click(screen.getByRole('button', {name: 'Pause'}));
+ updateMap.mockClear();
+ frame(2000);
+ expect(updateMap).not.toHaveBeenCalled();
+ expect(callbacks.size).toBe(0);
+});
+
+test('resumes elapsed time, finishes exactly at the end, and replays from the beginning', () => {
+ const {updateMap} = setup();
+ fireEvent.change(screen.getByRole('slider'), {target: {value: '1500'}});
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ frame(500);
+ expect(updateMap).toHaveBeenLastCalledWith({
+ ...evaluateCameraTour(tour, 2000),
+ transitionDuration: 0
+ });
+ frame(5000);
+ expect(updateMap).toHaveBeenLastCalledWith({...tour.stops[1].camera, transitionDuration: 0});
+ expect(screen.getByLabelText('Elapsed time')).toHaveTextContent('4 s');
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ expect(callbacks.size).toBe(0);
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ expect(updateMap).toHaveBeenLastCalledWith({...camera, transitionDuration: 0});
+});
+
+test('marker selection is separate from Go to and the playback position', () => {
+ const {updateMap, commit} = setup();
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 2: Work'}));
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(screen.getByRole('textbox', {name: 'Stop name'})).toHaveValue('Work');
+ expect(screen.getByRole('button', {name: 'Stop 1: Home'})).toHaveAttribute(
+ 'aria-current',
+ 'step'
+ );
+ expect(screen.getByRole('slider')).toHaveValue('0');
+ expect(updateMap).not.toHaveBeenCalled();
+ expect(commit).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveAttribute(
+ 'aria-current',
+ 'step'
+ );
+ expect(screen.getByRole('slider')).toHaveValue('3000');
+ expect(updateMap).toHaveBeenLastCalledWith({...tour.stops[1].camera, transitionDuration: 0});
+});
+
+test.each([0, 1000])(
+ 'Go to uses the selected camera at coincident arrivals with a final hold of %i ms',
+ holdDurationMs => {
+ const coincident = {
+ stops: [
+ {...tour.stops[0], holdDurationMs: 0, travelDurationMs: 0},
+ {...tour.stops[1], holdDurationMs}
+ ]
+ };
+ const {updateMap} = setup(coincident);
+ if (holdDurationMs) fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ const staleCallback = [...callbacks.values()][0];
+ updateMap.mockClear();
+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));
+ expect(updateMap).toHaveBeenCalledTimes(1);
+ expect(updateMap).toHaveBeenLastCalledWith({...camera, transitionDuration: 0});
+ expect(screen.getByRole('slider')).toHaveValue('0');
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ expect(callbacks.size).toBe(0);
+ if (staleCallback) act(() => staleCallback(500));
+ expect(updateMap).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 2: Work'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));
+ expect(updateMap).toHaveBeenLastCalledWith({...tour.stops[1].camera, transitionDuration: 0});
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 1: Home'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Restart'}));
+ expect(updateMap).toHaveBeenLastCalledWith({...tour.stops[1].camera, transitionDuration: 0});
+ }
+);
+
+test.each(['pointerDown', 'wheel', 'keyDown'] as const)(
+ 'manual map %s pauses playback before more frames',
+ event => {
+ const {updateMap} = setup();
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ const staleCallback = [...callbacks.values()][0];
+ fireEvent[event](screen.getByRole('button', {name: 'Map surface'}));
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ updateMap.mockClear();
+ act(() => staleCallback(1000));
+ expect(updateMap).not.toHaveBeenCalled();
+ expect(callbacks.size).toBe(0);
+ }
+);
+
+test('search navigation pauses playback while unrelated sidebar pointer events do not', () => {
+ setup();
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ fireEvent.pointerDown(screen.getByRole('textbox', {name: 'Stop name'}));
+ expect(screen.getByRole('button', {name: 'Pause'})).toBeInTheDocument();
+ fireEvent.keyDown(screen.getByRole('textbox', {name: 'Search map'}), {key: 'Enter'});
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+});
+
+test('editing and unmounting cancel playback while collapsing only hides the editor', () => {
+ const {unmount, updateMap} = setup();
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ fireEvent.change(screen.getByRole('textbox', {name: 'Stop name'}), {
+ target: {value: 'Changed'}
+ });
+ expect(callbacks.size).toBe(0);
+ expect(screen.getByLabelText('Elapsed time')).toHaveTextContent('0 s');
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Camera animation'}));
+ expect(screen.queryByRole('button', {name: 'Pause'})).toBeNull();
+ expect(callbacks.size).toBe(1);
+ frame(1500);
+ expect(updateMap).toHaveBeenLastCalledWith({
+ ...evaluateCameraTour(tour, 1500),
+ transitionDuration: 0
+ });
+ fireEvent.click(screen.getByRole('button', {name: 'Camera animation'}));
+ expect(screen.getByRole('button', {name: 'Pause'})).toBeInTheDocument();
+ unmount();
+ expect(callbacks.size).toBe(0);
+});
+
+test('zero-duration tours disable playback but can jump to their evaluated camera', () => {
+ const instant = {
+ stops: tour.stops.map(stop => ({...stop, holdDurationMs: 0, travelDurationMs: 0}))
+ };
+ const {updateMap} = setup(instant);
+ expect(screen.getByRole('button', {name: 'Play'})).toBeDisabled();
+ expect(screen.getByRole('slider')).toBeDisabled();
+ fireEvent.click(screen.getByRole('button', {name: 'Restart'}));
+ expect(updateMap).toHaveBeenLastCalledWith({...tour.stops[1].camera, transitionDuration: 0});
+});
+
+test.each([
+ {...INITIAL_MAP_STATE, isSplit: true},
+ {...INITIAL_MAP_STATE, globe: {...INITIAL_MAP_STATE.globe!, enabled: true}}
+])('unsupported map modes do not expose tour editing or playback', mapState => {
+ setup(tour, {mapState, bookmarks: [{id: 'saved', name: 'Saved view', camera}]});
+ expect(screen.getByText('Use a single 2D or 3D map to edit camera views.')).toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: 'Play'})).toBeNull();
+ expect(screen.queryByRole('button', {name: 'Add stop'})).toBeNull();
+ expect(screen.queryByRole('menu')).toBeNull();
+});
+
+test('navigating to a saved bookmark pauses the tour before the next frame', () => {
+ const {updateMap} = setup(tour, {bookmarksEnabled: true});
+ fireEvent.click(screen.getByRole('button', {name: 'Bookmarks'}));
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ fireEvent.click(
+ within(document.querySelector('.interaction-camera-bookmarks') as HTMLElement).getByRole(
+ 'button',
+ {name: 'Go to'}
+ )
+ );
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ expect(updateMap).toHaveBeenLastCalledWith(expect.objectContaining({transitionDuration: 1000}));
+ updateMap.mockClear();
+ frame(1500);
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('disabling pauses immediately, preserves stops and elapsed time, and re-enables paused', () => {
+ const {updateMap, commit, toggle} = setup();
+ const enable = screen.getByRole('checkbox', {name: 'Enable camera animation'});
+ const expand = screen.getByRole('button', {name: 'Camera animation'});
+ expect(enable).toBeChecked();
+ expect(document.getElementById(expand.getAttribute('aria-controls') || '')).not.toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ frame(1500);
+ const staleCallback = [...callbacks.values()][0];
+ fireEvent.click(enable);
+ expect(toggle).toHaveBeenLastCalledWith('cameraTour', false);
+ expect(enable).not.toBeChecked();
+ expect(expand).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.getByRole('button', {name: 'Play'})).toBeDisabled();
+ expect(screen.getByRole('button', {name: 'Restart'})).toBeDisabled();
+ expect(screen.getByRole('button', {name: 'Go to'})).toBeDisabled();
+ expect(screen.getByRole('slider')).toBeDisabled();
+ updateMap.mockClear();
+ act(() => staleCallback(2000));
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 2: Work'}));
+ expect(updateMap).not.toHaveBeenCalled();
+ expect(callbacks.size).toBe(0);
+ expect(commit).not.toHaveBeenCalled();
+ expect(screen.getByLabelText('Elapsed time')).toHaveTextContent('1.5 s');
+ expect(screen.getByRole('textbox', {name: 'Stop name'})).toHaveValue('Work');
+ fireEvent.click(expand);
+ fireEvent.click(enable);
+ expect(expand).toHaveAttribute('aria-expanded', 'false');
+ expect(callbacks.size).toBe(0);
+ fireEvent.click(expand);
+ expect(screen.getByRole('button', {name: 'Play'})).toBeEnabled();
+ expect(screen.getByLabelText('Elapsed time')).toHaveTextContent('1.5 s');
+ expect(commit).not.toHaveBeenCalled();
+});
+
+test('floating bookmark navigation outside the map pauses playback before any stale frame', () => {
+ const {updateMap} = setup(tour, {floatingBookmarks: true, bookmarksEnabled: true});
+ const navigate = screen.getByRole('button', {name: 'Saved view'});
+ expect(navigate.closest('.maps')).toBeNull();
+ expect(navigate.closest('.camera-bookmark-panel')).not.toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ const staleCallback = [...callbacks.values()][0];
+ fireEvent.click(navigate);
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ expect(updateMap).toHaveBeenLastCalledWith(expect.objectContaining({transitionDuration: 1000}));
+ updateMap.mockClear();
+ act(() => staleCallback(1500));
+ expect(updateMap).not.toHaveBeenCalled();
+ expect(callbacks.size).toBe(0);
+});
+
+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 measureStops(coincident = false) {
+ const original = HTMLElement.prototype.getBoundingClientRect;
+ jest
+ .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
+ .mockImplementation(function (this: HTMLElement) {
+ if (!this.classList.contains('camera-tour-marker-slot')) return original.call(this);
+ const markers = Array.from(
+ this.parentElement?.querySelectorAll('.camera-tour-marker-slot') || []
+ );
+ const left = coincident ? 0 : markers.indexOf(this) * 100;
+ return {
+ x: left,
+ y: 0,
+ top: 0,
+ left,
+ right: left + 100,
+ bottom: 40,
+ width: 100,
+ height: 40,
+ toJSON: () => ({})
+ };
+ });
+}
+
+test('keyboard selection stays available but Space and arrows never reorder stops', async () => {
+ measureStops();
+ const {commit, updateMap} = setup();
+ const home = screen.getByRole('button', {name: 'Stop 1: Home'});
+ const work = screen.getByRole('button', {name: 'Stop 2: Work'});
+ home.focus();
+ fireEvent.keyDown(home, {key: ' ', code: 'Space'});
+ fireEvent.keyUp(home, {key: ' ', code: 'Space'});
+ fireEvent.click(home); // The native Space keyup click, which fireEvent does not synthesize.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 0));
+ });
+ expect(home).not.toHaveAttribute('data-dragging');
+ fireEvent.keyDown(home, {key: 'ArrowRight', code: 'ArrowRight'});
+ expect(work).toHaveFocus();
+ expect(work).toHaveAttribute('aria-pressed', 'true');
+ expect(screen.queryByRole('spinbutton', {name: 'Travel to next (s)'})).toBeNull();
+ fireEvent.keyDown(work, {key: ' ', code: 'Space'});
+ fireEvent.keyUp(work, {key: ' ', code: 'Space'});
+ fireEvent.click(work);
+ fireEvent.keyDown(work, {key: 'Escape', code: 'Escape'});
+ expect(work).not.toHaveAttribute('data-dragging');
+ expect(work).toHaveAccessibleName('Stop 2: Work');
+ fireEvent.keyDown(work, {key: 'ArrowLeft', code: 'ArrowLeft'});
+ expect(home).toHaveFocus();
+ expect(home).toHaveAttribute('aria-pressed', 'true');
+ expect(screen.getByRole('spinbutton', {name: 'Travel to next (s)'})).toHaveValue(2);
+ fireEvent.keyDown(home, {key: 'Enter', code: 'Enter'});
+ expect(home).toHaveAttribute('aria-pressed', 'true');
+ expect(home).toHaveAccessibleName('Stop 1: Home');
+ expect(commit).not.toHaveBeenCalled();
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('selected-stop actions and timing edit only that stop without dragging or navigation', () => {
+ measureStops();
+ const liveCamera = {...camera, pitch: 60};
+ const {commit, updateMap} = setup(tour, {liveCamera});
+ const work = screen.getByRole('button', {name: 'Stop 2: Work'});
+ fireEvent.click(work);
+ const capture = screen.getByRole('button', {name: 'Pick current location'});
+ fireEvent.pointerDown(capture, {button: 0, clientX: 180, clientY: 120});
+ fireEvent.pointerMove(document, {clientX: 20, clientY: 120});
+ fireEvent.pointerUp(document);
+ fireEvent.click(capture);
+ expect(commit).toHaveBeenLastCalledWith({
+ stops: [tour.stops[0], {...tour.stops[1], camera: liveCamera}]
+ });
+ expect(work).not.toHaveAttribute('data-dragging');
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ updateMap.mockClear();
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Hold (s)'}), {
+ target: {value: '2'}
+ });
+ expect(commit.mock.lastCall[0].stops[1]).toMatchObject({
+ id: 'work',
+ holdDurationMs: 2000,
+ travelDurationMs: 9999
+ });
+ expect(callbacks.size).toBe(0);
+ expect(screen.getByRole('button', {name: 'Play'})).toBeInTheDocument();
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('pointer reorder preserves the selected stop and its durations without navigating', async () => {
+ measureStops();
+ const {commit, updateMap} = setup();
+ const home = screen.getByRole('button', {name: 'Stop 1: Home'});
+ const work = screen.getByRole('button', {name: 'Stop 2: Work'});
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ const staleCallback = [...callbacks.values()][0];
+ updateMap.mockClear();
+ fireEvent.pointerDown(work, {button: 0, clientX: 150, clientY: 20});
+ work.focus(); // Simulate the pointer-focus default omitted by fireEvent.
+ fireEvent.pointerMove(document, {clientX: 144, clientY: 20});
+ await waitFor(() => expect(work).toHaveAttribute('data-dragging', 'true'));
+ expect(callbacks.size).toBe(0);
+ const positions = [home.parentElement!.style.left, work.parentElement!.style.left];
+ fireEvent.pointerMove(document, {clientX: 50, clientY: 20});
+ expect([home.parentElement!.style.left, work.parentElement!.style.left]).toEqual(positions);
+ fireEvent.pointerUp(document, {clientX: 50, clientY: 20});
+ fireEvent.click(work); // The post-drag click must not select or navigate.
+ await waitFor(() => expect(commit).toHaveBeenCalledWith({stops: [tour.stops[1], tour.stops[0]]}));
+ expect(home).toHaveAttribute('aria-pressed', 'true');
+ expect(home).toHaveAccessibleName('Stop 2: Home');
+ expect(work).toHaveAttribute('aria-pressed', 'false');
+ expect(work).not.toHaveAttribute('data-dragging');
+ expect(work).toHaveFocus();
+ act(() => staleCallback(1500));
+ expect(updateMap).not.toHaveBeenCalled();
+ await waitFor(() => {
+ fireEvent.click(work);
+ expect(work).toHaveAttribute('aria-pressed', 'true');
+ });
+ expect(screen.getByRole('spinbutton', {name: 'Travel to next (s)'})).toHaveValue(9.999);
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test.each(['pointercancel', 'escape', 'outside'] as const)(
+ 'pointer %s cancels reorder without saving or navigation',
+ async cancel => {
+ measureStops();
+ const {commit, updateMap} = setup();
+ const home = screen.getByRole('button', {name: 'Stop 1: Home'});
+ fireEvent.pointerDown(home, {button: 0, clientX: 50, clientY: 20});
+ fireEvent.pointerMove(document, {clientX: 56, clientY: 20});
+ await waitFor(() => expect(home).toHaveAttribute('data-dragging', 'true'));
+ fireEvent.pointerMove(document, {clientX: 150, clientY: 20});
+ if (cancel === 'pointercancel') fireEvent.pointerCancel(document);
+ else if (cancel === 'escape') fireEvent.keyDown(document, {key: 'Escape', code: 'Escape'});
+ else {
+ fireEvent.pointerMove(document, {clientX: 500, clientY: 500});
+ fireEvent.pointerUp(document, {clientX: 500, clientY: 500});
+ }
+ expect(home).not.toHaveAttribute('data-dragging');
+ expect(home).toHaveAttribute('aria-pressed', 'true');
+ expect(home).toHaveAccessibleName('Stop 1: Home');
+ expect(commit).not.toHaveBeenCalled();
+ expect(updateMap).not.toHaveBeenCalled();
+ // dnd-kit suppresses the click immediately following cancellation; let it release
+ // before the next test tries to open its freshly mounted panel.
+ await waitFor(() => {
+ const work = screen.getByRole('button', {name: 'Stop 2: Work'});
+ fireEvent.click(work);
+ expect(work).toHaveAttribute('aria-pressed', 'true');
+ });
+ }
+);
+
+test('one-stop deletion restores capture focus and empty controls; many stops stay keyboard-accessible', () => {
+ const {unmount, commit} = setup({stops: [tour.stops[0]]});
+ expect(screen.getByRole('button', {name: 'Stop 1: Home'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(screen.queryByRole('spinbutton', {name: 'Travel to next (s)'})).toBeNull();
+ fireEvent.click(screen.getByRole('button', {name: 'Delete'}));
+ expect(commit).toHaveBeenLastCalledWith(null);
+ expect(screen.getByRole('button', {name: 'Add stop'})).toHaveFocus();
+ expect(screen.queryByRole('spinbutton')).toBeNull();
+ expect(screen.queryByRole('group', {name: 'Animation stops'})).toBeNull();
+ unmount();
+ const many = {
+ stops: Array.from({length: 30}, (_, index) => ({
+ ...tour.stops[0],
+ id: `stop-${index}`,
+ name: `View ${index}`
+ }))
+ };
+ setup(many);
+ const first = screen.getByRole('button', {name: 'Stop 1: View 0'});
+ const last = screen.getByRole('button', {name: 'Stop 30: View 29'});
+ first.focus();
+ fireEvent.keyDown(first, {key: 'End', code: 'End'});
+ expect(last).toHaveFocus();
+ expect(last).toHaveAttribute('aria-pressed', 'true');
+ expect(screen.getByRole('textbox', {name: 'Stop name'})).toHaveValue('View 29');
+ fireEvent.keyDown(last, {key: 'Home', code: 'Home'});
+ expect(first).toHaveFocus();
+ fireEvent.keyDown(first, {key: 'Enter', code: 'Enter'});
+ expect(first).toHaveAttribute('aria-pressed', 'true');
+});
+
+test('normalizes Hold and Travel blocks to authored duration, including the final Hold only', () => {
+ setup();
+ const hold = screen.getByRole('button', {name: 'Stop 1: Home — Hold: 1 s'});
+ const travel = screen.getByRole('button', {name: 'Stop 1: Home — Travel: 2 s'});
+ const finalHold = screen.getByRole('button', {name: 'Stop 2: Work — Hold: 1 s'});
+ // These proportions encode authored time, rather than incidental visual dimensions.
+ expect(hold).toHaveStyle({left: '0%', width: '25%'});
+ expect(travel).toHaveStyle({left: '25%', width: '50%'});
+ expect(finalHold).toHaveStyle({left: '75%', width: '25%'});
+ expect(screen.getByRole('button', {name: 'Stop 1: Home'}).parentElement).toHaveStyle({
+ left: 'clamp(16px, 0%, calc(100% - 16px))'
+ });
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'}).parentElement).toHaveStyle({
+ left: 'clamp(16px, 75%, calc(100% - 16px))'
+ });
+ expect(screen.queryByRole('button', {name: /Stop 2: Work — Travel:/})).toBeNull();
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Travel to next (s)'}), {
+ target: {value: '6'}
+ });
+ expect(hold).toHaveStyle({left: '0%', width: '12.5%'});
+ expect(travel).toHaveStyle({left: '12.5%', width: '75%'});
+ expect(finalHold).toHaveStyle({left: '87.5%', width: '12.5%'});
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('8 s');
+});
+
+test('segment activation selects its owner and focuses the corresponding input without navigation or reorder', () => {
+ const {commit, updateMap} = setup();
+ fireEvent.click(screen.getByRole('button', {name: 'Play'}));
+ const staleFrame = [...callbacks.values()][0];
+ updateMap.mockClear();
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 2: Work — Hold: 1 s'}));
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(screen.getByRole('spinbutton', {name: 'Hold (s)'})).toHaveFocus();
+ expect(callbacks.size).toBe(0);
+ act(() => staleFrame(1500));
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 1: Home — Travel: 2 s'}));
+ expect(screen.getByRole('button', {name: 'Stop 1: Home'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(screen.getByRole('spinbutton', {name: 'Travel to next (s)'})).toHaveFocus();
+ fireEvent.click(screen.getByRole('button', {name: 'Stop 1: Home — Hold: 1 s'}));
+ expect(screen.getByRole('spinbutton', {name: 'Hold (s)'})).toHaveFocus();
+ expect(commit).not.toHaveBeenCalled();
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test('coincident zero-time stops remain selectable without inventing timeline duration', () => {
+ const zeroTour = {
+ stops: tour.stops.map(stop => ({...stop, holdDurationMs: 0, travelDurationMs: 0}))
+ };
+ const {commit, updateMap} = setup(zeroTour);
+ for (const stop of zeroTour.stops) {
+ const hold = screen.getByRole('button', {name: new RegExp(`${stop.name} — Hold:`)});
+ expect(hold).toHaveStyle({left: '0%', width: '0%'});
+ expect(hold).toHaveAttribute('tabindex', '-1');
+ }
+ const first = screen.getByRole('button', {name: 'Stop 1: Home'});
+ first.focus();
+ fireEvent.keyDown(first, {key: 'ArrowRight', code: 'ArrowRight'});
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveFocus();
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ expect(screen.getByRole('textbox', {name: 'Stop name'})).toHaveValue('Work');
+ expect(screen.getByRole('spinbutton', {name: 'Hold (s)'})).toHaveValue(0);
+ expect(screen.getByRole('button', {name: 'Play'})).toBeDisabled();
+ expect(commit).not.toHaveBeenCalled();
+ expect(updateMap).not.toHaveBeenCalled();
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Hold (s)'}), {target: {value: '2'}});
+ expect(screen.getByRole('button', {name: 'Stop 2: Work — Hold: 2 s'})).toHaveStyle({
+ left: '0%',
+ width: '100%'
+ });
+ expect(screen.getByLabelText('Tour duration')).toHaveTextContent('2 s');
+});
+
+test('tiny segments keep their duration proportions and are editable through their stop', () => {
+ const {commit, updateMap} = setup({
+ stops: [
+ {...tour.stops[0], holdDurationMs: 1, travelDurationMs: 9998},
+ {...tour.stops[1], holdDurationMs: 1}
+ ]
+ });
+ expect(screen.getByRole('button', {name: 'Stop 1: Home — Hold: 0 s'})).toHaveStyle({
+ width: '0.01%'
+ });
+ const marker = screen.getByRole('button', {name: 'Stop 2: Work'});
+ marker.focus();
+ fireEvent.keyDown(marker, {key: 'Enter', code: 'Enter'});
+ expect(screen.getByRole('spinbutton', {name: 'Hold (s)'})).toHaveValue(0.001);
+ expect(screen.getByRole('button', {name: 'Stop 2: Work'})).toHaveAttribute(
+ 'aria-pressed',
+ 'true'
+ );
+ fireEvent.change(screen.getByRole('spinbutton', {name: 'Hold (s)'}), {target: {value: '1'}});
+ expect(commit.mock.lastCall[0].stops[1]).toMatchObject({id: 'work', holdDurationMs: 1000});
+ expect(updateMap).not.toHaveBeenCalled();
+});
+
+test.each([
+ ['first', 1, ['second', 'first', 'third']],
+ ['third', -1, ['first', 'third', 'second']]
+] as const)(
+ 'coincident arrivals move %s one position in the drag direction',
+ async (id, direction, order) => {
+ measureStops(true);
+ const stops = ['first', 'second', 'third'].map((stopId, index) => ({
+ ...tour.stops[0],
+ id: stopId,
+ name: stopId,
+ holdDurationMs: index === 2 ? 1000 : 0,
+ travelDurationMs: 0
+ }));
+ const {commit, updateMap} = setup({stops});
+ const marker = screen.getByRole('button', {
+ name: `Stop ${stops.findIndex(stop => stop.id === id) + 1}: ${id}`
+ });
+ marker.focus();
+ fireEvent.keyDown(marker, {key: 'Enter', code: 'Enter'});
+ fireEvent.pointerDown(marker, {button: 0, clientX: 50, clientY: 20});
+ fireEvent.pointerMove(document, {clientX: 50 + direction * 6, clientY: 20});
+ await waitFor(() => expect(marker).toHaveAttribute('data-dragging', 'true'));
+ fireEvent.pointerMove(document, {clientX: 50 + direction * 10, clientY: 20});
+ fireEvent.pointerUp(document, {clientX: 50 + direction * 10, clientY: 20});
+ await waitFor(() => expect(commit).toHaveBeenCalledTimes(1));
+ expect(commit.mock.lastCall[0].stops.map((stop: {id: string}) => stop.id)).toEqual(order);
+ expect(marker).toHaveAttribute('aria-pressed', 'true');
+ expect(updateMap).not.toHaveBeenCalled();
+ await waitFor(() => {
+ fireEvent.click(screen.getByRole('button', {name: 'Go to'}));
+ expect(updateMap).toHaveBeenCalledTimes(1);
+ });
+ }
+);
diff --git a/src/components/src/side-panel/interaction-panel/camera-tour-config.tsx b/src/components/src/side-panel/interaction-panel/camera-tour-config.tsx
new file mode 100644
index 000000000..ea3ac4265
--- /dev/null
+++ b/src/components/src/side-panel/interaction-panel/camera-tour-config.tsx
@@ -0,0 +1,976 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useContext, useId, useLayoutEffect, useRef, useState} from 'react';
+import styled from 'styled-components';
+import {useIntl} from 'react-intl';
+import {
+ CameraBookmark,
+ CameraSnapshot,
+ CameraTour,
+ CameraTourStop,
+ MapState
+} from '@kepler.gl/types';
+import {MapStateActions, UIStateActions, VisStateActions} from '@kepler.gl/actions';
+import {generateHashId} from '@kepler.gl/common-utils';
+import {getCameraSnapshot, normalizeCameraTour} from '@kepler.gl/utils';
+import {Button, Input, InlineInput, PanelContent, PanelLabel} from '../../common/styled-components';
+import {MapViewStateContext} from '../../map-view-state-context';
+import useCameraTourPlayback from './use-camera-tour-playback';
+import CameraPanelHeader, {CameraPanel, CameraIconButton} from './camera-panel-header';
+import {Play, Pause, Reset, Add, LocationMarker, Replace, Delete, Copy} from '../../common/icons';
+import {
+ DndContext,
+ PointerSensor,
+ closestCenter,
+ pointerWithin,
+ useSensor,
+ useSensors,
+ useDraggable,
+ useDroppable,
+ CollisionDetection
+} from '@dnd-kit/core';
+import {arrayMove} from '@dnd-kit/sortable';
+import {CSS} from '@dnd-kit/utilities';
+import {restrictToHorizontalAxis} from '@dnd-kit/modifiers';
+import PanelHeaderActionFactory from '../panel-header-action';
+import {Hint} from './zoom-opacity-config';
+import Portaled from '../../common/portaled';
+import {ContextMenu} from '../../common/context-menu';
+
+const PanelHeaderAction = PanelHeaderActionFactory();
+const TRACK_MODIFIERS = [restrictToHorizontalAxis];
+
+// Identical arrival times have identical targets. Resolve them as a one-place
+// move in the drag direction, rather than silently choosing DOM registration order.
+const timelineCollision = (
+ args: Parameters<CollisionDetection>[0],
+ stops: CameraTourStop[],
+ originX: number
+) => {
+ const hits = args.pointerCoordinates ? pointerWithin(args) : closestCenter(args);
+ if (hits.length < 2 || !args.pointerCoordinates) return hits;
+ const first = args.droppableRects.get(hits[0].id);
+ if (!first) return hits;
+ const tied = hits.filter(hit => {
+ const rect = args.droppableRects.get(hit.id);
+ return (
+ rect && Math.abs(rect.left - first.left) < 0.5 && Math.abs(rect.width - first.width) < 0.5
+ );
+ });
+ if (tied.length < 2) return hits;
+ const direction = Math.sign(args.pointerCoordinates.x - originX);
+ const from = stops.findIndex(stop => stop.id === args.active.id);
+ const ordered = tied.sort(
+ (a, b) => stops.findIndex(stop => stop.id === a.id) - stops.findIndex(stop => stop.id === b.id)
+ );
+ const target =
+ direction > 0
+ ? ordered.find(hit => stops.findIndex(stop => stop.id === hit.id) > from)
+ : direction < 0
+ ? [...ordered].reverse().find(hit => stops.findIndex(stop => stop.id === hit.id) < from)
+ : undefined;
+ const hit = target || tied.find(item => item.id === args.active.id);
+ return hit ? [hit] : [];
+};
+
+const Actions = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+ margin-bottom: 8px;
+ > button:first-child {
+ flex-shrink: 0;
+ }
+`;
+const TrackViewport = styled.div`
+ max-width: 100%;
+ margin-bottom: 8px;
+`;
+// Blocks use the full content width; only marker hit targets are clamped inward
+// at the endpoints. Zero-length intervals remain zero width.
+const StopTrack = styled.div`
+ position: relative;
+ height: 58px;
+ user-select: none;
+ &::before {
+ content: '';
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 16px;
+ border-top: 1px solid ${props => props.theme.textColor};
+ opacity: 0.25;
+ }
+`;
+const MarkerSlot = styled.div`
+ position: absolute;
+ top: 0;
+ width: 32px;
+ height: 32px;
+ margin-left: -16px;
+`;
+const TimeSegment = styled.button<{$travel: boolean; $selected: boolean}>`
+ position: absolute;
+ top: 34px;
+ height: 22px;
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ overflow: hidden;
+ white-space: nowrap;
+ cursor: pointer;
+ color: ${props => (props.$selected ? props.theme.textColorHl : props.theme.textColor)};
+ background: ${props =>
+ props.$travel
+ ? `repeating-linear-gradient(135deg, ${props.theme.panelContentBackground} 0 3px, ${props.theme.panelBackgroundHover} 3px 4px)`
+ : props.theme.panelBackgroundHover};
+ box-shadow: inset 0 0 0 1px
+ ${props => (props.$selected ? props.theme.activeColor : props.theme.panelBorderColor)};
+ font-size: 10px;
+ &:hover {
+ box-shadow: inset 0 0 0 2px ${props => props.theme.activeColor};
+ }
+ &:focus-visible {
+ outline: 2px solid ${props => props.theme.activeColor};
+ outline-offset: 1px;
+ z-index: 2;
+ }
+`;
+// The numbered marker is compact; its transparent button remains easy to target.
+const StopMarker = styled.button<{$selected: boolean; $dragging: boolean}>`
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ position: relative;
+ background: transparent;
+ border: 0;
+ color: ${props => (props.$selected ? props.theme.panelContentBackground : props.theme.textColor)};
+ cursor: ${props => (props.$dragging ? 'grabbing' : 'grab')};
+ width: 32px;
+ height: 32px;
+ padding: 0;
+ touch-action: none;
+ span {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ box-sizing: border-box;
+ min-width: 18px;
+ height: 18px;
+ padding: 0 3px;
+ border-radius: 9px;
+ border: 1px solid
+ ${props =>
+ props.$selected ? props.theme.activeColor : props.theme.sliderInactiveBorderColor};
+ background: ${props =>
+ props.$selected ? props.theme.activeColor : props.theme.panelBackground};
+ font-size: 10px;
+ line-height: 1;
+ font-weight: 600;
+ }
+ &[data-drop-target] span,
+ &:hover span {
+ border-color: ${props => props.theme.activeColor};
+ }
+ &:focus-visible {
+ outline: 2px solid ${props => props.theme.activeColor};
+ outline-offset: -2px;
+ border-radius: 3px;
+ }
+ &[aria-current='step']::after {
+ content: '';
+ position: absolute;
+ bottom: 1px;
+ width: 3px;
+ height: 3px;
+ border-radius: 50%;
+ background: ${props => props.theme.textColor};
+ }
+`;
+const StopEditor = styled.div`
+ border: 1px solid ${props => props.theme.panelBorderColor};
+ border-radius: 3px;
+ padding: 8px;
+`;
+const StopHeading = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin-bottom: 8px;
+`;
+const StopName = styled(InlineInput)`
+ min-width: 0;
+ flex: 1;
+ height: 24px;
+ padding: 2px 4px;
+ font-size: 12px;
+`;
+const StopActions = styled.div`
+ display: flex;
+ flex-shrink: 0;
+`;
+const StopActionButton = styled(CameraIconButton)`
+ width: 24px;
+ height: 24px;
+ flex-shrink: 0;
+ border-radius: 2px;
+ color: ${props => props.theme.textColor};
+ &:hover:not(:disabled) {
+ background: ${props => props.theme.panelBackgroundHover};
+ color: ${props => props.theme.textColorHl};
+ }
+ &:disabled {
+ opacity: 0.4;
+ }
+`;
+const Timing = styled.div`
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ align-items: end;
+ gap: 8px;
+ label {
+ min-width: 0;
+ margin-bottom: 0;
+ text-transform: none;
+ }
+ input {
+ width: 100%;
+ height: ${props => props.theme.inputBoxHeightSmall};
+ padding: ${props => props.theme.inputPaddingSmall};
+ font-size: ${props => props.theme.inputFontSizeSmall};
+ margin-top: 4px;
+ }
+`;
+const EndOfTour = styled.div`
+ color: ${props => props.theme.labelColor};
+ font-size: 11px;
+ span {
+ display: flex;
+ align-items: center;
+ height: ${props => props.theme.inputBoxHeightSmall};
+ margin-top: 4px;
+ }
+`;
+const Timeline = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin-top: 8px;
+`;
+const Scrubber = styled.input<{$progress: number}>`
+ appearance: none;
+ min-width: 24px;
+ flex: 1;
+ height: 24px;
+ margin: 0 4px;
+ background: transparent;
+ cursor: pointer;
+ &::-webkit-slider-runnable-track {
+ height: 3px;
+ border-radius: 2px;
+ background: linear-gradient(
+ to right,
+ ${props => props.theme.activeColor} ${props => props.$progress}%,
+ ${props => props.theme.sliderBarBgd} ${props => props.$progress}%
+ );
+ }
+ &::-moz-range-track {
+ height: 3px;
+ border-radius: 2px;
+ background: ${props => props.theme.sliderBarBgd};
+ }
+ &::-moz-range-progress {
+ height: 3px;
+ background: ${props => props.theme.activeColor};
+ }
+ &::-webkit-slider-thumb {
+ appearance: none;
+ width: 9px;
+ height: 9px;
+ margin-top: -3px;
+ border: 0;
+ border-radius: 50%;
+ background: ${props => props.theme.sliderHandleColor};
+ }
+ &::-moz-range-thumb {
+ width: 9px;
+ height: 9px;
+ border: 0;
+ border-radius: 50%;
+ background: ${props => props.theme.sliderHandleColor};
+ }
+ &:focus-visible {
+ outline: 2px solid ${props => props.theme.activeColor};
+ outline-offset: 1px;
+ }
+ &:disabled {
+ opacity: 0.4;
+ cursor: default;
+ }
+`;
+const TimeReadout = styled.div<{$elapsedWidth: number}>`
+ color: ${props => props.theme.textColor};
+ font-size: 10px;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ flex-shrink: 0;
+ output:first-child {
+ display: inline-block;
+ min-width: ${props => props.$elapsedWidth}ch;
+ text-align: right;
+ }
+`;
+const AddStopAnchor = styled.div`
+ position: relative;
+`;
+const MenuAnchor = styled.div`
+ position: absolute;
+ top: 100%;
+ left: 0;
+ width: 0;
+ height: 0;
+`;
+const SourceMenu = styled(ContextMenu)`
+ ${props => props.theme.dropdownList};
+ width: 226px;
+ min-width: 0;
+ max-width: calc(100vw - 80px);
+ max-height: min(280px, calc(100vh - 80px));
+ overflow-x: hidden;
+ button {
+ display: block;
+ width: 100%;
+ border: 0;
+ background: transparent;
+ text-align: left;
+ cursor: pointer;
+ &:focus-visible {
+ outline: 2px solid ${props => props.theme.activeColor};
+ outline-offset: -2px;
+ background: ${props => props.theme.dropdownListHighlightBg};
+ }
+ &:disabled {
+ opacity: 0.4;
+ cursor: default;
+ }
+ }
+ .list__item__anchor {
+ display: block;
+ }
+`;
+
+type StopSource = {key: string; label: string; disabled: boolean; bookmarkId?: string};
+
+function StopSourceMenu({
+ id,
+ label,
+ sources,
+ onSelect,
+ onClose
+}: {
+ id: string;
+ label: string;
+ sources: StopSource[];
+ onSelect: (source: StopSource) => void;
+ onClose: () => void;
+}) {
+ const menu = useRef<HTMLDivElement>(null);
+ useLayoutEffect(() => {
+ // Preserve focus by bookmark identity through list updates. If the focused
+ // source was removed or disabled, fall back to the first available source.
+ if (
+ !menu.current?.contains(document.activeElement) ||
+ (document.activeElement as HTMLButtonElement)?.disabled
+ ) {
+ menu.current?.querySelector<HTMLButtonElement>('button:not(:disabled)')?.focus();
+ }
+ }, [sources]);
+ return (
+ <SourceMenu
+ id={id}
+ ref={menu}
+ role="menu"
+ aria-label={label}
+ onKeyDown={event => {
+ if (event.key === 'Escape' || event.key === 'Tab') {
+ event.preventDefault();
+ event.stopPropagation();
+ onClose();
+ return;
+ }
+ if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return;
+ event.preventDefault();
+ const items = Array.from(
+ menu.current?.querySelectorAll<HTMLButtonElement>('button:not(:disabled)') || []
+ );
+ const index = items.indexOf(document.activeElement as HTMLButtonElement);
+ const next =
+ event.key === 'Home'
+ ? 0
+ : event.key === 'End'
+ ? items.length - 1
+ : (index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length;
+ items[next]?.focus();
+ }}
+ >
+ {sources.map(source => (
+ <button
+ key={source.key}
+ type="button"
+ role="menuitem"
+ className="list__item"
+ tabIndex={-1}
+ disabled={source.disabled}
+ onClick={() => onSelect(source)}
+ >
+ <span className="list__item__anchor" title={source.label}>
+ {source.label}
+ </span>
+ </button>
+ ))}
+ </SourceMenu>
+ );
+}
+
+function DraggableStopMarker({
+ stop,
+ index,
+ selected,
+ current,
+ panelId,
+ onSelect,
+ onMoveFocus,
+ markerRef,
+ position
+}: {
+ stop: CameraTourStop;
+ index: number;
+ selected: boolean;
+ current: boolean;
+ panelId: string;
+ onSelect: () => void;
+ onMoveFocus: (key: string) => void;
+ markerRef: (node: HTMLButtonElement | null) => void;
+ position: number;
+}) {
+ const intl = useIntl();
+ const {listeners, setNodeRef, transform, isDragging} = useDraggable({id: stop.id});
+ const {setNodeRef: setDropRef, isOver} = useDroppable({id: stop.id});
+ const label = `${intl.formatMessage({id: 'camera.stop', defaultMessage: 'Stop'})} ${index + 1}: ${
+ stop.name
+ }`;
+ return (
+ <MarkerSlot
+ ref={setDropRef}
+ className="camera-tour-marker-slot"
+ style={{
+ left: `clamp(16px, ${position}%, calc(100% - 16px))`,
+ zIndex: isDragging ? 4 : isOver ? 3 : selected ? 2 : 1
+ }}
+ >
+ <StopMarker
+ {...listeners}
+ ref={node => {
+ setNodeRef(node);
+ markerRef(node);
+ }}
+ id={`${panelId}-${stop.id}`}
+ type="button"
+ data-stop-id={stop.id}
+ data-dragging={isDragging || undefined}
+ $selected={selected}
+ $dragging={isDragging}
+ style={{transform: CSS.Translate.toString(transform)}}
+ data-drop-target={isOver || undefined}
+ aria-label={label}
+ title={label}
+ aria-pressed={selected}
+ aria-current={current ? 'step' : undefined}
+ aria-controls={`${panelId}-selected-stop`}
+ onClick={onSelect}
+ onKeyDown={event => {
+ if (!isDragging && ['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) {
+ event.preventDefault();
+ onMoveFocus(event.key);
+ } else if (!isDragging && event.key === 'Enter') {
+ event.preventDefault();
+ onSelect();
+ }
+ }}
+ >
+ <span aria-hidden="true">{index + 1}</span>
+ </StopMarker>
+ </MarkerSlot>
+ );
+}
+
+export type CameraTourConfigProps = {
+ tour?: CameraTour | null;
+ enabled?: boolean;
+ uiStateActions?: typeof UIStateActions;
+ bookmarks?: CameraBookmark[];
+ mapState?: MapState;
+ mapStateActions?: typeof MapStateActions;
+ visStateActions: typeof VisStateActions;
+};
+
+export default function CameraTourConfig({
+ tour,
+ enabled = true,
+ uiStateActions,
+ bookmarks = [],
+ mapState,
+ mapStateActions,
+ visStateActions
+}: CameraTourConfigProps) {
+ const panelId = `camera-tour-${useId()}`;
+ const [open, setOpen] = useState(false);
+ const [sourceMenuOpen, setSourceMenuOpen] = useState(false);
+ const [selectedId, setSelectedId] = useState<string | null>(null);
+ const intl = useIntl();
+ const message = (key: string, fallback: string) =>
+ intl.formatMessage({id: `camera.${key}`, defaultMessage: fallback});
+ const seconds = (time: number) =>
+ `${intl.formatNumber(time / 1000, {maximumFractionDigits: 2})} s`;
+ const {getInternalViewState} = useContext(MapViewStateContext);
+ const readCamera = () => getCameraSnapshot(getInternalViewState()) || getCameraSnapshot(mapState);
+ const supported = Boolean(mapState && !mapState.isSplit && !mapState.globe?.enabled);
+ const playback = useCameraTourPlayback(tour, mapStateActions?.updateMap, supported && enabled);
+ const stops = tour?.stops || [];
+ const selected = stops.find(stop => stop.id === selectedId) || stops[0];
+ const selectedIndex = selected ? stops.indexOf(selected) : -1;
+ const markerRefs = useRef(new Map<string, HTMLButtonElement>());
+ const addButton = useRef<HTMLButtonElement>(null);
+ const closeSourceMenu = () => {
+ setSourceMenuOpen(false);
+ addButton.current?.focus();
+ };
+ useLayoutEffect(() => {
+ if (sourceMenuOpen && (!bookmarks.length || !supported || !open)) {
+ setSourceMenuOpen(false);
+ addButton.current?.focus();
+ }
+ }, [sourceMenuOpen, bookmarks.length, supported, open]);
+ const sources: StopSource[] = [
+ {key: 'current', label: message('currentView', 'Current view'), disabled: !readCamera()},
+ ...bookmarks.map(bookmark => ({
+ key: `bookmark:${bookmark.id}`,
+ bookmarkId: bookmark.id,
+ label: bookmark.name,
+ disabled: !getCameraSnapshot(bookmark.camera)
+ }))
+ ];
+ const timingInputs = useRef<
+ Partial<Record<'holdDurationMs' | 'travelDurationMs', HTMLInputElement>>
+ >({});
+ const pendingTimingFocus = useRef<'holdDurationMs' | 'travelDurationMs' | null>(null);
+ const dragStops = useRef<CameraTourStop[] | null>(null);
+ const dragOriginX = useRef(0);
+ const focusRequest = useRef<string | null | undefined>(undefined);
+ useLayoutEffect(() => {
+ if (pendingTimingFocus.current) {
+ timingInputs.current[pendingTimingFocus.current]?.focus();
+ pendingTimingFocus.current = null;
+ }
+ if (focusRequest.current === undefined) return;
+ const target = focusRequest.current
+ ? markerRefs.current.get(focusRequest.current)
+ : addButton.current;
+ target?.focus();
+ focusRequest.current = undefined;
+ }, [stops, selectedId]);
+ const sensors = useSensors(useSensor(PointerSensor, {activationConstraint: {distance: 4}}));
+ let time = 0;
+ const starts = stops.map(stop => {
+ const start = time;
+ time += stop.holdDurationMs + stop.travelDurationMs;
+ return start;
+ });
+ const percent = (duration: number) =>
+ playback.duration > 0 && Number.isFinite(duration)
+ ? Math.max(0, Math.min(100, (duration / playback.duration) * 100))
+ : 0;
+ const focusTiming = (stop: CameraTourStop, field: 'holdDurationMs' | 'travelDurationMs') => {
+ playback.pause();
+ if (selected?.id === stop.id) timingInputs.current[field]?.focus();
+ else {
+ pendingTimingFocus.current = field;
+ setSelectedId(stop.id);
+ }
+ };
+ const currentIndex = starts.reduce(
+ (current, start, index) => (start <= playback.elapsed ? index : current),
+ 0
+ );
+ const commit = (next: CameraTourStop[]) => {
+ // Reject unsafe combined durations without clearing the existing tour.
+ if (next.length && !normalizeCameraTour({stops: next})) return false;
+ playback.pause();
+ visStateActions.setCameraTour(next.length ? {stops: next} : null);
+ return true;
+ };
+ const add = (camera: CameraSnapshot | null, name?: string) => {
+ if (!camera) return;
+ const id = generateHashId(6);
+ const saved = commit([
+ ...stops,
+ {
+ id,
+ name: name || `${message('stop', 'Stop')} ${stops.length + 1}`,
+ camera,
+ holdDurationMs: 2000,
+ travelDurationMs: 3000
+ }
+ ]);
+ if (saved) setSelectedId(id);
+ };
+ const update = (id: string, changes: Partial<CameraTourStop>) =>
+ commit(stops.map(stop => (stop.id === id ? {...stop, ...changes} : stop)));
+ const select = (index: number) => {
+ playback.pause();
+ setSelectedId(stops[index].id);
+ };
+ const stopActions = selected
+ ? [
+ {
+ key: 'goTo',
+ label: message('goTo', 'Go to'),
+ Icon: LocationMarker,
+ disabled: !enabled || !mapStateActions,
+ // Coincident arrivals share a time, but Go to targets the selected camera.
+ onClick: () => playback.seek(starts[selectedIndex], selected.camera)
+ },
+ {
+ key: 'pickCurrentLocation',
+ label: message('pickCurrentLocation', 'Pick current location'),
+ Icon: Replace,
+ disabled: !readCamera(),
+ onClick: () => {
+ const camera = readCamera();
+ if (camera) update(selected.id, {camera});
+ }
+ },
+ {
+ key: 'duplicate',
+ label: message('duplicate', 'Duplicate'),
+ Icon: Copy,
+ onClick: () => {
+ const id = generateHashId(6);
+ const next = [...stops];
+ next.splice(selectedIndex + 1, 0, {...selected, id, camera: {...selected.camera}});
+ if (commit(next)) {
+ focusRequest.current = id;
+ setSelectedId(id);
+ }
+ }
+ },
+ {
+ key: 'delete',
+ label: message('delete', 'Delete'),
+ Icon: Delete,
+ onClick: () => {
+ const next = stops.filter(stop => stop.id !== selected.id);
+ if (commit(next)) {
+ const id = next[Math.min(selectedIndex, next.length - 1)]?.id || null;
+ focusRequest.current = id;
+ setSelectedId(id);
+ }
+ }
+ }
+ ]
+ : [];
+
+ return (
+ <CameraPanel className="interaction-camera-tour">
+ <CameraPanelHeader
+ id={panelId}
+ title={message('animation', 'Camera animation')}
+ enableLabel={message('enableAnimation', 'Enable camera animation')}
+ open={open}
+ enabled={enabled}
+ onToggleOpen={() => setOpen(!open)}
+ onToggleEnabled={
+ uiStateActions
+ ? () => {
+ playback.pause();
+ uiStateActions.setMapControlVisibility('cameraTour', !enabled);
+ }
+ : undefined
+ }
+ Icon={Play}
+ />
+ {open && (
+ <PanelContent id={`${panelId}-content`}>
+ {!supported ? (
+ <p>{message('singleMap', 'Use a single 2D or 3D map to edit camera views.')}</p>
+ ) : (
+ <>
+ <Hint>{message('animationHint', 'Animate the map between saved views.')}</Hint>
+ <Actions>
+ <AddStopAnchor>
+ <Button
+ type="button"
+ secondary
+ small
+ ref={addButton}
+ disabled={sources.every(source => source.disabled)}
+ aria-haspopup={bookmarks.length ? 'menu' : undefined}
+ aria-expanded={bookmarks.length ? sourceMenuOpen : undefined}
+ aria-controls={sourceMenuOpen ? `${panelId}-sources` : undefined}
+ onClick={() => {
+ if (bookmarks.length) setSourceMenuOpen(!sourceMenuOpen);
+ else add(readCamera());
+ }}
+ onKeyDown={event => {
+ if (bookmarks.length && event.key === 'ArrowDown') {
+ event.preventDefault();
+ setSourceMenuOpen(true);
+ }
+ }}
+ >
+ <Add height="12px" aria-hidden="true" />
+ {message('addStop', 'Add stop')}
+ </Button>
+ <Portaled
+ component={MenuAnchor}
+ isOpened={sourceMenuOpen && bookmarks.length > 0}
+ left={0}
+ top={0}
+ onClose={closeSourceMenu}
+ >
+ <StopSourceMenu
+ id={`${panelId}-sources`}
+ label={message('addStop', 'Add stop')}
+ sources={sources}
+ onClose={closeSourceMenu}
+ onSelect={source => {
+ closeSourceMenu();
+ if (source.bookmarkId !== undefined) {
+ const bookmark = bookmarks.find(item => item.id === source.bookmarkId);
+ if (bookmark) add(getCameraSnapshot(bookmark.camera), bookmark.name);
+ } else add(readCamera());
+ }}
+ />
+ </Portaled>
+ </AddStopAnchor>
+ </Actions>
+ <DndContext
+ id={panelId}
+ sensors={sensors}
+ accessibility={{screenReaderInstructions: {draggable: ''}}}
+ modifiers={TRACK_MODIFIERS}
+ collisionDetection={args => timelineCollision(args, stops, dragOriginX.current)}
+ onDragStart={({activatorEvent}) => {
+ playback.pause();
+ dragStops.current = stops;
+ dragOriginX.current = (activatorEvent as PointerEvent).clientX;
+ if (selected) setSelectedId(selected.id);
+ }}
+ onDragCancel={() => {
+ dragStops.current = null;
+ }}
+ onDragEnd={({active, over}) => {
+ const unchanged = dragStops.current === stops;
+ dragStops.current = null;
+ if (!unchanged || !over || active.id === over.id) return;
+ const from = stops.findIndex(stop => stop.id === active.id);
+ const to = stops.findIndex(stop => stop.id === over.id);
+ if (from >= 0 && to >= 0) commit(arrayMove(stops, from, to));
+ }}
+ >
+ <TrackViewport hidden={!stops.length}>
+ <StopTrack role="group" aria-label={message('stopTrack', 'Animation stops')}>
+ {stops.map((stop, index) => (
+ <DraggableStopMarker
+ key={stop.id}
+ stop={stop}
+ index={index}
+ position={percent(starts[index])}
+ selected={selected?.id === stop.id}
+ current={currentIndex === index}
+ panelId={panelId}
+ onSelect={() => select(index)}
+ onMoveFocus={key => {
+ const next =
+ key === 'Home'
+ ? 0
+ : key === 'End'
+ ? stops.length - 1
+ : Math.max(
+ 0,
+ Math.min(stops.length - 1, index + (key === 'ArrowLeft' ? -1 : 1))
+ );
+ select(next);
+ markerRefs.current.get(stops[next].id)?.focus();
+ }}
+ markerRef={node => {
+ if (node) markerRefs.current.set(stop.id, node);
+ else markerRefs.current.delete(stop.id);
+ }}
+ />
+ ))}
+ {stops.flatMap((stop, index) =>
+ (['holdDurationMs', 'travelDurationMs'] as const).map(field => {
+ if (field === 'travelDurationMs' && index === stops.length - 1) return null;
+ const travel = field === 'travelDurationMs';
+ const label = `${message('stop', 'Stop')} ${index + 1}: ${stop.name} — ${
+ travel
+ ? message('travelSegment', 'Travel')
+ : message('holdSegment', 'Hold')
+ }: ${seconds(stop[field])}`;
+ return (
+ <TimeSegment
+ key={`${stop.id}-${field}`}
+ type="button"
+ tabIndex={stop[field] > 0 ? 0 : -1}
+ $travel={travel}
+ $selected={selected?.id === stop.id}
+ data-timing-stop-id={stop.id}
+ data-timing-field={field}
+ aria-label={label}
+ title={label}
+ aria-controls={`${panelId}-${field}`}
+ style={{
+ left: `${percent(
+ starts[index] + (travel ? stop.holdDurationMs : 0)
+ )}%`,
+ width: `${percent(stop[field])}%`
+ }}
+ onClick={() => focusTiming(stop, field)}
+ >
+ {seconds(stop[field])}
+ </TimeSegment>
+ );
+ })
+ )}
+ </StopTrack>
+ </TrackViewport>
+ </DndContext>
+ {selected && (
+ <>
+ <StopEditor
+ id={`${panelId}-selected-stop`}
+ role="group"
+ aria-labelledby={`${panelId}-${selected.id}`}
+ >
+ <StopHeading>
+ <StopName
+ aria-label={message('stopName', 'Stop name')}
+ title={selected.name}
+ value={selected.name}
+ onChange={event => update(selected.id, {name: event.target.value})}
+ />
+ <StopActions>
+ {stopActions.map(({key, label, Icon, disabled, onClick}) => (
+ <StopActionButton
+ key={key}
+ type="button"
+ aria-label={label}
+ title={label}
+ disabled={disabled}
+ onClick={onClick}
+ >
+ <PanelHeaderAction
+ id={`${panelId}-${key}`}
+ tooltip={`camera.${key}`}
+ flush
+ disabled={disabled}
+ IconComponent={Icon}
+ />
+ </StopActionButton>
+ ))}
+ </StopActions>
+ </StopHeading>
+ <Timing>
+ {(['holdDurationMs', 'travelDurationMs'] as const).map(key =>
+ key === 'travelDurationMs' && selectedIndex === stops.length - 1 ? (
+ <EndOfTour key={key}>
+ {message('travel', 'Travel to next (s)')}
+ <span>{message('endOfTour', 'End of tour')}</span>
+ </EndOfTour>
+ ) : (
+ <PanelLabel key={key}>
+ {key === 'holdDurationMs'
+ ? message('hold', 'Hold (s)')
+ : message('travel', 'Travel to next (s)')}
+ <Input
+ id={`${panelId}-${key}`}
+ ref={node => {
+ if (node) timingInputs.current[key] = node;
+ else delete timingInputs.current[key];
+ }}
+ type="number"
+ min={0}
+ step={0.1}
+ value={selected[key] / 1000}
+ onChange={event => {
+ const secondsValue = event.target.valueAsNumber;
+ if (
+ Number.isFinite(secondsValue) &&
+ secondsValue >= 0 &&
+ secondsValue * 1000 <= Number.MAX_SAFE_INTEGER
+ )
+ update(selected.id, {[key]: secondsValue * 1000});
+ }}
+ />
+ </PanelLabel>
+ )
+ )}
+ </Timing>
+ </StopEditor>
+ <Timeline>
+ <StopActionButton
+ type="button"
+ aria-label={
+ playback.playing ? message('pause', 'Pause') : message('play', 'Play')
+ }
+ title={playback.playing ? message('pause', 'Pause') : message('play', 'Play')}
+ disabled={!enabled || !playback.duration || !mapStateActions}
+ onClick={playback.playing ? playback.pause : playback.play}
+ >
+ {playback.playing ? <Pause height="16px" /> : <Play height="16px" />}
+ </StopActionButton>
+ <StopActionButton
+ type="button"
+ aria-label={message('restart', 'Restart')}
+ title={message('restart', 'Restart')}
+ disabled={!enabled || !mapStateActions}
+ onClick={() => playback.seek(0)}
+ >
+ <Reset height="14px" />
+ </StopActionButton>
+ <Scrubber
+ $progress={
+ playback.duration ? (playback.elapsed / playback.duration) * 100 : 0
+ }
+ type="range"
+ min={0}
+ max={playback.duration}
+ step="any"
+ value={playback.elapsed}
+ disabled={!enabled || !playback.duration || !mapStateActions}
+ aria-label={message('scrub', 'Camera tour time')}
+ aria-valuetext={seconds(playback.elapsed)}
+ onChange={event => playback.seek(Number(event.target.value))}
+ />
+ <TimeReadout $elapsedWidth={seconds(playback.duration).length + 3}>
+ <output aria-label={message('elapsed', 'Elapsed time')}>
+ {seconds(playback.elapsed)}
+ </output>{' '}
+ /{' '}
+ <output aria-label={message('duration', 'Tour duration')}>
+ {seconds(playback.duration)}
+ </output>
+ </TimeReadout>
+ </Timeline>
+ </>
+ )}
+ </>
+ )}
+ </PanelContent>
+ )}
+ </CameraPanel>
+ );
+}
diff --git a/src/components/src/side-panel/interaction-panel/use-camera-tour-playback.ts b/src/components/src/side-panel/interaction-panel/use-camera-tour-playback.ts
new file mode 100644
index 000000000..e50761668
--- /dev/null
+++ b/src/components/src/side-panel/interaction-panel/use-camera-tour-playback.ts
@@ -0,0 +1,108 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {useCallback, useContext, useEffect, useMemo, useRef, useState} from 'react';
+import {CameraSnapshot, CameraTour} from '@kepler.gl/types';
+import {MapStateActions} from '@kepler.gl/actions';
+import {evaluateCameraTour, getCameraTourDuration} from '@kepler.gl/utils';
+import {RootContext} from '../../context';
+
+/** Local playback state, separate from the saved tour and data/filter animation. */
+export default function useCameraTourPlayback(
+ tour: CameraTour | null | undefined,
+ updateMap: typeof MapStateActions.updateMap | undefined,
+ enabled: boolean
+) {
+ const root = useContext(RootContext);
+ const duration = useMemo(() => getCameraTourDuration(tour), [tour]);
+ const [elapsed, setElapsed] = useState(0);
+ const [playing, setPlaying] = useState(false);
+ const frame = useRef<number | null>(null);
+ const running = useRef(false);
+
+ const pause = useCallback(() => {
+ running.current = false;
+ if (frame.current !== null) window.cancelAnimationFrame(frame.current);
+ frame.current = null;
+ setPlaying(false);
+ }, []);
+
+ const apply = useCallback(
+ (time: number, camera = evaluateCameraTour(tour, time)) => {
+ if (camera && updateMap) updateMap({...camera, transitionDuration: 0});
+ setElapsed(time);
+ },
+ [tour, updateMap]
+ );
+
+ const seek = useCallback(
+ (time: number, camera?: CameraSnapshot) => {
+ pause();
+ if (enabled && Number.isFinite(time)) apply(Math.max(0, Math.min(duration, time)), camera);
+ },
+ [pause, enabled, apply, duration]
+ );
+
+ const play = useCallback(() => {
+ if (!enabled || !updateMap || duration <= 0) return;
+ pause();
+ const start = elapsed >= duration ? 0 : elapsed;
+ const origin = performance.now() - start;
+ running.current = true;
+ setPlaying(true);
+ apply(start);
+ const tick = (now: number) => {
+ if (!running.current) return;
+ const time = Math.max(0, Math.min(duration, now - origin));
+ apply(time);
+ if (time >= duration) pause();
+ else if (running.current) frame.current = window.requestAnimationFrame(tick);
+ };
+ frame.current = window.requestAnimationFrame(tick);
+ }, [enabled, updateMap, duration, pause, elapsed, apply]);
+
+ useEffect(() => {
+ pause();
+ setElapsed(0);
+ }, [tour, pause]);
+
+ useEffect(() => {
+ if (!enabled) pause();
+ }, [enabled, pause]);
+
+ useEffect(
+ () => () => {
+ running.current = false;
+ if (frame.current !== null) window.cancelAnimationFrame(frame.current);
+ },
+ []
+ );
+
+ useEffect(() => {
+ if (!playing) return;
+ const element = root?.current;
+ const interrupt = (event: Event) => {
+ // Capture phase pauses before a map gesture or navigation button changes the camera.
+ if (
+ event.target instanceof Element &&
+ event.target.closest(
+ '.maps, .geocoder-panel, .interaction-camera-bookmarks, .camera-bookmark-panel'
+ )
+ )
+ pause();
+ };
+ const onVisibility = () => {
+ if (document.hidden) pause();
+ };
+ for (const event of ['pointerdown', 'wheel', 'keydown', 'click'])
+ element?.addEventListener(event, interrupt, true);
+ document.addEventListener('visibilitychange', onVisibility);
+ return () => {
+ for (const event of ['pointerdown', 'wheel', 'keydown', 'click'])
+ element?.removeEventListener(event, interrupt, true);
+ document.removeEventListener('visibilitychange', onVisibility);
+ };
+ }, [playing, pause, root]);
+
+ return {elapsed, duration, playing, play, pause, seek};
+}
diff --git a/src/components/src/types.ts b/src/components/src/types.ts
index ec52524f2..852a96e84 100644
--- a/src/components/src/types.ts
+++ b/src/components/src/types.ts
@@ -7,6 +7,7 @@ import {Layer, LayerClassesType} from '@kepler.gl/layers';
import {
Annotation,
CameraBookmark,
+ CameraTour,
Filter,
InteractionConfig,
MapState,
@@ -41,6 +42,7 @@ export type SidePanelProps = {
layers: Layer[];
annotations?: Annotation[];
cameraBookmarks?: CameraBookmark[];
+ cameraTour?: CameraTour | null;
layerClasses: LayerClassesType;
layerOrder: LayerOrder;
mapStyle: MapStyle;
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index ea6d70080..214f96dfe 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -1057,6 +1057,28 @@ ${'```'}
copyCoordinates: 'Copy coordinates',
copiedCoordinates: 'Coordinates copied',
copyFailed: 'Could not copy coordinates',
+ animation: 'Camera animation',
+ animationHint: 'Animate the map between saved views.',
+ enableAnimation: 'Enable camera animation',
+ stop: 'Stop',
+ stopName: 'Stop name',
+ stopTrack: 'Animation stops',
+ holdSegment: 'Hold',
+ travelSegment: 'Travel',
+ pickCurrentLocation: 'Pick current location',
+ currentView: 'Current view',
+ addStop: 'Add stop',
+ endOfTour: 'End of tour',
+ hold: 'Hold (s)',
+ travel: 'Travel to next (s)',
+ duplicate: 'Duplicate',
+ goToStop: 'Go to stop',
+ scrub: 'Camera tour time',
+ elapsed: 'Elapsed time',
+ duration: 'Tour duration',
+ pause: 'Pause',
+ play: 'Play',
+ restart: 'Restart',
bookmarks: 'Bookmarks',
bookmark: 'Bookmark',
bookmarkName: 'Bookmark name',
diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.ts
index 0f2777965..9b38dd377 100644
--- a/src/reducers/src/ui-state-updaters.ts
+++ b/src/reducers/src/ui-state-updaters.ts
@@ -128,6 +128,7 @@ export const DEFAULT_MAP_CONTROLS: MapControls = {
{} as MapControls
),
// Camera controls are UI preferences; saved camera snapshots remain independent.
+ cameraTour: {...DEFAULT_MAP_CONTROLS_FEATURES},
cameraBookmarks: {
...DEFAULT_MAP_CONTROLS_FEATURES,
show: false,
@@ -506,7 +507,9 @@ export const setMapControlVisibilityUpdater = (
): UiState => {
const mapControl =
state.mapControls?.[panelId] ??
- (panelId === 'cameraBookmarks' ? DEFAULT_MAP_CONTROLS.cameraBookmarks : undefined);
+ (panelId === 'cameraBookmarks' || panelId === 'cameraTour'
+ ? DEFAULT_MAP_CONTROLS[panelId]
+ : undefined);
if (!mapControl) {
return state;
}
@@ -537,9 +540,9 @@ export const setMapControlSettingsUpdater = (
{payload: {panelId, settings}}: UIStateActions.setMapControlSettingsUpdaterAction
): UiState => {
const mapControl = (state.mapControls?.[panelId] ??
- (panelId === 'cameraBookmarks'
- ? DEFAULT_MAP_CONTROLS.cameraBookmarks
- : undefined)) as MapControlMapLegend | undefined;
+ (panelId === 'cameraBookmarks' ? DEFAULT_MAP_CONTROLS.cameraBookmarks : undefined)) as
+ | MapControlMapLegend
+ | undefined;
if (!mapControl) {
return state;
}
@@ -1190,6 +1193,27 @@ export const receiveMapConfigUpdater = (
};
}
+ const savedBookmarks = uiState.mapControls?.cameraBookmarks;
+ if (typeof savedBookmarks?.show === 'boolean') {
+ newState = {
+ ...newState,
+ mapControls: {
+ ...newState.mapControls,
+ cameraBookmarks: {
+ ...DEFAULT_MAP_CONTROLS.cameraBookmarks!,
+ ...newState.mapControls.cameraBookmarks,
+ show: savedBookmarks.show,
+ activeMapIndex: 0
+ }
+ }
+ };
+ }
+ if (savedBookmarks?.settings) {
+ newState = setMapControlSettingsUpdater(newState, {
+ payload: {panelId: 'cameraBookmarks', settings: savedBookmarks.settings}
+ } as UIStateActions.setMapControlSettingsUpdaterAction);
+ }
+
if (uiState.mapControls?.mapLegend?.settings) {
newState = setMapControlSettingsUpdater(newState, {
payload: {panelId: 'mapLegend', settings: uiState.mapControls.mapLegend.settings}
diff --git a/src/schemas/src/ui-state-schema.ts b/src/schemas/src/ui-state-schema.ts
index b6ba49513..bcb05e8df 100644
--- a/src/schemas/src/ui-state-schema.ts
+++ b/src/schemas/src/ui-state-schema.ts
@@ -30,6 +30,21 @@ export const propertiesV1 = {
},
key: 'chart'
}),
+ cameraBookmarks: new Schema({
+ version: VERSIONS.v1,
+ properties: {
+ show: null,
+ settings: new Schema({
+ version: VERSIONS.v1,
+ properties: {
+ position: null,
+ contentHeight: null
+ },
+ key: 'settings'
+ })
+ },
+ key: 'cameraBookmarks'
+ }),
mapInfo: new Schema({
version: VERSIONS.v1,
properties: {
diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.ts
index fe6d503fb..b82f57bec 100644
--- a/src/types/schemas.d.ts
+++ b/src/types/schemas.d.ts
@@ -3,7 +3,14 @@
import {RGBColor, Merge, RequireFrom} from './types';
-import {Filter, InteractionConfig, AnimationConfig, SplitMap, Feature} from './reducers';
+import {
+ Filter,
+ InteractionConfig,
+ AnimationConfig,
+ SplitMap,
+ Feature,
+ MapLegendControlSettings
+} from './reducers';
import {LayerTextLabel} from './layers';
import {ChartConfig} from './charts';
@@ -188,6 +195,10 @@ export type ParsedUiState = {
active?: boolean;
show?: boolean;
};
+ cameraBookmarks?: {
+ show?: boolean;
+ settings?: Partial<MapLegendControlSettings>;
+ };
};
locale?: string;
theme?: string;
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 67e9b7d18..cb755348f 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -261,6 +261,12 @@ export type KeplerApplicationConfig = {
*/
enableMapInfo?: boolean;
+ /** Whether to show the Bookmarks panel in Interactions. Enabled by default. */
+ enableCameraBookmarks?: boolean;
+
+ /** Whether to show the Camera animation panel in Interactions. Enabled by default. */
+ enableCameraTour?: boolean;
+
/**
* Master switch for power-user JSON editors. When false, every section editor is hidden.
* Defaults to true; each section also has its own flag.
@@ -497,6 +503,10 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableMapInfo: true,
+ enableCameraBookmarks: true,
+
+ enableCameraTour: true,
+
enableJsonEditors: true,
enableLayerJsonEditor: true,
enableFilterJsonEditor: true,
diff --git a/test/browser/components/side-panel/interaction-manager-test.js b/test/browser/components/side-panel/interaction-manager-test.js
index 49652c483..c7a3981cb 100644
--- a/test/browser/components/side-panel/interaction-manager-test.js
+++ b/test/browser/components/side-panel/interaction-manager-test.js
@@ -6,11 +6,12 @@ import test from 'tape';
import sinon from 'sinon';
import {mount} from 'enzyme';
import {ThemeProvider} from 'styled-components';
+import {render, within} from '@testing-library/react';
import {InteractionManagerFactory, appInjector} from '@kepler.gl/components';
import {defaultInteractionConfig, getZoomOpacityAnnotationTargetId} from '@kepler.gl/reducers';
import {theme} from '@kepler.gl/styles';
-import {initApplicationConfig} from '@kepler.gl/utils';
+import {getApplicationConfig, initApplicationConfig} from '@kepler.gl/utils';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
const InteractionManager = appInjector.get(InteractionManagerFactory);
@@ -22,6 +23,58 @@ global.ResizeObserver = class ResizeObserver {
const panelMetadata = {id: 'interaction', label: 'sidebar.panels.interaction'};
+test('Components -> InteractionManager camera panels follow application config independently', t => {
+ const {enableCameraBookmarks, enableCameraTour} = getApplicationConfig();
+ const originalFlags = {enableCameraBookmarks, enableCameraTour};
+ try {
+ for (const flags of [
+ {},
+ {enableCameraBookmarks: false},
+ {enableCameraTour: false},
+ {enableCameraBookmarks: false, enableCameraTour: false},
+ {enableCameraBookmarks: true, enableCameraTour: true}
+ ]) {
+ initApplicationConfig({...originalFlags, ...flags});
+ const rendered = render(
+ <ThemeProvider theme={theme}>
+ <IntlWrapper>
+ <InteractionManager
+ interactionConfig={{}}
+ datasets={{}}
+ panelMetadata={panelMetadata}
+ cameraBookmarksEnabled={true}
+ cameraTourEnabled={true}
+ visStateActions={{
+ interactionConfigChange: () => {},
+ setColumnDisplayFormat: () => {}
+ }}
+ />
+ </IntlWrapper>
+ </ThemeProvider>
+ );
+ try {
+ const panel = within(rendered.container);
+ t.equal(
+ Boolean(panel.queryByRole('button', {name: 'Bookmarks'})),
+ flags.enableCameraBookmarks !== false,
+ `bookmark panel visibility for ${JSON.stringify(flags)}`
+ );
+ t.equal(
+ Boolean(panel.queryByRole('button', {name: 'Camera animation'})),
+ flags.enableCameraTour !== false,
+ `animation panel visibility for ${JSON.stringify(flags)}`
+ );
+ } finally {
+ rendered.unmount();
+ rendered.container.remove();
+ }
+ }
+ } finally {
+ initApplicationConfig(originalFlags);
+ }
+ t.end();
+});
+
function expandLegend(wrapper) {
wrapper.find('.interaction-legend__header').hostNodes().at(0).simulate('click');
wrapper.update();
diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.js
index 592bcf284..39e6f93ae 100644
--- a/test/node/reducers/composer-state-test.js
+++ b/test/node/reducers/composer-state-test.js
@@ -11,9 +11,10 @@ import {
confirmReplaceDataset,
loadFilesSuccess,
registerEntry,
- stageLoadedFiles
+ stageLoadedFiles,
+ wrapTo
} from '@kepler.gl/actions';
-import {processCsvData} from '@kepler.gl/processors';
+import {processCsvData, processKeplerglJSON} from '@kepler.gl/processors';
import keplerGlReducer, {
addDataToMapUpdater,
replaceDataInMapUpdater,
@@ -26,7 +27,7 @@ import keplerGlReducer, {
import {MapSplitMode} from '@kepler.gl/constants';
import KeplerGlSchema from '@kepler.gl/schemas';
import {KeplerTable} from '@kepler.gl/table';
-import {getTimeBins} from '@kepler.gl/utils';
+import {getTimeBins, getMapJSON, exportToJsonString} from '@kepler.gl/utils';
import testCsvData, {sampleConfig, dataWithNulls} from 'test/fixtures/test-csv-data';
import testHexIdData, {
@@ -921,7 +922,7 @@ test('#composerStateReducer - dataset replacement preserves data-independent boo
t.end();
});
-test('#composerStateReducer - loading saved bookmarks does not opt in or reset UI visibility', t => {
+test('#composerStateReducer - legacy bookmarks do not opt in or reset an explicit host preference', 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}}
@@ -930,6 +931,7 @@ test('#composerStateReducer - loading saved bookmarks does not opt in or reset U
...initial,
visState: {...initial.visState, cameraBookmarks: bookmarks}
});
+ delete config.config.uiState.mapControls.cameraBookmarks; // Legacy files have no preference.
const {cameraBookmarks, ...legacyControls} = initial.uiState.mapControls;
for (const controls of [
initial.uiState.mapControls,
@@ -950,6 +952,114 @@ test('#composerStateReducer - loading saved bookmarks does not opt in or reset U
t.end();
});
+
+test('#composerStateReducer - project JSON bookmark visibility and layout survive file import', 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 settings = {
+ position: {x: 42, y: 64, anchorX: 'left', anchorY: 'bottom'},
+ contentHeight: 80
+ };
+ for (const show of [true, false]) {
+ for (const isSplit of [false, true]) {
+ const source = {
+ ...initial,
+ visState: {...initial.visState, cameraBookmarks: bookmarks},
+ mapState: {...initial.mapState, isSplit},
+ uiState: {
+ ...initial.uiState,
+ mapControls: {
+ ...initial.uiState.mapControls,
+ cameraBookmarks: {
+ ...initial.uiState.mapControls.cameraBookmarks,
+ show,
+ settings,
+ activeMapIndex: 1
+ }
+ }
+ }
+ };
+ // This is the same JSON construction and parsing used by project export/import.
+ const json = JSON.parse(exportToJsonString(getMapJSON(source, {hasData: true})));
+ t.deepEqual(
+ json.config.config.uiState.mapControls.cameraBookmarks,
+ {show, settings},
+ 'project JSON carries visibility and layout only'
+ );
+ const {cameraBookmarks, ...legacyControls} = initial.uiState.mapControls;
+ for (const controls of [
+ legacyControls,
+ {
+ ...initial.uiState.mapControls,
+ cameraBookmarks: {...cameraBookmarks, show: !show, activeMapIndex: 1}
+ }
+ ]) {
+ const target = {...initial, uiState: {...initial.uiState, mapControls: controls}};
+ const imported = keplerGlReducer(
+ {test: target},
+ wrapTo(
+ 'test',
+ loadFilesSuccess(
+ [
+ {
+ info: {format: 'keplergl', label: 'saved-map.json'},
+ data: processKeplerglJSON(json)
+ }
+ ],
+ {centerMap: false}
+ )
+ )
+ ).test;
+ t.equal(
+ imported.uiState.mapControls.cameraBookmarks.show,
+ show,
+ 'restores explicit visibility over the target preference'
+ );
+ t.deepEqual(
+ imported.uiState.mapControls.cameraBookmarks.settings,
+ settings,
+ 'restores floating panel layout'
+ );
+ t.equal(
+ imported.uiState.mapControls.cameraBookmarks.activeMapIndex,
+ 0,
+ 'does not restore transient split-map index'
+ );
+ t.deepEqual(imported.visState.cameraBookmarks, bookmarks, 'preserves saved camera data');
+ t.equal(imported.mapState.isSplit, isSplit, 'preserves the saved map mode');
+ }
+ }
+ }
+ const legacyJson = JSON.parse(exportToJsonString(getMapJSON(initial, {hasData: true})));
+ delete legacyJson.config.config.uiState.mapControls.cameraBookmarks;
+ for (const withUiState of [true, false]) {
+ const json = JSON.parse(JSON.stringify(legacyJson));
+ if (!withUiState) delete json.config.config.uiState;
+ const imported = keplerGlReducer(
+ {test: initial},
+ wrapTo(
+ 'test',
+ loadFilesSuccess(
+ [{info: {format: 'keplergl', label: 'legacy.json'}, data: processKeplerglJSON(json)}],
+ {centerMap: false}
+ )
+ )
+ ).test;
+ t.equal(
+ imported.uiState.mapControls.cameraBookmarks.show,
+ false,
+ 'legacy project defaults 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.js
index dc28479b4..9edf3b67b 100644
--- a/test/node/reducers/ui-state-test.js
+++ b/test/node/reducers/ui-state-test.js
@@ -557,7 +557,11 @@ test('#uiStateReducer -> bookmarks default off and legacy controls can opt in',
);
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');
+ t.equal(
+ loaded.mapControls.cameraBookmarks?.show === true,
+ false,
+ 'legacy load does not opt in'
+ );
}
const positioned = reducer(
initial,
@@ -574,7 +578,11 @@ test('#uiStateReducer -> bookmarks default off and legacy controls can opt in',
'legacy settings updates work'
);
const enabled = reducer(initial, setMapControlVisibility('cameraBookmarks', true));
- t.equal(enabled.mapControls.cameraBookmarks.show, true, 'legacy control can be enabled directly');
+ 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));
@@ -584,7 +592,11 @@ test('#uiStateReducer -> bookmarks default off and legacy controls can opt in',
90,
'disable keeps layout settings'
);
- t.deepEqual(disabled.mapControls.mapLegend, initial.mapControls.mapLegend, 'legend is unchanged');
+ t.deepEqual(
+ disabled.mapControls.mapLegend,
+ initial.mapControls.mapLegend,
+ 'legend is unchanged'
+ );
}
t.end();
});
@@ -609,3 +621,26 @@ test('#uiStateReducer -> explicit bookmark opt-in survives initialization and le
}
t.end();
});
+
+test('#uiStateReducer -> camera animation visibility is independent of bookmarks', t => {
+ const {cameraTour, ...legacyControls} = INITIAL_UI_STATE.mapControls;
+ t.equal(cameraTour.show, true, 'enabled initially');
+ for (const initial of [
+ INITIAL_UI_STATE,
+ uiStateReducerFactory({mapControls: legacyControls})(undefined, {}),
+ reducer(INITIAL_UI_STATE, keplerGlInit({initialUiState: {mapControls: legacyControls}}))
+ ]) {
+ t.equal(
+ initial.mapControls.cameraTour?.show !== false,
+ true,
+ 'missing/default control is enabled'
+ );
+ const state = reducer(initial, setMapControlVisibility('cameraTour', false));
+ const {cameraTour: disabledTour, ...otherControls} = state.mapControls;
+ t.equal(disabledTour.show, false, 'disables camera animation');
+ t.deepEqual(otherControls, legacyControls, 'does not change other controls');
+ const enabled = reducer(state, setMapControlVisibility('cameraTour', true));
+ t.equal(enabled.mapControls.cameraTour.show, true, 'can enable it again');
+ }
+ t.end();
+});
diff --git a/test/node/schemas/ui-state-schema-test.js b/test/node/schemas/ui-state-schema-test.js
index 01d9e163c..30b1e7d78 100644
--- a/test/node/schemas/ui-state-schema-test.js
+++ b/test/node/schemas/ui-state-schema-test.js
@@ -23,7 +23,15 @@ test('#uiStateSchema -> v1 -> save load uiState', t => {
t.equal(uiToSave.theme, 'dark', 'default theme should be dark');
t.deepEqual(
uiToSave.mapControls,
- {mapLegend: {active: false}, chart: {active: false}, mapInfo: {active: true, show: true}},
+ {
+ mapLegend: {active: false},
+ chart: {active: false},
+ mapInfo: {active: true, show: true},
+ cameraBookmarks: {
+ show: false,
+ settings: initialState.uiState.mapControls.cameraBookmarks.settings
+ }
+ },
'default mapLegend and chart should be inactive and map info open'
);
@@ -67,3 +75,45 @@ test('#uiStateSchema -> v1 -> save load uiState with mapLegend active and locale
t.end();
});
+
+test('#uiStateSchema -> bookmark preferences persist without transient control state', t => {
+ const settings = {
+ position: {x: 42, y: 64, anchorX: 'left', anchorY: 'bottom'},
+ contentHeight: 80
+ };
+ for (const show of [true, false]) {
+ const state = cloneDeep(InitialState);
+ state.uiState.mapControls.cameraBookmarks = {
+ ...state.uiState.mapControls.cameraBookmarks,
+ show,
+ activeMapIndex: 1,
+ disableClose: true,
+ settings: {...settings, temporary: 'not saved'}
+ };
+ const saved = SchemaManager.getConfigToSave(state);
+ t.deepEqual(
+ saved.config.uiState.mapControls.cameraBookmarks,
+ {show, settings},
+ `${show}: saves only visibility and layout`
+ );
+ for (const version of ['v0', 'v1']) {
+ const parsed = SchemaManager.parseSavedConfig({
+ version,
+ config: {uiState: saved.config.uiState}
+ });
+ t.deepEqual(
+ parsed.uiState.mapControls.cameraBookmarks,
+ {show, settings},
+ `${version}: reads preferences`
+ );
+ }
+ }
+ for (const version of ['v0', 'v1']) {
+ const parsed = SchemaManager.parseSavedConfig({version, config: {uiState: {mapControls: {}}}});
+ t.notOk(
+ 'cameraBookmarks' in parsed.uiState.mapControls,
+ `${version}: missing legacy preference stays absent`
+ );
+ }
+ t.end();
+});