/**
* **Read-only sprite rasterizer** — engine-agnostic. Turns a {@link MarkerWidget} whose
* `static` flag is set into a bitmap that the engine adapters place as a **native icon**
* (MapLibre `addImage`, OpenLayers `Icon`, Leaflet ``), so a non-selected cartouche
* gets the rich `WidgetBox` layout without N live DOM cards to reposition each frame.
*
* Strategy: **measure in the DOM, paint on a canvas.** We build the box-layout tree as a
* real (off-screen) DOM subtree — so the browser's own flex/text layout positions every
* node (one layout logic, shared with the live card) — then read each node's measured
* geometry back and **repaint** it onto a 2D canvas (`fillText` / rounded-rect frames /
* `drawImage` for glyph SVGs). No `foreignObject` is involved, so the canvas stays
* origin-clean and is readable as `ImageData` / `toDataURL` / a WebGL texture on **every**
* browser (incl. Safari/WebKit, where a `foreignObject` render would taint it).
*
* The DOM subtree is measured **inside the engine's own container** (off-screen) so it
* inherits the exact same font/line-height cascade as a real mounted card → pixel parity.
*
* The result is cached per `id` and only re-rasterized when the layout hash or the
* device-pixel-ratio changes — never on pan/zoom.
*/
import type { LatLng, MarkerWidget, WidgetCoord, WidgetGlyph, WidgetNode, WidgetText } from "./index.js";
import { boxBorderWidth, boxPadding, boxRadius } from "./textbox.js";
import { applyBoxFrame, resolveBoxShape, boxShapeLayout, type ShapeLayout } from "./widget.js";
import { colorizeSprite, svgToDataUrl } from "./symbols.js";
import { defaultCoordFormat } from "./coerce.js";
/** Rendered size of a sprite, in **CSS px** (for placement / anchoring / collision). */
export interface WidgetSize {
width: number;
height: number;
}
/** Options shared by {@link measureWidget} / {@link rasterizeWidget}. */
export interface SpriteOptions {
/** Device pixels per CSS px the bitmap is rendered at. Default `window.devicePixelRatio` (≥1). */
dpr?: number;
/** Formatter for `coord` leaves (mirrors {@link MapAdapter.setCoordFormat}). Default decimal lat/lon. */
coordFmt?: (ll: LatLng) => string;
/** Element to measure the off-screen tree inside, so it inherits the same CSS cascade (font,
* line-height) as a real card. Pass the engine map container; defaults to `document.body`. */
container?: HTMLElement;
}
/** A rasterized sprite: a device-pixel canvas plus its CSS-px size and the dpr it was drawn at. */
export interface SpriteResult {
/** Canvas at device resolution (`width = round(cssWidth × dpr)`); origin-clean, so it can be read
* back (`getContext("2d").getImageData` / `toDataURL`) or uploaded as a texture on any browser. */
canvas: HTMLCanvasElement;
/** CSS-px width (icon display size). */
width: number;
/** CSS-px height. */
height: number;
/** The device-pixel-ratio this canvas was rendered at. */
dpr: number;
}
interface CacheEntry {
hash: string;
size: WidgetSize;
sprite?: SpriteResult;
}
/** Per-`id` cache: size + (lazily) the rasterized bitmap. Keyed by the widget id so re-rasters only
* happen on a content/dpr change (req. "re-raster only on change", never per frame/pan/zoom). */
const cache = new Map();
/** Drop cached sprite(s). Pass an `id` to evict one, or omit to clear all (engine `destroy`). */
export function clearSpriteCache(id?: string): void {
if (id == null) cache.clear();
else cache.delete(id);
}
function currentDpr(opt?: number): number {
if (opt && opt > 0) return opt;
return (typeof window !== "undefined" && window.devicePixelRatio) || 1;
}
// ── content hashing (re-raster only on change) ────────────────────────────────
/** True if the subtree contains a live `coord` leaf (its text depends on the anchor). */
function hasCoord(node: WidgetNode): boolean {
if (!("kind" in node)) return node.items.some(hasCoord);
return node.kind === "coord";
}
/** Stable hash of everything that affects the rasterized pixels. The `child` tree + card frame +
* font are JSON-stable; a `coord` leaf additionally folds in the formatted anchor (so moving the
* underlying point re-rasters, while a pan/zoom — which never changes the anchor — does not). */
function widgetHash(w: MarkerWidget, coordFmt: (ll: LatLng) => string): string {
const frame = {
child: w.child,
bg: w.bg,
border: w.border,
borderWidth: w.borderWidth,
radius: w.radius,
padding: w.padding,
boxShape: w.boxShape,
font: w.font,
};
let h = JSON.stringify(frame);
if (hasCoord(w.child)) h += "|coord:" + coordFmt(w.anchor);
return h;
}
// ── building the static DOM (the read-only form of the box tree) ──────────────
/** Apply the card-level frame to the sprite root — mirrors `Card.update`'s root styling so a
* `static` widget lays out identically to its live DOM card (same bg/border/radius/padding/font).
* This draws the plain **rect** frame; a non-rect `boxShape` (pentagon / custom polygon) is handled
* in {@link rasterizeWidget} (via {@link shapedLayout} + {@link paintShapeFrame}), which strips this
* rect frame and paints the contour instead — see {@link Card.applyShape} for the live-card twin. */
function applyCardFrame(s: CSSStyleDeclaration, w: MarkerWidget): void {
const framed = !!(w.bg || w.border);
s.position = "relative";
s.display = "inline-block";
s.boxSizing = "border-box";
s.whiteSpace = "nowrap";
s.background = w.bg ?? "transparent";
s.border = w.border ? `${boxBorderWidth(w.borderWidth)}px solid ${w.border}` : "";
s.borderRadius = `${boxRadius(w.radius)}px`;
if (framed || w.padding != null) {
const [pv, ph] = boxPadding(w.padding);
s.padding = `${pv}px ${ph}px`;
} else {
s.padding = "0";
}
s.color = w.font?.color ?? "";
s.fontSize = w.font?.size != null ? `${w.font.size}px` : "";
s.fontFamily = w.font?.family ?? "";
s.lineHeight = w.font?.lineHeight != null ? String(w.font.lineHeight) : "1.2";
}
/** Replicate `setGlyph`: inject the inline SVG and force the inner node to fill the glyph box. */
function setGlyphHtml(el: HTMLElement, svg: string): void {
el.innerHTML = svg;
const inner = el.firstElementChild as HTMLElement | null;
if (inner) { inner.style.width = "100%"; inner.style.height = "100%"; inner.style.display = "block"; }
}
/** The label text a `"picker"` shows for its current value (the option's `label`, else its value). */
function pickerText(node: WidgetText): string {
const sel = (node.options ?? []).find((o) => (typeof o === "string" ? o : o.value) === node.value);
if (sel == null) return node.value;
return typeof sel === "string" ? sel : (sel.label ?? sel.value);
}
/**
* Build the **read-only** DOM form of one node — same layout CSS as the live card (so it measures
* identically), but every interactive control is flattened to a static span:
* - editable `input` → a span showing its value,
* - `"picker"` → a span showing the current option's label (+ its glyph if any),
* - `gauge`/`dial` → omitted (a read-only sprite has no editing controls; see {@link MarkerWidget.static}).
*/
function buildNode(node: WidgetNode, anchor: LatLng, coordFmt: (ll: LatLng) => string): HTMLElement | null {
// WidgetBox (no `kind`)
if (!("kind" in node)) {
const el = document.createElement("div");
const s = el.style;
s.display = "flex";
s.flexDirection = node.dir === "v" ? "column" : "row";
s.alignItems = node.align === "start" ? "flex-start" : node.align === "end" ? "flex-end" : "center";
s.gap = `${node.gap ?? 0}px`;
if (node.color != null) s.color = node.color;
if (node.size != null) s.fontSize = `${node.size}px`;
applyBoxFrame(s, node);
for (const item of node.items) {
const child = buildNode(item, anchor, coordFmt);
if (child) el.appendChild(child);
}
return el;
}
if (node.kind === "glyph") {
const g = node as WidgetGlyph;
const el = document.createElement("span");
el.style.display = "inline-flex";
setGlyphHtml(el, g.svg);
const px = g.size != null ? `${g.size}px` : "";
el.style.width = px;
el.style.height = px;
if (g.color != null) el.style.color = g.color;
return el;
}
if (node.kind === "coord") {
const c = node as WidgetCoord;
const el = document.createElement("span");
if (c.color != null) el.style.color = c.color;
if (c.size != null) el.style.fontSize = `${c.size}px`;
el.textContent = coordFmt(anchor);
return el;
}
// gauge / dial — editing controls; a read-only sprite shows none.
if (node.kind === "gauge" || node.kind === "dial") return null;
// text (static label, flattened input, or flattened picker)
const t = node as WidgetText;
const el = document.createElement("span");
const s = el.style;
s.whiteSpace = "pre-line";
s.textAlign = "center";
if (t.uppercase) s.textTransform = "uppercase";
if (t.color != null) s.color = t.color;
if (t.size != null) s.fontSize = `${t.size}px`;
el.textContent = t.control === "picker" ? pickerText(t) : t.value;
return el;
}
/** Build the full sprite root for `w` (card frame + read-only box tree). */
function buildStaticTree(w: MarkerWidget, coordFmt: (ll: LatLng) => string): HTMLElement {
const root = document.createElement("div");
applyCardFrame(root.style, w);
const content = document.createElement("div");
content.style.display = "inline-block";
const child = buildNode(w.child, w.anchor, coordFmt);
if (child) content.appendChild(child);
root.appendChild(content);
return root;
}
/** Mount `root` off-screen inside `container` so it lays out with the same CSS cascade as a card. */
function mountOffscreen(root: HTMLElement, container: HTMLElement): void {
root.style.position = "absolute";
root.style.left = "-99999px";
root.style.top = "0";
root.style.transform = "none";
root.style.pointerEvents = "none";
container.appendChild(root);
}
// ── painting the measured tree onto a canvas ──────────────────────────────────
/** A loaded glyph image keyed by its colorized SVG markup (deduplicated across identical glyphs). */
type GlyphImages = Map;
/** The colorized SVG markup for a glyph element (its inline `