@orbat-mapper/tactical-draw 0.31.1 → 0.33.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.d.mts CHANGED
@@ -584,18 +584,26 @@ type NoteEmSize = {
584
584
  value: number;
585
585
  unit: "meters";
586
586
  };
587
- /** A stroke in em. On a frame's border, `"double"` makes `width` two rules and their gap. */
587
+ /**
588
+ * A stroke in em. On a frame's border, `"double"` makes `width` two rules and their gap,
589
+ * and `"dashed"` uses the browser's dash pattern.
590
+ */
588
591
  interface NoteStroke {
589
592
  color: string;
590
593
  width: number;
591
- style?: "solid" | "double";
594
+ style?: "solid" | "double" | "dashed";
592
595
  }
593
596
  /** Built-in frame preset names. */
594
- type NoteFramePresetId = "plate" | "card" | "alert" | "dark" | "field" | "minimal" | "friendly" | "enemy" | "title" | "site" | "narrative";
597
+ type NoteFramePresetId = "basic" | "plate" | "card" | "alert" | "dark" | "field" | "minimal" | "friendly" | "enemy" | "friendly-solid" | "enemy-solid" | "title" | "site" | "narrative";
595
598
  /** Horizontal alignment of a Note's headings within the content width. */
596
599
  type NoteHeadingAlign = "start" | "center" | "end";
597
600
  /** Horizontal alignment of a Note's paragraphs within the content width. */
598
601
  type NoteBodyAlign = NoteHeadingAlign;
602
+ /**
603
+ * How a Note's paragraphs and lists are set: `"italic"`, `"light"` (weight 300) or
604
+ * `"caps"` (capitals). Headings keep their own style.
605
+ */
606
+ type NoteBodyStyle = "regular" | "italic" | "light" | "caps";
599
607
  /** Font families by typographic role. */
600
608
  interface NoteFontRoles {
601
609
  heading: string;
@@ -609,6 +617,10 @@ interface NoteFrameTokenOverrides {
609
617
  accentText?: string;
610
618
  textColor?: string;
611
619
  padding?: number;
620
+ /** Inset at the left and right. Defaults to `padding`. */
621
+ paddingX?: number;
622
+ /** Inset at the top and bottom. Defaults to `padding`. */
623
+ paddingY?: number;
612
624
  cornerRadius?: number;
613
625
  blockSpacing?: number;
614
626
  lineHeight?: number;
@@ -619,10 +631,20 @@ interface NoteFrameTokenOverrides {
619
631
  headingAlign?: NoteHeadingAlign;
620
632
  /** Where paragraphs sit within the content width. Defaults to `"start"`; lists stay there. */
621
633
  bodyAlign?: NoteBodyAlign;
634
+ /** How paragraphs and lists are set. Defaults to `"regular"`. */
635
+ bodyStyle?: NoteBodyStyle;
622
636
  /** Multiplies the heading sizes, 1.5 em for level 1 and 1.2 em for level 2. */
623
637
  headingScale?: number;
624
638
  /** Sets headings bold. Defaults to `true`; when false, headings are regular weight. */
625
639
  headingBold?: boolean;
640
+ /** Sets level-1 headings bold or regular. Defaults to `headingBold`. */
641
+ heading1Bold?: boolean;
642
+ /** Sets level-2 headings bold or regular. Defaults to `headingBold`. */
643
+ heading2Bold?: boolean;
644
+ /** Colour of level-1 headings outside the header band. Defaults to `textColor`. */
645
+ heading1Color?: string;
646
+ /** Colour of level-2 headings outside the header band. Defaults to `textColor`. */
647
+ heading2Color?: string;
626
648
  /** Added after each heading character, as a fraction of the heading's size. */
627
649
  headingLetterSpacing?: number;
628
650
  /** Sets a heading's lowercase letters as smaller capitals. */
@@ -630,7 +652,8 @@ interface NoteFrameTokenOverrides {
630
652
  fonts?: Partial<NoteFontRoles>;
631
653
  }
632
654
  interface NoteFrame {
633
- preset: NoteFramePresetId;
655
+ /** The preset; without one, `"basic"`. */
656
+ preset?: NoteFramePresetId;
634
657
  tokens?: NoteFrameTokenOverrides;
635
658
  }
636
659
  interface NoteGraphicStyle {
@@ -648,7 +671,8 @@ interface NoteGraphic {
648
671
  emSize: NoteEmSize;
649
672
  /** Total box width in em, frame included (2 to 60). */
650
673
  width: number;
651
- frame: NoteFrame;
674
+ /** The frame; without one, the `"basic"` preset as is. */
675
+ frame?: NoteFrame;
652
676
  /** Markdown text and images, opaque to TacticalDraw. Any string is valid, even an empty one. */
653
677
  content: string;
654
678
  name?: string;
@@ -665,6 +689,11 @@ interface NoteRaster {
665
689
  * this the box height is only as exact as the raster's aspect ratio.
666
690
  */
667
691
  heightEm?: number;
692
+ /**
693
+ * The Note's width in em when the raster was drawn. While a Note's raster for a new
694
+ * width is still drawing, the previous one is shown at this width instead of stretched.
695
+ */
696
+ widthEm?: number;
668
697
  }
669
698
  /**
670
699
  * Host-supplied note rasteriser (ADR-0066, ADR-0069). `resolve` is synchronous:
@@ -674,6 +703,12 @@ interface NoteRaster {
674
703
  */
675
704
  interface NoteCapability {
676
705
  resolve(note: NoteGraphic, pxPerEm: number): NoteRaster | "pending";
706
+ /**
707
+ * The height in em the Note lays out to, measured synchronously, or `undefined` while
708
+ * that isn't known yet. With it, the box follows a content or width edit at once,
709
+ * while the raster catches up; without it, the box height waits for the raster.
710
+ */
711
+ measure?(note: NoteGraphic): number | undefined;
677
712
  /** Monotonic host-owned revision, bumped whenever a pending raster becomes ready. */
678
713
  readonly generation?: number;
679
714
  /** When note rasters fade out (ADR-0069). Each threshold has a default. */
@@ -1665,6 +1700,11 @@ interface SnapCandidateRequest {
1665
1700
  pixel: PixelCoordinate;
1666
1701
  interaction: SnapInteraction;
1667
1702
  graphicId?: string;
1703
+ /**
1704
+ * Every graphic a multi-selection moves together; candidates of any of them
1705
+ * are skipped, so the group never snaps onto itself. Set instead of `graphicId`.
1706
+ */
1707
+ graphicIds?: readonly string[];
1668
1708
  controlPointIndex?: number;
1669
1709
  originalEvent?: unknown;
1670
1710
  }
@@ -1676,6 +1716,14 @@ interface SnapCandidate {
1676
1716
  controlPointIndex?: number;
1677
1717
  priority?: number;
1678
1718
  }
1719
+ /**
1720
+ * Host snap candidates near `request`. A provider that leaves out the moving
1721
+ * graphic's own candidates should check `request.graphicIds` (a multi-selection)
1722
+ * as well as `request.graphicId`. A move or scale that tests several
1723
+ * points of a graphic (a control measure's control points, a Note's or an
1724
+ * Image's corners and centre) asks once per tested point on each pointer move,
1725
+ * so keep it cheap: return only candidates near `request.pixel`.
1726
+ */
1679
1727
  type SnapCandidateProvider = (request: SnapCandidateRequest) => readonly SnapCandidate[];
1680
1728
  /**
1681
1729
  * A snap the host answers later, such as one to terrain it has to sample
@@ -1732,11 +1780,11 @@ type DrawImageDraft = Pick<ImageGraphic, "kind" | "resourceId" | "intrinsicSize"
1732
1780
  //#endregion
1733
1781
  //#region src/tactical-draw/note-draw-controller.d.ts
1734
1782
  /**
1735
- * A Note to place with one click. The host supplies the content (`content`)
1736
- * and `frame`; everything else defaults: `emSize` to 14 screen px at the
1783
+ * A Note to place with one click. The host supplies the content (`content`);
1784
+ * everything else defaults: `frame` to the basic preset, `emSize` to 14 screen px at the
1737
1785
  * current resolution and `width` to 24 em (ADR-0066).
1738
1786
  */
1739
- type DrawNoteDraft = Pick<NoteGraphic, "kind" | "content" | "frame"> & Partial<Omit<NoteGraphic, "kind" | "content" | "frame">>;
1787
+ type DrawNoteDraft = Pick<NoteGraphic, "kind" | "content"> & Partial<Omit<NoteGraphic, "kind" | "content">>;
1740
1788
  //#endregion
1741
1789
  //#region src/tactical-draw/marker-draw-controller.d.ts
1742
1790
  type DrawMarkerDraft = Pick<Marker, "kind" | "symbolId"> & Partial<Omit<Marker, "kind" | "symbolId">>;
@@ -2765,4 +2813,4 @@ declare function nearestWorldCopyLng(lng: number, refLng: number): number;
2765
2813
  /** `nearestWorldCopyLng` applied to a lon/lat position. */
2766
2814
  declare function nearestWorldCopyPosition(position: Position, refLng: number): Position;
2767
2815
  //#endregion
2768
- export { type AnchoredGraphic, BaseMapAdapter, type CombinedAbort, DEFAULT_EDIT_MODIFIERS, DEFAULT_LABEL_SIZE_PIXELS, DEFAULT_MARKER_SIZE, DEFAULT_PIN_PRESENTATION, DEFAULT_TEXT_SIZE_MAX_PIXELS, DEFAULT_TEXT_SIZE_MIN_PIXELS, type DeferredSnapProvider, type DrawImageDraft, type DrawMarkerDraft, type DrawMeasureDraft, type DrawNoteDraft, type DrawOptions, type DrawPointSymbolDraft, type DrawSession, type EditChangeEvent, type EditManyOptions, type EditMode, type EditModifiers, type EditOptions, type EditPointerDriver, type EditSession, type FeatureGroup, type FeatureHighlightBand, type Graphic, type GraphicEditChangeEvent, type GraphicEditSession, type GraphicGeometrySnappingOptions, type GraphicRender, type GraphicSnapshot, type GuideStyle, HATCH_PATTERNS, HIGHLIGHT_BAND_SLOTS, HIGHLIGHT_CASING_OUTSET_CSS_PIXELS, HIGHLIGHT_GLOW_BANDS, type HandleStyle, type HatchPattern, type HighlightBand, type HighlightBandSlot, type HighlightCasing, type IconResource, type ImageCapability, ImageCapabilityRequiredError, type ImageFootprint, type ImageGraphic, type ImageGraphicStyle, type ImageIntrinsicSize, type ImageOverlayResource, type ImageRender, type ImageResource, type ImageSize, type InteractionHit, type InteractionStyle, type LabelExtent, type LabelSizeBand, type LayerId, MINE_PATTERN_TILE_SIZE, type MapAdapter, type MapCursor, type MapEvent, type MapEventHandler, type Marker, type MarkerAnchor, type MarkerCapability, MarkerCapabilityRequiredError, type MarkerFootprint, type MarkerIcon, type MarkerRender, type MarkerSize, type MarkerStyle, type MergedPickFeature, type ModifierKey, NOTE_MAX_RASTER_PIXELS, NOTE_MAX_WIDTH, NOTE_MIN_WIDTH, type NativeEventEntry, type NoteBodyAlign, type NoteCapability, NoteCapabilityRequiredError, type NoteEmSize, type NoteFadeThresholds, type NoteFontRoles, type NoteFootprint, type NoteFrame, type NoteFramePresetId, type NoteFrameTokenOverrides, type NoteGraphic, type NoteGraphicStyle, type NoteHeadingAlign, type NoteRaster, type NoteRender, type NoteStroke, type OffsetDragModifier, type PickCandidate, type PickCandidateHit, type PickCandidateHitKind, type PickCandidateInput, type PickEvaluationContext, type PickEvent, type PickHandler, type PickOptions, type PickPointerType, PinFootprint, PinOverridePatch, PinPresentation, PinPresentationCapability, PinPresentationPatch, PinPresentationState, PinPresentationStatus, PinPresentationStatusEvent, PinPresentationStore, PinRender, type PinnableGraphic, type PixelCoordinate, type PointSymbol, type PointSymbolAnchor, type PointSymbolCapability, PointSymbolCapabilityRequiredError, type PointSymbolColors, type PointSymbolConnector, type PointSymbolFootprint, type PointSymbolGraphicModifiers, type PointSymbolOffset, type PointSymbolOffsetControls, type PointSymbolOffsetLayout, type PointSymbolOffsetStyle, type PointSymbolPlacement, type PointSymbolProjection, type PointSymbolRect, type PointSymbolRender, type PointSymbolSize, type PointSymbolStyle, type PointSymbolView, type PointerCallback, PointerCallbackHub, type PointerEventInfo, type ResolvedEditModifiers, type ResolvedPickPresentation, type Rgba, type RotatedScreenBounds, type ScreenBounds, type SessionChangeSource, type SessionHistory, type SessionHistoryState, type SettleReason, type SizeAnchor, type SnapCandidate, type SnapCandidateProvider, type SnapCandidateRequest, type SnapInteraction, type SnapResult, type SnappingOptions, type StyleOptions, TEXT_FADE_END_RATIO, TEXT_HALO_BREAKPOINT_PIXELS, TEXT_HALO_COLOR, TOUCH_HIT_TOLERANCE_PX, TacticalDraw, TacticalDrawAbortError, type TacticalDrawAbortReason, TacticalDrawDestroyedError, type TacticalDrawLayerOptions, type TacticalDrawOptions, type TextAppearance, type TextSizeProps, type TextStyleOptions, type ToPixel, type TransformBox, type TransformChangeEvent, type TransformSession, type TransientChangeEvent, type TransientPhase, 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 };
2816
+ export { type AnchoredGraphic, BaseMapAdapter, type CombinedAbort, DEFAULT_EDIT_MODIFIERS, DEFAULT_LABEL_SIZE_PIXELS, DEFAULT_MARKER_SIZE, DEFAULT_PIN_PRESENTATION, DEFAULT_TEXT_SIZE_MAX_PIXELS, DEFAULT_TEXT_SIZE_MIN_PIXELS, type DeferredSnapProvider, type DrawImageDraft, type DrawMarkerDraft, type DrawMeasureDraft, type DrawNoteDraft, type DrawOptions, type DrawPointSymbolDraft, type DrawSession, type EditChangeEvent, type EditManyOptions, type EditMode, type EditModifiers, type EditOptions, type EditPointerDriver, type EditSession, type FeatureGroup, type FeatureHighlightBand, type Graphic, type GraphicEditChangeEvent, type GraphicEditSession, type GraphicGeometrySnappingOptions, type GraphicRender, type GraphicSnapshot, type GuideStyle, HATCH_PATTERNS, HIGHLIGHT_BAND_SLOTS, HIGHLIGHT_CASING_OUTSET_CSS_PIXELS, HIGHLIGHT_GLOW_BANDS, type HandleStyle, type HatchPattern, type HighlightBand, type HighlightBandSlot, type HighlightCasing, type IconResource, type ImageCapability, ImageCapabilityRequiredError, type ImageFootprint, type ImageGraphic, type ImageGraphicStyle, type ImageIntrinsicSize, type ImageOverlayResource, type ImageRender, type ImageResource, type ImageSize, type InteractionHit, type InteractionStyle, type LabelExtent, type LabelSizeBand, type LayerId, MINE_PATTERN_TILE_SIZE, type MapAdapter, type MapCursor, type MapEvent, type MapEventHandler, type Marker, type MarkerAnchor, type MarkerCapability, MarkerCapabilityRequiredError, type MarkerFootprint, type MarkerIcon, type MarkerRender, type MarkerSize, type MarkerStyle, type MergedPickFeature, type ModifierKey, NOTE_MAX_RASTER_PIXELS, NOTE_MAX_WIDTH, NOTE_MIN_WIDTH, type NativeEventEntry, type NoteBodyAlign, type NoteBodyStyle, type NoteCapability, NoteCapabilityRequiredError, type NoteEmSize, type NoteFadeThresholds, type NoteFontRoles, type NoteFootprint, type NoteFrame, type NoteFramePresetId, type NoteFrameTokenOverrides, type NoteGraphic, type NoteGraphicStyle, type NoteHeadingAlign, type NoteRaster, type NoteRender, type NoteStroke, type OffsetDragModifier, type PickCandidate, type PickCandidateHit, type PickCandidateHitKind, type PickCandidateInput, type PickEvaluationContext, type PickEvent, type PickHandler, type PickOptions, type PickPointerType, PinFootprint, PinOverridePatch, PinPresentation, PinPresentationCapability, PinPresentationPatch, PinPresentationState, PinPresentationStatus, PinPresentationStatusEvent, PinPresentationStore, PinRender, type PinnableGraphic, type PixelCoordinate, type PointSymbol, type PointSymbolAnchor, type PointSymbolCapability, PointSymbolCapabilityRequiredError, type PointSymbolColors, type PointSymbolConnector, type PointSymbolFootprint, type PointSymbolGraphicModifiers, type PointSymbolOffset, type PointSymbolOffsetControls, type PointSymbolOffsetLayout, type PointSymbolOffsetStyle, type PointSymbolPlacement, type PointSymbolProjection, type PointSymbolRect, type PointSymbolRender, type PointSymbolSize, type PointSymbolStyle, type PointSymbolView, type PointerCallback, PointerCallbackHub, type PointerEventInfo, type ResolvedEditModifiers, type ResolvedPickPresentation, type Rgba, type RotatedScreenBounds, type ScreenBounds, type SessionChangeSource, type SessionHistory, type SessionHistoryState, type SettleReason, type SizeAnchor, type SnapCandidate, type SnapCandidateProvider, type SnapCandidateRequest, type SnapInteraction, type SnapResult, type SnappingOptions, type StyleOptions, TEXT_FADE_END_RATIO, TEXT_HALO_BREAKPOINT_PIXELS, TEXT_HALO_COLOR, TOUCH_HIT_TOLERANCE_PX, TacticalDraw, TacticalDrawAbortError, type TacticalDrawAbortReason, TacticalDrawDestroyedError, type TacticalDrawLayerOptions, type TacticalDrawOptions, type TextAppearance, type TextSizeProps, type TextStyleOptions, type ToPixel, type TransformBox, type TransformChangeEvent, type TransformSession, type TransientChangeEvent, type TransientPhase, 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 };
package/dist/index.mjs CHANGED
@@ -2097,16 +2097,31 @@ function validateNoteGraphic(note) {
2097
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
2098
  if (note.emSize.unit !== "meters") throw new TypeError("NoteGraphic.emSize.unit must be \"meters\"");
2099
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);
2100
+ if (note.frame !== void 0) {
2101
+ if (!isRecord(note.frame)) throw new TypeError("NoteGraphic.frame must be an object");
2102
+ const { preset, tokens } = note.frame;
2103
+ if (preset !== void 0 && (typeof preset !== "string" || !preset)) throw new TypeError("NoteGraphic.frame.preset must be a non-empty string");
2104
+ if (tokens !== void 0) validateFrameTokens(tokens);
2105
+ }
2102
2106
  if (typeof note.content !== "string") throw new TypeError("NoteGraphic.content must be a string");
2103
2107
  noteOpacity(note);
2104
2108
  }
2109
+ const NOTE_STROKE_STYLES = [
2110
+ "solid",
2111
+ "double",
2112
+ "dashed"
2113
+ ];
2105
2114
  const NOTE_ALIGNS = [
2106
2115
  "start",
2107
2116
  "center",
2108
2117
  "end"
2109
2118
  ];
2119
+ const NOTE_BODY_STYLES = [
2120
+ "regular",
2121
+ "italic",
2122
+ "light",
2123
+ "caps"
2124
+ ];
2110
2125
  function validateFrameTokens(tokens) {
2111
2126
  const path = "NoteGraphic.frame.tokens";
2112
2127
  if (!isRecord(tokens)) throw new TypeError(`${path} must be an object`);
@@ -2114,10 +2129,14 @@ function validateFrameTokens(tokens) {
2114
2129
  "background",
2115
2130
  "accent",
2116
2131
  "accentText",
2117
- "textColor"
2132
+ "textColor",
2133
+ "heading1Color",
2134
+ "heading2Color"
2118
2135
  ]) optionalString(tokens, key, path);
2119
2136
  for (const key of [
2120
2137
  "padding",
2138
+ "paddingX",
2139
+ "paddingY",
2121
2140
  "cornerRadius",
2122
2141
  "blockSpacing",
2123
2142
  "lineHeight",
@@ -2131,7 +2150,13 @@ function validateFrameTokens(tokens) {
2131
2150
  const band = tokens.headerBand;
2132
2151
  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
2152
  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`);
2153
+ if (tokens.bodyStyle !== void 0 && !NOTE_BODY_STYLES.includes(tokens.bodyStyle)) throw new TypeError(`${path}.bodyStyle must be "regular", "italic", "light" or "caps"`);
2154
+ for (const key of [
2155
+ "headingBold",
2156
+ "heading1Bold",
2157
+ "heading2Bold",
2158
+ "headingSmallCaps"
2159
+ ]) if (tokens[key] !== void 0 && typeof tokens[key] !== "boolean") throw new TypeError(`${path}.${key} must be a boolean`);
2135
2160
  optionalStroke(tokens, "border", path);
2136
2161
  if (tokens.fonts !== void 0) {
2137
2162
  if (!isRecord(tokens.fonts)) throw new TypeError(`${path}.fonts must be an object`);
@@ -2144,7 +2169,7 @@ function optionalString(record, key, path) {
2144
2169
  function optionalStroke(record, key, path) {
2145
2170
  const stroke = record[key];
2146
2171
  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? }`);
2172
+ if (!isRecord(stroke) || typeof stroke.color !== "string" || !(typeof stroke.width === "number" && Number.isFinite(stroke.width) && stroke.width >= 0) || !(stroke.style === void 0 || NOTE_STROKE_STYLES.includes(stroke.style))) throw new TypeError(`${path}.${key} must be null or { color, width, style? }`);
2148
2173
  }
2149
2174
  function isFinitePosition(value) {
2150
2175
  return Array.isArray(value) && value.length >= 2 && Number.isFinite(value[0]) && Number.isFinite(value[1]);
@@ -3081,6 +3106,7 @@ function graphicCandidates(graphics) {
3081
3106
  return candidates;
3082
3107
  }
3083
3108
  function isSelfCandidate(candidate, request) {
3109
+ if (candidate.graphicId !== void 0 && request.graphicIds?.includes(candidate.graphicId)) return true;
3084
3110
  if (request.graphicId === void 0 || candidate.graphicId !== request.graphicId) return false;
3085
3111
  if (request.interaction === "reshape" && request.controlPointIndex !== void 0) return candidate.controlPointIndex === void 0 || candidate.controlPointIndex === request.controlPointIndex;
3086
3112
  return true;
@@ -3134,7 +3160,7 @@ function interpolatePosition(a, b, t) {
3134
3160
  for (let index = 0; index < dimensions; index += 1) position.push(a[index] + (b[index] - a[index]) * t);
3135
3161
  return position;
3136
3162
  }
3137
- function generatedGeometryCandidates(adapter, paths, request, options) {
3163
+ function generatedGeometryCandidates(project, paths, request, options) {
3138
3164
  const resolved = options === true ? {} : options;
3139
3165
  const edges = resolved.edges ?? true;
3140
3166
  const vertices = resolved.vertices ?? false;
@@ -3152,8 +3178,8 @@ function generatedGeometryCandidates(adapter, paths, request, options) {
3152
3178
  for (let index = 1; index < path.positions.length; index += 1) {
3153
3179
  const a = path.positions[index - 1];
3154
3180
  const b = path.positions[index];
3155
- const aPixel = adapter.getPixelFromCoordinate(a);
3156
- const bPixel = adapter.getPixelFromCoordinate(b);
3181
+ const aPixel = project(a);
3182
+ const bPixel = project(b);
3157
3183
  if (!aPixel || !bPixel) continue;
3158
3184
  const t = clampedSegmentParameter(request.pixel, aPixel, bPixel) ?? 0;
3159
3185
  candidates.push({
@@ -3187,30 +3213,23 @@ function createSnapResolver(adapter, getGraphics, getGeometryFeatures, getOption
3187
3213
  }
3188
3214
  return indexedGeometryPaths;
3189
3215
  };
3190
- return (request) => {
3191
- const options = getOptions();
3192
- const clear = () => options?.onSnap?.(null);
3193
- if (!options?.enabled || options.bypass?.(request.originalEvent)) {
3194
- clear();
3195
- return null;
3196
- }
3216
+ /** The snap for `request` under `options`, without reporting it. */
3217
+ const resolve = (request, options, project) => {
3218
+ if (!options?.enabled || options.bypass?.(request.originalEvent)) return null;
3197
3219
  const tolerance = options.tolerancePixels ?? DEFAULT_TOLERANCE_PIXELS;
3198
- if (!Number.isFinite(tolerance) || tolerance < 0) {
3199
- clear();
3200
- return null;
3201
- }
3220
+ if (!Number.isFinite(tolerance) || tolerance < 0) return null;
3202
3221
  const candidateLists = [];
3203
3222
  if (options.sources?.graphics !== false) candidateLists.push(builtInCandidates());
3204
3223
  const graphicGeometry = options.sources?.graphicGeometry;
3205
- if (graphicGeometry) candidateLists.push(generatedGeometryCandidates(adapter, geometryPaths(), request, graphicGeometry));
3224
+ if (graphicGeometry) candidateLists.push(generatedGeometryCandidates(project, geometryPaths(), request, graphicGeometry));
3206
3225
  const external = options.sources?.external?.(request);
3207
3226
  if (external) candidateLists.push(external);
3208
3227
  let best = null;
3209
3228
  for (const list of candidateLists) for (const candidate of list) {
3210
3229
  if (isSelfCandidate(candidate, request)) continue;
3211
- const pixel = adapter.getPixelFromCoordinate(candidate.coordinate);
3230
+ const pixel = project(candidate.coordinate);
3212
3231
  if (!pixel) continue;
3213
- const distancePixels = Math.hypot(pixel[0] - request.pixel[0], pixel[1] - request.pixel[1]);
3232
+ const distancePixels = pixelDistance$1(pixel, request.pixel);
3214
3233
  if (distancePixels > tolerance) continue;
3215
3234
  const priority = candidate.priority ?? 0;
3216
3235
  const bestPriority = best?.candidate.priority ?? 0;
@@ -3222,9 +3241,33 @@ function createSnapResolver(adapter, getGraphics, getGeometryFeatures, getOption
3222
3241
  distancePixels
3223
3242
  };
3224
3243
  }
3225
- options.onSnap?.(best);
3226
3244
  return best;
3227
3245
  };
3246
+ const closest = (requests, cursor) => {
3247
+ const options = getOptions();
3248
+ const pixels = /* @__PURE__ */ new Map();
3249
+ const project = (position) => {
3250
+ if (!pixels.has(position)) pixels.set(position, adapter.getPixelFromCoordinate(position));
3251
+ return pixels.get(position);
3252
+ };
3253
+ let best = null;
3254
+ for (const request of requests) {
3255
+ const result = resolve(request, options, project);
3256
+ if (!result) continue;
3257
+ const rank = cursor ? pixelDistance$1(result.pixel, cursor) : result.distancePixels;
3258
+ if (!best || rank < best.rank || rank === best.rank && result.distancePixels < best.result.distancePixels) best = {
3259
+ request,
3260
+ result,
3261
+ rank
3262
+ };
3263
+ }
3264
+ options?.onSnap?.(best?.result ?? null);
3265
+ return best && {
3266
+ request: best.request,
3267
+ result: best.result
3268
+ };
3269
+ };
3270
+ return Object.assign((request) => closest([request])?.result ?? null, { closest });
3228
3271
  }
3229
3272
  //#endregion
3230
3273
  //#region src/tactical-draw/draw-controller.ts
@@ -6202,47 +6245,58 @@ function runEdit(opts) {
6202
6245
  toDragPixel: (landed) => landed
6203
6246
  };
6204
6247
  }
6205
- /** A body drag snaps its moved first control point; null when it can't be placed. */
6206
- function translateTarget(pixel, info, drag) {
6207
- if (drag.fsm.kind !== "body") return null;
6208
- const first = drag.preDragPoints[0];
6209
- if (!first) return null;
6248
+ /**
6249
+ * Every moved control point of a body drag as a snap target, in order, null
6250
+ * where one can't be placed: the first is what `sources.deferred` is asked
6251
+ * about. Empty for any other box drag.
6252
+ */
6253
+ function translateTargets(pixel, info, drag) {
6254
+ if (drag.fsm.kind !== "body") return [];
6210
6255
  const cursor = driver.fromPixel(pixel);
6211
6256
  const origin = driver.fromPixel(drag.downPixel);
6212
- const anchor = [...first];
6213
- anchor[0] = first[0] + cursor[0] - origin[0];
6214
- anchor[1] = first[1] + cursor[1] - origin[1];
6215
- const anchorPixel = driver.toPixel(anchor);
6216
- if (!anchorPixel) return null;
6217
- return {
6218
- request: {
6219
- coordinate: anchor,
6220
- pixel: anchorPixel,
6221
- interaction: "translate",
6222
- graphicId: measure.id,
6223
- originalEvent: info?.native
6224
- },
6225
- toDragPixel: (landed) => {
6226
- const at = driver.fromPixel(landed);
6227
- return driver.toPixel([origin[0] + at[0] - first[0], origin[1] + at[1] - first[1]]) ?? [pixel[0] + landed[0] - anchorPixel[0], pixel[1] + landed[1] - anchorPixel[1]];
6228
- }
6229
- };
6257
+ const dx = cursor[0] - origin[0];
6258
+ const dy = cursor[1] - origin[1];
6259
+ return drag.preDragPoints.map((point) => {
6260
+ const moved = [...point];
6261
+ moved[0] = point[0] + dx;
6262
+ moved[1] = point[1] + dy;
6263
+ const movedPixel = driver.toPixel(moved);
6264
+ if (!movedPixel) return null;
6265
+ return {
6266
+ request: {
6267
+ coordinate: moved,
6268
+ pixel: movedPixel,
6269
+ interaction: "translate",
6270
+ graphicId: measure.id,
6271
+ originalEvent: info?.native
6272
+ },
6273
+ toDragPixel: (landed) => {
6274
+ const at = driver.fromPixel(landed);
6275
+ return driver.toPixel([origin[0] + at[0] - point[0], origin[1] + at[1] - point[1]]) ?? [pixel[0] + landed[0] - movedPixel[0], pixel[1] + landed[1] - movedPixel[1]];
6276
+ }
6277
+ };
6278
+ });
6230
6279
  }
6231
6280
  /**
6232
6281
  * Runs a drag at `pixel` through the immediate snap sources: the drag pixel
6233
6282
  * they put it at, and the target there for `sources.deferred` to answer.
6283
+ * `targetsAt` lists the points the immediate sources test, null where one
6284
+ * can't be placed; the first is the deferred target. The snap nearest the
6285
+ * cursor wins and is reported once.
6234
6286
  */
6235
- function snapDrag(pixel, targetAt) {
6236
- const target = targetAt(pixel);
6237
- const result = target && snap?.(target.request);
6238
- if (!result) return {
6287
+ function snapDrag(pixel, targetsAt) {
6288
+ const targets = targetsAt(pixel);
6289
+ const candidates = targets.filter((target) => target !== null);
6290
+ const hit = snap?.closest(candidates.map((candidate) => candidate.request), pixel);
6291
+ const winner = hit && candidates.find((candidate) => candidate.request === hit.request);
6292
+ if (!winner) return {
6239
6293
  pixel,
6240
- target
6294
+ target: targets[0] ?? null
6241
6295
  };
6242
- const snapped = target.toDragPixel(result.pixel);
6296
+ const snapped = winner.toDragPixel(hit.result.pixel);
6243
6297
  return {
6244
6298
  pixel: snapped,
6245
- target: targetAt(snapped)
6299
+ target: targetsAt(snapped)[0] ?? null
6246
6300
  };
6247
6301
  }
6248
6302
  const deferred = createDeferredDragSnap(deferredSnap, () => ctx.settled);
@@ -6458,7 +6512,7 @@ function runEdit(opts) {
6458
6512
  function paintDragSnapshot(pixel, info) {
6459
6513
  if (!activeDrag) return;
6460
6514
  const { controlPointIndex } = activeDrag;
6461
- const snapped = snapDrag(pixel, (at) => reshapeTarget(at, info, controlPointIndex));
6515
+ const snapped = snapDrag(pixel, (at) => [reshapeTarget(at, info, controlPointIndex)]);
6462
6516
  moveDeferred(snapped.pixel, snapped.target, (at) => paintDragAt(at, info));
6463
6517
  }
6464
6518
  function paintDragAt(resolvedPixel, info) {
@@ -6512,7 +6566,7 @@ function runEdit(opts) {
6512
6566
  function paintBoxDragSnapshot(pixel, info, constrainRotation = false) {
6513
6567
  if (!activeBoxDrag) return;
6514
6568
  const drag = activeBoxDrag;
6515
- const snapped = snapDrag(pixel, (at) => translateTarget(at, info, drag));
6569
+ const snapped = snapDrag(pixel, (at) => translateTargets(at, info, drag));
6516
6570
  moveDeferred(snapped.pixel, snapped.target, (at) => paintBoxDragAt(at, constrainRotation));
6517
6571
  }
6518
6572
  function paintBoxDragAt(resolvedPixel, constrainRotation) {
@@ -6659,7 +6713,7 @@ function runEdit(opts) {
6659
6713
  renderHandlesLayer();
6660
6714
  return;
6661
6715
  }
6662
- const snapped = snapDrag(pixel, (at) => reshapeTarget(at, info, controlPointIndex));
6716
+ const snapped = snapDrag(pixel, (at) => [reshapeTarget(at, info, controlPointIndex)]);
6663
6717
  deferred.finish(releaseDeferred(snapped.pixel, snapped.target), (finalPixel) => {
6664
6718
  const next = fsm.end(finalPixel, { constrainAngles: constrainHeld(info) });
6665
6719
  transient.emit("end", next, controlPointIndex);
@@ -6696,7 +6750,7 @@ function runEdit(opts) {
6696
6750
  preDragPoints,
6697
6751
  downPixel
6698
6752
  };
6699
- const snapped = snapDrag(pixel, (at) => translateTarget(at, info, drag));
6753
+ const snapped = snapDrag(pixel, (at) => translateTargets(at, info, drag));
6700
6754
  deferred.finish(releaseDeferred(snapped.pixel, snapped.target), (finalPixel) => {
6701
6755
  const finalSnapshot = fsm.move(finalPixel, { constrainRotation: constrainHeld(info) });
6702
6756
  replaceWorkingPoints(preDragPoints);
@@ -7030,6 +7084,17 @@ function renderImageForAdapter(adapter, capability, image) {
7030
7084
  feature: overlayPickFeature(image, "image", coordinates, render.available)
7031
7085
  };
7032
7086
  }
7087
+ /**
7088
+ * The position `x` metres along a rotated box's own x axis (right) and `y` along its
7089
+ * y axis (up) from `position`. `rotation` is clockwise from north, as in
7090
+ * {@link groundBoxCoordinates}.
7091
+ */
7092
+ function offsetGroundPosition(adapter, position, rotation, x, y) {
7093
+ const [centerX, centerY] = adapter.fromLonLat(position);
7094
+ const cos = Math.cos(-rotation);
7095
+ const sin = Math.sin(-rotation);
7096
+ return adapter.toLonLat([centerX + x * cos - y * sin, centerY + x * sin + y * cos]);
7097
+ }
7033
7098
  /** Corners TL, TR, BR, BL in lon/lat of a box rotated clockwise about its centre, in Web Mercator metres. */
7034
7099
  function groundBoxCoordinates(adapter, position, rotation, widthMetres, heightMetres) {
7035
7100
  const [centerX, centerY] = adapter.fromLonLat(position);
@@ -7174,23 +7239,21 @@ function renderNoteForAdapter(adapter, capability, note, cache = createNoteResol
7174
7239
  const emPixels = screenEmPixels(adapter, note);
7175
7240
  const step = densityStep((emPixels ?? FALLBACK_EM_PIXELS) * positiveOr(capability.pixelRatio, 1));
7176
7241
  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));
7242
+ const measured = measuredHeight(capability, note);
7243
+ let pxPerEm = cappedDensity(measured ?? cache.heights.get(note.id) ?? placeholderNoteHeight(note));
7178
7244
  let raster = resolveRaster(capability, note, pxPerEm, cache);
7179
- if (raster) {
7245
+ if (raster && measured === void 0) {
7180
7246
  const exact = cappedDensity(rasterHeightEm(note, raster));
7181
7247
  if (Math.abs(exact - pxPerEm) > pxPerEm * 1e-9) {
7182
7248
  pxPerEm = exact;
7183
7249
  raster = resolveRaster(capability, note, pxPerEm, cache);
7184
7250
  }
7185
7251
  }
7186
- const render = raster ? {
7187
- height: rasterHeightEm(note, raster),
7188
- available: true
7189
- } : {
7190
- height: placeholderNoteHeight(note),
7191
- available: false
7252
+ const render = {
7253
+ height: measured ?? (raster ? rasterHeightEm(note, raster) : placeholderNoteHeight(note)),
7254
+ available: raster !== void 0
7192
7255
  };
7193
- if (raster) cache.heights.set(note.id, render.height);
7256
+ if (measured !== void 0 || raster) cache.heights.set(note.id, render.height);
7194
7257
  const fade = emPixels === void 0 ? 1 : noteFade(emPixels, pxPerEm, capability.fade);
7195
7258
  const coordinates = groundBoxCoordinates(adapter, note.position, note.rotation, note.width * note.emSize.value, render.height * note.emSize.value);
7196
7259
  if (fade === 0) return {
@@ -7204,15 +7267,36 @@ function renderNoteForAdapter(adapter, capability, note, cache = createNoteResol
7204
7267
  url: raster.url,
7205
7268
  width: raster.width,
7206
7269
  height: raster.height,
7207
- coordinates,
7270
+ coordinates: rasterCoordinates(adapter, note, render.height, raster) ?? coordinates,
7208
7271
  opacity: noteOpacity(note) * fade
7209
7272
  } } : {},
7210
7273
  features: [overlayPickFeature(note, "note", coordinates, render.available)]
7211
7274
  };
7212
7275
  }
7213
- /** The box height a ready raster stands for: the layout's, or else from its pixel aspect. */
7276
+ /** The width in em a raster was drawn at: its own, or else the Note's. */
7277
+ function rasterWidthEm(note, raster) {
7278
+ return raster.widthEm ?? note.width;
7279
+ }
7280
+ /** The height in em a raster stands for: the layout's, or else from its pixel aspect. */
7214
7281
  function rasterHeightEm(note, raster) {
7215
- return raster.heightEm ?? note.width * raster.height / raster.width;
7282
+ return raster.heightEm ?? rasterWidthEm(note, raster) * raster.height / raster.width;
7283
+ }
7284
+ /** The capability's synchronous layout height, if it has one and it is usable. */
7285
+ function measuredHeight(capability, note) {
7286
+ const height = capability.measure?.(note);
7287
+ return height !== void 0 && Number.isFinite(height) && height > 0 ? height : void 0;
7288
+ }
7289
+ /**
7290
+ * Where a raster drawn for an earlier width or content goes while the next one draws:
7291
+ * at its own size, from the box's top-left corner, so its text isn't stretched. A raster
7292
+ * of the box's own size returns `undefined` and fills the box.
7293
+ */
7294
+ function rasterCoordinates(adapter, note, boxHeight, raster) {
7295
+ const width = rasterWidthEm(note, raster);
7296
+ const height = rasterHeightEm(note, raster);
7297
+ if (width === note.width && Math.abs(height - boxHeight) < 1e-9) return void 0;
7298
+ const em = note.emSize.value;
7299
+ return groundBoxCoordinates(adapter, offsetGroundPosition(adapter, note.position, note.rotation, (width - note.width) * em / 2, (boxHeight - height) * em / 2), note.rotation, width * em, height * em);
7216
7300
  }
7217
7301
  function resolveRaster(capability, note, pxPerEm, cache) {
7218
7302
  const memo = cache.rasters.get(note);
@@ -7254,6 +7338,7 @@ function validateRaster(raster) {
7254
7338
  if (!Number.isFinite(raster.width) || raster.width <= 0) throw new TypeError("NoteRaster.width must be a positive finite number");
7255
7339
  if (!Number.isFinite(raster.height) || raster.height <= 0) throw new TypeError("NoteRaster.height must be a positive finite number");
7256
7340
  if (raster.heightEm !== void 0 && !(Number.isFinite(raster.heightEm) && raster.heightEm > 0)) throw new TypeError("NoteRaster.heightEm must be a positive finite number");
7341
+ if (raster.widthEm !== void 0 && !(Number.isFinite(raster.widthEm) && raster.widthEm > 0)) throw new TypeError("NoteRaster.widthEm must be a positive finite number");
7257
7342
  return raster;
7258
7343
  }
7259
7344
  //#endregion
@@ -7434,6 +7519,55 @@ function createFrameCoalescer(run) {
7434
7519
  };
7435
7520
  }
7436
7521
  //#endregion
7522
+ //#region src/tactical-draw/box-snap.ts
7523
+ /**
7524
+ * The closest snap of `points`, tested as one request each and reported once.
7525
+ * With `cursor`, the snap nearest the cursor wins, so the part of the box being
7526
+ * dragged near snaps before a far one. Null with no resolver or no snap.
7527
+ */
7528
+ function closestBoxSnap(context, points, interaction, originalEvent, cursor) {
7529
+ if (!context.snap) return null;
7530
+ const { graphicId, graphicIds } = context;
7531
+ const requests = points.flatMap((coordinate) => {
7532
+ const pixel = context.toPixel(coordinate);
7533
+ return pixel ? [{
7534
+ coordinate,
7535
+ pixel,
7536
+ interaction,
7537
+ graphicId,
7538
+ graphicIds,
7539
+ originalEvent
7540
+ }] : [];
7541
+ });
7542
+ return context.snap.closest(requests, cursor);
7543
+ }
7544
+ /** How far `hit` moves the point it tested on the ground, in Web Mercator metres. */
7545
+ function groundSnapOffset(adapter, { request, result }) {
7546
+ const [fromX, fromY] = adapter.fromLonLat(request.coordinate);
7547
+ const [toX, toY] = adapter.fromLonLat(result.coordinate);
7548
+ return [toX - fromX, toY - fromY];
7549
+ }
7550
+ /**
7551
+ * A corner scale snapped to `target`: the factor that puts the dragged corner
7552
+ * of `startCorners` (TL, TR, BR, BL) at `target` projected on to its diagonal,
7553
+ * with the opposite corner fixed, and where `center` goes for a given factor.
7554
+ * Null for a degenerate box.
7555
+ */
7556
+ function snappedCornerScale(adapter, startCorners, cornerIndex, center, target) {
7557
+ const [anchorX, anchorY] = adapter.fromLonLat(startCorners[(cornerIndex + 2) % 4]);
7558
+ const [cornerX, cornerY] = adapter.fromLonLat(startCorners[cornerIndex]);
7559
+ const [toX, toY] = adapter.fromLonLat(target);
7560
+ const [centerX, centerY] = adapter.fromLonLat(center);
7561
+ const dx = cornerX - anchorX;
7562
+ const dy = cornerY - anchorY;
7563
+ const lengthSquared = dx * dx + dy * dy;
7564
+ if (lengthSquared === 0) return null;
7565
+ return {
7566
+ factor: ((toX - anchorX) * dx + (toY - anchorY) * dy) / lengthSquared,
7567
+ centerAt: (factor) => adapter.toLonLat([anchorX + (centerX - anchorX) * factor, anchorY + (centerY - anchorY) * factor])
7568
+ };
7569
+ }
7570
+ //#endregion
7437
7571
  //#region src/tactical-draw/transform-controller.ts
7438
7572
  /** No point symbol may scale below this factor of its own size — mirrors the box-drag floor. */
7439
7573
  const MIN_POINT_SYMBOL_SIZE = .1;
@@ -7479,7 +7613,7 @@ function defaultGroupSizeAnchor(graphics) {
7479
7613
  */
7480
7614
  function runGroupTransform(opts) {
7481
7615
  const constrainKey = () => opts.editModifiers().constrain;
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;
7616
+ const { adapter, capability, imageCapability, noteCapability, markerCapability, graphics, graphicsLayer, previewLayer, handlesLayer, renderOptions: renderOpts, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, publishWorkingGraphics, settleWorkingGraphics, isOnGraphicsLayer, onSettled, onClickAwayGraphicsPick, snap } = opts;
7483
7617
  const { noteResolveCache } = opts;
7484
7618
  assertCapabilityFor(graphics);
7485
7619
  validateHostResources(graphics);
@@ -8283,6 +8417,7 @@ function runGroupTransform(opts) {
8283
8417
  preDragPoints,
8284
8418
  preDragBox: groupBox,
8285
8419
  downPixel: pixel,
8420
+ bodySnap: boxHit.kind === "body" ? groupBodySnap(pixel) : null,
8286
8421
  lastSnapshot: {
8287
8422
  points: preDragPoints,
8288
8423
  box: groupBox
@@ -8294,8 +8429,48 @@ function runGroupTransform(opts) {
8294
8429
  dragInFlight = true;
8295
8430
  driver.setDragPanEnabled(false);
8296
8431
  };
8297
- function paintBoxDragSnapshot(pixel, constrainRotation = false) {
8432
+ /**
8433
+ * A body drag's snapping, from pointer-down at `downPixel`: the corners and
8434
+ * centre of the box around every member's footprint, without the edit
8435
+ * padding, in lon/lat. A corner near an intersection lines up two sides of
8436
+ * the group, an edge near a line that side. Null without a resolver.
8437
+ */
8438
+ function groupBodySnap(downPixel) {
8439
+ if (!snap) return null;
8440
+ const box = fitTransformBox(members.flatMap((member) => member.lastBoxPixels), boxAngle, 0);
8441
+ if (!box) return null;
8442
+ return {
8443
+ points: [...boxCorners(box), box.center].map((corner) => driver.fromPixel(corner)),
8444
+ origin: driver.fromPixel(downPixel),
8445
+ context: {
8446
+ adapter,
8447
+ snap,
8448
+ toPixel: (position) => driver.toPixel(position),
8449
+ graphicIds: members.map((member) => member.graphic.id)
8450
+ }
8451
+ };
8452
+ }
8453
+ /**
8454
+ * The drag pixel that puts a body drag at `pixel` on the snap nearest the
8455
+ * cursor: every snap point moves by the pointer's lon/lat delta (as
8456
+ * `beginBoxDrag` moves the members), and the winner's offset to its target is
8457
+ * added to the pointer. `pixel` itself with no snap.
8458
+ */
8459
+ function snappedDragPixel(bodySnap, pixel, info) {
8460
+ const { points, origin, context } = bodySnap;
8461
+ const cursor = driver.fromPixel(pixel);
8462
+ const dx = cursor[0] - origin[0];
8463
+ const dy = cursor[1] - origin[1];
8464
+ const hit = closestBoxSnap(context, points.map((point) => [point[0] + dx, point[1] + dy]), "translate", info?.native, pixel);
8465
+ if (!hit) return pixel;
8466
+ const { coordinate: from } = hit.request;
8467
+ const { coordinate: to } = hit.result;
8468
+ return driver.toPixel([cursor[0] + to[0] - from[0], cursor[1] + to[1] - from[1]]) ?? pixel;
8469
+ }
8470
+ function paintBoxDragSnapshot(rawPixel, constrainRotation = false, info) {
8298
8471
  if (!activeBoxDrag) return;
8472
+ const { bodySnap } = activeBoxDrag;
8473
+ const pixel = bodySnap ? snappedDragPixel(bodySnap, rawPixel, info) : rawPixel;
8299
8474
  const snapshot = activeBoxDrag.fsm.move(pixel, { constrainRotation });
8300
8475
  activeBoxDrag.lastSnapshot = snapshot;
8301
8476
  applyConcatenatedPoints(snapshot.points);
@@ -8309,7 +8484,7 @@ function runGroupTransform(opts) {
8309
8484
  const boxDragPaintCoalescer = createFrameCoalescer(paintBoxDragSnapshot);
8310
8485
  const onDriverMove = (pixel, info) => {
8311
8486
  if (ctx.settled) return;
8312
- if (activeBoxDrag) boxDragPaintCoalescer.schedule(pixel, modifierHeld(info, constrainKey()));
8487
+ if (activeBoxDrag) boxDragPaintCoalescer.schedule(pixel, modifierHeld(info, constrainKey()), info);
8313
8488
  };
8314
8489
  const onDriverUp = (pixel, info) => {
8315
8490
  if (!activeBoxDrag) return;
@@ -8320,7 +8495,7 @@ function runGroupTransform(opts) {
8320
8495
  driver.setDragPanEnabled(true);
8321
8496
  return;
8322
8497
  }
8323
- const { fsm, preDragPoints, preDragBox, downPixel, preDragOptionsOverrideByMember, preDragAmplifierPlacementsByMember, preDragPointSymbolStateByMember } = activeBoxDrag;
8498
+ const { fsm, preDragPoints, preDragBox, downPixel, preDragOptionsOverrideByMember, preDragAmplifierPlacementsByMember, preDragPointSymbolStateByMember, bodySnap } = activeBoxDrag;
8324
8499
  activeBoxDrag = null;
8325
8500
  driver.setDragPanEnabled(true);
8326
8501
  if (fsm.kind === "body" && withinClickSlop(pixel, downPixel)) {
@@ -8334,7 +8509,7 @@ function runGroupTransform(opts) {
8334
8509
  shell.noteBodyClick();
8335
8510
  return;
8336
8511
  }
8337
- const finalSnapshot = fsm.move(pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
8512
+ const finalSnapshot = fsm.move(bodySnap ? snappedDragPixel(bodySnap, pixel, info) : pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
8338
8513
  const { scale, rotation } = boxScaleRotation(fsm.kind, finalSnapshot.box, preDragBox);
8339
8514
  const nextPointSymbolStateByMember = scalePointSymbolStates(preDragPointSymbolStateByMember, scale, rotation);
8340
8515
  applyConcatenatedPoints(preDragPoints);
@@ -9154,24 +9329,52 @@ function runImageEdit(opts) {
9154
9329
  const result = drag.fsm.move(pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
9155
9330
  next.position = [...result.points[0]];
9156
9331
  const delta = boxScaleRotation(drag.kind, result.box, drag.startBox);
9157
- if (drag.kind === "scale") next.size = {
9158
- value: Math.max(.1, next.size.value * delta.scale),
9159
- unit: "meters"
9160
- };
9161
- else if (drag.kind === "rotate") next.rotation = normalizeRotation(next.rotation + delta.rotation);
9332
+ if (drag.kind === "scale") {
9333
+ next.size = {
9334
+ value: Math.max(.1, next.size.value * delta.scale),
9335
+ unit: "meters"
9336
+ };
9337
+ return snappedScale(drag, next, info) ?? next;
9338
+ } else if (drag.kind === "rotate") next.rotation = normalizeRotation(next.rotation + delta.rotation);
9162
9339
  else {
9163
- const anchorPixel = driver.toPixel(next.position) ?? pixel;
9164
- const snapped = snap?.({
9165
- coordinate: next.position,
9166
- pixel: anchorPixel,
9167
- interaction: "translate",
9168
- graphicId: image.id,
9169
- originalEvent: info?.native
9170
- });
9171
- if (snapped) next.position = snapped.coordinate;
9340
+ const hit = closestBoxSnap(boxSnap, [next.position, ...cornersOf(next)], "translate", info?.native, pixel);
9341
+ if (hit) next.position = offsetGroundPosition(adapter, next.position, 0, ...groundSnapOffset(adapter, hit));
9172
9342
  }
9173
9343
  return next;
9174
9344
  };
9345
+ const boxSnap = {
9346
+ adapter,
9347
+ snap,
9348
+ toPixel: (position) => driver.toPixel(position),
9349
+ graphicId: image.id
9350
+ };
9351
+ /** `value`'s footprint corners TL, TR, BR, BL on the ground, without the edit padding. */
9352
+ const cornersOf = (value) => {
9353
+ const { width, height } = value.intrinsicSize;
9354
+ return groundBoxCoordinates(adapter, value.position, value.rotation, value.size.value, value.size.value * height / width);
9355
+ };
9356
+ /**
9357
+ * A corner scale whose dragged corner snaps: the snapped point projected on
9358
+ * to the diagonal from the fixed opposite corner gives the factor. Null when
9359
+ * nothing snaps.
9360
+ */
9361
+ const snappedScale = (current, scaled, info) => {
9362
+ const { start, cornerIndex } = current;
9363
+ if (cornerIndex === void 0) return null;
9364
+ const corner = cornersOf(scaled)[cornerIndex];
9365
+ const hit = closestBoxSnap(boxSnap, [corner], "reshape", info?.native);
9366
+ if (!hit) return null;
9367
+ const scale = snappedCornerScale(adapter, cornersOf(start), cornerIndex, start.position, hit.result.coordinate);
9368
+ if (!scale) return null;
9369
+ const value = Math.max(.1, start.size.value * scale.factor);
9370
+ const next = cloneImageGraphic(start);
9371
+ next.size = {
9372
+ value,
9373
+ unit: "meters"
9374
+ };
9375
+ next.position = scale.centerAt(value / start.size.value);
9376
+ return next;
9377
+ };
9175
9378
  const onDown = (pixel, info) => {
9176
9379
  if (ctx.settled || !box || !modes.includes("transform")) return;
9177
9380
  const hit = pickBoxHandle(box, pixel, info?.hitTolerance ?? 12);
@@ -9191,7 +9394,8 @@ function runImageEdit(opts) {
9191
9394
  kind: hit.kind,
9192
9395
  down: [...pixel],
9193
9396
  start: cloneImageGraphic(working),
9194
- startBox: box
9397
+ startBox: box,
9398
+ ...hit.kind === "scale" ? { cornerIndex: hit.index } : {}
9195
9399
  };
9196
9400
  driver.setDragPanEnabled(false);
9197
9401
  };
@@ -9382,6 +9586,18 @@ function runNoteEdit(opts) {
9382
9586
  render: renderNoteForAdapter(adapter, capability, value, resolveCache()).render
9383
9587
  });
9384
9588
  const snapshot = () => snapshotOf(working);
9589
+ /** The box height in em `value` lays out to, as far as is known now: measured if it can be. */
9590
+ const heightOf = (value) => measuredHeight(capability, value) ?? renderNoteForAdapter(adapter, capability, value, resolveCache()).render.height;
9591
+ /**
9592
+ * `next` centred `x` metres along its own axis from `from`, and moved so its top edge
9593
+ * stays where it was at `fromHeight`: like a text box, a Note whose layout grows or
9594
+ * shrinks does so at the bottom, not about its centre.
9595
+ */
9596
+ const keepTop = (next, fromHeight, from = next.position, x = 0) => {
9597
+ const y = (fromHeight - heightOf(next)) * next.emSize.value / 2;
9598
+ next.position = offsetGroundPosition(adapter, from, next.rotation, x, y);
9599
+ return next;
9600
+ };
9385
9601
  /**
9386
9602
  * The box handles: corners and rotate grip, then the Note-only width grips.
9387
9603
  */
@@ -9474,6 +9690,7 @@ function runNoteEdit(opts) {
9474
9690
  if (ctx.settled) return;
9475
9691
  const next = normalizeNoteGraphic(updater(cloneNoteGraphic(working)));
9476
9692
  if (next.kind !== "note" || next.id !== note.id) throw new TypeError("updateGraphic must preserve note kind and id");
9693
+ if (next.rotation === working.rotation && deepEqual(next.position, working.position) && deepEqual(next.emSize, working.emSize)) keepTop(next, heightOf(working));
9477
9694
  renderNoteForAdapter(adapter, capability, next, resolveCache());
9478
9695
  apply(next, "programmatic", "Update graphic");
9479
9696
  },
@@ -9494,27 +9711,36 @@ function runNoteEdit(opts) {
9494
9711
  /**
9495
9712
  * A width drag: the grabbed edge follows the pointer along the Note's own x
9496
9713
  * 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.
9714
+ * opposite edge keeps its ground position. The height follows the new layout,
9715
+ * growing or shrinking at the bottom.
9498
9716
  */
9499
- const widened = (current, pixel) => {
9717
+ const widened = (current, pixel, info) => {
9718
+ const pointer = groundAt(pixel);
9719
+ const side = current.index === 1 ? 1 : -1;
9720
+ const next = widenedUnsnapped(current, side, pointer);
9721
+ const corners = cornersOf(next);
9722
+ const edge = side === 1 ? [corners[1], corners[2]] : [corners[0], corners[3]];
9723
+ const midpoint = offsetGroundPosition(adapter, next.position, next.rotation, side * next.width * next.emSize.value / 2, 0);
9724
+ const hit = closestSnap([...edge, midpoint], "reshape", info, pixel);
9725
+ if (!hit) return next;
9726
+ const [dx, dy] = groundSnapOffset(adapter, hit);
9727
+ return widenedUnsnapped(current, side, [pointer[0] + dx, pointer[1] + dy]);
9728
+ };
9729
+ /** {@link widened} for a pointer at `pointer` in Web Mercator metres, without snapping. */
9730
+ const widenedUnsnapped = (current, side, pointer) => {
9500
9731
  const next = cloneNoteGraphic(current.start);
9501
9732
  const { start } = current;
9502
9733
  const em = start.emSize.value;
9503
- const side = current.index === 1 ? 1 : -1;
9504
9734
  const axis = [Math.cos(start.rotation) * side, -Math.sin(start.rotation) * side];
9505
- const pointer = groundAt(pixel);
9506
9735
  const pulled = (pointer[0] - current.downGround[0]) * axis[0] + (pointer[1] - current.downGround[1]) * axis[1];
9507
9736
  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
9737
  next.width = width;
9512
- return next;
9738
+ return keepTop(next, current.startHeight, start.position, side * (width - start.width) * em / 2);
9513
9739
  };
9514
9740
  const transformed = (pixel, info) => {
9515
9741
  if (!drag) return null;
9516
- if (drag.kind === "width") return widened(drag, pixel);
9517
- const next = cloneNoteGraphic(drag.start);
9742
+ if (drag.kind === "width") return widened(drag, pixel, info);
9743
+ let next = cloneNoteGraphic(drag.start);
9518
9744
  const result = drag.fsm.move(pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
9519
9745
  next.position = [...result.points[0]];
9520
9746
  const delta = boxScaleRotation(drag.kind, result.box, drag.startBox);
@@ -9528,25 +9754,58 @@ function runNoteEdit(opts) {
9528
9754
  };
9529
9755
  if (value !== startEm * delta.scale) {
9530
9756
  const factor = value / startEm;
9531
- const { anchor } = drag;
9757
+ const anchor = boxCorners(drag.startBox)[(drag.cornerIndex + 2) % 4];
9532
9758
  const center = driver.toPixel(drag.start.position);
9533
9759
  if (center) next.position = driver.fromPixel([anchor[0] + (center[0] - anchor[0]) * factor, anchor[1] + (center[1] - anchor[1]) * factor]);
9534
9760
  }
9761
+ next = snappedScale(drag, next, info) ?? next;
9535
9762
  } else if (drag.kind === "rotate") next.rotation = normalizeRotation(next.rotation + delta.rotation);
9536
9763
  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;
9764
+ const corners = cornersOf(next, drag.startHeight);
9765
+ const hit = closestSnap([next.position, ...corners], "translate", info, pixel);
9766
+ if (hit) next.position = offsetGroundPosition(adapter, next.position, 0, ...groundSnapOffset(adapter, hit));
9546
9767
  }
9547
9768
  return next;
9548
9769
  };
9549
9770
  /**
9771
+ * A corner scale whose dragged corner snaps: the snapped point projected on
9772
+ * to the diagonal from the fixed opposite corner gives the factor, clamped to
9773
+ * the edit's `emSize` range. Null when nothing snaps.
9774
+ */
9775
+ const snappedScale = (current, scaled, info) => {
9776
+ const { start, startHeight, cornerIndex } = current;
9777
+ const corner = cornersOf(scaled, startHeight)[cornerIndex];
9778
+ const hit = closestSnap([corner], "reshape", info);
9779
+ if (!hit) return null;
9780
+ const scale = snappedCornerScale(adapter, cornersOf(start, startHeight), cornerIndex, start.position, hit.result.coordinate);
9781
+ if (!scale) return null;
9782
+ const [min, max] = current.emSizeRange;
9783
+ const value = Math.min(max, Math.max(min, start.emSize.value * scale.factor));
9784
+ const next = cloneNoteGraphic(start);
9785
+ next.emSize = {
9786
+ value,
9787
+ unit: "meters"
9788
+ };
9789
+ next.position = scale.centerAt(value / start.emSize.value);
9790
+ return next;
9791
+ };
9792
+ /**
9793
+ * `value`'s box corners TL, TR, BR, BL on the ground, without the edit
9794
+ * padding. Pass `height` in em when it is known, to skip measuring the layout.
9795
+ */
9796
+ const cornersOf = (value, height = heightOf(value)) => {
9797
+ const em = value.emSize.value;
9798
+ return groundBoxCoordinates(adapter, value.position, value.rotation, value.width * em, height * em);
9799
+ };
9800
+ const boxSnap = {
9801
+ adapter,
9802
+ snap,
9803
+ toPixel: (position) => driver.toPixel(position),
9804
+ graphicId: note.id
9805
+ };
9806
+ /** {@link closestBoxSnap} of the Note's `points`. */
9807
+ const closestSnap = (points, interaction, info, cursor) => closestBoxSnap(boxSnap, points, interaction, info?.native, cursor);
9808
+ /**
9550
9809
  * The `emSize` range a scale drag may reach: the limits around the size this
9551
9810
  * edit started with. `updateGraphic` can set a size outside them, so a drag
9552
9811
  * from there includes its start value rather than jumping to the limit.
@@ -9562,7 +9821,8 @@ function runNoteEdit(opts) {
9562
9821
  index: hit.index,
9563
9822
  down: [...pixel],
9564
9823
  start: cloneNoteGraphic(working),
9565
- downGround: groundAt(pixel)
9824
+ downGround: groundAt(pixel),
9825
+ startHeight: heightOf(working)
9566
9826
  };
9567
9827
  else {
9568
9828
  const shared = {
@@ -9579,12 +9839,13 @@ function runNoteEdit(opts) {
9579
9839
  }),
9580
9840
  down: [...pixel],
9581
9841
  start: cloneNoteGraphic(working),
9582
- startBox: box
9842
+ startBox: box,
9843
+ startHeight: heightOf(working)
9583
9844
  };
9584
9845
  drag = hit.kind === "scale" ? {
9585
9846
  ...shared,
9586
9847
  kind: "scale",
9587
- anchor: boxCorners(box)[(hit.index + 2) % 4],
9848
+ cornerIndex: hit.index,
9588
9849
  emSizeRange: emSizeRange(working.emSize.value)
9589
9850
  } : {
9590
9851
  ...shared,
@@ -11341,7 +11602,8 @@ var TacticalDraw = class {
11341
11602
  isOnGraphicsLayer,
11342
11603
  onSettled,
11343
11604
  onClickAwayGraphicsPick,
11344
- editModifiers: this.currentEditModifiers
11605
+ editModifiers: this.currentEditModifiers,
11606
+ snap: this.resolveSnap
11345
11607
  }), (handle) => {
11346
11608
  this.activeTransform = handle;
11347
11609
  return () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orbat-mapper/tactical-draw",
3
- "version": "0.31.1",
3
+ "version": "0.33.0",
4
4
  "description": "Engine-agnostic draw/edit core for tactical control measures (MIL-STD-2525 / APP-6). The MapAdapter ABI and bring-your-own-engine entry point for the tactical-draw package family.",
5
5
  "license": "MIT",
6
6
  "author": "Orbat Mapper",