Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: copy coordinates and annotation actions in the map context menu (#3782)
Igor Dykhta5b118cd54e7d
diff --git a/src/charts/src/aggregation.ts b/src/charts/src/aggregation.tsindex 82ddfb50a..6beffae21 100644--- a/src/charts/src/aggregation.ts+++ b/src/charts/src/aggregation.ts@@ -789,7 +789,7 @@ export function buildHeatmapCells({if (!xAxis?.field?.name || !yAxis?.field?.name) {return [];}- // Cap both axes at 10×10 (Studio-style labeled table).+ // Cap both axes at 10×10 for a labeled table.const limit = Math.min(Math.max(1, numGroups > 0 ? numGroups : DEFAULT_NUM_GROUPS),DEFAULT_NUM_GROUPSdiff --git a/src/charts/src/chart-views.tsx b/src/charts/src/chart-views.tsxindex 0291d8121..9d35f63d0 100644--- a/src/charts/src/chart-views.tsx+++ b/src/charts/src/chart-views.tsx@@ -258,7 +258,7 @@ function getVerticalBarLabelLayout(bins: ChartBin[]): {const maxLen = Math.max(1, ...bins.map(bin => displayBinKey(String(bin.key)).length));const slotWidth = VERTICAL_BAR_PLOT_WIDTH / Math.max(1, bins.length);const labelWidth = maxLen * LABEL_CHAR_WIDTH;- // Keep short labels horizontal (Studio-like); rotate when they won't fit in their slot.+ // Keep short labels horizontal; rotate when they won't fit in their slot.const rotated = labelWidth > slotWidth * 0.9 || maxLen > 8;if (!rotated) {return {rotated: false, labelBand: 5, padRight: 0, gap: 6};diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex ca670da6b..d37834252 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -18,6 +18,15 @@ import {VisStateActions, MapStateActions, UIStateActions} from '@kepler.gl/actioimport MapPopoverFactory from './map/map-popover';import MapControlFactory from './map/map-control';import MapScaleFactory from './map/map-scale';+import MapCoordinateMenu, {+ annotationContextMenuItems,+ coordinateMenuFromClick,+ contextMenuTargetIsMapOverlay,+ coordinateMenuHiddenByTooltip,+ isFeatureActionPanelOpen,+ isRightDrag,+ CoordinateMenuState+} from './map/map-coordinate-menu';import {StyledMapContainer} from './common/styled-components';import {Attribution,@@ -75,6 +84,8 @@ import {import {FILTER_TYPES,GEOCODER_LAYER_ID,+ EDITOR_LAYER_ID,+ EDITOR_LAYER_PICKING_RADIUS,THROTTLE_NOTIFICATION_TIME,DEFAULT_PICKING_RADIUS,NO_MAP_ID,@@ -309,9 +320,13 @@ export default function MapContainerFactory(showBaseMapLibLogo: false,// attribution strings collected from the resolved map sources (e.g. CARTO,// OpenFreeMap). Populated after TileJSON resolves.- basemapAttributions: [] as string[]+ basemapAttributions: [] as string[],+ coordinateMenu: null as CoordinateMenuState | null};+ // Right-button press origin, used to ignore rotate/pitch drags.+ _rightPress: {x: number; y: number} | null = null;+componentDidMount() {if (!this._ref.current) {return;@@ -332,6 +347,9 @@ export default function MapContainerFactory(}componentDidUpdate(prevProps) {+ if (this.state.coordinateMenu && this._coordinateMenuSuppressed()) {+ this.setState({coordinateMenu: null});+ }if (prevProps.mapStyle.styleType !== this.props.mapStyle.styleType) {this._removeBasemapAttributionListeners();if (this.props.mapStyle.styleType === NO_MAP_ID) {@@ -476,6 +494,155 @@ export default function MapContainerFactory(this.props.visStateActions.onLayerClick(null);};+ _closeCoordinateMenu = () => {+ if (this.state.coordinateMenu) {+ this.setState({coordinateMenu: null});+ }+ };++ _onMapPointerDownCapture = (event: React.PointerEvent<HTMLDivElement>) => {+ if (event.button === 2) {+ this._rightPress = {x: event.clientX, y: event.clientY};+ }+ };++ /**+ * A polygon or polygon filter under the cursor owns this right-click.+ * Its action panel (Filter layers) is anchored at the same pixel.+ */+ _rightClickHitsEditorFeature(clientX: number, clientY: number): boolean {+ const deck = this._deck;+ const canvas = deck?.canvas || deck?.getCanvas?.();+ const rect = canvas?.getBoundingClientRect?.();+ if (!deck?.pickMultipleObjects || !rect) {+ return false;+ }+ try {+ const picks = deck.pickMultipleObjects({+ x: clientX - rect.left,+ y: clientY - rect.top,+ radius: EDITOR_LAYER_PICKING_RADIUS,+ layerIds: [EDITOR_LAYER_ID]+ });+ return Array.isArray(picks) && picks.some(pick => pick?.object);+ } catch {+ return false;+ }+ }++ /**+ * Copy coordinates stays hidden when this right-click belongs to a tooltip+ * or to the polygon / filter action panel.+ */+ _coordinateMenuSuppressed(clientX?: number, clientY?: number): boolean {+ const {visState, index} = this.props;+ return (+ isFeatureActionPanelOpen(visState.editor, index) ||+ coordinateMenuHiddenByTooltip(+ Boolean(visState.interactionConfig.tooltip?.enabled),+ visState.hoverInfo?.layer?.id+ ) ||+ (clientX !== undefined &&+ clientY !== undefined &&+ this._rightClickHitsEditorFeature(clientX, clientY))+ );+ }++ _annotationMenuItems() {+ const {readOnly, visState} = this.props;+ const annotations = visState.annotations ?? [];+ return annotationContextMenuItems({+ annotationsEnabled: Boolean(getApplicationConfig().enableAnnotations),+ readOnly,+ annotationCount: annotations.length,+ hiddenAnnotationCount: annotations.filter(annotation => !annotation.isVisible).length+ });+ }++ /** Hide and show write each annotation, the same flag the panel eye uses. */+ _setEachAnnotationVisible(isVisible: boolean) {+ const {visState, visStateActions} = this.props;+ for (const annotation of visState.annotations ?? []) {+ if (annotation.isVisible !== isVisible) {+ visStateActions.updateAnnotation(annotation.id, {isVisible});+ }+ }+ }++ _onAddAnnotation = () => {+ const menu = this.state.coordinateMenu;+ if (!menu) {+ return;+ }+ // A new annotation belongs with the rest of the set, so bring hidden ones back.+ this._setEachAnnotationVisible(true);+ const {index, mapControls, uiStateActions, visStateActions} = this.props;+ if (!mapControls?.annotation?.active) {+ uiStateActions.toggleMapControl('annotation', Number(index ?? 0));+ }+ visStateActions.addAnnotation({+ anchorPoint: menu.coordinate,+ mapIndex: index ?? 0+ });+ this._closeCoordinateMenu();+ };++ _onToggleAnnotations = () => {+ this._setEachAnnotationVisible(!this._annotationMenuItems().annotationsVisible);+ this._closeCoordinateMenu();+ };++ /**+ * Browser context menu stays suppressed. A click (not a right-drag) can+ * copy "lat, lng", add an annotation, or hide and show annotations.+ * A feature with tooltips enabled pins the tooltip instead of opening the menu.+ */+ _onMapContextMenu = (event: React.MouseEvent<HTMLDivElement>) => {+ event.preventDefault();++ const start = this._rightPress;+ this._rightPress = null;+ if (+ isRightDrag(start, event.clientX, event.clientY) ||+ contextMenuTargetIsMapOverlay(event.target) ||+ this._coordinateMenuSuppressed(event.clientX, event.clientY)+ ) {+ this._closeCoordinateMenu();+ return;+ }++ const {isExport, visState, mapState, index} = this.props;+ const annotationItems = this._annotationMenuItems();+ if (+ isExport ||+ (!visState.interactionConfig.coordinate.enabled &&+ !annotationItems.showAddAnnotation &&+ !annotationItems.showAnnotationToggle)+ ) {+ this._closeCoordinateMenu();+ return;+ }++ const bounds = this._ref.current?.getBoundingClientRect();+ if (!bounds) {+ this._closeCoordinateMenu();+ return;+ }++ const internalViewState = this.context?.getInternalViewState(index);+ const viewport = getViewportFromMapState({+ ...mapState,+ ...internalViewState+ }) as {+ unproject: (xyz: number[], opts?: {targetZ?: number}) => number[];+ };++ const coordinateMenu = coordinateMenuFromClick(event.clientX, event.clientY, bounds, point =>+ viewport.unproject(point, {targetZ: 0})+ );+ this.setState({coordinateMenu});+ };+_onLayerHover = (_idx: number, info: PickingInfo<any> | null) => {this.props.visStateActions.onLayerHover(info, this.props.index);};@@ -1670,11 +1837,34 @@ export default function MapContainerFactory(<StyledMapref={this._ref}style={this.styleSelector(this.props)}- onContextMenu={event => event.preventDefault()}+ onPointerDownCapture={this._onMapPointerDownCapture}+ onContextMenu={this._onMapContextMenu}$mixBlendMode={visState.overlayBlending}$mapLibCssClass={baseMapLibraryConfig.mapLibCssClass}>{mapContent}+ {this.state.coordinateMenu &&+ !this.props.isExport &&+ !isFeatureActionPanelOpen(visState.editor, this.props.index) &&+ !coordinateMenuHiddenByTooltip(+ Boolean(visState.interactionConfig.tooltip?.enabled),+ visState.hoverInfo?.layer?.id+ ) ? (+ <MapCoordinateMenu+ x={this.state.coordinateMenu.x}+ y={this.state.coordinateMenu.y}+ text={+ visState.interactionConfig.coordinate.enabled+ ? this.state.coordinateMenu.text+ : null+ }+ showCopy={visState.interactionConfig.coordinate.enabled}+ {...this._annotationMenuItems()}+ onAddAnnotation={this._onAddAnnotation}+ onToggleAnnotations={this._onToggleAnnotations}+ onClose={this._closeCoordinateMenu}+ />+ ) : null}</StyledMap>);}diff --git a/src/components/src/map/charts/chart-config-group.tsx b/src/components/src/map/charts/chart-config-group.tsxindex 81fe0e160..c258a09ad 100644--- a/src/components/src/map/charts/chart-config-group.tsx+++ b/src/components/src/map/charts/chart-config-group.tsx@@ -18,7 +18,7 @@ export const ChartConfigSection = styled.div``;/**- * Compact label | control rows, matching Studio chart settings density.+ * Compact label | control rows for chart settings.*/export const ChartConfigSectionWrapper = styled.div`display: grid;diff --git a/src/components/src/map/coordinate-info.tsx b/src/components/src/map/coordinate-info.tsxindex 07e8c0e5e..d002ec8d4 100644--- a/src/components/src/map/coordinate-info.tsx+++ b/src/components/src/map/coordinate-info.tsx@@ -8,9 +8,28 @@ import {StyledLayerName} from './layer-hover-info';// 6th decimal is worth up to 0.11 m// https://gis.stackexchange.com/questions/8650/measuring-accuracy-of-latitude-and-longitude-const DECIMAL = 6;+export const MAP_COORDINATE_DECIMAL = 6;const DECIMAL_Z = 1;+/**+ * Format a `[lng, lat]` pair as `"lat, lng"` at map-popover precision.+ * Returns null when either value is missing or not finite.+ */+export function formatMapCoordinate(coordinate: number[] | null | undefined): string | null {+ if (!coordinate || coordinate.length < 2) {+ return null;+ }+ const lng = Number(coordinate[0]);+ const lat = Number(coordinate[1]);+ if (!Number.isFinite(lng) || !Number.isFinite(lat)) {+ return null;+ }+ return `${preciseRound(lat, MAP_COORDINATE_DECIMAL)}, ${preciseRound(+ lng,+ MAP_COORDINATE_DECIMAL+ )}`;+}+export interface CoordinateInfoProps {coordinate: number[];zoom: number;@@ -26,8 +45,8 @@ const CoordinateInfoFactory = () => {<table><tbody><tr className="row">- <td className="row__value">{preciseRound(coordinate[1], DECIMAL)},</td>- <td className="row__value">{preciseRound(coordinate[0], DECIMAL)},</td>+ <td className="row__value">{preciseRound(coordinate[1], MAP_COORDINATE_DECIMAL)},</td>+ <td className="row__value">{preciseRound(coordinate[0], MAP_COORDINATE_DECIMAL)},</td><td className="row__value">{preciseRound(zoom, DECIMAL_Z)}z</td></tr></tbody>diff --git a/src/components/src/map/map-coordinate-menu.spec.tsx b/src/components/src/map/map-coordinate-menu.spec.tsxnew file mode 100644index 000000000..7b2cd1ae8--- /dev/null+++ b/src/components/src/map/map-coordinate-menu.spec.tsx@@ -0,0 +1,293 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {act, fireEvent, render, screen} from '@testing-library/react';+import copy from 'copy-to-clipboard';+import {ThemeProvider} from 'styled-components';+import {IntlProvider} from 'react-intl';++import {theme} from '@kepler.gl/styles';+import {messages} from '@kepler.gl/localization';++import {formatMapCoordinate} from './coordinate-info';+import MapCoordinateMenu, {+ annotationContextMenuItems,+ contextMenuTargetIsFeatureUi,+ contextMenuTargetIsMapOverlay,+ coordinateMenuFromClick,+ coordinateMenuHiddenByTooltip,+ isFeatureActionPanelOpen,+ isRightDrag+} from './map-coordinate-menu';++jest.mock('copy-to-clipboard', () => jest.fn(() => true));++const copyMock = copy as jest.MockedFunction<typeof copy>;++function renderMenu(text = '37.774929, -122.419418') {+ const onClose = jest.fn();+ render(+ <ThemeProvider theme={theme}>+ <IntlProvider locale="en" messages={messages.en}>+ <MapCoordinateMenu x={20} y={30} text={text} onClose={onClose} />+ </IntlProvider>+ </ThemeProvider>+ );+ return {onClose};+}++describe('formatMapCoordinate', () => {+ test('writes latitude first at 6 decimal places', () => {+ expect(formatMapCoordinate([-122.4194183, 37.7749295])).toBe('37.774930, -122.419418');+ });++ test('rejects missing or non-finite values', () => {+ expect(formatMapCoordinate(null)).toBeNull();+ expect(formatMapCoordinate([1])).toBeNull();+ expect(formatMapCoordinate([Number.NaN, 1])).toBeNull();+ });+});++describe('coordinateMenuFromClick', () => {+ const bounds = {left: 10, top: 20, width: 100, height: 80};++ test('unprojects a click inside the map', () => {+ const menu = coordinateMenuFromClick(30, 40, bounds, point => {+ expect(point).toEqual([20, 20]);+ return [-122.4, 37.7];+ });+ expect(menu).toEqual({+ x: 20,+ y: 20,+ text: '37.700000, -122.400000',+ coordinate: [-122.4, 37.7]+ });+ });++ test('ignores clicks outside the container and failed projections', () => {+ expect(coordinateMenuFromClick(0, 40, bounds, () => [-122, 37])).toBeNull();+ expect(coordinateMenuFromClick(30, 40, bounds, () => null)).toBeNull();+ expect(+ coordinateMenuFromClick(30, 40, bounds, () => {+ throw new Error('not invertible');+ })+ ).toBeNull();+ });+});++describe('isRightDrag', () => {+ test('treats a stationary right-click as a click', () => {+ expect(isRightDrag(null, 10, 10)).toBe(false);+ expect(isRightDrag({x: 10, y: 10}, 12, 11)).toBe(false);+ });++ test('treats movement past the threshold as a drag', () => {+ expect(isRightDrag({x: 0, y: 0}, 8, 0)).toBe(true);+ });+});++describe('isFeatureActionPanelOpen', () => {+ const feature = {type: 'Feature'};++ test('is open when this map right-clicked a polygon or filter', () => {+ expect(+ isFeatureActionPanelOpen(+ {selectedFeature: feature, selectionContext: {rightClick: true, mapIndex: 0}},+ 0+ )+ ).toBe(true);+ });++ test('stays closed for another map, a left click, or no selection', () => {+ expect(+ isFeatureActionPanelOpen(+ {selectedFeature: feature, selectionContext: {rightClick: true, mapIndex: 1}},+ 0+ )+ ).toBe(false);+ expect(+ isFeatureActionPanelOpen(+ {selectedFeature: feature, selectionContext: {rightClick: false, mapIndex: 0}},+ 0+ )+ ).toBe(false);+ expect(isFeatureActionPanelOpen({selectedFeature: null}, 0)).toBe(false);+ });+});++describe('coordinateMenuHiddenByTooltip', () => {+ test('hides the menu when a tooltip can describe the feature under the cursor', () => {+ expect(coordinateMenuHiddenByTooltip(true, 'point-layer')).toBe(true);+ });++ test('keeps the menu when tooltips are off or the cursor is on empty map', () => {+ expect(coordinateMenuHiddenByTooltip(false, 'point-layer')).toBe(false);+ expect(coordinateMenuHiddenByTooltip(true, null)).toBe(false);+ });+});++describe('annotationContextMenuItems', () => {+ test('offers add on an editable map and hide once annotations exist', () => {+ expect(+ annotationContextMenuItems({annotationsEnabled: true, readOnly: false, annotationCount: 0})+ ).toEqual({showAddAnnotation: true, showAnnotationToggle: false, annotationsVisible: false});+ expect(+ annotationContextMenuItems({annotationsEnabled: true, readOnly: false, annotationCount: 2})+ ).toEqual({showAddAnnotation: true, showAnnotationToggle: true, annotationsVisible: true});+ });++ test('hides add on a read-only map and both actions when annotations are off', () => {+ expect(+ annotationContextMenuItems({annotationsEnabled: true, readOnly: true, annotationCount: 1})+ ).toEqual({showAddAnnotation: false, showAnnotationToggle: true, annotationsVisible: true});+ expect(annotationContextMenuItems({annotationsEnabled: false, annotationCount: 3})).toEqual({+ showAddAnnotation: false,+ showAnnotationToggle: false,+ annotationsVisible: true+ });+ });++ test('offers show when every annotation is hidden and hide while any remain visible', () => {+ expect(+ annotationContextMenuItems({+ annotationsEnabled: true,+ annotationCount: 2,+ hiddenAnnotationCount: 2+ })+ ).toEqual({showAddAnnotation: true, showAnnotationToggle: true, annotationsVisible: false});+ expect(+ annotationContextMenuItems({+ annotationsEnabled: true,+ annotationCount: 2,+ hiddenAnnotationCount: 1+ })+ ).toEqual({showAddAnnotation: true, showAnnotationToggle: true, annotationsVisible: true});+ expect(+ annotationContextMenuItems({+ annotationsEnabled: true,+ annotationCount: 0,+ hiddenAnnotationCount: 0+ })+ ).toEqual({showAddAnnotation: true, showAnnotationToggle: false, annotationsVisible: false});+ });+});++describe('contextMenuTargetIsMapOverlay', () => {+ test('matches map controls, scale, and attribution but not the map surface', () => {+ document.body.innerHTML =+ '<div class="map-control"><button id="zoom">Zoom in</button></div>' ++ '<div class="map-scale" id="scale">1 km</div>' ++ '<div class="maplibre-attribution-container"><a id="attrib">© kepler.gl</a></div>' ++ '<div id="map"></div>';+ expect(contextMenuTargetIsMapOverlay(document.getElementById('zoom'))).toBe(true);+ expect(contextMenuTargetIsMapOverlay(document.getElementById('scale'))).toBe(true);+ expect(contextMenuTargetIsMapOverlay(document.getElementById('attrib'))).toBe(true);+ expect(contextMenuTargetIsMapOverlay(document.getElementById('map'))).toBe(false);+ expect(contextMenuTargetIsMapOverlay(null)).toBe(false);+ });+});++describe('contextMenuTargetIsFeatureUi', () => {+ test('matches the feature panel and polygon-filter badge', () => {+ document.body.innerHTML =+ '<div class="feature-action-panel"><button id="filter">Filter layers</button></div>' ++ '<div class="editor-filter-badges"><button id="badge"></button></div>' ++ '<div id="map"></div>';+ expect(contextMenuTargetIsFeatureUi(document.getElementById('filter'))).toBe(true);+ expect(contextMenuTargetIsFeatureUi(document.getElementById('badge'))).toBe(true);+ expect(contextMenuTargetIsFeatureUi(document.getElementById('map'))).toBe(false);+ expect(contextMenuTargetIsFeatureUi(null)).toBe(false);+ });+});++describe('MapCoordinateMenu', () => {+ beforeEach(() => {+ copyMock.mockClear();+ copyMock.mockReturnValue(true);+ });++ test('copies lat, lng and then closes', () => {+ jest.useFakeTimers();+ const {onClose} = renderMenu();++ fireEvent.click(screen.getByRole('menuitem', {name: 'Copy coordinates'}));++ expect(copyMock).toHaveBeenCalledWith('37.774929, -122.419418');+ expect(screen.getByRole('menuitem', {name: 'Copied'})).toBeTruthy();+ expect(onClose).not.toHaveBeenCalled();++ act(() => {+ jest.advanceTimersByTime(700);+ });+ expect(onClose).toHaveBeenCalledTimes(1);+ jest.useRealTimers();+ });++ test('adds an annotation and hides annotations from the same menu', () => {+ const onClose = jest.fn();+ const onAddAnnotation = jest.fn();+ const onToggleAnnotations = jest.fn();+ render(+ <ThemeProvider theme={theme}>+ <IntlProvider locale="en" messages={messages.en}>+ <MapCoordinateMenu+ x={20}+ y={30}+ text="37.774929, -122.419418"+ onClose={onClose}+ showAddAnnotation={true}+ showAnnotationToggle={true}+ annotationsVisible={true}+ onAddAnnotation={onAddAnnotation}+ onToggleAnnotations={onToggleAnnotations}+ />+ </IntlProvider>+ </ThemeProvider>+ );++ fireEvent.click(screen.getByRole('menuitem', {name: 'Add Annotation'}));+ expect(onAddAnnotation).toHaveBeenCalledTimes(1);++ fireEvent.click(screen.getByRole('menuitem', {name: 'Hide Annotations'}));+ expect(onToggleAnnotations).toHaveBeenCalledTimes(1);+ });++ test('keeps add available while annotations are hidden and offers show', () => {+ const onAddAnnotation = jest.fn();+ render(+ <ThemeProvider theme={theme}>+ <IntlProvider locale="en" messages={messages.en}>+ <MapCoordinateMenu+ x={20}+ y={30}+ text={null}+ showCopy={false}+ onClose={jest.fn()}+ showAddAnnotation={true}+ showAnnotationToggle={true}+ annotationsVisible={false}+ onAddAnnotation={onAddAnnotation}+ />+ </IntlProvider>+ </ThemeProvider>+ );++ const add = screen.getByRole('menuitem', {name: 'Add Annotation'});+ expect(add).toHaveProperty('disabled', false);+ fireEvent.click(add);+ expect(onAddAnnotation).toHaveBeenCalledTimes(1);+ expect(screen.getByRole('menuitem', {name: 'Show Annotations'})).toBeTruthy();+ expect(screen.queryByRole('menuitem', {name: 'Copy coordinates'})).toBeNull();+ });++ test('leaves the menu open when the clipboard write fails', () => {+ copyMock.mockReturnValue(false);+ const {onClose} = renderMenu();++ fireEvent.click(screen.getByRole('menuitem', {name: 'Copy coordinates'}));++ expect(onClose).not.toHaveBeenCalled();+ expect(screen.getByRole('menuitem', {name: 'Copy coordinates'})).toBeTruthy();+ });+});diff --git a/src/components/src/map/map-coordinate-menu.tsx b/src/components/src/map/map-coordinate-menu.tsxnew file mode 100644index 000000000..9ab6575bd--- /dev/null+++ b/src/components/src/map/map-coordinate-menu.tsx@@ -0,0 +1,353 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useEffect, useLayoutEffect, useRef, useState} from 'react';+import styled from 'styled-components';+import copy from 'copy-to-clipboard';+import {FormattedMessage} from '@kepler.gl/localization';++import {formatMapCoordinate} from './coordinate-info';+import {AnnotationText, Checkmark, Copy, EyeSeen, EyeUnseen} from '../common/icons';++const RIGHT_DRAG_THRESHOLD_PX = 3;+const MENU_OPEN_OFFSET_PX = 4;++export type CoordinateMenuState = {+ x: number;+ y: number;+ text: string;+ /** `[lng, lat]` at the click, used to place a new annotation. */+ coordinate: [number, number];+};++/** Which annotation actions belong on this right-click. */+export function annotationContextMenuItems({+ annotationsEnabled,+ readOnly = false,+ annotationCount,+ hiddenAnnotationCount = 0+}: {+ annotationsEnabled: boolean;+ readOnly?: boolean;+ annotationCount: number;+ /** Annotations with their own visibility turned off. */+ hiddenAnnotationCount?: number;+}): {showAddAnnotation: boolean; showAnnotationToggle: boolean; annotationsVisible: boolean} {+ if (!annotationsEnabled) {+ return {showAddAnnotation: false, showAnnotationToggle: false, annotationsVisible: true};+ }+ // Hide while any annotation is on the map. Show when every one is hidden.+ const annotationsVisible = annotationCount > 0 && hiddenAnnotationCount < annotationCount;+ return {+ showAddAnnotation: !readOnly,+ showAnnotationToggle: annotationCount > 0,+ annotationsVisible+ };+}++type Bounds = {+ left: number;+ top: number;+ width: number;+ height: number;+};++/**+ * The polygon / polygon-filter action panel (Filter layers) is open on this map.+ * The copy menu uses the same anchor and would cover that panel.+ */+export function isFeatureActionPanelOpen(+ editor:+ | {+ selectedFeature?: unknown;+ selectionContext?: {rightClick?: boolean; mapIndex?: number} | null;+ }+ | null+ | undefined,+ mapIndex = 0+): boolean {+ const context = editor?.selectionContext;+ return Boolean(+ editor?.selectedFeature && context?.rightClick && (context.mapIndex ?? 0) === (mapIndex ?? 0)+ );+}++/**+ * Hide the coordinate menu while a tooltip can describe the feature under the+ * cursor. The right-click pins that tooltip instead.+ */+export function coordinateMenuHiddenByTooltip(+ tooltipEnabled: boolean,+ hoverLayerId?: string | null+): boolean {+ return Boolean(tooltipEnabled && hoverLayerId);+}++/** Right-click landed on the feature action panel or a polygon-filter badge. */+export function contextMenuTargetIsFeatureUi(target: EventTarget | null): boolean {+ return target instanceof Element+ ? Boolean(target.closest('.feature-action-panel, .editor-filter-badges'))+ : false;+}++/**+ * Map chrome drawn on top of the basemap. A right-click here belongs to that+ * control, not to the map point underneath it.+ */+const MAP_OVERLAY_SELECTOR = [+ '.feature-action-panel',+ '.editor-filter-badges',+ '.map-control',+ '.map-control-panel',+ '.map-navigation-control',+ '.map-scale',+ '.map-popover',+ '.annotation-manager',+ '.effect-manager',+ '.chart-manager',+ '.maplibre-attribution-container',+ '.mapbox-attribution-container',+ '.maplibregl-ctrl',+ '.mapboxgl-ctrl'+].join(', ');++export function contextMenuTargetIsMapOverlay(target: EventTarget | null): boolean {+ return target instanceof Element ? Boolean(target.closest(MAP_OVERLAY_SELECTOR)) : false;+}++/**+ * Right-button press that moved farther than a few pixels is a rotate/pitch+ * drag, not a request for the coordinate menu.+ */+export function isRightDrag(+ start: {x: number; y: number} | null,+ clientX: number,+ clientY: number+): boolean {+ if (!start) {+ return false;+ }+ const dx = clientX - start.x;+ const dy = clientY - start.y;+ return dx * dx + dy * dy > RIGHT_DRAG_THRESHOLD_PX * RIGHT_DRAG_THRESHOLD_PX;+}++/**+ * Map a right-click inside the map container to a `"lat, lng"` menu anchor.+ * `unproject` receives pixel offsets from the container's top-left.+ */+export function coordinateMenuFromClick(+ clientX: number,+ clientY: number,+ bounds: Bounds,+ unproject: (point: [number, number]) => number[] | null | undefined+): CoordinateMenuState | null {+ const x = clientX - bounds.left;+ const y = clientY - bounds.top;+ if (+ !Number.isFinite(x) ||+ !Number.isFinite(y) ||+ x < 0 ||+ y < 0 ||+ x > bounds.width ||+ y > bounds.height+ ) {+ return null;+ }++ let lngLat: number[] | null | undefined;+ try {+ lngLat = unproject([x, y]);+ } catch {+ return null;+ }++ const text = formatMapCoordinate(lngLat);+ if (!text || !lngLat || lngLat.length < 2) {+ return null;+ }+ return {x, y, text, coordinate: [lngLat[0], lngLat[1]]};+}++const StyledMenu = styled.div`+ position: absolute;+ z-index: 99;+ display: flex;+ flex-direction: column;+ box-shadow: ${props => props.theme.dropdownListShadow};+ background-color: ${props => props.theme.dropdownListBgd};+ border-radius: 2px;+ pointer-events: auto;++ button {+ display: flex;+ flex-direction: row;+ align-items: center;+ gap: 8px;+ border: 0;+ border-radius: 2px;+ margin: 0;+ padding: 8px 12px 8px 8px;+ background-color: ${props => props.theme.dropdownListBgd};+ color: ${props => props.theme.textColor};+ font-family: ${props => props.theme.fontFamily};+ font-size: 12px;+ line-height: 14px;+ white-space: nowrap;+ cursor: pointer;++ &:hover,+ &:focus {+ outline: none;+ background-color: ${props => props.theme.dropdownListHighlightBg};+ color: ${props => props.theme.textColorHl};+ }+ }+`;++export type MapCoordinateMenuProps = {+ x: number;+ y: number;+ text: string | null;+ onClose: () => void;+ showCopy?: boolean;+ showAddAnnotation?: boolean;+ showAnnotationToggle?: boolean;+ annotationsVisible?: boolean;+ onAddAnnotation?: () => void;+ onToggleAnnotations?: () => void;+};++const MapCoordinateMenu: React.FC<MapCoordinateMenuProps> = ({+ x,+ y,+ text,+ onClose,+ showCopy = true,+ showAddAnnotation = false,+ showAnnotationToggle = false,+ annotationsVisible = true,+ onAddAnnotation,+ onToggleAnnotations+}) => {+ const menuRef = useRef<HTMLDivElement>(null);+ const [shift, setShift] = useState({x: MENU_OPEN_OFFSET_PX, y: MENU_OPEN_OFFSET_PX});+ const [interactive, setInteractive] = useState(false);+ const [copied, setCopied] = useState(false);++ useLayoutEffect(() => {+ const node = menuRef.current;+ const parent = node?.offsetParent as HTMLElement | null;+ if (!node || !parent) {+ return;+ }+ const next = {x: MENU_OPEN_OFFSET_PX, y: MENU_OPEN_OFFSET_PX};+ if (x + next.x + node.offsetWidth > parent.clientWidth) {+ next.x = -node.offsetWidth - MENU_OPEN_OFFSET_PX;+ }+ if (y + next.y + node.offsetHeight > parent.clientHeight) {+ next.y = -node.offsetHeight - MENU_OPEN_OFFSET_PX;+ }+ setShift(next);+ }, [x, y, text, copied, showCopy, showAddAnnotation, showAnnotationToggle, annotationsVisible]);++ useEffect(() => {+ setInteractive(false);+ const enableId = window.setTimeout(() => setInteractive(true), 0);+ return () => window.clearTimeout(enableId);+ }, [x, y]);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'Escape') {+ onClose();+ }+ };+ const onPointerDown = (event: PointerEvent) => {+ if (!menuRef.current?.contains(event.target as Node)) {+ onClose();+ }+ };+ window.addEventListener('keydown', onKeyDown);+ const listenId = window.setTimeout(() => {+ window.addEventListener('pointerdown', onPointerDown);+ }, 0);+ return () => {+ window.removeEventListener('keydown', onKeyDown);+ window.removeEventListener('pointerdown', onPointerDown);+ window.clearTimeout(listenId);+ };+ }, [onClose]);++ useEffect(() => {+ if (!copied) {+ return undefined;+ }+ const closeId = window.setTimeout(onClose, 700);+ return () => window.clearTimeout(closeId);+ }, [copied, onClose]);++ const onCopy = () => {+ if (copied || !text) {+ return;+ }+ if (copy(text)) {+ setCopied(true);+ }+ };++ return (+ <StyledMenu+ ref={menuRef}+ role="menu"+ data-testid="map-coordinate-menu"+ style={{+ left: x + shift.x,+ top: y + shift.y,+ pointerEvents: interactive ? 'auto' : 'none'+ }}+ onMouseDown={event => event.stopPropagation()}+ onContextMenu={event => {+ event.preventDefault();+ event.stopPropagation();+ }}+ >+ {showAddAnnotation ? (+ <button type="button" role="menuitem" onClick={() => onAddAnnotation?.()}>+ <AnnotationText height="14px" aria-hidden={true} />+ <FormattedMessage id="interactions.addAnnotation" />+ </button>+ ) : null}+ {showAnnotationToggle ? (+ <button type="button" role="menuitem" onClick={() => onToggleAnnotations?.()}>+ {annotationsVisible ? (+ <EyeUnseen height="14px" aria-hidden={true} />+ ) : (+ <EyeSeen height="14px" aria-hidden={true} />+ )}+ <FormattedMessage+ id={+ annotationsVisible ? 'interactions.hideAnnotations' : 'interactions.showAnnotations'+ }+ />+ </button>+ ) : null}+ {showCopy && text ? (+ <button type="button" role="menuitem" onClick={onCopy}>+ {copied ? (+ <Checkmark height="14px" aria-hidden={true} />+ ) : (+ <Copy height="14px" aria-hidden={true} />+ )}+ {copied ? (+ <FormattedMessage id="interactions.coordinateCopied" />+ ) : (+ <FormattedMessage id="interactions.copyCoordinate" />+ )}+ </button>+ ) : null}+ </StyledMenu>+ );+};++export default MapCoordinateMenu;diff --git a/src/components/src/side-panel/interaction-manager.tsx b/src/components/src/side-panel/interaction-manager.tsxindex 34dea235e..422c7dc9f 100644--- a/src/components/src/side-panel/interaction-manager.tsx+++ b/src/components/src/side-panel/interaction-manager.tsx@@ -85,6 +85,9 @@ function InteractionManagerFactory(title={intl.formatMessage({id: panelMetadata.label})}/>{Object.keys(interactionConfig).map(key => {+ if (key === 'annotation') {+ return null;+ }if (key === 'legend') {return layers ? (<LegendConfigdiff --git a/src/layers/src/editor-layer/editor-layer-utils.ts b/src/layers/src/editor-layer/editor-layer-utils.tsindex babf2a99d..31b87725c 100644--- a/src/layers/src/editor-layer/editor-layer-utils.ts+++ b/src/layers/src/editor-layer/editor-layer-utils.ts@@ -49,6 +49,7 @@ export function onClick(}): boolean {const drawingActive = isDrawingActive(editorMenuActive, editor.mode);+ const rightClick = Boolean(event?.rightButton || event?.srcEvent?.button === 2);if (info?.layer?.id === EDITOR_LAYER_ID && info?.object) {const isEditHandle = Boolean(@@ -61,7 +62,7 @@ export function onClick(}} else {let clickContext;- if (event.rightButton && Array.isArray(event.srcEvent?.point)) {+ if (rightClick && Array.isArray(event.srcEvent?.point)) {const {point} = event.srcEvent;clickContext = {mapIndex,@@ -87,7 +88,7 @@ export function onClick(onLayerClick(null, event);} else {if (editor.selectedFeature) {- if (event.rightButton) {+ if (rightClick) {return true;}diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.tsindex 74ee51e9e..adf74606e 100644--- a/src/localization/src/translations/ca.ts+++ b/src/localization/src/translations/ca.ts@@ -646,6 +646,12 @@ export default {tooltip: 'Suggeriment',brush: 'Pinzell',coordinate: 'Coordenades',+ annotation: 'Anotacions',+ addAnnotation: 'Afegeix una anotació',+ showAnnotations: 'Mostra les anotacions',+ hideAnnotations: 'Amaga les anotacions',+ copyCoordinate: 'Copia les coordenades',+ coordinateCopied: 'Copiat',geocoder: 'Geocodificador',legend: 'Llegenda',legendHint: 'Tria quines capes apareixen a la llegenda. Les capes segueixen al mapa.',diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.tsindex 707f26787..1ec8c2159 100644--- a/src/localization/src/translations/cn.ts+++ b/src/localization/src/translations/cn.ts@@ -626,6 +626,12 @@ export default {tooltip: '工具提示',brush: '刷',coordinate: '坐标',+ annotation: '注释',+ addAnnotation: '添加注释',+ showAnnotations: '显示注释',+ hideAnnotations: '隐藏注释',+ copyCoordinate: '复制坐标',+ coordinateCopied: '已复制',geocoder: '地理编码器',legend: '图例',legendHint: '选择哪些图层显示在图例中。图层仍会留在地图上。',diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex af64a2d17..8f7a44f73 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -942,6 +942,12 @@ ${'```'}tooltip: 'Tooltip',brush: 'Brush',coordinate: 'Coordinates',+ annotation: 'Annotations',+ addAnnotation: 'Add Annotation',+ showAnnotations: 'Show Annotations',+ hideAnnotations: 'Hide Annotations',+ copyCoordinate: 'Copy coordinates',+ coordinateCopied: 'Copied',geocoder: 'Geocoder',legend: 'Legend',legendHint: 'Choose which layers appear in the map legend. Layers stay on the map.',diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.tsindex 946799eaa..6b62353dd 100644--- a/src/localization/src/translations/es.ts+++ b/src/localization/src/translations/es.ts@@ -647,6 +647,12 @@ export default {tooltip: 'Sugerencias',brush: 'Pincel',coordinate: 'Coordenadas',+ annotation: 'Anotaciones',+ addAnnotation: 'Añadir anotación',+ showAnnotations: 'Mostrar anotaciones',+ hideAnnotations: 'Ocultar anotaciones',+ copyCoordinate: 'Copiar coordenadas',+ coordinateCopied: 'Copiado',geocoder: 'Geocodificador',legend: 'Leyenda',legendHint: 'Elige qué capas aparecen en la leyenda. Las capas siguen en el mapa.',diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.tsindex a90409fb6..0b7d76d23 100644--- a/src/localization/src/translations/fi.ts+++ b/src/localization/src/translations/fi.ts@@ -644,6 +644,12 @@ export default {tooltip: 'Vihje',brush: 'Harja',coordinate: 'Koordinaatit',+ annotation: 'Merkinnät',+ addAnnotation: 'Lisää merkintä',+ showAnnotations: 'Näytä merkinnät',+ hideAnnotations: 'Piilota merkinnät',+ copyCoordinate: 'Kopioi koordinaatit',+ coordinateCopied: 'Kopioitu',geocoder: 'Geocoder',legend: 'Selite',legendHint: 'Valitse, mitkä tasot näkyvät selitteessä. Tasot pysyvät kartalla.',diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.tsindex c28fc39a5..1be8483d0 100644--- a/src/localization/src/translations/ja.ts+++ b/src/localization/src/translations/ja.ts@@ -642,6 +642,12 @@ export default {tooltip: 'ツールチップ',brush: 'ブラシ',coordinate: '座標',+ annotation: 'アノテーション',+ addAnnotation: '注釈を追加',+ showAnnotations: '注釈を表示',+ hideAnnotations: '注釈を非表示',+ copyCoordinate: '座標をコピー',+ coordinateCopied: 'コピーしました',geocoder: 'ジオコーダー',legend: '凡例',legendHint: '凡例に表示するレイヤを選びます。マップ上のレイヤはそのままです。',diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.tsindex cc524fde5..d0b6784a2 100644--- a/src/localization/src/translations/pt.ts+++ b/src/localization/src/translations/pt.ts@@ -647,6 +647,12 @@ export default {tooltip: 'Dica de contexto',brush: 'Pincel',coordinate: 'Coordenadas',+ annotation: 'Anotações',+ addAnnotation: 'Adicionar anotação',+ showAnnotations: 'Mostrar anotações',+ hideAnnotations: 'Ocultar anotações',+ copyCoordinate: 'Copiar coordenadas',+ coordinateCopied: 'Copiado',geocoder: 'Geocoder',legend: 'Legenda',legendHint: 'Escolha quais camadas aparecem na legenda. As camadas continuam no mapa.',diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.tsindex 4496d94c4..a85f2d581 100644--- a/src/localization/src/translations/ru.ts+++ b/src/localization/src/translations/ru.ts@@ -648,6 +648,12 @@ export default {tooltip: 'Подсказка',brush: 'Кисть',coordinate: 'Координаты',+ annotation: 'Аннотации',+ addAnnotation: 'Добавить аннотацию',+ showAnnotations: 'Показать аннотации',+ hideAnnotations: 'Скрыть аннотации',+ copyCoordinate: 'Копировать координаты',+ coordinateCopied: 'Скопировано',geocoder: 'Геокодер',legend: 'Легенда',legendHint: 'Выберите, какие слои видны в легенде. На карте слои остаются.',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex a8bd2795f..ed6577224 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -326,6 +326,11 @@ export const defaultInteractionConfig: InteractionConfig = {enabled: false,position: null},+ annotation: {+ id: 'annotation',+ label: 'interactions.annotation',+ enabled: false+ },zoomOpacity: {id: 'zoomOpacity',label: 'interactions.fadeOnZoom',diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.tsindex 47eabaf0d..748859767 100644--- a/src/schemas/src/vis-state-schema.ts+++ b/src/schemas/src/vis-state-schema.ts@@ -710,7 +710,15 @@ class InteractionSchemaV0 extends Schema {}}-const interactionPropsV1 = ['tooltip', 'legend', 'brush', 'geocoder', 'coordinate', 'zoomOpacity'];+const interactionPropsV1 = [+ 'tooltip',+ 'legend',+ 'brush',+ 'geocoder',+ 'coordinate',+ 'annotation',+ 'zoomOpacity'+];export class InteractionSchemaV1 extends Schema {key = 'interactionConfig';@@ -724,14 +732,16 @@ export class InteractionSchemaV1 extends Schema {return Array.isArray(this.properties)? {[this.key]: this.properties.reduce((accu, key) => {- const interaction = interactionConfig[key];+ const interaction = interactionConfig[key as keyof InteractionConfig];+ // Older saved states may not have annotation or zoomOpacity.if (!interaction) {return accu;}+ const config = 'config' in interaction ? interaction.config : undefined;return {...accu,[key]: {- ...interaction.config,+ ...(config || {}),enabled: interaction.enabled}};diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.tsindex 2b01f319f..2f56f26de 100644--- a/src/types/reducers.d.ts+++ b/src/types/reducers.d.ts@@ -436,6 +436,9 @@ export type Coordinate = BaseInteraction & {id: 'coordinate';position: number[] | null;};+export type AnnotationInteraction = BaseInteraction & {+ id: 'annotation';+};export type LegendInfo = BaseInteraction & {id: 'legend';config: {@@ -471,6 +474,7 @@ export type InteractionConfig = {geocoder: Geocoder;brush: Brush;coordinate: Coordinate;+ annotation: AnnotationInteraction;zoomOpacity: ZoomOpacityInteraction;};export type MapInfo = {diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.tsindex b50d59d2e..a636d1b0f 100644--- a/src/types/schemas.d.ts+++ b/src/types/schemas.d.ts@@ -45,6 +45,9 @@ export type SavedInteractionConfig = {coordinate: {enabled: boolean;};+ annotation?: {+ enabled: boolean;+ };legend?: {enabled: boolean;hideInvisibleLayers?: boolean;diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.jsindex 18d4214b3..f2c75c318 100644--- a/test/node/schemas/vis-state-schema-test.js+++ b/test/node/schemas/vis-state-schema-test.js@@ -228,6 +228,9 @@ test('#visStateSchema -> v1 -> save load interaction', t => {enabled: false,hideInvisibleLayers: false},+ annotation: {+ enabled: false+ },zoomOpacity: {enabled: false,controllers: []@@ -294,6 +297,9 @@ test('#visStateSchema -> v1 -> save load interaction -> tooltip format', t => {enabled: false,hideInvisibleLayers: false},+ annotation: {+ enabled: false+ },zoomOpacity: {enabled: false,controllers: []