@orbat-mapper/tactical-draw 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { DEFAULT_HIGHLIGHT_WIDTH, DEFAULT_LABEL_HEIGHT_CSS_PIXELS, DEFAULT_SYMBOL_COLOR, FILL_PATTERN_DEFINITIONS, LABEL_FADE_END_RATIO, NON_SOLID_FILL_PATTERNS, applyBoxTransformOptions, canDeleteControlMeasureVertex, canonicalTextAmplifierKey, cloneControlMeasure, controlMeasureIdFromFeature, dragControlMeasureOptionHandle, foldsBoxTransformOptions, freezeOrientationOptions, getControlMeasureMetadata, getControlMeasureModifierDrag, getControlMeasureOptionHandles, getControlMeasurePartOf, getControlMeasureSegments, getDefaultOptions, keepControlMeasureDrawnSize, labelSizeBandHideThreshold, normalizeTextAmplifiers, remapVertexAlignedOptions, renderControlMeasure, resetControlMeasureOptionHandle, resolveAmplifierPlacement, resolveSizePair, resolveStyleHints, resolveSymbolColor, roundToFixed, switchSizePairUnit } from "@orbat-mapper/control-measures";
1
+ import { DEFAULT_HIGHLIGHT_WIDTH, DEFAULT_LABEL_HEIGHT_CSS_PIXELS, DEFAULT_SYMBOL_COLOR, FILL_PATTERN_DEFINITIONS, LABEL_FADE_END_RATIO, NON_SOLID_FILL_PATTERNS, applyBoxTransformOptions, canDeleteControlMeasureVertex, canonicalTextAmplifierKey, cloneControlMeasure, controlMeasureIdFromFeature, dragControlMeasureOptionHandle, foldsBoxTransformOptions, freezeOrientationOptions, getControlMeasureMetadata, getControlMeasureModifierDrag, getControlMeasureOptionHandles, getControlMeasurePartOf, getControlMeasureSegments, getDefaultOptions, keepControlMeasureDrawnSize, labelSizeBandHideThreshold, labelTextOffsetEms, normalizeTextAmplifiers, remapVertexAlignedOptions, renderControlMeasure, resetControlMeasureOptionHandle, resolveAmplifierPlacement, resolveSizePair, resolveStyleHints, resolveSymbolColor, roundToFixed, switchSizePairUnit } from "@orbat-mapper/control-measures";
2
2
  function pickPointerType(originalEvent) {
3
3
  if (typeof PointerEvent !== "undefined" && originalEvent instanceof PointerEvent) {
4
4
  if (originalEvent.pointerType === "touch") return "touch";
@@ -1716,6 +1716,32 @@ function pickBoxHandle(box, pixel, tolerance) {
1716
1716
  if (inside) return { kind: "body" };
1717
1717
  return null;
1718
1718
  }
1719
+ /** The left and right edge midpoints of `box`, in screen pixels: `[left, right]`. */
1720
+ function widthHandlePixels(box) {
1721
+ const { center, halfWidth, angle } = box;
1722
+ const edge = (x) => {
1723
+ const [rx, ry] = rotate(x, 0, angle);
1724
+ return [center[0] + rx, center[1] + ry];
1725
+ };
1726
+ return [edge(-halfWidth), edge(halfWidth)];
1727
+ }
1728
+ /**
1729
+ * Pick the box like {@link pickBoxHandle}, with the width handles checked after
1730
+ * the corners and the rotate grip and before body containment. Inside the box a
1731
+ * width handle reaches no further than a quarter of the box width, so a narrow
1732
+ * box keeps its middle for the body.
1733
+ */
1734
+ function pickWidthBoxHandle(box, pixel, tolerance) {
1735
+ const hit = pickBoxHandle(box, pixel, tolerance);
1736
+ if (hit && hit.kind !== "body") return hit;
1737
+ const reach = hit ? Math.min(tolerance, box.halfWidth / 2) : tolerance;
1738
+ const edges = widthHandlePixels(box);
1739
+ for (let i = 0; i < edges.length; i++) if (pixelDistance$1(edges[i], pixel) <= reach) return {
1740
+ kind: "width",
1741
+ index: i
1742
+ };
1743
+ return hit;
1744
+ }
1719
1745
  //#endregion
1720
1746
  //#region src/point-symbol-offset.ts
1721
1747
  const EPSILON = 1e-7;
@@ -1978,6 +2004,27 @@ function constrainRotation(angle) {
1978
2004
  }
1979
2005
  //#endregion
1980
2006
  //#region src/marker.ts
2007
+ /**
2008
+ * One `MarkerCapability` from several, such as a badge catalog and the host's
2009
+ * own icons: each marker gets the icon of the first capability that recognises
2010
+ * its symbol id. `generation` is the sum of the parts' generations, so it still
2011
+ * increases when any part bumps its own.
2012
+ */
2013
+ function composeMarkerCapabilities(...capabilities) {
2014
+ return {
2015
+ render(marker) {
2016
+ for (const capability of capabilities) {
2017
+ const icon = capability.render(marker);
2018
+ if (icon) return icon;
2019
+ }
2020
+ },
2021
+ get generation() {
2022
+ let total;
2023
+ for (const capability of capabilities) if (capability.generation !== void 0) total = (total ?? 0) + capability.generation;
2024
+ return total;
2025
+ }
2026
+ };
2027
+ }
1981
2028
  function isMarker(graphic) {
1982
2029
  return typeof graphic === "object" && graphic !== null && "kind" in graphic && graphic.kind === "marker";
1983
2030
  }
@@ -2007,9 +2054,108 @@ function normalizeMarker(marker) {
2007
2054
  return next;
2008
2055
  }
2009
2056
  //#endregion
2057
+ //#region src/note-graphic.ts
2058
+ /**
2059
+ * The Note graphic kind (ADR-0066): a framed box of Markdown content pinned to
2060
+ * the ground at its centre. TacticalDraw never lays Notes out itself, and treats
2061
+ * `content` as an opaque string; a host-supplied {@link NoteCapability} (backed by
2062
+ * `@orbat-mapper/tactical-notes`) turns a Note into a note raster.
2063
+ *
2064
+ * The frame types below mirror `@orbat-mapper/tactical-notes`' model so a
2065
+ * `NoteGraphic` is structurally assignable to its `NoteModel`, without a
2066
+ * package dependency in either direction.
2067
+ */
2068
+ /** Notes are between 2 and 60 em wide. */
2069
+ const NOTE_MIN_WIDTH = 2;
2070
+ const NOTE_MAX_WIDTH = 60;
2071
+ /** Longest side of a note raster requested for the interactive map (ADR-0069). */
2072
+ const NOTE_MAX_RASTER_PIXELS = 2048;
2073
+ function isNoteGraphic(graphic) {
2074
+ return typeof graphic === "object" && graphic !== null && "kind" in graphic && graphic.kind === "note";
2075
+ }
2076
+ function cloneNoteGraphic(note) {
2077
+ return structuredClone(note);
2078
+ }
2079
+ function normalizeNoteGraphic(note) {
2080
+ validateNoteGraphic(note);
2081
+ const next = cloneNoteGraphic(note);
2082
+ next.rotation = normalizeRotation(next.rotation);
2083
+ if (next.style?.opacity !== void 0) next.style.opacity = noteOpacity(next);
2084
+ return next;
2085
+ }
2086
+ function noteOpacity(note) {
2087
+ const opacity = note.style?.opacity ?? 1;
2088
+ if (!Number.isFinite(opacity)) throw new TypeError("NoteGraphic.style.opacity must be finite");
2089
+ return Math.max(0, Math.min(1, opacity));
2090
+ }
2091
+ /** Throws a `TypeError` naming the first malformed field. */
2092
+ function validateNoteGraphic(note) {
2093
+ if (!note.id) throw new TypeError("NoteGraphic.id must not be empty");
2094
+ if (note.schemaVersion !== 1) throw new TypeError("NoteGraphic.schemaVersion must be 1");
2095
+ if (!isFinitePosition(note.position)) throw new TypeError("NoteGraphic.position must be a finite geographic position");
2096
+ if (!Number.isFinite(note.rotation)) throw new TypeError("NoteGraphic.rotation must be finite");
2097
+ if (!isRecord(note.emSize) || !(Number.isFinite(note.emSize.value) && note.emSize.value > 0)) throw new TypeError("NoteGraphic.emSize.value must be a positive finite number");
2098
+ if (note.emSize.unit !== "meters") throw new TypeError("NoteGraphic.emSize.unit must be \"meters\"");
2099
+ if (!Number.isFinite(note.width) || note.width < 2 || note.width > 60) throw new TypeError(`NoteGraphic.width must be between 2 and 60 em`);
2100
+ if (!isRecord(note.frame) || typeof note.frame.preset !== "string" || !note.frame.preset) throw new TypeError("NoteGraphic.frame.preset must be a non-empty string");
2101
+ if (note.frame.tokens !== void 0) validateFrameTokens(note.frame.tokens);
2102
+ if (typeof note.content !== "string") throw new TypeError("NoteGraphic.content must be a string");
2103
+ noteOpacity(note);
2104
+ }
2105
+ const NOTE_ALIGNS = [
2106
+ "start",
2107
+ "center",
2108
+ "end"
2109
+ ];
2110
+ function validateFrameTokens(tokens) {
2111
+ const path = "NoteGraphic.frame.tokens";
2112
+ if (!isRecord(tokens)) throw new TypeError(`${path} must be an object`);
2113
+ for (const key of [
2114
+ "background",
2115
+ "accent",
2116
+ "accentText",
2117
+ "textColor"
2118
+ ]) optionalString(tokens, key, path);
2119
+ for (const key of [
2120
+ "padding",
2121
+ "cornerRadius",
2122
+ "blockSpacing",
2123
+ "lineHeight",
2124
+ "headerBandPadding",
2125
+ "headingScale",
2126
+ "headingLetterSpacing"
2127
+ ]) {
2128
+ const value = tokens[key];
2129
+ if (value !== void 0 && !(typeof value === "number" && Number.isFinite(value) && value >= 0)) throw new TypeError(`${path}.${key} must be a non-negative finite number`);
2130
+ }
2131
+ const band = tokens.headerBand;
2132
+ if (band !== void 0 && band !== null && !(typeof band === "number" && Number.isFinite(band) && band >= 0)) throw new TypeError(`${path}.headerBand must be null or a non-negative finite number`);
2133
+ for (const key of ["headingAlign", "bodyAlign"]) if (tokens[key] !== void 0 && !NOTE_ALIGNS.includes(tokens[key])) throw new TypeError(`${path}.${key} must be "start", "center" or "end"`);
2134
+ for (const key of ["headingBold", "headingSmallCaps"]) if (tokens[key] !== void 0 && typeof tokens[key] !== "boolean") throw new TypeError(`${path}.${key} must be a boolean`);
2135
+ optionalStroke(tokens, "border", path);
2136
+ if (tokens.fonts !== void 0) {
2137
+ if (!isRecord(tokens.fonts)) throw new TypeError(`${path}.fonts must be an object`);
2138
+ for (const role of ["heading", "body"]) optionalString(tokens.fonts, role, `${path}.fonts`);
2139
+ }
2140
+ }
2141
+ function optionalString(record, key, path) {
2142
+ if (record[key] !== void 0 && typeof record[key] !== "string") throw new TypeError(`${path}.${key} must be a string`);
2143
+ }
2144
+ function optionalStroke(record, key, path) {
2145
+ const stroke = record[key];
2146
+ if (stroke === void 0 || stroke === null) return;
2147
+ if (!isRecord(stroke) || typeof stroke.color !== "string" || !(typeof stroke.width === "number" && Number.isFinite(stroke.width) && stroke.width >= 0) || !(stroke.style === void 0 || stroke.style === "solid" || stroke.style === "double")) throw new TypeError(`${path}.${key} must be null or { color, width, style? }`);
2148
+ }
2149
+ function isFinitePosition(value) {
2150
+ return Array.isArray(value) && value.length >= 2 && Number.isFinite(value[0]) && Number.isFinite(value[1]);
2151
+ }
2152
+ function isRecord(value) {
2153
+ return typeof value === "object" && value !== null;
2154
+ }
2155
+ //#endregion
2010
2156
  //#region src/graphic.ts
2011
2157
  function isAnchoredGraphic(graphic) {
2012
- return isPointSymbol(graphic) || isImageGraphic(graphic) || isMarker(graphic);
2158
+ return isPointSymbol(graphic) || isImageGraphic(graphic) || isMarker(graphic) || isNoteGraphic(graphic);
2013
2159
  }
2014
2160
  function isPinnableGraphic(graphic) {
2015
2161
  return isPointSymbol(graphic) || isMarker(graphic);
@@ -3768,6 +3914,7 @@ function handleFeatureId(prefix, kind, index) {
3768
3914
  case "scale": return `${prefix}:handle-scale:${index}`;
3769
3915
  case "rotate": return `${prefix}:handle-rotate`;
3770
3916
  case "snap": return `${prefix}:handle-snap:${index}`;
3917
+ case "width": return `${prefix}:handle-width:${index}`;
3771
3918
  }
3772
3919
  }
3773
3920
  function handleStyleFor(kind, interactionStyle, unset = false, active = false) {
@@ -3781,6 +3928,7 @@ function handleStyleFor(kind, interactionStyle, unset = false, active = false) {
3781
3928
  case "scale": return interactionStyle?.scaleHandle;
3782
3929
  case "rotate": return interactionStyle?.rotateHandle;
3783
3930
  case "snap": return interactionStyle?.snapTargetHandle;
3931
+ case "width": return interactionStyle?.widthHandle;
3784
3932
  }
3785
3933
  }
3786
3934
  /**
@@ -4549,6 +4697,23 @@ function createSessionHistory(options) {
4549
4697
  * / GeoJSON features lives in one place instead of two copies drifting apart.
4550
4698
  * See ADR-0017.
4551
4699
  */
4700
+ /**
4701
+ * The edit modes of a kind edited only through its box (Image, Note): `transform`
4702
+ * and `delete`, where `delete` wins.
4703
+ */
4704
+ function normaliseBoxEditModes(kind, input) {
4705
+ const modes = input ?? ["transform"];
4706
+ for (const mode of modes) if (mode !== "transform" && mode !== "delete") throw new TypeError(`${kind} editing does not support mode "${mode}"`);
4707
+ return modes.includes("delete") ? ["delete"] : [...new Set(modes)];
4708
+ }
4709
+ /** A footprint as an edit box: never collapsed, grown by the interaction style's padding. */
4710
+ function paddedEditBox(box, padding = 0) {
4711
+ return {
4712
+ ...box,
4713
+ halfWidth: Math.max(1, box.halfWidth) + padding,
4714
+ halfHeight: Math.max(1, box.halfHeight) + padding
4715
+ };
4716
+ }
4552
4717
  /** Walk a GeoJSON `Geometry`'s coordinate arrays, pushing every `Position` onto `out`. */
4553
4718
  function collectFeaturePositions(geometry, out) {
4554
4719
  switch (geometry.type) {
@@ -4677,14 +4842,15 @@ function normalizeAngle(angle) {
4677
4842
  * half the fitted width along the label's local +x for `"start"` (text
4678
4843
  * grows away from the anchor) or local −x for `"end"` (text grows back
4679
4844
  * toward the anchor) — `rotate()` (`transform-box.ts`) already uses the
4680
- * screen (y-down) convention this offset needs.
4845
+ * screen (y-down) convention this offset needs. The label's screen-space
4846
+ * `textOffsetEms` further moves it by that many `h` in the same local frame.
4681
4847
  * - **Hidden**: a ground-anchored size past `textMaxSizePixels` (ADR-0037),
4682
4848
  * or faded out below the band minimum (ADR-0060), returns `null` — the box
4683
4849
  * tracks `resolveTextAppearance`'s hide rule rather than keep boxing text
4684
4850
  * that no adapter is drawing.
4685
4851
  */
4686
4852
  function fitLabelTransformBox(input) {
4687
- const { text, rotation, textAnchor, textSizePixels, textSizeMeters, anchor, resolution, bearing, unclamped, textMaxSizePixels, labelSizeBand } = input;
4853
+ const { text, rotation, textAnchor, textOffsetEms, textSizePixels, textSizeMeters, anchor, resolution, bearing, unclamped, textMaxSizePixels, labelSizeBand } = input;
4688
4854
  if (!text) return null;
4689
4855
  const angle = normalizeAngle(Math.PI - (rotation ?? 0) - (bearing ?? 0));
4690
4856
  let h = 16;
@@ -4703,9 +4869,12 @@ function fitLabelTransformBox(input) {
4703
4869
  const height = lines.length * LINE_HEIGHT_FACTOR * h;
4704
4870
  const halfWidth = width / 2 + 4;
4705
4871
  const halfHeight = height / 2 + 4;
4872
+ const [offsetRight, offsetDown] = textOffsetEms ?? [0, 0];
4873
+ const localX = (textAnchor === "start" ? width / 2 : textAnchor === "end" ? -width / 2 : 0) + offsetRight * h;
4874
+ const localY = offsetDown * h;
4706
4875
  let center = anchor;
4707
- if (textAnchor === "start" || textAnchor === "end") {
4708
- const [ox, oy] = rotate((textAnchor === "start" ? 1 : -1) * width / 2, 0, angle);
4876
+ if (localX !== 0 || localY !== 0) {
4877
+ const [ox, oy] = rotate(localX, localY, angle);
4709
4878
  center = [anchor[0] + ox, anchor[1] + oy];
4710
4879
  }
4711
4880
  return {
@@ -4730,6 +4899,7 @@ function fitLabelBoxFromFeature(feature, anchorPixel, view) {
4730
4899
  text: typeof props.text === "string" ? props.text : void 0,
4731
4900
  rotation: typeof props.rotation === "number" ? props.rotation : void 0,
4732
4901
  textAnchor: props.textAnchor === "start" || props.textAnchor === "end" ? props.textAnchor : void 0,
4902
+ textOffsetEms: labelTextOffsetEms(props),
4733
4903
  textSizePixels: typeof props.textSizePixels === "number" ? props.textSizePixels : void 0,
4734
4904
  textSizeMeters: typeof props.textSizeMeters === "number" ? props.textSizeMeters : void 0,
4735
4905
  textMaxSizePixels: typeof props.textMaxSizePixels === "number" ? props.textMaxSizePixels : void 0,
@@ -5014,6 +5184,7 @@ function createLabelPlacement(deps) {
5014
5184
  downPixel: pixel,
5015
5185
  text: typeof props.text === "string" ? props.text : void 0,
5016
5186
  textAnchor: props.textAnchor === "start" || props.textAnchor === "end" ? props.textAnchor : void 0,
5187
+ textOffsetEms: labelTextOffsetEms(props),
5017
5188
  textSizePixels: typeof props.textSizePixels === "number" ? props.textSizePixels : void 0,
5018
5189
  textSizeMeters: typeof props.textSizeMeters === "number" ? props.textSizeMeters : void 0,
5019
5190
  lastBox: labelBox
@@ -5053,6 +5224,7 @@ function createLabelPlacement(deps) {
5053
5224
  text: drag.text,
5054
5225
  rotation,
5055
5226
  textAnchor: drag.textAnchor,
5227
+ textOffsetEms: drag.textOffsetEms,
5056
5228
  textSizePixels: drag.textSizePixels,
5057
5229
  textSizeMeters: drag.textSizeMeters,
5058
5230
  anchor: drag.anchorPixel,
@@ -6678,6 +6850,13 @@ var ImageCapabilityRequiredError = class ImageCapabilityRequiredError extends Er
6678
6850
  Object.setPrototypeOf(this, ImageCapabilityRequiredError.prototype);
6679
6851
  }
6680
6852
  };
6853
+ var NoteCapabilityRequiredError = class NoteCapabilityRequiredError extends Error {
6854
+ constructor() {
6855
+ super("TacticalDraw: note capability is not configured");
6856
+ this.name = "NoteCapabilityRequiredError";
6857
+ Object.setPrototypeOf(this, NoteCapabilityRequiredError.prototype);
6858
+ }
6859
+ };
6681
6860
  var MarkerCapabilityRequiredError = class MarkerCapabilityRequiredError extends Error {
6682
6861
  constructor() {
6683
6862
  super("TacticalDraw: marker capability is not configured");
@@ -6837,7 +7016,7 @@ function renderImageForAdapter(adapter, capability, image) {
6837
7016
  ...resolved ? { overlayUrl: source.overlayUrl } : {},
6838
7017
  available: resolved !== void 0
6839
7018
  };
6840
- const coordinates = imageOverlayCoordinates(adapter, image, render);
7019
+ const coordinates = groundBoxCoordinates(adapter, image.position, image.rotation, image.size.value, image.size.value * render.height / render.width);
6841
7020
  return {
6842
7021
  render,
6843
7022
  ...render.overlayUrl ? { overlay: {
@@ -6848,15 +7027,16 @@ function renderImageForAdapter(adapter, capability, image) {
6848
7027
  coordinates,
6849
7028
  opacity: imageOpacity(image)
6850
7029
  } } : {},
6851
- feature: imageOverlayFeature(image, coordinates, render.available)
7030
+ feature: overlayPickFeature(image, "image", coordinates, render.available)
6852
7031
  };
6853
7032
  }
6854
- function imageOverlayCoordinates(adapter, image, render) {
6855
- const [centerX, centerY] = adapter.fromLonLat(image.position);
6856
- const halfWidth = image.size.value / 2;
6857
- const halfHeight = image.size.value * render.height / render.width / 2;
6858
- const cos = Math.cos(-image.rotation);
6859
- const sin = Math.sin(-image.rotation);
7033
+ /** Corners TL, TR, BR, BL in lon/lat of a box rotated clockwise about its centre, in Web Mercator metres. */
7034
+ function groundBoxCoordinates(adapter, position, rotation, widthMetres, heightMetres) {
7035
+ const [centerX, centerY] = adapter.fromLonLat(position);
7036
+ const halfWidth = widthMetres / 2;
7037
+ const halfHeight = heightMetres / 2;
7038
+ const cos = Math.cos(-rotation);
7039
+ const sin = Math.sin(-rotation);
6860
7040
  const rotate = (x, y) => adapter.toLonLat([centerX + x * cos - y * sin, centerY + x * sin + y * cos]);
6861
7041
  return [
6862
7042
  rotate(-halfWidth, halfHeight),
@@ -6865,20 +7045,25 @@ function imageOverlayCoordinates(adapter, image, render) {
6865
7045
  rotate(-halfWidth, -halfHeight)
6866
7046
  ];
6867
7047
  }
6868
- function imageOverlayFeature(image, coordinates, available) {
7048
+ /**
7049
+ * The polygon that picks an overlay graphic: transparent while its raster is
7050
+ * available, else a grey placeholder. It names the overlay it carries, because
7051
+ * OpenLayers paints an overlay through the feature that names it.
7052
+ */
7053
+ function overlayPickFeature(graphic, kind, coordinates, available) {
6869
7054
  return {
6870
7055
  type: "Feature",
6871
- id: `${image.id}:image`,
7056
+ id: `${graphic.id}:${kind}`,
6872
7057
  geometry: {
6873
7058
  type: "Polygon",
6874
7059
  coordinates: [[...coordinates.map((coordinate) => [...coordinate]), [...coordinates[0]]]]
6875
7060
  },
6876
7061
  properties: {
6877
- ...image.properties ?? {},
6878
- graphicId: image.id,
6879
- graphicKind: "image",
6880
- imageOverlayId: `${image.id}:image-overlay`,
6881
- imageAvailable: available,
7062
+ ...graphic.properties ?? {},
7063
+ graphicId: graphic.id,
7064
+ graphicKind: kind,
7065
+ imageOverlayId: `${graphic.id}:${kind}-overlay`,
7066
+ [`${kind}Available`]: available,
6882
7067
  pickInterior: true,
6883
7068
  style: available ? {
6884
7069
  fillColor: "rgba(0,0,0,0)",
@@ -6895,13 +7080,18 @@ function imageOverlayFeature(image, coordinates, available) {
6895
7080
  function validateResolvedResource(image, resource) {
6896
7081
  if (resource.id !== image.resourceId) throw new TypeError("ImageCapability returned a resource with a mismatched id");
6897
7082
  if (!isSelfContainedRasterDataUrl(resource.overlayUrl)) throw new TypeError("ImageResource.overlayUrl must be a self-contained raster data URL");
7083
+ if (resource.svg !== void 0 && typeof resource.svg !== "string") throw new TypeError("ImageResource.svg must be a string when present");
6898
7084
  if (!Number.isFinite(resource.width) || resource.width <= 0) throw new TypeError("ImageResource.width must be a positive finite number");
6899
7085
  if (!Number.isFinite(resource.height) || resource.height <= 0) throw new TypeError("ImageResource.height must be a positive finite number");
6900
7086
  if (resource.width !== image.intrinsicSize.width || resource.height !== image.intrinsicSize.height) throw new TypeError("ImageResource dimensions must match ImageGraphic.intrinsicSize");
6901
7087
  return resource;
6902
7088
  }
7089
+ /** Reads only the header, so the cost doesn't grow with the size of the image. */
6903
7090
  function isSelfContainedRasterDataUrl(value) {
6904
- const match = /^data:(image\/[a-z0-9.+-]+)(?:;[^,]*)?,.+$/is.exec(value);
7091
+ if (typeof value !== "string") return false;
7092
+ const comma = value.indexOf(",");
7093
+ if (comma < 0 || comma === value.length - 1) return false;
7094
+ const match = /^data:(image\/[a-z0-9.+-]+)(?:;[^,]*)?$/i.exec(value.slice(0, comma));
6905
7095
  return match !== null && match[1].toLowerCase() !== "image/svg+xml";
6906
7096
  }
6907
7097
  function missingResource(image) {
@@ -6914,6 +7104,159 @@ function missingResource(image) {
6914
7104
  };
6915
7105
  }
6916
7106
  //#endregion
7107
+ //#region src/tactical-draw/note-rendering.ts
7108
+ function createNoteResolveCache() {
7109
+ return {
7110
+ heights: /* @__PURE__ */ new Map(),
7111
+ rasters: /* @__PURE__ */ new WeakMap()
7112
+ };
7113
+ }
7114
+ /** Screen pixels per em assumed when the adapter reports no resolution. */
7115
+ const FALLBACK_EM_PIXELS = 32;
7116
+ const DEFAULT_MIN_EM_PIXELS = 6;
7117
+ const DEFAULT_MAX_STRETCH = 1;
7118
+ /** Placeholder heuristic (ADR-0066): about 0.6 em per character, plate-like spacing. */
7119
+ const PLACEHOLDER_EM_PER_CHAR = .6;
7120
+ const PLACEHOLDER_PADDING = .8;
7121
+ const PLACEHOLDER_LINE_HEIGHT = 1.4;
7122
+ const PLACEHOLDER_BLOCK_SPACING = .6;
7123
+ const PLACEHOLDER_IMAGE_ASPECT = 3 / 4;
7124
+ /** A source line holding only an image, which fills the content width. */
7125
+ const PLACEHOLDER_IMAGE_LINE = /^!\[.*\]\(.*\)$/;
7126
+ /**
7127
+ * Estimated box height in em for a Note whose raster is still pending. Content is
7128
+ * opaque here, so this counts its source lines: a blank line stands for a block gap.
7129
+ */
7130
+ function placeholderNoteHeight(note) {
7131
+ const contentWidth = Math.max(1, note.width - 2 * PLACEHOLDER_PADDING);
7132
+ const blocks = note.content.split(/\n\s*\n/).filter((block) => block.trim() !== "");
7133
+ let height = 2 * PLACEHOLDER_PADDING + PLACEHOLDER_BLOCK_SPACING * Math.max(0, blocks.length - 1);
7134
+ for (const line of blocks.flatMap((block) => block.split("\n"))) {
7135
+ const text = line.trim();
7136
+ if (PLACEHOLDER_IMAGE_LINE.test(text)) height += contentWidth * PLACEHOLDER_IMAGE_ASPECT;
7137
+ else height += Math.ceil(text.length * PLACEHOLDER_EM_PER_CHAR / contentWidth) * PLACEHOLDER_LINE_HEIGHT;
7138
+ }
7139
+ return height;
7140
+ }
7141
+ /** The adapter's resolution in metres per pixel, or `undefined` if it has no usable one. */
7142
+ function usableResolution(adapter) {
7143
+ const resolution = adapter.getResolution();
7144
+ return hasUsableResolution(resolution) ? resolution : void 0;
7145
+ }
7146
+ /** Screen-space box of a Note, for highlights, edit boxes and marquee hit tests. */
7147
+ function noteFootprint(note, render, adapter) {
7148
+ const center = adapter.getPixelFromCoordinate(note.position);
7149
+ if (!center) return null;
7150
+ const pxPerEm = note.emSize.value / (usableResolution(adapter) ?? 1);
7151
+ const box = {
7152
+ center,
7153
+ halfWidth: note.width * pxPerEm / 2,
7154
+ halfHeight: render.height * pxPerEm / 2,
7155
+ angle: note.rotation - adapter.getBearing()
7156
+ };
7157
+ return {
7158
+ box,
7159
+ corners: boxCorners(box)
7160
+ };
7161
+ }
7162
+ /**
7163
+ * Resolve and render one Note. Validates the Note and the resolved raster first,
7164
+ * so a malformed Note or raster throws before any caller state changes.
7165
+ *
7166
+ * The density requested from the capability follows the view (ADR-0069): the
7167
+ * on-screen pixels per em, times the capability's pixel ratio, rounded up to a
7168
+ * power of two and capped so the raster's longest side stays within
7169
+ * {@link NOTE_MAX_RASTER_PIXELS}. The overlay fades over one step once an em
7170
+ * is smaller on screen than the fade threshold, or once the cap stretches it.
7171
+ */
7172
+ function renderNoteForAdapter(adapter, capability, note, cache = createNoteResolveCache()) {
7173
+ validateNoteGraphic(note);
7174
+ const emPixels = screenEmPixels(adapter, note);
7175
+ const step = densityStep((emPixels ?? FALLBACK_EM_PIXELS) * positiveOr(capability.pixelRatio, 1));
7176
+ const cappedDensity = (heightEm) => Math.min(step, (NOTE_MAX_RASTER_PIXELS - .5) / Math.max(note.width, heightEm));
7177
+ let pxPerEm = cappedDensity(cache.heights.get(note.id) ?? placeholderNoteHeight(note));
7178
+ let raster = resolveRaster(capability, note, pxPerEm, cache);
7179
+ if (raster) {
7180
+ const exact = cappedDensity(rasterHeightEm(note, raster));
7181
+ if (Math.abs(exact - pxPerEm) > pxPerEm * 1e-9) {
7182
+ pxPerEm = exact;
7183
+ raster = resolveRaster(capability, note, pxPerEm, cache);
7184
+ }
7185
+ }
7186
+ const render = raster ? {
7187
+ height: rasterHeightEm(note, raster),
7188
+ available: true
7189
+ } : {
7190
+ height: placeholderNoteHeight(note),
7191
+ available: false
7192
+ };
7193
+ if (raster) cache.heights.set(note.id, render.height);
7194
+ const fade = emPixels === void 0 ? 1 : noteFade(emPixels, pxPerEm, capability.fade);
7195
+ const coordinates = groundBoxCoordinates(adapter, note.position, note.rotation, note.width * note.emSize.value, render.height * note.emSize.value);
7196
+ if (fade === 0) return {
7197
+ render,
7198
+ features: []
7199
+ };
7200
+ return {
7201
+ render,
7202
+ ...raster ? { overlay: {
7203
+ id: `${note.id}:note-overlay`,
7204
+ url: raster.url,
7205
+ width: raster.width,
7206
+ height: raster.height,
7207
+ coordinates,
7208
+ opacity: noteOpacity(note) * fade
7209
+ } } : {},
7210
+ features: [overlayPickFeature(note, "note", coordinates, render.available)]
7211
+ };
7212
+ }
7213
+ /** The box height a ready raster stands for: the layout's, or else from its pixel aspect. */
7214
+ function rasterHeightEm(note, raster) {
7215
+ return raster.heightEm ?? note.width * raster.height / raster.width;
7216
+ }
7217
+ function resolveRaster(capability, note, pxPerEm, cache) {
7218
+ const memo = cache.rasters.get(note);
7219
+ if (memo && memo.pxPerEm === pxPerEm) return memo.raster;
7220
+ const resolved = capability.resolve(note, pxPerEm);
7221
+ if (resolved === "pending") return void 0;
7222
+ const raster = validateRaster(resolved);
7223
+ cache.rasters.set(note, {
7224
+ pxPerEm,
7225
+ raster
7226
+ });
7227
+ return raster;
7228
+ }
7229
+ function screenEmPixels(adapter, note) {
7230
+ const resolution = usableResolution(adapter);
7231
+ return resolution === void 0 ? void 0 : note.emSize.value / resolution;
7232
+ }
7233
+ /** The power of two at or above `pxPerEm`, at least 1. */
7234
+ function densityStep(pxPerEm) {
7235
+ return 2 ** Math.max(0, Math.ceil(Math.log2(pxPerEm)));
7236
+ }
7237
+ /**
7238
+ * Overlay opacity factor. Each fade spans one step: opaque at its threshold,
7239
+ * gone at a factor of two past it. Stretch is measured in CSS pixels per
7240
+ * raster pixel, so a capped raster only fades once it is coarser than 1×.
7241
+ */
7242
+ function noteFade(emPixels, pxPerEm, thresholds) {
7243
+ const maxStretch = positiveOr(thresholds?.maxStretch, DEFAULT_MAX_STRETCH);
7244
+ const small = thresholds?.minEmPixels === 0 ? Number.POSITIVE_INFINITY : Math.log2(emPixels / (positiveOr(thresholds?.minEmPixels, DEFAULT_MIN_EM_PIXELS) / 2));
7245
+ const stretched = 1 - Math.log2(emPixels / pxPerEm / maxStretch);
7246
+ return Math.max(0, Math.min(1, small, stretched));
7247
+ }
7248
+ function positiveOr(value, fallback) {
7249
+ return value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
7250
+ }
7251
+ function validateRaster(raster) {
7252
+ if (typeof raster !== "object" || raster === null) throw new TypeError("NoteCapability.resolve must return a NoteRaster or \"pending\"");
7253
+ if (!isSelfContainedRasterDataUrl(raster.url)) throw new TypeError("NoteRaster.url must be a self-contained raster data URL");
7254
+ if (!Number.isFinite(raster.width) || raster.width <= 0) throw new TypeError("NoteRaster.width must be a positive finite number");
7255
+ if (!Number.isFinite(raster.height) || raster.height <= 0) throw new TypeError("NoteRaster.height must be a positive finite number");
7256
+ if (raster.heightEm !== void 0 && !(Number.isFinite(raster.heightEm) && raster.heightEm > 0)) throw new TypeError("NoteRaster.heightEm must be a positive finite number");
7257
+ return raster;
7258
+ }
7259
+ //#endregion
6917
7260
  //#region src/tactical-draw/marker-rendering.ts
6918
7261
  const PLACEHOLDER_SIZE = 24;
6919
7262
  const PLACEHOLDER = {
@@ -7136,7 +7479,8 @@ function defaultGroupSizeAnchor(graphics) {
7136
7479
  */
7137
7480
  function runGroupTransform(opts) {
7138
7481
  const constrainKey = () => opts.editModifiers().constrain;
7139
- const { adapter, capability, imageCapability, markerCapability, graphics, graphicsLayer, previewLayer, handlesLayer, renderOptions: renderOpts, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, publishWorkingGraphics, settleWorkingGraphics, isOnGraphicsLayer, onSettled, onClickAwayGraphicsPick } = opts;
7482
+ const { adapter, capability, imageCapability, noteCapability, markerCapability, graphics, graphicsLayer, previewLayer, handlesLayer, renderOptions: renderOpts, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, publishWorkingGraphics, settleWorkingGraphics, isOnGraphicsLayer, onSettled, onClickAwayGraphicsPick } = opts;
7483
+ const { noteResolveCache } = opts;
7140
7484
  assertCapabilityFor(graphics);
7141
7485
  validateHostResources(graphics);
7142
7486
  let sizeAnchor = opts.sizeAnchor ?? defaultGroupSizeAnchor(graphics);
@@ -7144,12 +7488,14 @@ function runGroupTransform(opts) {
7144
7488
  function assertCapabilityFor(list) {
7145
7489
  if (!capability && list.some(isPointSymbol)) throw new PointSymbolCapabilityRequiredError();
7146
7490
  if (!imageCapability && list.some(isImageGraphic)) throw new ImageCapabilityRequiredError();
7491
+ if (!noteCapability && list.some(isNoteGraphic)) throw new NoteCapabilityRequiredError();
7147
7492
  if (!markerCapability && list.some(isMarker)) throw new MarkerCapabilityRequiredError();
7148
7493
  }
7149
7494
  /** Validate host integration before listeners, layers, or interaction state are created. */
7150
7495
  function validateHostResources(list) {
7151
7496
  for (const graphic of list) {
7152
7497
  if (isImageGraphic(graphic)) renderImageForAdapter(adapter, imageCapability, graphic);
7498
+ if (isNoteGraphic(graphic)) renderNoteForAdapter(adapter, noteCapability, graphic, noteResolveCache());
7153
7499
  if (isMarker(graphic)) resolveMarkerRender(markerCapability, graphic);
7154
7500
  }
7155
7501
  }
@@ -7159,6 +7505,9 @@ function runGroupTransform(opts) {
7159
7505
  function isImageMember(member) {
7160
7506
  return isImageGraphic(member.graphic);
7161
7507
  }
7508
+ function isNoteMember(member) {
7509
+ return isNoteGraphic(member.graphic);
7510
+ }
7162
7511
  function isMarkerMember(member) {
7163
7512
  return isMarker(member.graphic);
7164
7513
  }
@@ -7174,9 +7523,9 @@ function runGroupTransform(opts) {
7174
7523
  graphic,
7175
7524
  editStartPoints,
7176
7525
  workingPoints: editStartPoints.map((p) => [...p]),
7177
- editStartSize: graphic.size.value,
7526
+ editStartSize: anchoredSizeValue(graphic),
7178
7527
  editStartRotation: graphic.rotation,
7179
- workingSize: graphic.size.value,
7528
+ workingSize: anchoredSizeValue(graphic),
7180
7529
  workingRotation: graphic.rotation,
7181
7530
  workingAmplifierPlacements: void 0,
7182
7531
  optionsOverride: null,
@@ -7244,6 +7593,17 @@ function runGroupTransform(opts) {
7244
7593
  image.rotation = member.workingRotation;
7245
7594
  return image;
7246
7595
  }
7596
+ /** A Note member scales `emSize` uniformly; its `width` in em never changes in a group. */
7597
+ function buildWorkingNote(member) {
7598
+ const note = cloneNoteGraphic(member.graphic);
7599
+ note.position = [...member.workingPoints[0]];
7600
+ note.emSize = {
7601
+ value: member.workingSize,
7602
+ unit: "meters"
7603
+ };
7604
+ note.rotation = member.workingRotation;
7605
+ return note;
7606
+ }
7247
7607
  function buildWorkingMarker(member) {
7248
7608
  const marker = cloneMarker(member.graphic);
7249
7609
  marker.position = [...member.workingPoints[0]];
@@ -7278,6 +7638,13 @@ function runGroupTransform(opts) {
7278
7638
  render: renderImageForAdapter(adapter, imageCapability, image).render
7279
7639
  };
7280
7640
  }
7641
+ if (isNoteMember(member)) {
7642
+ const note = buildWorkingNote(member);
7643
+ return {
7644
+ graphic: cloneNoteGraphic(note),
7645
+ render: renderNoteForAdapter(adapter, noteCapability, note, noteResolveCache()).render
7646
+ };
7647
+ }
7281
7648
  if (isMarkerMember(member)) {
7282
7649
  const marker = buildWorkingMarker(member);
7283
7650
  return {
@@ -7297,6 +7664,7 @@ function runGroupTransform(opts) {
7297
7664
  const member = members[i];
7298
7665
  if (isPointSymbolMember(member)) return buildWorkingPointSymbol(member);
7299
7666
  if (isImageMember(member)) return buildWorkingImage(member);
7667
+ if (isNoteMember(member)) return buildWorkingNote(member);
7300
7668
  if (isMarkerMember(member)) return buildWorkingMarker(member);
7301
7669
  return buildWorkingMeasureWith(member, member.optionsOverride);
7302
7670
  }
@@ -7451,6 +7819,13 @@ function runGroupTransform(opts) {
7451
7819
  features = [plan.feature];
7452
7820
  const footprint = imageFootprint(image, plan.render, adapter);
7453
7821
  if (footprint) boxPixels = footprint.corners;
7822
+ } else if (isNoteMember(member)) {
7823
+ const note = buildWorkingNote(member);
7824
+ const plan = renderNoteForAdapter(adapter, noteCapability, note, noteResolveCache());
7825
+ imageOverlays = plan.overlay ? [plan.overlay] : void 0;
7826
+ features = plan.features;
7827
+ const footprint = noteFootprint(note, plan.render, adapter);
7828
+ if (footprint) boxPixels = footprint.corners;
7454
7829
  } else if (isMarkerMember(member)) {
7455
7830
  const marker = buildWorkingMarker(member);
7456
7831
  pinGroup = opts.renderPin?.(marker);
@@ -8030,12 +8405,21 @@ function runGroupTransform(opts) {
8030
8405
  abort(reason, cause) {
8031
8406
  core.abort(reason, cause);
8032
8407
  },
8033
- syncHostGraphics
8408
+ syncHostGraphics,
8409
+ refreshNoteRenders() {
8410
+ if (ctx.settled || !members.some(isNoteMember)) return;
8411
+ renderAllPreviews();
8412
+ renderHandlesLayer();
8413
+ }
8034
8414
  };
8035
8415
  }
8416
+ /** The scalar a uniform group scale multiplies: `size.value`, or a Note's `emSize.value`. */
8417
+ function anchoredSizeValue(graphic) {
8418
+ return isNoteGraphic(graphic) ? graphic.emSize.value : graphic.size.value;
8419
+ }
8036
8420
  //#endregion
8037
8421
  //#region src/tactical-draw/point-symbol-draw-controller.ts
8038
- const PREVIEW_ID$2 = "__td_point_symbol_preview__";
8422
+ const PREVIEW_ID$3 = "__td_point_symbol_preview__";
8039
8423
  function runPointSymbolDraw(options) {
8040
8424
  const { adapter, capability, draft, previewLayer, generateId, signal, onSettled, snap } = options;
8041
8425
  let latestPosition = draft.position;
@@ -8052,9 +8436,9 @@ function runPointSymbolDraw(options) {
8052
8436
  });
8053
8437
  const renderPreview = () => {
8054
8438
  if (!latestPosition) return;
8055
- const plan = renderPointSymbolForAdapter(adapter, capability, build(PREVIEW_ID$2, latestPosition));
8439
+ const plan = renderPointSymbolForAdapter(adapter, capability, build(PREVIEW_ID$3, latestPosition));
8056
8440
  ctx.writeLayer(previewLayer, [{
8057
- id: PREVIEW_ID$2,
8441
+ id: PREVIEW_ID$3,
8058
8442
  features: plan.features,
8059
8443
  iconResources: [plan.resource]
8060
8444
  }]);
@@ -8559,7 +8943,7 @@ function runPointSymbolEdit(opts) {
8559
8943
  }
8560
8944
  //#endregion
8561
8945
  //#region src/tactical-draw/image-draw-controller.ts
8562
- const PREVIEW_ID$1 = "__td_image_preview__";
8946
+ const PREVIEW_ID$2 = "__td_image_preview__";
8563
8947
  const DEFAULT_IMAGE_WIDTH_PIXELS = 128;
8564
8948
  function runImageDraw(options) {
8565
8949
  const { adapter, capability, draft, previewLayer, generateId, signal, onSettled, snap } = options;
@@ -8587,9 +8971,9 @@ function runImageDraw(options) {
8587
8971
  const planFor = (id, position) => renderImageForAdapter(adapter, capability, build(id, position));
8588
8972
  const renderPreview = () => {
8589
8973
  if (!latestPosition) return;
8590
- const plan = planFor(PREVIEW_ID$1, latestPosition);
8974
+ const plan = planFor(PREVIEW_ID$2, latestPosition);
8591
8975
  ctx.writeLayer(previewLayer, [{
8592
- id: PREVIEW_ID$1,
8976
+ id: PREVIEW_ID$2,
8593
8977
  features: [plan.feature],
8594
8978
  iconResources: [],
8595
8979
  ...plan.overlay ? { imageOverlays: [plan.overlay] } : {}
@@ -8635,9 +9019,7 @@ function positiveResolution(resolution) {
8635
9019
  //#endregion
8636
9020
  //#region src/tactical-draw/image-edit-controller.ts
8637
9021
  function normaliseImageModes(input) {
8638
- const modes = input ?? ["transform"];
8639
- for (const mode of modes) if (mode !== "transform" && mode !== "delete") throw new TypeError(`Image editing does not support mode "${mode}"`);
8640
- return modes.includes("delete") ? ["delete"] : [...new Set(modes)];
9022
+ return normaliseBoxEditModes("Image", input);
8641
9023
  }
8642
9024
  function runImageEdit(opts) {
8643
9025
  const constrainKey = () => opts.editModifiers().constrain;
@@ -8669,11 +9051,7 @@ function runImageEdit(opts) {
8669
9051
  if (ctx.settled) return;
8670
9052
  const plan = renderImageForAdapter(adapter, capability, working);
8671
9053
  const footprint = imageFootprint(working, plan.render, adapter);
8672
- const nextBox = footprint ? {
8673
- ...footprint.box,
8674
- halfWidth: Math.max(1, footprint.box.halfWidth) + (interactionStyle?.boxPadding ?? 0),
8675
- halfHeight: Math.max(1, footprint.box.halfHeight) + (interactionStyle?.boxPadding ?? 0)
8676
- } : null;
9054
+ const nextBox = footprint ? paddedEditBox(footprint.box, interactionStyle?.boxPadding) : null;
8677
9055
  const handles = [];
8678
9056
  if (modes.includes("transform") && nextBox) handles.push(boxOutlineFeature(nextBox, (pixel) => driver.fromPixel(pixel), `${handleIdPrefix}:box-outline`, interactionStyle?.boxOutline), ...toFeatures(boxToHandles(nextBox, (pixel) => driver.fromPixel(pixel)), handleIdPrefix, interactionStyle));
8679
9057
  const group = {
@@ -8893,6 +9271,405 @@ function runImageEdit(opts) {
8893
9271
  };
8894
9272
  }
8895
9273
  //#endregion
9274
+ //#region src/tactical-draw/note-draw-controller.ts
9275
+ const PREVIEW_ID$1 = "__td_note_preview__";
9276
+ function runNoteDraw(options) {
9277
+ const { adapter, capability, draft, previewLayer, generateId, signal, onSettled, snap } = options;
9278
+ let latestPosition = draft.position;
9279
+ let ctx;
9280
+ const savedCursor = "";
9281
+ const build = (id, position) => ({
9282
+ ...structuredClone(draft),
9283
+ id,
9284
+ kind: "note",
9285
+ schemaVersion: 1,
9286
+ position: [...position],
9287
+ rotation: normalizeRotation(draft.rotation ?? 0),
9288
+ emSize: structuredClone(draft.emSize ?? {
9289
+ value: 14 * (usableResolution(adapter) ?? 1),
9290
+ unit: "meters"
9291
+ }),
9292
+ width: draft.width ?? 24,
9293
+ ...draft.style ? { style: {
9294
+ ...draft.style,
9295
+ opacity: Math.max(0, Math.min(1, draft.style.opacity ?? 1))
9296
+ } } : {}
9297
+ });
9298
+ const planFor = (id, position) => renderNoteForAdapter(adapter, capability, build(id, position));
9299
+ const renderPreview = () => {
9300
+ if (!latestPosition) return;
9301
+ const plan = planFor(PREVIEW_ID$1, latestPosition);
9302
+ ctx.writeLayer(previewLayer, [{
9303
+ id: PREVIEW_ID$1,
9304
+ features: plan.features,
9305
+ iconResources: [],
9306
+ ...plan.overlay ? { imageOverlays: [plan.overlay] } : {}
9307
+ }]);
9308
+ };
9309
+ const handlePointerMove = (event) => {
9310
+ latestPosition = snappedDrawPosition(snap, event);
9311
+ renderPreview();
9312
+ };
9313
+ const handleClick = (event) => {
9314
+ latestPosition = snappedDrawPosition(snap, event);
9315
+ ctx.commit(() => {
9316
+ const graphic = build(draft.id ?? generateId(), latestPosition);
9317
+ return {
9318
+ graphic,
9319
+ render: planFor(graphic.id, graphic.position).render
9320
+ };
9321
+ });
9322
+ };
9323
+ return runInteraction({
9324
+ adapter,
9325
+ signal,
9326
+ layers: [previewLayer],
9327
+ onViewChange: renderPreview,
9328
+ onSettled,
9329
+ attach(interaction) {
9330
+ ctx = interaction;
9331
+ interaction.onTeardown(() => {
9332
+ adapter.off("pointermove", handlePointerMove);
9333
+ adapter.off("click", handleClick);
9334
+ adapter.setCursor(savedCursor);
9335
+ });
9336
+ adapter.setCursor("crosshair");
9337
+ adapter.on("pointermove", handlePointerMove);
9338
+ adapter.on("click", handleClick);
9339
+ renderPreview();
9340
+ }
9341
+ });
9342
+ }
9343
+ //#endregion
9344
+ //#region src/tactical-draw/note-edit-controller.ts
9345
+ /**
9346
+ * A single-Note edit's corner scale keeps `emSize` between these multiples of
9347
+ * the value the Note had when the edit started (ADR-0066), so the limits don't
9348
+ * follow the zoom and reset with each edit. The model itself does not limit it,
9349
+ * and neither do group transforms.
9350
+ */
9351
+ const NOTE_MIN_SCALE = .3;
9352
+ const NOTE_MAX_SCALE = 4;
9353
+ function normaliseNoteModes(input) {
9354
+ return normaliseBoxEditModes("Note", input);
9355
+ }
9356
+ function runNoteEdit(opts) {
9357
+ const constrainKey = () => opts.editModifiers().constrain;
9358
+ const { adapter, capability, resolveCache, note, graphicsLayer, previewLayer, handlesLayer, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, settleToGraphics, publishWorkingGraphic, wasOnGraphicsLayer, onSettled, onClickAwayGraphicsPick, snap } = opts;
9359
+ validateNoteGraphic(note);
9360
+ let modes = normaliseNoteModes(opts.modes);
9361
+ let usesGraphicStack = wasOnGraphicsLayer;
9362
+ let working = cloneNoteGraphic(note);
9363
+ let dirty = false;
9364
+ let box = null;
9365
+ let drag = null;
9366
+ /** The resolution the working graphic was last painted at. */
9367
+ let paintedResolution;
9368
+ let ctx;
9369
+ let driver;
9370
+ let shell;
9371
+ const changeEmitter = createChangeEmitter({
9372
+ listenerErrorsMessage: "GraphicEditSession.onChange errors",
9373
+ isSettled: () => ctx.settled,
9374
+ abort: () => ctx.fail(new TacticalDrawAbortError("session")),
9375
+ close: () => ctx.commit(snapshot)
9376
+ });
9377
+ const commitEmitter = createCommitEmitter("GraphicEditSession.onCommit listener errors");
9378
+ const settleEmitter = createSettleEmitter("GraphicEditSession.onSettled listener errors");
9379
+ const captureHistory = () => ({ working: cloneNoteGraphic(working) });
9380
+ const snapshotOf = (value) => ({
9381
+ graphic: cloneNoteGraphic(value),
9382
+ render: renderNoteForAdapter(adapter, capability, value, resolveCache()).render
9383
+ });
9384
+ const snapshot = () => snapshotOf(working);
9385
+ /**
9386
+ * The box handles: corners and rotate grip, then the Note-only width grips.
9387
+ */
9388
+ const handlesFor = (nextBox) => {
9389
+ const fromPixel = (pixel) => driver.fromPixel(pixel);
9390
+ const widths = widthHandlePixels(nextBox).map((pixel, index) => ({
9391
+ kind: "width",
9392
+ index,
9393
+ position: fromPixel(pixel)
9394
+ }));
9395
+ return [...boxToHandles(nextBox, fromPixel), ...widths];
9396
+ };
9397
+ const render = (publishGraphic = true) => {
9398
+ if (ctx.settled) return;
9399
+ const plan = renderNoteForAdapter(adapter, capability, working, resolveCache());
9400
+ const footprint = noteFootprint(working, plan.render, adapter);
9401
+ const nextBox = footprint ? paddedEditBox(footprint.box, interactionStyle?.boxPadding) : null;
9402
+ const handles = [];
9403
+ if (modes.includes("transform") && nextBox) handles.push(boxOutlineFeature(nextBox, (pixel) => driver.fromPixel(pixel), `${handleIdPrefix}:box-outline`, interactionStyle?.boxOutline), ...toFeatures(handlesFor(nextBox), handleIdPrefix, interactionStyle));
9404
+ const group = {
9405
+ id: working.id,
9406
+ features: plan.features,
9407
+ iconResources: [],
9408
+ ...plan.overlay ? { imageOverlays: [plan.overlay] } : {}
9409
+ };
9410
+ if (publishGraphic) {
9411
+ paintedResolution = adapter.getResolution();
9412
+ publishWorkingGraphic(group);
9413
+ ctx.writeLayer(previewLayer, usesGraphicStack ? [] : [group]);
9414
+ }
9415
+ box = nextBox;
9416
+ ctx.writeLayer(handlesLayer, [{
9417
+ id: `__td_note_edit_handles__:${working.id}`,
9418
+ features: handles,
9419
+ iconResources: []
9420
+ }]);
9421
+ };
9422
+ const emitChange = (previousState, source, onAccepted) => changeEmitter.emit({
9423
+ source,
9424
+ graphic: snapshot(),
9425
+ previous: snapshotOf(previousState.working),
9426
+ session
9427
+ }, {
9428
+ rollback() {
9429
+ working = cloneNoteGraphic(previousState.working);
9430
+ dirty = !deepEqual(working, note);
9431
+ render();
9432
+ },
9433
+ onAccepted
9434
+ });
9435
+ const history = createSessionHistory({
9436
+ initial: captureHistory(),
9437
+ clone: (value) => ({ working: cloneNoteGraphic(value.working) }),
9438
+ equals: (a, b) => deepEqual(a.working, b.working),
9439
+ isCurrent: (value) => deepEqual(working, value.working),
9440
+ apply(from, to, source) {
9441
+ working = cloneNoteGraphic(to.working);
9442
+ dirty = !deepEqual(working, note);
9443
+ render();
9444
+ return emitChange(from, source);
9445
+ }
9446
+ });
9447
+ const apply = (next, source, label) => {
9448
+ const previous = captureHistory();
9449
+ working = cloneNoteGraphic(next);
9450
+ dirty = !deepEqual(working, note);
9451
+ render();
9452
+ emitChange(previous, source, () => history.record(captureHistory(), label));
9453
+ };
9454
+ const session = {
9455
+ history,
9456
+ graphic: cloneNoteGraphic(note),
9457
+ get workingGraphic() {
9458
+ return cloneNoteGraphic(working);
9459
+ },
9460
+ get dirty() {
9461
+ return dirty;
9462
+ },
9463
+ get modes() {
9464
+ return modes;
9465
+ },
9466
+ close: () => ctx.commit(snapshot),
9467
+ abort: () => ctx.fail(new TacticalDrawAbortError("session")),
9468
+ setModes(next) {
9469
+ if (ctx.settled) return;
9470
+ modes = normaliseNoteModes(next);
9471
+ render();
9472
+ },
9473
+ updateGraphic(updater) {
9474
+ if (ctx.settled) return;
9475
+ const next = normalizeNoteGraphic(updater(cloneNoteGraphic(working)));
9476
+ if (next.kind !== "note" || next.id !== note.id) throw new TypeError("updateGraphic must preserve note kind and id");
9477
+ renderNoteForAdapter(adapter, capability, next, resolveCache());
9478
+ apply(next, "programmatic", "Update graphic");
9479
+ },
9480
+ onChange(listener) {
9481
+ if (ctx.settled) return () => {};
9482
+ return changeEmitter.register(listener);
9483
+ },
9484
+ onCommit(listener) {
9485
+ if (ctx.settled) return () => {};
9486
+ return commitEmitter.register(listener);
9487
+ },
9488
+ onSettled(listener) {
9489
+ return settleEmitter.register(listener);
9490
+ }
9491
+ };
9492
+ /** Pointer pixel in Web Mercator metres. */
9493
+ const groundAt = (pixel) => adapter.fromLonLat(driver.fromPixel(pixel));
9494
+ /**
9495
+ * A width drag: the grabbed edge follows the pointer along the Note's own x
9496
+ * axis, `width` is clamped to its model range, and the centre moves so the
9497
+ * opposite edge keeps its ground position. The height follows the new layout.
9498
+ */
9499
+ const widened = (current, pixel) => {
9500
+ const next = cloneNoteGraphic(current.start);
9501
+ const { start } = current;
9502
+ const em = start.emSize.value;
9503
+ const side = current.index === 1 ? 1 : -1;
9504
+ const axis = [Math.cos(start.rotation) * side, -Math.sin(start.rotation) * side];
9505
+ const pointer = groundAt(pixel);
9506
+ const pulled = (pointer[0] - current.downGround[0]) * axis[0] + (pointer[1] - current.downGround[1]) * axis[1];
9507
+ const width = Math.min(60, Math.max(2, start.width + pulled / em));
9508
+ const shift = (width - start.width) * em / 2;
9509
+ const [cx, cy] = adapter.fromLonLat(start.position);
9510
+ next.position = adapter.toLonLat([cx + axis[0] * shift, cy + axis[1] * shift]);
9511
+ next.width = width;
9512
+ return next;
9513
+ };
9514
+ const transformed = (pixel, info) => {
9515
+ if (!drag) return null;
9516
+ if (drag.kind === "width") return widened(drag, pixel);
9517
+ const next = cloneNoteGraphic(drag.start);
9518
+ const result = drag.fsm.move(pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
9519
+ next.position = [...result.points[0]];
9520
+ const delta = boxScaleRotation(drag.kind, result.box, drag.startBox);
9521
+ if (drag.kind === "scale") {
9522
+ const [min, max] = drag.emSizeRange;
9523
+ const startEm = drag.start.emSize.value;
9524
+ const value = Math.min(max, Math.max(min, startEm * delta.scale));
9525
+ next.emSize = {
9526
+ value,
9527
+ unit: "meters"
9528
+ };
9529
+ if (value !== startEm * delta.scale) {
9530
+ const factor = value / startEm;
9531
+ const { anchor } = drag;
9532
+ const center = driver.toPixel(drag.start.position);
9533
+ if (center) next.position = driver.fromPixel([anchor[0] + (center[0] - anchor[0]) * factor, anchor[1] + (center[1] - anchor[1]) * factor]);
9534
+ }
9535
+ } else if (drag.kind === "rotate") next.rotation = normalizeRotation(next.rotation + delta.rotation);
9536
+ else {
9537
+ const anchorPixel = driver.toPixel(next.position) ?? pixel;
9538
+ const snapped = snap?.({
9539
+ coordinate: next.position,
9540
+ pixel: anchorPixel,
9541
+ interaction: "translate",
9542
+ graphicId: note.id,
9543
+ originalEvent: info?.native
9544
+ });
9545
+ if (snapped) next.position = snapped.coordinate;
9546
+ }
9547
+ return next;
9548
+ };
9549
+ /**
9550
+ * The `emSize` range a scale drag may reach: the limits around the size this
9551
+ * edit started with. `updateGraphic` can set a size outside them, so a drag
9552
+ * from there includes its start value rather than jumping to the limit.
9553
+ */
9554
+ const emSizeRange = (startEm) => [Math.min(startEm, note.emSize.value * NOTE_MIN_SCALE), Math.max(startEm, note.emSize.value * NOTE_MAX_SCALE)];
9555
+ const onDown = (pixel, info) => {
9556
+ if (ctx.settled || !box || !modes.includes("transform")) return;
9557
+ const tolerance = info?.hitTolerance ?? 12;
9558
+ const hit = pickWidthBoxHandle(box, pixel, tolerance);
9559
+ if (!hit) return;
9560
+ if (hit.kind === "width") drag = {
9561
+ kind: "width",
9562
+ index: hit.index,
9563
+ down: [...pixel],
9564
+ start: cloneNoteGraphic(working),
9565
+ downGround: groundAt(pixel)
9566
+ };
9567
+ else {
9568
+ const shared = {
9569
+ fsm: beginBoxDrag({
9570
+ kind: hit.kind,
9571
+ downPixel: pixel,
9572
+ points: [[...working.position]],
9573
+ projection: {
9574
+ toPixel: (position) => driver.toPixel(position),
9575
+ fromPixel: (coordinate) => driver.fromPixel(coordinate)
9576
+ },
9577
+ box,
9578
+ cornerIndex: hit.kind === "scale" ? hit.index : void 0
9579
+ }),
9580
+ down: [...pixel],
9581
+ start: cloneNoteGraphic(working),
9582
+ startBox: box
9583
+ };
9584
+ drag = hit.kind === "scale" ? {
9585
+ ...shared,
9586
+ kind: "scale",
9587
+ anchor: boxCorners(box)[(hit.index + 2) % 4],
9588
+ emSizeRange: emSizeRange(working.emSize.value)
9589
+ } : {
9590
+ ...shared,
9591
+ kind: hit.kind
9592
+ };
9593
+ }
9594
+ driver.setDragPanEnabled(false);
9595
+ };
9596
+ const onMove = (pixel, info) => {
9597
+ const next = transformed(pixel, info);
9598
+ if (!next) return;
9599
+ working = next;
9600
+ render();
9601
+ };
9602
+ const onUp = (pixel, info) => {
9603
+ if (!drag) return;
9604
+ const current = drag;
9605
+ const next = transformed(pixel, info);
9606
+ drag = null;
9607
+ shell.suppressNextClickAway();
9608
+ driver.setDragPanEnabled(true);
9609
+ working = cloneNoteGraphic(current.start);
9610
+ if (!next) return;
9611
+ if (current.kind === "body" && withinClickSlop(pixel, current.down)) {
9612
+ render();
9613
+ return;
9614
+ }
9615
+ apply(next, "gesture", `${current.kind[0].toUpperCase()}${current.kind.slice(1)}`);
9616
+ };
9617
+ const handle = runEditInteraction({
9618
+ adapter,
9619
+ signal,
9620
+ layers: [previewLayer, handlesLayer],
9621
+ graphicsLayer,
9622
+ previewLayer,
9623
+ handlesLayer,
9624
+ closeOnClickAway,
9625
+ onViewChange: () => render(!Object.is(adapter.getResolution(), paintedResolution)),
9626
+ onBeforeTeardown: (settlement) => settleToGraphics(settlement.status === "committed" ? settlement.value.graphic : void 0),
9627
+ onDown,
9628
+ onMove,
9629
+ onUp,
9630
+ ownsGraphic: (id) => id === note.id,
9631
+ close: () => ctx.commit(snapshot),
9632
+ onForeignPick: onClickAwayGraphicsPick,
9633
+ historySettle: () => history.settle(),
9634
+ facadeOnSettled: onSettled,
9635
+ emitSettle: (settlement) => settleFromInteraction(settlement, commitEmitter, settleEmitter),
9636
+ attach(interaction, createdDriver, createdShell) {
9637
+ ctx = interaction;
9638
+ driver = createdDriver;
9639
+ shell = createdShell;
9640
+ render();
9641
+ onSession?.(session);
9642
+ }
9643
+ });
9644
+ return {
9645
+ promise: handle.promise,
9646
+ get settled() {
9647
+ return handle.settled;
9648
+ },
9649
+ get pointerCycleConsumed() {
9650
+ return handle.pointerCycleConsumed;
9651
+ },
9652
+ get usesGraphicStack() {
9653
+ return usesGraphicStack;
9654
+ },
9655
+ measureId: note.id,
9656
+ graphicKind: "note",
9657
+ abort: handle.abort,
9658
+ refreshNoteRender: () => render(),
9659
+ syncHostMembership(present) {
9660
+ if (handle.settled || usesGraphicStack === present) return;
9661
+ const previous = usesGraphicStack;
9662
+ usesGraphicStack = present;
9663
+ try {
9664
+ render();
9665
+ } catch (error) {
9666
+ usesGraphicStack = previous;
9667
+ throw error;
9668
+ }
9669
+ }
9670
+ };
9671
+ }
9672
+ //#endregion
8896
9673
  //#region src/tactical-draw/marker-draw-controller.ts
8897
9674
  /** Default icon height for a drawn marker when the draft omits `size`. */
8898
9675
  const DEFAULT_MARKER_SIZE = {
@@ -9315,6 +10092,9 @@ var GraphicStackCoordinator = class {
9315
10092
  * shared across every façade in the JS realm guarantees revisions never repeat.
9316
10093
  */
9317
10094
  let nextGraphicGroupRevision = 0;
10095
+ function sameFeatures(a, b) {
10096
+ return JSON.stringify(a) === JSON.stringify(b);
10097
+ }
9318
10098
  /**
9319
10099
  * `TacticalDraw` façade — slice #6 (issue #45).
9320
10100
  *
@@ -9347,6 +10127,7 @@ var TacticalDraw = class {
9347
10127
  currentEditModifiers = () => this.editModifiers;
9348
10128
  pointSymbols;
9349
10129
  images;
10130
+ notes;
9350
10131
  markers;
9351
10132
  snappingOptions;
9352
10133
  resolveSnap;
@@ -9392,7 +10173,6 @@ var TacticalDraw = class {
9392
10173
  * not as a programmatic preemption.
9393
10174
  */
9394
10175
  deferredGraphicsPick = null;
9395
- idCounter = 0;
9396
10176
  editCounter = 0;
9397
10177
  transformCounter = 0;
9398
10178
  /** Snapshot of the host's latest authoritative Graphic membership and order. */
@@ -9427,6 +10207,9 @@ var TacticalDraw = class {
9427
10207
  */
9428
10208
  lastSeenPointSymbolGeneration;
9429
10209
  lastSeenImageGeneration;
10210
+ lastSeenNoteGeneration;
10211
+ /** Note rasters per density step and last known Note heights (ADR-0069). */
10212
+ noteResolveCache = createNoteResolveCache();
9430
10213
  lastSeenMarkerGeneration;
9431
10214
  /**
9432
10215
  * Ids of graphics currently carrying a passive selection-highlight outline
@@ -9472,11 +10255,13 @@ var TacticalDraw = class {
9472
10255
  context: { labelSizeBand: interactiveLabelSizeBand(this.labelSizeBand) }
9473
10256
  };
9474
10257
  this.defaultInteractionStyle = options?.interactionStyle;
9475
- this.generateId = options?.generateId ?? (() => `td-${++this.idCounter}`);
10258
+ this.generateId = options?.generateId ?? defaultIdGenerator();
9476
10259
  this.pointSymbols = options?.pointSymbols;
9477
10260
  this.images = options?.images;
9478
10261
  this.lastSeenPointSymbolGeneration = this.pointSymbols?.generation;
9479
10262
  this.lastSeenImageGeneration = this.images?.generation;
10263
+ this.notes = options?.notes;
10264
+ this.lastSeenNoteGeneration = this.notes?.generation;
9480
10265
  this.markers = options?.markers;
9481
10266
  this.lastSeenMarkerGeneration = this.markers?.generation;
9482
10267
  this.snappingOptions = options?.snapping;
@@ -9649,19 +10434,25 @@ var TacticalDraw = class {
9649
10434
  const pinnable = isPinnableGraphic(graphic);
9650
10435
  const pinRevision = pinnable ? this.pins.revision(graphic.id) : void 0;
9651
10436
  const cached = this.graphicGroupCache.get(graphic);
9652
- if (cached && cached.pinRevision === pinRevision) {
10437
+ const noteGeneration = isNoteGraphic(graphic) ? this.notes?.generation : void 0;
10438
+ if (cached && cached.pinRevision === pinRevision && cached.noteGeneration === noteGeneration) {
9653
10439
  if (cached.dependence === "none") return cached.group;
9654
10440
  if (cached.dependence === "resolution" && Object.is(cached.resolution, this.adapter.getResolution())) return cached.group;
9655
10441
  }
9656
10442
  const presentation = pinnable ? this.pins.resolve(graphic.id) : void 0;
9657
10443
  const dependence = presentation && this.graphicUsesPinPresentation(graphic, presentation) ? "none" : graphicViewDependence(graphic, this.adapter.scalesGroundPointSymbolsNatively === true);
9658
10444
  const resolution = dependence === "none" ? void 0 : this.adapter.getResolution();
9659
- const group = this.buildGraphicGroup(graphic, presentation);
10445
+ const built = this.buildGraphicGroup(graphic, presentation);
10446
+ const group = cached && isNoteGraphic(graphic) && sameFeatures(cached.group.features, built.features) ? {
10447
+ ...built,
10448
+ revision: cached.group.revision
10449
+ } : built;
9660
10450
  this.graphicGroupCache.set(graphic, {
9661
10451
  group,
9662
10452
  dependence,
9663
10453
  resolution,
9664
- pinRevision
10454
+ pinRevision,
10455
+ noteGeneration
9665
10456
  });
9666
10457
  return group;
9667
10458
  }
@@ -9711,6 +10502,17 @@ var TacticalDraw = class {
9711
10502
  revision
9712
10503
  };
9713
10504
  }
10505
+ if (isNoteGraphic(graphic)) {
10506
+ if (!this.notes) throw new NoteCapabilityRequiredError();
10507
+ const plan = renderNoteForAdapter(this.adapter, this.notes, graphic, this.noteResolveCache);
10508
+ return {
10509
+ id: graphic.id,
10510
+ features: plan.features,
10511
+ iconResources: [],
10512
+ ...plan.overlay ? { imageOverlays: [plan.overlay] } : {},
10513
+ revision
10514
+ };
10515
+ }
9714
10516
  if (isMarker(graphic)) {
9715
10517
  if (!this.markers) throw new MarkerCapabilityRequiredError();
9716
10518
  const presentation = resolved ?? this.pins.resolve(graphic.id);
@@ -9751,19 +10553,35 @@ var TacticalDraw = class {
9751
10553
  if (clearBodies) {
9752
10554
  this.pinBodies = /* @__PURE__ */ new WeakMap();
9753
10555
  this.markerRenders = /* @__PURE__ */ new WeakMap();
10556
+ this.forgetNoteRasters();
9754
10557
  }
9755
10558
  this.graphicGroupCache = /* @__PURE__ */ new WeakMap();
9756
10559
  }
10560
+ forgetNoteRasters() {
10561
+ this.noteResolveCache = {
10562
+ heights: this.noteResolveCache.heights,
10563
+ rasters: /* @__PURE__ */ new WeakMap()
10564
+ };
10565
+ }
9757
10566
  /** Refresh capability-dependent renders before any caller-visible state is mutated. */
9758
10567
  refreshCapabilityGenerations() {
9759
10568
  const currentPointSymbolGeneration = this.pointSymbols?.generation;
9760
10569
  const currentImageGeneration = this.images?.generation;
9761
10570
  const currentMarkerGeneration = this.markers?.generation;
9762
- if (currentPointSymbolGeneration !== this.lastSeenPointSymbolGeneration || currentImageGeneration !== this.lastSeenImageGeneration || currentMarkerGeneration !== this.lastSeenMarkerGeneration) {
9763
- this.invalidateGraphicGroupCache();
10571
+ const currentNoteGeneration = this.notes?.generation;
10572
+ const notesChanged = currentNoteGeneration !== this.lastSeenNoteGeneration;
10573
+ const othersChanged = currentPointSymbolGeneration !== this.lastSeenPointSymbolGeneration || currentImageGeneration !== this.lastSeenImageGeneration || currentMarkerGeneration !== this.lastSeenMarkerGeneration;
10574
+ if (notesChanged || othersChanged) {
10575
+ if (othersChanged) this.invalidateGraphicGroupCache();
10576
+ else this.forgetNoteRasters();
9764
10577
  this.lastSeenPointSymbolGeneration = currentPointSymbolGeneration;
9765
10578
  this.lastSeenImageGeneration = currentImageGeneration;
10579
+ this.lastSeenNoteGeneration = currentNoteGeneration;
9766
10580
  this.lastSeenMarkerGeneration = currentMarkerGeneration;
10581
+ if (notesChanged) {
10582
+ if (this.activeEdit && "refreshNoteRender" in this.activeEdit) this.activeEdit.refreshNoteRender();
10583
+ this.activeTransform?.refreshNoteRenders();
10584
+ }
9767
10585
  }
9768
10586
  }
9769
10587
  /** Submit one complete grouped desired state for the host stack plus overrides. */
@@ -9880,7 +10698,7 @@ var TacticalDraw = class {
9880
10698
  seen.add(m.id);
9881
10699
  }
9882
10700
  this.refreshCapabilityGenerations();
9883
- for (const graphic of measures) if (isImageGraphic(graphic) || isMarker(graphic)) this.renderGraphicGroup(graphic);
10701
+ for (const graphic of measures) if (isImageGraphic(graphic) || isNoteGraphic(graphic) || isMarker(graphic)) this.renderGraphicGroup(graphic);
9884
10702
  const activeEdit = this.activeEdit;
9885
10703
  const constructingSession = activeEdit ? null : this.activeInteraction.session;
9886
10704
  const constructingGraphic = constructingSession && "workingGraphic" in constructingSession ? constructingSession.workingGraphic : void 0;
@@ -10021,6 +10839,10 @@ var TacticalDraw = class {
10021
10839
  if (!this.images) return null;
10022
10840
  return imageFootprint(graphic, renderImageForAdapter(this.adapter, this.images, graphic).render, this.adapter)?.box ?? null;
10023
10841
  }
10842
+ if (isNoteGraphic(graphic)) {
10843
+ if (!this.notes) return null;
10844
+ return noteFootprint(graphic, renderNoteForAdapter(this.adapter, this.notes, graphic, this.noteResolveCache).render, this.adapter)?.box ?? null;
10845
+ }
10024
10846
  if (isMarker(graphic)) {
10025
10847
  if (!this.markers) return null;
10026
10848
  return markerFootprint(graphic, this.markerRender(graphic), this.adapter)?.box ?? null;
@@ -10136,6 +10958,21 @@ var TacticalDraw = class {
10136
10958
  }
10137
10959
  draw(draft, options) {
10138
10960
  this.assertAlive();
10961
+ if (draft.kind === "note") {
10962
+ if (!this.notes) throw new NoteCapabilityRequiredError();
10963
+ const preempt = this.guardAndPreempt();
10964
+ if (preempt) return preempt;
10965
+ return this.runWithSlot((onSettled) => runNoteDraw({
10966
+ adapter: this.adapter,
10967
+ capability: this.notes,
10968
+ draft,
10969
+ previewLayer: this.previewLayer,
10970
+ generateId: this.generateId,
10971
+ signal: options?.signal,
10972
+ onSettled,
10973
+ snap: this.resolveSnap
10974
+ }), null);
10975
+ }
10139
10976
  if (draft.kind === "marker") {
10140
10977
  if (!this.markers) throw new MarkerCapabilityRequiredError();
10141
10978
  const preempt = this.guardAndPreempt();
@@ -10367,6 +11204,45 @@ var TacticalDraw = class {
10367
11204
  };
10368
11205
  });
10369
11206
  }
11207
+ if (isNoteGraphic(measure)) {
11208
+ normaliseNoteModes(options?.modes);
11209
+ if (!this.notes) throw new NoteCapabilityRequiredError();
11210
+ const preempt = this.guardAndPreempt();
11211
+ if (preempt) return preempt;
11212
+ const wasOnGraphicsLayer = this.lastRenderedMeasures.some((g) => g.id === measure.id);
11213
+ const handleIdPrefix = `__td_edit_${++this.editCounter}__`;
11214
+ return this.runWithSlot((onSettled) => runNoteEdit({
11215
+ adapter: this.adapter,
11216
+ capability: this.notes,
11217
+ resolveCache: () => this.noteResolveCache,
11218
+ note: measure,
11219
+ graphicsLayer: this.graphicsLayer,
11220
+ previewLayer: this.previewLayer,
11221
+ handlesLayer: this.handlesLayer,
11222
+ signal: options?.signal,
11223
+ closeOnClickAway: options?.closeOnClickAway,
11224
+ modes: options?.modes,
11225
+ interactionStyle: this.resolveInteractionStyle(options?.interactionStyle),
11226
+ onSession: this.trackSession(options?.onSession),
11227
+ handleIdPrefix,
11228
+ settleToGraphics: (settled) => this.settleWorkingGraphics([{
11229
+ id: measure.id,
11230
+ committed: settled
11231
+ }]),
11232
+ publishWorkingGraphic: (group) => this.publishWorkingGraphics([group]),
11233
+ wasOnGraphicsLayer,
11234
+ onSettled,
11235
+ onClickAwayGraphicsPick: (event) => this.dispatchHostPick(this.graphicsLayer, event),
11236
+ snap: this.resolveSnap,
11237
+ editModifiers: this.currentEditModifiers
11238
+ }), (handle) => {
11239
+ handle.syncHostMembership(this.lastRenderedMeasures.some((graphic) => graphic.id === handle.measureId && isNoteGraphic(graphic)));
11240
+ this.activeEdit = handle;
11241
+ return () => {
11242
+ if (this.activeEdit === handle) this.activeEdit = null;
11243
+ };
11244
+ });
11245
+ }
10370
11246
  normaliseModes(options?.modes);
10371
11247
  const preempt = this.guardAndPreempt();
10372
11248
  if (preempt) return preempt;
@@ -10428,6 +11304,7 @@ var TacticalDraw = class {
10428
11304
  }
10429
11305
  if (measures.some(isPointSymbol) && !this.pointSymbols) throw new PointSymbolCapabilityRequiredError();
10430
11306
  if (measures.some(isImageGraphic) && !this.images) throw new ImageCapabilityRequiredError();
11307
+ if (measures.some(isNoteGraphic) && !this.notes) throw new NoteCapabilityRequiredError();
10431
11308
  if (measures.some(isMarker) && !this.markers) throw new MarkerCapabilityRequiredError();
10432
11309
  const preempt = this.guardAndPreempt();
10433
11310
  if (preempt) return preempt;
@@ -10444,6 +11321,8 @@ var TacticalDraw = class {
10444
11321
  adapter: this.adapter,
10445
11322
  capability: this.pointSymbols,
10446
11323
  imageCapability: this.images,
11324
+ noteCapability: this.notes,
11325
+ noteResolveCache: () => this.noteResolveCache,
10447
11326
  markerCapability: this.markers,
10448
11327
  ...this.pointSymbols || this.markers ? { renderPin: (graphic) => this.buildGraphicGroup(graphic) } : {},
10449
11328
  graphics: measures,
@@ -10861,6 +11740,16 @@ var TacticalDraw = class {
10861
11740
  }
10862
11741
  };
10863
11742
  /**
11743
+ * `td-<8 random hex digits>-<n>`: the random prefix keeps ids from one instance
11744
+ * clear of graphics saved from another. `getRandomValues` also works outside
11745
+ * secure contexts, unlike `randomUUID`.
11746
+ */
11747
+ function defaultIdGenerator() {
11748
+ const prefix = crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, "0");
11749
+ let n = 0;
11750
+ return () => `td-${prefix}-${++n}`;
11751
+ }
11752
+ /**
10864
11753
  * The graphics-stack group for a pin-presented point symbol or marker
10865
11754
  * (ADR-0056): a pickable ground point plus the adapter-drawn billboard.
10866
11755
  */
@@ -10900,6 +11789,7 @@ function graphicViewDependence(graphic, nativePointSymbolScaling) {
10900
11789
  return graphic.size.unit === "meters" && !nativePointSymbolScaling ? "resolution" : "none";
10901
11790
  }
10902
11791
  if (isImageGraphic(graphic)) return "none";
11792
+ if (isNoteGraphic(graphic)) return "resolution";
10903
11793
  if (isMarker(graphic)) return markerScalesWithResolution(graphic, nativePointSymbolScaling) ? "resolution" : "none";
10904
11794
  return measureRendersFromViewState(graphic) ? "resolution" : "none";
10905
11795
  }
@@ -10993,6 +11883,12 @@ const BUILT_IN_INTERACTION_STYLE = {
10993
11883
  fillColor: "#ffffff",
10994
11884
  strokeColor: "#4f7cff",
10995
11885
  strokeWidth: 2
11886
+ },
11887
+ widthHandle: {
11888
+ pointRadius: 5,
11889
+ fillColor: "#ffffff",
11890
+ strokeColor: "#4f7cff",
11891
+ strokeWidth: 2
10996
11892
  }
10997
11893
  };
10998
11894
  const HANDLE_SLOTS = [
@@ -11005,7 +11901,8 @@ const HANDLE_SLOTS = [
11005
11901
  "snapTargetHandle",
11006
11902
  "activeSnapTargetHandle",
11007
11903
  "scaleHandle",
11008
- "rotateHandle"
11904
+ "rotateHandle",
11905
+ "widthHandle"
11009
11906
  ];
11010
11907
  /**
11011
11908
  * Per-slot, per-property shallow merge with explicit-undefined-unsets
@@ -11309,4 +12206,4 @@ function nearestWorldCopyPosition(position, refLng) {
11309
12206
  return [nearestWorldCopyLng(position[0], refLng), ...position.slice(1)];
11310
12207
  }
11311
12208
  //#endregion
11312
- export { BaseMapAdapter, DEFAULT_EDIT_MODIFIERS, DEFAULT_LABEL_SIZE_PIXELS, DEFAULT_MARKER_SIZE, DEFAULT_PIN_PRESENTATION, DEFAULT_TEXT_SIZE_MAX_PIXELS, DEFAULT_TEXT_SIZE_MIN_PIXELS, HATCH_PATTERNS, HIGHLIGHT_BAND_SLOTS, HIGHLIGHT_CASING_OUTSET_CSS_PIXELS, HIGHLIGHT_GLOW_BANDS, ImageCapabilityRequiredError, MINE_PATTERN_TILE_SIZE, MarkerCapabilityRequiredError, PinPresentationStore, PointSymbolCapabilityRequiredError, PointerCallbackHub, TEXT_FADE_END_RATIO, TEXT_HALO_BREAKPOINT_PIXELS, TEXT_HALO_COLOR, TOUCH_HIT_TOLERANCE_PX, TacticalDraw, TacticalDrawAbortError, TacticalDrawDestroyedError, alignPointSymbolIndicator, bindAbortable, canResetGroundSizes, cloneImageGraphic, cloneMarker, clonePointSymbol, coerceHandleStyle, combinePinScale, combineWithHostSignal, convertPointSymbolPlacement, effectivePointSymbolPixelSize, evaluatePickCandidates, fillPatternImageDimension, fillPatternImageId, getSizeAnchor, hasHighlightCasing, highlightBandsForStyle, highlightBandsInPaintOrder, highlightCasingWidth, hitTestFeature, hitTestIconFeature, ignoreAbort, imageFootprint, imageOpacity, isAnchoredGraphic, isImageGraphic, isMarker, isMinePattern, isPinnableGraphic, isPointSymbol, isTacticalDrawAbortError, isValidPinNumber, makeFillPatternImage, markerFootprint, markerOpacity, mergeNativeAndCachedPickFeatures, movePointSymbolLocation, nearestWorldCopyLng, nearestWorldCopyPosition, normalizeImageGraphic, normalizeMarker, parseColor, pickHitTolerance, pickPointerType, pinDistanceScale, pinZoomScale, placePointSymbol, pointSymbolFootprint, pointSymbolResource, renderOrderToVisualOrder, resetGroundSizeOptions, resizePointSymbolSize, resolveGroundTextSizePixels, resolveHighlightBands, resolveHighlightCasing, resolveMarkerRender, resolvePickPresentation, resolvePinPresentation, resolvePointSymbolOffset, resolveTextAppearance, resolveTextHaloWidth, resolveTextSizePixels, scalePointSymbolLayout, tryControlMeasureIdFromFeature, validateImageGraphic, validateMarker };
12209
+ export { BaseMapAdapter, DEFAULT_EDIT_MODIFIERS, DEFAULT_LABEL_SIZE_PIXELS, DEFAULT_MARKER_SIZE, DEFAULT_PIN_PRESENTATION, DEFAULT_TEXT_SIZE_MAX_PIXELS, DEFAULT_TEXT_SIZE_MIN_PIXELS, HATCH_PATTERNS, HIGHLIGHT_BAND_SLOTS, HIGHLIGHT_CASING_OUTSET_CSS_PIXELS, HIGHLIGHT_GLOW_BANDS, ImageCapabilityRequiredError, MINE_PATTERN_TILE_SIZE, MarkerCapabilityRequiredError, NOTE_MAX_RASTER_PIXELS, NOTE_MAX_WIDTH, NOTE_MIN_WIDTH, NoteCapabilityRequiredError, PinPresentationStore, PointSymbolCapabilityRequiredError, PointerCallbackHub, TEXT_FADE_END_RATIO, TEXT_HALO_BREAKPOINT_PIXELS, TEXT_HALO_COLOR, TOUCH_HIT_TOLERANCE_PX, TacticalDraw, TacticalDrawAbortError, TacticalDrawDestroyedError, alignPointSymbolIndicator, bindAbortable, canResetGroundSizes, cloneImageGraphic, cloneMarker, cloneNoteGraphic, clonePointSymbol, coerceHandleStyle, combinePinScale, combineWithHostSignal, composeMarkerCapabilities, convertPointSymbolPlacement, effectivePointSymbolPixelSize, evaluatePickCandidates, fillPatternImageDimension, fillPatternImageId, getSizeAnchor, hasHighlightCasing, highlightBandsForStyle, highlightBandsInPaintOrder, highlightCasingWidth, hitTestFeature, hitTestIconFeature, ignoreAbort, imageFootprint, imageOpacity, isAnchoredGraphic, isImageGraphic, isMarker, isMinePattern, isNoteGraphic, isPinnableGraphic, isPointSymbol, isTacticalDrawAbortError, isValidPinNumber, makeFillPatternImage, markerFootprint, markerOpacity, mergeNativeAndCachedPickFeatures, movePointSymbolLocation, nearestWorldCopyLng, nearestWorldCopyPosition, normalizeImageGraphic, normalizeMarker, normalizeNoteGraphic, noteFootprint, noteOpacity, parseColor, pickHitTolerance, pickPointerType, pinDistanceScale, pinZoomScale, placePointSymbol, pointSymbolFootprint, pointSymbolResource, renderNoteForAdapter, renderOrderToVisualOrder, resetGroundSizeOptions, resizePointSymbolSize, resolveGroundTextSizePixels, resolveHighlightBands, resolveHighlightCasing, resolveMarkerRender, resolvePickPresentation, resolvePinPresentation, resolvePointSymbolOffset, resolveTextAppearance, resolveTextHaloWidth, resolveTextSizePixels, scalePointSymbolLayout, tryControlMeasureIdFromFeature, validateImageGraphic, validateMarker, validateNoteGraphic };