Skip to content

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

feat: basic annotations (#3434)

Igor Dykhta3bca7250195f
diff --git a/examples/demo-app/src/factories/map-control.js b/examples/demo-app/src/factories/map-control.js
index b8f5b91b5..b73bb3b84 100644
--- a/examples/demo-app/src/factories/map-control.js
+++ b/examples/demo-app/src/factories/map-control.js
@@ -8,7 +8,8 @@ import {
withState,
MapControlFactory,
EffectControlFactory,
- EffectManagerFactory
+ EffectManagerFactory,
+ AnnotationManagerFactory
} from '@kepler.gl/components';
import {AiAssistantControlFactory} from '@kepler.gl/ai-assistant';
@@ -58,6 +59,7 @@ const StyledMapControlOverlay = styled.div`
CustomMapControlFactory.deps = [
EffectControlFactory,
EffectManagerFactory,
+ AnnotationManagerFactory,
SqlPanelControlFactory,
AiAssistantControlFactory,
...MapControlFactory.deps
@@ -65,6 +67,7 @@ CustomMapControlFactory.deps = [
function CustomMapControlFactory(
EffectControl,
EffectManager,
+ AnnotationManager,
SqlPanelControl,
AiAssistantControl,
...deps
@@ -79,8 +82,10 @@ function CustomMapControlFactory(
const CustomMapControl = props => {
const showEffects = Boolean(props.mapControls?.effect?.active);
+ const showAnnotations = Boolean(props.mapControls?.annotation?.active);
+ const rightPanelVisible = showEffects || showAnnotations;
return (
- <StyledMapControlOverlay top={props.top} rightPanelVisible={showEffects}>
+ <StyledMapControlOverlay top={props.top} rightPanelVisible={rightPanelVisible}>
<StyledMapControlPanel>
{<BannerMapPanel {...props} />}
{!props.isExport && props.currentSample ? <SampleMapPanel {...props} /> : null}
@@ -88,6 +93,7 @@ function CustomMapControlFactory(
</StyledMapControlPanel>
<StyledMapControlContextPanel>
{showEffects ? <EffectManager /> : null}
+ {showAnnotations ? <AnnotationManager /> : null}
</StyledMapControlContextPanel>
</StyledMapControlOverlay>
);
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index f17ec6760..dd5b00738 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -111,6 +111,13 @@ export const ActionTypes = {
REMOVE_EFFECT: `${ACTION_PREFIX}REMOVE_EFFECT`,
UPDATE_EFFECT: `${ACTION_PREFIX}UPDATE_EFFECT`,
+ // annotations
+ ADD_ANNOTATION: `${ACTION_PREFIX}ADD_ANNOTATION`,
+ REMOVE_ANNOTATION: `${ACTION_PREFIX}REMOVE_ANNOTATION`,
+ UPDATE_ANNOTATION: `${ACTION_PREFIX}UPDATE_ANNOTATION`,
+ DUPLICATE_ANNOTATION: `${ACTION_PREFIX}DUPLICATE_ANNOTATION`,
+ SET_SELECTED_ANNOTATION: `${ACTION_PREFIX}SET_SELECTED_ANNOTATION`,
+
// mapState
UPDATE_MAP: `${ACTION_PREFIX}UPDATE_MAP`,
FIT_BOUNDS: `${ACTION_PREFIX}FIT_BOUNDS`,
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 070df1034..2ad91bb59 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -22,6 +22,7 @@ import {
ParsedConfig,
ParsedLayer,
EffectPropsPartial,
+ AnnotationPropsPartial,
SyncTimelineMode,
AnimationConfig,
FilterAnimationConfig
@@ -679,6 +680,116 @@ export function updateEffect(
};
}
+// Annotation Actions
+
+export type AddAnnotationUpdaterAction = {
+ config?: AnnotationPropsPartial;
+};
+
+/**
+ * Add a new annotation
+ * @memberof visStateActions
+ * @param config - new annotation config
+ * @returns action
+ * @public
+ */
+export function addAnnotation(
+ config?: AnnotationPropsPartial
+): Merge<AddAnnotationUpdaterAction, {type: typeof ActionTypes.ADD_ANNOTATION}> {
+ return {
+ type: ActionTypes.ADD_ANNOTATION,
+ config
+ };
+}
+
+export type RemoveAnnotationUpdaterAction = {
+ id: string;
+};
+
+/**
+ * Remove an annotation
+ * @memberof visStateActions
+ * @param id id of the annotation to be removed
+ * @returns action
+ * @public
+ */
+export function removeAnnotation(
+ id: string
+): Merge<RemoveAnnotationUpdaterAction, {type: typeof ActionTypes.REMOVE_ANNOTATION}> {
+ return {
+ type: ActionTypes.REMOVE_ANNOTATION,
+ id
+ };
+}
+
+export type UpdateAnnotationUpdaterAction = {
+ id: string;
+ config: AnnotationPropsPartial;
+};
+
+/**
+ * Update an annotation
+ * @memberof visStateActions
+ * @param id id of the annotation to be updated
+ * @param config partial annotation config to merge
+ * @returns action
+ * @public
+ */
+export function updateAnnotation(
+ id: string,
+ config: AnnotationPropsPartial
+): Merge<UpdateAnnotationUpdaterAction, {type: typeof ActionTypes.UPDATE_ANNOTATION}> {
+ return {
+ type: ActionTypes.UPDATE_ANNOTATION,
+ id,
+ config
+ };
+}
+
+export type DuplicateAnnotationUpdaterAction = {
+ id: string;
+};
+
+/**
+ * Duplicate an annotation
+ * @memberof visStateActions
+ * @param id id of the annotation to be duplicated
+ * @returns action
+ * @public
+ */
+export function duplicateAnnotation(
+ id: string
+): Merge<DuplicateAnnotationUpdaterAction, {type: typeof ActionTypes.DUPLICATE_ANNOTATION}> {
+ return {
+ type: ActionTypes.DUPLICATE_ANNOTATION,
+ id
+ };
+}
+
+export type SetSelectedAnnotationUpdaterAction = {
+ id: string | null;
+ isEditingText?: boolean;
+};
+
+/**
+ * Set the selected annotation
+ * @memberof visStateActions
+ * @param id id of annotation to select, or null to deselect
+ * @param isEditingText whether the text of the annotation is being edited
+ * @returns action
+ * @public
+ */
+export function setSelectedAnnotation(
+ id: string | null,
+ isEditingText?: boolean
+): Merge<SetSelectedAnnotationUpdaterAction, {type: typeof ActionTypes.SET_SELECTED_ANNOTATION}> {
+ return {
+ type: ActionTypes.SET_SELECTED_ANNOTATION,
+ id,
+ isEditingText
+ };
+}
+
export type RemoveDatasetUpdaterAction = {
dataId: string;
};
diff --git a/src/components/package.json b/src/components/package.json
index 559264ecb..fba9b1367 100644
--- a/src/components/package.json
+++ b/src/components/package.json
@@ -56,10 +56,15 @@
"@kepler.gl/table": "3.3.0-alpha.0",
"@kepler.gl/types": "3.3.0-alpha.0",
"@kepler.gl/utils": "3.3.0-alpha.0",
+ "@lexical/link": "^0.9.0",
+ "@lexical/react": "^0.9.0",
+ "@lexical/selection": "^0.9.0",
+ "@lexical/utils": "^0.9.0",
"@loaders.gl/mvt": "^4.4.1",
"@loaders.gl/pmtiles": "^4.4.1",
"@loaders.gl/wms": "4.4.1",
"@mapbox/mapbox-sdk": "^0.15.3",
+ "@math.gl/web-mercator": "^4.1.0",
"@tippyjs/react": "^4.2.0",
"@types/classnames": "^2.3.1",
"@types/d3-array": "^2.8.0",
@@ -90,6 +95,7 @@
"exenv": "^1.2.2",
"fuzzy": "^0.1.3",
"global": "^4.3.0",
+ "lexical": "^0.9.0",
"lodash": "4.17.23",
"mapbox-gl": "1.13.1",
"maplibre-gl": "^4.0.0",
diff --git a/src/components/src/annotations/annotation-node.tsx b/src/components/src/annotations/annotation-node.tsx
new file mode 100644
index 000000000..ca2c47fd1
--- /dev/null
+++ b/src/components/src/annotations/annotation-node.tsx
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {FC} from 'react';
+import {useDraggable} from '@dnd-kit/core';
+import {Annotation, AnnotationWithArm} from '@kepler.gl/types';
+import {AnnotationKind} from '@kepler.gl/constants';
+import {makeMarker, MapViewport, CircleAnnotationMarker} from './annotation-utils';
+
+const HANDLE_RADIUS = 6;
+
+const MoveHandle: FC<{id: string; x: number; y: number}> = ({id, x, y}) => {
+ const {attributes, listeners, setNodeRef} = useDraggable({id});
+ return (
+ <circle
+ ref={setNodeRef as any}
+ {...listeners}
+ {...attributes}
+ cx={x}
+ cy={y}
+ r={HANDLE_RADIUS}
+ fill="transparent"
+ stroke="rgba(255,255,255,0.6)"
+ strokeWidth={1}
+ cursor="move"
+ style={{pointerEvents: 'all'}}
+ />
+ );
+};
+
+const ResizeHandle: FC<{id: string; x: number; y: number}> = ({id, x, y}) => {
+ const {attributes, listeners, setNodeRef} = useDraggable({id});
+ return (
+ <circle
+ ref={setNodeRef as any}
+ {...listeners}
+ {...attributes}
+ cx={x}
+ cy={y}
+ r={HANDLE_RADIUS}
+ fill="transparent"
+ stroke="rgba(255,255,255,0.6)"
+ strokeWidth={1}
+ cursor="ew-resize"
+ style={{pointerEvents: 'all'}}
+ />
+ );
+};
+
+export type AnnotationNodeProps = {
+ annotation: Annotation;
+ viewport: MapViewport;
+ isEditing: boolean;
+ isSelected: boolean;
+};
+
+const AnnotationNode: FC<AnnotationNodeProps> = ({annotation, viewport, isEditing, isSelected}) => {
+ const {lineColor, lineWidth} = annotation;
+ const marker = makeMarker(annotation, viewport);
+ const {kind, x, y, tx, ty} = marker;
+ const arrW = 3 + lineWidth * 2;
+ const isArm = 'armLength' in annotation;
+
+ const moveHandle = isEditing ? (
+ <MoveHandle id={`${annotation.id}:MOVE_POINT`} x={0} y={0} />
+ ) : null;
+
+ const selectionHighlight =
+ isEditing && isSelected ? (
+ <circle r={HANDLE_RADIUS + 2} fill="none" stroke="rgba(64,169,255,0.6)" strokeWidth={2} />
+ ) : null;
+
+ let body: React.ReactNode = null;
+
+ switch (kind) {
+ case AnnotationKind.CIRCLE: {
+ const circleMarker = marker as CircleAnnotationMarker;
+ body = (
+ <>
+ <circle
+ r={circleMarker.r}
+ fill="none"
+ stroke={lineColor}
+ strokeWidth={lineWidth}
+ {...(isSelected && isEditing ? {strokeDasharray: '6 3'} : {})}
+ />
+ <path
+ d={`M${circleMarker.ax},${circleMarker.ay} L${tx},${ty}`}
+ stroke={lineColor}
+ strokeWidth={lineWidth}
+ fill="none"
+ strokeLinecap="round"
+ />
+ {isEditing ? (
+ <>
+ {moveHandle}
+ {selectionHighlight}
+ <ResizeHandle id={`${annotation.id}:RESIZE`} x={circleMarker.r} y={0} />
+ </>
+ ) : null}
+ </>
+ );
+ break;
+ }
+ case AnnotationKind.POINT:
+ case AnnotationKind.ARROW:
+ body = (
+ <>
+ <path
+ d={`M0,0 L${tx},${ty}`}
+ stroke={lineColor}
+ fill="none"
+ strokeWidth={lineWidth}
+ strokeLinecap="round"
+ />
+ {kind === AnnotationKind.ARROW ? (
+ <path
+ transform={
+ isArm ? `rotate(${90 + (annotation as AnnotationWithArm).angle})` : undefined
+ }
+ d={`M0,${lineWidth} L${-arrW},${-arrW} L${arrW},${-arrW} Z`}
+ stroke="none"
+ fill={lineColor}
+ />
+ ) : null}
+ {kind === AnnotationKind.POINT ? (
+ <circle r={lineWidth * 1.5} fill={lineColor} stroke="none" />
+ ) : null}
+ {moveHandle}
+ {selectionHighlight}
+ </>
+ );
+ break;
+ default:
+ body = (
+ <>
+ {moveHandle}
+ {selectionHighlight}
+ </>
+ );
+ }
+
+ return <g transform={`translate(${x},${y})`}>{body}</g>;
+};
+
+export default AnnotationNode;
diff --git a/src/components/src/annotations/annotation-overlay.tsx b/src/components/src/annotations/annotation-overlay.tsx
new file mode 100644
index 000000000..032d98325
--- /dev/null
+++ b/src/components/src/annotations/annotation-overlay.tsx
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {FC, useCallback, useMemo} from 'react';
+import styled from 'styled-components';
+import {
+ DndContext,
+ DragMoveEvent,
+ DragStartEvent,
+ DragEndEvent,
+ PointerSensor,
+ useSensor,
+ useSensors
+} from '@dnd-kit/core';
+import {Annotation} from '@kepler.gl/types';
+import {ActionHandler, updateAnnotation, setSelectedAnnotation} from '@kepler.gl/actions';
+import AnnotationNode from './annotation-node';
+import AnnotationText from './annotation-text';
+import {MapViewport, movePoint, moveText, resizeCircle} from './annotation-utils';
+
+const AnnotationOverlayContainer = styled.div`
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ pointer-events: none;
+ overflow: hidden;
+ z-index: 0;
+`;
+
+const AnnotationSvgContainer = styled.svg`
+ position: absolute;
+ top: 0;
+ left: 0;
+ pointer-events: none;
+`;
+
+const AnnotationTextContainer = styled.div`
+ position: absolute;
+ top: 0;
+ left: 0;
+ pointer-events: none;
+`;
+
+export type AnnotationOverlayProps = {
+ annotations: Annotation[];
+ selectedAnnotationId: string | null;
+ isEditingAnnotationText: boolean;
+ isAnnotationMode: boolean;
+ mapIndex: number;
+ viewport: MapViewport;
+ updateAnnotation: ActionHandler<typeof updateAnnotation>;
+ setSelectedAnnotation: ActionHandler<typeof setSelectedAnnotation>;
+};
+
+const AnnotationOverlay: FC<AnnotationOverlayProps> = ({
+ annotations,
+ selectedAnnotationId,
+ isEditingAnnotationText,
+ isAnnotationMode,
+ mapIndex,
+ viewport,
+ updateAnnotation: onUpdateAnnotation,
+ setSelectedAnnotation: onSetSelectedAnnotation
+}) => {
+ const annotationsToRender = useMemo(
+ () => annotations.filter(ann => (ann.mapIndex ?? 0) === mapIndex && ann.isVisible).reverse(),
+ [annotations, mapIndex]
+ );
+
+ const draggedAnnotationRef = React.useRef<Annotation | null>(null);
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, {
+ activationConstraint: {distance: 3}
+ })
+ );
+
+ const accessibility = useMemo(
+ () => ({
+ announcements: {
+ onDragStart() {
+ return '';
+ },
+ onDragOver() {
+ return '';
+ },
+ onDragEnd() {
+ return '';
+ },
+ onDragCancel() {
+ return '';
+ }
+ },
+ screenReaderInstructions: {draggable: ''},
+ ...(typeof document !== 'undefined' ? {container: document.body} : {})
+ }),
+ []
+ );
+
+ const handleDragStart = useCallback(
+ (ev: DragStartEvent) => {
+ const annId = `${ev.active.id}`.split(':')[0];
+ const ann = annotations.find(a => a.id === annId) ?? null;
+ draggedAnnotationRef.current = ann;
+ if (ann) {
+ onSetSelectedAnnotation(ann.id, false);
+ }
+ },
+ [annotations, onSetSelectedAnnotation]
+ );
+
+ const handleDragMove = useCallback(
+ (ev: DragMoveEvent) => {
+ const [annId, handleKind] = `${ev.active.id}`.split(':');
+ const draggedAnn = draggedAnnotationRef.current;
+ if (!draggedAnn || draggedAnn.id !== annId) return;
+
+ let changes: Partial<Annotation> = {};
+ switch (handleKind) {
+ case 'MOVE_POINT':
+ changes = movePoint(draggedAnn, ev.delta, viewport);
+ break;
+ case 'MOVE_TEXT':
+ changes = moveText(draggedAnn, ev.delta, viewport);
+ break;
+ case 'RESIZE':
+ changes = resizeCircle(draggedAnn, ev.delta, viewport);
+ break;
+ }
+ if (Object.keys(changes).length > 0) {
+ onUpdateAnnotation(annId, changes);
+ }
+ },
+ [viewport, onUpdateAnnotation]
+ );
+
+ const handleDragEnd = useCallback((_ev: DragEndEvent) => {
+ draggedAnnotationRef.current = null;
+ }, []);
+
+ const handleSelectAnnotation = useCallback(
+ (id: string, isEditingText: boolean) => {
+ onSetSelectedAnnotation(id, isEditingText);
+ },
+ [onSetSelectedAnnotation]
+ );
+
+ const handleChangeText = useCallback(
+ (id: string, text: string, editorState?: Record<string, any>) => {
+ onUpdateAnnotation(id, {label: text, ...(editorState ? {editorState} : {})});
+ },
+ [onUpdateAnnotation]
+ );
+
+ if (!annotationsToRender.length) {
+ return null;
+ }
+
+ const {width, height} = viewport;
+
+ return (
+ <AnnotationOverlayContainer>
+ <DndContext
+ sensors={sensors}
+ accessibility={accessibility}
+ onDragStart={handleDragStart}
+ onDragMove={handleDragMove}
+ onDragEnd={handleDragEnd}
+ >
+ <AnnotationSvgContainer width={width} height={height}>
+ {annotationsToRender.map(annotation => (
+ <AnnotationNode
+ key={annotation.id}
+ annotation={annotation}
+ viewport={viewport}
+ isEditing={isAnnotationMode}
+ isSelected={annotation.id === selectedAnnotationId}
+ />
+ ))}
+ </AnnotationSvgContainer>
+ <AnnotationTextContainer style={{width, height}}>
+ {annotationsToRender.map(annotation => (
+ <AnnotationText
+ key={annotation.id}
+ annotation={annotation}
+ viewport={viewport}
+ isEditing={isAnnotationMode}
+ isSelected={annotation.id === selectedAnnotationId}
+ isEditingText={annotation.id === selectedAnnotationId && isEditingAnnotationText}
+ onSelect={isEditingText => handleSelectAnnotation(annotation.id, isEditingText)}
+ onChangeText={(text, editorState) =>
+ handleChangeText(annotation.id, text, editorState)
+ }
+ onUpdateAnnotation={config => onUpdateAnnotation(annotation.id, config)}
+ />
+ ))}
+ </AnnotationTextContainer>
+ </DndContext>
+ </AnnotationOverlayContainer>
+ );
+};
+
+export default AnnotationOverlay;
diff --git a/src/components/src/annotations/annotation-panel.tsx b/src/components/src/annotations/annotation-panel.tsx
new file mode 100644
index 000000000..497c9015d
--- /dev/null
+++ b/src/components/src/annotations/annotation-panel.tsx
@@ -0,0 +1,568 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback} from 'react';
+import classnames from 'classnames';
+import styled from 'styled-components';
+import {injectIntl, IntlShape} from 'react-intl';
+import {
+ addAnnotation,
+ removeAnnotation,
+ updateAnnotation,
+ duplicateAnnotation,
+ setSelectedAnnotation,
+ ActionHandler
+} from '@kepler.gl/actions';
+import {visStateLens, mapStateLens} from '@kepler.gl/reducers';
+import {Annotation} from '@kepler.gl/types';
+import {
+ AnnotationKind,
+ ANNOTATION_KINDS,
+ ANNOTATION_LINE_WIDTH_OPTIONS
+} from '@kepler.gl/constants';
+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 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';
+
+// Styled components
+
+const StyledAnnotationPanelContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ pointer-events: none !important;
+ flex-grow: 1;
+ justify-content: space-between;
+ overflow: hidden;
+
+ & > * {
+ pointer-events: all;
+ }
+`;
+
+const StyledAnnotationPanel = styled.div`
+ top: 0;
+ background-color: ${props => props.theme.sidePanelBg};
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ overflow: hidden;
+`;
+
+const StyledAnnotationPanelHeader = styled.div`
+ padding: ${({theme}) =>
+ `${theme.effectPanelPaddingTop || 8}px ${theme.effectPanelPaddingSide || 16}px 4px ${
+ theme.effectPanelPaddingSide || 16
+ }px`};
+ border-bottom: 1px solid ${props => props.theme.borderColor};
+ min-width: ${({theme}) => theme.effectPanelWidth}px;
+`;
+
+const StyledPanelHeaderRow = styled.div`
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 8px;
+`;
+
+const StyledPanelTitle = styled.div`
+ color: ${props => props.theme.titleTextColor};
+ font-size: ${props => props.theme.sidePanelTitleFontsize};
+ line-height: ${props => props.theme.sidePanelTitleLineHeight};
+ font-weight: 400;
+ letter-spacing: 1.25px;
+`;
+
+const StyledAddButton = styled.div`
+ display: flex;
+ align-items: center;
+ height: ${props => props.theme.inputBoxHeight};
+ width: fit-content;
+ padding: 4px 10px;
+ background-color: ${props => props.theme.secondaryBtnBgd};
+ border-radius: ${props => props.theme.primaryBtnRadius};
+ font-size: ${props => props.theme.primaryBtnFontSizeDefault};
+ color: ${props => props.theme.secondaryBtnActColor};
+ cursor: pointer;
+ font-weight: 500;
+ letter-spacing: 0.3px;
+ border: none;
+ &:hover {
+ background-color: ${props => props.theme.secondaryBtnBgdHover};
+ }
+`;
+
+const StyledAddIcon = styled(Add)`
+ margin-right: 8px;
+ height: 16px;
+`;
+
+const StyledAnnotationPanelContent = styled.div`
+ ${props => props.theme.sidePanelScrollBar};
+ padding: 10px 0;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+`;
+
+const StyledAnnotationItemWrapper = styled.div`
+ font-size: 12px;
+ border-radius: 1px;
+ margin: 3px 16px;
+`;
+
+const StyledAnnotationItemHeader = styled(StyledPanelHeader)`
+ height: ${props => props.theme.effectPanelHeaderHeight}px;
+ position: relative;
+ align-items: stretch;
+
+ &:hover {
+ cursor: pointer;
+ background-color: ${props => props.theme.panelBackgroundHover};
+ }
+
+ border-left: 3px solid ${props => props.theme.panelBackgroundHover};
+`;
+
+const HeaderLabelSection = styled.div`
+ margin-left: 10px;
+ flex-grow: 1;
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+ overflow: hidden;
+`;
+
+const StyledAnnotationLabel = styled.div`
+ font-size: 12px;
+ color: ${props => props.theme.textColor};
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+`;
+
+const StyledAnnotationKind = styled.div`
+ font-size: 10px;
+ color: ${props => props.theme.subtextColor};
+ margin-top: 2px;
+`;
+
+const HeaderActionSection = styled.div`
+ display: flex;
+ position: absolute;
+ height: 100%;
+ align-items: stretch;
+ right: 10px;
+ &:hover {
+ .annotation-panel__header__actions__hidden {
+ opacity: 1;
+ background-color: ${props => props.theme.panelBackgroundHover};
+ }
+ }
+`;
+
+type StyledHiddenActionsProps = {$isConfigActive: boolean};
+const StyledPanelHeaderHiddenActions = styled.div.attrs({
+ className: 'annotation-panel__header__actions__hidden'
+})<StyledHiddenActionsProps>`
+ opacity: 0;
+ display: flex;
+ align-items: center;
+ transition: opacity 0.4s ease, background-color 0.4s ease;
+ background-color: ${props =>
+ props.$isConfigActive ? props.theme.panelBackgroundHover : props.theme.panelBackground};
+
+ &:hover {
+ opacity: 1;
+ }
+`;
+
+const HeaderActionWrapper = styled.div<{$active?: boolean; $hoverColor?: string}>`
+ margin-left: 8px;
+ display: flex;
+ align-items: center;
+ color: ${props =>
+ props.$active ? props.theme.panelHeaderIconActive : props.theme.panelHeaderIcon};
+ cursor: pointer;
+
+ &:hover {
+ color: ${props =>
+ props.$hoverColor ? props.theme[props.$hoverColor] : props.theme.panelHeaderIconHover};
+ }
+`;
+
+const StyledConfigSection = styled.div`
+ position: relative;
+ margin: ${props => props.theme.effectConfiguratorMargin};
+ padding: ${props => props.theme.effectConfiguratorPadding};
+`;
+
+const StyledConfigRow = styled.div`
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 9px;
+`;
+
+const StyledConfigLabel = styled.div`
+ font-size: ${props => props.theme.inputFontSize};
+ color: ${props => props.theme.effectPanelTextSecondary1};
+ 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;
+ width: 100px;
+`;
+
+const StyledColorButtonWrapper = styled.div`
+ width: 100px;
+ .button {
+ color: ${props => props.theme.effectPanelTextSecondary2};
+ display: flex;
+ gap: 5px;
+ border: none;
+ transition: background 0.2s;
+ background-color: ${props => props.theme.inputBgd};
+ padding: 8px 5px 8px 10px;
+ &:active {
+ color: ${props => props.theme.effectPanelTextMain};
+ background-color: ${props => props.theme.inputBgdHover};
+ }
+ &:hover {
+ color: ${props => props.theme.effectPanelTextMain};
+ background-color: ${props => props.theme.inputBgdHover};
+ }
+ & > svg {
+ margin-right: 0;
+ }
+ }
+`;
+
+const StyledColorDropdown = styled.div`
+ ${props => props.theme.panelDropdownScrollBar}
+ background-color: ${props => props.theme.panelBackground};
+ box-shadow: ${props => props.theme.panelBoxShadow};
+ border-radius: ${props => props.theme.panelBorderRadius};
+ overflow-y: auto;
+ max-height: 500px;
+ position: relative;
+ z-index: 999;
+ width: 220px;
+`;
+
+const InlineColorPicker: React.FC<{
+ color: [number, number, number];
+ onSetColor: (value: [number, number, number]) => void;
+}> = ({color, onSetColor}) => {
+ const [isOpen, setIsOpen] = React.useState(false);
+ const hexColor = React.useMemo(() => rgbToHex(color), [color]);
+ const colorBlockStyle = React.useMemo(
+ () => ({width: 16, height: 16, backgroundColor: hexColor, borderRadius: 2}),
+ [hexColor]
+ );
+ const handleSelectColor = React.useCallback(
+ (v: any) => {
+ onSetColor(v);
+ },
+ [onSetColor]
+ );
+
+ return (
+ <StyledColorButtonWrapper>
+ <Button onClick={() => setIsOpen(!isOpen)}>
+ <div style={colorBlockStyle} />
+ <ArrowDownSmall />
+ </Button>
+ <Portaled top={0} left={0} isOpened={isOpen} onClose={() => setIsOpen(false)}>
+ <StyledColorDropdown>
+ <SingleColorPalette selectedColor={hexColor} onSelectColor={handleSelectColor} />
+ </StyledColorDropdown>
+ </Portaled>
+ </StyledColorButtonWrapper>
+ );
+};
+
+// Types
+export type AnnotationManagerState = {
+ visState: VisState;
+ mapState: MapState;
+ visStateActions: {
+ addAnnotation: ActionHandler<typeof addAnnotation>;
+ removeAnnotation: ActionHandler<typeof removeAnnotation>;
+ updateAnnotation: ActionHandler<typeof updateAnnotation>;
+ duplicateAnnotation: ActionHandler<typeof duplicateAnnotation>;
+ setSelectedAnnotation: ActionHandler<typeof setSelectedAnnotation>;
+ };
+};
+
+export type AnnotationManagerProps = {
+ intl: IntlShape;
+} & AnnotationManagerState;
+
+AnnotationManagerFactory.deps = [];
+
+export default function AnnotationManagerFactory(): React.FC<any> {
+ const AnnotationManager: React.FC<AnnotationManagerProps> = ({
+ intl,
+ visState,
+ mapState,
+ visStateActions
+ }) => {
+ const {annotations, selectedAnnotationId} = visState;
+
+ const handleAddAnnotation = useCallback(() => {
+ visStateActions.addAnnotation({
+ anchorPoint: [mapState.longitude, mapState.latitude]
+ });
+ }, [visStateActions, mapState.longitude, mapState.latitude]);
+
+ const handleSelectAnnotation = useCallback(
+ (id: string) => {
+ visStateActions.setSelectedAnnotation(id === selectedAnnotationId ? null : id, false);
+ },
+ [visStateActions, selectedAnnotationId]
+ );
+
+ const handleRemoveAnnotation = useCallback(
+ (e: React.MouseEvent, id: string) => {
+ e.stopPropagation();
+ visStateActions.removeAnnotation(id);
+ },
+ [visStateActions]
+ );
+
+ const handleDuplicateAnnotation = useCallback(
+ (e: React.MouseEvent, id: string) => {
+ e.stopPropagation();
+ visStateActions.duplicateAnnotation(id);
+ },
+ [visStateActions]
+ );
+
+ const handleToggleVisibility = useCallback(
+ (e: React.MouseEvent, annotation: Annotation) => {
+ e.stopPropagation();
+ visStateActions.updateAnnotation(annotation.id, {isVisible: !annotation.isVisible});
+ },
+ [visStateActions]
+ );
+
+ const handleChangeKind = useCallback(
+ (id: string, kind: AnnotationKind) => {
+ visStateActions.updateAnnotation(id, {kind});
+ },
+ [visStateActions]
+ );
+
+ const handleChangeLineWidth = useCallback(
+ (id: string, lineWidth: number) => {
+ visStateActions.updateAnnotation(id, {lineWidth});
+ },
+ [visStateActions]
+ );
+
+ const handleChangeLineColor = useCallback(
+ (id: string, rgb: [number, number, number]) => {
+ const lineColor = rgbToHex(rgb);
+ visStateActions.updateAnnotation(id, {lineColor});
+ },
+ [visStateActions]
+ );
+
+ return (
+ <StyledAnnotationPanelContainer className="annotation-manager">
+ <StyledAnnotationPanel>
+ <StyledAnnotationPanelHeader>
+ <StyledPanelHeaderRow>
+ <StyledPanelTitle>
+ {intl.formatMessage({id: 'annotationManager.title', defaultMessage: 'Annotations'})}
+ </StyledPanelTitle>
+ <StyledAddButton onClick={handleAddAnnotation}>
+ <StyledAddIcon />
+ {intl.formatMessage({id: 'annotationManager.addAnnotation', defaultMessage: 'Add'})}
+ </StyledAddButton>
+ </StyledPanelHeaderRow>
+ </StyledAnnotationPanelHeader>
+ <StyledAnnotationPanelContent>
+ {annotations.map(annotation => {
+ const isSelected = annotation.id === selectedAnnotationId;
+ return (
+ <StyledAnnotationItemWrapper key={annotation.id}>
+ <StyledAnnotationItemHeader
+ active={isSelected}
+ onClick={() => handleSelectAnnotation(annotation.id)}
+ >
+ <HeaderLabelSection>
+ <StyledAnnotationLabel>{annotation.label}</StyledAnnotationLabel>
+ <StyledAnnotationKind>{annotation.kind}</StyledAnnotationKind>
+ </HeaderLabelSection>
+
+ <HeaderActionSection className="annotation-panel__header__actions">
+ <StyledPanelHeaderHiddenActions $isConfigActive={isSelected}>
+ <HeaderActionWrapper
+ $hoverColor="negative"
+ data-tip
+ data-for={`remove-annotation_${annotation.id}`}
+ onClick={e => handleRemoveAnnotation(e, annotation.id)}
+ >
+ <Trash height="16px" />
+ </HeaderActionWrapper>
+ <Tooltip
+ id={`remove-annotation_${annotation.id}`}
+ effect="solid"
+ delayShow={500}
+ type="error"
+ >
+ <span>
+ <FormattedMessage id="tooltip.removeAnnotation" />
+ </span>
+ </Tooltip>
+
+ <HeaderActionWrapper
+ data-tip
+ data-for={`duplicate-annotation_${annotation.id}`}
+ onClick={e => handleDuplicateAnnotation(e, annotation.id)}
+ >
+ <Copy height="16px" />
+ </HeaderActionWrapper>
+ <Tooltip
+ id={`duplicate-annotation_${annotation.id}`}
+ effect="solid"
+ delayShow={500}
+ >
+ <span>
+ <FormattedMessage id="tooltip.duplicateAnnotation" />
+ </span>
+ </Tooltip>
+ </StyledPanelHeaderHiddenActions>
+
+ <HeaderActionWrapper
+ data-tip
+ data-for={`visibility-annotation_${annotation.id}`}
+ onClick={e => handleToggleVisibility(e, annotation)}
+ >
+ {annotation.isVisible ? (
+ <EyeSeen height="16px" />
+ ) : (
+ <EyeUnseen height="16px" />
+ )}
+ </HeaderActionWrapper>
+ <Tooltip
+ id={`visibility-annotation_${annotation.id}`}
+ effect="solid"
+ delayShow={500}
+ >
+ <span>
+ <FormattedMessage
+ id={
+ annotation.isVisible
+ ? 'tooltip.hideAnnotation'
+ : 'tooltip.showAnnotation'
+ }
+ />
+ </span>
+ </Tooltip>
+
+ <HeaderActionWrapper
+ $active={isSelected}
+ className={classnames('annotation__enable-config', {
+ 'is-open': isSelected
+ })}
+ data-tip
+ data-for={`config-annotation_${annotation.id}`}
+ onClick={() => handleSelectAnnotation(annotation.id)}
+ >
+ <ArrowDown height="16px" />
+ </HeaderActionWrapper>
+ <Tooltip
+ id={`config-annotation_${annotation.id}`}
+ effect="solid"
+ delayShow={500}
+ >
+ <span>
+ <FormattedMessage id="tooltip.annotationSettings" />
+ </span>
+ </Tooltip>
+ </HeaderActionSection>
+ </StyledAnnotationItemHeader>
+
+ {isSelected ? (
+ <StyledConfigSection>
+ <StyledConfigRow>
+ <StyledConfigLabel>
+ {intl.formatMessage({id: 'annotationManager.type', defaultMessage: 'Type'})}
+ </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({id: 'annotationManager.lineWidth', defaultMessage: 'Line Width'})}
+ </StyledConfigLabel>
+ <StyledSelect
+ value={annotation.lineWidth}
+ onChange={e =>
+ handleChangeLineWidth(annotation.id, Number(e.target.value))
+ }
+ >
+ {ANNOTATION_LINE_WIDTH_OPTIONS.map(w => (
+ <option key={w} value={w}>
+ {w}px
+ </option>
+ ))}
+ </StyledSelect>
+ </StyledConfigRow>
+ <StyledConfigRow>
+ <StyledConfigLabel>
+ {intl.formatMessage({id: 'annotationManager.color', defaultMessage: 'Color'})}
+ </StyledConfigLabel>
+ <InlineColorPicker
+ color={hexToRgb(annotation.lineColor)}
+ onSetColor={rgb => handleChangeLineColor(annotation.id, rgb)}
+ />
+ </StyledConfigRow>
+ </StyledConfigSection>
+ ) : null}
+ </StyledAnnotationItemWrapper>
+ );
+ })}
+ </StyledAnnotationPanelContent>
+ </StyledAnnotationPanel>
+ </StyledAnnotationPanelContainer>
+ );
+ };
+
+ return withState([visStateLens, mapStateLens], state => state, {
+ visStateActions: {
+ addAnnotation,
+ removeAnnotation,
+ updateAnnotation,
+ duplicateAnnotation,
+ setSelectedAnnotation
+ }
+ })(injectIntl(AnnotationManager)) as React.FC<any>;
+}
diff --git a/src/components/src/annotations/annotation-text.tsx b/src/components/src/annotations/annotation-text.tsx
new file mode 100644
index 000000000..28264db70
--- /dev/null
+++ b/src/components/src/annotations/annotation-text.tsx
@@ -0,0 +1,211 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {FC, useCallback, useEffect, useMemo} from 'react';
+import styled from 'styled-components';
+import {useDraggable} from '@dnd-kit/core';
+import {Annotation, AnnotationWithArm} from '@kepler.gl/types';
+import {AnnotationKind} from '@kepler.gl/constants';
+import {makeMarker, isLeftOriented, MapViewport} from './annotation-utils';
+import {LexicalRichTextEditor, LexicalToolbar} from './lexical-editor';
+import {SerializedEditorState} from 'lexical';
+
+type StyledAnnotationTextProps = {
+ $isEditing?: boolean;
+ $isSelected?: boolean;
+ $isEditingText?: boolean;
+ $textVerticalAlign?: string;
+};
+
+const StyledAnnotationText = styled.div<StyledAnnotationTextProps>`
+ position: absolute;
+ color: #fff;
+ transition: border-color 0.2s;
+ border: 2px solid transparent;
+ padding: 4px 8px;
+ white-space: pre-wrap;
+ word-break: break-word;
+ &:focus {
+ outline: none;
+ }
+ ${props =>
+ props.$isEditing
+ ? `
+ border-color: ${props.$isSelected ? 'rgba(255,255,255,0.8)' : 'rgba(255,255,255,0.2)'};
+ &:hover {
+ border-color: rgba(255,255,255,0.6);
+ }
+ cursor: move;
+ pointer-events: all;
+ `
+ : `
+ pointer-events: none;
+ a {
+ pointer-events: all;
+ cursor: pointer;
+ }
+ `}
+ ${props =>
+ props.$isEditingText
+ ? `
+ .editor-inner {
+ cursor: text;
+ }
+ `
+ : ''}
+ .editor-inner {
+ justify-content: ${props =>
+ props.$textVerticalAlign === 'top'
+ ? 'flex-start'
+ : props.$textVerticalAlign === 'middle'
+ ? 'center'
+ : 'flex-end'};
+ }
+`;
+
+const StyledToolbarWrapper = styled.div`
+ position: absolute;
+ bottom: 100%;
+ left: 0;
+ background-color: rgba(30, 33, 40, 0.95);
+ border-radius: 5px;
+ width: max-content;
+ padding: 2px 5px;
+ margin-bottom: 4px;
+ z-index: 1;
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
+`;
+
+export type AnnotationTextProps = {
+ annotation: Annotation;
+ viewport: MapViewport;
+ isEditing: boolean;
+ isSelected: boolean;
+ isEditingText: boolean;
+ onSelect: (isEditingText: boolean) => void;
+ onChangeText: (text: string, editorState?: SerializedEditorState) => void;
+ onUpdateAnnotation: (config: Partial<Annotation>) => void;
+};
+
+const AnnotationText: FC<AnnotationTextProps> = ({
+ annotation,
+ viewport,
+ isEditing,
+ isSelected,
+ isEditingText,
+ onSelect,
+ onChangeText,
+ onUpdateAnnotation
+}) => {
+ const {attributes, listeners, setNodeRef} = useDraggable({
+ id: `${annotation.id}:MOVE_TEXT`
+ });
+
+ const {textWidth, textHeight, lineColor, lineWidth, textVerticalAlign, autoSize, kind} =
+ annotation;
+ const {x, y, tx, ty} = makeMarker(annotation, viewport);
+
+ const isArm = 'armLength' in annotation;
+ const isLeft = isArm && isLeftOriented((annotation as AnnotationWithArm).angle);
+
+ const style = useMemo(
+ () => ({
+ ...(autoSize ? {minWidth: 80} : {width: textWidth || 120}),
+ bottom: viewport.height - (y + ty),
+ borderBottom:
+ kind !== AnnotationKind.TEXT ? `${lineWidth}px solid ${lineColor}` : undefined,
+ ...(kind === AnnotationKind.TEXT
+ ? {left: x + tx - (textWidth || 80) / 2}
+ : isLeft
+ ? {right: viewport.width - x - tx}
+ : {left: x + tx})
+ }),
+ [autoSize, kind, textWidth, tx, ty, viewport.width, viewport.height, x, y, isLeft, lineWidth, lineColor]
+ );
+
+ const handleEditorChange = useCallback(
+ (change: {text: string; editorState: SerializedEditorState}) => {
+ onChangeText(change.text, change.editorState);
+ },
+ [onChangeText]
+ );
+
+ useEffect(() => {
+ if (!isEditingText || !isSelected || !isEditing) {
+ window.getSelection()?.removeAllRanges();
+ }
+ }, [isEditingText, isSelected, isEditing]);
+
+ return (
+ <StyledAnnotationText
+ ref={setNodeRef}
+ $isEditing={isEditing}
+ $isEditingText={isEditingText}
+ $isSelected={isSelected}
+ $textVerticalAlign={textVerticalAlign}
+ style={style}
+ {...(isEditing
+ ? {
+ ...attributes,
+ ...listeners,
+ onPointerDown: (evt: React.PointerEvent) => {
+ const {target} = evt;
+ if (target instanceof Element && target.closest('.lexical-toolbar')) {
+ return;
+ }
+ if (isEditingText) {
+ if (target instanceof Element && target.closest('.editor-inner')) {
+ return;
+ }
+ listeners?.onPointerDown?.(evt as any);
+ return;
+ }
+ listeners?.onPointerDown?.(evt as any);
+ if (!isSelected) {
+ onSelect(false);
+ }
+ }
+ }
+ : {})}
+ onClick={evt => {
+ if (!isEditing) return;
+ const target = evt.target;
+ if (target instanceof Element && target.closest('.lexical-toolbar')) {
+ return;
+ }
+ evt.stopPropagation();
+ if (!isEditingText) {
+ onSelect(true);
+ }
+ }}
+ onDoubleClick={() => {
+ if (!isEditing) {
+ onSelect(true);
+ }
+ }}
+ >
+ <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>
+ </StyledAnnotationText>
+ );
+};
+
+export default AnnotationText;
diff --git a/src/components/src/annotations/annotation-utils.ts b/src/components/src/annotations/annotation-utils.ts
new file mode 100644
index 000000000..474b5e63b
--- /dev/null
+++ b/src/components/src/annotations/annotation-utils.ts
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {addMetersToLngLat} from '@math.gl/web-mercator';
+import {Annotation, AnnotationWithArm} from '@kepler.gl/types';
+import {AnnotationKind, isAnnotationWithArm} from '@kepler.gl/constants';
+
+export type MapViewport = {
+ project: (lngLat: [number, number]) => [number, number];
+ unproject: (xy: [number, number]) => [number, number];
+ longitude: number;
+ latitude: number;
+ width: number;
+ height: number;
+ zoom: number;
+};
+
+export type BaseAnnotationMarker = {
+ kind: AnnotationKind;
+ x: number;
+ y: number;
+ tx: number;
+ ty: number;
+};
+
+export type CircleAnnotationMarker = BaseAnnotationMarker & {
+ kind: AnnotationKind.CIRCLE;
+ ax: number;
+ ay: number;
+ r: number;
+};
+
+export type AnnotationMarker = BaseAnnotationMarker | CircleAnnotationMarker;
+
+function degreesToRadians(degree: number): number {
+ return degree * (Math.PI / 180);
+}
+
+function calcRadius(
+ viewport: MapViewport,
+ point: [number, number],
+ radiusInMeters: number
+): number {
+ const [x, y] = viewport.project(point);
+ const shifted = addMetersToLngLat(point, [radiusInMeters, 0, 0]) as [number, number];
+ const [x1, y1] = viewport.project(shifted);
+ const dx = x1 - x;
+ const dy = y1 - y;
+ return Math.sqrt(dx * dx + dy * dy);
+}
+
+export function makeMarker(annotation: Annotation, viewport: MapViewport): AnnotationMarker {
+ const {kind, anchorPoint} = annotation;
+ const angle = isAnnotationWithArm(annotation) ? degreesToRadians(annotation.angle) : 0;
+ const [x, y] = viewport.project(anchorPoint);
+
+ switch (kind) {
+ case AnnotationKind.CIRCLE: {
+ const {armLength, radiusInMeters} = annotation;
+ const r = calcRadius(viewport, anchorPoint, radiusInMeters);
+ const [ax, ay] = [Math.cos(angle) * r, Math.sin(angle) * r];
+ const [tx, ty] = [Math.cos(angle) * (r + armLength), Math.sin(angle) * (r + armLength)];
+ return {kind, x, y, ax, ay, tx, ty, r} as CircleAnnotationMarker;
+ }
+ case AnnotationKind.ARROW:
+ case AnnotationKind.POINT: {
+ const {armLength} = annotation;
+ const [tx, ty] = [Math.cos(angle) * armLength, Math.sin(angle) * armLength];
+ return {kind, x, y, tx, ty};
+ }
+ case AnnotationKind.TEXT:
+ default:
+ return {kind, x, y, tx: 0, ty: 0};
+ }
+}
+
+export function isLeftOriented(angle: number): boolean {
+ return angle > 90 || angle < -90;
+}
+
+export function movePoint(
+ annotation: Annotation,
+ delta: {x: number; y: number},
+ viewport: MapViewport
+): Partial<Annotation> {
+ const {anchorPoint} = annotation;
+ const [px, py] = viewport.project(anchorPoint);
+ const [lon, lat] = viewport.unproject([px + delta.x, py + delta.y]);
+ return {anchorPoint: [lon, lat]};
+}
+
+export function moveText(
+ annotation: Annotation,
+ delta: {x: number; y: number},
+ viewport: MapViewport
+): Partial<Annotation> {
+ const marker = makeMarker(annotation, viewport);
+ const {kind, tx, ty} = marker;
+
+ if (kind === AnnotationKind.TEXT) {
+ return movePoint(annotation, delta, viewport);
+ }
+ if (!isAnnotationWithArm(annotation)) {
+ return {};
+ }
+
+ const [tx1, ty1] = [tx + delta.x, ty + delta.y];
+ const nextAngle = radiansToDegrees(Math.atan2(ty1, tx1));
+ let nextArm: number;
+
+ switch (kind) {
+ case AnnotationKind.ARROW:
+ case AnnotationKind.POINT:
+ nextArm = Math.sqrt(tx1 * tx1 + ty1 * ty1);
+ break;
+ case AnnotationKind.CIRCLE:
+ nextArm = Math.sqrt(tx1 * tx1 + ty1 * ty1) - (marker as CircleAnnotationMarker).r;
+ break;
+ default:
+ nextArm = (annotation as AnnotationWithArm).armLength;
+ }
+ return {angle: nextAngle, armLength: nextArm};
+}
+
+export function resizeCircle(
+ annotation: Annotation,
+ delta: {x: number; y: number},
+ viewport: MapViewport
+): Partial<Annotation> {
+ if (annotation.kind !== AnnotationKind.CIRCLE) return {};
+ const {anchorPoint, radiusInMeters} = annotation;
+ const shifted = addMetersToLngLat(anchorPoint, [radiusInMeters, 0, 0]) as [number, number];
+ const [x] = viewport.project(shifted);
+ const newPoint = viewport.unproject([x + delta.x, viewport.project(anchorPoint)[1]]);
+ const dx = newPoint[0] - anchorPoint[0];
+ const currentRadius = shifted[0] - anchorPoint[0];
+ const ratio = currentRadius !== 0 ? (currentRadius + dx) / currentRadius : 1;
+ return {radiusInMeters: Math.max(0, radiusInMeters * ratio)};
+}
+
+function radiansToDegrees(radians: number): number {
+ return radians * (180 / Math.PI);
+}
diff --git a/src/components/src/annotations/index.ts b/src/components/src/annotations/index.ts
new file mode 100644
index 000000000..ac865d152
--- /dev/null
+++ b/src/components/src/annotations/index.ts
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export {default as AnnotationOverlay} from './annotation-overlay';
+export {default as AnnotationNode} from './annotation-node';
+export {default as AnnotationText} from './annotation-text';
+export {default as AnnotationManagerFactory} from './annotation-panel';
+export * from './annotation-utils';
+export type {AnnotationOverlayProps} from './annotation-overlay';
+export type {AnnotationManagerProps} from './annotation-panel';
diff --git a/src/components/src/annotations/lexical-editor/clickable-link-plugin.ts b/src/components/src/annotations/lexical-editor/clickable-link-plugin.ts
new file mode 100644
index 000000000..6230c50e4
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/clickable-link-plugin.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$getSelection, $isRangeSelection} from 'lexical';
+import {useEffect} from 'react';
+
+import type {LexicalEditor} from 'lexical';
+
+export default function ClickableLinkPlugin({
+ newTab = true
+}: {
+ newTab?: boolean;
+}): JSX.Element | null {
+ const [editor] = useLexicalComposerContext();
+ useEffect(() => {
+ function onClick(e: Event) {
+ if (editor.isEditable()) {
+ return;
+ }
+
+ const evt = e as MouseEvent;
+ const linkDomNode = getLinkDomNode(evt, editor);
+ if (!linkDomNode) {
+ return;
+ }
+ const href = linkDomNode.getAttribute('href');
+ if (linkDomNode.getAttribute('contenteditable') === 'false' || href == null) {
+ return;
+ }
+ const selection = editor.getEditorState().read($getSelection);
+ if ($isRangeSelection(selection) && !selection.isCollapsed()) {
+ return;
+ }
+
+ if (href && newTab) {
+ window.open(href, '_blank', 'noopener,noreferrer');
+ } else if (href) {
+ window.location.href = href;
+ }
+ }
+ return editor.registerRootListener(
+ (rootElement: null | HTMLElement, prevRootElement: null | HTMLElement) => {
+ if (prevRootElement !== null) {
+ prevRootElement.removeEventListener('click', onClick);
+ }
+ if (rootElement !== null) {
+ rootElement.addEventListener('click', onClick);
+ }
+ }
+ );
+ }, [editor, newTab]);
+ return null;
+}
+
+function isLinkDomNode(domNode: Node): boolean {
+ return domNode.nodeName.toLowerCase() === 'a';
+}
+
+function getLinkDomNode(event: MouseEvent, editor: LexicalEditor): HTMLAnchorElement | null {
+ return editor.getEditorState().read(() => {
+ const domNode = event.target as Node;
+ if (isLinkDomNode(domNode)) {
+ return domNode as HTMLAnchorElement;
+ }
+ if (domNode.parentNode && isLinkDomNode(domNode.parentNode)) {
+ return domNode.parentNode as HTMLAnchorElement;
+ }
+ return null;
+ });
+}
diff --git a/src/components/src/annotations/lexical-editor/floating-link-editor.tsx b/src/components/src/annotations/lexical-editor/floating-link-editor.tsx
new file mode 100644
index 000000000..e8ef5ae1f
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/floating-link-editor.tsx
@@ -0,0 +1,263 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Dispatch, FC, useCallback, useEffect, useRef, useState} from 'react';
+import styled from 'styled-components';
+import {$isLinkNode, TOGGLE_LINK_COMMAND} from '@lexical/link';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {$findMatchingParent, mergeRegister} from '@lexical/utils';
+import {
+ $getSelection,
+ $isRangeSelection,
+ COMMAND_PRIORITY_CRITICAL,
+ COMMAND_PRIORITY_HIGH,
+ COMMAND_PRIORITY_LOW,
+ KEY_ESCAPE_COMMAND,
+ LexicalEditor,
+ SELECTION_CHANGE_COMMAND
+} from 'lexical';
+
+import {DEFAULT_LINK_NODE_PROPS} from './lexical-constants';
+import {getSelectedNode, sanitizeUrl} from './lexical-utils';
+
+const StyledLinkEditor = styled.div`
+ position: absolute;
+ top: calc(100% + 4px);
+ left: 0;
+ width: max-content;
+ max-width: 300px;
+ min-width: 150px;
+ padding: 6px 10px;
+ background-color: rgba(30, 33, 40, 0.95);
+ box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
+ border-radius: 6px;
+ z-index: 20;
+
+ .link-input {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ & > a {
+ color: rgb(33, 111, 219);
+ flex-grow: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-size: 12px;
+ white-space: nowrap;
+ }
+ }
+ input {
+ &:focus {
+ outline: none;
+ }
+ width: 100%;
+ font-size: 12px;
+ background: rgba(0, 0, 0, 0.3);
+ color: #fff;
+ border: 1px solid rgba(255, 255, 255, 0.2);
+ padding: 4px 6px;
+ border-radius: 4px;
+ }
+`;
+
+const EditButton = styled.button`
+ background: transparent;
+ border: none;
+ color: rgba(255, 255, 255, 0.7);
+ cursor: pointer;
+ font-size: 11px;
+ padding: 2px 4px;
+ border-radius: 3px;
+ &:hover {
+ color: #fff;
+ background: rgba(255, 255, 255, 0.1);
+ }
+`;
+
+const FloatingLinkEditor: FC<{
+ editor: LexicalEditor;
+ isLink: boolean;
+ setIsLink: Dispatch<boolean>;
+}> = ({editor, isLink, setIsLink}) => {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [linkUrl, setLinkUrl] = useState('');
+ const [isShown, setShown] = useState(false);
+ const [isEditMode, setEditMode] = useState(false);
+ const [lastSelection, setLastSelection] = useState<any>(null);
+
+ const updateLinkEditor = useCallback(() => {
+ function clear() {
+ setShown(false);
+ setLastSelection(null);
+ setEditMode(false);
+ setLinkUrl('');
+ }
+
+ if (!editor.isEditable()) {
+ clear();
+ return;
+ }
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ const node = getSelectedNode(selection);
+ const parent = node.getParent();
+ if ($isLinkNode(parent)) {
+ setLinkUrl(parent?.getURL());
+ } else if ($isLinkNode(node)) {
+ setLinkUrl(node.getURL());
+ } else {
+ clear();
+ return;
+ }
+ }
+
+ const nativeSelection = window.getSelection();
+ const rootElement = editor.getRootElement();
+
+ if (
+ selection !== null &&
+ nativeSelection !== null &&
+ rootElement !== null &&
+ rootElement.contains(nativeSelection.anchorNode) &&
+ editor.isEditable()
+ ) {
+ setShown(true);
+ setLastSelection(selection);
+ } else {
+ clear();
+ }
+
+ return true;
+ }, [editor]);
+
+ useEffect(() => {
+ return mergeRegister(
+ editor.registerEditableListener(editable => {
+ if (!editable) {
+ updateLinkEditor();
+ }
+ }),
+ editor.registerUpdateListener(({editorState}) => {
+ editorState.read(() => {
+ updateLinkEditor();
+ });
+ }),
+ editor.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ () => {
+ updateLinkEditor();
+ return true;
+ },
+ COMMAND_PRIORITY_LOW
+ ),
+ editor.registerCommand(
+ KEY_ESCAPE_COMMAND,
+ () => {
+ if (isLink) {
+ setIsLink(false);
+ return true;
+ }
+ return false;
+ },
+ COMMAND_PRIORITY_HIGH
+ )
+ );
+ }, [editor, updateLinkEditor, setIsLink, isLink]);
+
+ useEffect(() => {
+ editor.getEditorState().read(() => {
+ updateLinkEditor();
+ });
+ }, [editor, updateLinkEditor]);
+
+ useEffect(() => {
+ if (isEditMode && inputRef.current) {
+ inputRef.current.focus();
+ }
+ }, [isEditMode]);
+
+ return isShown ? (
+ <StyledLinkEditor className="link-editor">
+ {isEditMode ? (
+ <input
+ ref={inputRef}
+ className="link-input"
+ value={linkUrl}
+ onChange={event => {
+ setLinkUrl(event.target.value);
+ }}
+ onKeyDown={event => {
+ if (event.key === 'Enter' || event.key === 'Escape') {
+ event.preventDefault();
+ event.stopPropagation();
+ if (lastSelection !== null) {
+ if (linkUrl !== '') {
+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
+ ...DEFAULT_LINK_NODE_PROPS,
+ url: sanitizeUrl(linkUrl)
+ });
+ }
+ setEditMode(false);
+ }
+ }
+ }}
+ />
+ ) : (
+ <div className="link-input">
+ <a href={linkUrl} target="_blank" rel="noopener noreferrer">
+ {linkUrl}
+ </a>
+ <EditButton
+ tabIndex={0}
+ onMouseDown={event => event.preventDefault()}
+ onClick={() => setEditMode(true)}
+ >
+ ✎
+ </EditButton>
+ </div>
+ )}
+ </StyledLinkEditor>
+ ) : null;
+};
+
+export default function FloatingLinkEditorPlugin(): JSX.Element | null {
+ const [editor] = useLexicalComposerContext();
+ const [activeEditor, setActiveEditor] = useState(editor);
+ const [isLink, setIsLink] = useState(false);
+
+ const updateToolbar = useCallback(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ const node = getSelectedNode(selection);
+ const linkParent = $findMatchingParent(node, $isLinkNode);
+ if (linkParent) {
+ setIsLink(true);
+ } else {
+ setIsLink(false);
+ }
+ }
+ }, []);
+
+ useEffect(() => {
+ return mergeRegister(
+ editor.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ (_payload, newEditor) => {
+ updateToolbar();
+ setActiveEditor(newEditor);
+ return false;
+ },
+ COMMAND_PRIORITY_CRITICAL
+ ),
+ editor.registerEditableListener(editable => {
+ if (!editable) {
+ setIsLink(false);
+ }
+ })
+ );
+ }, [editor, updateToolbar]);
+
+ return isLink ? (
+ <FloatingLinkEditor editor={activeEditor} isLink={isLink} setIsLink={setIsLink} />
+ ) : null;
+}
diff --git a/src/components/src/annotations/lexical-editor/index.ts b/src/components/src/annotations/lexical-editor/index.ts
new file mode 100644
index 000000000..0d332e4df
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/index.ts
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export {LexicalRichTextEditor} from './lexical-rich-text-editor';
+export {LexicalToolbar} from './lexical-toolbar';
+export type {LexicalRichTextEditorProps} from './lexical-rich-text-editor';
+export type {LexicalToolbarProps} from './lexical-toolbar';
+export {default as FloatingLinkEditorPlugin} from './floating-link-editor';
+export {default as ClickableLinkPlugin} from './clickable-link-plugin';
+export {
+ FONT_FAMILY_OPTIONS,
+ FONT_SIZE_OPTIONS,
+ DEFAULT_FONT_FAMILY,
+ DEFAULT_FONT_SIZE,
+ DEFAULT_FONT_COLOR,
+ DEFAULT_BG_COLOR,
+ DEFAULT_LINK_NODE_PROPS
+} from './lexical-constants';
diff --git a/src/components/src/annotations/lexical-editor/lexical-constants.ts b/src/components/src/annotations/lexical-editor/lexical-constants.ts
new file mode 100644
index 000000000..51b7df4d0
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/lexical-constants.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export const LOW_PRIORITY_COMMAND = 1;
+
+export const FONT_FAMILY_OPTIONS = [
+ 'Arial',
+ 'Courier New',
+ 'Georgia',
+ 'Inter',
+ 'Times New Roman',
+ 'Trebuchet MS',
+ 'Verdana'
+];
+
+export const DEFAULT_FONT_FAMILY = 'Inter';
+
+export const FONT_SIZE_OPTIONS = [
+ '10px',
+ '12px',
+ '14px',
+ '16px',
+ '18px',
+ '20px',
+ '22px',
+ '24px',
+ '28px',
+ '32px'
+];
+
+export const DEFAULT_FONT_SIZE = '14px';
+export const DEFAULT_FONT_COLOR = '#FFFFFF';
+export const DEFAULT_BG_COLOR = 'transparent';
+export const DEFAULT_LINK_NODE_PROPS = {
+ url: 'https://',
+ target: '_blank',
+ rel: 'noopener noreferrer'
+};
diff --git a/src/components/src/annotations/lexical-editor/lexical-nodes.ts b/src/components/src/annotations/lexical-editor/lexical-nodes.ts
new file mode 100644
index 000000000..55b3c843f
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/lexical-nodes.ts
@@ -0,0 +1,9 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {AutoLinkNode, LinkNode} from '@lexical/link';
+import type {Klass, LexicalNode} from 'lexical';
+
+const LexicalNodes: Array<Klass<LexicalNode>> = [AutoLinkNode, LinkNode];
+
+export default LexicalNodes;
diff --git a/src/components/src/annotations/lexical-editor/lexical-rich-text-editor.tsx b/src/components/src/annotations/lexical-editor/lexical-rich-text-editor.tsx
new file mode 100644
index 000000000..8fa38747c
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/lexical-rich-text-editor.tsx
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {FC, ReactNode, useCallback, useEffect, useMemo} from 'react';
+import styled from 'styled-components';
+import {LexicalComposer} from '@lexical/react/LexicalComposer';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {ContentEditable} from '@lexical/react/LexicalContentEditable';
+import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';
+import {HistoryPlugin} from '@lexical/react/LexicalHistoryPlugin';
+import {LinkPlugin} from '@lexical/react/LexicalLinkPlugin';
+import {OnChangePlugin} from '@lexical/react/LexicalOnChangePlugin';
+import {RichTextPlugin} from '@lexical/react/LexicalRichTextPlugin';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ EditorState,
+ SerializedEditorState
+} from 'lexical';
+
+import LexicalNodes from './lexical-nodes';
+import LEXICAL_THEME from './lexical-theme';
+import {updateEditorState} from './lexical-utils';
+import ClickableLinkPlugin from './clickable-link-plugin';
+import FloatingLinkEditorPlugin from './floating-link-editor';
+
+export type LexicalRichTextEditorProps = {
+ width?: number;
+ height?: number;
+ editorState?: SerializedEditorState;
+ initialText?: string;
+ isEditable: boolean;
+ children?: ReactNode;
+ onChange: (config: {text: string; editorState: SerializedEditorState}) => void;
+};
+
+const LEXICAL_EDITOR_CONFIG = {
+ namespace: 'annotation-editor',
+ theme: LEXICAL_THEME,
+ nodes: [...LexicalNodes],
+ onError(error: Error) {
+ throw error;
+ }
+};
+
+type ContainerProps = {
+ $width?: number;
+ $height?: number;
+};
+
+const Container = styled.div<ContainerProps>`
+ display: flex;
+ flex-direction: column;
+
+ .editor-inner {
+ ${props => (props.$width ? `width: ${props.$width}px` : '')};
+ ${props => (props.$height ? `height: ${props.$height}px` : '')};
+ border: none;
+ display: flex;
+ flex-direction: column;
+ }
+ .editor-input {
+ outline: none;
+ min-height: 20px;
+ }
+ .editor-input:focus {
+ outline: none;
+ }
+ .lexical-paragraph {
+ margin: 0;
+ line-height: 1.4;
+ }
+ .lexical-text-bold {
+ font-weight: bold;
+ }
+ .lexical-text-italic {
+ font-style: italic;
+ }
+ .lexical-text-underline {
+ text-decoration: underline;
+ }
+ .lexical-text-strikethrough {
+ text-decoration: line-through;
+ }
+ .lexical-text-underline-strikethrough {
+ text-decoration: underline line-through;
+ }
+ .lexical-ltr {
+ text-align: left;
+ }
+ .lexical-rtl {
+ text-align: right;
+ }
+ .lexical-link {
+ color: rgb(33, 111, 219);
+ }
+`;
+
+const LexicalEditorInner: FC<LexicalRichTextEditorProps> = ({isEditable, onChange}) => {
+ const [editor] = useLexicalComposerContext();
+
+ useEffect(() => {
+ editor.setEditable(isEditable);
+ if (!isEditable) {
+ const rootElement = editor.getRootElement();
+ if (rootElement && rootElement.contains(document.activeElement)) {
+ (document.activeElement as HTMLElement)?.blur();
+ }
+ const domSelection = window.getSelection();
+ if (domSelection && rootElement && rootElement.contains(domSelection.anchorNode)) {
+ domSelection.removeAllRanges();
+ }
+ }
+ }, [editor, isEditable]);
+
+ const handleChange = useCallback(
+ (state: EditorState) => {
+ state.read(() => {
+ const root = $getRoot();
+ onChange({text: root.getTextContent(), editorState: state.toJSON()});
+ });
+ },
+ [onChange]
+ );
+
+ return (
+ <div className="editor-inner">
+ <RichTextPlugin
+ contentEditable={<ContentEditable className="editor-input" />}
+ placeholder={<></>}
+ ErrorBoundary={LexicalErrorBoundary}
+ />
+ <LinkPlugin />
+ <ClickableLinkPlugin newTab={true} />
+ <HistoryPlugin />
+ <OnChangePlugin onChange={handleChange} ignoreSelectionChange={true} />
+ <FloatingLinkEditorPlugin />
+ </div>
+ );
+};
+
+export const LexicalRichTextEditor: FC<LexicalRichTextEditorProps> = props => {
+ const {width, height, isEditable, editorState, initialText, children} = props;
+
+ const initialConfig = useMemo(
+ () => ({
+ ...LEXICAL_EDITOR_CONFIG,
+ editable: isEditable,
+ editorState: (editor: any) => {
+ if (editorState) {
+ updateEditorState(editor, editorState);
+ } else if (initialText) {
+ $getRoot().append($createParagraphNode().append($createTextNode(initialText)));
+ }
+ }
+ }),
+ // Only use initial values
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ []
+ );
+
+ return (
+ <LexicalComposer initialConfig={initialConfig}>
+ <Container className="editor-container" $width={width} $height={height}>
+ {children}
+ <LexicalEditorInner {...props} />
+ </Container>
+ </LexicalComposer>
+ );
+};
diff --git a/src/components/src/annotations/lexical-editor/lexical-theme.ts b/src/components/src/annotations/lexical-editor/lexical-theme.ts
new file mode 100644
index 000000000..c320d79a6
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/lexical-theme.ts
@@ -0,0 +1,19 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+const LEXICAL_THEME = {
+ ltr: 'lexical-ltr',
+ rtl: 'lexical-rtl',
+ paragraph: 'lexical-paragraph',
+ link: 'lexical-link',
+ text: {
+ bold: 'lexical-text-bold',
+ italic: 'lexical-text-italic',
+ underline: 'lexical-text-underline',
+ strikethrough: 'lexical-text-strikethrough',
+ underlineStrikethrough: 'lexical-text-underline-strikethrough',
+ code: 'lexical-text-code'
+ }
+};
+
+export default LEXICAL_THEME;
diff --git a/src/components/src/annotations/lexical-editor/lexical-toolbar.tsx b/src/components/src/annotations/lexical-editor/lexical-toolbar.tsx
new file mode 100644
index 000000000..a6e331538
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/lexical-toolbar.tsx
@@ -0,0 +1,353 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {FC, useCallback, useEffect, useRef, useState} from 'react';
+import styled from 'styled-components';
+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+
+import {FONT_FAMILY_OPTIONS, FONT_SIZE_OPTIONS} from './lexical-constants';
+import {useLexicalTextStyle, useLexicalTextFormat, useInsertLexicalLink} from './use-lexical-toolbar';
+import SingleColorPalette from '../../side-panel/layer-panel/single-color-palette';
+
+export type LexicalToolbarProps = {
+ isEditingText?: boolean;
+ textVerticalAlign?: 'top' | 'bottom' | 'middle';
+ onChangeTextVerticalAlign?: (value: 'top' | 'bottom' | 'middle') => void;
+};
+
+const ToolbarContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 4px 0;
+`;
+
+const ToolbarRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ flex-wrap: wrap;
+`;
+
+const ToolbarDivider = styled.div`
+ height: 20px;
+ width: 0;
+ border-left: 1px solid rgba(255, 255, 255, 0.3);
+ margin: 0 4px;
+`;
+
+const ToolbarSelect = styled.select`
+ background: rgba(255, 255, 255, 0.1);
+ color: #fff;
+ border: 1px solid rgba(255, 255, 255, 0.2);
+ border-radius: 3px;
+ padding: 2px 4px;
+ font-size: 11px;
+ cursor: pointer;
+ max-width: 90px;
+ &:focus {
+ outline: none;
+ border-color: rgba(255, 255, 255, 0.5);
+ }
+`;
+
+const ToolbarButton = styled.button<{$active?: boolean}>`
+ background: ${props => (props.$active ? 'rgba(255,255,255,0.2)' : 'transparent')};
+ color: #fff;
+ border: none;
+ border-radius: 3px;
+ padding: 3px 6px;
+ font-size: 12px;
+ cursor: pointer;
+ min-width: 24px;
+ height: 24px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ &:hover {
+ background: rgba(255, 255, 255, 0.15);
+ }
+ &:disabled {
+ opacity: 0.4;
+ cursor: default;
+ &:hover {
+ background: transparent;
+ }
+ }
+`;
+
+const ColorSwatch = styled.div<{$color: string}>`
+ width: 14px;
+ height: 14px;
+ border-radius: 2px;
+ background-color: ${props => props.$color};
+ border: 1px solid rgba(255, 255, 255, 0.3);
+`;
+
+const ColorPickerPopover = styled.div`
+ position: absolute;
+ top: 100%;
+ left: 0;
+ margin-top: 4px;
+ background: rgba(30, 33, 40, 0.98);
+ border-radius: 6px;
+ padding: 8px;
+ z-index: 20;
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 120px;
+`;
+
+const ColorPresetRow = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 4px;
+ border-radius: 3px;
+ cursor: pointer;
+ font-size: 11px;
+ color: #fff;
+ &:hover {
+ background: rgba(255, 255, 255, 0.1);
+ }
+`;
+
+const ColorPresetSwatch = styled.div<{$color: string; $isSelected?: boolean}>`
+ width: 16px;
+ height: 16px;
+ border-radius: 3px;
+ background: ${props => props.$color};
+ border: 1.5px solid ${props => (props.$isSelected ? '#fff' : 'rgba(255,255,255,0.3)')};
+ flex-shrink: 0;
+`;
+
+const CustomPickerWrapper = styled.div`
+ border-top: 1px solid rgba(255, 255, 255, 0.15);
+ padding-top: 4px;
+ margin-top: 2px;
+`;
+
+const SingleColorPaletteWrapper = styled.div`
+ position: absolute;
+ top: 100%;
+ left: 0;
+ margin-top: 4px;
+ z-index: 30;
+ background: ${props => props.theme.panelBackground || 'rgba(30, 33, 40, 0.98)'};
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
+ border-radius: 6px;
+ overflow: hidden;
+ width: 220px;
+`;
+
+type ColorPickerButtonProps = {
+ color: string;
+ presets: Array<{color: string; label: string}>;
+ title: string;
+ label?: string;
+ renderIcon?: () => React.ReactNode;
+ onSelectColor: (color: string) => void;
+};
+
+const ColorPickerWrapper = styled.div`
+ position: relative;
+`;
+
+const ColorPickerButton: FC<ColorPickerButtonProps> = ({color, presets, title, label, renderIcon, onSelectColor}) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [showCustom, setShowCustom] = useState(false);
+ const wrapperRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ if (!isOpen) return;
+ const handleClickOutside = (e: MouseEvent) => {
+ if (wrapperRef.current && !wrapperRef.current.contains(e.target as Node)) {
+ setIsOpen(false);
+ setShowCustom(false);
+ }
+ };
+ document.addEventListener('mousedown', handleClickOutside);
+ return () => document.removeEventListener('mousedown', handleClickOutside);
+ }, [isOpen]);
+
+ const handleToggle = useCallback(() => {
+ setIsOpen(prev => !prev);
+ setShowCustom(false);
+ }, []);
+
+ const handlePresetSelect = useCallback(
+ (c: string) => {
+ onSelectColor(c);
+ setIsOpen(false);
+ setShowCustom(false);
+ },
+ [onSelectColor]
+ );
+
+ const handleCustomSelect = useCallback(
+ (color: [number, number, number] | {colors: string[]}) => {
+ if (Array.isArray(color)) {
+ const hex = `#${color.map(v => v.toString(16).padStart(2, '0')).join('')}`;
+ onSelectColor(hex);
+ }
+ setIsOpen(false);
+ setShowCustom(false);
+ },
+ [onSelectColor]
+ ) as (color: any, e?: any) => void;
+
+ return (
+ <ColorPickerWrapper ref={wrapperRef}>
+ <ToolbarButton onClick={handleToggle} title={title}>
+ {renderIcon ? renderIcon() : <span style={{fontSize: '10px'}}>{label}</span>}
+ <ColorSwatch $color={color === 'transparent' ? 'rgba(255,255,255,0.1)' : color} style={{marginLeft: 4}} />
+ </ToolbarButton>
+ {isOpen && !showCustom && (
+ <ColorPickerPopover onMouseDown={e => e.preventDefault()}>
+ {presets.map(p => (
+ <ColorPresetRow key={p.color} onClick={() => handlePresetSelect(p.color)}>
+ <ColorPresetSwatch
+ $color={p.color === 'transparent' ? 'repeating-conic-gradient(#808080 0% 25%, transparent 0% 50%) 50% / 8px 8px' : p.color}
+ $isSelected={color === p.color}
+ style={p.color === 'transparent' ? {background: 'repeating-conic-gradient(#606060 0% 25%, #404040 0% 50%) 50% / 8px 8px'} : undefined}
+ />
+ {p.label}
+ </ColorPresetRow>
+ ))}
+ <CustomPickerWrapper>
+ <ColorPresetRow onClick={() => setShowCustom(true)}>
+ <ColorPresetSwatch
+ $color="linear-gradient(135deg, #f00, #0f0, #00f)"
+ style={{background: 'linear-gradient(135deg, #f44, #4f4, #44f)'}}
+ />
+ Custom...
+ </ColorPresetRow>
+ </CustomPickerWrapper>
+ </ColorPickerPopover>
+ )}
+ {isOpen && showCustom && (
+ <SingleColorPaletteWrapper onMouseDown={e => e.preventDefault()}>
+ <SingleColorPalette
+ selectedColor={color === 'transparent' ? '#000000' : color}
+ onSelectColor={handleCustomSelect}
+ />
+ </SingleColorPaletteWrapper>
+ )}
+ </ColorPickerWrapper>
+ );
+};
+
+const FONT_COLOR_PRESETS = [
+ {color: '#FFFFFF', label: 'White'},
+ {color: '#000000', label: 'Black'}
+];
+
+const BG_COLOR_PRESETS = [
+ {color: 'transparent', label: 'No fill'},
+ {color: '#000000', label: 'Black'},
+ {color: '#FFFFFF', label: 'White'}
+];
+
+export const LexicalToolbar: FC<LexicalToolbarProps> = ({
+ isEditingText,
+ textVerticalAlign,
+ onChangeTextVerticalAlign
+}) => {
+ const [editor] = useLexicalComposerContext();
+ const {fontSize, fontFamily, fontColor, bgColor, handleChangeStyle} =
+ useLexicalTextStyle({
+ editor,
+ isEditingText: Boolean(isEditingText)
+ });
+ const {isBold, isItalic, isUnderline, handleToggleTextFormat} = useLexicalTextFormat({
+ editor,
+ isEditingText: Boolean(isEditingText)
+ });
+ const {isLink, insertLink} = useInsertLexicalLink({
+ editor,
+ isEditingText: Boolean(isEditingText)
+ });
+
+ return (
+ <ToolbarContainer className="lexical-toolbar" onMouseDown={e => {
+ if (e.target instanceof HTMLSelectElement) return;
+ e.preventDefault();
+ }}>
+ <ToolbarRow>
+ <ToolbarSelect
+ value={fontFamily}
+ onChange={e => handleChangeStyle('font-family', e.target.value)}
+ style={{marginRight: 2}}
+ >
+ {FONT_FAMILY_OPTIONS.map(f => (
+ <option key={f} value={f}>
+ {f}
+ </option>
+ ))}
+ </ToolbarSelect>
+ <ToolbarSelect
+ value={fontSize}
+ onChange={e => handleChangeStyle('font-size', e.target.value)}
+ >
+ {FONT_SIZE_OPTIONS.map(s => (
+ <option key={s} value={s}>
+ {s}
+ </option>
+ ))}
+ </ToolbarSelect>
+ <ToolbarDivider />
+ <ToolbarButton $active={isBold} onClick={() => handleToggleTextFormat('bold')} title="Bold">
+ <strong>B</strong>
+ </ToolbarButton>
+ <ToolbarButton
+ $active={isItalic}
+ onClick={() => handleToggleTextFormat('italic')}
+ title="Italic"
+ >
+ <em>I</em>
+ </ToolbarButton>
+ <ToolbarButton
+ $active={isUnderline}
+ onClick={() => handleToggleTextFormat('underline')}
+ title="Underline"
+ >
+ <u>U</u>
+ </ToolbarButton>
+ <ToolbarDivider />
+ <ColorPickerButton
+ color={fontColor}
+ presets={FONT_COLOR_PRESETS}
+ title="Text Color"
+ label="A"
+ onSelectColor={c => handleChangeStyle('color', c)}
+ />
+ <ColorPickerButton
+ color={bgColor}
+ presets={BG_COLOR_PRESETS}
+ title="Background Color"
+ label=""
+ renderIcon={() => (
+ <svg viewBox="0 0 16 16" width="12" height="12" style={{fill: 'none', stroke: 'currentColor', strokeWidth: 1.5}}>
+ <rect x="2" y="2" width="12" height="12" rx="1" strokeDasharray="2 1.5" />
+ <line x1="4" y1="14" x2="14" y2="4" />
+ <line x1="4" y1="10" x2="10" y2="4" />
+ <line x1="4" y1="6" x2="6" y2="4" />
+ </svg>
+ )}
+ onSelectColor={c => handleChangeStyle('background-color', c)}
+ />
+ <ToolbarDivider />
+ <ToolbarButton
+ $active={isLink}
+ onClick={insertLink}
+ disabled={!isEditingText}
+ title="Insert Link"
+ >
+ 🔗
+ </ToolbarButton>
+ </ToolbarRow>
+ </ToolbarContainer>
+ );
+};
diff --git a/src/components/src/annotations/lexical-editor/lexical-utils.ts b/src/components/src/annotations/lexical-editor/lexical-utils.ts
new file mode 100644
index 000000000..6ea27f2dd
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/lexical-utils.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {$isAtNodeEnd} from '@lexical/selection';
+import {ElementNode, LexicalEditor, RangeSelection, SerializedEditorState, TextNode} from 'lexical';
+
+export function getSelectedNode(selection: RangeSelection): TextNode | ElementNode {
+ const anchor = selection.anchor;
+ const focus = selection.focus;
+ const anchorNode = selection.anchor.getNode();
+ const focusNode = selection.focus.getNode();
+ if (anchorNode === focusNode) {
+ return anchorNode;
+ }
+ const isBackward = selection.isBackward();
+ if (isBackward) {
+ return $isAtNodeEnd(focus) ? anchorNode : focusNode;
+ } else {
+ return $isAtNodeEnd(anchor) ? focusNode : anchorNode;
+ }
+}
+
+export function updateEditorState(
+ editor: LexicalEditor,
+ editorState: SerializedEditorState | undefined
+): void {
+ try {
+ if (editorState) {
+ editor.setEditorState(editor.parseEditorState(editorState));
+ }
+ } catch (e) {
+ // eslint-disable-next-line no-console
+ console.error(e);
+ }
+}
+
+export function sanitizeUrl(url: string): string {
+ const SAFE_URL_PATTERN = /^(?:(?:https?|mailto|ftp|tel|file|sms):|[^&:/?#]*(?:[/?#]|$))/gi;
+ const DATA_URL_PATTERN =
+ /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i;
+
+ url = String(url).trim();
+ if (url.match(SAFE_URL_PATTERN) || url.match(DATA_URL_PATTERN)) return url;
+ return 'https://';
+}
diff --git a/src/components/src/annotations/lexical-editor/use-lexical-toolbar.ts b/src/components/src/annotations/lexical-editor/use-lexical-toolbar.ts
new file mode 100644
index 000000000..92a0fbcfa
--- /dev/null
+++ b/src/components/src/annotations/lexical-editor/use-lexical-toolbar.ts
@@ -0,0 +1,320 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {$isLinkNode, TOGGLE_LINK_COMMAND} from '@lexical/link';
+import {$getSelectionStyleValueForProperty, $patchStyleText} from '@lexical/selection';
+import {mergeRegister} from '@lexical/utils';
+import {
+ $getSelection,
+ $isRangeSelection,
+ FORMAT_ELEMENT_COMMAND,
+ SELECTION_CHANGE_COMMAND,
+ TextFormatType,
+ $createRangeSelection,
+ $getRoot,
+ $setSelection,
+ LexicalEditor
+} from 'lexical';
+import {useCallback, useEffect, useMemo, useState} from 'react';
+
+import {
+ DEFAULT_BG_COLOR,
+ DEFAULT_FONT_FAMILY,
+ DEFAULT_FONT_SIZE,
+ DEFAULT_FONT_COLOR,
+ DEFAULT_LINK_NODE_PROPS,
+ LOW_PRIORITY_COMMAND
+} from './lexical-constants';
+import {getSelectedNode} from './lexical-utils';
+
+type UseLexicalToolbarProps = {
+ isEditingText?: boolean;
+ editor: LexicalEditor;
+};
+
+export type UseLexicalTextFormatReturn = {
+ isBold: boolean;
+ isItalic: boolean;
+ isUnderline: boolean;
+ handleToggleTextFormat: (format: string) => void;
+};
+
+export const useLexicalTextFormat = ({
+ isEditingText,
+ editor
+}: UseLexicalToolbarProps): UseLexicalTextFormatReturn => {
+ const [isBold, setIsBold] = useState(false);
+ const [isItalic, setIsItalic] = useState(false);
+ const [isUnderline, setIsUnderline] = useState(false);
+
+ const updateTextFormat = useCallback(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ setIsBold(selection.hasFormat('bold'));
+ setIsItalic(selection.hasFormat('italic'));
+ setIsUnderline(selection.hasFormat('underline'));
+ }
+ }, []);
+
+ useEffect(() => {
+ return mergeRegister(
+ editor.registerUpdateListener(({editorState}) => {
+ editorState.read(() => {
+ updateTextFormat();
+ });
+ }),
+ editor.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ () => {
+ updateTextFormat();
+ return false;
+ },
+ LOW_PRIORITY_COMMAND
+ )
+ );
+ }, [editor, updateTextFormat]);
+
+ const handleToggleTextFormat = useCallback(
+ (format: string) => {
+ const wasEditable = editor.isEditable();
+ if (!wasEditable) {
+ editor.setEditable(true);
+ }
+ editor.update(() => {
+ let selection = $getSelection();
+ if (!$isRangeSelection(selection) || selection.isCollapsed()) {
+ const root = $getRoot();
+ const newSelection = $createRangeSelection();
+ newSelection.focus.set(root.getKey(), 0, 'element');
+ newSelection.anchor.set(root.getKey(), root.getChildrenSize(), 'element');
+ $setSelection(newSelection);
+ selection = $getSelection();
+ }
+ if ($isRangeSelection(selection)) {
+ selection.formatText(format as TextFormatType);
+ }
+ });
+ if (!wasEditable) {
+ setTimeout(() => editor.setEditable(false), 0);
+ }
+ },
+ [editor]
+ );
+ return {isBold, isItalic, isUnderline, handleToggleTextFormat};
+};
+
+export type UseLexicalTextStyleReturn = {
+ fontSize: string;
+ fontColor: string;
+ bgColor: string;
+ fontFamily: string;
+ handleChangeStyle: (style: string, value: string) => void;
+ handleAlignHorizontal: (alignment: 'left' | 'right' | 'center' | 'justify') => void;
+};
+
+export const useLexicalTextStyle = ({
+ editor,
+ isEditingText,
+ defaultSettings
+}: {
+ editor: LexicalEditor;
+ isEditingText: boolean;
+ defaultSettings?: Partial<{
+ fontSize: string;
+ fontColor: string;
+ bgColor: string;
+ fontFamily: string;
+ }>;
+}): UseLexicalTextStyleReturn => {
+ const defaultValues = useMemo(
+ () => ({
+ fontSize: DEFAULT_FONT_SIZE,
+ fontColor: DEFAULT_FONT_COLOR,
+ bgColor: DEFAULT_BG_COLOR,
+ fontFamily: DEFAULT_FONT_FAMILY,
+ ...defaultSettings
+ }),
+ [defaultSettings]
+ );
+
+ const [fontSize, setFontSize] = useState<string>(defaultValues.fontSize);
+ const [fontColor, setFontColor] = useState<string>(defaultValues.fontColor);
+ const [bgColor, setBgColor] = useState<string>(defaultValues.bgColor);
+ const [fontFamily, setFontFamily] = useState<string>(defaultValues.fontFamily);
+
+ const updateTextStyle = useCallback(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ setFontSize(
+ $getSelectionStyleValueForProperty(selection, 'font-size', defaultValues.fontSize)
+ );
+ setFontColor($getSelectionStyleValueForProperty(selection, 'color', defaultValues.fontColor));
+ setBgColor($getSelectionStyleValueForProperty(selection, 'background-color', 'transparent'));
+ setFontFamily(
+ $getSelectionStyleValueForProperty(selection, 'font-family', defaultValues.fontFamily)
+ );
+ }
+ }, [defaultValues.fontColor, defaultValues.fontFamily, defaultValues.fontSize]);
+
+ useEffect(() => {
+ return mergeRegister(
+ editor.registerUpdateListener(({editorState}) => {
+ editorState.read(() => {
+ updateTextStyle();
+ });
+ }),
+ editor.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ () => {
+ updateTextStyle();
+ return false;
+ },
+ LOW_PRIORITY_COMMAND
+ )
+ );
+ }, [editor, updateTextStyle]);
+
+ const handleChangeStyle = useCallback(
+ (style: string, option: string) => {
+ const wasEditable = editor.isEditable();
+ if (!wasEditable) {
+ editor.setEditable(true);
+ }
+ editor.update(
+ () => {
+ let selection = $getSelection();
+ if (!$isRangeSelection(selection) || selection.isCollapsed()) {
+ const root = $getRoot();
+ const newSelection = $createRangeSelection();
+ newSelection.focus.set(root.getKey(), 0, 'element');
+ newSelection.anchor.set(root.getKey(), root.getChildrenSize(), 'element');
+ $setSelection(newSelection);
+ selection = $getSelection();
+ }
+ if ($isRangeSelection(selection)) {
+ $patchStyleText(selection, {[style]: option});
+ }
+ },
+ {
+ onUpdate: () => {
+ if (!wasEditable) {
+ editor.setEditable(false);
+ }
+ }
+ }
+ );
+ },
+ [editor]
+ );
+
+ const handleAlignHorizontal = useCallback(
+ (alignment: 'left' | 'right' | 'center' | 'justify') => {
+ const wasEditable = editor.isEditable();
+ if (!wasEditable) {
+ editor.setEditable(true);
+ }
+ editor.update(
+ () => {
+ let selection = $getSelection();
+ if (!$isRangeSelection(selection) || selection.isCollapsed()) {
+ const root = $getRoot();
+ const newSelection = $createRangeSelection();
+ newSelection.focus.set(root.getKey(), 0, 'element');
+ newSelection.anchor.set(root.getKey(), root.getChildrenSize(), 'element');
+ $setSelection(newSelection);
+ }
+ },
+ {
+ onUpdate: () => {
+ editor.dispatchCommand(FORMAT_ELEMENT_COMMAND, alignment);
+ if (!wasEditable) {
+ editor.setEditable(false);
+ }
+ }
+ }
+ );
+ },
+ [editor]
+ );
+
+ return {
+ fontSize,
+ fontColor,
+ bgColor,
+ fontFamily,
+ handleChangeStyle,
+ handleAlignHorizontal
+ };
+};
+
+export type UseInsertLexicalLinkReturn = {
+ isLink: boolean;
+ insertLink: () => void;
+};
+
+export const useInsertLexicalLink = ({
+ isEditingText,
+ editor
+}: UseLexicalToolbarProps): UseInsertLexicalLinkReturn => {
+ const [isLink, setIsLink] = useState(false);
+
+ const updateLink = useCallback(() => {
+ const selection = $getSelection();
+ if ($isRangeSelection(selection)) {
+ const node = getSelectedNode(selection);
+ const parent = node.getParent();
+ if ($isLinkNode(parent) || $isLinkNode(node)) {
+ setIsLink(true);
+ } else {
+ setIsLink(false);
+ }
+ }
+ }, []);
+
+ useEffect(() => {
+ return mergeRegister(
+ editor.registerUpdateListener(({editorState}) => {
+ editorState.read(() => {
+ updateLink();
+ });
+ }),
+ editor.registerCommand(
+ SELECTION_CHANGE_COMMAND,
+ () => {
+ updateLink();
+ return false;
+ },
+ LOW_PRIORITY_COMMAND
+ )
+ );
+ }, [editor, updateLink]);
+
+ const insertLink = useCallback(() => {
+ const wasEditable = editor.isEditable();
+ if (!wasEditable) {
+ editor.setEditable(true);
+ }
+ editor.update(() => {
+ let selection = $getSelection();
+ if (!$isRangeSelection(selection) || selection.isCollapsed()) {
+ const root = $getRoot();
+ const newSelection = $createRangeSelection();
+ newSelection.focus.set(root.getKey(), 0, 'element');
+ newSelection.anchor.set(root.getKey(), root.getChildrenSize(), 'element');
+ $setSelection(newSelection);
+ }
+ });
+ setTimeout(() => {
+ if (!isLink) {
+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, DEFAULT_LINK_NODE_PROPS);
+ } else {
+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
+ }
+ if (!wasEditable) {
+ editor.setEditable(false);
+ }
+ }, 0);
+ }, [editor, isLink]);
+
+ return {isLink, insertLink};
+};
diff --git a/src/components/src/common/icons/annotation-text.tsx b/src/components/src/common/icons/annotation-text.tsx
new file mode 100644
index 000000000..25519d318
--- /dev/null
+++ b/src/components/src/common/icons/annotation-text.tsx
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {Component} from 'react';
+import Base, {BaseProps} from './base';
+
+export default class AnnotationText extends Component<Partial<BaseProps>> {
+ static defaultProps = {
+ height: '16px',
+ predefinedClassName: 'data-ex-icons-annotation-text'
+ };
+
+ render() {
+ return (
+ <Base viewBox="0 0 64 64" {...this.props}>
+ <text
+ x="4"
+ y="48"
+ fontSize="42"
+ fontWeight="bold"
+ fontFamily="Arial, sans-serif"
+ fill="currentColor"
+ >
+ A
+ </text>
+ <text
+ x="36"
+ y="48"
+ fontSize="42"
+ fontWeight="bold"
+ fontFamily="Arial, sans-serif"
+ fill="currentColor"
+ >
+ a
+ </text>
+ </Base>
+ );
+ }
+}
diff --git a/src/components/src/common/icons/index.tsx b/src/components/src/common/icons/index.tsx
index 1223af6bd..a94d10669 100644
--- a/src/components/src/common/icons/index.tsx
+++ b/src/components/src/common/icons/index.tsx
@@ -89,6 +89,7 @@ export {default as OrderByList} from './order-by-list';
export {default as OrderByDataset} from './order-by-dataset';
export {default as Messages} from './messages';
export {default as Crosshairs} from './crosshairs';
+export {default as AnnotationText} from './annotation-text';
export {default as CursorClick} from './cursor-click';
export {default as CursorPoint} from './cursor-point';
export {default as Calendar} from './calendar';
diff --git a/src/components/src/common/range-slider.tsx b/src/components/src/common/range-slider.tsx
index 5a0b934d7..cc31d255f 100644
--- a/src/components/src/common/range-slider.tsx
+++ b/src/components/src/common/range-slider.tsx
@@ -325,7 +325,7 @@ export default function RangeSliderFactory(
animationWindow={animationWindow}
filter={filter}
datasets={datasets}
- range={displayRange!}
+ range={displayRange || range}
value={value}
width={plotWidth}
isRanged={isRanged}
@@ -362,8 +362,8 @@ export default function RangeSliderFactory(
<Slider
marks={this.props.marks}
isRanged={isRanged}
- minValue={displayRange![0]}
- maxValue={displayRange![1]}
+ minValue={(displayRange || range)[0]}
+ maxValue={(displayRange || range)[1]}
value0={this.props.value0}
value1={this.props.value1}
step={step}
diff --git a/src/components/src/effects/effect-panel.tsx b/src/components/src/effects/effect-panel.tsx
index dcbe82c24..05fc9eacc 100644
--- a/src/components/src/effects/effect-panel.tsx
+++ b/src/components/src/effects/effect-panel.tsx
@@ -37,8 +37,7 @@ const PanelWrapper = styled.div<PanelWrapperProps>`
&.dragging {
cursor: move;
}
- margin: 3px auto 3px 25px;
- max-width: 295px;
+ margin: 3px 16px;
`;
EffectPanelFactory.deps = [EffectPanelHeaderFactory, EffectConfiguratorFactory];
diff --git a/src/components/src/effects/effect-type-selector.tsx b/src/components/src/effects/effect-type-selector.tsx
index d361fc273..692657353 100644
--- a/src/components/src/effects/effect-type-selector.tsx
+++ b/src/components/src/effects/effect-type-selector.tsx
@@ -41,6 +41,7 @@ const DropdownWrapper = styled.div`
const StyledEffectTypeSelector = styled.div`
.item-selector .item-selector__dropdown {
padding: 4px 10px 4px 10px;
+ width: fit-content;
background-color: ${props => props.theme.secondaryBtnBgd};
border-radius: ${props => props.theme.primaryBtnRadius};
font-size: ${props => props.theme.primaryBtnFontSizeDefault};
diff --git a/src/components/src/geocoder/geocoder.tsx b/src/components/src/geocoder/geocoder.tsx
index 38b1cdd9f..493d60db0 100644
--- a/src/components/src/geocoder/geocoder.tsx
+++ b/src/components/src/geocoder/geocoder.tsx
@@ -50,9 +50,7 @@ export const testForCoordinates = (query: string): [true, number, number] | [fal
const EDGE_MERIDIAN = 180;
-export function getViewportBbox(
- mapState: MapState
-): [number, number, number, number] | null {
+export function getViewportBbox(mapState: MapState): [number, number, number, number] | null {
if (!mapState.width || !mapState.height) {
return null;
}
@@ -232,7 +230,11 @@ const GeoCoder: React.FC<GeocoderProps & IntlProps> = ({
debounceTimeout = setTimeout(async () => {
if (limit > 0 && Boolean(queryString)) {
try {
- const geocodeParams: {query: string; limit: number; bbox?: [number, number, number, number]} = {
+ const geocodeParams: {
+ query: string;
+ limit: number;
+ bbox?: [number, number, number, number];
+ } = {
query: queryString,
limit
};
@@ -242,9 +244,7 @@ const GeoCoder: React.FC<GeocoderProps & IntlProps> = ({
geocodeParams.bbox = bbox;
}
}
- const response = await client
- .forwardGeocode(geocodeParams)
- .send();
+ const response = await client.forwardGeocode(geocodeParams).send();
if (response.body.features) {
setShowResults(true);
setResults(response.body.features);
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index 89a419c23..c4a9201f9 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -354,6 +354,16 @@ export {default as EffectManagerFactory} from './effects/effect-manager';
export {default as EffectTimeConfiguratorFactory} from './effects/effect-time-configurator';
export {default as EffectTypeSelectorFactory} from './effects/effect-type-selector';
export {default as SidePanelTitleFactory} from './effects/side-panel-title';
+
+// Annotations
+export {default as AnnotationManagerFactory} from './annotations/annotation-panel';
+export {AnnotationOverlay} from './annotations';
+export {AnnotationNode} from './annotations';
+export {AnnotationText} from './annotations';
+export {makeMarker, movePoint, moveText, resizeCircle, isLeftOriented} from './annotations';
+export type {MapViewport, AnnotationMarker} from './annotations';
+export {default as AnnotationControlFactory} from './map/annotations/annotation-control';
+
export {default as ColorBreaksPanelFactory} from './side-panel/layer-panel/color-breaks-panel';
export {default as DimensionScaleSelectorFactory} from './side-panel/layer-panel/dimension-scale-selector';
export {default as HowToButton} from './side-panel/layer-panel/how-to-button';
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index a713bcda6..09b7b3e43 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -24,6 +24,7 @@ import {
} from './common/styled-components';
import EditorFactory from './editor/editor';
+import {AnnotationOverlay} from './annotations';
// utils
import {
@@ -778,6 +779,37 @@ export default function MapContainerFactory(
// no-op
};
+ _annotationViewportCache: {key: string; viewport: any} | null = null;
+
+ _getAnnotationViewport(mapState: any, internalViewState: any) {
+ const longitude = internalViewState?.longitude ?? mapState.longitude;
+ const latitude = internalViewState?.latitude ?? mapState.latitude;
+ const zoom = internalViewState?.zoom ?? mapState.zoom;
+ const pitch = internalViewState?.pitch ?? mapState.pitch ?? 0;
+ const bearing = internalViewState?.bearing ?? mapState.bearing ?? 0;
+ const width = mapState.width || 0;
+ const height = mapState.height || 0;
+ const key = `${longitude},${latitude},${zoom},${pitch},${bearing},${width},${height}`;
+
+ if (this._annotationViewportCache?.key === key) {
+ return this._annotationViewportCache.viewport;
+ }
+
+ const mergedState = {...mapState, ...internalViewState, width, height};
+ const vp = getViewportFromMapState(mergedState) as any;
+ const viewport = {
+ project: (lngLat: [number, number]) => vp.project(lngLat) as [number, number],
+ unproject: (xy: [number, number]) => vp.unproject(xy) as [number, number],
+ longitude,
+ latitude,
+ width,
+ height,
+ zoom
+ };
+ this._annotationViewportCache = {key, viewport};
+ return viewport;
+ }
+
_onDeckError = (error, layer) => {
const errorMessage = error?.message || 'unknown-error';
const layerMessage = layer?.id ? ` in ${layer.id} layer` : '';
@@ -1364,6 +1396,16 @@ export default function MapContainerFactory(
display: editor.visible ? 'block' : 'none'
}}
/>
+ <AnnotationOverlay
+ annotations={visState.annotations}
+ selectedAnnotationId={visState.selectedAnnotationId}
+ isEditingAnnotationText={visState.isEditingAnnotationText}
+ isAnnotationMode={Boolean(mapControls?.annotation?.active)}
+ mapIndex={index || 0}
+ viewport={this._getAnnotationViewport(mapState, internalViewState)}
+ updateAnnotation={visStateActions.updateAnnotation}
+ setSelectedAnnotation={visStateActions.setSelectedAnnotation}
+ />
{this.props.children}
{mapStyle.topMapStyle ? (
<ResolvedMapComponent
diff --git a/src/components/src/map/annotations/annotation-control.tsx b/src/components/src/map/annotations/annotation-control.tsx
new file mode 100644
index 000000000..513702cd2
--- /dev/null
+++ b/src/components/src/map/annotations/annotation-control.tsx
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, ComponentType} from 'react';
+import {MapControls} from '@kepler.gl/types';
+import {getApplicationConfig} from '@kepler.gl/utils';
+import {AnnotationText} from '../../common/icons';
+import {MapControlButton} from '../../common/styled-components';
+import MapControlTooltipFactory from '../map-control-tooltip';
+
+interface AnnotationControlIcons {
+ annotationIcon: ComponentType<any>;
+}
+
+export type AnnotationControlProps = {
+ mapControls: MapControls;
+ onToggleMapControl: (control: string) => void;
+ actionIcons?: AnnotationControlIcons;
+};
+
+AnnotationControlFactory.deps = [MapControlTooltipFactory];
+
+export default function AnnotationControlFactory(
+ MapControlTooltip: ReturnType<typeof MapControlTooltipFactory>
+): React.FC<AnnotationControlProps> {
+ const defaultActionIcons = {
+ annotationIcon: AnnotationText
+ };
+
+ const AnnotationControl = ({
+ mapControls,
+ onToggleMapControl,
+ actionIcons = defaultActionIcons
+ }: AnnotationControlProps) => {
+ const onClick = useCallback(
+ event => {
+ event.preventDefault();
+ onToggleMapControl('annotation');
+ },
+ [onToggleMapControl]
+ );
+
+ if (!getApplicationConfig().enableAnnotations) {
+ return null;
+ }
+
+ const showControl = mapControls?.annotation?.show;
+ if (!showControl) {
+ return null;
+ }
+
+ const active = mapControls?.annotation?.active;
+ return (
+ <MapControlTooltip
+ id="show-annotation"
+ message={active ? 'tooltip.hideAnnotationPanel' : 'tooltip.showAnnotationPanel'}
+ >
+ <MapControlButton
+ className="map-control-button toggle-annotation"
+ onClick={onClick}
+ active={active}
+ >
+ <actionIcons.annotationIcon height="22px" />
+ </MapControlButton>
+ </MapControlTooltip>
+ );
+ };
+
+ AnnotationControl.displayName = 'AnnotationControl';
+ return React.memo(AnnotationControl);
+}
diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsx
index d7cff529a..1802a30e4 100644
--- a/src/components/src/map/map-control.tsx
+++ b/src/components/src/map/map-control.tsx
@@ -17,6 +17,8 @@ import {Editor, LayerVisConfig, MapControls, MapState} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {MapStateActions, UIStateActions} from '@kepler.gl/actions';
+import AnnotationControlFactory from './annotations/annotation-control';
+
interface StyledMapControlProps {
$top?: number;
}
@@ -89,7 +91,8 @@ MapControlFactory.deps = [
LayerSelectorPanelFactory,
MapLegendPanelFactory,
MapDrawPanelFactory,
- LocalePanelFactory
+ LocalePanelFactory,
+ AnnotationControlFactory
];
function MapControlFactory(
@@ -98,13 +101,15 @@ function MapControlFactory(
LayerSelectorPanel: ReturnType<typeof LayerSelectorPanelFactory>,
MapLegendPanel: ReturnType<typeof MapLegendPanelFactory>,
MapDrawPanel: ReturnType<typeof MapDrawPanelFactory>,
- LocalePanel: ReturnType<typeof LocalePanelFactory>
+ LocalePanel: ReturnType<typeof LocalePanelFactory>,
+ AnnotationControl: ReturnType<typeof AnnotationControlFactory>
) {
const DEFAULT_ACTIONS = [
SplitMapButton,
LayerSelectorPanel,
Toggle3dButton,
MapDrawPanel,
+ AnnotationControl,
LocalePanel,
MapLegendPanel
];
diff --git a/src/constants/src/annotation.ts b/src/constants/src/annotation.ts
new file mode 100644
index 000000000..f7a6eade5
--- /dev/null
+++ b/src/constants/src/annotation.ts
@@ -0,0 +1,36 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export enum AnnotationKind {
+ TEXT = 'TEXT',
+ ARROW = 'ARROW',
+ POINT = 'POINT',
+ CIRCLE = 'CIRCLE'
+}
+
+export function isAnnotationKind(kind: string): kind is AnnotationKind {
+ return Object.values(AnnotationKind).includes(kind as AnnotationKind);
+}
+
+export function isAnnotationWithArm<T extends object>(
+ anno: T
+): anno is T & {armLength: number; angle: number} {
+ return isFinite((anno as any).armLength);
+}
+
+export const INITIAL_ANNOTATION_KIND = AnnotationKind.POINT;
+export const INITIAL_ANNOTATION_ANGLE = -45;
+export const INITIAL_ANNOTATION_ARM_LENGTH = 50;
+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 ANNOTATION_KINDS = [
+ {id: AnnotationKind.TEXT, label: 'Text'},
+ {id: AnnotationKind.POINT, label: 'Point'},
+ {id: AnnotationKind.ARROW, label: 'Arrow'},
+ {id: AnnotationKind.CIRCLE, label: 'Circle'}
+];
+
+export const ANNOTATION_LINE_WIDTH_OPTIONS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index de3b5af7d..18bbc0f7e 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -1338,6 +1338,7 @@ export const MAP_CONTROLS = keyMirror({
mapDraw: null,
mapLocale: null,
effect: null,
+ annotation: null,
aiAssistant: null
});
diff --git a/src/constants/src/index.ts b/src/constants/src/index.ts
index 291d291cc..c6b839421 100644
--- a/src/constants/src/index.ts
+++ b/src/constants/src/index.ts
@@ -14,3 +14,4 @@ export * from './tooltip';
export * from './user-feedbacks';
export * from './user-guides';
export * from './time';
+export * from './annotation';
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index 17ea19edd..3cd5d6012 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -68,7 +68,8 @@ export default {
layer: 'Capes',
filter: 'Filtres',
interaction: 'Interaccions',
- basemap: 'Mapa base'
+ basemap: 'Mapa base',
+ annotation: 'Anotacions'
},
panelViewToggle: {
list: 'Visualitza Llista',
@@ -230,6 +231,13 @@ export default {
time: 'Hora',
timezone: 'Zona horària'
},
+ annotationManager: {
+ title: 'Anotacions',
+ addAnnotation: 'Afegir',
+ type: 'Tipus',
+ lineWidth: "Amplada de línia",
+ color: 'Color'
+ },
effectDescription: {
lightAndShadow:
"Simula il·luminació solar realista i ombres basades en l'hora del dia i la ubicació geogràfica. Intensitat d'ombra, colors de llum solar i ambiental ajustables.",
@@ -334,6 +342,13 @@ export default {
syncTimelineEnd: 'Fi del període de temps del filtre actual',
showEffectPanel: "Mostra el panell d'efectes",
hideEffectPanel: "Amaga el panell d'efectes",
+ showAnnotationPanel: "Mostra les anotacions",
+ hideAnnotationPanel: "Amaga les anotacions",
+ removeAnnotation: "Elimina l'anotació",
+ duplicateAnnotation: "Duplica l'anotació",
+ hideAnnotation: "Amaga l'anotació",
+ showAnnotation: "Mostra l'anotació",
+ annotationSettings: "Configuració de l'anotació",
removeEffect: "Elimina l'efecte",
disableEffect: "Desactiva l'efecte",
effectSettings: "Configuració de l'efecte"
@@ -551,7 +566,8 @@ export default {
},
header: {
visibleLayers: 'Capes visibles',
- layerLegend: 'Llegenda de capes'
+ layerLegend: 'Llegenda de capes',
+ annotations: 'Anotacions'
},
interactions: {
tooltip: 'Suggeriment',
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index f52f0da01..daa26a300 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -68,7 +68,8 @@ export default {
layer: '图层',
filter: '过滤器',
interaction: '交互',
- basemap: '底图'
+ basemap: '底图',
+ annotation: '注释'
},
panelViewToggle: {
list: '查看列表',
@@ -227,6 +228,13 @@ export default {
time: '时间',
timezone: '时区'
},
+ annotationManager: {
+ title: '注释',
+ addAnnotation: '添加',
+ type: '类型',
+ lineWidth: '线宽',
+ color: '颜色'
+ },
effectDescription: {
lightAndShadow:
'根据一天中的时间和地理位置模拟逼真的阳光照射和阴影投射。可调节阴影强度、阳光和环境光颜色。',
@@ -321,6 +329,13 @@ export default {
syncTimelineEnd: '当前过滤时间段的结束',
showEffectPanel: '显示效果面板',
hideEffectPanel: '隐藏效果面板',
+ showAnnotationPanel: '显示注释',
+ hideAnnotationPanel: '隐藏注释',
+ removeAnnotation: '删除注释',
+ duplicateAnnotation: '复制注释',
+ hideAnnotation: '隐藏注释',
+ showAnnotation: '显示注释',
+ annotationSettings: '注释设置',
removeEffect: '移除效果',
disableEffect: '禁用效果',
effectSettings: '效果设置'
@@ -535,7 +550,8 @@ export default {
},
header: {
visibleLayers: '可见图层',
- layerLegend: '图层图例'
+ layerLegend: '图层图例',
+ annotations: '注释'
},
interactions: {
tooltip: '工具提示',
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 0271eb5c3..811b5ac1d 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -68,7 +68,8 @@ export default {
layer: 'Layers',
filter: 'Filters',
interaction: 'Interactions',
- basemap: 'Base map'
+ basemap: 'Base map',
+ annotation: 'Annotations'
},
panelViewToggle: {
list: 'View List',
@@ -220,7 +221,7 @@ export default {
},
effectManager: {
effects: 'Effects',
- addEffect: 'Add effect',
+ addEffect: 'Add',
pickDateTime: 'Pick date/time',
currentTime: 'Current time',
pickCurrrentTime: 'Pick current time',
@@ -228,6 +229,13 @@ export default {
time: 'Time',
timezone: 'Timezone'
},
+ annotationManager: {
+ title: 'Annotations',
+ addAnnotation: 'Add',
+ type: 'Type',
+ lineWidth: 'Line Width',
+ color: 'Color'
+ },
effectDescription: {
lightAndShadow:
'Simulates realistic sun lighting and shadow casting based on time of day and geographic location. Adjustable shadow intensity, sun and ambient light colors.',
@@ -332,6 +340,13 @@ export default {
syncTimelineEnd: 'End of current filter timeframe',
showEffectPanel: 'Show effect panel',
hideEffectPanel: 'Hide effect panel',
+ showAnnotationPanel: 'Show annotations',
+ hideAnnotationPanel: 'Hide annotations',
+ removeAnnotation: 'Remove annotation',
+ duplicateAnnotation: 'Duplicate annotation',
+ hideAnnotation: 'Hide annotation',
+ showAnnotation: 'Show annotation',
+ annotationSettings: 'Annotation settings',
removeEffect: 'Remove effect',
disableEffect: 'Disable effect',
effectSettings: 'Effect settings'
@@ -610,7 +625,8 @@ ${'```'}
},
header: {
visibleLayers: 'Visible layers',
- layerLegend: 'Legend'
+ layerLegend: 'Legend',
+ annotations: 'Annotations'
},
interactions: {
tooltip: 'Tooltip',
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index 80a6d82ec..520d41326 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -68,7 +68,8 @@ export default {
layer: 'Capas',
filter: 'Filtros',
interaction: 'Interacciones',
- basemap: 'Mapa base'
+ basemap: 'Mapa base',
+ annotation: 'Anotaciones'
},
panelViewToggle: {
list: 'Ver Lista',
@@ -231,6 +232,13 @@ export default {
time: 'Hora',
timezone: 'Zona horaria'
},
+ annotationManager: {
+ title: 'Anotaciones',
+ addAnnotation: 'Añadir',
+ type: 'Tipo',
+ lineWidth: 'Ancho de línea',
+ color: 'Color'
+ },
effectDescription: {
lightAndShadow:
'Simula iluminación solar realista y proyección de sombras basada en la hora del día y la ubicación geográfica. Intensidad de sombra, colores de luz solar y ambiental ajustables.',
@@ -335,6 +343,13 @@ export default {
syncTimelineEnd: 'Fin del período de tiempo del filtro actual',
showEffectPanel: 'Mostrar panel de efectos',
hideEffectPanel: 'Ocultar panel de efectos',
+ showAnnotationPanel: 'Mostrar anotaciones',
+ hideAnnotationPanel: 'Ocultar anotaciones',
+ removeAnnotation: 'Eliminar anotación',
+ duplicateAnnotation: 'Duplicar anotación',
+ hideAnnotation: 'Ocultar anotación',
+ showAnnotation: 'Mostrar anotación',
+ annotationSettings: 'Configuración de anotación',
removeEffect: 'Eliminar efecto',
disableEffect: 'Desactivar efecto',
effectSettings: 'Configuración de efecto'
@@ -552,7 +567,8 @@ export default {
},
header: {
visibleLayers: 'Capas visibles',
- layerLegend: 'Capa de leyenda'
+ layerLegend: 'Capa de leyenda',
+ annotations: 'Anotaciones'
},
interactions: {
tooltip: 'Sugerencias',
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index 8ce573772..e80c29d88 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -67,7 +67,8 @@ export default {
layer: 'Tasot',
filter: 'Suodattimet',
interaction: 'Interaktiot',
- basemap: 'Taustakartta'
+ basemap: 'Taustakartta',
+ annotation: 'Merkinnät'
},
panelViewToggle: {
list: 'Näytä lista',
@@ -229,6 +230,13 @@ export default {
time: 'Aika',
timezone: 'Aikavyöhyke'
},
+ annotationManager: {
+ title: 'Merkinnät',
+ addAnnotation: 'Lisää',
+ type: 'Tyyppi',
+ lineWidth: 'Viivan leveys',
+ color: 'Väri'
+ },
effectDescription: {
lightAndShadow:
'Simuloi realistista auringonvaloa ja varjojen heijastusta vuorokaudenajan ja maantieteellisen sijainnin perusteella. Säädettävä varjon voimakkuus, auringon- ja ympäristövalon värit.',
@@ -331,6 +339,13 @@ export default {
syncTimelineEnd: 'Nykyisen suodattimen aikajakson loppu',
showEffectPanel: 'Näytä efektipaneeli',
hideEffectPanel: 'Piilota efektipaneeli',
+ showAnnotationPanel: 'Näytä merkinnät',
+ hideAnnotationPanel: 'Piilota merkinnät',
+ removeAnnotation: 'Poista merkintä',
+ duplicateAnnotation: 'Kopioi merkintä',
+ hideAnnotation: 'Piilota merkintä',
+ showAnnotation: 'Näytä merkintä',
+ annotationSettings: 'Merkinnän asetukset',
removeEffect: 'Poista efekti',
disableEffect: 'Poista efekti käytöstä',
effectSettings: 'Efektiasetukset',
@@ -549,7 +564,8 @@ export default {
},
header: {
visibleLayers: 'Näkyvissä olevat tasot',
- layerLegend: 'Tason selite'
+ layerLegend: 'Tason selite',
+ annotations: 'Merkinnät'
},
interactions: {
tooltip: 'Vihje',
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index ccb1fe0ab..fe08f68f9 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -68,7 +68,8 @@ export default {
layer: 'レイヤ',
filter: 'フィルター',
interaction: 'インタラクション',
- basemap: 'ベースマップ'
+ basemap: 'ベースマップ',
+ annotation: 'アノテーション'
},
panelViewToggle: {
list: 'リスト表示',
@@ -228,6 +229,13 @@ export default {
time: '時刻',
timezone: 'タイムゾーン'
},
+ annotationManager: {
+ title: 'アノテーション',
+ addAnnotation: '追加',
+ type: 'タイプ',
+ lineWidth: '線幅',
+ color: '色'
+ },
effectDescription: {
lightAndShadow:
'時刻と地理的位置に基づいてリアルな太陽光と影の投影をシミュレートします。影の強さ、太陽光と環境光の色を調整できます。',
@@ -329,6 +337,13 @@ export default {
syncTimelineEnd: '現在のフィルタ期間の終了',
showEffectPanel: 'エフェクトパネルを表示',
hideEffectPanel: 'エフェクトパネルを非表示',
+ showAnnotationPanel: 'アノテーションを表示',
+ hideAnnotationPanel: 'アノテーションを非表示',
+ removeAnnotation: 'アノテーションを削除',
+ duplicateAnnotation: 'アノテーションを複製',
+ hideAnnotation: 'アノテーションを隠す',
+ showAnnotation: 'アノテーションを表示',
+ annotationSettings: 'アノテーション設定',
removeEffect: 'エフェクトを削除',
disableEffect: 'エフェクトを無効化',
effectSettings: 'エフェクト設定',
@@ -548,7 +563,8 @@ export default {
},
header: {
visibleLayers: '表示中のレイヤ',
- layerLegend: 'レイヤ判例'
+ layerLegend: 'レイヤ判例',
+ annotations: 'アノテーション'
},
interactions: {
tooltip: 'ツールチップ',
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index c182f3287..c6a796914 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -68,7 +68,8 @@ export default {
layer: 'Camadas',
filter: 'Filtros',
interaction: 'Interações',
- basemap: 'Mapa base'
+ basemap: 'Mapa base',
+ annotation: 'Anotações'
},
panelViewToggle: {
list: 'Ver Lista',
@@ -231,6 +232,13 @@ export default {
time: 'Hora',
timezone: 'Fuso horário'
},
+ annotationManager: {
+ title: 'Anotações',
+ addAnnotation: 'Adicionar',
+ type: 'Tipo',
+ lineWidth: 'Largura da linha',
+ color: 'Cor'
+ },
effectDescription: {
lightAndShadow:
'Simula iluminação solar realista e projeção de sombras com base na hora do dia e localização geográfica. Intensidade de sombra, cores de luz solar e ambiente ajustáveis.',
@@ -335,6 +343,13 @@ export default {
syncTimelineEnd: 'Fim do período de tempo do filtro atual',
showEffectPanel: 'Mostrar painel de efeitos',
hideEffectPanel: 'Ocultar painel de efeitos',
+ showAnnotationPanel: 'Mostrar anotações',
+ hideAnnotationPanel: 'Ocultar anotações',
+ removeAnnotation: 'Remover anotação',
+ duplicateAnnotation: 'Duplicar anotação',
+ hideAnnotation: 'Ocultar anotação',
+ showAnnotation: 'Mostrar anotação',
+ annotationSettings: 'Configurações da anotação',
removeEffect: 'Remover efeito',
disableEffect: 'Desativar efeito',
effectSettings: 'Configurações de efeito'
@@ -553,7 +568,8 @@ export default {
},
header: {
visibleLayers: 'Camadas Visíveis',
- layerLegend: 'Legenda da Camada'
+ layerLegend: 'Legenda da Camada',
+ annotations: 'Anotações'
},
interactions: {
tooltip: 'Dica de contexto',
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index 0a36bc3d9..8723ece4a 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -68,7 +68,8 @@ export default {
layer: 'Слои',
filter: 'Фильтры',
interaction: 'Взаимодействия',
- basemap: 'Базовая карта'
+ basemap: 'Базовая карта',
+ annotation: 'Аннотации'
},
panelViewToggle: {
list: 'Просмотр списком',
@@ -230,6 +231,13 @@ export default {
time: 'Время',
timezone: 'Часовой пояс'
},
+ annotationManager: {
+ title: 'Аннотации',
+ addAnnotation: 'Добавить',
+ type: 'Тип',
+ lineWidth: 'Толщина линии',
+ color: 'Цвет'
+ },
effectDescription: {
lightAndShadow:
'Имитирует реалистичное солнечное освещение и отбрасывание теней на основе времени суток и географического положения. Регулируемая интенсивность теней, цвета солнечного и рассеянного света.',
@@ -332,6 +340,13 @@ export default {
syncTimelineEnd: 'Конец текущего периода фильтра',
showEffectPanel: 'Показать панель эффектов',
hideEffectPanel: 'Скрыть панель эффектов',
+ showAnnotationPanel: 'Показать аннотации',
+ hideAnnotationPanel: 'Скрыть аннотации',
+ removeAnnotation: 'Удалить аннотацию',
+ duplicateAnnotation: 'Дублировать аннотацию',
+ hideAnnotation: 'Скрыть аннотацию',
+ showAnnotation: 'Показать аннотацию',
+ annotationSettings: 'Настройки аннотации',
removeEffect: 'Удалить эффект',
disableEffect: 'Отключить эффект',
effectSettings: 'Настройки эффекта',
@@ -553,7 +568,8 @@ export default {
},
header: {
visibleLayers: 'Видимые слои',
- layerLegend: 'Легенда слоя'
+ layerLegend: 'Легенда слоя',
+ annotations: 'Аннотации'
},
interactions: {
tooltip: 'Подсказка',
diff --git a/src/processors/src/data-processor.ts b/src/processors/src/data-processor.ts
index eeedf0a45..8097c5ea4 100644
--- a/src/processors/src/data-processor.ts
+++ b/src/processors/src/data-processor.ts
@@ -583,7 +583,8 @@ function castBigIntColumnsToFloat64(arrowTable: arrow.Table): arrow.Table {
const newColumns: Record<string, arrow.Vector> = {};
for (let i = 0; i < arrowTable.numCols; i++) {
const field = arrowTable.schema.fields[i];
- const col = arrowTable.getChildAt(i)!;
+ const col = arrowTable.getChildAt(i);
+ if (!col) continue;
if (arrow.DataType.isInt(field.type) && field.type.bitWidth === 64) {
const float64Array = new Float64Array(col.length);
for (let j = 0; j < col.length; j++) {
diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.ts
index d8daa5f28..f31dbd2c5 100644
--- a/src/reducers/src/vis-state-merger.ts
+++ b/src/reducers/src/vis-state-merger.ts
@@ -17,7 +17,14 @@ import {
import {Layer} from '@kepler.gl/layers';
import {createEffect} from '@kepler.gl/effects';
import {notNullorUndefined} from '@kepler.gl/common-utils';
-import {AGGREGATION_TYPES, LAYER_BLENDINGS, OVERLAY_BLENDINGS} from '@kepler.gl/constants';
+import {
+ AGGREGATION_TYPES,
+ LAYER_BLENDINGS,
+ OVERLAY_BLENDINGS,
+ isAnnotationKind,
+ INITIAL_ANNOTATION_LINE_COLOR,
+ INITIAL_ANNOTATION_LINE_WIDTH
+} from '@kepler.gl/constants';
import {CURRENT_VERSION, VisState, VisStateMergers, KeplerGLSchemaClass} from '@kepler.gl/schemas';
import {
@@ -582,6 +589,44 @@ export function mergeEffects<S extends VisState>(
};
}
+/**
+ * Merge annotations with saved config
+ */
+export function mergeAnnotations<S extends VisState>(state: S, annotations: any[]): S {
+ if (!annotations || !annotations.length) {
+ return state;
+ }
+ const existingIds = new Set(state.annotations.map(a => a.id));
+ const validAnnotations = annotations
+ .filter(
+ a =>
+ a &&
+ a.id &&
+ !existingIds.has(a.id) &&
+ isAnnotationKind(a.kind) &&
+ Array.isArray(a.anchorPoint) &&
+ a.anchorPoint.length === 2
+ )
+ .map(a => ({
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ label: '',
+ lineColor: INITIAL_ANNOTATION_LINE_COLOR,
+ lineWidth: INITIAL_ANNOTATION_LINE_WIDTH,
+ textWidth: 0,
+ textHeight: 0,
+ ...a
+ }));
+ if (!validAnnotations.length) {
+ return state;
+ }
+ return {
+ ...state,
+ annotations: [...state.annotations, ...validAnnotations]
+ };
+}
+
/**
* Merge interactionConfig.tooltip with saved config,
* validate fieldsToShow
@@ -1125,6 +1170,11 @@ export const VIS_STATE_MERGERS: VisStateMergers<any> = [
merge: mergeEffects,
prop: 'effects'
},
+ {
+ merge: mergeAnnotations,
+ prop: 'annotations',
+ toMergeProp: 'annotationsToBeMerged'
+ },
{
merge: mergeInteractions,
prop: 'interactionConfig',
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index 59609c39d..6f2c675e7 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -96,7 +96,15 @@ import {
SORT_ORDER,
SYNC_TIMELINE_MODES,
CHANNEL_SCALES,
- SCALE_TYPES
+ SCALE_TYPES,
+ INITIAL_ANNOTATION_KIND,
+ INITIAL_ANNOTATION_ANGLE,
+ INITIAL_ANNOTATION_ARM_LENGTH,
+ INITIAL_ANNOTATION_TEXT_WIDTH,
+ INITIAL_ANNOTATION_TEXT_HEIGHT,
+ INITIAL_ANNOTATION_LINE_WIDTH,
+ INITIAL_ANNOTATION_LINE_COLOR,
+ AnnotationKind
} from '@kepler.gl/constants';
import {LAYER_ID_LENGTH, Layer, LayerClasses} from '@kepler.gl/layers';
import {
@@ -130,7 +138,9 @@ import {
Editor,
Field,
LayerVisConfig,
- TimeRangeFilter
+ TimeRangeFilter,
+ Annotation,
+ AnnotationPropsPartial
} from '@kepler.gl/types';
import {Loader} from '@loaders.gl/loader-utils';
@@ -302,6 +312,12 @@ export const INITIAL_VIS_STATE: VisState = {
effects: [],
effectOrder: [],
+ // annotations
+ annotations: [],
+ annotationsToBeMerged: [],
+ selectedAnnotationId: null,
+ isEditingAnnotationText: false,
+
interactionConfig: defaultInteractionConfig,
interactionToBeMerged: {},
@@ -2036,6 +2052,174 @@ export const updateEffectUpdater = (
};
};
+// ANNOTATION UPDATERS
+
+function makeNewAnnotation(config?: AnnotationPropsPartial): Annotation {
+ const kind = config?.kind ?? INITIAL_ANNOTATION_KIND;
+ const base = {
+ id: config?.id ?? generateHashId(6),
+ kind,
+ isVisible: config?.isVisible ?? true,
+ autoSize: config?.autoSize ?? true,
+ autoSizeY: config?.autoSizeY ?? true,
+ anchorPoint: config?.anchorPoint ?? ([0, 0] as [number, number]),
+ label: config?.label ?? 'New Annotation',
+ lineColor: config?.lineColor ?? INITIAL_ANNOTATION_LINE_COLOR,
+ lineWidth: config?.lineWidth ?? INITIAL_ANNOTATION_LINE_WIDTH,
+ textWidth: config?.textWidth ?? INITIAL_ANNOTATION_TEXT_WIDTH,
+ textHeight: config?.textHeight ?? INITIAL_ANNOTATION_TEXT_HEIGHT,
+ textVerticalAlign: config?.textVerticalAlign ?? ('bottom' as const),
+ mapIndex: config?.mapIndex
+ };
+
+ switch (kind) {
+ case AnnotationKind.POINT:
+ return {
+ ...base,
+ kind: AnnotationKind.POINT,
+ armLength: (config as any)?.armLength ?? INITIAL_ANNOTATION_ARM_LENGTH,
+ angle: (config as any)?.angle ?? INITIAL_ANNOTATION_ANGLE
+ };
+ case AnnotationKind.ARROW:
+ return {
+ ...base,
+ kind: AnnotationKind.ARROW,
+ armLength: (config as any)?.armLength ?? INITIAL_ANNOTATION_ARM_LENGTH,
+ angle: (config as any)?.angle ?? INITIAL_ANNOTATION_ANGLE
+ };
+ case AnnotationKind.CIRCLE:
+ return {
+ ...base,
+ kind: AnnotationKind.CIRCLE,
+ armLength: (config as any)?.armLength ?? INITIAL_ANNOTATION_ARM_LENGTH,
+ angle: (config as any)?.angle ?? INITIAL_ANNOTATION_ANGLE,
+ radiusInMeters: (config as any)?.radiusInMeters ?? 1000
+ };
+ case AnnotationKind.TEXT:
+ default:
+ return {
+ ...base,
+ kind: AnnotationKind.TEXT
+ };
+ }
+}
+
+/**
+ * Add a new annotation
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const addAnnotationUpdater = (
+ state: VisState,
+ action: VisStateActions.AddAnnotationUpdaterAction
+): VisState => {
+ const newAnnotation = makeNewAnnotation(action.config);
+ return {
+ ...state,
+ annotations: [newAnnotation, ...state.annotations],
+ selectedAnnotationId: newAnnotation.id,
+ isEditingAnnotationText: true
+ };
+};
+
+/**
+ * Remove an annotation
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const removeAnnotationUpdater = (
+ state: VisState,
+ {id}: VisStateActions.RemoveAnnotationUpdaterAction
+): VisState => {
+ return {
+ ...state,
+ annotations: state.annotations.filter(a => a.id !== id),
+ selectedAnnotationId: state.selectedAnnotationId === id ? null : state.selectedAnnotationId,
+ isEditingAnnotationText:
+ state.selectedAnnotationId === id ? false : state.isEditingAnnotationText
+ };
+};
+
+/**
+ * Update an annotation
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const updateAnnotationUpdater = (
+ state: VisState,
+ {id, config}: VisStateActions.UpdateAnnotationUpdaterAction
+): VisState => {
+ const idx = state.annotations.findIndex(a => a.id === id);
+ if (idx < 0) {
+ Console.warn(`can not update annotation with invalid id ${id}`);
+ return state;
+ }
+ const prev = state.annotations[idx];
+ let nextAnnotation: Annotation;
+
+ if (config.kind && config.kind !== prev.kind) {
+ nextAnnotation = makeNewAnnotation({...prev, ...config} as AnnotationPropsPartial);
+ } else {
+ nextAnnotation = {...prev, ...config} as Annotation;
+ }
+
+ const newAnnotations = [...state.annotations];
+ newAnnotations[idx] = nextAnnotation;
+ return {
+ ...state,
+ annotations: newAnnotations
+ };
+};
+
+/**
+ * Duplicate an annotation
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const duplicateAnnotationUpdater = (
+ state: VisState,
+ {id}: VisStateActions.DuplicateAnnotationUpdaterAction
+): VisState => {
+ const original = state.annotations.find(a => a.id === id);
+ if (!original) {
+ Console.warn(`can not duplicate annotation with invalid id ${id}`);
+ return state;
+ }
+ const newAnnotation = {
+ ...cloneDeep(original),
+ id: generateHashId(6),
+ label: `Copy of ${original.label}`
+ };
+ return {
+ ...state,
+ annotations: [newAnnotation, ...state.annotations],
+ selectedAnnotationId: newAnnotation.id,
+ isEditingAnnotationText: false
+ };
+};
+
+/**
+ * Set selected annotation
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const setSelectedAnnotationUpdater = (
+ state: VisState,
+ {id, isEditingText}: VisStateActions.SetSelectedAnnotationUpdaterAction
+): VisState => {
+ if (
+ id === state.selectedAnnotationId &&
+ (isEditingText ?? false) === state.isEditingAnnotationText
+ ) {
+ return state;
+ }
+ return {
+ ...state,
+ selectedAnnotationId: id,
+ isEditingAnnotationText: isEditingText ?? false
+ };
+};
+
/**
* Remove a dataset and all layers, filters, tooltip configs that based on it
* @memberof visStateUpdaters
diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.ts
index c8603a820..29acda538 100644
--- a/src/reducers/src/vis-state.ts
+++ b/src/reducers/src/vis-state.ts
@@ -165,6 +165,16 @@ const actionHandler = {
[ActionTypes.UPDATE_EFFECT]: visStateUpdaters.updateEffectUpdater,
+ [ActionTypes.ADD_ANNOTATION]: visStateUpdaters.addAnnotationUpdater,
+
+ [ActionTypes.REMOVE_ANNOTATION]: visStateUpdaters.removeAnnotationUpdater,
+
+ [ActionTypes.UPDATE_ANNOTATION]: visStateUpdaters.updateAnnotationUpdater,
+
+ [ActionTypes.DUPLICATE_ANNOTATION]: visStateUpdaters.duplicateAnnotationUpdater,
+
+ [ActionTypes.SET_SELECTED_ANNOTATION]: visStateUpdaters.setSelectedAnnotationUpdater,
+
[ActionTypes.CREATE_NEW_DATASET_SUCCESS]: visStateUpdaters.createNewDatasetSuccessUpdater,
[ActionTypes.SET_LOADING_INDICATOR]: visStateUpdaters.setLoadingIndicatorUpdater
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index 5ccc68048..0fe7c71bd 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -28,7 +28,8 @@ import {
SavedVisState,
SplitMap,
ValueOf,
- Effect
+ Effect,
+ Annotation
} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
@@ -56,6 +57,10 @@ export interface VisState {
layerOrder: string[];
effects: Effect[];
effectOrder: string[];
+ annotations: Annotation[];
+ annotationsToBeMerged: any[];
+ selectedAnnotationId: string | null;
+ isEditingAnnotationText: boolean;
filters: Filter[];
filterToBeMerged: any[];
datasets: Datasets;
@@ -831,6 +836,46 @@ export class EffectsSchema extends Schema {
}
}
+const annotationPropsV1 = {
+ id: null,
+ kind: null,
+ isVisible: null,
+ autoSize: null,
+ autoSizeY: null,
+ anchorPoint: null,
+ label: null,
+ editorState: null,
+ mapIndex: null,
+ lineColor: null,
+ lineWidth: null,
+ textWidth: null,
+ textHeight: null,
+ textVerticalAlign: null,
+ armLength: null,
+ angle: null,
+ radiusInMeters: null
+};
+
+export class AnnotationsSchema extends Schema {
+ key = 'annotations';
+
+ save(annotations) {
+ return {
+ [this.key]: annotations.map(
+ annotation => this.savePropertiesOrApplySchema(annotation).annotations
+ )
+ };
+ }
+
+ load(annotations) {
+ return {
+ [this.key]: annotations.map(
+ annotation => this.loadPropertiesOrApplySchema(annotation).annotations
+ )
+ };
+ }
+}
+
export const filterPropsV1 = {
...filterPropsV0,
plotType: new PlotTypeSchema({
@@ -892,6 +937,10 @@ export const propertiesV1 = {
version: VERSIONS.v1,
properties: effectPropsV1
}),
+ annotations: new AnnotationsSchema({
+ version: VERSIONS.v1,
+ properties: annotationPropsV1
+ }),
interactionConfig: new InteractionSchemaV1({
version: VERSIONS.v1,
properties: interactionPropsV1
diff --git a/src/types/annotations.d.ts b/src/types/annotations.d.ts
new file mode 100644
index 000000000..30848e3f8
--- /dev/null
+++ b/src/types/annotations.d.ts
@@ -0,0 +1,50 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {AnnotationKind} from '@kepler.gl/constants';
+
+export {AnnotationKind} from '@kepler.gl/constants';
+export {isAnnotationKind, isAnnotationWithArm} from '@kepler.gl/constants';
+
+export type BaseAnnotation = {
+ id: string;
+ kind: AnnotationKind;
+ isVisible: boolean;
+ autoSize: boolean;
+ autoSizeY: boolean;
+ anchorPoint: [number, number];
+ label: string;
+ editorState?: Record<string, any>;
+ mapIndex?: number;
+ lineColor: string;
+ lineWidth: number;
+ textWidth: number;
+ textHeight: number;
+ textVerticalAlign?: 'top' | 'middle' | 'bottom';
+};
+
+export type AnnotationWithArm = BaseAnnotation & {
+ armLength: number;
+ angle: number;
+};
+
+export type TextAnnotation = BaseAnnotation & {
+ kind: AnnotationKind.TEXT;
+};
+
+export type PointAnnotation = AnnotationWithArm & {
+ kind: AnnotationKind.POINT;
+};
+
+export type ArrowAnnotation = AnnotationWithArm & {
+ kind: AnnotationKind.ARROW;
+};
+
+export type CircleAnnotation = AnnotationWithArm & {
+ kind: AnnotationKind.CIRCLE;
+ radiusInMeters: number;
+};
+
+export type Annotation = TextAnnotation | PointAnnotation | ArrowAnnotation | CircleAnnotation;
+
+export type AnnotationPropsPartial = Partial<Annotation>;
diff --git a/src/types/index.d.ts b/src/types/index.d.ts
index 155feb9d6..aa5b23e7f 100644
--- a/src/types/index.d.ts
+++ b/src/types/index.d.ts
@@ -8,6 +8,7 @@ export * from './schemas';
export * from './types';
export * from './components';
export * from './effects';
+export * from './annotations';
export * from './datasets';
export * as StacTypes from './stac';
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index 6075997ae..799bba313 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -460,6 +460,7 @@ export type MapControls = {
mapDraw?: MapControlItem;
mapLocale?: MapControlItem;
effect?: MapControlItem;
+ annotation?: MapControlItem;
aiAssistant?: MapControlItem;
};
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 4dbeb6ee0..6b8ba618f 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -96,6 +96,9 @@ export type KeplerApplicationConfig = {
/** Maximum pitch angle in degrees. deck.gl defaults to 60; set higher (up to 85) for elevated perspectives.
* Note: values above 60 may cause rendering artifacts with some basemap tile providers. */
maxPitch?: number;
+
+ /** Whether to enable the annotations feature. Enabled by default. */
+ enableAnnotations?: boolean;
};
const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
@@ -159,7 +162,9 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
// Default to true for webpack builds, false for other build tools (e.g., Vite)
escapeXhtmlForWebpack: isWebpackBuild(),
- maxPitch: 60
+ maxPitch: 60,
+
+ enableAnnotations: true
};
const applicationConfig: Required<KeplerApplicationConfig> = DEFAULT_APPLICATION_CONFIG;
diff --git a/src/utils/src/filter-utils.ts b/src/utils/src/filter-utils.ts
index 515dd53c6..f63665d62 100644
--- a/src/utils/src/filter-utils.ts
+++ b/src/utils/src/filter-utils.ts
@@ -389,7 +389,9 @@ export const getPolygonFilterFunctor = (layer, filter, dataContainer) => {
if (Array.isArray(coordinates[0])) {
return (coordinates as number[][]).some(
coord =>
- coord.length >= 2 && coord.every(Number.isFinite) && isInPolygon(coord, filter.value)
+ coord.length >= 2 &&
+ coord.every(Number.isFinite) &&
+ isInPolygon(coord, filter.value)
);
}
return (
diff --git a/test/browser/components/map/map-control-test.js b/test/browser/components/map/map-control-test.js
index c35af30af..6d0143955 100644
--- a/test/browser/components/map/map-control-test.js
+++ b/test/browser/components/map/map-control-test.js
@@ -76,7 +76,7 @@ test('MapControlFactory - display all options', t => {
onSetLocale={onSetLocale}
/>
);
- t.equal($.find('.map-control-action').length, 6, 'Should show 6 action panels');
+ t.equal($.find('.map-control-action').length, 7, 'Should show 7 action panels');
t.end();
});
@@ -103,7 +103,7 @@ test('MapControlFactory - display options', t => {
t.equal(wrapper.find(MapControl).length, 1, 'Should render MapControl');
// layer selector is not active
- t.equal(wrapper.find(MapControlButton).length, 5, 'Should show 5 MapControlButton');
+ t.equal(wrapper.find(MapControlButton).length, 6, 'Should show 6 MapControlButton');
t.equal(wrapper.find(Split).length, 1, 'Should show 1 split map button');
t.equal(wrapper.find(Cube3d).length, 1, 'Should show 1 toggle 3d button');
@@ -126,8 +126,8 @@ test('MapControlFactory - display options', t => {
)
});
- // 6 control buttons as legend is opened automatically in split map mode
- t.equal(wrapper.find(MapControlButton).length, 6, 'Should show 6 MapControlButton');
+ // 7 control buttons as legend is opened automatically in split map mode
+ t.equal(wrapper.find(MapControlButton).length, 7, 'Should show 7 MapControlButton');
t.equal(wrapper.find(Split).length, 0, 'Should show 0 split map split button');
t.equal(wrapper.find(Delete).length, 1, 'Should show 1 split map delete button');
t.equal(wrapper.find(Layers).length, 1, 'Should show 1 Layer button');
@@ -194,7 +194,7 @@ test('MapControlFactory - click options', t => {
}, 'MapContainer should not fail without props');
// layer selector is not active
- t.equal(wrapper.find(MapControlButton).length, 6, 'Should show 6 MapControlButton');
+ t.equal(wrapper.find(MapControlButton).length, 7, 'Should show 7 MapControlButton');
t.equal(wrapper.find(Delete).length, 1, 'Should show 1 delete split map button');
// click split Map
diff --git a/test/node/reducers/annotation-merger-test.js b/test/node/reducers/annotation-merger-test.js
new file mode 100644
index 000000000..348f0f071
--- /dev/null
+++ b/test/node/reducers/annotation-merger-test.js
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {mergeAnnotations, INITIAL_VIS_STATE} from '@kepler.gl/reducers';
+import {AnnotationKind} from '@kepler.gl/constants';
+
+const makeState = (annotations = []) => ({
+ ...INITIAL_VIS_STATE,
+ annotations
+});
+
+const makeAnnotation = (overrides = {}) => ({
+ id: 'ann-1',
+ kind: AnnotationKind.POINT,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [10, 20],
+ label: 'Test',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 0,
+ textHeight: 0,
+ armLength: 50,
+ angle: -45,
+ ...overrides
+});
+
+test('#mergeAnnotations -> should merge valid annotations', t => {
+ const state = makeState();
+ const annotations = [makeAnnotation({id: 'a1'}), makeAnnotation({id: 'a2', label: 'Second'})];
+
+ const result = mergeAnnotations(state, annotations);
+
+ t.equal(result.annotations.length, 2, 'should merge 2 annotations');
+ t.equal(result.annotations[0].id, 'a1', 'first annotation id should match');
+ t.equal(result.annotations[1].id, 'a2', 'second annotation id should match');
+
+ t.end();
+});
+
+test('#mergeAnnotations -> should return same state for empty input', t => {
+ const state = makeState();
+
+ t.equal(mergeAnnotations(state, []), state, 'should return same state for empty array');
+ t.equal(mergeAnnotations(state, null), state, 'should return same state for null');
+ t.equal(mergeAnnotations(state, undefined), state, 'should return same state for undefined');
+
+ t.end();
+});
+
+test('#mergeAnnotations -> should filter out invalid annotations', t => {
+ const state = makeState();
+ const annotations = [
+ makeAnnotation({id: 'valid'}),
+ {id: null, kind: AnnotationKind.POINT, anchorPoint: [0, 0]},
+ {id: 'no-kind', kind: null, anchorPoint: [0, 0]},
+ {id: 'no-anchor', kind: AnnotationKind.POINT, anchorPoint: 'invalid'},
+ {id: 'bad-kind', kind: 'INVALID_KIND', anchorPoint: [0, 0]},
+ null,
+ undefined
+ ];
+
+ const result = mergeAnnotations(state, annotations);
+
+ t.equal(result.annotations.length, 1, 'should only include valid annotation');
+ t.equal(result.annotations[0].id, 'valid', 'should keep the valid one');
+
+ t.end();
+});
+
+test('#mergeAnnotations -> should reject duplicate IDs', t => {
+ const existing = makeAnnotation({id: 'existing-1'});
+ const state = makeState([existing]);
+
+ const annotations = [
+ makeAnnotation({id: 'existing-1', label: 'Duplicate'}),
+ makeAnnotation({id: 'new-1', label: 'New'})
+ ];
+
+ const result = mergeAnnotations(state, annotations);
+
+ t.equal(result.annotations.length, 2, 'should have 2 annotations (1 existing + 1 new)');
+ t.equal(result.annotations[0].id, 'existing-1', 'existing should remain');
+ t.equal(result.annotations[0].label, 'Test', 'existing should not be overwritten');
+ t.equal(result.annotations[1].id, 'new-1', 'new annotation should be appended');
+
+ t.end();
+});
+
+test('#mergeAnnotations -> should validate annotation kind', t => {
+ const state = makeState();
+ const annotations = [
+ makeAnnotation({id: 'text', kind: AnnotationKind.TEXT}),
+ makeAnnotation({id: 'point', kind: AnnotationKind.POINT}),
+ makeAnnotation({id: 'arrow', kind: AnnotationKind.ARROW}),
+ makeAnnotation({id: 'circle', kind: AnnotationKind.CIRCLE}),
+ makeAnnotation({id: 'invalid', kind: 'HEXAGON'})
+ ];
+
+ const result = mergeAnnotations(state, annotations);
+
+ t.equal(result.annotations.length, 4, 'should accept 4 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.notOk(ids.includes('invalid'), 'HEXAGON is invalid');
+
+ t.end();
+});
+
+test('#mergeAnnotations -> should return same state when all annotations are invalid', t => {
+ const state = makeState();
+ const annotations = [
+ {id: 'bad1', kind: 'INVALID', anchorPoint: [0, 0]},
+ {id: null, kind: AnnotationKind.POINT, anchorPoint: [0, 0]}
+ ];
+
+ const result = mergeAnnotations(state, annotations);
+
+ t.equal(result, state, 'should return same state reference when no valid annotations');
+
+ t.end();
+});
diff --git a/test/node/reducers/annotation-updater-test.js b/test/node/reducers/annotation-updater-test.js
new file mode 100644
index 000000000..65e5a4abd
--- /dev/null
+++ b/test/node/reducers/annotation-updater-test.js
@@ -0,0 +1,220 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {visStateReducer as reducer, INITIAL_VIS_STATE} from '@kepler.gl/reducers';
+import {VisStateActions} from '@kepler.gl/actions';
+import {AnnotationKind} from '@kepler.gl/constants';
+
+const initialState = {...INITIAL_VIS_STATE};
+
+test('#visStateReducer -> ADD_ANNOTATION', t => {
+ const state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ anchorPoint: [10, 20]
+ })
+ );
+
+ t.equal(state.annotations.length, 1, 'should add one annotation');
+ t.deepEqual(state.annotations[0].anchorPoint, [10, 20], 'should set anchorPoint');
+ t.equal(state.annotations[0].kind, AnnotationKind.POINT, 'should default to POINT kind');
+ t.equal(state.annotations[0].isVisible, true, 'should be visible by default');
+ t.equal(state.annotations[0].label, 'New Annotation', 'should have default label');
+ t.equal(state.selectedAnnotationId, state.annotations[0].id, 'should select new annotation');
+ t.equal(state.isEditingAnnotationText, true, 'should start editing text');
+
+ t.end();
+});
+
+test('#visStateReducer -> ADD_ANNOTATION with custom config', t => {
+ const state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ anchorPoint: [5, 15],
+ kind: AnnotationKind.CIRCLE,
+ label: 'My Circle',
+ lineColor: '#FF0000',
+ lineWidth: 4
+ })
+ );
+
+ t.equal(state.annotations.length, 1, 'should add one annotation');
+ t.equal(state.annotations[0].kind, AnnotationKind.CIRCLE, 'should use provided kind');
+ t.equal(state.annotations[0].label, 'My Circle', 'should use provided label');
+ t.equal(state.annotations[0].lineColor, '#FF0000', 'should use provided lineColor');
+ t.equal(state.annotations[0].lineWidth, 4, 'should use provided lineWidth');
+ t.ok(state.annotations[0].radiusInMeters, 'CIRCLE should have radiusInMeters');
+
+ t.end();
+});
+
+test('#visStateReducer -> ADD_ANNOTATION with TEXT kind', t => {
+ const state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ anchorPoint: [0, 0],
+ kind: AnnotationKind.TEXT
+ })
+ );
+
+ t.equal(state.annotations[0].kind, AnnotationKind.TEXT, 'should create TEXT annotation');
+ t.notOk('armLength' in state.annotations[0], 'TEXT should not have armLength');
+ t.notOk('angle' in state.annotations[0], 'TEXT should not have angle');
+
+ t.end();
+});
+
+test('#visStateReducer -> ADD_ANNOTATION with ARROW kind', t => {
+ const state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ anchorPoint: [0, 0],
+ kind: AnnotationKind.ARROW
+ })
+ );
+
+ t.equal(state.annotations[0].kind, AnnotationKind.ARROW, 'should create ARROW annotation');
+ t.ok('armLength' in state.annotations[0], 'ARROW should have armLength');
+ t.ok('angle' in state.annotations[0], 'ARROW should have angle');
+
+ t.end();
+});
+
+test('#visStateReducer -> REMOVE_ANNOTATION', t => {
+ let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
+ const id = state.annotations[0].id;
+
+ state = reducer(state, VisStateActions.removeAnnotation(id));
+
+ t.equal(state.annotations.length, 0, 'should remove annotation');
+ t.equal(state.selectedAnnotationId, null, 'should deselect removed annotation');
+
+ t.end();
+});
+
+test('#visStateReducer -> REMOVE_ANNOTATION preserves selection of other', t => {
+ let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
+ state = reducer(state, VisStateActions.addAnnotation({anchorPoint: [1, 1]}));
+
+ const firstId = state.annotations[1].id;
+ const secondId = state.annotations[0].id;
+
+ // select the second annotation
+ state = reducer(state, VisStateActions.setSelectedAnnotation(secondId, false));
+
+ // remove the first
+ state = reducer(state, VisStateActions.removeAnnotation(firstId));
+
+ t.equal(state.annotations.length, 1, 'should have one annotation left');
+ t.equal(state.selectedAnnotationId, secondId, 'should preserve selection of other annotation');
+
+ t.end();
+});
+
+test('#visStateReducer -> UPDATE_ANNOTATION', t => {
+ let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
+ const id = state.annotations[0].id;
+
+ state = reducer(
+ state,
+ VisStateActions.updateAnnotation(id, {
+ label: 'Updated Label',
+ lineColor: '#00FF00'
+ })
+ );
+
+ t.equal(state.annotations[0].label, 'Updated Label', 'should update label');
+ t.equal(state.annotations[0].lineColor, '#00FF00', 'should update lineColor');
+ t.equal(state.annotations[0].id, id, 'should preserve id');
+
+ t.end();
+});
+
+test('#visStateReducer -> UPDATE_ANNOTATION with kind change', t => {
+ let state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ anchorPoint: [0, 0],
+ kind: AnnotationKind.POINT
+ })
+ );
+ const id = state.annotations[0].id;
+
+ state = reducer(state, VisStateActions.updateAnnotation(id, {kind: AnnotationKind.CIRCLE}));
+
+ t.equal(state.annotations[0].kind, AnnotationKind.CIRCLE, 'should change kind');
+ t.ok('radiusInMeters' in state.annotations[0], 'should add CIRCLE-specific properties');
+
+ t.end();
+});
+
+test('#visStateReducer -> UPDATE_ANNOTATION with invalid id', t => {
+ let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
+
+ const prevState = state;
+ state = reducer(state, VisStateActions.updateAnnotation('nonexistent', {label: 'x'}));
+
+ t.equal(state, prevState, 'should return same state for invalid id');
+
+ t.end();
+});
+
+test('#visStateReducer -> DUPLICATE_ANNOTATION', t => {
+ let state = reducer(
+ initialState,
+ VisStateActions.addAnnotation({
+ anchorPoint: [10, 20],
+ kind: AnnotationKind.ARROW
+ })
+ );
+ const originalId = state.annotations[0].id;
+
+ state = reducer(state, VisStateActions.duplicateAnnotation(originalId));
+
+ t.equal(state.annotations.length, 2, 'should have two annotations');
+ t.notEqual(state.annotations[0].id, originalId, 'duplicate should have new id');
+ t.ok(
+ state.annotations[0].label.startsWith('Copy of'),
+ 'duplicate label should start with "Copy of"'
+ );
+ t.deepEqual(state.annotations[0].anchorPoint, [10, 20], 'duplicate should copy anchorPoint');
+ t.equal(state.annotations[0].kind, AnnotationKind.ARROW, 'duplicate should copy kind');
+ t.equal(state.selectedAnnotationId, state.annotations[0].id, 'should select the duplicate');
+ t.equal(state.isEditingAnnotationText, false, 'should not edit text on duplicate');
+
+ t.end();
+});
+
+test('#visStateReducer -> DUPLICATE_ANNOTATION with invalid id', t => {
+ let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
+ const prevState = state;
+
+ state = reducer(state, VisStateActions.duplicateAnnotation('nonexistent'));
+
+ t.equal(state, prevState, 'should return same state for invalid id');
+
+ t.end();
+});
+
+test('#visStateReducer -> SET_SELECTED_ANNOTATION', t => {
+ let state = reducer(initialState, VisStateActions.addAnnotation({anchorPoint: [0, 0]}));
+ const id = state.annotations[0].id;
+
+ // Deselect
+ state = reducer(state, VisStateActions.setSelectedAnnotation(null, false));
+ t.equal(state.selectedAnnotationId, null, 'should deselect');
+ t.equal(state.isEditingAnnotationText, false, 'should stop editing');
+
+ // Select with editing
+ state = reducer(state, VisStateActions.setSelectedAnnotation(id, true));
+ t.equal(state.selectedAnnotationId, id, 'should select annotation');
+ t.equal(state.isEditingAnnotationText, true, 'should start editing text');
+
+ // Same state no change
+ const prevState = state;
+ state = reducer(state, VisStateActions.setSelectedAnnotation(id, true));
+ t.equal(state, prevState, 'should return same state if already in same selection state');
+
+ t.end();
+});
diff --git a/test/node/reducers/index.js b/test/node/reducers/index.js
index 196c9603e..0f3c79cf7 100644
--- a/test/node/reducers/index.js
+++ b/test/node/reducers/index.js
@@ -12,3 +12,7 @@ import './root-test';
// test mergers
import './vis-state-merger-test';
+import './annotation-merger-test';
+
+// test annotation updaters
+import './annotation-updater-test';
diff --git a/test/node/schemas/annotation-schema-test.js b/test/node/schemas/annotation-schema-test.js
new file mode 100644
index 000000000..5280defd8
--- /dev/null
+++ b/test/node/schemas/annotation-schema-test.js
@@ -0,0 +1,215 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {AnnotationsSchema} from '@kepler.gl/schemas';
+import {AnnotationKind} from '@kepler.gl/constants';
+import {VERSIONS} from '@kepler.gl/schemas';
+
+const annotationPropsV1 = {
+ id: null,
+ kind: null,
+ isVisible: null,
+ autoSize: null,
+ autoSizeY: null,
+ anchorPoint: null,
+ label: null,
+ editorState: null,
+ mapIndex: null,
+ lineColor: null,
+ lineWidth: null,
+ textWidth: null,
+ textHeight: null,
+ textVerticalAlign: null,
+ armLength: null,
+ angle: null,
+ radiusInMeters: null
+};
+
+const schema = new AnnotationsSchema({
+ version: VERSIONS.v1,
+ properties: annotationPropsV1
+});
+
+const makePointAnnotation = (overrides = {}) => ({
+ id: 'ann-point-1',
+ kind: AnnotationKind.POINT,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [10, 20],
+ label: 'Point annotation',
+ editorState: {root: {children: [], direction: null, format: '', indent: 0, type: 'root', version: 1}},
+ mapIndex: 0,
+ lineColor: '#FF0000',
+ lineWidth: 3,
+ textWidth: 120,
+ textHeight: 40,
+ textVerticalAlign: 'bottom',
+ armLength: 60,
+ angle: -30,
+ radiusInMeters: null,
+ ...overrides
+});
+
+const makeCircleAnnotation = (overrides = {}) => ({
+ id: 'ann-circle-1',
+ kind: AnnotationKind.CIRCLE,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [-122.4, 37.8],
+ label: 'Circle annotation',
+ editorState: null,
+ mapIndex: null,
+ lineColor: '#00FF00',
+ lineWidth: 2,
+ textWidth: 0,
+ textHeight: 0,
+ textVerticalAlign: 'bottom',
+ armLength: 50,
+ angle: -45,
+ radiusInMeters: 5000,
+ ...overrides
+});
+
+const makeTextAnnotation = (overrides = {}) => ({
+ id: 'ann-text-1',
+ kind: AnnotationKind.TEXT,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ label: 'Text only',
+ editorState: null,
+ mapIndex: null,
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ textVerticalAlign: 'middle',
+ armLength: null,
+ angle: null,
+ radiusInMeters: null,
+ ...overrides
+});
+
+test('#AnnotationsSchema -> save', t => {
+ const annotations = [makePointAnnotation(), makeCircleAnnotation()];
+
+ const saved = schema.save(annotations);
+
+ t.ok(saved.annotations, 'should have annotations key');
+ t.equal(saved.annotations.length, 2, 'should save 2 annotations');
+
+ const savedPoint = saved.annotations[0];
+ t.equal(savedPoint.id, 'ann-point-1', 'should save id');
+ t.equal(savedPoint.kind, AnnotationKind.POINT, 'should save kind');
+ t.deepEqual(savedPoint.anchorPoint, [10, 20], 'should save anchorPoint');
+ t.equal(savedPoint.label, 'Point annotation', 'should save label');
+ t.equal(savedPoint.lineColor, '#FF0000', 'should save lineColor');
+ t.equal(savedPoint.armLength, 60, 'should save armLength');
+ t.equal(savedPoint.angle, -30, 'should save angle');
+
+ const savedCircle = saved.annotations[1];
+ t.equal(savedCircle.kind, AnnotationKind.CIRCLE, 'should save circle kind');
+ t.equal(savedCircle.radiusInMeters, 5000, 'should save radiusInMeters');
+
+ t.end();
+});
+
+test('#AnnotationsSchema -> load', t => {
+ const savedAnnotations = [
+ {
+ id: 'loaded-1',
+ kind: AnnotationKind.ARROW,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [5, 10],
+ label: 'Loaded arrow',
+ mapIndex: null,
+ lineColor: '#0000FF',
+ lineWidth: 4,
+ textWidth: 80,
+ textHeight: 20,
+ textVerticalAlign: 'bottom',
+ armLength: 70,
+ angle: 45,
+ radiusInMeters: null
+ }
+ ];
+
+ const loaded = schema.load(savedAnnotations);
+
+ t.ok(loaded.annotations, 'should have annotations key');
+ t.equal(loaded.annotations.length, 1, 'should load 1 annotation');
+
+ const ann = loaded.annotations[0];
+ t.equal(ann.id, 'loaded-1', 'should load id');
+ t.equal(ann.kind, AnnotationKind.ARROW, 'should load kind');
+ t.deepEqual(ann.anchorPoint, [5, 10], 'should load anchorPoint');
+ t.equal(ann.label, 'Loaded arrow', 'should load label');
+ t.equal(ann.armLength, 70, 'should load armLength');
+
+ t.end();
+});
+
+test('#AnnotationsSchema -> save/load round-trip', t => {
+ const original = [makePointAnnotation(), makeCircleAnnotation(), makeTextAnnotation()];
+
+ const saved = schema.save(original);
+ const loaded = schema.load(saved.annotations);
+
+ t.equal(loaded.annotations.length, 3, 'should round-trip 3 annotations');
+
+ // Check point
+ t.equal(loaded.annotations[0].id, 'ann-point-1', 'point id round-trips');
+ t.equal(loaded.annotations[0].kind, AnnotationKind.POINT, 'point kind round-trips');
+ t.deepEqual(loaded.annotations[0].anchorPoint, [10, 20], 'point anchorPoint round-trips');
+ t.equal(loaded.annotations[0].armLength, 60, 'point armLength round-trips');
+ t.equal(loaded.annotations[0].textVerticalAlign, 'bottom', 'point textVerticalAlign round-trips');
+ t.deepEqual(
+ loaded.annotations[0].editorState,
+ {root: {children: [], direction: null, format: '', indent: 0, type: 'root', version: 1}},
+ 'point editorState round-trips'
+ );
+
+ // Check circle
+ t.equal(loaded.annotations[1].id, 'ann-circle-1', 'circle id round-trips');
+ t.equal(loaded.annotations[1].radiusInMeters, 5000, 'circle radiusInMeters round-trips');
+
+ // Check text
+ t.equal(loaded.annotations[2].id, 'ann-text-1', 'text id round-trips');
+ t.equal(loaded.annotations[2].kind, AnnotationKind.TEXT, 'text kind round-trips');
+ t.equal(loaded.annotations[2].textVerticalAlign, 'middle', 'text textVerticalAlign round-trips');
+
+ t.end();
+});
+
+test('#AnnotationsSchema -> save empty annotations', t => {
+ const saved = schema.save([]);
+
+ t.ok(saved.annotations, 'should have annotations key');
+ t.equal(saved.annotations.length, 0, 'should save empty array');
+
+ t.end();
+});
+
+test('#AnnotationsSchema -> saves only known properties', t => {
+ const annotation = {
+ ...makePointAnnotation(),
+ unknownProp: 'should be stripped',
+ anotherExtra: 123
+ };
+
+ const saved = schema.save([annotation]);
+ const savedAnn = saved.annotations[0];
+
+ t.notOk('unknownProp' in savedAnn, 'should not save unknown properties');
+ t.notOk('anotherExtra' in savedAnn, 'should not save extra properties');
+ t.ok('id' in savedAnn, 'should save known property: id');
+ t.ok('kind' in savedAnn, 'should save known property: kind');
+
+ t.end();
+});
diff --git a/test/node/schemas/index.js b/test/node/schemas/index.js
index d76474e64..76e46b09b 100644
--- a/test/node/schemas/index.js
+++ b/test/node/schemas/index.js
@@ -8,3 +8,4 @@ import './map-style-schema-test';
import './dataset-schema-test';
import './schema-conversion-test';
import './ui-state-schema-test';
+import './annotation-schema-test';
diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.js
index ade7cd872..1464b5aab 100644
--- a/test/node/schemas/vis-state-schema-test.js
+++ b/test/node/schemas/vis-state-schema-test.js
@@ -33,6 +33,7 @@ const expectedVisStateEntries = [
'filters',
'layers',
'effects',
+ 'annotations',
'interactionConfig',
'layerBlending',
'overlayBlending',
diff --git a/test/node/utils/annotation-utils-test.js b/test/node/utils/annotation-utils-test.js
new file mode 100644
index 000000000..8dabedc74
--- /dev/null
+++ b/test/node/utils/annotation-utils-test.js
@@ -0,0 +1,205 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {AnnotationKind} from '@kepler.gl/constants';
+import {makeMarker, movePoint, moveText, resizeCircle, isLeftOriented} from '@kepler.gl/components';
+
+const mockViewport = {
+ project: ([lng, lat]) => [lng * 10 + 500, lat * -10 + 300],
+ unproject: ([x, y]) => [(x - 500) / 10, (y - 300) / -10],
+ longitude: 0,
+ latitude: 0,
+ width: 1000,
+ height: 600,
+ zoom: 10
+};
+
+const makePointAnnotation = (overrides = {}) => ({
+ id: 'test-point',
+ kind: AnnotationKind.POINT,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ label: 'Test',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ armLength: 50,
+ angle: 0,
+ ...overrides
+});
+
+const makeTextAnnotation = (overrides = {}) => ({
+ id: 'test-text',
+ kind: AnnotationKind.TEXT,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ label: 'Test',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ ...overrides
+});
+
+const makeCircleAnnotation = (overrides = {}) => ({
+ id: 'test-circle',
+ kind: AnnotationKind.CIRCLE,
+ isVisible: true,
+ autoSize: true,
+ autoSizeY: true,
+ anchorPoint: [0, 0],
+ label: 'Circle',
+ lineColor: '#FFFFFF',
+ lineWidth: 2,
+ textWidth: 100,
+ textHeight: 30,
+ armLength: 50,
+ angle: 0,
+ radiusInMeters: 1000,
+ ...overrides
+});
+
+test('#isLeftOriented', t => {
+ t.equal(isLeftOriented(0), false, '0 degrees is right-oriented');
+ t.equal(isLeftOriented(45), false, '45 degrees is right-oriented');
+ t.equal(isLeftOriented(90), false, '90 degrees is right-oriented');
+ t.equal(isLeftOriented(91), true, '91 degrees is left-oriented');
+ t.equal(isLeftOriented(180), true, '180 degrees is left-oriented');
+ t.equal(isLeftOriented(-90), false, '-90 degrees is right-oriented');
+ t.equal(isLeftOriented(-91), true, '-91 degrees is left-oriented');
+ t.equal(isLeftOriented(-180), true, '-180 degrees is left-oriented');
+
+ t.end();
+});
+
+test('#makeMarker -> POINT annotation', t => {
+ const annotation = makePointAnnotation({anchorPoint: [10, 20], armLength: 50, angle: 0});
+ const marker = makeMarker(annotation, mockViewport);
+
+ t.equal(marker.kind, AnnotationKind.POINT, 'should return POINT kind');
+ t.ok(isFinite(marker.x), 'should have numeric x');
+ t.ok(isFinite(marker.y), 'should have numeric y');
+ t.ok(isFinite(marker.tx), 'should have numeric tx');
+ t.ok(isFinite(marker.ty), 'should have numeric ty');
+ t.equal(marker.tx, 50, 'tx should equal armLength when angle is 0');
+ t.ok(Math.abs(marker.ty) < 0.001, 'ty should be ~0 when angle is 0');
+
+ t.end();
+});
+
+test('#makeMarker -> TEXT annotation', t => {
+ const annotation = makeTextAnnotation({anchorPoint: [5, 10]});
+ const marker = makeMarker(annotation, mockViewport);
+
+ t.equal(marker.kind, AnnotationKind.TEXT, 'should return TEXT kind');
+ t.equal(marker.tx, 0, 'TEXT should have tx = 0');
+ t.equal(marker.ty, 0, 'TEXT should have ty = 0');
+
+ t.end();
+});
+
+test('#makeMarker -> POINT with non-zero angle', t => {
+ const annotation = makePointAnnotation({armLength: 100, angle: 90});
+ const marker = makeMarker(annotation, mockViewport);
+
+ t.ok(Math.abs(marker.tx) < 0.001, 'tx should be ~0 at 90 degrees');
+ t.ok(Math.abs(marker.ty - 100) < 0.001, 'ty should be ~100 at 90 degrees');
+
+ t.end();
+});
+
+test('#movePoint -> should compute new anchorPoint from delta', t => {
+ const annotation = makePointAnnotation({anchorPoint: [0, 0]});
+ const delta = {x: 10, y: -5};
+
+ const changes = movePoint(annotation, delta, mockViewport);
+
+ t.ok(changes.anchorPoint, 'should return anchorPoint');
+ t.equal(changes.anchorPoint.length, 2, 'anchorPoint should be [lon, lat]');
+ // With our mock viewport: unproject([500 + 10, 300 + (-5)]) = [(510-500)/10, (295-300)/-10] = [1, 0.5]
+ t.equal(changes.anchorPoint[0], 1, 'longitude should shift by delta.x / scale');
+ t.equal(
+ changes.anchorPoint[1],
+ 0.5,
+ 'latitude should increase when moving up (negative y delta)'
+ );
+
+ t.end();
+});
+
+test('#movePoint -> zero delta returns same position', t => {
+ const annotation = makePointAnnotation({anchorPoint: [5, 10]});
+ const delta = {x: 0, y: 0};
+
+ const changes = movePoint(annotation, delta, mockViewport);
+
+ t.deepEqual(changes.anchorPoint, [5, 10], 'should return same anchorPoint for zero delta');
+
+ t.end();
+});
+
+test('#moveText -> TEXT annotation delegates to movePoint', t => {
+ const annotation = makeTextAnnotation({anchorPoint: [0, 0]});
+ const delta = {x: 20, y: 10};
+
+ const changes = moveText(annotation, delta, mockViewport);
+
+ t.ok(changes.anchorPoint, 'TEXT moveText should return anchorPoint');
+ t.notOk(changes.angle, 'TEXT moveText should not return angle');
+ t.notOk(changes.armLength, 'TEXT moveText should not return armLength');
+
+ t.end();
+});
+
+test('#moveText -> POINT annotation changes angle and armLength', t => {
+ const annotation = makePointAnnotation({armLength: 50, angle: 0});
+ const delta = {x: 10, y: 10};
+
+ const changes = moveText(annotation, delta, mockViewport);
+
+ t.ok('angle' in changes, 'should return angle');
+ t.ok('armLength' in changes, 'should return armLength');
+ t.notOk('anchorPoint' in changes, 'should not return anchorPoint');
+
+ t.end();
+});
+
+test('#resizeCircle -> non-circle returns empty', t => {
+ const annotation = makePointAnnotation();
+ const delta = {x: 10, y: 0};
+
+ const changes = resizeCircle(annotation, delta, mockViewport);
+
+ t.deepEqual(changes, {}, 'should return empty object for non-circle');
+
+ t.end();
+});
+
+test('#resizeCircle -> circle returns radiusInMeters', t => {
+ const annotation = makeCircleAnnotation({radiusInMeters: 1000});
+ const delta = {x: 5, y: 0};
+
+ const changes = resizeCircle(annotation, delta, mockViewport);
+
+ t.ok('radiusInMeters' in changes, 'should return radiusInMeters');
+ t.ok(changes.radiusInMeters > 0, 'radius should be positive');
+
+ t.end();
+});
+
+test('#resizeCircle -> radius cannot go below 0', t => {
+ const annotation = makeCircleAnnotation({radiusInMeters: 10});
+ const delta = {x: -99999, y: 0};
+
+ const changes = resizeCircle(annotation, delta, mockViewport);
+
+ t.ok(changes.radiusInMeters >= 0, 'radius should not be negative');
+
+ t.end();
+});
diff --git a/test/node/utils/data-processor-test.js b/test/node/utils/data-processor-test.js
index 6ac0922c6..44a00f5fd 100644
--- a/test/node/utils/data-processor-test.js
+++ b/test/node/utils/data-processor-test.js
@@ -165,11 +165,7 @@ test('Processor -> detectDelimiter', t => {
'should fall back to comma when no delimiter produces multiple columns'
);
t.equal(detectDelimiter(''), ',', 'should return comma for empty string');
- t.equal(
- detectDelimiter('a,b,c'),
- ',',
- 'should handle input without newline (single line)'
- );
+ t.equal(detectDelimiter('a,b,c'), ',', 'should handle input without newline (single line)');
t.equal(
detectDelimiter('"a\tb"\tc\td\n1\t2\t3'),
@@ -241,7 +237,8 @@ test('Processor -> processCsvData -> pipe-separated', t => {
});
test('Processor -> processCsvData -> semicolon with quoted commas', t => {
- const data = '"City, Country";Population;Area\n"Berlin, Germany";3600000;891\n"Paris, France";2100000;105';
+ const data =
+ '"City, Country";Population;Area\n"Berlin, Germany";3600000;891\n"Paris, France";2100000;105';
const result = processCsvData(data);
t.equal(result.fields.length, 3, 'should parse 3 fields');
@@ -347,12 +344,21 @@ test('Processor -> processCsvData -> semicolon-separated with numeric data', t =
});
test('Processor -> processCsvData -> pipe-separated with special characters in values', t => {
- const data = 'id|description|url\n1|"hello, world"|http://example.com\n2|"foo; bar"|http://test.org';
+ const data =
+ 'id|description|url\n1|"hello, world"|http://example.com\n2|"foo; bar"|http://test.org';
const result = processCsvData(data);
t.equal(result.fields.length, 3, 'should parse 3 fields');
- t.equal(result.rows[0][1], 'hello, world', 'should handle commas inside quoted pipe-separated fields');
- t.equal(result.rows[1][1], 'foo; bar', 'should handle semicolons inside quoted pipe-separated fields');
+ t.equal(
+ result.rows[0][1],
+ 'hello, world',
+ 'should handle commas inside quoted pipe-separated fields'
+ );
+ t.equal(
+ result.rows[1][1],
+ 'foo; bar',
+ 'should handle semicolons inside quoted pipe-separated fields'
+ );
t.end();
});
diff --git a/test/node/utils/filter-utils-test.js b/test/node/utils/filter-utils-test.js
index 459756845..aa62406da 100644
--- a/test/node/utils/filter-utils-test.js
+++ b/test/node/utils/filter-utils-test.js
@@ -670,7 +670,15 @@ test('filterUtils -> getPolygonFilterFunctor -> point layer with dataToFeature (
properties: {},
geometry: {
type: 'Polygon',
- coordinates: [[[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1]]]
+ coordinates: [
+ [
+ [-1, -1],
+ [1, -1],
+ [1, 1],
+ [-1, 1],
+ [-1, -1]
+ ]
+ ]
}
};
@@ -683,12 +691,18 @@ test('filterUtils -> getPolygonFilterFunctor -> point layer with dataToFeature (
getPositionAccessor: () => () => null,
dataToFeature: {
length: 6,
- 0: [0.5, 0.5], // inside
- 1: [10, 10], // outside
- 2: [[10, 10], [0.2, 0.2]], // MultiPoint: one inside
- 3: [[10, 10], [20, 20]], // MultiPoint: all outside
- 4: [], // empty coordinates (e.g. empty GeometryCollection)
- 5: [[], [0.5, 0.5]] // MultiPoint with one empty coord pair
+ 0: [0.5, 0.5], // inside
+ 1: [10, 10], // outside
+ 2: [
+ [10, 10],
+ [0.2, 0.2]
+ ], // MultiPoint: one inside
+ 3: [
+ [10, 10],
+ [20, 20]
+ ], // MultiPoint: all outside
+ 4: [], // empty coordinates (e.g. empty GeometryCollection)
+ 5: [[], [0.5, 0.5]] // MultiPoint with one empty coord pair
}
};
@@ -699,7 +713,11 @@ test('filterUtils -> getPolygonFilterFunctor -> point layer with dataToFeature (
t.equal(fn({index: 2}), true, 'MultiPoint with at least one point inside should return true');
t.equal(fn({index: 3}), false, 'MultiPoint with all points outside should return false');
t.equal(fn({index: 4}), false, 'Empty coordinates should return false');
- t.equal(fn({index: 5}), true, 'MultiPoint with one empty and one valid inside should return true');
+ t.equal(
+ fn({index: 5}),
+ true,
+ 'MultiPoint with one empty and one valid inside should return true'
+ );
// Point layer without dataToFeature (standard column mode)
const layerWithoutDataToFeature = {
diff --git a/test/node/utils/index.js b/test/node/utils/index.js
index 62126c741..cd556a0c5 100644
--- a/test/node/utils/index.js
+++ b/test/node/utils/index.js
@@ -27,3 +27,4 @@ import './composer-helpers-test';
import './dom-to-image';
import './effect-utils-test';
import './duckdb-utils-test';
+import './annotation-utils-test';
diff --git a/webpack/shared-webpack-configuration.js b/webpack/shared-webpack-configuration.js
index 2f7f5041d..ab5e48e3f 100644
--- a/webpack/shared-webpack-configuration.js
+++ b/webpack/shared-webpack-configuration.js
@@ -32,7 +32,8 @@ workspaces.forEach(workspace => {
const ENV_VARIABLES_WITH_INSTRUCTIONS = {
MapboxAccessToken: 'You can get the token at https://www.mapbox.com/help/how-access-tokens-work/',
DropboxClientId: 'You can get the token at https://www.dropbox.com/developers',
- CartoClientId: 'You can get the token at https://carto.com/help/working-with-data/carto-platform-api-keys',
+ CartoClientId:
+ 'You can get the token at https://carto.com/help/working-with-data/carto-platform-api-keys',
MapboxExportToken: 'You can get the token at https://www.mapbox.com/help/how-access-tokens-work/',
FoursquareClientId: 'You can get the token at https://location.foursquare.com/developer',
FoursquareDomain: 'You can get the token at https://location.foursquare.com/developer',
diff --git a/yarn.lock b/yarn.lock
index 808b4bc15..b971895ee 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5237,10 +5237,15 @@ __metadata:
"@kepler.gl/table": "npm:3.3.0-alpha.0"
"@kepler.gl/types": "npm:3.3.0-alpha.0"
"@kepler.gl/utils": "npm:3.3.0-alpha.0"
+ "@lexical/link": "npm:^0.9.0"
+ "@lexical/react": "npm:^0.9.0"
+ "@lexical/selection": "npm:^0.9.0"
+ "@lexical/utils": "npm:^0.9.0"
"@loaders.gl/mvt": "npm:^4.4.1"
"@loaders.gl/pmtiles": "npm:^4.4.1"
"@loaders.gl/wms": "npm:4.4.1"
"@mapbox/mapbox-sdk": "npm:^0.15.3"
+ "@math.gl/web-mercator": "npm:^4.1.0"
"@tippyjs/react": "npm:^4.2.0"
"@types/classnames": "npm:^2.3.1"
"@types/d3-array": "npm:^2.8.0"
@@ -5271,6 +5276,7 @@ __metadata:
exenv: "npm:^1.2.2"
fuzzy: "npm:^0.1.3"
global: "npm:^4.3.0"
+ lexical: "npm:^0.9.0"
lodash: "npm:4.17.23"
mapbox-gl: "npm:1.13.1"
maplibre-gl: "npm:^4.0.0"
@@ -5713,6 +5719,249 @@ __metadata:
languageName: node
linkType: hard
+"@lexical/clipboard@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/clipboard@npm:0.9.2"
+ dependencies:
+ "@lexical/html": "npm:0.9.2"
+ "@lexical/list": "npm:0.9.2"
+ "@lexical/selection": "npm:0.9.2"
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/a2e9927c0b624a8f3d99789716d4e0920117f8623fa43b7c1d78496ef7b13fc8dee0dcbce495d5a50e480e23e5fea7d817114289b279f000752368f1fe3b35ec
+ languageName: node
+ linkType: hard
+
+"@lexical/code@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/code@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ prismjs: "npm:^1.27.0"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/7221df87be64721f5724b132e2691e4c3d3c44cd98863564d9c8f1acaaddf5e3c4206fcfa1afd07dd22e2156ad3093d2b3eb5a4c1be08aa2194e3f203d549e3c
+ languageName: node
+ linkType: hard
+
+"@lexical/dragon@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/dragon@npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/f4c3b16c35ae4db1e41aea07cd866d792e82d5ac88a8a81f598b5a3142b6321f3d8b4f5362d217e3314f5b1c95de54469a85a9766e600fc89f563f3589b66f78
+ languageName: node
+ linkType: hard
+
+"@lexical/hashtag@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/hashtag@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/19eeed5fc8604c67e102511bede8cba53f2154160a05d8dd1e86764d3677b7b8ce3d09ee4bca0b42e0f54acbc17a4323a2606a27d1307309feec83771f0061ec
+ languageName: node
+ linkType: hard
+
+"@lexical/history@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/history@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/b558a20f2310dce2a0bdd952a923a04d3183caf1c5ee6c11bce78b58836b813d372dd62f9ac4e04f43ca4cd31a91efbd97922c6225acd09a6c4337982d289ab8
+ languageName: node
+ linkType: hard
+
+"@lexical/html@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/html@npm:0.9.2"
+ dependencies:
+ "@lexical/selection": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/d758d8829f9aef3e8088418ace9211faff8a3706e2c1f131019373f0f5eefd593c77b56c66ac3acf0ad14ac6ae704d28d22e28075d1343c76b73a991467c0703
+ languageName: node
+ linkType: hard
+
+"@lexical/link@npm:0.9.2, @lexical/link@npm:^0.9.0":
+ version: 0.9.2
+ resolution: "@lexical/link@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/c7aaf67a130cc8527765d89ca46f63151ade3f8be8608328ea8492bc5a1f1057e099515706f8064b43cb6299016875c9338f8335b9294c47ff3c012d1ff643b7
+ languageName: node
+ linkType: hard
+
+"@lexical/list@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/list@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/75a8d48baa5be4abda5501330d7ec761c9772cdca7047161d5a27bdc7c513c5fbf23158f5d55bd2f113c448256579ca3cb405fcf1f52bd8095a8bca3bc8be123
+ languageName: node
+ linkType: hard
+
+"@lexical/mark@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/mark@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/1226e43137045ab1b92a73a60728ddb14680db8c032747d2b2f0ce932a913bdedce7d4e8c26538d9f844710731845dab649662be1c1c2f27af072ff4cb86a5b6
+ languageName: node
+ linkType: hard
+
+"@lexical/markdown@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/markdown@npm:0.9.2"
+ dependencies:
+ "@lexical/code": "npm:0.9.2"
+ "@lexical/link": "npm:0.9.2"
+ "@lexical/list": "npm:0.9.2"
+ "@lexical/rich-text": "npm:0.9.2"
+ "@lexical/text": "npm:0.9.2"
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/f527902ff9e8e74eee227887e45a97b9d6220d6c893d59a617b5c1028192e38a6a940071d15c775264316657530a9b62bef7341c36f62e563fc9b794b6ace19e
+ languageName: node
+ linkType: hard
+
+"@lexical/offset@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/offset@npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/d7c477534d6f56cb5133daf68ff64af6dd3ddb33ebf3b693292719706c087b6699030d3a64d982155d093b6aad122571592d35fef7a8867309631a588cf17d4c
+ languageName: node
+ linkType: hard
+
+"@lexical/overflow@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/overflow@npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/6847d293b1fb0e8ebcb145f103f2e2374a14ae50ac5f258e2b85797acbbbc16eb17fcdbea3aec63f785170067450196d7b2277a431895a241150334582c54f8e
+ languageName: node
+ linkType: hard
+
+"@lexical/plain-text@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/plain-text@npm:0.9.2"
+ peerDependencies:
+ "@lexical/clipboard": 0.9.2
+ "@lexical/selection": 0.9.2
+ "@lexical/utils": 0.9.2
+ lexical: 0.9.2
+ checksum: 10c0/44e65f93865ed11e6f68dcb9f37a2ffa68832d4534f565d264af0513ce9ca568b5f6d298bb3c12c92ced4100424e040cd348057342ff3827e587f756e4e6c843
+ languageName: node
+ linkType: hard
+
+"@lexical/react@npm:^0.9.0":
+ version: 0.9.2
+ resolution: "@lexical/react@npm:0.9.2"
+ dependencies:
+ "@lexical/clipboard": "npm:0.9.2"
+ "@lexical/code": "npm:0.9.2"
+ "@lexical/dragon": "npm:0.9.2"
+ "@lexical/hashtag": "npm:0.9.2"
+ "@lexical/history": "npm:0.9.2"
+ "@lexical/link": "npm:0.9.2"
+ "@lexical/list": "npm:0.9.2"
+ "@lexical/mark": "npm:0.9.2"
+ "@lexical/markdown": "npm:0.9.2"
+ "@lexical/overflow": "npm:0.9.2"
+ "@lexical/plain-text": "npm:0.9.2"
+ "@lexical/rich-text": "npm:0.9.2"
+ "@lexical/selection": "npm:0.9.2"
+ "@lexical/table": "npm:0.9.2"
+ "@lexical/text": "npm:0.9.2"
+ "@lexical/utils": "npm:0.9.2"
+ "@lexical/yjs": "npm:0.9.2"
+ react-error-boundary: "npm:^3.1.4"
+ peerDependencies:
+ lexical: 0.9.2
+ react: ">=17.x"
+ react-dom: ">=17.x"
+ checksum: 10c0/f312400414e20079d394d735d72dd6f360336c9700a9fb962178f8685fed81267f3b789071726cd053a4755c5fdbfa68d39939ac302fa0656e3d7c294bd1b5d0
+ languageName: node
+ linkType: hard
+
+"@lexical/rich-text@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/rich-text@npm:0.9.2"
+ peerDependencies:
+ "@lexical/clipboard": 0.9.2
+ "@lexical/selection": 0.9.2
+ "@lexical/utils": 0.9.2
+ lexical: 0.9.2
+ checksum: 10c0/9470230289a598beb5bb238598d4eac7259cdbc05b3278b17099bcc59a120fc2b01df47f7d4456d205b7da63e5122db833e2a542fd672a14fde4aa8af1e5f9b0
+ languageName: node
+ linkType: hard
+
+"@lexical/selection@npm:0.9.2, @lexical/selection@npm:^0.9.0":
+ version: 0.9.2
+ resolution: "@lexical/selection@npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/70228193b64e813598f7d2192639409ae30eea337935bab8808a5a754e431c7e79789e1d261b4f5684d70dd3fa0de0e9e1925b92b3a8a925d3db48e50f42f9ab
+ languageName: node
+ linkType: hard
+
+"@lexical/table@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/table@npm:0.9.2"
+ dependencies:
+ "@lexical/utils": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/8bbd35be82eefc72bbf2f0f04414f61a7ed651ac376bacd0a1ad348f1e0d2a32934306046954b70a4630b68f43a806e6bd4ab97dd4ceb9b45ef5d1c000cb2e54
+ languageName: node
+ linkType: hard
+
+"@lexical/text@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/text@npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/eb61f36e958738ad10b5e42f048db3820aee1965bff71dc29488ac50165bcc6a493d4d7bc50bb08369b8cd9b428650d427b5ea5c5cefc54ef92c296392c2bf4b
+ languageName: node
+ linkType: hard
+
+"@lexical/utils@npm:0.9.2, @lexical/utils@npm:^0.9.0":
+ version: 0.9.2
+ resolution: "@lexical/utils@npm:0.9.2"
+ dependencies:
+ "@lexical/list": "npm:0.9.2"
+ "@lexical/selection": "npm:0.9.2"
+ "@lexical/table": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ checksum: 10c0/90c6818d74b553ded41db69d8235620befd6522582fc6892a94afc7ffd8029c95a0d332a4ac2f6759c49995f25e3c635764f46f611fd7dd2e1863fca4f905d6e
+ languageName: node
+ linkType: hard
+
+"@lexical/yjs@npm:0.9.2":
+ version: 0.9.2
+ resolution: "@lexical/yjs@npm:0.9.2"
+ dependencies:
+ "@lexical/offset": "npm:0.9.2"
+ peerDependencies:
+ lexical: 0.9.2
+ yjs: ">=13.5.22"
+ checksum: 10c0/eb787f501fff0d8ee21c9c97c3f3df2d37f18c5c3209922d0d7c7453e8b1378c14bda12b1cb795d15fe537dadf829bab695fd88adf8f48e13fc2d51ea3d73a56
+ languageName: node
+ linkType: hard
+
"@ljharb/resumer@npm:~0.0.1":
version: 0.0.1
resolution: "@ljharb/resumer@npm:0.0.1"
@@ -22077,6 +22326,13 @@ __metadata:
languageName: node
linkType: hard
+"lexical@npm:^0.9.0":
+ version: 0.9.2
+ resolution: "lexical@npm:0.9.2"
+ checksum: 10c0/89ab6d133d5572603d1cac834c31749add4f03a42cee0c7cd729d6dc9724df9e9517962bacb738bd3d145d1d79988f7038f2576e340cb4c80e55f881618c3208
+ languageName: node
+ linkType: hard
+
"lie@npm:~3.3.0":
version: 3.3.0
resolution: "lie@npm:3.3.0"
@@ -26051,6 +26307,13 @@ __metadata:
languageName: node
linkType: hard
+"prismjs@npm:^1.27.0":
+ version: 1.30.0
+ resolution: "prismjs@npm:1.30.0"
+ checksum: 10c0/f56205bfd58ef71ccfcbcb691fd0eb84adc96c6ff21b0b69fc6fdcf02be42d6ef972ba4aed60466310de3d67733f6a746f89f2fb79c00bf217406d465b3e8f23
+ languageName: node
+ linkType: hard
+
"proc-log@npm:^4.1.0, proc-log@npm:^4.2.0":
version: 4.2.0
resolution: "proc-log@npm:4.2.0"
@@ -26701,6 +26964,17 @@ __metadata:
languageName: node
linkType: hard
+"react-error-boundary@npm:^3.1.4":
+ version: 3.1.4
+ resolution: "react-error-boundary@npm:3.1.4"
+ dependencies:
+ "@babel/runtime": "npm:^7.12.5"
+ peerDependencies:
+ react: ">=16.13.1"
+ checksum: 10c0/f977ca61823e43de2381d53dd7aa8b4d79ff6a984c9afdc88dc44f9973b99de7fd382d2f0f91f2688e24bb987c0185bf45d0b004f22afaaab0f990a830253bfb
+ languageName: node
+ linkType: hard
+
"react-fit@npm:^1.7.0":
version: 1.7.1
resolution: "react-fit@npm:1.7.1"