Skip to content

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

feat(annotations): add ruler variant (#3858)

Igor Dykhta14990a8c9a0d
diff --git a/SUMMARY.md b/SUMMARY.md
index d940c60e9..daa670db7 100644
--- a/SUMMARY.md
+++ b/SUMMARY.md
@@ -34,6 +34,7 @@
* [Color Palettes](docs/user-guides/l-color-attributes.md)
* [Filters](docs/user-guides/e-filters.md)
* [Draw on Map](docs/user-guides/draw-on-map.md)
+ * [Annotations and Rulers](docs/user-guides/annotations.md)
* [Map Styles](docs/user-guides/f-map-styles.md)
* [Interactions](docs/user-guides/g-interactions.md)
* [Map Settings](docs/user-guides/m-map-settings.md)
diff --git a/docs/upgrade-guide-v3.3.md b/docs/upgrade-guide-v3.3.md
index cd871dc9c..edf274e49 100644
--- a/docs/upgrade-guide-v3.3.md
+++ b/docs/upgrade-guide-v3.3.md
@@ -394,6 +394,8 @@ A new map split mode (`MapSplitMode.SWIPE_COMPARE`) enables side-by-side compari
A new annotation system allows adding text labels, markers, and shapes directly on the map. New actions: `addAnnotation`, `removeAnnotation`, `updateAnnotation`, `duplicateAnnotation`, `setSelectedAnnotation`.
+**Ruler** annotations add independently draggable endpoints and separate **Custom Text** and **Distance** switches. Labels report geodesic ground distance in kilometres; endpoint elevation affects placement. Ruler geometry, rich text, and label settings are preserved in map configurations and HTML exports. See [Annotations and Rulers](./user-guides/annotations.md) for creation and editing instructions.
+
### Layer Groups
Layers can now be organized into named groups with shared visibility and legend controls. New actions: `addLayerGroup`, `removeLayerGroup`, `updateLayerGroup`, `addLayerToLayerGroup`, `removeLayerFromLayerGroup`.
diff --git a/docs/user-guides/README.md b/docs/user-guides/README.md
index e97d73624..793bcdffe 100644
--- a/docs/user-guides/README.md
+++ b/docs/user-guides/README.md
@@ -51,6 +51,11 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da
#### [Draw on Map](./draw-on-map.md)
+#### [Annotations and Rulers](./annotations.md)
+* [Create a ruler](./annotations.md#create-a-ruler)
+* [Edit ruler labels](./annotations.md#edit-ruler-labels)
+* [3D placement and distance](./annotations.md#3d-placement-and-distance)
+
#### [Map styles](./f-map-styles.md#map-styles)
* [Base map styles](./f-map-styles.md#base-map-styles)
* [Map layers](./f-map-styles.md#toggle-map-layers)
diff --git a/docs/user-guides/annotations.md b/docs/user-guides/annotations.md
new file mode 100644
index 000000000..f529928de
--- /dev/null
+++ b/docs/user-guides/annotations.md
@@ -0,0 +1,79 @@
+# Annotations and Rulers
+
+Annotations add text, points, arrows, circles, and rulers to your map. You can keep multiple annotations and measurements on the same map, each with its own text, color, and visibility settings.
+
+<!-- TOC -->
+
+- [Open the annotations panel](#open-the-annotations-panel)
+- [Create a ruler](#create-a-ruler)
+- [Edit ruler labels](#edit-ruler-labels)
+- [3D placement and distance](#3d-placement-and-distance)
+- [Dateline and globe views](#dateline-and-globe-views)
+- [Manage annotations](#manage-annotations)
+- [Save and export](#save-and-export)
+<!-- /TOC -->
+
+## Open the annotations panel
+
+Click the **Annotations** button in the map controls. Its tooltip reads **Show annotations** when the panel is closed.
+
+Keep the panel open to edit annotations. Closing it hides editing handles while leaving visible annotations on the map.
+
+Each annotation's settings start with five type icons: **Text**, **Point**, **Arrow**, **Circle**, and **Ruler**. Click an icon to switch the annotation's type. The active type is highlighted; hover over an icon to see its name.
+
+## Create a ruler
+
+1. Click **Add** in the Annotations panel. A point annotation appears at the map center.
+2. In the annotation's settings, click the **Ruler** icon, the last of the five type icons. If the settings are collapsed, click its entry in the panel to expand them.
+3. Drag the circular handle at either end of the line to set the measured span. Each handle moves its own endpoint.
+4. Drag the **Line Width** slider to choose a width from 1 to 10 pixels, and use **Color** to style the ruler. You can also focus the slider and use the arrow keys to adjust the width, or **Home** and **End** to select the minimum and maximum.
+
+You can also right-click a map location and choose **Add Annotation**, then click the **Ruler** icon in its settings.
+
+Repeat these steps to add more rulers. For very short rulers or coincident endpoints, the handles are spaced apart so you can reach both endpoints.
+
+## Edit ruler labels
+
+The **Custom Text** and **Distance** switches control the two parts of a ruler's label independently. Both are on by default.
+
+| Custom Text | Distance | Label shown |
+| --- | --- | --- |
+| On | On | Your text and the calculated distance |
+| On | Off | Your text |
+| Off | On | The calculated distance |
+| Off | Off | No label; the ruler line remains visible |
+
+With **Custom Text** on, click the text on the map to edit it and use the formatting toolbar. The distance updates automatically as you move either endpoint.
+
+The label stays at the midpoint between the projected endpoints. Move the endpoints to reposition a ruler; its midpoint label stays attached to the line.
+
+## 3D placement and distance
+
+When dragging an endpoint over a pickable 3D surface, kepler.gl uses the surface position and elevation. If no 3D surface is picked, the endpoint uses the ground plane at elevation zero.
+
+The distance label reports **geodesic ground distance in kilometres**, rounded to two decimal places. Elevation affects where the endpoints are drawn; the reported length uses their longitude and latitude. For example, endpoints at the same longitude and latitude but different elevations have a ground distance of zero. Rulers with zero ground distance have no automatic distance label.
+
+## Dateline and globe views
+
+Rulers crossing the dateline use the shortest longitude span between their endpoints.
+
+In [globe view](./m-map-settings.md#globe-view), a ruler is visible only while both endpoints are on the visible hemisphere. Rotate the globe to bring both endpoints into view if a ruler disappears.
+
+## Manage annotations
+
+Select an annotation in the panel to change its settings. Use its eye icon to hide or show it, the copy icon to duplicate it, or the trash icon to remove it. Duplicated rulers retain their endpoints and settings and can be edited independently.
+
+Point, arrow, and circle annotations also have **Text Side** and **Placement** selectors for positioning their labels. Text annotations use these selectors to position text around their anchor. Rulers use a midpoint label and the two label switches instead.
+
+Rulers follow the same visibility and fade-on-zoom settings as other annotations.
+
+## Save and export
+
+Use [Export Map](./k-save-and-export.md#export-map) to save or share your annotations:
+
+- **JSON** preserves annotation types, endpoints (including elevation), rich text, styling, and label switches in the map configuration.
+- **HTML** includes the ruler configuration. Editable exports support annotation editing; view-only exports display rulers with editing controls hidden.
+
+Use a kepler.gl version that supports ruler annotations when loading or sharing saved maps.
+
+[Back to table of contents](README.md)
diff --git a/docs/user-guides/k-save-and-export.md b/docs/user-guides/k-save-and-export.md
index 9b79cc6ae..d2002622f 100644
--- a/docs/user-guides/k-save-and-export.md
+++ b/docs/user-guides/k-save-and-export.md
@@ -29,6 +29,8 @@ You can export the current map using two different formats. The __Export Map__ w
- HTML: create a single html file loads and renders your current map.
- JSON: create a json file with your current map config and data.
+[Annotations and rulers](./annotations.md#save-and-export) are saved with the map configuration, including ruler endpoints, rich text, styling, and label switches. View-only HTML exports display annotations with editing controls hidden.
+
### <a href="#export-html-map">Export Map as HTML</a>
![Export Map as HTML](https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/documentation/k-save-and-export-4.png "activate interactions")
diff --git a/src/components/src/annotations/annotation-node.spec.tsx b/src/components/src/annotations/annotation-node.spec.tsx
index 2c0bf8cb5..4a2bae99b 100644
--- a/src/components/src/annotations/annotation-node.spec.tsx
+++ b/src/components/src/annotations/annotation-node.spec.tsx
@@ -8,7 +8,7 @@ import {render} from '@testing-library/react';
import {AnnotationKind} from '@kepler.gl/constants';
import {Annotation} from '@kepler.gl/types';
-import AnnotationNode from './annotation-node';
+import AnnotationNode, {RulerEndpointHandles} from './annotation-node';
import {MapViewport} from './annotation-utils';
const annotation: Annotation = {
@@ -37,6 +37,23 @@ const viewport: MapViewport = {
zoom: 4
};
+const rulerAnnotation: Annotation = {
+ id: 'ruler-1',
+ kind: AnnotationKind.RULER,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0, 10],
+ endPoint: [2, 0, 30],
+ label: 'Measured span',
+ lineColor: '#ffffff',
+ lineWidth: 2,
+ textWidth: 120,
+ textHeight: 40,
+ showCustomText: true,
+ showDistance: true
+};
+
describe('AnnotationNode', () => {
test('removes the entire annotation shape from hit testing at zero opacity', () => {
const {container, rerender} = render(
@@ -72,4 +89,54 @@ describe('AnnotationNode', () => {
expect(shape.style.display).toBe('');
});
+
+ test('renders a ruler line and only exposes both endpoint handles while editing', () => {
+ const projectingViewport: MapViewport = {
+ ...viewport,
+ project: ([lng, _lat, altitude = 0]) => [100 + lng * 10, 200 - altitude]
+ };
+ const {container, rerender} = render(
+ <svg>
+ <DndContext>
+ <AnnotationNode
+ annotation={rulerAnnotation}
+ viewport={projectingViewport}
+ isEditing={true}
+ isSelected={true}
+ />
+ <RulerEndpointHandles
+ annotation={rulerAnnotation}
+ viewport={projectingViewport}
+ isEditing={true}
+ isSelected={true}
+ />
+ </DndContext>
+ </svg>
+ );
+
+ expect(container.querySelector('path')).toHaveAttribute('d', 'M0,0 L20,-20');
+ expect(container.querySelectorAll('circle')).toHaveLength(4);
+
+ rerender(
+ <svg>
+ <DndContext>
+ <AnnotationNode
+ annotation={rulerAnnotation}
+ viewport={projectingViewport}
+ isEditing={false}
+ isSelected={false}
+ />
+ <RulerEndpointHandles
+ annotation={rulerAnnotation}
+ viewport={projectingViewport}
+ isEditing={false}
+ isSelected={false}
+ />
+ </DndContext>
+ </svg>
+ );
+
+ expect(container.querySelector('path')).toBeInTheDocument();
+ expect(container.querySelectorAll('circle')).toHaveLength(0);
+ });
});
diff --git a/src/components/src/annotations/annotation-node.tsx b/src/components/src/annotations/annotation-node.tsx
index 2f064278b..46e12156c 100644
--- a/src/components/src/annotations/annotation-node.tsx
+++ b/src/components/src/annotations/annotation-node.tsx
@@ -3,9 +3,14 @@
import React, {FC} from 'react';
import {useDraggable} from '@dnd-kit/core';
-import {Annotation, AnnotationWithArm} from '@kepler.gl/types';
+import {Annotation, AnnotationWithArm, RulerAnnotation} from '@kepler.gl/types';
import {AnnotationKind} from '@kepler.gl/constants';
-import {makeMarker, MapViewport, CircleAnnotationMarker} from './annotation-utils';
+import {
+ makeMarker,
+ MapViewport,
+ CircleAnnotationMarker,
+ RulerAnnotationMarker
+} from './annotation-utils';
const HANDLE_RADIUS = 6;
@@ -55,6 +60,84 @@ export type AnnotationNodeProps = {
isSelected: boolean;
};
+export type RulerEndpointHandlesProps = {
+ annotation: RulerAnnotation;
+ opacity?: number;
+ viewport: MapViewport;
+ isEditing: boolean;
+ isSelected: boolean;
+};
+
+/**
+ * Ruler handles render in a dedicated SVG above midpoint text so even a short
+ * ruler remains draggable when its label overlaps an endpoint.
+ */
+export const RulerEndpointHandles: FC<RulerEndpointHandlesProps> = ({
+ annotation,
+ opacity = 1,
+ viewport,
+ isEditing,
+ isSelected
+}) => {
+ if (!isEditing) return null;
+ const marker = makeMarker(annotation, viewport) as RulerAnnotationMarker;
+ // Keep both hit targets reachable, including when the endpoints coincide.
+ // Dragging still applies its delta to the geographic endpoint, not this offset.
+ const length = Math.hypot(marker.ex, marker.ey);
+ const offset = Math.max(0, (HANDLE_RADIUS * 2 + 2 - length) / 2);
+ const dx = length > 0 ? marker.ex / length : 1;
+ const dy = length > 0 ? marker.ey / length : 0;
+ const startX = -dx * offset;
+ const startY = -dy * offset;
+ const endX = marker.ex + dx * offset;
+ const endY = marker.ey + dy * offset;
+ return (
+ <g
+ data-annotation-id={annotation.id}
+ data-annotation-part="handles"
+ transform={`translate(${marker.x},${marker.y})`}
+ style={{
+ opacity,
+ display: opacity === 0 ? 'none' : undefined,
+ visibility: opacity === 0 ? 'hidden' : undefined,
+ pointerEvents: opacity === 0 ? 'none' : undefined
+ }}
+ >
+ {offset > 0 ? (
+ <path
+ d={`M${startX},${startY} L0,0 M${marker.ex},${marker.ey} L${endX},${endY}`}
+ fill="none"
+ stroke="rgba(255,255,255,0.6)"
+ strokeWidth={1}
+ style={{pointerEvents: 'none'}}
+ />
+ ) : null}
+ <MoveHandle id={`${annotation.id}:MOVE_RULER_START`} x={startX} y={startY} />
+ <MoveHandle id={`${annotation.id}:MOVE_RULER_END`} x={endX} y={endY} />
+ {isSelected ? (
+ <>
+ <circle
+ cx={startX}
+ cy={startY}
+ r={HANDLE_RADIUS + 2}
+ fill="none"
+ stroke="rgba(64,169,255,0.6)"
+ strokeWidth={2}
+ />
+ <circle
+ cx={endX}
+ cy={endY}
+ r={HANDLE_RADIUS + 2}
+ fill="none"
+ stroke="rgba(64,169,255,0.6)"
+ strokeWidth={2}
+ />
+ </>
+ ) : null}
+ </g>
+ );
+};
+
const AnnotationNode: FC<AnnotationNodeProps> = ({
annotation,
opacity = 1,
@@ -138,6 +221,19 @@ const AnnotationNode: FC<AnnotationNodeProps> = ({
</>
);
break;
+ case AnnotationKind.RULER: {
+ const rulerMarker = marker as RulerAnnotationMarker;
+ body = (
+ <path
+ d={`M0,0 L${rulerMarker.ex},${rulerMarker.ey}`}
+ stroke={lineColor}
+ fill="none"
+ strokeWidth={lineWidth}
+ strokeLinecap="round"
+ />
+ );
+ break;
+ }
default:
body = (
<>
diff --git a/src/components/src/annotations/annotation-overlay.spec.tsx b/src/components/src/annotations/annotation-overlay.spec.tsx
new file mode 100644
index 000000000..1a80e68ff
--- /dev/null
+++ b/src/components/src/annotations/annotation-overlay.spec.tsx
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import {fireEvent} from '@testing-library/react';
+
+import {AnnotationKind} from '@kepler.gl/constants';
+import {Annotation, RulerAnnotation} from '@kepler.gl/types';
+import {renderWithTheme} from 'test/helpers/component-jest-utils';
+
+import AnnotationOverlay from './annotation-overlay';
+import {MapViewport} from './annotation-utils';
+
+const ruler: RulerAnnotation = {
+ id: 'ruler-1',
+ kind: AnnotationKind.RULER,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ endPoint: [0.01, 0],
+ label: 'Short ruler',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ showCustomText: true,
+ showDistance: true
+};
+
+const viewport: MapViewport = {
+ project: ([lng, lat]) => [500 + lng * 10, 300 - lat * 10],
+ unproject: ([x, y]) => [(x - 500) / 10, (y - 300) / -10],
+ longitude: 0,
+ latitude: 0,
+ width: 1000,
+ height: 600,
+ zoom: 10
+};
+
+// jsdom lacks PointerEvent; MouseEvent supplies the coordinates used by the sensor.
+function dispatchPointer(target: Node, type: string, x: number, y: number) {
+ const event = new MouseEvent(type, {bubbles: true, button: 0, clientX: x, clientY: y});
+ Object.defineProperty(event, 'isPrimary', {value: true});
+ fireEvent(target, event);
+}
+
+const makeLegacyAnnotation = (kind: AnnotationKind): Annotation =>
+ ({...ruler, id: 'legacy-1', kind, armLength: 20, angle: 0, radiusInMeters: 1000} as Annotation);
+
+describe('AnnotationOverlay ruler interactions', () => {
+ test.each([
+ AnnotationKind.TEXT,
+ AnnotationKind.POINT,
+ AnnotationKind.ARROW,
+ AnnotationKind.CIRCLE
+ ])('preserves anchor and label dragging for %s annotations', kind => {
+ const updateAnnotation = jest.fn();
+ const {container} = renderWithTheme(
+ <AnnotationOverlay
+ annotations={[makeLegacyAnnotation(kind)]}
+ selectedAnnotationId="legacy-1"
+ isEditingAnnotationText={false}
+ isAnnotationMode={true}
+ mapIndex={0}
+ viewport={viewport}
+ updateAnnotation={updateAnnotation}
+ setSelectedAnnotation={jest.fn()}
+ />
+ );
+ const anchor = container.querySelector('[data-annotation-part="shape"] [role="button"]')!;
+ const text = container.querySelector('[data-annotation-part="text"]')!;
+
+ for (const handle of [anchor, text]) {
+ updateAnnotation.mockClear();
+ dispatchPointer(handle, 'pointerdown', 500, 300);
+ dispatchPointer(document, 'pointermove', 504, 300);
+ dispatchPointer(document, 'pointermove', 520, 290);
+ dispatchPointer(document, 'pointerup', 520, 290);
+
+ expect(updateAnnotation).toHaveBeenCalled();
+ const [id, changes] = updateAnnotation.mock.calls[updateAnnotation.mock.calls.length - 1];
+ expect(id).toBe('legacy-1');
+ if (handle === anchor || kind === AnnotationKind.TEXT) {
+ expect(changes).toEqual({anchorPoint: [2, 1]});
+ } else {
+ expect(changes).not.toHaveProperty('anchorPoint');
+ expect(changes.angle).toBeLessThan(0);
+ expect(changes.armLength).toBeGreaterThan(20);
+ expect(changes.textSide).toBe('right');
+ expect(changes.textVerticalPosition).toBe('above');
+ }
+ }
+ });
+
+ test('renders legacy annotations and rulers without editing controls in view mode', () => {
+ const updateAnnotation = jest.fn();
+ const setSelectedAnnotation = jest.fn();
+ const {container} = renderWithTheme(
+ <AnnotationOverlay
+ annotations={[makeLegacyAnnotation(AnnotationKind.POINT), ruler]}
+ selectedAnnotationId={ruler.id}
+ isEditingAnnotationText={true}
+ isAnnotationMode={false}
+ mapIndex={0}
+ viewport={viewport}
+ updateAnnotation={updateAnnotation}
+ setSelectedAnnotation={setSelectedAnnotation}
+ />
+ );
+
+ expect(container.querySelectorAll('[data-annotation-part="shape"]')).toHaveLength(2);
+ expect(container.querySelectorAll('[data-annotation-part="text"]')).toHaveLength(2);
+ expect(container.querySelector('[data-annotation-part="distance"]')).toHaveTextContent(
+ 'Length: 1.11 km'
+ );
+ expect(container.querySelector('[role="button"], [contenteditable="true"]')).toBeNull();
+ for (const text of container.querySelectorAll('[data-annotation-part="text"]')) {
+ fireEvent.click(text);
+ }
+ expect(updateAnnotation).not.toHaveBeenCalled();
+ expect(setSelectedAnnotation).not.toHaveBeenCalled();
+ });
+
+ test('renders endpoint handles above midpoint text so short rulers remain draggable', () => {
+ const {container} = renderWithTheme(
+ <AnnotationOverlay
+ annotations={[ruler]}
+ selectedAnnotationId={ruler.id}
+ isEditingAnnotationText={false}
+ isAnnotationMode={true}
+ mapIndex={0}
+ viewport={viewport}
+ updateAnnotation={jest.fn()}
+ setSelectedAnnotation={jest.fn()}
+ />
+ );
+
+ const text = container.querySelector('[data-annotation-part="text"]');
+ const handles = container.querySelector('[data-annotation-part="handles"]');
+
+ expect(text).toBeInTheDocument();
+ expect(handles).toBeInTheDocument();
+ expect(text?.compareDocumentPosition(handles as Node) & Node.DOCUMENT_POSITION_FOLLOWING).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ );
+ });
+
+ test.each<[string, [number, number]]>([
+ ['short', [0.01, 0]],
+ ['coincident', [0, 0]],
+ ['vertical', [0, 0.01]],
+ ['diagonal', [0.01, 0.01]]
+ ])('independently drags both endpoints of a %s ruler', (_name, endPoint) => {
+ const updateAnnotation = jest.fn();
+ const setSelectedAnnotation = jest.fn();
+ const {container} = renderWithTheme(
+ <AnnotationOverlay
+ annotations={[{...ruler, endPoint}]}
+ selectedAnnotationId={ruler.id}
+ isEditingAnnotationText={false}
+ isAnnotationMode={true}
+ mapIndex={0}
+ viewport={viewport}
+ updateAnnotation={updateAnnotation}
+ setSelectedAnnotation={setSelectedAnnotation}
+ />
+ );
+ const handles = Array.from<SVGCircleElement>(
+ container.querySelectorAll('[data-annotation-part="handles"] [role="button"]')
+ );
+ expect(handles).toHaveLength(2);
+ const centers = handles.map(handle => [
+ Number(handle.getAttribute('cx')),
+ Number(handle.getAttribute('cy'))
+ ]);
+ const radii = handles.map(handle => Number(handle.getAttribute('r')));
+ // Unlike dispatching directly to overlapping nodes, this checks both pointer
+ // targets are actually reachable without being covered by the other handle.
+ expect(
+ Math.hypot(centers[1][0] - centers[0][0], centers[1][1] - centers[0][1])
+ ).toBeGreaterThan(radii[0] + radii[1]);
+
+ handles.forEach((handle, index) => {
+ updateAnnotation.mockClear();
+ const [x, y] = [500 + centers[index][0], 300 + centers[index][1]];
+ dispatchPointer(handle, 'pointerdown', x, y);
+ dispatchPointer(document, 'pointermove', x + 4, y);
+ dispatchPointer(document, 'pointermove', x + 20, y - 10);
+ dispatchPointer(document, 'pointerup', x + 20, y - 10);
+
+ expect(setSelectedAnnotation).toHaveBeenLastCalledWith(ruler.id, false);
+ expect(updateAnnotation).toHaveBeenCalled();
+ const [id, changes] = updateAnnotation.mock.calls[updateAnnotation.mock.calls.length - 1];
+ const key = index === 0 ? 'anchorPoint' : 'endPoint';
+ const original = index === 0 ? ruler.anchorPoint : endPoint;
+ expect(id).toBe(ruler.id);
+ expect(Object.keys(changes)).toEqual([key]);
+ expect(changes[key][0]).toBeCloseTo(original[0] + 2);
+ expect(changes[key][1]).toBeCloseTo(original[1] + 1);
+ });
+ });
+});
diff --git a/src/components/src/annotations/annotation-overlay.tsx b/src/components/src/annotations/annotation-overlay.tsx
index db3cb71e2..19bf9395b 100644
--- a/src/components/src/annotations/annotation-overlay.tsx
+++ b/src/components/src/annotations/annotation-overlay.tsx
@@ -12,15 +12,17 @@ import {
useSensor,
useSensors
} from '@dnd-kit/core';
-import {Annotation} from '@kepler.gl/types';
+import {Annotation, RulerAnnotation} from '@kepler.gl/types';
+import {AnnotationKind} from '@kepler.gl/constants';
import {ActionHandler, updateAnnotation, setSelectedAnnotation} from '@kepler.gl/actions';
-import AnnotationNode from './annotation-node';
+import AnnotationNode, {RulerEndpointHandles} from './annotation-node';
import AnnotationText from './annotation-text';
import {
MapViewport,
PickWorldPosition,
- isPointVisibleOnGlobe,
+ isAnnotationVisibleOnGlobe,
movePoint,
+ moveRulerEndpoint,
moveText,
resizeCircle
} from './annotation-utils';
@@ -85,7 +87,7 @@ const AnnotationOverlay: FC<AnnotationOverlayProps> = ({
(ann.mapIndex ?? 0) === mapIndex &&
ann.isVisible &&
// Hide annotations on the far side of the globe (occluded by the planet)
- (!isGlobeEnabled || isPointVisibleOnGlobe(ann.anchorPoint, viewport))
+ (!isGlobeEnabled || isAnnotationVisibleOnGlobe(ann, viewport))
)
.reverse(),
[annotations, mapIndex, isGlobeEnabled, viewport]
@@ -144,6 +146,24 @@ const AnnotationOverlay: FC<AnnotationOverlayProps> = ({
case 'MOVE_POINT':
changes = movePoint(draggedAnn, ev.delta, viewport, pickWorldPosition);
break;
+ case 'MOVE_RULER_START':
+ changes = moveRulerEndpoint(
+ draggedAnn,
+ 'start',
+ ev.delta,
+ viewport,
+ pickWorldPosition
+ );
+ break;
+ case 'MOVE_RULER_END':
+ changes = moveRulerEndpoint(
+ draggedAnn,
+ 'end',
+ ev.delta,
+ viewport,
+ pickWorldPosition
+ );
+ break;
case 'MOVE_TEXT':
changes = moveText(draggedAnn, ev.delta, viewport, pickWorldPosition);
break;
@@ -190,6 +210,7 @@ const AnnotationOverlay: FC<AnnotationOverlayProps> = ({
onDragStart={handleDragStart}
onDragMove={handleDragMove}
onDragEnd={handleDragEnd}
+ onDragCancel={handleDragEnd}
>
<AnnotationSvgContainer width={width} height={height}>
{annotationsToRender.map(annotation => (
@@ -221,6 +242,23 @@ const AnnotationOverlay: FC<AnnotationOverlayProps> = ({
/>
))}
</AnnotationTextContainer>
+ <AnnotationSvgContainer width={width} height={height}>
+ {annotationsToRender
+ .filter(
+ (annotation): annotation is RulerAnnotation =>
+ annotation.kind === AnnotationKind.RULER
+ )
+ .map(annotation => (
+ <RulerEndpointHandles
+ key={annotation.id}
+ annotation={annotation}
+ opacity={getAnnotationOpacity(annotation.id)}
+ viewport={viewport}
+ isEditing={isAnnotationMode}
+ isSelected={annotation.id === selectedAnnotationId}
+ />
+ ))}
+ </AnnotationSvgContainer>
</DndContext>
</AnnotationOverlayContainer>
);
diff --git a/src/components/src/annotations/annotation-panel.spec.tsx b/src/components/src/annotations/annotation-panel.spec.tsx
new file mode 100644
index 000000000..084b7d352
--- /dev/null
+++ b/src/components/src/annotations/annotation-panel.spec.tsx
@@ -0,0 +1,398 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import {Provider} from 'react-redux';
+import configureStore from 'redux-mock-store';
+import {fireEvent, screen, within} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import {AnnotationKind} from '@kepler.gl/constants';
+import {VisStateActions} from '@kepler.gl/actions';
+import {theme} from '@kepler.gl/styles';
+import {IntlWrapper, renderWithTheme} from 'test/helpers/component-jest-utils';
+
+import AnnotationManagerFactory from './annotation-panel';
+
+const mockStore = configureStore();
+const AnnotationManager = AnnotationManagerFactory();
+
+const makeState = (showCustomText: boolean, showDistance: boolean) => ({
+ visState: {
+ annotations: [
+ {
+ id: 'ruler-1',
+ kind: AnnotationKind.RULER,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ endPoint: [1, 0],
+ label: 'Measured span',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ showCustomText,
+ showDistance
+ }
+ ],
+ selectedAnnotationId: 'ruler-1'
+ },
+ mapState: {longitude: 0, latitude: 0}
+});
+
+describe('AnnotationManager ruler settings', () => {
+ test.each([
+ [true, true],
+ [true, false],
+ [false, true],
+ [false, false]
+ ])('renders independent custom text and distance switches (%s, %s)', (customText, distance) => {
+ const store = mockStore(makeState(customText, distance));
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ const customTextSwitch = screen.getByRole('checkbox', {name: 'Custom Text'});
+ const distanceSwitch = screen.getByRole('checkbox', {name: 'Distance'});
+
+ expect(customTextSwitch).toHaveProperty('checked', customText);
+ expect(distanceSwitch).toHaveProperty('checked', distance);
+ for (const input of [customTextSwitch, distanceSwitch]) {
+ expect(input.closest('label')).toHaveStyle({
+ lineHeight: `${theme.switchHeight}px`,
+ paddingLeft: `${theme.switchWidth - theme.switchLabelMargin}px`
+ });
+ }
+ });
+
+ test.each([true, false])('toggles each ruler switch independently from %s', checked => {
+ const store = mockStore(makeState(checked, checked));
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ fireEvent.click(screen.getByText('Custom Text'));
+ fireEvent.click(screen.getByText('Distance'));
+
+ expect(store.getActions()).toEqual([
+ VisStateActions.updateAnnotation('ruler-1', {showCustomText: !checked}),
+ VisStateActions.updateAnnotation('ruler-1', {showDistance: !checked})
+ ]);
+ });
+});
+
+describe('AnnotationManager type icons', () => {
+ test.each([
+ [AnnotationKind.TEXT, 'Text', AnnotationKind.POINT, 'Point'],
+ [AnnotationKind.POINT, 'Point', AnnotationKind.ARROW, 'Arrow'],
+ [AnnotationKind.ARROW, 'Arrow', AnnotationKind.CIRCLE, 'Circle'],
+ [AnnotationKind.CIRCLE, 'Circle', AnnotationKind.RULER, 'Ruler'],
+ [AnnotationKind.RULER, 'Ruler', AnnotationKind.TEXT, 'Text']
+ ] as const)(
+ '%s type icon is highlighted and supports switching',
+ (kind, label, nextKind, nextLabel) => {
+ const state = makeState(true, true);
+ Object.assign(state.visState.annotations[0], {kind, armLength: 50, angle: -45});
+ const store = mockStore(state);
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ const group = screen.getByRole('group', {name: 'Type'});
+ const buttons = within(group).getAllByRole('button');
+ expect(buttons.map(button => button.getAttribute('aria-label'))).toEqual([
+ 'Text',
+ 'Point',
+ 'Arrow',
+ 'Circle',
+ 'Ruler'
+ ]);
+ expect(screen.queryByText('Type')).not.toBeInTheDocument();
+ expect(group).toHaveStyle({width: '100%', height: theme.inputBoxHeight});
+ expect(within(group).getAllByRole('button', {pressed: true})).toEqual([
+ within(group).getByRole('button', {name: label})
+ ]);
+ expect(within(group).getByRole('button', {name: label})).toHaveStyle({
+ color: theme.switchTrackBgdActive,
+ borderColor: theme.switchTrackBgdActive
+ });
+ for (const button of buttons) {
+ expect(button).toHaveStyle({flex: '1', height: '100%', padding: '0'});
+ expect(button).toHaveAttribute('type', 'button');
+ expect(button).toHaveAttribute('title', button.getAttribute('aria-label'));
+ expect(button.querySelector('svg')).toBeInTheDocument();
+ }
+
+ fireEvent.click(within(group).getByRole('button', {name: nextLabel}));
+ expect(store.getActions()).toEqual([
+ VisStateActions.updateAnnotation('ruler-1', {kind: nextKind})
+ ]);
+ }
+ );
+
+ test('supports keyboard activation of type icons', async () => {
+ const user = userEvent.setup();
+ const store = mockStore(makeState(true, true));
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ screen.getByRole('button', {name: 'Text'}).focus();
+ await user.keyboard('{Enter}');
+ await user.tab();
+ expect(screen.getByRole('button', {name: 'Point'})).toHaveFocus();
+ await user.keyboard(' ');
+
+ expect(store.getActions()).toEqual([
+ VisStateActions.updateAnnotation('ruler-1', {kind: AnnotationKind.TEXT}),
+ VisStateActions.updateAnnotation('ruler-1', {kind: AnnotationKind.POINT})
+ ]);
+ });
+});
+
+describe('AnnotationManager line width slider', () => {
+ const renderSlider = (lineWidth = 2) => {
+ const state = makeState(true, true);
+ state.visState.annotations[0].lineWidth = lineWidth;
+ const store = mockStore(state);
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+ return {store, slider: screen.getByRole('slider', {name: 'Line Width'})};
+ };
+
+ test.each([1, 2, 10])('displays the saved %spx width and slider bounds', width => {
+ const {slider} = renderSlider(width);
+
+ expect(slider).toHaveAttribute('aria-valuemin', '1');
+ expect(slider).toHaveAttribute('aria-valuemax', '10');
+ expect(slider).toHaveAttribute('aria-valuenow', String(width));
+ expect(slider).toHaveAttribute('aria-valuetext', `${width}px`);
+ expect(within(slider).getByText(`${width}px`)).toBeInTheDocument();
+ expect(slider).toHaveStyle({
+ flex: '1',
+ minWidth: '0',
+ marginLeft: '36px',
+ height: theme.inputBoxHeightSmall
+ });
+ });
+
+ test.each([
+ {key: 'ArrowLeft', width: 2, next: 1},
+ {key: 'ArrowDown', width: 2, next: 1},
+ {key: 'ArrowRight', width: 2, next: 3},
+ {key: 'ArrowUp', width: 2, next: 3},
+ {key: 'Home', width: 6, next: 1},
+ {key: 'End', width: 6, next: 10},
+ {key: 'ArrowLeft', width: 1, next: 1},
+ {key: 'ArrowRight', width: 10, next: 10}
+ ])('handles $key at $width px without exceeding the bounds', ({key, width, next}) => {
+ const {store, slider} = renderSlider(width);
+ slider.focus();
+ expect(slider).toHaveFocus();
+
+ fireEvent.keyDown(slider, {key});
+
+ expect(store.getActions()).toEqual(
+ next === width ? [] : [VisStateActions.updateAnnotation('ruler-1', {lineWidth: next})]
+ );
+ });
+
+ test('ignores keys unrelated to width adjustment', () => {
+ const {store, slider} = renderSlider();
+ fireEvent.keyDown(slider, {key: 'Enter'});
+ expect(store.getActions()).toEqual([]);
+ });
+
+ test.each([
+ [-10, 1],
+ [30, 4],
+ [45, 6],
+ [120, 10]
+ ])('drags to %s and applies the nearest valid width %s', (clientX, width) => {
+ const {store, slider} = renderSlider();
+ const track = slider.querySelector('.kg-slider')!;
+ Object.defineProperty(track, 'offsetWidth', {configurable: true, value: 90});
+ const handle = slider.querySelectorAll('.kg-range-slider__handle')[1];
+
+ fireEvent.mouseDown(handle);
+ fireEvent.mouseMove(document, {clientX});
+ fireEvent.mouseUp(document);
+
+ expect(store.getActions()).toEqual([
+ VisStateActions.updateAnnotation('ruler-1', {lineWidth: width})
+ ]);
+ });
+});
+
+describe('AnnotationManager selectors', () => {
+ const originalIntersectionObserver = window.IntersectionObserver;
+
+ beforeAll(() => {
+ window.IntersectionObserver = class {
+ observe() {
+ return undefined;
+ }
+ unobserve() {
+ return undefined;
+ }
+ disconnect() {
+ return undefined;
+ }
+ } as unknown as typeof IntersectionObserver;
+ });
+
+ afterAll(() => {
+ window.IntersectionObserver = originalIntersectionObserver;
+ });
+
+ test.each([AnnotationKind.RULER, AnnotationKind.POINT])(
+ 'uses consistent row height and spacing for %s options',
+ kind => {
+ const state = makeState(true, true);
+ Object.assign(state.visState.annotations[0], {kind, armLength: 50, angle: -45});
+ const store = mockStore(state);
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ const labels =
+ kind === AnnotationKind.RULER
+ ? ['Line Width', 'Color', 'Custom Text', 'Distance']
+ : ['Line Width', 'Color', 'Text Side', 'Placement'];
+ labels.forEach((label, index) => {
+ expect(screen.getByText(label).parentElement).toHaveStyle({
+ minHeight: theme.inputBoxHeightSmall,
+ alignItems: 'center',
+ marginBottom: index === labels.length - 1 ? '0' : '8px'
+ });
+ });
+ }
+ );
+
+ test('keeps color picker and selectors compact with matching widths', () => {
+ const state = makeState(true, true);
+ Object.assign(state.visState.annotations[0], {
+ kind: AnnotationKind.POINT,
+ armLength: 50,
+ angle: -45
+ });
+ const store = mockStore(state);
+ const {container} = renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+ const selector = container.querySelector('.item-selector');
+ const colorButton = screen.getByRole('button', {name: ''});
+
+ expect(selector).toHaveStyle({width: '100px'});
+ for (const dropdown of container.querySelectorAll('.item-selector__dropdown')) {
+ expect(dropdown).toHaveStyle({height: theme.inputBoxHeightSmall, boxSizing: 'border-box'});
+ }
+ expect(colorButton.parentElement).toHaveStyle({width: '100px'});
+ expect(colorButton).toHaveStyle({
+ width: '100%',
+ height: theme.inputBoxHeightSmall,
+ padding: '4px 5px 4px 10px',
+ boxSizing: 'border-box'
+ });
+ });
+
+ test.each(['Right', 'Above'])(
+ 'keeps %s unchanged when Enter is pressed without choosing an option', current => {
+ const state = makeState(true, true);
+ Object.assign(state.visState.annotations[0], {
+ kind: AnnotationKind.POINT,
+ armLength: 50,
+ angle: -45
+ });
+ const store = mockStore(state);
+ renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ fireEvent.click(screen.getByText(current));
+ fireEvent.keyDown(document.activeElement!, {key: 'Enter', keyCode: 13});
+
+ expect(store.getActions()).toEqual([]);
+ expect(screen.getByText(current)).toBeInTheDocument();
+ }
+ );
+
+ test.each([
+ {
+ current: 'Right',
+ next: 'Left',
+ changes: {textSide: 'left', textVerticalPosition: 'above', angle: -135}
+ },
+ {
+ current: 'Above',
+ next: 'Below',
+ changes: {textSide: 'right', textVerticalPosition: 'below', angle: 45}
+ }
+ ] as const)('changes $current to $next through a kepler.gl selector', ({current, next, changes}) => {
+ const state = makeState(true, true);
+ const store = mockStore({
+ ...state,
+ visState: {
+ ...state.visState,
+ annotations: [
+ {
+ ...state.visState.annotations[0],
+ kind: AnnotationKind.POINT,
+ armLength: 50,
+ angle: -45
+ }
+ ]
+ }
+ });
+ const {container} = renderWithTheme(
+ <IntlWrapper>
+ <Provider store={store}>
+ <AnnotationManager />
+ </Provider>
+ </IntlWrapper>
+ );
+
+ expect(container.querySelector('select')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText(current));
+ expect(screen.queryByPlaceholderText('Search')).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText(next));
+
+ expect(store.getActions()).toEqual([VisStateActions.updateAnnotation('ruler-1', changes)]);
+ expect(screen.queryByText(next)).not.toBeInTheDocument();
+ });
+});
diff --git a/src/components/src/annotations/annotation-panel.tsx b/src/components/src/annotations/annotation-panel.tsx
index 24bef17e9..8d0f02391 100644
--- a/src/components/src/annotations/annotation-panel.tsx
+++ b/src/components/src/annotations/annotation-panel.tsx
@@ -29,14 +29,56 @@ import {VisState} from '@kepler.gl/schemas';
import {MapState} from '@kepler.gl/types';
import {withState} from '../injector';
-import {Add, ArrowDown, ArrowDownSmall, Copy, EyeSeen, EyeUnseen, Trash} from '../common/icons';
-import {StyledPanelHeader, Tooltip, Button} from '../common/styled-components';
+import {
+ Add,
+ AnnotationText,
+ ArrowDown,
+ ArrowDownSmall,
+ Base,
+ BaseProps,
+ Circle,
+ Copy,
+ DrawPoint,
+ EyeSeen,
+ EyeUnseen,
+ Trash
+} from '../common/icons';
+import {StyledPanelHeader, Tooltip, Button, ButtonGroup} from '../common/styled-components';
+import Switch from '../common/switch';
+import ItemSelector from '../common/item-selector/item-selector';
+import Slider from '../common/slider/slider';
import Portaled from '../common/portaled';
import SingleColorPalette from '../side-panel/layer-panel/single-color-palette';
import {hexToRgb, rgbToHex} from '@kepler.gl/utils';
import {FormattedMessage} from '@kepler.gl/localization';
import {angleForTextPlacement, getTextPlacement} from './annotation-utils';
+const AnnotationArrowIcon = (props: Partial<BaseProps>) => (
+ <Base viewBox="0 0 24 24" {...props}>
+ <path d="M5 19 19 5M7 5h12v12" fill="none" stroke="currentColor" strokeWidth="2" />
+ </Base>
+);
+
+const AnnotationRulerIcon = (props: Partial<BaseProps>) => (
+ <Base viewBox="0 0 24 24" {...props}>
+ <g fill="none" stroke="currentColor" strokeWidth="1.5">
+ <rect x="2" y="7" width="20" height="10" rx="1" />
+ <path d="M6 7v5m4-5v3m4-3v5m4-5v3" />
+ </g>
+ </Base>
+);
+
+const ANNOTATION_ICONS = {
+ [AnnotationKind.TEXT]: AnnotationText,
+ [AnnotationKind.POINT]: DrawPoint,
+ [AnnotationKind.ARROW]: AnnotationArrowIcon,
+ [AnnotationKind.CIRCLE]: Circle,
+ [AnnotationKind.RULER]: AnnotationRulerIcon
+};
+
+const MIN_LINE_WIDTH = Math.min(...ANNOTATION_LINE_WIDTH_OPTIONS);
+const MAX_LINE_WIDTH = Math.max(...ANNOTATION_LINE_WIDTH_OPTIONS);
+
// Styled components
const StyledAnnotationPanelContainer = styled.div`
@@ -228,7 +270,47 @@ const StyledConfigRow = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
- margin-bottom: 9px;
+ min-height: ${props => props.theme.inputBoxHeightSmall};
+ margin-bottom: 8px;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+`;
+
+const StyledAnnotationTypeGroup = styled(ButtonGroup)`
+ width: 100%;
+ height: ${props => props.theme.inputBoxHeight};
+ align-items: stretch;
+ margin-bottom: 8px;
+`;
+
+const StyledAnnotationTypeButton = styled(Button)<{$active: boolean}>`
+ flex: 1;
+ min-width: 0;
+ height: 100%;
+ box-sizing: border-box;
+ padding: 0;
+ background-color: ${props => props.theme.inputBgd};
+ color: ${props => (props.$active ? props.theme.switchTrackBgdActive : props.theme.inputColor)};
+ border: 1px solid
+ ${props => (props.$active ? props.theme.switchTrackBgdActive : 'transparent')};
+
+ &:hover,
+ &:focus,
+ &:active {
+ background-color: ${props => props.theme.inputBgdHover};
+ color: ${props => (props.$active ? props.theme.switchTrackBgdActive : props.theme.inputColor)};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${props => props.theme.switchTrackBgdActive};
+ outline-offset: -2px;
+ }
+
+ svg {
+ margin-right: 0;
+ }
`;
const StyledConfigLabel = styled.div`
@@ -237,27 +319,59 @@ const StyledConfigLabel = styled.div`
text-transform: capitalize;
`;
-const StyledSelect = styled.select`
- background: ${props => props.theme.inputBgd};
- color: ${props => props.theme.inputColor};
- border: 1px solid ${props => props.theme.inputBorderColor || 'transparent'};
- border-radius: 4px;
- padding: 4px 8px;
- font-size: 12px;
- cursor: pointer;
+const StyledSelect = styled(ItemSelector).attrs({size: 'small'})`
width: 100px;
+
+ .item-selector__dropdown {
+ box-sizing: border-box;
+ }
+`;
+
+const StyledRulerSwitch = styled(Switch)`
+ .kg-checkbox__label {
+ /* The track starts in the label margin; align its right edge with the row. */
+ padding-left: ${props => props.theme.switchWidth - props.theme.switchLabelMargin}px;
+ }
+`;
+
+const StyledLineWidthSlider = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex: 1;
+ min-width: 0;
+ margin-left: 36px;
+ height: ${props => props.theme.inputBoxHeightSmall};
+ padding-left: 6px;
+ box-sizing: border-box;
+
+ &:focus-visible {
+ outline: 2px solid ${props => props.theme.switchTrackBgdActive};
+ outline-offset: 2px;
+ }
+
+ span.annotation-line-width-value {
+ min-width: 28px;
+ text-align: right;
+ color: ${props => props.theme.effectPanelTextSecondary2};
+ font-size: ${props => props.theme.inputFontSize};
+ }
`;
const StyledColorButtonWrapper = styled.div`
width: 100px;
.button {
+ width: 100%;
+ height: ${props => props.theme.inputBoxHeightSmall};
+ box-sizing: border-box;
color: ${props => props.theme.effectPanelTextSecondary2};
display: flex;
+ justify-content: space-between;
gap: 5px;
border: none;
transition: background 0.2s;
background-color: ${props => props.theme.inputBgd};
- padding: 8px 5px 8px 10px;
+ padding: 4px 5px 4px 10px;
&:active {
color: ${props => props.theme.effectPanelTextMain};
background-color: ${props => props.theme.inputBgdHover};
@@ -395,6 +509,28 @@ export default function AnnotationManagerFactory(): React.FC<any> {
[visStateActions]
);
+ const handleLineWidthKeyDown = useCallback(
+ (event: React.KeyboardEvent, annotation: Annotation) => {
+ const widths: Record<string, number> = {
+ ArrowLeft: annotation.lineWidth - 1,
+ ArrowDown: annotation.lineWidth - 1,
+ ArrowRight: annotation.lineWidth + 1,
+ ArrowUp: annotation.lineWidth + 1,
+ Home: MIN_LINE_WIDTH,
+ End: MAX_LINE_WIDTH
+ };
+ const width = widths[event.key];
+ if (!Number.isFinite(width)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const lineWidth = Math.min(MAX_LINE_WIDTH, Math.max(MIN_LINE_WIDTH, Math.round(width)));
+ if (lineWidth !== annotation.lineWidth) {
+ handleChangeLineWidth(annotation.id, lineWidth);
+ }
+ },
+ [handleChangeLineWidth]
+ );
+
const handleChangeLineColor = useCallback(
(id: string, rgb: [number, number, number]) => {
const lineColor = rgbToHex(rgb);
@@ -403,6 +539,13 @@ export default function AnnotationManagerFactory(): React.FC<any> {
[visStateActions]
);
+ const handleToggleRulerText = useCallback(
+ (id: string, property: 'showCustomText' | 'showDistance', checked: boolean) => {
+ visStateActions.updateAnnotation(id, {[property]: checked});
+ },
+ [visStateActions]
+ );
+
const handleChangeTextPlacement = useCallback(
(
annotation: Annotation,
@@ -545,45 +688,63 @@ export default function AnnotationManagerFactory(): React.FC<any> {
{isSelected ? (
<StyledConfigSection>
+ <StyledAnnotationTypeGroup
+ role="group"
+ aria-label={intl.formatMessage({
+ id: 'annotationManager.type',
+ defaultMessage: 'Type'
+ })}
+ >
+ {ANNOTATION_KINDS.map(({id, label}) => {
+ const Icon = ANNOTATION_ICONS[id];
+ return (
+ <StyledAnnotationTypeButton
+ key={id}
+ type="button"
+ title={label}
+ aria-label={label}
+ aria-pressed={annotation.kind === id}
+ $active={annotation.kind === id}
+ onClick={() => handleChangeKind(annotation.id, id)}
+ >
+ <Icon height="20px" aria-hidden="true" focusable="false" />
+ </StyledAnnotationTypeButton>
+ );
+ })}
+ </StyledAnnotationTypeGroup>
<StyledConfigRow>
<StyledConfigLabel>
{intl.formatMessage({
- id: 'annotationManager.type',
- defaultMessage: 'Type'
+ id: 'annotationManager.lineWidth',
+ defaultMessage: 'Line Width'
})}
</StyledConfigLabel>
- <StyledSelect
- value={annotation.kind}
- onChange={e =>
- handleChangeKind(annotation.id, e.target.value as AnnotationKind)
- }
- >
- {ANNOTATION_KINDS.map(k => (
- <option key={k.id} value={k.id}>
- {k.label}
- </option>
- ))}
- </StyledSelect>
- </StyledConfigRow>
- <StyledConfigRow>
- <StyledConfigLabel>
- {intl.formatMessage({
+ <StyledLineWidthSlider
+ role="slider"
+ tabIndex={0}
+ aria-label={intl.formatMessage({
id: 'annotationManager.lineWidth',
defaultMessage: 'Line Width'
})}
- </StyledConfigLabel>
- <StyledSelect
- value={annotation.lineWidth}
- onChange={e =>
- handleChangeLineWidth(annotation.id, Number(e.target.value))
- }
+ aria-valuemin={MIN_LINE_WIDTH}
+ aria-valuemax={MAX_LINE_WIDTH}
+ aria-valuenow={annotation.lineWidth}
+ aria-valuetext={`${annotation.lineWidth}px`}
+ onKeyDown={event => handleLineWidthKeyDown(event, annotation)}
>
- {ANNOTATION_LINE_WIDTH_OPTIONS.map(w => (
- <option key={w} value={w}>
- {w}px
- </option>
- ))}
- </StyledSelect>
+ <Slider
+ minValue={MIN_LINE_WIDTH}
+ maxValue={MAX_LINE_WIDTH}
+ value0={MIN_LINE_WIDTH}
+ value1={annotation.lineWidth}
+ step={1}
+ isRanged={false}
+ onSlider1Change={width => handleChangeLineWidth(annotation.id, width)}
+ />
+ <span className="annotation-line-width-value">
+ {annotation.lineWidth}px
+ </span>
+ </StyledLineWidthSlider>
</StyledConfigRow>
<StyledConfigRow>
<StyledConfigLabel>
@@ -597,50 +758,105 @@ export default function AnnotationManagerFactory(): React.FC<any> {
onSetColor={rgb => handleChangeLineColor(annotation.id, rgb)}
/>
</StyledConfigRow>
- <StyledConfigRow>
- <StyledConfigLabel>
- {intl.formatMessage({
- id: 'annotationManager.textSide',
- defaultMessage: 'Text Side'
- })}
- </StyledConfigLabel>
- <StyledSelect
- value={textPlacement.side}
- onChange={e =>
- handleChangeTextPlacement(annotation, {
- textSide: e.target.value as AnnotationTextSide
- })
- }
- >
- {ANNOTATION_TEXT_SIDES.map(s => (
- <option key={s.id} value={s.id}>
- {s.label}
- </option>
- ))}
- </StyledSelect>
- </StyledConfigRow>
- <StyledConfigRow>
- <StyledConfigLabel>
- {intl.formatMessage({
- id: 'annotationManager.textPlacement',
- defaultMessage: 'Placement'
- })}
- </StyledConfigLabel>
- <StyledSelect
- value={textPlacement.vertical}
- onChange={e =>
- handleChangeTextPlacement(annotation, {
- textVerticalPosition: e.target.value as AnnotationTextVerticalPosition
- })
- }
- >
- {ANNOTATION_TEXT_VERTICAL_POSITIONS.map(p => (
- <option key={p.id} value={p.id}>
- {p.label}
- </option>
- ))}
- </StyledSelect>
- </StyledConfigRow>
+ {annotation.kind === AnnotationKind.RULER ? (
+ <>
+ <StyledConfigRow>
+ <StyledConfigLabel
+ as="label"
+ htmlFor={`annotation-${annotation.id}-show-custom-text`}
+ >
+ {intl.formatMessage({
+ id: 'annotationManager.customText',
+ defaultMessage: 'Custom Text'
+ })}
+ </StyledConfigLabel>
+ <StyledRulerSwitch
+ id={`annotation-${annotation.id}-show-custom-text`}
+ checked={annotation.showCustomText}
+ onChange={event =>
+ handleToggleRulerText(
+ annotation.id,
+ 'showCustomText',
+ event.target.checked
+ )
+ }
+ />
+ </StyledConfigRow>
+ <StyledConfigRow>
+ <StyledConfigLabel
+ as="label"
+ htmlFor={`annotation-${annotation.id}-show-distance`}
+ >
+ {intl.formatMessage({
+ id: 'annotationManager.distance',
+ defaultMessage: 'Distance'
+ })}
+ </StyledConfigLabel>
+ <StyledRulerSwitch
+ id={`annotation-${annotation.id}-show-distance`}
+ checked={annotation.showDistance}
+ onChange={event =>
+ handleToggleRulerText(
+ annotation.id,
+ 'showDistance',
+ event.target.checked
+ )
+ }
+ />
+ </StyledConfigRow>
+ </>
+ ) : (
+ <>
+ <StyledConfigRow>
+ <StyledConfigLabel>
+ {intl.formatMessage({
+ id: 'annotationManager.textSide',
+ defaultMessage: 'Text Side'
+ })}
+ </StyledConfigLabel>
+ <StyledSelect
+ selectedItems={ANNOTATION_TEXT_SIDES.find(
+ s => s.id === textPlacement.side
+ )}
+ options={ANNOTATION_TEXT_SIDES}
+ displayOption="label"
+ getOptionValue="id"
+ multiSelect={false}
+ searchable={false}
+ onChange={side => {
+ if (side == null) return;
+ handleChangeTextPlacement(annotation, {
+ textSide: side as AnnotationTextSide
+ });
+ }}
+ />
+ </StyledConfigRow>
+ <StyledConfigRow>
+ <StyledConfigLabel>
+ {intl.formatMessage({
+ id: 'annotationManager.textPlacement',
+ defaultMessage: 'Placement'
+ })}
+ </StyledConfigLabel>
+ <StyledSelect
+ selectedItems={ANNOTATION_TEXT_VERTICAL_POSITIONS.find(
+ p => p.id === textPlacement.vertical
+ )}
+ options={ANNOTATION_TEXT_VERTICAL_POSITIONS}
+ displayOption="label"
+ getOptionValue="id"
+ multiSelect={false}
+ searchable={false}
+ onChange={position => {
+ if (position == null) return;
+ handleChangeTextPlacement(annotation, {
+ textVerticalPosition: position as AnnotationTextVerticalPosition
+ });
+ }}
+ />
+ </StyledConfigRow>
+ </>
+ )}
</StyledConfigSection>
) : null}
</StyledAnnotationItemWrapper>
diff --git a/src/components/src/annotations/annotation-text.spec.tsx b/src/components/src/annotations/annotation-text.spec.tsx
new file mode 100644
index 000000000..95cb147aa
--- /dev/null
+++ b/src/components/src/annotations/annotation-text.spec.tsx
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import {DndContext} from '@dnd-kit/core';
+import {screen} from '@testing-library/react';
+
+import {AnnotationKind} from '@kepler.gl/constants';
+import {Annotation} from '@kepler.gl/types';
+import {renderWithTheme} from 'test/helpers/component-jest-utils';
+
+import AnnotationText from './annotation-text';
+import {MapViewport} from './annotation-utils';
+
+const viewport: MapViewport = {
+ project: ([lng, lat]) => [500 + lng * 10, 300 - lat * 10],
+ unproject: ([x, y]) => [(x - 500) / 10, (y - 300) / -10],
+ longitude: 0,
+ latitude: 0,
+ width: 1000,
+ height: 600,
+ zoom: 10
+};
+
+const makeRuler = (overrides: Partial<Annotation> = {}): Annotation =>
+ ({
+ id: 'ruler-1',
+ kind: AnnotationKind.RULER,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ endPoint: [1, 0],
+ label: 'Measured span',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ showCustomText: true,
+ showDistance: true,
+ ...overrides
+ } as Annotation);
+
+const renderRulerText = (annotation: Annotation, isEditing = false, opacity = 1) =>
+ renderWithTheme(
+ <DndContext>
+ <AnnotationText
+ annotation={annotation}
+ opacity={opacity}
+ viewport={viewport}
+ isEditing={isEditing}
+ isSelected={isEditing}
+ isEditingText={isEditing}
+ onSelect={jest.fn()}
+ onChangeText={jest.fn()}
+ onUpdateAnnotation={jest.fn()}
+ />
+ </DndContext>
+ );
+
+describe('AnnotationText ruler labels', () => {
+ test('renders custom text and live distance together at the ruler midpoint', async () => {
+ const {container} = renderRulerText(makeRuler());
+
+ expect(await screen.findByText('Measured span')).toBeInTheDocument();
+ expect(screen.getByText('Length: 111.20 km')).toBeInTheDocument();
+ expect(container.querySelector('[data-annotation-part="text"]')).toHaveStyle({
+ left: '505px',
+ top: '300px',
+ transform: 'translate(-50%, -50%)'
+ });
+ });
+
+ test('can show only distance, or no midpoint text at all while leaving shape rendering separate', () => {
+ const distanceOnly = renderRulerText(makeRuler({showCustomText: false}));
+ expect(screen.getByText('Length: 111.20 km')).toBeInTheDocument();
+ expect(screen.queryByText('Measured span')).not.toBeInTheDocument();
+ distanceOnly.unmount();
+
+ const hidden = renderRulerText(
+ makeRuler({showCustomText: false, showDistance: false}),
+ true
+ );
+ expect(hidden.container.querySelector('[data-annotation-part="text"]')).toBeNull();
+ });
+
+ test('applies annotation zoom fading to the combined ruler label', () => {
+ const {container} = renderRulerText(makeRuler(), false, 0);
+ expect(container.querySelector('[data-annotation-part="text"]')).toHaveStyle({
+ opacity: '0',
+ visibility: 'hidden',
+ pointerEvents: 'none'
+ });
+ });
+});
diff --git a/src/components/src/annotations/annotation-text.tsx b/src/components/src/annotations/annotation-text.tsx
index c213c0cb5..65288a8f6 100644
--- a/src/components/src/annotations/annotation-text.tsx
+++ b/src/components/src/annotations/annotation-text.tsx
@@ -5,7 +5,12 @@ import React, {FC, useCallback, useEffect, useMemo} from 'react';
import styled from 'styled-components';
import {useDraggable} from '@dnd-kit/core';
import {Annotation} from '@kepler.gl/types';
-import {getAnnotationTextBoxStyle, MapViewport} from './annotation-utils';
+import {AnnotationKind} from '@kepler.gl/constants';
+import {
+ getAnnotationTextBoxStyle,
+ getRulerDistanceLabel,
+ MapViewport
+} from './annotation-utils';
import {LexicalRichTextEditor, LexicalToolbar} from './lexical-editor';
import {SerializedEditorState} from 'lexical';
@@ -13,6 +18,7 @@ type StyledAnnotationTextProps = {
$isEditing?: boolean;
$isSelected?: boolean;
$isEditingText?: boolean;
+ $isDraggable?: boolean;
$textVerticalAlign?: string;
};
@@ -34,7 +40,7 @@ const StyledAnnotationText = styled.div<StyledAnnotationTextProps>`
&:hover {
border-color: rgba(255,255,255,0.6);
}
- cursor: move;
+ cursor: ${props.$isDraggable ? 'move' : 'default'};
pointer-events: all;
`
: `
@@ -75,6 +81,11 @@ const StyledToolbarWrapper = styled.div`
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
`;
+const StyledRulerDistance = styled.div`
+ line-height: 1.4;
+ white-space: nowrap;
+`;
+
export type AnnotationTextProps = {
annotation: Annotation;
opacity?: number;
@@ -98,8 +109,14 @@ const AnnotationText: FC<AnnotationTextProps> = ({
onChangeText,
onUpdateAnnotation
}) => {
+ const isRuler = annotation.kind === AnnotationKind.RULER;
+ const showCustomText = !isRuler || annotation.showCustomText;
+ const distanceText =
+ isRuler && annotation.showDistance ? getRulerDistanceLabel(annotation) : '';
+ const isDraggable = !isRuler;
const {attributes, listeners, setNodeRef} = useDraggable({
- id: `${annotation.id}:MOVE_TEXT`
+ id: `${annotation.id}:MOVE_TEXT`,
+ disabled: !isDraggable
});
const {textWidth, textHeight, textVerticalAlign} = annotation;
@@ -117,10 +134,14 @@ const AnnotationText: FC<AnnotationTextProps> = ({
);
useEffect(() => {
- if (!isEditingText || !isSelected || !isEditing) {
+ if (!isEditingText || !isSelected || !isEditing || !showCustomText) {
window.getSelection()?.removeAllRanges();
}
- }, [isEditingText, isSelected, isEditing]);
+ }, [isEditingText, isSelected, isEditing, showCustomText]);
+
+ if (!showCustomText && !distanceText) {
+ return null;
+ }
return (
<StyledAnnotationText
@@ -128,6 +149,7 @@ const AnnotationText: FC<AnnotationTextProps> = ({
$isEditing={isEditing}
$isEditingText={isEditingText}
$isSelected={isSelected}
+ $isDraggable={isDraggable}
$textVerticalAlign={textVerticalAlign}
data-annotation-id={annotation.id}
data-annotation-part="text"
@@ -137,7 +159,7 @@ const AnnotationText: FC<AnnotationTextProps> = ({
visibility: opacity === 0 ? 'hidden' : undefined,
pointerEvents: opacity === 0 ? 'none' : undefined
}}
- {...(isEditing
+ {...(isEditing && isDraggable
? {
...attributes,
...listeners,
@@ -168,7 +190,7 @@ const AnnotationText: FC<AnnotationTextProps> = ({
}
evt.stopPropagation();
if (!isEditingText) {
- onSelect(true);
+ onSelect(showCustomText);
}
}}
onDoubleClick={() => {
@@ -177,26 +199,31 @@ const AnnotationText: FC<AnnotationTextProps> = ({
}
}}
>
- <LexicalRichTextEditor
- {...(isEditingText && annotation.autoSize ? {} : {width: textWidth || undefined})}
- {...(isEditingText && annotation.autoSizeY ? {} : {height: textHeight || undefined})}
- isEditable={isEditing && isEditingText}
- editorState={annotation.editorState as SerializedEditorState | undefined}
- initialText={annotation.label}
- onChange={handleEditorChange}
- >
- {isEditing && isSelected ? (
- <StyledToolbarWrapper>
- <LexicalToolbar
- isEditingText={isEditingText}
- textVerticalAlign={textVerticalAlign}
- onChangeTextVerticalAlign={value => {
- onUpdateAnnotation({textVerticalAlign: value});
- }}
- />
- </StyledToolbarWrapper>
- ) : null}
- </LexicalRichTextEditor>
+ {showCustomText ? (
+ <LexicalRichTextEditor
+ {...(isEditingText && annotation.autoSize ? {} : {width: textWidth || undefined})}
+ {...(isEditingText && annotation.autoSizeY ? {} : {height: textHeight || undefined})}
+ isEditable={isEditing && isEditingText}
+ editorState={annotation.editorState as SerializedEditorState | undefined}
+ initialText={annotation.label}
+ onChange={handleEditorChange}
+ >
+ {isEditing && isSelected ? (
+ <StyledToolbarWrapper>
+ <LexicalToolbar
+ isEditingText={isEditingText}
+ textVerticalAlign={textVerticalAlign}
+ onChangeTextVerticalAlign={value => {
+ onUpdateAnnotation({textVerticalAlign: value});
+ }}
+ />
+ </StyledToolbarWrapper>
+ ) : null}
+ </LexicalRichTextEditor>
+ ) : null}
+ {distanceText ? (
+ <StyledRulerDistance data-annotation-part="distance">{distanceText}</StyledRulerDistance>
+ ) : null}
</StyledAnnotationText>
);
};
diff --git a/src/components/src/annotations/annotation-utils.ts b/src/components/src/annotations/annotation-utils.ts
index bd7326d69..c9df9aa99 100644
--- a/src/components/src/annotations/annotation-utils.ts
+++ b/src/components/src/annotations/annotation-utils.ts
@@ -2,7 +2,10 @@
// Copyright contributors to the kepler.gl project
import {addMetersToLngLat} from '@math.gl/web-mercator';
-import {Annotation, AnnotationWithArm} from '@kepler.gl/types';
+import {Annotation, AnnotationWithArm, RulerAnnotation} from '@kepler.gl/types';
+import {formatLineLengthLabel} from '@kepler.gl/layers';
+import {point} from '@turf/helpers';
+import distance from '@turf/distance';
import {
AnnotationKind,
AnnotationTextSide,
@@ -46,7 +49,19 @@ export type CircleAnnotationMarker = BaseAnnotationMarker & {
r: number;
};
-export type AnnotationMarker = BaseAnnotationMarker | CircleAnnotationMarker;
+export type RulerAnnotationMarker = BaseAnnotationMarker & {
+ kind: AnnotationKind.RULER;
+ /** Second endpoint and midpoint, relative to x/y. */
+ ex: number;
+ ey: number;
+ mx: number;
+ my: number;
+};
+
+export type AnnotationMarker =
+ | BaseAnnotationMarker
+ | CircleAnnotationMarker
+ | RulerAnnotationMarker;
function degreesToRadians(degree: number): number {
return degree * (Math.PI / 180);
@@ -71,6 +86,25 @@ function calcRadius(viewport: MapViewport, point: LngLatAltitude, radiusInMeters
return Math.sqrt(dx * dx + dy * dy);
}
+/**
+ * Choose the geographically closest wrapped world copy before projecting. A
+ * distant copy can appear closer on screen under perspective projection.
+ */
+function projectClosestEndpoint(
+ viewport: MapViewport,
+ startPoint: LngLatAltitude,
+ endPoint: LngLatAltitude
+): [number, number] {
+ const altitude = endPoint[2];
+ const nearestWrap = Math.round((startPoint[0] - endPoint[0]) / 360);
+ const wrappedPoint = [endPoint[0] + nearestWrap * 360, endPoint[1]];
+ if (altitude !== undefined) wrappedPoint.push(altitude);
+ const [x, y] = viewport.project(wrappedPoint);
+ if (Number.isFinite(x) && Number.isFinite(y)) return [x, y];
+ const [sx, sy] = viewport.project(startPoint);
+ return [sx, sy];
+}
+
export function makeMarker(annotation: Annotation, viewport: MapViewport): AnnotationMarker {
const {kind, anchorPoint} = annotation;
const angle = isAnnotationWithArm(annotation) ? degreesToRadians(annotation.angle) : 0;
@@ -90,6 +124,14 @@ export function makeMarker(annotation: Annotation, viewport: MapViewport): Annot
const [tx, ty] = [Math.cos(angle) * armLength, Math.sin(angle) * armLength];
return {kind, x, y, tx, ty};
}
+ case AnnotationKind.RULER: {
+ const [endX, endY] = projectClosestEndpoint(viewport, anchorPoint, annotation.endPoint);
+ const ex = endX - x;
+ const ey = endY - y;
+ const mx = ex / 2;
+ const my = ey / 2;
+ return {kind, x, y, tx: mx, ty: my, ex, ey, mx, my};
+ }
case AnnotationKind.TEXT:
default:
return {kind, x, y, tx: 0, ty: 0};
@@ -129,6 +171,7 @@ export type AnnotationTextBoxStyle = {
right?: number;
borderTop?: string;
borderBottom?: string;
+ transform?: string;
};
export function getAnnotationTextBoxStyle(
@@ -142,6 +185,13 @@ export function getAnnotationTextBoxStyle(
const py = y + ty;
const style: AnnotationTextBoxStyle = autoSize ? {minWidth: 80} : {width: textWidth || 120};
+ if (kind === AnnotationKind.RULER) {
+ style.left = px;
+ style.top = py;
+ style.transform = 'translate(-50%, -50%)';
+ return style;
+ }
+
if (vertical === 'below') {
style.top = py;
if (kind !== AnnotationKind.TEXT) {
@@ -223,21 +273,81 @@ export function isPointVisibleOnGlobe(
return angularDistanceDeg(point, [roundTrip[0], roundTrip[1]]) < GLOBE_VISIBILITY_TOLERANCE_DEG;
}
-export function movePoint(
+/** A ruler is safe to draw as a DOM overlay only while both endpoints are visible. */
+export function isAnnotationVisibleOnGlobe(
annotation: Annotation,
+ viewport: MapViewport
+): boolean {
+ return (
+ isPointVisibleOnGlobe(annotation.anchorPoint, viewport) &&
+ (annotation.kind !== AnnotationKind.RULER ||
+ isPointVisibleOnGlobe(annotation.endPoint, viewport))
+ );
+}
+
+function moveCoordinate(
+ point: LngLatAltitude,
delta: {x: number; y: number},
viewport: MapViewport,
- pickWorldPosition?: PickWorldPosition
-): Partial<Annotation> {
- const {anchorPoint} = annotation;
- const [px, py] = viewport.project(anchorPoint);
+ pickWorldPosition?: PickWorldPosition,
+ projectedPoint?: [number, number]
+): LngLatAltitude {
+ const [px, py] = projectedPoint ?? viewport.project(point);
const screen: [number, number] = [px + delta.x, py + delta.y];
const picked = normalizeAnchorPoint(pickWorldPosition?.(screen));
if (picked) {
- return {anchorPoint: picked};
+ return picked;
}
const [lon, lat] = viewport.unproject(screen);
- return {anchorPoint: Number.isFinite(lon) && Number.isFinite(lat) ? [lon, lat] : anchorPoint};
+ return Number.isFinite(lon) && Number.isFinite(lat) ? [lon, lat] : point;
+}
+
+function normalizeRulerLongitude(point: LngLatAltitude): LngLatAltitude {
+ const longitude = (((point[0] + 180) % 360) + 360) % 360 - 180;
+ return point.length === 3 ? [longitude, point[1], point[2]] : [longitude, point[1]];
+}
+
+export function movePoint(
+ annotation: Annotation,
+ delta: {x: number; y: number},
+ viewport: MapViewport,
+ pickWorldPosition?: PickWorldPosition
+): Partial<Annotation> {
+ return {
+ anchorPoint: moveCoordinate(annotation.anchorPoint, delta, viewport, pickWorldPosition)
+ };
+}
+
+export function moveRulerEndpoint(
+ annotation: Annotation,
+ endpoint: 'start' | 'end',
+ delta: {x: number; y: number},
+ viewport: MapViewport,
+ pickWorldPosition?: PickWorldPosition
+): Partial<RulerAnnotation> {
+ if (annotation.kind !== AnnotationKind.RULER) return {};
+ if (endpoint === 'start') {
+ return {
+ // The start is the ruler's screen-space origin. Keep its unwrapped
+ // longitude so dragging across the dateline stays on the visible world
+ // copy; makeMarker wraps only the second endpoint relative to it.
+ anchorPoint: moveCoordinate(annotation.anchorPoint, delta, viewport, pickWorldPosition)
+ };
+ }
+ const marker = makeMarker(annotation, viewport) as RulerAnnotationMarker;
+ const projectedEndPoint: [number, number] = [marker.x + marker.ex, marker.y + marker.ey];
+ return {
+ endPoint: normalizeRulerLongitude(
+ moveCoordinate(annotation.endPoint, delta, viewport, pickWorldPosition, projectedEndPoint)
+ )
+ };
+}
+
+/** Existing editor convention: geodesic ground length in kilometers, rounded to 2 decimals. */
+export function getRulerDistanceLabel(annotation: Annotation): string {
+ if (annotation.kind !== AnnotationKind.RULER) return '';
+ const lengthKm = distance(point(annotation.anchorPoint), point(annotation.endPoint));
+ return formatLineLengthLabel(lengthKm);
}
export function moveText(
diff --git a/src/components/src/common/item-selector/item-selector.spec.tsx b/src/components/src/common/item-selector/item-selector.spec.tsx
index f430c8449..c11beb64c 100644
--- a/src/components/src/common/item-selector/item-selector.spec.tsx
+++ b/src/components/src/common/item-selector/item-selector.spec.tsx
@@ -31,6 +31,64 @@ beforeAll(() => {
});
describe('ItemSelector', () => {
+ test('keeps disabled single selectors out of the tab order and blocks keyboard opening', async () => {
+ const user = userEvent.setup();
+ renderWithTheme(
+ <IntlProvider locale="en" messages={messages.en}>
+ <ItemSelector
+ options={['Alpha', 'Beta']}
+ selectedItems="Alpha"
+ onChange={jest.fn()}
+ multiSelect={false}
+ searchable={false}
+ disabled={true}
+ />
+ </IntlProvider>
+ );
+ const selector = screen.getByRole('button', {name: 'Alpha'});
+
+ await user.tab();
+ expect(selector).not.toHaveFocus();
+ fireEvent.keyDown(selector, {key: 'Enter', keyCode: 13});
+ expect(screen.queryByText('Beta')).not.toBeInTheDocument();
+ });
+
+ test('opens a single selector with the keyboard and restores focus after selection or Escape', async () => {
+ const onChange = jest.fn();
+ const user = userEvent.setup();
+ renderWithTheme(
+ <IntlProvider locale="en" messages={messages.en}>
+ <ItemSelector
+ options={['Alpha', 'Beta']}
+ selectedItems="Alpha"
+ onChange={onChange}
+ multiSelect={false}
+ searchable={false}
+ />
+ </IntlProvider>
+ );
+ const selector = screen.getByText('Alpha').closest('.item-selector')!;
+
+ await user.tab();
+ expect(selector).toHaveFocus();
+ await user.keyboard('{Enter}');
+ expect(screen.getByText('Beta')).toBeInTheDocument();
+ fireEvent.keyDown(document.activeElement!, {key: 'ArrowDown', keyCode: 40});
+ fireEvent.keyDown(document.activeElement!, {key: 'ArrowDown', keyCode: 40});
+ fireEvent.keyDown(document.activeElement!, {key: 'Enter', keyCode: 13});
+
+ expect(onChange).toHaveBeenCalledWith('Beta');
+ expect(selector).toHaveFocus();
+ expect(screen.queryByText('Beta')).not.toBeInTheDocument();
+
+ await user.keyboard(' ');
+ expect(screen.getByText('Beta')).toBeInTheDocument();
+ await user.keyboard('{Escape}');
+ expect(screen.queryByText('Beta')).not.toBeInTheDocument();
+ expect(selector).toHaveFocus();
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
test('preserves object selections when Enter has no highlighted option', async () => {
const onChange = jest.fn();
const user = userEvent.setup();
diff --git a/src/components/src/common/item-selector/item-selector.tsx b/src/components/src/common/item-selector/item-selector.tsx
index c147204a7..0d3d7ab6a 100644
--- a/src/components/src/common/item-selector/item-selector.tsx
+++ b/src/components/src/common/item-selector/item-selector.tsx
@@ -243,7 +243,9 @@ class ItemSelectorUnmemoized extends Component<
}
this._preparingSelection = false;
if (this.props.closeOnSelect) {
- this.setState({showTypeahead: false, preparing: false});
+ this.setState({showTypeahead: false, preparing: false}, () => {
+ if (!this.props.multiSelect) this.root.current?.focus();
+ });
this._onBlur();
} else {
this.setState({preparing: false});
@@ -270,7 +272,7 @@ class ItemSelectorUnmemoized extends Component<
this.props.onChange(null);
};
- _showTypeahead: MouseEventHandler = e => {
+ _showTypeahead = (e: React.SyntheticEvent<unknown>) => {
e.stopPropagation();
if (!this.props.disabled) {
if (this.props.onOpen) {
@@ -282,6 +284,22 @@ class ItemSelectorUnmemoized extends Component<
}
};
+ _handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
+ if (this.props.multiSelect || this.props.disabled) return;
+ if (event.key === 'Escape' && this.state.showTypeahead) {
+ event.preventDefault();
+ event.stopPropagation();
+ this._hideTypeahead();
+ this.root.current?.focus();
+ } else if (
+ event.target === event.currentTarget &&
+ ['Enter', ' ', 'ArrowDown'].includes(event.key)
+ ) {
+ event.preventDefault();
+ this._showTypeahead(event);
+ }
+ };
+
_renderDropdown(intl: IntlShape) {
const {placement = 'bottom'} = this.props;
const {dimensions} = this.state;
@@ -351,7 +369,15 @@ class ItemSelectorUnmemoized extends Component<
const intl = this.props.intl;
return (
- <div className={classnames('item-selector', this.props.className)} ref={this.root}>
+ <div
+ className={classnames('item-selector', this.props.className)}
+ ref={this.root}
+ role={this.props.multiSelect ? undefined : 'button'}
+ tabIndex={!this.props.multiSelect && !disabled ? 0 : undefined}
+ aria-expanded={this.props.multiSelect ? undefined : this.state.showTypeahead}
+ aria-disabled={this.props.multiSelect ? undefined : Boolean(disabled)}
+ onKeyDown={this._handleKeyDown}
+ >
<div style={{position: 'relative'}}>
{/* this part is used to display the label */}
{this.props.multiSelect ? (
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index b36f20bce..a862ee0cd 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -409,6 +409,7 @@ export {AnnotationText} from './annotations';
export {
makeMarker,
movePoint,
+ moveRulerEndpoint,
moveText,
resizeCircle,
isLeftOriented,
@@ -417,10 +418,18 @@ export {
angleForTextPlacement,
textPlacementFromAngle,
getAnnotationTextBoxStyle,
+ getRulerDistanceLabel,
+ isAnnotationVisibleOnGlobe,
isPointVisibleOnGlobe,
normalizeAnchorPoint
} from './annotations';
-export type {MapViewport, AnnotationMarker, PickWorldPosition, LngLatAltitude} from './annotations';
+export type {
+ MapViewport,
+ AnnotationMarker,
+ RulerAnnotationMarker,
+ PickWorldPosition,
+ LngLatAltitude
+} from './annotations';
export {default as AnnotationControlFactory} from './map/annotations/annotation-control';
export {default as ColorBreaksPanelFactory} from './side-panel/layer-panel/color-breaks-panel';
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index 5ff05c8ee..9f5afa25b 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -1230,7 +1230,8 @@ export default function MapContainerFactory(
mapboxApiAccessToken,
mapboxApiUrl,
layersForDeck,
- isAnnotationMode: Boolean(mapControls?.annotation?.active),
+ isAnnotationMode:
+ Boolean(mapControls?.annotation?.active) && !Boolean(this.props.readOnly),
editorInfo: primaryMap
? {
editor,
@@ -1756,7 +1757,9 @@ export default function MapContainerFactory(
}
selectedAnnotationId={visState.selectedAnnotationId}
isEditingAnnotationText={visState.isEditingAnnotationText}
- isAnnotationMode={Boolean(mapControls?.annotation?.active)}
+ isAnnotationMode={
+ Boolean(mapControls?.annotation?.active) && !Boolean(this.props.readOnly)
+ }
mapIndex={index || 0}
viewport={this._getAnnotationViewport(mapState, internalViewState)}
isGlobeEnabled={Boolean(mapState.globe?.enabled)}
diff --git a/src/constants/src/annotation.ts b/src/constants/src/annotation.ts
index 0e4167796..b35b1a6ab 100644
--- a/src/constants/src/annotation.ts
+++ b/src/constants/src/annotation.ts
@@ -5,7 +5,8 @@ export enum AnnotationKind {
TEXT = 'TEXT',
ARROW = 'ARROW',
POINT = 'POINT',
- CIRCLE = 'CIRCLE'
+ CIRCLE = 'CIRCLE',
+ RULER = 'RULER'
}
export function isAnnotationKind(kind: string): kind is AnnotationKind {
@@ -25,6 +26,7 @@ export const INITIAL_ANNOTATION_TEXT_WIDTH = 0;
export const INITIAL_ANNOTATION_TEXT_HEIGHT = 0;
export const INITIAL_ANNOTATION_LINE_WIDTH = 2;
export const INITIAL_ANNOTATION_LINE_COLOR = '#FFFFFF';
+export const INITIAL_ANNOTATION_RULER_LENGTH_METERS = 1000;
export type AnnotationTextSide = 'left' | 'right';
export type AnnotationTextVerticalPosition = 'above' | 'below';
@@ -36,7 +38,8 @@ export const ANNOTATION_KINDS = [
{id: AnnotationKind.TEXT, label: 'Text'},
{id: AnnotationKind.POINT, label: 'Point'},
{id: AnnotationKind.ARROW, label: 'Arrow'},
- {id: AnnotationKind.CIRCLE, label: 'Circle'}
+ {id: AnnotationKind.CIRCLE, label: 'Circle'},
+ {id: AnnotationKind.RULER, label: 'Ruler'}
];
export const ANNOTATION_LINE_WIDTH_OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index e4228135d..0d659bc63 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -356,6 +356,8 @@ export default {
type: 'Type',
lineWidth: 'Line Width',
color: 'Color',
+ customText: 'Custom Text',
+ distance: 'Distance',
textSide: 'Text Side',
textPlacement: 'Placement'
},
diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.ts
index 5216da174..01a9f9901 100644
--- a/src/reducers/src/vis-state-merger.ts
+++ b/src/reducers/src/vis-state-merger.ts
@@ -30,6 +30,7 @@ import {
DEFAULT_TEXT_LABEL,
LAYER_BLENDINGS,
OVERLAY_BLENDINGS,
+ AnnotationKind,
isAnnotationKind,
INITIAL_ANNOTATION_LINE_COLOR,
INITIAL_ANNOTATION_LINE_WIDTH
@@ -863,7 +864,11 @@ export function mergeAnnotations<S extends VisState>(state: S, annotations: any[
isAnnotationKind(a.kind) &&
Array.isArray(a.anchorPoint) &&
(a.anchorPoint.length === 2 || a.anchorPoint.length === 3) &&
- a.anchorPoint.every(value => Number.isFinite(value))
+ a.anchorPoint.every(value => Number.isFinite(value)) &&
+ (a.kind !== AnnotationKind.RULER ||
+ (Array.isArray(a.endPoint) &&
+ (a.endPoint.length === 2 || a.endPoint.length === 3) &&
+ a.endPoint.every(value => Number.isFinite(value))))
)
.map(a => ({
isVisible: true,
@@ -874,7 +879,13 @@ export function mergeAnnotations<S extends VisState>(state: S, annotations: any[
lineWidth: INITIAL_ANNOTATION_LINE_WIDTH,
textWidth: 0,
textHeight: 0,
- ...a
+ ...a,
+ ...(a.kind === AnnotationKind.RULER
+ ? {
+ showCustomText: a.showCustomText ?? true,
+ showDistance: a.showDistance ?? true
+ }
+ : {})
}));
if (!validAnnotations.length) {
return state;
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index 263c09b32..7ea9f4f60 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -130,6 +130,7 @@ import {
INITIAL_ANNOTATION_TEXT_HEIGHT,
INITIAL_ANNOTATION_LINE_WIDTH,
INITIAL_ANNOTATION_LINE_COLOR,
+ INITIAL_ANNOTATION_RULER_LENGTH_METERS,
INITIAL_ANNOTATION_TEXT_SIDE,
INITIAL_ANNOTATION_TEXT_VERTICAL_POSITION,
ANNOTATION_ANGLE_BY_PLACEMENT,
@@ -200,6 +201,7 @@ import {
LayerChartConfig
} from '@kepler.gl/types';
import {Loader} from '@loaders.gl/loader-utils';
+import {addMetersToLngLat} from '@math.gl/web-mercator';
import {
Datasets,
@@ -3053,11 +3055,15 @@ function makeNewAnnotation(config?: AnnotationPropsPartial): Annotation {
const textSide =
config?.textSide ??
derivedFromAngle?.side ??
- (kind === AnnotationKind.TEXT ? undefined : INITIAL_ANNOTATION_TEXT_SIDE);
+ (kind === AnnotationKind.TEXT || kind === AnnotationKind.RULER
+ ? undefined
+ : INITIAL_ANNOTATION_TEXT_SIDE);
const textVerticalPosition =
config?.textVerticalPosition ??
derivedFromAngle?.vertical ??
- (kind === AnnotationKind.TEXT ? undefined : INITIAL_ANNOTATION_TEXT_VERTICAL_POSITION);
+ (kind === AnnotationKind.TEXT || kind === AnnotationKind.RULER
+ ? undefined
+ : INITIAL_ANNOTATION_TEXT_VERTICAL_POSITION);
const base = {
id: config?.id ?? generateHashId(6),
kind,
@@ -3066,6 +3072,7 @@ function makeNewAnnotation(config?: AnnotationPropsPartial): Annotation {
autoSizeY: config?.autoSizeY ?? true,
anchorPoint: config?.anchorPoint ?? ([0, 0] as [number, number]),
label: config?.label ?? 'New Annotation',
+ ...(config?.editorState ? {editorState: config.editorState} : {}),
lineColor: config?.lineColor ?? INITIAL_ANNOTATION_LINE_COLOR,
lineWidth: config?.lineWidth ?? INITIAL_ANNOTATION_LINE_WIDTH,
textWidth: config?.textWidth ?? INITIAL_ANNOTATION_TEXT_WIDTH,
@@ -3104,6 +3111,26 @@ function makeNewAnnotation(config?: AnnotationPropsPartial): Annotation {
angle: providedAngle ?? defaultAngle,
radiusInMeters: (config as any)?.radiusInMeters ?? 1000
};
+ case AnnotationKind.RULER: {
+ const anchorPoint = base.anchorPoint;
+ const shifted = addMetersToLngLat(anchorPoint, [
+ INITIAL_ANNOTATION_RULER_LENGTH_METERS,
+ 0,
+ 0
+ ]);
+ const altitude = anchorPoint[2];
+ const defaultEndPoint =
+ altitude !== undefined && Number.isFinite(altitude)
+ ? ([shifted[0], shifted[1], altitude] as [number, number, number])
+ : ([shifted[0], shifted[1]] as [number, number]);
+ return {
+ ...base,
+ kind: AnnotationKind.RULER,
+ endPoint: (config as any)?.endPoint ?? defaultEndPoint,
+ showCustomText: (config as any)?.showCustomText ?? true,
+ showDistance: (config as any)?.showDistance ?? true
+ };
+ }
case AnnotationKind.TEXT:
default:
return {
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index 4e8f9ae02..52a50e013 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -973,7 +973,10 @@ const annotationPropsV1 = {
textVerticalPosition: null,
armLength: null,
angle: null,
- radiusInMeters: null
+ radiusInMeters: null,
+ endPoint: null,
+ showCustomText: null,
+ showDistance: null
};
export class AnnotationsSchema extends Schema {
diff --git a/src/types/annotations.d.ts b/src/types/annotations.d.ts
index d539ed638..3642d0cfd 100644
--- a/src/types/annotations.d.ts
+++ b/src/types/annotations.d.ts
@@ -52,6 +52,21 @@ export type CircleAnnotation = AnnotationWithArm & {
radiusInMeters: number;
};
-export type Annotation = TextAnnotation | PointAnnotation | ArrowAnnotation | CircleAnnotation;
+export type RulerAnnotation = BaseAnnotation & {
+ kind: AnnotationKind.RULER;
+ /** Second [lng, lat] or [lng, lat, altitudeMeters] endpoint. */
+ endPoint: [number, number] | [number, number, number];
+ /** Whether the user-authored rich text is rendered at the ruler midpoint. */
+ showCustomText: boolean;
+ /** Whether the computed geodesic length is rendered at the ruler midpoint. */
+ showDistance: boolean;
+};
+
+export type Annotation =
+ | TextAnnotation
+ | PointAnnotation
+ | ArrowAnnotation
+ | CircleAnnotation
+ | RulerAnnotation;
export type AnnotationPropsPartial = Partial<Annotation>;
diff --git a/test/node/reducers/annotation-merger-test.js b/test/node/reducers/annotation-merger-test.js
index f130afdbf..685a50fb0 100644
--- a/test/node/reducers/annotation-merger-test.js
+++ b/test/node/reducers/annotation-merger-test.js
@@ -96,22 +96,43 @@ test('#mergeAnnotations -> should validate annotation kind', t => {
makeAnnotation({id: 'point', kind: AnnotationKind.POINT}),
makeAnnotation({id: 'arrow', kind: AnnotationKind.ARROW}),
makeAnnotation({id: 'circle', kind: AnnotationKind.CIRCLE}),
+ makeAnnotation({id: 'ruler', kind: AnnotationKind.RULER, endPoint: [1, 1]}),
makeAnnotation({id: 'invalid', kind: 'HEXAGON'})
];
const result = mergeAnnotations(state, annotations);
- t.equal(result.annotations.length, 4, 'should accept 4 valid kinds');
+ t.equal(result.annotations.length, 5, 'should accept 5 valid kinds');
const ids = result.annotations.map(a => a.id);
t.ok(ids.includes('text'), 'TEXT is valid');
t.ok(ids.includes('point'), 'POINT is valid');
t.ok(ids.includes('arrow'), 'ARROW is valid');
t.ok(ids.includes('circle'), 'CIRCLE is valid');
+ t.ok(ids.includes('ruler'), 'RULER is valid');
t.notOk(ids.includes('invalid'), 'HEXAGON is invalid');
t.end();
});
+test('#mergeAnnotations -> should validate RULER endPoint', t => {
+ const state = makeState();
+ const annotations = [
+ makeAnnotation({id: 'valid-ruler', kind: AnnotationKind.RULER, endPoint: [1, 2, 3]}),
+ makeAnnotation({id: 'missing-end', kind: AnnotationKind.RULER}),
+ makeAnnotation({id: 'bad-end', kind: AnnotationKind.RULER, endPoint: [1, Number.NaN]})
+ ];
+
+ const result = mergeAnnotations(state, annotations);
+
+ t.equal(result.annotations.length, 1, 'only ruler with a finite 2D/3D endpoint should merge');
+ t.equal(result.annotations[0].id, 'valid-ruler', 'valid ruler should be preserved');
+ t.deepEqual(result.annotations[0].endPoint, [1, 2, 3], '3D endpoint should be preserved');
+ t.equal(result.annotations[0].showCustomText, true, 'missing custom text flag should default on');
+ t.equal(result.annotations[0].showDistance, true, 'missing distance flag should default on');
+
+ t.end();
+});
+
test('#mergeAnnotations -> should not stamp default text placement on legacy annotations', t => {
const state = makeState();
const annotations = [
diff --git a/test/node/reducers/annotation-updater-test.js b/test/node/reducers/annotation-updater-test.js
index 0a07ea946..92f5a22b2 100644
--- a/test/node/reducers/annotation-updater-test.js
+++ b/test/node/reducers/annotation-updater-test.js
@@ -92,6 +92,67 @@ test('#visStateReducer -> ADD_ANNOTATION with ARROW kind', t => {
t.end();
});
+test('#visStateReducer -> ADD_ANNOTATION with RULER kind', t => {
+ const state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ id: 'ruler-1',
+ anchorPoint: [0, 0, 25],
+ kind: AnnotationKind.RULER
+ })
+ );
+
+ const ruler = state.annotations[0];
+ t.equal(ruler.kind, AnnotationKind.RULER, 'should create a RULER annotation');
+ t.equal(ruler.endPoint.length, 3, 'default end should keep the start altitude');
+ t.equal(ruler.endPoint[2], 25, 'default endpoints should begin at the same altitude');
+ t.equal(ruler.showCustomText, true, 'custom text should be enabled by default');
+ t.equal(ruler.showDistance, true, 'distance should be enabled by default');
+ t.notOk('armLength' in ruler, 'RULER should not use leader-arm geometry');
+
+ t.end();
+});
+
+test('#visStateReducer -> multiple RULER annotations update independently', t => {
+ let state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ id: 'ruler-1',
+ kind: AnnotationKind.RULER,
+ anchorPoint: [0, 0],
+ endPoint: [1, 0]
+ })
+ );
+ state = reducer(
+ state,
+ VisStateActions.addAnnotation({
+ id: 'ruler-2',
+ kind: AnnotationKind.RULER,
+ anchorPoint: [10, 10],
+ endPoint: [11, 10]
+ })
+ );
+ state = reducer(
+ state,
+ VisStateActions.updateAnnotation('ruler-1', {
+ endPoint: [2, 0],
+ showCustomText: false,
+ showDistance: false
+ })
+ );
+
+ const first = state.annotations.find(annotation => annotation.id === 'ruler-1');
+ const second = state.annotations.find(annotation => annotation.id === 'ruler-2');
+ t.deepEqual(first.endPoint, [2, 0], 'target ruler endpoint should update');
+ t.equal(first.showCustomText, false, 'target custom text can be disabled');
+ t.equal(first.showDistance, false, 'target distance can be disabled simultaneously');
+ t.deepEqual(second.endPoint, [11, 10], 'other ruler endpoint should remain unchanged');
+ t.equal(second.showCustomText, true, 'other ruler text setting should remain unchanged');
+ t.equal(second.showDistance, true, 'other ruler distance setting should remain unchanged');
+
+ t.end();
+});
+
test('#visStateReducer -> ADD_ANNOTATION derives placement from angle', t => {
const state = reducer(
initialState,
@@ -227,6 +288,47 @@ test('#visStateReducer -> UPDATE_ANNOTATION text placement snaps arm angle', t =
t.end();
});
+test('#visStateReducer -> kind changes preserve rich text, including conversions to rulers', t => {
+ const editorState = {
+ root: {
+ children: [
+ {
+ children: [{type: 'text', version: 1, text: 'Formatted label', format: 1}],
+ type: 'paragraph',
+ version: 1,
+ direction: null,
+ format: '',
+ indent: 0
+ }
+ ],
+ type: 'root',
+ version: 1,
+ direction: null,
+ format: '',
+ indent: 0
+ }
+ };
+ let state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({id: 'formatted', label: 'Formatted label'})
+ );
+ state = reducer(state, VisStateActions.updateAnnotation('formatted', {editorState}));
+
+ for (const kind of [
+ AnnotationKind.RULER,
+ AnnotationKind.POINT,
+ AnnotationKind.ARROW,
+ AnnotationKind.CIRCLE,
+ AnnotationKind.TEXT
+ ]) {
+ state = reducer(state, VisStateActions.updateAnnotation('formatted', {kind}));
+ t.deepEqual(state.annotations[0].editorState, editorState, `${kind} keeps rich-text formatting`);
+ t.equal(state.annotations[0].label, 'Formatted label', `${kind} keeps the plain text label`);
+ }
+
+ t.end();
+});
+
test('#visStateReducer -> UPDATE_ANNOTATION with invalid id', t => {
let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
diff --git a/test/node/schemas/annotation-schema-test.js b/test/node/schemas/annotation-schema-test.js
index 9e8ca9da4..a12582999 100644
--- a/test/node/schemas/annotation-schema-test.js
+++ b/test/node/schemas/annotation-schema-test.js
@@ -25,7 +25,10 @@ const annotationPropsV1 = {
textVerticalPosition: null,
armLength: null,
angle: null,
- radiusInMeters: null
+ radiusInMeters: null,
+ endPoint: null,
+ showCustomText: null,
+ showDistance: null
};
const schema = new AnnotationsSchema({
@@ -102,6 +105,27 @@ const makeTextAnnotation = (overrides = {}) => ({
...overrides
});
+const makeRulerAnnotation = (overrides = {}) => ({
+ id: 'ann-ruler-1',
+ kind: AnnotationKind.RULER,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [-122.4, 37.8, 20],
+ endPoint: [-122.39, 37.81, 80],
+ label: 'Measured span',
+ editorState: null,
+ mapIndex: 0,
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 120,
+ textHeight: 40,
+ textVerticalAlign: 'middle',
+ showCustomText: false,
+ showDistance: true,
+ ...overrides
+});
+
test('#AnnotationsSchema -> save', t => {
const annotations = [makePointAnnotation(), makeCircleAnnotation()];
@@ -164,12 +188,17 @@ test('#AnnotationsSchema -> load', t => {
});
test('#AnnotationsSchema -> save/load round-trip', t => {
- const original = [makePointAnnotation(), makeCircleAnnotation(), makeTextAnnotation()];
+ const original = [
+ makePointAnnotation(),
+ makeCircleAnnotation(),
+ makeTextAnnotation(),
+ makeRulerAnnotation()
+ ];
const saved = schema.save(original);
const loaded = schema.load(saved.annotations);
- t.equal(loaded.annotations.length, 3, 'should round-trip 3 annotations');
+ t.equal(loaded.annotations.length, 4, 'should round-trip 4 annotations');
// Check point
t.equal(loaded.annotations[0].id, 'ann-point-1', 'point id round-trips');
@@ -204,6 +233,16 @@ test('#AnnotationsSchema -> save/load round-trip', t => {
t.equal(loaded.annotations[2].kind, AnnotationKind.TEXT, 'text kind round-trips');
t.equal(loaded.annotations[2].textVerticalAlign, 'middle', 'text textVerticalAlign round-trips');
+ // Check ruler
+ t.equal(loaded.annotations[3].kind, AnnotationKind.RULER, 'ruler kind round-trips');
+ t.deepEqual(
+ loaded.annotations[3].endPoint,
+ [-122.39, 37.81, 80],
+ 'ruler 3D endPoint round-trips'
+ );
+ t.equal(loaded.annotations[3].showCustomText, false, 'custom text checkbox round-trips');
+ t.equal(loaded.annotations[3].showDistance, true, 'distance checkbox round-trips');
+
t.end();
});
diff --git a/test/node/utils/annotation-utils-test.js b/test/node/utils/annotation-utils-test.js
index 2dbd43b9f..9b8c754a0 100644
--- a/test/node/utils/annotation-utils-test.js
+++ b/test/node/utils/annotation-utils-test.js
@@ -2,16 +2,20 @@
// Copyright contributors to the kepler.gl project
import test from 'tape';
+import {WebMercatorViewport} from '@deck.gl/core';
import {AnnotationKind} from '@kepler.gl/constants';
import {
makeMarker,
movePoint,
+ moveRulerEndpoint,
moveText,
resizeCircle,
isLeftOriented,
isBelowOriented,
getTextPlacement,
getAnnotationTextBoxStyle,
+ getRulerDistanceLabel,
+ isAnnotationVisibleOnGlobe,
isPointVisibleOnGlobe,
normalizeAnchorPoint
} from '@kepler.gl/components';
@@ -76,6 +80,24 @@ const makeCircleAnnotation = (overrides = {}) => ({
...overrides
});
+const makeRulerAnnotation = (overrides = {}) => ({
+ id: 'test-ruler',
+ kind: AnnotationKind.RULER,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ endPoint: [1, 0],
+ label: 'Ruler',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ showCustomText: true,
+ showDistance: true,
+ ...overrides
+});
+
test('#isLeftOriented', t => {
t.equal(isLeftOriented(0), false, '0 degrees is right-oriented');
t.equal(isLeftOriented(45), false, '45 degrees is right-oriented');
@@ -216,6 +238,100 @@ test('#makeMarker -> POINT annotation', t => {
t.end();
});
+test('#makeMarker -> RULER uses projected 3D endpoints and their screen midpoint', t => {
+ const marker = makeMarker(
+ makeRulerAnnotation({anchorPoint: [0, 0, 10], endPoint: [2, 0, 30]}),
+ mockViewport
+ );
+
+ t.equal(marker.kind, AnnotationKind.RULER, 'should return RULER kind');
+ t.equal(marker.x, 500, 'start x should be projected');
+ t.equal(marker.y, 290, 'start altitude should affect projected y');
+ t.equal(marker.ex, 20, 'end x should be relative to the start');
+ t.equal(marker.ey, -20, 'different endpoint altitude should affect the line');
+ t.equal(marker.mx, 10, 'midpoint x should bisect the projected line');
+ t.equal(marker.my, -10, 'midpoint y should bisect the projected line');
+
+ t.end();
+});
+
+test('#makeMarker -> RULER crosses the dateline through the closest world copy', t => {
+ const wrappingViewport = {
+ ...mockViewport,
+ project: ([lng, lat]) => [lng, lat]
+ };
+ const marker = makeMarker(
+ makeRulerAnnotation({anchorPoint: [179, 0], endPoint: [-179, 0]}),
+ wrappingViewport
+ );
+
+ t.equal(marker.ex, 2, 'dateline ruler should span two degrees, not 358');
+ t.equal(marker.mx, 1, 'text midpoint should stay halfway along the short segment');
+
+ t.end();
+});
+
+test('#makeMarker -> RULER follows a start more than one wrapped world away', t => {
+ const wrappingViewport = {
+ ...mockViewport,
+ project: ([lng, lat]) => [lng, lat]
+ };
+ const marker = makeMarker(
+ makeRulerAnnotation({anchorPoint: [541, 0], endPoint: [-178, 0]}),
+ wrappingViewport
+ );
+
+ t.equal(marker.ex, 1, 'end should use the +720 degree world copy nearest the start');
+ t.equal(marker.mx, 0.5, 'midpoint should remain on that short rendered segment');
+
+ t.end();
+});
+
+test('#makeMarker -> RULER keeps the nearest longitude wrap under perspective', t => {
+ const viewport = new WebMercatorViewport({
+ width: 1000,
+ height: 600,
+ longitude: 0,
+ latitude: 0,
+ zoom: 6,
+ pitch: 60,
+ bearing: 90
+ });
+ const ruler = makeRulerAnnotation({anchorPoint: [7.1444, 0], endPoint: [-3.1732, 0]});
+ const start = viewport.project(ruler.anchorPoint);
+ const end = viewport.project(ruler.endPoint);
+ const marker = makeMarker(ruler, viewport);
+ const style = getAnnotationTextBoxStyle(ruler, viewport);
+
+ t.equal(marker.ex, end[0] - start[0], 'end x should use the nearest geographic world copy');
+ t.equal(marker.ey, end[1] - start[1], 'end y should use the nearest geographic world copy');
+ t.equal(style.left, (start[0] + end[0]) / 2, 'label x should bisect the correct endpoints');
+ t.equal(style.top, (start[1] + end[1]) / 2, 'label y should bisect the correct endpoints');
+
+ let pickedScreen;
+ moveRulerEndpoint(ruler, 'end', {x: 3, y: 5}, viewport, screen => {
+ pickedScreen = screen;
+ return null;
+ });
+ t.deepEqual(pickedScreen, [end[0] + 3, end[1] + 5], 'dragging should start at the visible end');
+
+ t.end();
+});
+
+test('#getAnnotationTextBoxStyle -> RULER centers text on the projected midpoint', t => {
+ const style = getAnnotationTextBoxStyle(
+ makeRulerAnnotation({anchorPoint: [0, 0, 10], endPoint: [2, 0, 30]}),
+ mockViewport
+ );
+
+ t.equal(style.left, 510, 'midpoint x should account for both endpoints');
+ t.equal(style.top, 280, 'midpoint y should account for both endpoint altitudes');
+ t.equal(style.transform, 'translate(-50%, -50%)', 'text should be centered on midpoint');
+ t.notOk(style.borderTop, 'ruler text should not draw an annotation leader border');
+
+ t.end();
+});
+
test('#makeMarker -> TEXT annotation', t => {
const annotation = makeTextAnnotation({anchorPoint: [5, 10]});
const marker = makeMarker(annotation, mockViewport);
@@ -295,6 +411,89 @@ test('#movePoint -> falls back to ground plane when pick returns no altitude', t
t.end();
});
+test('#moveRulerEndpoint -> moves endpoints independently using 3D surface picks', t => {
+ const ruler = makeRulerAnnotation({anchorPoint: [0, 0, 5], endPoint: [1, 1, 10]});
+ const movedStart = moveRulerEndpoint(
+ ruler,
+ 'start',
+ {x: 5, y: 5},
+ mockViewport,
+ () => [2, 3, 40]
+ );
+ const movedEnd = moveRulerEndpoint(
+ ruler,
+ 'end',
+ {x: 5, y: 5},
+ mockViewport,
+ () => [4, 5, 80]
+ );
+
+ t.deepEqual(movedStart.anchorPoint, [2, 3, 40], 'start should snap to its picked surface');
+ t.notOk('endPoint' in movedStart, 'moving start should not change end');
+ t.deepEqual(movedEnd.endPoint, [4, 5, 80], 'end should snap to its picked surface');
+ t.notOk('anchorPoint' in movedEnd, 'moving end should not change start');
+
+ t.end();
+});
+
+test('#moveRulerEndpoint -> falls back to elevation 0 for either endpoint', t => {
+ const ruler = makeRulerAnnotation({anchorPoint: [0, 0, 5], endPoint: [1, 1, 10]});
+ const changes = moveRulerEndpoint(ruler, 'end', {x: 10, y: -5}, mockViewport, () => null);
+
+ t.equal(changes.endPoint.length, 2, 'ground fallback should omit altitude');
+ t.deepEqual(changes.endPoint, [2, 2.5], 'fallback should use viewport ground unprojection');
+
+ t.end();
+});
+
+test('#moveRulerEndpoint -> drags from the rendered world copy across the dateline', t => {
+ const wrappingViewport = {
+ ...mockViewport,
+ project: ([lng, lat]) => [lng, lat],
+ unproject: ([x, y]) => [x, y]
+ };
+ const ruler = makeRulerAnnotation({anchorPoint: [179, 0], endPoint: [-179, 0]});
+ let pickedScreen;
+ const changes = moveRulerEndpoint(
+ ruler,
+ 'end',
+ {x: 1, y: 0},
+ wrappingViewport,
+ screen => {
+ pickedScreen = screen;
+ return null;
+ }
+ );
+
+ t.deepEqual(pickedScreen, [182, 0], 'surface pick should start at the visible +181 handle');
+ t.deepEqual(changes.endPoint, [-178, 0], 'stored longitude should remain normalized');
+
+ t.end();
+});
+
+test('#moveRulerEndpoint -> keeps the start on its visible world copy across the dateline', t => {
+ const wrappingViewport = {
+ ...mockViewport,
+ project: ([lng, lat]) => [lng, lat],
+ unproject: ([x, y]) => [x, y]
+ };
+ const ruler = makeRulerAnnotation({anchorPoint: [179, 0], endPoint: [-179, 0]});
+ const changes = moveRulerEndpoint(ruler, 'start', {x: 2, y: 0}, wrappingViewport, () => null);
+
+ t.deepEqual(changes.anchorPoint, [181, 0], 'start should remain on the adjacent +181 world copy');
+
+ t.end();
+});
+
+test('#getRulerDistanceLabel -> follows geodesic kilometer measurement convention', t => {
+ t.equal(
+ getRulerDistanceLabel(makeRulerAnnotation({anchorPoint: [0, 0, 10], endPoint: [1, 0, 80]})),
+ 'Length: 111.20 km',
+ 'distance should use ground geodesic length and existing two-decimal format'
+ );
+ t.end();
+});
+
test('#normalizeAnchorPoint', t => {
t.deepEqual(normalizeAnchorPoint([1, 2]), [1, 2], 'keeps 2D anchors');
t.deepEqual(normalizeAnchorPoint([1, 2, 3]), [1, 2, 3], 'keeps 3D anchors');
@@ -484,3 +683,29 @@ test('#isPointVisibleOnGlobe -> non-finite projection is treated as not visible'
t.end();
});
+
+test('#isAnnotationVisibleOnGlobe -> RULER requires both endpoints on the visible hemisphere', t => {
+ const viewport = {
+ project: ([lng, lat]) => [lng, lat],
+ unproject: ([x, y]) => (x > 90 ? [0, 0] : [x, y])
+ };
+
+ t.equal(
+ isAnnotationVisibleOnGlobe(
+ makeRulerAnnotation({anchorPoint: [10, 0], endPoint: [120, 0]}),
+ viewport
+ ),
+ false,
+ 'ruler should hide rather than render through the globe when one endpoint is occluded'
+ );
+ t.equal(
+ isAnnotationVisibleOnGlobe(
+ makeRulerAnnotation({anchorPoint: [10, 0], endPoint: [20, 0]}),
+ viewport
+ ),
+ true,
+ 'ruler should show when both endpoints are visible'
+ );
+
+ t.end();
+});
diff --git a/test/node/utils/export-utils-test.js b/test/node/utils/export-utils-test.js
index c9abd81b4..d687b639e 100644
--- a/test/node/utils/export-utils-test.js
+++ b/test/node/utils/export-utils-test.js
@@ -76,6 +76,37 @@ test('exportUtils -> ExportHtml includes map info', t => {
t.end();
});
+test('exportUtils -> ExportHtml preserves ruler annotation geometry and text settings', t => {
+ const html = exportMapToHTML({
+ datasets: [],
+ config: {
+ version: 'v1',
+ config: {
+ visState: {
+ annotations: [
+ {
+ id: 'ruler-1',
+ kind: 'RULER',
+ anchorPoint: [0, 0, 10],
+ endPoint: [1, 1, 80],
+ showCustomText: false,
+ showDistance: true
+ }
+ ]
+ }
+ }
+ },
+ mode: 'READ'
+ });
+
+ t.ok(html.includes('"kind":"RULER"'), 'HTML should embed the ruler variant');
+ t.ok(html.includes('"endPoint":[1,1,80]'), 'HTML should embed its 3D endpoint');
+ t.ok(html.includes('"showCustomText":false'), 'HTML should embed custom-text visibility');
+ t.ok(html.includes('"showDistance":true'), 'HTML should embed distance visibility');
+
+ t.end();
+});
+
test('exportUtils -> ExportHtml mounts editable and view-only export controls', t => {
const editHtml = exportMapToHTML({
datasets: [],