/** * OpenLayers adapter — grafts onto a host-owned `ol/Map`. Per-overlay style * functions read the same feature render-props as the MapLibre adapter, so the * engines render identically. Glyphs use `ol/style/Icon` (sprite or data-URI); * text boxes use OL's native `backgroundFill`/`backgroundStroke`. * * The manifest (`layers`) and the hit-testable set (`hitOverlays`) are supplied * by the consumer; this adapter knows no domain type. */ // NB: VALUE imports from `ol/*` MUST end in `.js`. `ol` ships ESM with NO package // `exports` map (`type: "module"`), so under Node ESM a bare `"ol/Map"` resolves // to the *directory* and throws ERR_UNSUPPORTED_DIR_IMPORT. tsc does not rewrite // specifiers; bundlers hide this, Node does not. `import type` is erased, so the // type-only `ol/*` imports below need no `.js`. import type { Feature as GeoJSONFeature, FeatureCollection } from "geojson"; import type { FeatureLike } from "ol/Feature"; import type { EventsKey } from "ol/events"; import { getHeight, getWidth } from "ol/extent.js"; import GeoJSON from "ol/format/GeoJSON.js"; import DragPan from "ol/interaction/DragPan.js"; import DoubleClickZoom from "ol/interaction/DoubleClickZoom.js"; import type BaseLayer from "ol/layer/Base"; import VectorLayer from "ol/layer/Vector.js"; import OlMap from "ol/Map.js"; import Overlay from "ol/Overlay.js"; import { unByKey } from "ol/Observable.js"; import { fromLonLat, toLonLat, transformExtent, get as getProjection } from "ol/proj.js"; import type Projection from "ol/proj/Projection"; import { register as registerProj4 } from "ol/proj/proj4.js"; import OSM from "ol/source/OSM.js"; import VectorSource from "ol/source/Vector.js"; import TileLayer from "ol/layer/Tile.js"; import { Circle as CircleStyle, Fill, Icon, Stroke, Style, Text } from "ol/style.js"; import type { StyleLike } from "ol/style/Style"; import View from "ol/View.js"; import type { AdapterOptions, HighlightStyle, Hit, KeyEvent, LatLng, LayerKind, LngLatBounds, MapAdapter, MarkerWidget, PointerEvent, ProjectionSpec, SnapshotOptions, SymbolSprites, ToolbarItem, ToolbarOptions, TooltipStyle, WidgetEdit, } from "./index.js"; import { cursorForHit, defaultCoordFormat } from "./index.js"; import { densifyBboxRing, warnOnce } from "./geo.js"; import { WidgetLayer, snapshotWithWidgets } from "./widget.js"; import { rasterizeWidget, clearSpriteCache, type SpriteResult } from "./sprite.js"; import { num, str, rgba, deg2rad, wrapLabel } from "./coerce.js"; import { boxPadding, textBoxBorderWidth } from "./textbox.js"; import { modifiers } from "./modifiers.js"; import { colorizeSprite, svgToDataUrl } from "./symbols.js"; import { resolveAdapterOptions, type ResolvedAdapterOptions } from "./options.js"; import { populateToolbar, setToolbarActive } from "./toolbar.js"; import { deliverSnapshot, shutterFlash, snapshotToolbarItem } from "./snapshot.js"; import { lockToolbarItem } from "./lock.js"; import { fullscreenToolbarItem } from "./fullscreen.js"; import { bindKeyListener, refocusMap } from "./keyboard.js"; import { applyTooltipStyle } from "./tooltip.js"; /** True when a hit is something the user grabs to drag (any handle/guide carrying * a `role`). Construction guides (no role) and plain fills are not draggable. */ function isDraggableHit(hit: Hit): boolean { return hit.props["role"] != null; } const OL_TOOLBAR_STYLE_ID = "draw-adapter-ol-toolbar-style"; /** OpenLayers styles `.ol-control` buttons blue/translucent by default, so our toolbar * looks like loose buttons with no bar. Give it a solid white bar + plain buttons (like * MapLibre's ctrl-group / the Leaflet bar). Injected once. */ function ensureOLToolbarStyle(): void { if (typeof document === "undefined" || document.getElementById(OL_TOOLBAR_STYLE_ID)) return; const style = document.createElement("style"); style.id = OL_TOOLBAR_STYLE_ID; style.textContent = ".ol-control.draw-adapter-toolbar{background:#fff;border-radius:4px;box-shadow:0 1px 5px rgba(0,0,0,.3);padding:0;overflow:hidden}" + ".ol-control.draw-adapter-toolbar button{width:30px;height:30px;margin:0;padding:0;border:0;border-radius:0;" + "background:#fff;color:#24292f;font-size:inherit;cursor:pointer}" + ".ol-control.draw-adapter-toolbar button:hover{background:#f4f4f4}" + ".ol-control.draw-adapter-toolbar button:disabled{opacity:.28;filter:grayscale(1);cursor:not-allowed}"; document.head.appendChild(style); } /** Minimal structural type for the `proj4` default export — it is an OPTIONAL peer dependency * (only needed for a `{kind:"proj4"}` projection), so it is never statically imported. */ type Proj4 = { defs(name: string, projection: string): void }; let proj4Mod: Proj4 | undefined; /** Lazily load the optional `proj4` peer. Resolves to the callable default export, cached so the * first custom-projection call is async (a microtask) and every later one is synchronous. */ async function loadProj4(): Promise { if (proj4Mod) return proj4Mod; const m = (await import("proj4")) as unknown as { default?: Proj4 } & Proj4; proj4Mod = m.default ?? m; return proj4Mod; } /** Batteries-included host map (headless hosts pass their own `map` instead). */ export function createOpenLayersMap(opts: { container: HTMLElement | string; center: [number, number]; zoom: number }): OlMap { return new OlMap({ target: opts.container, layers: [new TileLayer({ source: new OSM() })], view: new View({ center: fromLonLat(opts.center), zoom: opts.zoom }), }); } /** Overlay a `static` marker-widget sprite hit resolves against — reuses the call-out overlay so the * consumer's existing call-out interaction handles it unchanged (see {@link MarkerWidget.static}). */ const WSPRITE_HIT_OVERLAY = "text-boxes"; const ORIGIN_FRAC: Record = { center: [0.5, 0.5], top: [0.5, 0], bottom: [0.5, 1], left: [0, 0.5], right: [1, 0.5], "top-left": [0, 0], "top-right": [1, 0], "bottom-left": [0, 1], "bottom-right": [1, 1], }; /** The [x,y] fraction (0..1) of the sprite that pins to its geo anchor — an OpenLayers `Icon` anchor. */ function originFraction(o: MarkerWidget["origin"]): [number, number] { if (!o) return [0.5, 0.5]; if (typeof o === "object") return [o.x, o.y]; return ORIGIN_FRAC[o] ?? [0.5, 0.5]; } /** Build an `ol/style/Icon` from a rasterized sprite: the device-px canvas displayed at its CSS WxH * (`scale = 1/dpr`), pinned by `origin`. Screen-fixed at every zoom (an `Icon` doesn't scale w/ view). */ function spriteIcon(res: SpriteResult, o: MarkerWidget["origin"]): Icon { const [ax, ay] = originFraction(o); return new Icon({ img: res.canvas, scale: 1 / res.dpr, anchor: [ax, ay], anchorXUnits: "fraction", anchorYUnits: "fraction" }); } export class OpenLayersAdapter implements MapAdapter { /** OpenLayers composites onto `` layers → snapshot is supported. */ protected readonly snapshotSupported = true; private readonly map: OlMap; private readonly opts: ResolvedAdapterOptions; private readonly kindOf: Map; /** overlay id → manifest z-index (higher = drawn on top), for hit priority. */ private readonly zOf: Map; private readonly sources = new Map(); private readonly layers = new Map(); private readonly layerOverlay = new Map(); private readonly format = new GeoJSON(); private readonly iconCache = new Map(); private sprites: Record = {}; // sprite id → raw SVG (re-tinted per feature) private dragPan: DragPan | undefined; private dblClickZoom: DoubleClickZoom | undefined; private readyPromise: Promise | undefined; private tooltipStyle: TooltipStyle | undefined; private olKeys: EventsKey[] = []; private viewKey: EventsKey | undefined; private domPointerUp: ((e: globalThis.PointerEvent) => void) | undefined; private windowBlur: (() => void) | undefined; private blurListener: (() => void) | undefined; /** Press state captured at `down`, used to emit a `click` immediately on release — OL's own * `singleclick` is ~250 ms delayed and a quick second click becomes a `dblclick`, so deselect * felt like it needed several clicks. */ private pressHit: Hit | undefined; private pressLngLat: LatLng | undefined; private pressX = 0; private pressY = 0; private pressDown = false; private viewportPointerDown: ((e: globalThis.PointerEvent) => void) | undefined; private keyCleanup: (() => void) | undefined; private viewportDblclick: ((e: globalThis.MouseEvent) => void) | undefined; private viewportContext: ((e: globalThis.MouseEvent) => void) | undefined; private toolbarEl: HTMLElement | undefined; private tooltipEl: HTMLElement | undefined; private dragging = false; private locked = false; private panOn = true; private dblOn = true; private widgets: WidgetLayer | undefined; private pointerCb: ((ev: PointerEvent) => void) | undefined; /** Coord formatter, mirrored from {@link setCoordFormat} so sprites format `coord` leaves like cards. */ private coordFmt: (ll: LatLng) => string = defaultCoordFormat; /** Source/layer for `static`-widget sprites (lazy; mapped to {@link WSPRITE_HIT_OVERLAY} for hits). */ private spriteSource: VectorSource | undefined; private spriteLayer: VectorLayer | undefined; /** Monotonic token so a superseded async sprite update never clobbers a newer `setWidgets`. */ private spriteToken = 0; /** Widget ids with a live sprite (for cache eviction on `destroy`). */ private readonly spriteIds = new Set(); /** Raw EPSG:4326 data per overlay, kept so a projection swap can re-read (reproject) it. */ private readonly lastData = new Map(); /** The non-interactive frame layer (see {@link highlightArea}); its last extent + style, so a * projection swap redraws it into the new view. */ private highlightLayer: VectorLayer | undefined; private highlightExtent: LngLatBounds | null = null; private highlightStyleOpts: HighlightStyle | undefined; /** Last {@link viewArea} request, re-applied once an async projection swap settles. */ private lastFit: { extent: LngLatBounds; opts?: { padding?: number; duration?: number } } | undefined; /** True while a `{kind:"proj4"}` view swap is loading proj4 (defers `viewArea` until it lands). */ private projPending = false; constructor(opts: { map: OlMap } & AdapterOptions) { this.map = opts.map; this.opts = resolveAdapterOptions(opts); this.kindOf = new Map(opts.layers.map((l) => [l.id, l.kind])); this.zOf = new Map(opts.layers.map((l, i) => [l.id, i])); } registerSymbols(sprites: SymbolSprites): Promise { for (const [id, svg] of Object.entries(sprites)) { this.sprites[id] = svg; // keep the raw SVG; colour is baked on demand for (const key of [...this.iconCache.keys()]) if (key.startsWith(`${id}|`)) this.iconCache.delete(key); } for (const [id, kind] of this.kindOf) if (kind === "symbol" || kind === "circle") this.layers.get(id)?.changed(); return Promise.resolve(); } ready(): Promise { if (!this.readyPromise) { for (const spec of this.opts.layers) { const source = new VectorSource(); this.sources.set(spec.id, source); const layer = new VectorLayer({ source, style: this.styleFor(spec.kind) }); this.layers.set(spec.id, layer); this.layerOverlay.set(layer, spec.id); this.map.addLayer(layer); } const interactions = this.map.getInteractions().getArray(); this.dragPan = interactions.find((i): i is DragPan => i instanceof DragPan); this.dblClickZoom = interactions.find((i): i is DoubleClickZoom => i instanceof DoubleClickZoom); this.readyPromise = Promise.resolve(); } return this.readyPromise; } /** The view's CURRENT projection — the single source of truth for every lon/lat ↔ map * transform below, so a {@link setProjection} swap reprojects everything consistently. */ private viewProj(): Projection { return this.map.getView().getProjection(); } setOverlay(id: string, data: FeatureCollection): void { this.lastData.set(id, data); // kept so a projection swap can reproject it this.loadInto(id, data); } /** Read `data` (EPSG:4326) into overlay `id`'s source, reprojected to the view's projection. */ private loadInto(id: string, data: FeatureCollection): void { const source = this.sources.get(id); if (!source) return; source.clear(); if (data.features.length) { source.addFeatures(this.format.readFeatures(data, { dataProjection: "EPSG:4326", featureProjection: this.viewProj() })); } } setOverlayVisible(id: string, visible: boolean): void { this.layers.get(id)?.setVisible(visible); } addToolbar(items: ToolbarItem[], options?: ToolbarOptions): HTMLElement { if (this.toolbarEl) return this.toolbarEl; ensureOLToolbarStyle(); const el = document.createElement("div"); el.className = "ol-control draw-adapter-toolbar"; const snap = snapshotToolbarItem(options?.snapshot, { supported: this.snapshotSupported, snapshot: (o) => this.snapshot(o), flash: () => shutterFlash(this.map.getViewport()), }); const full = fullscreenToolbarItem(options?.fullscreen, () => this.getContainer(), () => this.map.updateSize()); const lock = lockToolbarItem(options?.lock, (on) => this.setInteractive(on)); const chrome = [snap, full, lock].filter((x): x is ToolbarItem => x != null); populateToolbar(el, [...items, ...chrome], options, () => refocusMap(this.map.getViewport())); this.map.getTargetElement()?.appendChild(el); this.toolbarEl = el; return el; } setActiveTool(id: string | null): void { if (this.toolbarEl) setToolbarActive(this.toolbarEl, id); } /** Capture the map as PNG, then apply `opts.target` (download/clipboard/none). The * capture promise is handed to `deliverSnapshot` *pending* so a clipboard write fires * synchronously within the click (gesture-safe). */ snapshot(opts?: SnapshotOptions): Promise { return deliverSnapshot(this.capture(opts), opts); } /** * Compose every visible layer canvas onto one target canvas inside a * `rendercomplete` frame (OpenLayers' official "export map" pattern). `scale` * defaults to the device-pixel-ratio (OL already renders at that density); * the target canvas is `getSize() × scale` and each layer's CSS transform is * pre-multiplied by `scale`, so `low` stays at CSS resolution and `medium`/`high` * supersample (best-effort). */ private capture(opts?: SnapshotOptions): Promise { const ratio = (typeof window !== "undefined" && window.devicePixelRatio) || 1; const targetScale = opts?.scale ?? ratio; const size = this.map.getSize(); if (!size) return Promise.reject(new Error("snapshot failed: map has no size")); // Hide the requested overlays (editing chrome) so they aren't composited; restored // after (the compositing into the target canvas is synchronous). const restore = opts?.hideOverlays?.length ? this.hideOverlays(opts.hideOverlays) : undefined; return new Promise((resolve, reject) => { const settle = (run: () => void): void => { try { run(); } finally { restore?.(); } }; this.map.once("rendercomplete", () => settle(() => { try { const out = document.createElement("canvas"); out.width = Math.max(1, Math.round(size[0]! * targetScale)); out.height = Math.max(1, Math.round(size[1]! * targetScale)); const ctx = out.getContext("2d"); if (!ctx) return reject(new Error("snapshot failed")); const viewport = this.map.getViewport(); const canvases = viewport.querySelectorAll(".ol-layer canvas, canvas.ol-layer"); canvases.forEach((canvas) => { if (canvas.width === 0) return; const parent = canvas.parentNode as HTMLElement | null; const opacity = parent?.style.opacity ?? canvas.style.opacity; ctx.globalAlpha = opacity === "" || opacity == null ? 1 : Number(opacity); // The layer canvas (device px) carries a CSS `matrix(...)` mapping it to // CSS px. Pre-multiply by `targetScale` to land in the target's pixels. const m = /^matrix\(([^)]+)\)$/.exec(canvas.style.transform); const t = m ? m[1]!.split(",").map(Number) : [1, 0, 0, 1, 0, 0]; ctx.setTransform( targetScale * t[0]!, targetScale * t[1]!, targetScale * t[2]!, targetScale * t[3]!, targetScale * t[4]!, targetScale * t[5]!, ); ctx.drawImage(canvas, 0, 0); }); ctx.globalAlpha = 1; ctx.setTransform(1, 0, 0, 1, 0, 0); const cards = this.widgets?.snapshotCards() ?? []; snapshotWithWidgets(out, cards, (ll) => this.project(ll), targetScale).then(resolve, reject); } catch (e) { reject(e instanceof Error ? e : new Error("snapshot failed")); } })); this.map.renderSync(); }); } /** Hide the given overlay ids' layers; returns a function that restores their * visibility. Used to drop editing chrome from a snapshot. */ private hideOverlays(overlayIds: string[]): () => void { const hidden: VectorLayer[] = []; for (const id of overlayIds) { const layer = this.layers.get(id); if (layer && layer.getVisible()) { layer.setVisible(false); hidden.push(layer); } } return () => { for (const l of hidden) l.setVisible(true); }; } getCenter(): LatLng { const c = this.map.getView().getCenter(); if (!c) return { lat: 0, lon: 0 }; const [lon, lat] = toLonLat(c, this.viewProj()); return { lat: lat!, lon: lon! }; } getViewSpan(): number { const size = this.map.getSize(); if (!size) return 10; const extent = transformExtent(this.map.getView().calculateExtent(size), this.viewProj(), "EPSG:4326"); return Math.max(getWidth(extent), getHeight(extent)) || 10; } getBounds(): LngLatBounds { const ext = transformExtent(this.map.getView().calculateExtent(this.map.getSize()), this.viewProj(), "EPSG:4326"); return [ext[0]!, ext[1]!, ext[2]!, ext[3]!]; } getZoom(): number { return this.map.getView().getZoom() ?? 0; } getContainer(): HTMLElement { return this.map.getTargetElement() as HTMLElement; } fitBounds(bbox: LngLatBounds, opts?: { padding?: number }): void { const ext = transformExtent([bbox[0], bbox[1], bbox[2], bbox[3]], "EPSG:4326", this.viewProj()); const p = opts?.padding ?? 0; const size = this.map.getSize(); this.map.getView().fit(ext, { padding: [p, p, p, p], ...(size ? { size } : {}) }); } setProjection(projection: ProjectionSpec): void { if (projection === "mercator" || projection === "globe") { if (projection === "globe") warnOnce("draw-adapter (OpenLayers): 'globe' projection is not supported; staying in Web Mercator."); const merc = getProjection("EPSG:3857"); if (merc && this.viewProj().getCode() !== merc.getCode()) this.swapProjection(merc); return; } // { kind: "proj4" } — register the CRS and rebuild the view in it. proj4 already loaded ⇒ // synchronous; first use ⇒ deferred a microtask, then `viewArea`'s last request is re-applied. if (proj4Mod) { this.applyProj4(proj4Mod, projection); return; } this.projPending = true; void loadProj4() .then((p4) => { this.applyProj4(p4, projection); this.projPending = false; if (this.lastFit) this.applyFit(this.lastFit.extent, this.lastFit.opts); }) .catch(() => { this.projPending = false; warnOnce("draw-adapter (OpenLayers): a custom projection needs the optional `proj4` peer dependency, which could not be loaded. Staying in the current projection."); }); } /** Register a proj4 def, make it available to OL, and swap the view onto it. */ private applyProj4(p4: Proj4, spec: { kind: "proj4"; code: string; def: string }): void { p4.defs(spec.code, spec.def); registerProj4(p4 as never); const projection = getProjection(spec.code); if (projection) this.swapProjection(projection); } /** Rebuild the view onto `projection` (keeping the center as lon/lat + zoom), then re-read every * overlay + the highlight so their geometries reproject. */ private swapProjection(projection: Projection): void { const view = this.map.getView(); const center = view.getCenter(); const ll = center ? toLonLat(center, view.getProjection()) : [0, 0]; const zoom = view.getZoom() ?? 2; this.map.setView(new View({ projection, center: fromLonLat([ll[0]!, ll[1]!], projection), zoom })); for (const [id, data] of this.lastData) this.loadInto(id, data); if (this.highlightExtent) this.drawHighlight(this.highlightExtent, this.highlightStyleOpts); } viewArea(extent: LngLatBounds, opts?: { padding?: number; duration?: number }): void { this.lastFit = opts ? { extent, opts } : { extent }; if (this.projPending) return; // view is mid-swap; applyFit runs when setProjection settles this.applyFit(extent, opts); } /** Project the (densified, dateline-aware) area ring into the view projection and fit its bounding * box — so the framing follows the projection's curvature and never zooms out across the dateline. */ private applyFit(extent: LngLatBounds, opts?: { padding?: number; duration?: number }): void { const proj = this.viewProj(); let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (const [lon, lat] of densifyBboxRing(extent, 16)) { const c = fromLonLat([lon, lat], proj); const x = c[0]!, y = c[1]!; if (x < minX) minX = x; if (y < minY) minY = y; if (x > maxX) maxX = x; if (y > maxY) maxY = y; } if (!isFinite(minX)) return; const p = opts?.padding ?? 0; const size = this.map.getSize(); this.map.getView().fit([minX, minY, maxX, maxY], { padding: [p, p, p, p], ...(size ? { size } : {}), ...(opts?.duration != null ? { duration: opts.duration } : {}), }); } highlightArea(extent: LngLatBounds | null, style?: HighlightStyle): void { this.highlightExtent = extent; this.highlightStyleOpts = style; if (!extent) { this.highlightLayer?.getSource()?.clear(); return; } this.drawHighlight(extent, style); } /** (Re)draw the frame polygon (densified, reprojected to the view) into the highlight layer. */ private drawHighlight(extent: LngLatBounds, style?: HighlightStyle): void { const layer = this.ensureHighlightLayer(); const source = layer.getSource(); if (!source) return; source.clear(); const ring = densifyBboxRing(extent, 64); const feature = this.format.readFeature( { type: "Feature", properties: {}, geometry: { type: "Polygon", coordinates: [ring] } }, { dataProjection: "EPSG:4326", featureProjection: this.viewProj() }, ); source.addFeature(feature as never); layer.setStyle(new Style({ stroke: new Stroke({ color: style?.color ?? "#666", width: style?.width ?? 1, lineDash: style?.dash ?? [6, 4] }), ...(style?.fill ? { fill: new Fill({ color: style.fill }) } : {}), })); } /** The frame's own VectorLayer, inserted directly BELOW the first drawing overlay (so it sits * above the basemap, below the overlays). Non-hittable: it is absent from `layerOverlay`. */ private ensureHighlightLayer(): VectorLayer { if (this.highlightLayer) return this.highlightLayer; const layer = new VectorLayer({ source: new VectorSource() }); const layers = this.map.getLayers(); const firstOverlay = this.layers.values().next().value as BaseLayer | undefined; const idx = firstOverlay ? layers.getArray().indexOf(firstOverlay) : layers.getLength(); layers.insertAt(Math.max(0, idx), layer); this.highlightLayer = layer; return layer; } project(p: LatLng): [number, number] | null { const px = this.map.getPixelFromCoordinate(fromLonLat([p.lon, p.lat], this.viewProj())); return px ? [px[0]!, px[1]!] : null; } unproject(px: [number, number]): LatLng | null { const coord = this.map.getCoordinateFromPixel(px); if (!coord) return null; const [lon, lat] = toLonLat(coord, this.viewProj()); return { lat: lat!, lon: lon! }; } onViewChange(cb: () => void): void { if (this.viewKey) unByKey(this.viewKey); // single slot — drop the previous so a re-call never leaks this.viewKey = this.map.on("moveend", cb); } setPanEnabled(enabled: boolean): void { this.panOn = enabled; if (!this.locked) this.dragPan?.setActive(enabled); } setDoubleClickZoom(enabled: boolean): void { this.dblOn = enabled; if (!this.locked) this.dblClickZoom?.setActive(enabled); } setInteractive(enabled: boolean): void { this.locked = !enabled; // Our drawing input is NOT an OL interaction (it's map.on/viewport listeners), so // toggling every interaction freezes navigation without touching the drawing. const interactions = this.map.getInteractions().getArray(); if (this.locked) { for (const i of interactions) i.setActive(false); } else { for (const i of interactions) i.setActive(true); this.dragPan?.setActive(this.panOn); // restore the controller's request this.dblClickZoom?.setActive(this.dblOn); } } setCursor(cursor: string): void { const el = this.map.getTargetElement(); if (el) el.style.cursor = cursor; } setTooltip(text: string | null, at: LatLng, style?: TooltipStyle): void { if (style) this.tooltipStyle = style; if (text == null) { if (this.tooltipEl) this.tooltipEl.style.display = "none"; return; } if (!this.tooltipEl) { this.tooltipEl = document.createElement("div"); this.tooltipEl.className = "draw-adapter-tooltip"; if (this.tooltipStyle) applyTooltipStyle(this.tooltipEl, this.tooltipStyle); this.map.getTargetElement()?.appendChild(this.tooltipEl); } else if (style) { applyTooltipStyle(this.tooltipEl, style); } const px = this.map.getPixelFromCoordinate(fromLonLat([at.lon, at.lat], this.viewProj())); if (!px) return; this.tooltipEl.textContent = text; this.tooltipEl.style.display = "block"; this.tooltipEl.style.left = `${px[0]}px`; this.tooltipEl.style.top = `${px[1]}px`; } onPointer(cb: (ev: PointerEvent) => void): void { this.pointerCb = cb; // also feeds the widget layer's synthetic card events if (this.domPointerUp) return; // `pointerdown` in the CAPTURE phase: run before OpenLayers' own DragPan (the // viewport listener registered before us). When the press lands on a draggable // hit, `stopPropagation()` keeps DragPan from starting a pan — disabling it in // the callback is too late. NB: only stop draggable `down`s; letting plain // clicks through preserves OL's `singleclick` (e.g. "change symbol" on click). this.viewportPointerDown = (e: globalThis.PointerEvent) => { if ((e.target as HTMLElement | null)?.closest?.(".draw-adapter-widget")) return; // card owns it const coord = this.map.getEventCoordinate(e); if (!coord) return; this.dragging = true; const [lon, lat] = toLonLat(coord, this.viewProj()); const hit = this.hitAt(this.map.getEventPixel(e)); this.pressHit = hit; this.pressLngLat = { lat: lat!, lon: lon! }; this.pressX = e.clientX; this.pressY = e.clientY; this.pressDown = true; if (hit && isDraggableHit(hit)) e.stopPropagation(); cb({ type: "down", lngLat: { lat: lat!, lon: lon! }, ...modifiers(e), ...(hit ? { hit } : {}) }); }; // "up" must fire even when pointerup lands off the canvas (no coordinate), so a // drag (and its delete-on-release) always completes. this.domPointerUp = (e: globalThis.PointerEvent): void => { if ((e.target as HTMLElement | null)?.closest?.(".draw-adapter-widget")) { this.pressDown = false; return; } // card's own up const moved = !this.pressDown || Math.abs(e.clientX - this.pressX) > 3 || Math.abs(e.clientY - this.pressY) > 3; this.dragging = false; const upCoord = this.map.getEventCoordinate(e); // real lon/lat when the event has one (#2) const upLL = upCoord ? toLonLat(upCoord, this.viewProj()) : null; cb({ type: "up", lngLat: upLL ? { lat: upLL[1]!, lon: upLL[0]! } : { lat: 0, lon: 0 }, ...modifiers(e) }); // Emit the click NOW (a `down`+`up` at one spot) instead of waiting for OL's debounced // `singleclick` — so a single click selects/deselects instantly, like MapLibre/Leaflet. if (this.pressDown && !moved && this.pressLngLat) { cb({ type: "click", lngLat: this.pressLngLat, ...modifiers(e), ...(this.pressHit ? { hit: this.pressHit } : {}) }); } this.pressDown = false; }; this.map.getViewport().addEventListener("pointerdown", this.viewportPointerDown, true); document.addEventListener("pointerup", this.domPointerUp); if (typeof window !== "undefined") { // Leaving the window mid-press loses the `up`; purge press state so the first click back // (the focusing click) starts clean instead of inheriting a stale drag/hit. this.windowBlur = () => { this.dragging = false; this.pressHit = undefined; this.pressDown = false; }; window.addEventListener("blur", this.windowBlur); } // OL's synthesized "dblclick" map event is SUPPRESSED when our capture-phase pointerdown // calls stopPropagation() on a draggable hit (a handle) to block DragPan — so on a handle // it never fires (no vertex insert). The NATIVE dblclick still fires, so we listen to that // and compute the hit ourselves (parity with MapLibre). this.viewportDblclick = (e: globalThis.MouseEvent): void => { const coord = this.map.getEventCoordinate(e); if (!coord) return; const [lon, lat] = toLonLat(coord, this.viewProj()); const hit = this.hitAt(this.map.getEventPixel(e)); cb({ type: "dblclick", lngLat: { lat: lat!, lon: lon! }, ...modifiers(e), ...(hit ? { hit } : {}) }); }; this.map.getViewport().addEventListener("dblclick", this.viewportDblclick); // Right-click → `contextmenu` (browser menu suppressed). The consumer decides the action. this.viewportContext = (e: globalThis.MouseEvent): void => { e.preventDefault(); const coord = this.map.getEventCoordinate(e); if (!coord) return; const [lon, lat] = toLonLat(coord, this.viewProj()); const hit = this.hitAt(this.map.getEventPixel(e)); cb({ type: "contextmenu", lngLat: { lat: lat!, lon: lon! }, ...modifiers(e), ...(hit ? { hit } : {}) }); }; this.map.getViewport().addEventListener("contextmenu", this.viewportContext); this.olKeys.push( this.map.on("pointermove", (evt) => { const [lon, lat] = toLonLat(evt.coordinate, this.viewProj()); const mods = modifiers(evt.originalEvent as MouseEvent); // Recover a swallowed `up`: a move with NO button held means the press already ended // (e.g. the pointerup was eaten by a window-focusing gesture). Finalise so nothing sticks. if (this.dragging && (evt.originalEvent as MouseEvent).buttons === 0) { this.dragging = false; this.pressHit = undefined; this.pressDown = false; cb({ type: "up", lngLat: { lat: lat!, lon: lon! }, ...mods }); } if (this.dragging) { cb({ type: "move", lngLat: { lat: lat!, lon: lon! }, ...mods }); return; } const hit = this.hitAt(evt.pixel); this.setCursor(cursorForHit(hit)); cb({ type: "move", lngLat: { lat: lat!, lon: lon! }, ...mods, ...(hit ? { hit } : {}) }); }), // NB: "click" is emitted immediately from the pointerup above (not OL's debounced // `singleclick`). "dblclick" stays a native viewport listener — OL's own dblclick map // event is suppressed on draggable hits by our pointerdown stopPropagation. ); } onKey(cb: (ev: KeyEvent) => void): void { if (this.keyCleanup) return; this.keyCleanup = bindKeyListener(this.map.getViewport(), cb); } onBlur(cb: () => void): void { if (this.blurListener || typeof window === "undefined") return; this.blurListener = cb; window.addEventListener("blur", cb); } private widgetLayer(): WidgetLayer { if (!this.widgets) { const map = this.map; this.widgets = new WidgetLayer({ createMount: (anchor) => { const el = document.createElement("div"); const overlay = new Overlay({ element: el, position: fromLonLat([anchor.lon, anchor.lat], this.viewProj()), positioning: "top-left", stopEvent: true, className: "draw-adapter-widget-ov", }); map.addOverlay(overlay); return { el, setAnchor: (a) => overlay.setPosition(fromLonLat([a.lon, a.lat], this.viewProj())), remove: () => map.removeOverlay(overlay), setZIndex: (z) => { if (el.parentElement) el.parentElement.style.zIndex = z > 0 ? String(z) : ""; }, }; }, unprojectClient: (cx, cy) => { const target = map.getTargetElement(); if (!target) return null; const r = target.getBoundingClientRect(); const coord = map.getCoordinateFromPixel([cx - r.left, cy - r.top]); if (!coord) return null; const [lon, lat] = toLonLat(coord, this.viewProj()); return { lat: lat!, lon: lon! }; }, emit: (ev) => this.pointerCb?.(ev), focus: () => refocusMap(this.map.getViewport()), }); } return this.widgets; } setWidgets(widgets: MarkerWidget[]): void { const dom: MarkerWidget[] = []; const sprites: MarkerWidget[] = []; for (const w of widgets) (w.static ? sprites : dom).push(w); this.widgetLayer().setWidgets(dom); this.updateSprites(sprites); } onWidgetEdit(cb: (e: WidgetEdit) => void): void { this.widgetLayer().onWidgetEdit(cb); } onWidgetDelete(cb: (e: { id: string }) => void): void { this.widgetLayer().onWidgetDelete(cb); } onWidgetAction(cb: (e: { id: string; event: string }) => void): void { this.widgetLayer().onWidgetAction(cb); } setCoordFormat(fn: (ll: LatLng) => string): void { this.coordFmt = fn; this.widgetLayer().setCoordFormat(fn); } /** Add the sprite source + vector layer once (lazy). Mapped to {@link WSPRITE_HIT_OVERLAY} so its * features hit-test like canvas call-outs; given a top z so they hit even if the consumer's manifest * has no `text-boxes` layer (else its `z` would be -1 and never win the hit priority). */ private ensureSpriteLayer(): VectorSource { if (!this.spriteSource) { this.spriteSource = new VectorSource(); this.spriteLayer = new VectorLayer({ source: this.spriteSource }); this.layerOverlay.set(this.spriteLayer, WSPRITE_HIT_OVERLAY); if (!this.zOf.has(WSPRITE_HIT_OVERLAY)) this.zOf.set(WSPRITE_HIT_OVERLAY, this.opts.layers.length); this.map.addLayer(this.spriteLayer); } return this.spriteSource; } /** * Rasterize each `static` widget to an `Icon` and push them as point features (props * `{ featureId, labelId }`) into the sprite layer. Async (glyph rasterization) and token-guarded so * a newer call wins. */ private updateSprites(widgets: MarkerWidget[]): void { if (!widgets.length && !this.spriteIds.size && !this.spriteSource) return; // never used → no-op const token = ++this.spriteToken; const run = async (): Promise => { const container = this.map.getTargetElement() ?? undefined; const dpr = (typeof window !== "undefined" && window.devicePixelRatio) || 1; const styled: Array<{ w: MarkerWidget; res: SpriteResult }> = []; for (const w of widgets) { const res = await rasterizeWidget(w, { dpr, coordFmt: this.coordFmt, container }); if (token !== this.spriteToken) return; // superseded mid-flight if (res) styled.push({ w, res }); } if (token !== this.spriteToken) return; const source = this.ensureSpriteLayer(); source.clear(); const seen = new Set(); if (styled.length) { const fc: FeatureCollection = { type: "FeatureCollection", features: styled.map(({ w }): GeoJSONFeature => ({ type: "Feature", geometry: { type: "Point", coordinates: [w.anchor.lon, w.anchor.lat] }, properties: { featureId: w.id, labelId: w.labelId ?? "l" }, })), }; const feats = this.format.readFeatures(fc, { dataProjection: "EPSG:4326", featureProjection: this.viewProj() }); for (let i = 0; i < feats.length; i++) { const { w, res } = styled[i]!; feats[i]!.setStyle(new Style({ image: spriteIcon(res, w.origin) })); seen.add(w.id); } source.addFeatures(feats); } for (const id of Array.from(this.spriteIds)) if (!seen.has(id)) { this.spriteIds.delete(id); clearSpriteCache(id); } for (const id of seen) this.spriteIds.add(id); }; void run().catch(() => { /* a failed rasterization leaves the prior sprites in place */ }); } destroy(): void { this.layerOverlay.forEach((_, layer) => this.map.removeLayer(layer as BaseLayer)); // incl. the sprite layer this.layerOverlay.clear(); this.layers.clear(); this.sources.clear(); this.iconCache.clear(); this.spriteSource = undefined; this.spriteLayer = undefined; for (const id of this.spriteIds) clearSpriteCache(id); this.spriteIds.clear(); if (this.highlightLayer) { this.map.removeLayer(this.highlightLayer); this.highlightLayer = undefined; } this.highlightExtent = null; this.highlightStyleOpts = undefined; this.lastData.clear(); this.lastFit = undefined; this.projPending = false; unByKey(this.olKeys); this.olKeys = []; if (this.viewKey) { unByKey(this.viewKey); this.viewKey = undefined; } if (this.viewportPointerDown) { this.map.getViewport().removeEventListener("pointerdown", this.viewportPointerDown, true); this.viewportPointerDown = undefined; } if (this.viewportContext) { this.map.getViewport().removeEventListener("contextmenu", this.viewportContext); this.viewportContext = undefined; } if (this.viewportDblclick) { this.map.getViewport().removeEventListener("dblclick", this.viewportDblclick); this.viewportDblclick = undefined; } if (this.domPointerUp) { document.removeEventListener("pointerup", this.domPointerUp); this.domPointerUp = undefined; } if (this.windowBlur && typeof window !== "undefined") { window.removeEventListener("blur", this.windowBlur); this.windowBlur = undefined; } if (this.blurListener && typeof window !== "undefined") { window.removeEventListener("blur", this.blurListener); this.blurListener = undefined; } this.pressHit = undefined; this.keyCleanup?.(); this.keyCleanup = undefined; this.toolbarEl?.remove(); this.toolbarEl = undefined; this.tooltipEl?.remove(); this.tooltipEl = undefined; this.widgets?.destroy(); this.widgets = undefined; this.pointerCb = undefined; this.readyPromise = undefined; if (this.locked) for (const i of this.map.getInteractions().getArray()) i.setActive(true); this.locked = false; this.panOn = this.dblOn = true; this.dragPan?.setActive(true); this.dblClickZoom?.setActive(true); // re-enable in case we were torn down mid-draw this.setCursor(""); } private hitAt(pixel: number[]): Hit | undefined { const hittable = this.opts.hitOverlays; // `forEachFeatureAtPixel` with a `hitTolerance` resolves the tolerance ring by // DISTANCE, so a nearby lower layer can be reported before a handle on top. For // parity with MapLibre (top-of-stack wins), collect every candidate and keep the // one whose overlay sits highest in the manifest (largest z-index). let best: Hit | undefined; let bestZ = -1; this.map.forEachFeatureAtPixel( pixel, (feature: FeatureLike, layer: unknown) => { const overlay = this.layerOverlay.get(layer); if (!overlay || !(hittable?.has(overlay) ?? true)) return false; const z = this.zOf.get(overlay) ?? -1; if (z > bestZ) { const props = { ...feature.getProperties() }; delete props["geometry"]; best = { overlay, props }; bestZ = z; } return false; // keep scanning all candidates at this pixel }, { hitTolerance: 5 }, ); return best; } private icon(spriteId: string, size: number, color: string, rotation: number): Icon | undefined { const svg = this.sprites[spriteId]; if (!svg) return undefined; const key = `${spriteId}|${color}|${size}|${rotation}`; let icon = this.iconCache.get(key); if (!icon) { icon = new Icon({ src: svgToDataUrl(colorizeSprite(svg, color)), scale: size, rotation: deg2rad(rotation) }); this.iconCache.set(key, icon); } return icon; } private dataIcon(src: string, size: number, rotation: number): Icon { const key = `data:${src}|${size}|${rotation}`; let icon = this.iconCache.get(key); if (!icon) { icon = new Icon({ src, scale: size, rotation: deg2rad(rotation) }); this.iconCache.set(key, icon); } return icon; } private styleFor(kind: LayerKind): StyleLike { const def = this.opts.defaultSymbolColor; switch (kind) { case "fill": return (f: FeatureLike): Style => { const fill = new Fill({ color: rgba(str(f.get("fillColor"), "#888"), num(f.get("fillOpacity"), 0.2)) }); const stroke = f.get("stroke") ? new Stroke({ color: rgba(str(f.get("stroke")), num(f.get("strokeOpacity"), 1)), width: num(f.get("strokeWidth"), 1) }) : undefined; return new Style(stroke ? { fill, stroke } : { fill }); }; case "line": return (f: FeatureLike): Style => { const stroke = str(f.get("stroke"), "#333"); const width = num(f.get("strokeWidth"), 2); const dash = f.get("dash") as number[] | undefined; const color = rgba(stroke, num(f.get("strokeOpacity"), 1)); const st = new Stroke({ color, width, ...(dash ? { lineDash: dash } : {}), lineCap: dash ? "butt" : "round", lineJoin: "round" }); // Filled polygons (e.g. wind-barb saw teeth) living in a line source. if (f.getGeometry?.()?.getType() === "Polygon") { return new Style({ stroke: st, fill: new Fill({ color: str(f.get("fillColor")) || stroke }) }); } return new Style({ stroke: st }); }; case "symbol": return (f: FeatureLike): Style => { const icon = this.icon(str(f.get("symbol")), num(f.get("size"), 1), str(f.get("symbolColor")) || def, num(f.get("rotation"), 0)); return icon ? new Style({ image: icon }) : new Style({}); }; case "text": return (f: FeatureLike): Style => { const size = num(f.get("textSize"), 13); const bg = str(f.get("textBackground")); const border = str(f.get("textBorder")); const box = bg || border; // box drawn only when a fill and/or border is set const [pv, ph] = boxPadding(f.get("textBoxSize")); // NB: OpenLayers' native text background is a plain rectangle — `textBoxRadius` // has no effect here (rounded boxes work on MapLibre/Leaflet only). return new Style({ text: new Text({ text: wrapLabel(str(f.get("text")), num(f.get("maxWidth"), 0), size), font: `${size}px sans-serif`, rotation: deg2rad(num(f.get("rotation"), 0)), // the box rotates with the text rotateWithView: false, fill: new Fill({ color: str(f.get("textColor"), "#111") }), stroke: new Stroke({ color: str(f.get("textHalo"), "#fff"), width: 3 }), ...(box ? { padding: [pv, ph, pv, ph] as [number, number, number, number] } : {}), ...(bg ? { backgroundFill: new Fill({ color: bg }) } : {}), ...(border ? { backgroundStroke: new Stroke({ color: border, width: textBoxBorderWidth(f.get("textBorderWidth")) }) } : {}), }), }); }; case "circle": return (f: FeatureLike): Style | Style[] => { const dot = new Style({ image: new CircleStyle({ radius: num(f.get("radius"), 5), fill: new Fill({ color: str(f.get("fill"), "#ffffff") }), stroke: new Stroke({ color: str(f.get("stroke"), "#58a6ff"), width: num(f.get("strokeWidth"), 2) }), }), }); const rot = num(f.get("iconRotate"), num(f.get("rotation"), 0)); const iconUri = str(f.get("icon")); if (iconUri) return [dot, new Style({ image: this.dataIcon(iconUri, num(f.get("size"), 1), rot) })]; const sprite = str(f.get("symbol")); if (sprite) { const icon = this.icon(sprite, num(f.get("size"), 1), str(f.get("symbolColor")) || def, rot); if (icon) return [dot, new Style({ image: icon })]; } return dot; }; } } }