@orbat-mapper/tactical-draw 0.22.1 → 0.24.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, NON_SOLID_FILL_PATTERNS, applyBoxTransformOptions, canonicalTextAmplifierKey, cloneControlMeasure, controlMeasureIdFromFeature, dragControlMeasureOptionHandle, foldsBoxTransformOptions, freezeOrientationOptions, getControlMeasureMetadata, getControlMeasureOptionHandles, getDefaultOptions, 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, labelSizeBandHideThreshold, 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";
@@ -350,13 +350,20 @@ function clipSegmentToBounds(a, b, bounds) {
350
350
  }
351
351
  return [[a[0] + start * dx, a[1] + start * dy], [a[0] + end * dx, a[1] + end * dy]];
352
352
  }
353
+ /** Pixel distance from `pixel` to segment `a`–`b`; `null` for a zero-length segment. */
353
354
  function distanceToSegment(pixel, a, b) {
355
+ if (a[0] === b[0] && a[1] === b[1]) return null;
356
+ return pixelSegmentDistance(pixel, a, b);
357
+ }
358
+ /**
359
+ * Pixel distance from `pixel` to the segment `a`–`b`, clamped to its ends; a
360
+ * zero-length segment measures to its point.
361
+ */
362
+ function pixelSegmentDistance(pixel, a, b) {
354
363
  const dx = b[0] - a[0];
355
364
  const dy = b[1] - a[1];
356
365
  const lengthSq = dx * dx + dy * dy;
357
- if (lengthSq === 0) return null;
358
- const unclamped = ((pixel[0] - a[0]) * dx + (pixel[1] - a[1]) * dy) / lengthSq;
359
- const t = Math.max(0, Math.min(1, unclamped));
366
+ const t = lengthSq > 0 ? Math.max(0, Math.min(1, ((pixel[0] - a[0]) * dx + (pixel[1] - a[1]) * dy) / lengthSq)) : 0;
360
367
  return Math.hypot(pixel[0] - (a[0] + t * dx), pixel[1] - (a[1] + t * dy));
361
368
  }
362
369
  /**
@@ -776,7 +783,7 @@ const DEFAULT_TEXT_SIZE_MAX_PIXELS = 24;
776
783
  * Share of the band minimum at which a fading ground label reaches zero
777
784
  * opacity and hides (ADR-0060): 4 px fades out to nothing at 3.2 px.
778
785
  */
779
- const TEXT_FADE_END_RATIO = .8;
786
+ const TEXT_FADE_END_RATIO = LABEL_FADE_END_RATIO;
780
787
  /**
781
788
  * Ground label size `textSizeMeters / resolution`, pinned to both edges of
782
789
  * the band. The fixed-scale rule behind [[resolveTextAppearance]]'s
@@ -789,6 +796,19 @@ function resolveGroundTextSizePixels(textSizeMeters, resolution, text) {
789
796
  return Math.min(max, Math.max(min, textSizeMeters / resolution));
790
797
  }
791
798
  /**
799
+ * `band` as the render context's label size band (ADR-0064): how an
800
+ * interactive map draws ground labels, pinned at the maximum and hiding below
801
+ * the minimum. Generators then size knockouts to the text on screen and drop
802
+ * them once the text hides.
803
+ */
804
+ function interactiveLabelSizeBand(band) {
805
+ return {
806
+ min: band?.textSizeMinPixels ?? 4,
807
+ max: band?.textSizeMaxPixels ?? 24,
808
+ belowMin: "hide"
809
+ };
810
+ }
811
+ /**
792
812
  * Resolve how a label renders on an interactive map at `resolution`, or
793
813
  * `null` when it should render nothing this frame:
794
814
  *
@@ -828,7 +848,7 @@ function resolveTextAppearance(props, resolution, policy) {
828
848
  sizePixels: Math.min(max, px),
829
849
  opacity: 1
830
850
  };
831
- const fadeEnd = min * TEXT_FADE_END_RATIO;
851
+ const fadeEnd = labelSizeBandHideThreshold(interactiveLabelSizeBand(props));
832
852
  if (px <= fadeEnd) return null;
833
853
  return {
834
854
  sizePixels: px,
@@ -1995,6 +2015,272 @@ function isPinnableGraphic(graphic) {
1995
2015
  return isPointSymbol(graphic) || isMarker(graphic);
1996
2016
  }
1997
2017
  //#endregion
2018
+ //#region src/tactical-draw/run-interaction.ts
2019
+ function runInteraction(spec) {
2020
+ const { adapter, signal, layers, onViewChange, onSettled, attach } = spec;
2021
+ if (signal?.aborted) {
2022
+ const error = new TacticalDrawAbortError("signal", { cause: signal.reason });
2023
+ const promise = Promise.reject(error);
2024
+ promise.catch(() => {});
2025
+ return {
2026
+ promise,
2027
+ settled: true,
2028
+ abort: () => {}
2029
+ };
2030
+ }
2031
+ let settled = false;
2032
+ const combined = combineWithHostSignal(signal);
2033
+ let resolveFn;
2034
+ let rejectFn;
2035
+ const promise = new Promise((resolve, reject) => {
2036
+ resolveFn = resolve;
2037
+ rejectFn = reject;
2038
+ });
2039
+ const ownedLayers = new Set(layers);
2040
+ let controllerDetach = null;
2041
+ let controllerOnAbort = null;
2042
+ function writeLayer(layer, groups) {
2043
+ if (!ownedLayers.has(layer)) return;
2044
+ adapter.setLayerFeatureGroups(layer, groups);
2045
+ }
2046
+ function clearLayers() {
2047
+ for (const layer of ownedLayers) adapter.setLayerFeatureGroups(layer, []);
2048
+ }
2049
+ const handleKeydown = (event) => {
2050
+ if (settled) return;
2051
+ if (event.key !== "Escape") return;
2052
+ fail(new TacticalDrawAbortError("escape"));
2053
+ };
2054
+ function teardown() {
2055
+ if (controllerDetach) controllerDetach();
2056
+ if (onViewChange) adapter.offViewChange(onViewChange);
2057
+ if (typeof window !== "undefined") window.removeEventListener("keydown", handleKeydown);
2058
+ combined.dispose();
2059
+ clearLayers();
2060
+ }
2061
+ function commit(produce) {
2062
+ if (settled) return void 0;
2063
+ let value;
2064
+ try {
2065
+ value = produce();
2066
+ } catch (err) {
2067
+ settled = true;
2068
+ teardown();
2069
+ rejectFn(err);
2070
+ if (onSettled) onSettled({
2071
+ status: "rejected",
2072
+ error: err
2073
+ });
2074
+ return;
2075
+ }
2076
+ settled = true;
2077
+ teardown();
2078
+ resolveFn(value);
2079
+ if (onSettled) onSettled({
2080
+ status: "committed",
2081
+ value
2082
+ });
2083
+ return value;
2084
+ }
2085
+ function fail(error) {
2086
+ if (settled) return;
2087
+ settled = true;
2088
+ teardown();
2089
+ if (controllerOnAbort) try {
2090
+ controllerOnAbort();
2091
+ } catch {}
2092
+ rejectFn(error);
2093
+ if (onSettled) onSettled({
2094
+ status: "rejected",
2095
+ error
2096
+ });
2097
+ }
2098
+ const ctx = {
2099
+ get settled() {
2100
+ return settled;
2101
+ },
2102
+ commit,
2103
+ fail,
2104
+ writeLayer,
2105
+ onTeardown(detach, onAbort) {
2106
+ controllerDetach = detach;
2107
+ controllerOnAbort = onAbort ?? null;
2108
+ }
2109
+ };
2110
+ combined.signal.addEventListener("abort", () => {
2111
+ if (settled) return;
2112
+ const reason = combined.signal.reason;
2113
+ if (reason instanceof TacticalDrawAbortError) fail(reason);
2114
+ else fail(new TacticalDrawAbortError("signal", { cause: reason }));
2115
+ }, { once: true });
2116
+ if (onViewChange) adapter.onViewChange(onViewChange);
2117
+ if (typeof window !== "undefined") window.addEventListener("keydown", handleKeydown);
2118
+ attach(ctx);
2119
+ return {
2120
+ promise,
2121
+ get settled() {
2122
+ return settled;
2123
+ },
2124
+ abort(reason, cause) {
2125
+ combined.abort(reason, cause);
2126
+ }
2127
+ };
2128
+ }
2129
+ /** Whether `b` lands within {@link CLICK_SLOP_PX} of `a` — a click, not a drag. */
2130
+ function withinClickSlop(a, b) {
2131
+ return Math.hypot(a[0] - b[0], a[1] - b[1]) <= 3;
2132
+ }
2133
+ function runEditInteraction(spec) {
2134
+ const { adapter, signal, layers, graphicsLayer, previewLayer, handlesLayer, closeOnClickAway } = spec;
2135
+ let ctx;
2136
+ let driver;
2137
+ let previewPick;
2138
+ let handlesPick;
2139
+ let graphicsPick;
2140
+ /**
2141
+ * Consume exactly one trailing click without closing — set through
2142
+ * `shell.suppressNextClickAway()` on delete / label-drag / post-drag paths.
2143
+ *
2144
+ * The suppression is scoped to the pointer cycle that armed it: it is cleared
2145
+ * again on the next `pointerdown` (see the `onDown` wrapper below). Hosts do
2146
+ * not agree on whether a completed drag is followed by a `click` at all —
2147
+ * MapLibre swallows its `click` when the pointer moved beyond its 3px
2148
+ * `clickTolerance`, while Leaflet delivers one. Without the reset, a
2149
+ * suppression armed after a real drag on MapLibre survives into the *next*
2150
+ * pointer cycle and eats the user's first genuine click-away, so exiting the
2151
+ * edit takes two clicks instead of one.
2152
+ */
2153
+ let suppressClickAway = false;
2154
+ /** A zero-movement body drag released this pointer cycle — set through `shell.noteBodyClick()`. */
2155
+ let bodyClickPending = false;
2156
+ const shell = {
2157
+ suppressNextClickAway() {
2158
+ suppressClickAway = true;
2159
+ },
2160
+ noteBodyClick() {
2161
+ bodyClickPending = true;
2162
+ }
2163
+ };
2164
+ const onPreviewPick = (event) => {
2165
+ previewPick = event;
2166
+ };
2167
+ const onHandlesPick = (event) => {
2168
+ handlesPick = event;
2169
+ };
2170
+ const onGraphicsPick = (event) => {
2171
+ graphicsPick = event;
2172
+ };
2173
+ const onClick = () => {
2174
+ const localPreview = previewPick;
2175
+ const localHandles = handlesPick;
2176
+ const localGraphics = graphicsPick;
2177
+ const wasBodyClick = bodyClickPending;
2178
+ previewPick = void 0;
2179
+ handlesPick = void 0;
2180
+ graphicsPick = void 0;
2181
+ bodyClickPending = false;
2182
+ if (ctx.settled) return;
2183
+ if (!closeOnClickAway) return;
2184
+ if (suppressClickAway) {
2185
+ suppressClickAway = false;
2186
+ return;
2187
+ }
2188
+ if (localHandles) return;
2189
+ if (localGraphics && !spec.ownsGraphic(localGraphics.id)) {
2190
+ spec.close();
2191
+ spec.onForeignPick?.(localGraphics);
2192
+ return;
2193
+ }
2194
+ if (localGraphics && spec.ownsGraphic(localGraphics.id)) {
2195
+ spec.onOwnClick?.(localGraphics);
2196
+ return;
2197
+ }
2198
+ if (localPreview) {
2199
+ spec.onOwnClick?.(localPreview);
2200
+ return;
2201
+ }
2202
+ if (wasBodyClick) return;
2203
+ spec.close();
2204
+ };
2205
+ return runInteraction({
2206
+ adapter,
2207
+ signal,
2208
+ layers,
2209
+ onViewChange: spec.onViewChange,
2210
+ onSettled: (settlement) => {
2211
+ try {
2212
+ spec.historySettle();
2213
+ } finally {
2214
+ spec.facadeOnSettled?.();
2215
+ spec.emitSettle(settlement);
2216
+ }
2217
+ },
2218
+ attach(interaction) {
2219
+ ctx = interaction;
2220
+ driver = adapter.createEditPointerDriver();
2221
+ let beforeTeardownRan = false;
2222
+ const runBeforeTeardown = (settlement) => {
2223
+ if (beforeTeardownRan) return;
2224
+ beforeTeardownRan = true;
2225
+ try {
2226
+ spec.onBeforeTeardown?.(settlement);
2227
+ } catch {}
2228
+ };
2229
+ const controllerContext = {
2230
+ get settled() {
2231
+ return interaction.settled;
2232
+ },
2233
+ commit(produce) {
2234
+ return interaction.commit(() => {
2235
+ const value = produce();
2236
+ runBeforeTeardown({
2237
+ status: "committed",
2238
+ value
2239
+ });
2240
+ return value;
2241
+ });
2242
+ },
2243
+ fail(error) {
2244
+ if (!interaction.settled) runBeforeTeardown({
2245
+ status: "rejected",
2246
+ error
2247
+ });
2248
+ interaction.fail(error);
2249
+ },
2250
+ writeLayer: interaction.writeLayer,
2251
+ onTeardown: interaction.onTeardown
2252
+ };
2253
+ const onDown = (pixel, info) => {
2254
+ suppressClickAway = false;
2255
+ spec.onDown(pixel, info);
2256
+ };
2257
+ const unsubDown = driver.onPointerDown(onDown);
2258
+ const unsubMove = driver.onPointerMove(spec.onMove);
2259
+ const unsubUp = driver.onPointerUp(spec.onUp);
2260
+ const unsubPreview = adapter.onPick(previewLayer, onPreviewPick);
2261
+ const unsubHandles = adapter.onPick(handlesLayer, onHandlesPick);
2262
+ const unsubGraphics = adapter.onPick(graphicsLayer, onGraphicsPick);
2263
+ adapter.on("click", onClick);
2264
+ interaction.onTeardown(() => {
2265
+ runBeforeTeardown({
2266
+ status: "rejected",
2267
+ error: void 0
2268
+ });
2269
+ adapter.off("click", onClick);
2270
+ unsubPreview();
2271
+ unsubHandles();
2272
+ unsubGraphics();
2273
+ unsubDown();
2274
+ unsubMove();
2275
+ unsubUp();
2276
+ spec.extraTeardown?.();
2277
+ driver.dispose();
2278
+ }, spec.onAbort);
2279
+ spec.attach(controllerContext, driver, shell);
2280
+ }
2281
+ });
2282
+ }
2283
+ //#endregion
1998
2284
  //#region src/tactical-draw/active-interaction.ts
1999
2285
  /**
2000
2286
  * Owns the facade's public interaction state: the abort handle used by
@@ -2073,29 +2359,47 @@ function sizeOptionSpecs(kind) {
2073
2359
  }
2074
2360
  /**
2075
2361
  * Whether `kind` has at least one size that can be restored to its normal
2076
- * pixel-authored appearance at the adapter's current resolution. Kept inside
2362
+ * pixel-authored appearance at the given resolution. Kept inside
2077
2363
  * tactical-draw using the core metadata catalog so hosts never need to
2078
2364
  * infer option names or special-case captured labels.
2365
+ *
2366
+ * `scale` only needs `getResolution()` (Web Mercator meters per CSS pixel), so
2367
+ * a host without a live map can pass a fixed one:
2368
+ * `canResetGroundSizes(measure, { getResolution: () => resolution })`.
2079
2369
  */
2080
- function canResetGroundSizes(measure, adapter) {
2081
- return hasUsableResolution(adapter.getResolution()) && sizeOptionSpecs(measure.kind).length > 0;
2370
+ function canResetGroundSizes(measure, scale) {
2371
+ return hasUsableResolution(scale.getResolution()) && sizeOptionSpecs(measure.kind).length > 0;
2082
2372
  }
2083
2373
  /**
2084
2374
  * Return the complete option record produced by resetting every known size
2085
- * pair to its default on-screen appearance at the adapter's current
2086
- * resolution. Pixel keys are removed and meter keys are written, so the
2087
- * result remains ground-anchored. Unrelated options are preserved.
2375
+ * pair to its default on-screen appearance at the given resolution. Pixel
2376
+ * keys are removed and meter keys are written, so the result remains
2377
+ * ground-anchored. A pair that inherits another pair's size is cleared so it
2378
+ * follows again. Unrelated options are preserved. This is the rule
2379
+ * `EditSession.resetGroundSizes()` applies; hosts resetting graphics outside
2380
+ * an edit session call it directly, passing a fixed resolution such as
2381
+ * `{ getResolution: () => resolution }`.
2088
2382
  *
2089
- * Returns `undefined` when the kind has no resettable sizes or the adapter has
2090
- * no usable resolution.
2383
+ * A pair's default is its own `defaultValue` when its `defaultUnit` is `"px"`,
2384
+ * else the kind's default pixel option.
2385
+ *
2386
+ * Returns options for any kind with size pairs, even when nothing changes;
2387
+ * compare with the input (e.g. structurally) to detect a no-op. Returns
2388
+ * `undefined` when the kind has no resettable sizes or the resolution is not
2389
+ * usable.
2091
2390
  */
2092
- function resetGroundSizeOptions(measure, adapter) {
2093
- const mpp = adapter.getResolution();
2391
+ function resetGroundSizeOptions(measure, scale) {
2392
+ const mpp = scale.getResolution();
2094
2393
  const specs = sizeOptionSpecs(measure.kind);
2095
2394
  if (!hasUsableResolution(mpp) || specs.length === 0) return void 0;
2096
2395
  const defaults = getDefaultOptions(measure.kind);
2097
2396
  const next = { ...measure.options ?? {} };
2098
2397
  for (const spec of specs) {
2398
+ if (spec.inheritsFrom !== void 0) {
2399
+ delete next[spec.pixels];
2400
+ delete next[spec.meters];
2401
+ continue;
2402
+ }
2099
2403
  const defaultPixels = spec.defaultUnit === "px" && spec.defaultValue !== void 0 ? spec.defaultValue : defaults[spec.pixels];
2100
2404
  if (typeof defaultPixels !== "number") continue;
2101
2405
  const result = switchSizePairUnit({
@@ -2129,7 +2433,7 @@ function measureUsesAdapterResolution(measure) {
2129
2433
  return sizeOptionSpecs(measure.kind).some((spec) => {
2130
2434
  if (options?.[spec.pixels] !== void 0) return true;
2131
2435
  if (options?.[spec.meters] !== void 0) return false;
2132
- return !spec.captureOnDraw && spec.defaultUnit === "px";
2436
+ return !spec.captureOnDraw && spec.inheritsFrom === void 0 && spec.defaultUnit === "px";
2133
2437
  });
2134
2438
  }
2135
2439
  /**
@@ -2175,14 +2479,15 @@ function defaultSizeAnchor(measure) {
2175
2479
  }
2176
2480
  /**
2177
2481
  * Materialize uncaptured pixel authoring defaults before commit, so the ground
2178
- * bake sees an explicit value. Meter-default dimensions and authored values
2179
- * remain unchanged; captured labels have their separate render/commit seam.
2482
+ * bake sees an explicit value. Meter-default dimensions, pairs that inherit
2483
+ * another pair's size, and authored values remain unchanged; captured labels
2484
+ * have their separate render/commit seam.
2180
2485
  */
2181
2486
  function withDefaultAuthoringSize(measure) {
2182
2487
  let options = measure.options ?? {};
2183
2488
  let changed = false;
2184
2489
  for (const spec of sizeOptionSpecs(measure.kind)) {
2185
- if (spec.captureOnDraw || spec.defaultUnit !== "px") continue;
2490
+ if (spec.captureOnDraw || spec.inheritsFrom !== void 0 || spec.defaultUnit !== "px") continue;
2186
2491
  if (options[spec.pixels] !== void 0 || options[spec.meters] !== void 0) continue;
2187
2492
  const resolved = resolveSizePair({
2188
2493
  kind: measure.kind,
@@ -2279,118 +2584,6 @@ function geographicMidpointLatitude(points) {
2279
2584
  }
2280
2585
  return (min + max) / 2;
2281
2586
  }
2282
- //#endregion
2283
- //#region src/tactical-draw/run-interaction.ts
2284
- function runInteraction(spec) {
2285
- const { adapter, signal, layers, onViewChange, onSettled, attach } = spec;
2286
- if (signal?.aborted) {
2287
- const error = new TacticalDrawAbortError("signal", { cause: signal.reason });
2288
- const promise = Promise.reject(error);
2289
- promise.catch(() => {});
2290
- return {
2291
- promise,
2292
- settled: true,
2293
- abort: () => {}
2294
- };
2295
- }
2296
- let settled = false;
2297
- const combined = combineWithHostSignal(signal);
2298
- let resolveFn;
2299
- let rejectFn;
2300
- const promise = new Promise((resolve, reject) => {
2301
- resolveFn = resolve;
2302
- rejectFn = reject;
2303
- });
2304
- const ownedLayers = new Set(layers);
2305
- let controllerDetach = null;
2306
- let controllerOnAbort = null;
2307
- function writeLayer(layer, groups) {
2308
- if (!ownedLayers.has(layer)) return;
2309
- adapter.setLayerFeatureGroups(layer, groups);
2310
- }
2311
- function clearLayers() {
2312
- for (const layer of ownedLayers) adapter.setLayerFeatureGroups(layer, []);
2313
- }
2314
- const handleKeydown = (event) => {
2315
- if (settled) return;
2316
- if (event.key !== "Escape") return;
2317
- fail(new TacticalDrawAbortError("escape"));
2318
- };
2319
- function teardown() {
2320
- if (controllerDetach) controllerDetach();
2321
- if (onViewChange) adapter.offViewChange(onViewChange);
2322
- if (typeof window !== "undefined") window.removeEventListener("keydown", handleKeydown);
2323
- combined.dispose();
2324
- clearLayers();
2325
- }
2326
- function commit(produce) {
2327
- if (settled) return void 0;
2328
- let value;
2329
- try {
2330
- value = produce();
2331
- } catch (err) {
2332
- settled = true;
2333
- teardown();
2334
- rejectFn(err);
2335
- if (onSettled) onSettled({
2336
- status: "rejected",
2337
- error: err
2338
- });
2339
- return;
2340
- }
2341
- settled = true;
2342
- teardown();
2343
- resolveFn(value);
2344
- if (onSettled) onSettled({
2345
- status: "committed",
2346
- value
2347
- });
2348
- return value;
2349
- }
2350
- function fail(error) {
2351
- if (settled) return;
2352
- settled = true;
2353
- teardown();
2354
- if (controllerOnAbort) try {
2355
- controllerOnAbort();
2356
- } catch {}
2357
- rejectFn(error);
2358
- if (onSettled) onSettled({
2359
- status: "rejected",
2360
- error
2361
- });
2362
- }
2363
- const ctx = {
2364
- get settled() {
2365
- return settled;
2366
- },
2367
- commit,
2368
- fail,
2369
- writeLayer,
2370
- onTeardown(detach, onAbort) {
2371
- controllerDetach = detach;
2372
- controllerOnAbort = onAbort ?? null;
2373
- }
2374
- };
2375
- combined.signal.addEventListener("abort", () => {
2376
- if (settled) return;
2377
- const reason = combined.signal.reason;
2378
- if (reason instanceof TacticalDrawAbortError) fail(reason);
2379
- else fail(new TacticalDrawAbortError("signal", { cause: reason }));
2380
- }, { once: true });
2381
- if (onViewChange) adapter.onViewChange(onViewChange);
2382
- if (typeof window !== "undefined") window.addEventListener("keydown", handleKeydown);
2383
- attach(ctx);
2384
- return {
2385
- promise,
2386
- get settled() {
2387
- return settled;
2388
- },
2389
- abort(reason, cause) {
2390
- combined.abort(reason, cause);
2391
- }
2392
- };
2393
- }
2394
2587
  /**
2395
2588
  * Round every component of a single position to {@link CONTROL_POINT_PRECISION}
2396
2589
  * places. Handles optional altitude (any trailing components) too.
@@ -2447,7 +2640,8 @@ function shouldSuppressGuide(metadata) {
2447
2640
  * Callers are responsible for the opt-out (`guide: false`) and the suppression
2448
2641
  * check via [[shouldSuppressGuide]] — this function only emits geometry.
2449
2642
  */
2450
- function buildGuideFeatures(points, isAreaKind, trailingFixedSlots = 0) {
2643
+ function buildGuideFeatures(points, isAreaKind, trailingFixedSlots = 0, segments) {
2644
+ if (segments) return segmentGuideFeatures(points, segments);
2451
2645
  const features = [];
2452
2646
  const spine = trailingFixedSlots > 0 ? points.slice(0, points.length - trailingFixedSlots) : points;
2453
2647
  if (spine.length >= 2) {
@@ -2481,7 +2675,101 @@ function buildGuideFeatures(points, isAreaKind, trailingFixedSlots = 0) {
2481
2675
  };
2482
2676
  features.push(closing);
2483
2677
  }
2484
- return features;
2678
+ return features;
2679
+ }
2680
+ /**
2681
+ * The open guide along a definition topology's real segments (ADR-0065):
2682
+ * consecutive segments that join end to start chain into one line. A single
2683
+ * chain stays a LineString, as the plain guide is; several become one
2684
+ * MultiLineString under the same id.
2685
+ */
2686
+ function segmentGuideFeatures(points, segments) {
2687
+ const chains = [];
2688
+ let lastEnd = null;
2689
+ for (const { from, to } of segments) {
2690
+ const a = points[from];
2691
+ const b = points[to];
2692
+ if (!a || !b) continue;
2693
+ if (lastEnd === from && chains.length > 0) chains[chains.length - 1].push(b);
2694
+ else chains.push([a, b]);
2695
+ lastEnd = to;
2696
+ }
2697
+ if (chains.length === 0) return [];
2698
+ return [{
2699
+ type: "Feature",
2700
+ id: PREVIEW_GUIDE_OPEN_ID,
2701
+ geometry: chains.length === 1 ? {
2702
+ type: "LineString",
2703
+ coordinates: chains[0]
2704
+ } : {
2705
+ type: "MultiLineString",
2706
+ coordinates: chains
2707
+ },
2708
+ properties: {
2709
+ part: "guide",
2710
+ segment: "open"
2711
+ }
2712
+ }];
2713
+ }
2714
+ //#endregion
2715
+ //#region src/tactical-draw/edit-modifiers.ts
2716
+ const KEY_PROPS = {
2717
+ alt: "altKey",
2718
+ shift: "shiftKey",
2719
+ ctrl: "ctrlKey",
2720
+ meta: "metaKey"
2721
+ };
2722
+ const MODIFIER_KEYS = Object.keys(KEY_PROPS);
2723
+ const DEFAULT_EDIT_MODIFIERS = Object.freeze({
2724
+ modifierDrag: Object.freeze(["ctrl", "meta"]),
2725
+ deleteOrReset: "alt",
2726
+ constrain: "shift"
2727
+ });
2728
+ function checkKey(role, key) {
2729
+ if (key === false) return false;
2730
+ if (!MODIFIER_KEYS.includes(key)) throw new RangeError(`editModifiers.${role}: ${JSON.stringify(key)} is not one of ${MODIFIER_KEYS.join(", ")} or false`);
2731
+ return key;
2732
+ }
2733
+ /**
2734
+ * Lay `patch` over `base`, validating every key. Throws a `RangeError` for an
2735
+ * unknown key, or when `deleteOrReset` shares a key with `modifierDrag` — both
2736
+ * act on the same vertex press, so the delete would silently win.
2737
+ */
2738
+ function resolveEditModifiers(base, patch) {
2739
+ let modifierDrag = base.modifierDrag;
2740
+ if (patch?.modifierDrag !== void 0) {
2741
+ const raw = patch.modifierDrag;
2742
+ const keys = (raw === false ? [] : typeof raw === "string" ? [raw] : raw).map((key) => checkKey("modifierDrag", key));
2743
+ const unique = [...new Set(keys)];
2744
+ modifierDrag = unique.length > 0 ? Object.freeze(unique) : false;
2745
+ }
2746
+ const deleteOrReset = patch?.deleteOrReset !== void 0 ? checkKey("deleteOrReset", patch.deleteOrReset) : base.deleteOrReset;
2747
+ const constrain = patch?.constrain !== void 0 ? checkKey("constrain", patch.constrain) : base.constrain;
2748
+ if (deleteOrReset && modifierDrag && modifierDrag.includes(deleteOrReset)) throw new RangeError(`editModifiers: deleteOrReset and modifierDrag both use "${deleteOrReset}"; they act on the same vertex press, so give them different keys`);
2749
+ return Object.freeze({
2750
+ modifierDrag,
2751
+ deleteOrReset,
2752
+ constrain
2753
+ });
2754
+ }
2755
+ /** Whether `info` reports any of `keys` held; never when the role is off. */
2756
+ function modifierHeld(info, keys) {
2757
+ if (!info || keys === false) return false;
2758
+ if (typeof keys === "string") return info[KEY_PROPS[keys]] === true;
2759
+ return keys.some((key) => info[KEY_PROPS[key]] === true);
2760
+ }
2761
+ /** Read `key` through engine event wrappers without assuming a DOM event type. */
2762
+ function eventModifierHeld(originalEvent, key) {
2763
+ if (key === false) return false;
2764
+ const prop = KEY_PROPS[key];
2765
+ let event = originalEvent;
2766
+ for (let depth = 0; depth < 4; depth += 1) {
2767
+ if (typeof event !== "object" || event === null) return false;
2768
+ if (prop in event && event[prop] === true) return true;
2769
+ if (!("originalEvent" in event)) return false;
2770
+ event = event.originalEvent;
2771
+ }
2772
+ return false;
2485
2773
  }
2486
2774
  //#endregion
2487
2775
  //#region src/tactical-draw/snapping.ts
@@ -2577,24 +2865,14 @@ function snappedDrawPosition(snap, event) {
2577
2865
  originalEvent: event.originalEvent
2578
2866
  })?.coordinate ?? event.coordinate;
2579
2867
  }
2580
- /** Read Shift through engine event wrappers without assuming a DOM event type. */
2581
- function shiftKeyPressed(originalEvent) {
2582
- let event = originalEvent;
2583
- for (let depth = 0; depth < 4; depth += 1) {
2584
- if (typeof event !== "object" || event === null) return false;
2585
- if ("shiftKey" in event && event.shiftKey === true) return true;
2586
- if (!("originalEvent" in event)) return false;
2587
- event = event.originalEvent;
2588
- }
2589
- return false;
2590
- }
2591
2868
  /**
2592
2869
  * Apply a rule's angular constraint to `points` when the gesture asks for it
2593
- * (Shift held) and the rule defines one. Returns `points` unchanged otherwise,
2594
- * so callers can use the result unconditionally.
2870
+ * (the `constrain` key held, Shift by default) and the rule defines one.
2871
+ * Returns `points` unchanged otherwise, so callers can use the result
2872
+ * unconditionally.
2595
2873
  */
2596
- function constrainedDrawPoints(rule, points, activePointIndex, originalEvent) {
2597
- if (!rule?.constrainAngles || !shiftKeyPressed(originalEvent)) return points;
2874
+ function constrainedDrawPoints(rule, points, activePointIndex, originalEvent, constrainKey) {
2875
+ if (!rule?.constrainAngles || !eventModifierHeld(originalEvent, constrainKey)) return points;
2598
2876
  return rule.constrainAngles(points, activePointIndex);
2599
2877
  }
2600
2878
  const DEFAULT_TOLERANCE_PIXELS = 12;
@@ -2787,6 +3065,7 @@ const PREVIEW_CURSOR$1 = "crosshair";
2787
3065
  * kinds need no host UI.
2788
3066
  */
2789
3067
  function runFixedLengthDraw(options) {
3068
+ const constrainKey = () => options.editModifiers().constrain;
2790
3069
  const { adapter, kind, previewLayer, guideLayer, renderOptions: renderOpts, generateId, signal, measureOptions, measureStyle, measureProperties, measureTextAmplifiers, guide: guideOpt, sizeAnchor, onSettled, onSession, seed, snap } = options;
2791
3070
  const metadata = getControlMeasureMetadata(kind);
2792
3071
  const rule = metadata.rule;
@@ -2883,7 +3162,7 @@ function runFixedLengthDraw(options) {
2883
3162
  }
2884
3163
  const activePointIndex = committed.length;
2885
3164
  committed.push(position);
2886
- committed.splice(0, committed.length, ...constrainedDrawPoints(rule, committed, activePointIndex, event.originalEvent));
3165
+ committed.splice(0, committed.length, ...constrainedDrawPoints(rule, committed, activePointIndex, event.originalEvent, constrainKey()));
2887
3166
  rubberBand = void 0;
2888
3167
  if (committed.length >= required) {
2889
3168
  ctx.commit(buildSnapshot);
@@ -2900,7 +3179,7 @@ function runFixedLengthDraw(options) {
2900
3179
  if (ctx.settled) return;
2901
3180
  if (committed.length === 0) return;
2902
3181
  rubberBand = snappedDrawPosition(snap, event);
2903
- const points = constrainedDrawPoints(rule, [...committed, rubberBand], committed.length, event.originalEvent);
3182
+ const points = constrainedDrawPoints(rule, [...committed, rubberBand], committed.length, event.originalEvent, constrainKey());
2904
3183
  rubberBand = points[committed.length] ?? rubberBand;
2905
3184
  renderPreview();
2906
3185
  const phase = transientStarted ? "move" : "start";
@@ -3064,6 +3343,7 @@ const PREVIEW_CURSOR = "crosshair";
3064
3343
  * added point again" as additional gesture-level commit triggers.
3065
3344
  */
3066
3345
  function runVariableLengthDraw(options) {
3346
+ const constrainKey = () => options.editModifiers().constrain;
3067
3347
  const { adapter, kind, previewLayer, guideLayer, renderOptions: renderOpts, generateId, signal, onSession, seed, measureOptions, measureStyle, measureProperties, measureTextAmplifiers, guide: guideOpt, sizeAnchor, onSettled, snap } = options;
3068
3348
  const metadata = getControlMeasureMetadata(kind);
3069
3349
  if (typeof metadata.minCoordinates !== "number") throw new Error(`runVariableLengthDraw: kind "${kind}" has no minCoordinates metadata`);
@@ -3189,7 +3469,7 @@ function runVariableLengthDraw(options) {
3189
3469
  const idx = insertionIndex(committed.length);
3190
3470
  committed.splice(idx, 0, [...pos]);
3191
3471
  if (rule) {
3192
- const derived = rule.derive(constrainedDrawPoints(rule, committed, idx, event.originalEvent));
3472
+ const derived = rule.derive(constrainedDrawPoints(rule, committed, idx, event.originalEvent, constrainKey()));
3193
3473
  committed.splice(0, committed.length, ...derived);
3194
3474
  }
3195
3475
  committed.splice(0, committed.length, ...roundControlPoints(committed));
@@ -3212,7 +3492,7 @@ function runVariableLengthDraw(options) {
3212
3492
  const idx = insertionIndex(committed.length);
3213
3493
  const spine = [...committed];
3214
3494
  spine.splice(idx, 0, rubberBand);
3215
- const points = constrainedDrawPoints(rule, spine, idx, event.originalEvent);
3495
+ const points = constrainedDrawPoints(rule, spine, idx, event.originalEvent, constrainKey());
3216
3496
  rubberBand = points[idx] ?? rubberBand;
3217
3497
  renderPreview();
3218
3498
  const phase = transientStarted ? "move" : "start";
@@ -3353,154 +3633,6 @@ function outlinePreview(points) {
3353
3633
  }
3354
3634
  return features;
3355
3635
  }
3356
- /** Whether `b` lands within {@link CLICK_SLOP_PX} of `a` — a click, not a drag. */
3357
- function withinClickSlop(a, b) {
3358
- return Math.hypot(a[0] - b[0], a[1] - b[1]) <= 3;
3359
- }
3360
- function runEditInteraction(spec) {
3361
- const { adapter, signal, layers, graphicsLayer, previewLayer, handlesLayer, closeOnClickAway } = spec;
3362
- let ctx;
3363
- let driver;
3364
- let previewPick;
3365
- let handlesPick;
3366
- let graphicsPick;
3367
- /**
3368
- * Consume exactly one trailing click without closing — set through
3369
- * `shell.suppressNextClickAway()` on delete / label-drag / post-drag paths.
3370
- *
3371
- * The suppression is scoped to the pointer cycle that armed it: it is cleared
3372
- * again on the next `pointerdown` (see the `onDown` wrapper below). Hosts do
3373
- * not agree on whether a completed drag is followed by a `click` at all —
3374
- * MapLibre swallows its `click` when the pointer moved beyond its 3px
3375
- * `clickTolerance`, while Leaflet delivers one. Without the reset, a
3376
- * suppression armed after a real drag on MapLibre survives into the *next*
3377
- * pointer cycle and eats the user's first genuine click-away, so exiting the
3378
- * edit takes two clicks instead of one.
3379
- */
3380
- let suppressClickAway = false;
3381
- /** A zero-movement body drag released this pointer cycle — set through `shell.noteBodyClick()`. */
3382
- let bodyClickPending = false;
3383
- const shell = {
3384
- suppressNextClickAway() {
3385
- suppressClickAway = true;
3386
- },
3387
- noteBodyClick() {
3388
- bodyClickPending = true;
3389
- }
3390
- };
3391
- const onPreviewPick = (event) => {
3392
- previewPick = event;
3393
- };
3394
- const onHandlesPick = (event) => {
3395
- handlesPick = event;
3396
- };
3397
- const onGraphicsPick = (event) => {
3398
- graphicsPick = event;
3399
- };
3400
- const onClick = () => {
3401
- const localPreview = previewPick;
3402
- const localHandles = handlesPick;
3403
- const localGraphics = graphicsPick;
3404
- const wasBodyClick = bodyClickPending;
3405
- previewPick = void 0;
3406
- handlesPick = void 0;
3407
- graphicsPick = void 0;
3408
- bodyClickPending = false;
3409
- if (ctx.settled) return;
3410
- if (!closeOnClickAway) return;
3411
- if (suppressClickAway) {
3412
- suppressClickAway = false;
3413
- return;
3414
- }
3415
- if (localHandles) return;
3416
- if (localGraphics && !spec.ownsGraphic(localGraphics.id)) {
3417
- spec.close();
3418
- spec.onForeignPick?.(localGraphics);
3419
- return;
3420
- }
3421
- if (localGraphics && spec.ownsGraphic(localGraphics.id)) return;
3422
- if (localPreview) return;
3423
- if (wasBodyClick) return;
3424
- spec.close();
3425
- };
3426
- return runInteraction({
3427
- adapter,
3428
- signal,
3429
- layers,
3430
- onViewChange: spec.onViewChange,
3431
- onSettled: (settlement) => {
3432
- try {
3433
- spec.historySettle();
3434
- } finally {
3435
- spec.facadeOnSettled?.();
3436
- spec.emitSettle(settlement);
3437
- }
3438
- },
3439
- attach(interaction) {
3440
- ctx = interaction;
3441
- driver = adapter.createEditPointerDriver();
3442
- let beforeTeardownRan = false;
3443
- const runBeforeTeardown = (settlement) => {
3444
- if (beforeTeardownRan) return;
3445
- beforeTeardownRan = true;
3446
- try {
3447
- spec.onBeforeTeardown?.(settlement);
3448
- } catch {}
3449
- };
3450
- const controllerContext = {
3451
- get settled() {
3452
- return interaction.settled;
3453
- },
3454
- commit(produce) {
3455
- return interaction.commit(() => {
3456
- const value = produce();
3457
- runBeforeTeardown({
3458
- status: "committed",
3459
- value
3460
- });
3461
- return value;
3462
- });
3463
- },
3464
- fail(error) {
3465
- if (!interaction.settled) runBeforeTeardown({
3466
- status: "rejected",
3467
- error
3468
- });
3469
- interaction.fail(error);
3470
- },
3471
- writeLayer: interaction.writeLayer,
3472
- onTeardown: interaction.onTeardown
3473
- };
3474
- const onDown = (pixel, info) => {
3475
- suppressClickAway = false;
3476
- spec.onDown(pixel, info);
3477
- };
3478
- const unsubDown = driver.onPointerDown(onDown);
3479
- const unsubMove = driver.onPointerMove(spec.onMove);
3480
- const unsubUp = driver.onPointerUp(spec.onUp);
3481
- const unsubPreview = adapter.onPick(previewLayer, onPreviewPick);
3482
- const unsubHandles = adapter.onPick(handlesLayer, onHandlesPick);
3483
- const unsubGraphics = adapter.onPick(graphicsLayer, onGraphicsPick);
3484
- adapter.on("click", onClick);
3485
- interaction.onTeardown(() => {
3486
- runBeforeTeardown({
3487
- status: "rejected",
3488
- error: void 0
3489
- });
3490
- adapter.off("click", onClick);
3491
- unsubPreview();
3492
- unsubHandles();
3493
- unsubGraphics();
3494
- unsubDown();
3495
- unsubMove();
3496
- unsubUp();
3497
- spec.extraTeardown?.();
3498
- driver.dispose();
3499
- }, spec.onAbort);
3500
- spec.attach(controllerContext, driver, shell);
3501
- }
3502
- });
3503
- }
3504
3636
  //#endregion
3505
3637
  //#region src/tactical-draw/handles.ts
3506
3638
  /** Size of a `compact` option handle relative to its slot's style. */
@@ -3543,7 +3675,7 @@ function segmentMidpoint(a, b) {
3543
3675
  * an empty control-point list.
3544
3676
  */
3545
3677
  function buildHandleSet(controlPoints, modes, options = {}) {
3546
- const { includeMidpoints = true, hiddenControlPointIndices = [], trailingFixedSlots = 0, closedRing = false } = options;
3678
+ const { includeMidpoints = true, hiddenControlPointIndices = [], trailingFixedSlots = 0, closedRing = false, segments } = options;
3547
3679
  const handles = [];
3548
3680
  const wantsReshape = modes.includes("reshape");
3549
3681
  if (wantsReshape || modes.includes("delete")) {
@@ -3555,7 +3687,18 @@ function buildHandleSet(controlPoints, modes, options = {}) {
3555
3687
  position: [...controlPoints[i]]
3556
3688
  });
3557
3689
  }
3558
- if (wantsReshape && includeMidpoints) {
3690
+ if (wantsReshape && includeMidpoints && segments) segments.forEach((segment, index) => {
3691
+ const a = controlPoints[segment.from];
3692
+ const b = controlPoints[segment.to];
3693
+ if (!a || !b) return;
3694
+ handles.push({
3695
+ kind: "midpoint",
3696
+ index,
3697
+ position: segmentMidpoint(a, b),
3698
+ segment: { ...segment }
3699
+ });
3700
+ });
3701
+ else if (wantsReshape && includeMidpoints) {
3559
3702
  const edgeCount = closedRing && trailingFixedSlots === 0 && controlPoints.length >= 3 ? controlPoints.length : controlPoints.length - 1 - trailingFixedSlots;
3560
3703
  for (let i = 0; i < edgeCount; i++) {
3561
3704
  const end = (i + 1) % controlPoints.length;
@@ -3577,10 +3720,12 @@ function handleFeatureId(prefix, kind, index) {
3577
3720
  case "geometry": return `${prefix}:handle-geometry:${index}`;
3578
3721
  case "scale": return `${prefix}:handle-scale:${index}`;
3579
3722
  case "rotate": return `${prefix}:handle-rotate`;
3723
+ case "snap": return `${prefix}:handle-snap:${index}`;
3580
3724
  }
3581
3725
  }
3582
- function handleStyleFor(kind, interactionStyle, unset = false) {
3726
+ function handleStyleFor(kind, interactionStyle, unset = false, active = false) {
3583
3727
  if (kind === "option" && unset && interactionStyle?.unsetOptionHandle) return interactionStyle.unsetOptionHandle;
3728
+ if (kind === "snap" && active && interactionStyle?.activeSnapTargetHandle) return interactionStyle.activeSnapTargetHandle;
3584
3729
  switch (kind) {
3585
3730
  case "vertex": return interactionStyle?.vertexHandle;
3586
3731
  case "midpoint": return interactionStyle?.midpointHandle;
@@ -3588,6 +3733,7 @@ function handleStyleFor(kind, interactionStyle, unset = false) {
3588
3733
  case "geometry": return interactionStyle?.geometryHandle;
3589
3734
  case "scale": return interactionStyle?.scaleHandle;
3590
3735
  case "rotate": return interactionStyle?.rotateHandle;
3736
+ case "snap": return interactionStyle?.snapTargetHandle;
3591
3737
  }
3592
3738
  }
3593
3739
  /**
@@ -3601,7 +3747,7 @@ function handleStyleFor(kind, interactionStyle, unset = false) {
3601
3747
  */
3602
3748
  function toFeatures(handles, featureIdPrefix, interactionStyle) {
3603
3749
  return handles.map((handle) => {
3604
- const slotStyle = handleStyleFor(handle.kind, interactionStyle, handle.unset);
3750
+ const slotStyle = handleStyleFor(handle.kind, interactionStyle, handle.unset, handle.active);
3605
3751
  const style = slotStyle && handle.compact ? compactHandleStyle(slotStyle) : slotStyle;
3606
3752
  return {
3607
3753
  type: "Feature",
@@ -3640,6 +3786,10 @@ function pickHandle(handles, pixel, tolerance, toPixel) {
3640
3786
  }
3641
3787
  //#endregion
3642
3788
  //#region src/tactical-draw/handle-drag.ts
3789
+ /** The control-point index a midpoint handle's grab inserts its new vertex at. */
3790
+ function midpointInsertIndex(handle) {
3791
+ return handle.segment?.insertAt ?? handle.index + 1;
3792
+ }
3643
3793
  function clonePoints(points) {
3644
3794
  return points.map((p) => [...p]);
3645
3795
  }
@@ -3764,9 +3914,10 @@ function beginHandleDrag(args) {
3764
3914
  }) }));
3765
3915
  }
3766
3916
  if (hit.kind !== "midpoint") throw new TypeError(`Unsupported control-point handle kind: ${hit.kind}`);
3767
- const insertIndex = hit.index + 1;
3768
- const segmentEndIndex = (hit.index + 1) % preDragPoints.length;
3769
- const mid = segmentMidpoint(preDragPoints[hit.index], preDragPoints[segmentEndIndex]);
3917
+ const insertIndex = midpointInsertIndex(hit);
3918
+ const segmentStartIndex = hit.segment?.from ?? hit.index;
3919
+ const segmentEndIndex = hit.segment?.to ?? (hit.index + 1) % preDragPoints.length;
3920
+ const mid = segmentMidpoint(preDragPoints[segmentStartIndex], preDragPoints[segmentEndIndex]);
3770
3921
  const insertedBase = [
3771
3922
  ...preDragPoints.slice(0, insertIndex),
3772
3923
  mid,
@@ -3859,6 +4010,154 @@ function beginBoxDrag(args) {
3859
4010
  };
3860
4011
  }
3861
4012
  //#endregion
4013
+ //#region src/tactical-draw/modifier-drag.ts
4014
+ /**
4015
+ * The modifier-drag state machine: a Ctrl/⌘ + drag from a vertex handed to a
4016
+ * definition's `modifierDrag` hook (ADR-0065), lifted out of `runEdit`
4017
+ * (`edit-controller.ts`) beside `handle-drag.ts`. The hook plans the drag once
4018
+ * from the pre-drag graphic and computes every frame from that plan, so this
4019
+ * module keeps the plan, the pre-drag graphic for the single commit, and the
4020
+ * snap target under the pointer.
4021
+ *
4022
+ * It is pure and projection-injected. It does not render, commit, toggle
4023
+ * drag-pan or track `dragInFlight`: those stay in the controller.
4024
+ */
4025
+ /** A Ctrl/⌘ + drag snaps onto a target within this multiple of the hit tolerance. */
4026
+ const MODIFIER_SNAP_SCALE = 1.5;
4027
+ /**
4028
+ * Start the hook's drag from vertex `index`; `null` when the hook declines
4029
+ * this point, so the press becomes a plain drag.
4030
+ */
4031
+ function beginModifierDrag(args) {
4032
+ const { hook, index, downPixel, projection } = args;
4033
+ const preDragPoints = args.controlPoints.map((p) => [...p]);
4034
+ const preDragOptions = args.options;
4035
+ const hookOptions = preDragOptions ?? {};
4036
+ const plan = hook.start({
4037
+ controlPoints: preDragPoints,
4038
+ options: hookOptions,
4039
+ index
4040
+ });
4041
+ if (!plan) return null;
4042
+ const { targets } = plan;
4043
+ const snapTolerance = args.tolerance * MODIFIER_SNAP_SCALE;
4044
+ /** The snap target the pointer is on, as an index into `targets`. */
4045
+ let target;
4046
+ function snapTarget(pixel) {
4047
+ let best;
4048
+ let bestDistance = snapTolerance;
4049
+ targets.forEach((position, k) => {
4050
+ const at = projection.toPixel(position);
4051
+ const distance = at ? pixelDistance$1(at, pixel) : Infinity;
4052
+ if (distance <= bestDistance) {
4053
+ best = k;
4054
+ bestDistance = distance;
4055
+ }
4056
+ });
4057
+ return best;
4058
+ }
4059
+ /** The pointer's lon/lat; updates the snap target. */
4060
+ function pointer(pixel) {
4061
+ target = snapTarget(pixel);
4062
+ return projection.fromPixel(pixel);
4063
+ }
4064
+ return {
4065
+ preDragPoints,
4066
+ preDragOptions,
4067
+ first: plan.first,
4068
+ move: (pixel) => plan.move(pointer(pixel), target),
4069
+ end(pixel) {
4070
+ const position = pointer(pixel);
4071
+ return target === void 0 && withinClickSlop(pixel, downPixel) ? void 0 : plan.end(position, target);
4072
+ },
4073
+ snapHandles: () => targets.map((position, k) => ({
4074
+ kind: "snap",
4075
+ index: k,
4076
+ position: [...position],
4077
+ ...k === target ? { active: true } : {}
4078
+ }))
4079
+ };
4080
+ }
4081
+ //#endregion
4082
+ //#region src/tactical-draw/part-selection.ts
4083
+ /**
4084
+ * Bind `kind`'s topology to a working graphic. `points` is the live working
4085
+ * array (mutated in place by the controller); `options` reads the current
4086
+ * working options.
4087
+ */
4088
+ function bindWorkingTopology(kind, points, options) {
4089
+ let cached = null;
4090
+ const segments = () => {
4091
+ const current = options();
4092
+ if (cached && cached.options === current && samePoints(cached.points, points)) return cached.segments;
4093
+ const result = getControlMeasureSegments(kind, points, current) ?? void 0;
4094
+ cached = {
4095
+ options: current,
4096
+ points: points.map((p) => [...p]),
4097
+ segments: result
4098
+ };
4099
+ return result;
4100
+ };
4101
+ return {
4102
+ segments,
4103
+ partOf: (index) => getControlMeasurePartOf(kind, points, options(), index),
4104
+ parts() {
4105
+ const parts = /* @__PURE__ */ new Set();
4106
+ for (const segment of segments() ?? []) if (segment.part !== void 0) parts.add(segment.part);
4107
+ return parts;
4108
+ },
4109
+ canDeleteVertex: (index) => canDeleteControlMeasureVertex(kind, points, options(), index)
4110
+ };
4111
+ }
4112
+ function samePoints(a, b) {
4113
+ return a.length === b.length && a.every((p, i) => p.length === b[i].length && p.every((c, k) => c === b[i][k]));
4114
+ }
4115
+ function createPartSelection(opts) {
4116
+ const { topology, isSettled, repaint } = opts;
4117
+ let selected = topology.parts().has(0) ? 0 : void 0;
4118
+ const listeners = createCommitEmitter("EditSession.onPartSelect listener errors");
4119
+ function select(part, repaintAfter = true) {
4120
+ if (isSettled() || part === selected) return;
4121
+ if (part === void 0 || !topology.parts().has(part)) return;
4122
+ selected = part;
4123
+ if (repaintAfter) repaint();
4124
+ listeners.emit(part);
4125
+ }
4126
+ return {
4127
+ get selected() {
4128
+ return selected;
4129
+ },
4130
+ select,
4131
+ reconcile() {
4132
+ if (selected === void 0 || topology.parts().has(selected)) return;
4133
+ select(0, false);
4134
+ },
4135
+ onSelect(listener) {
4136
+ if (isSettled()) return () => {};
4137
+ return listeners.register(listener);
4138
+ }
4139
+ };
4140
+ }
4141
+ /**
4142
+ * The part of the segment nearest `pixel` (for a click on the graphic's
4143
+ * body), or `undefined` when no projectable segment carries a part.
4144
+ */
4145
+ function partNearestPixel(pixel, segments, points, toPixel) {
4146
+ let best;
4147
+ let bestDistance = Infinity;
4148
+ for (const segment of segments ?? []) {
4149
+ const a = points[segment.from] && toPixel(points[segment.from]);
4150
+ const b = points[segment.to] && toPixel(points[segment.to]);
4151
+ if (!a || !b || segment.part === void 0) continue;
4152
+ const distance = pixelSegmentDistance(pixel, a, b);
4153
+ if (distance < bestDistance) {
4154
+ best = segment.part;
4155
+ bestDistance = distance;
4156
+ }
4157
+ }
4158
+ return best;
4159
+ }
4160
+ //#endregion
3862
4161
  //#region src/tactical-draw/deep-equal.ts
3863
4162
  /**
3864
4163
  * @internal
@@ -4760,6 +5059,8 @@ const ALLOWED_EDIT_MODES = new Set([
4760
5059
  * - close / abort / signal / preempt / destroy paths
4761
5060
  */
4762
5061
  function runEdit(opts) {
5062
+ const keys = opts.editModifiers;
5063
+ const constrainHeld = (info) => modifierHeld(info, keys().constrain);
4763
5064
  const { adapter, measure, graphicsLayer, previewLayer, guideLayer, handlesLayer, renderOptions: renderOpts, signal, closeOnClickAway = true, modes: initialModes, interactionStyle, onSession, handleIdPrefix, guide: guideOpt, settleToGraphics, publishWorkingGraphic, onSettled, onClickAwayGraphicsPick, snap, deferredSnap } = opts;
4764
5065
  let sizeAnchor = opts.sizeAnchor ?? defaultSizeAnchor(measure);
4765
5066
  let detailHandles = opts.detailHandles ?? false;
@@ -4778,6 +5079,12 @@ function runEdit(opts) {
4778
5079
  const editStartPoints = measure.controlPoints.map((p) => [...p]);
4779
5080
  const workingPoints = editStartPoints.map((p) => [...p]);
4780
5081
  let workingOptions = { ...measure.options ?? {} };
5082
+ const topology = bindWorkingTopology(measure.kind, workingPoints, () => workingOptions);
5083
+ const parts = createPartSelection({
5084
+ topology,
5085
+ isSettled: () => ctx.settled,
5086
+ repaint: () => renderHandlesLayer()
5087
+ });
4781
5088
  let workingTextAmplifiers = measure.textAmplifiers && Object.keys(measure.textAmplifiers).length > 0 ? { ...measure.textAmplifiers } : void 0;
4782
5089
  let workingAmplifierPlacements = measure.amplifierPlacements && Object.keys(measure.amplifierPlacements).length > 0 ? structuredClone(measure.amplifierPlacements) : void 0;
4783
5090
  let workingProperties = measure.properties ? structuredClone(measure.properties) : void 0;
@@ -4956,7 +5263,7 @@ function runEdit(opts) {
4956
5263
  lastWorkingFeatures = features;
4957
5264
  refitBox();
4958
5265
  const guidePoints = rule?.guidePoints ? rule.guidePoints(workingPoints) : workingPoints;
4959
- const guideFeatures = guideEnabled ? buildGuideFeatures(guidePoints, isAreaKind, trailingFixedSlots) : [];
5266
+ const guideFeatures = guideEnabled ? buildGuideFeatures(guidePoints, isAreaKind, trailingFixedSlots, topology.segments()) : [];
4960
5267
  ctx.writeLayer(guideLayer, [{
4961
5268
  id: `__td_edit_guide__:${measure.id}`,
4962
5269
  features: guideFeatures,
@@ -4975,7 +5282,8 @@ function runEdit(opts) {
4975
5282
  }
4976
5283
  function renderHandlesLayer() {
4977
5284
  if (ctx.settled) return;
4978
- const features = toFeatures(buildCurrentHandleSet(), handleIdPrefix, interactionStyle);
5285
+ parts.reconcile();
5286
+ const features = toFeatures([...buildCurrentHandleSet(), ...activeModifierDrag?.snapHandles() ?? []], handleIdPrefix, interactionStyle);
4979
5287
  if (modes.includes("labeldrag")) features.push(...labels.handleFeatures());
4980
5288
  if (modes.includes("transform")) {
4981
5289
  const liveBox = activeBoxDrag && !anchoredOptionTransformInFlight() ? activeBoxDrag.lastSnapshot.box : box;
@@ -4998,6 +5306,7 @@ function runEdit(opts) {
4998
5306
  function buildCurrentHandleSet() {
4999
5307
  const handles = buildHandleSet(workingPoints, modes, {
5000
5308
  includeMidpoints: midpointHandlesEnabled,
5309
+ segments: topology.segments(),
5001
5310
  hiddenControlPointIndices,
5002
5311
  trailingFixedSlots,
5003
5312
  closedRing
@@ -5012,6 +5321,7 @@ function runEdit(opts) {
5012
5321
  })));
5013
5322
  const optionHandles = getControlMeasureOptionHandles(measure.kind, workingPoints, workingOptions, {
5014
5323
  detail: detailHandles,
5324
+ ...parts.selected !== void 0 ? { part: parts.selected } : {},
5015
5325
  ...optionHandleContext()
5016
5326
  });
5017
5327
  for (let index = 0; index < optionHandles.length; index++) {
@@ -5469,6 +5779,15 @@ function runEdit(opts) {
5469
5779
  get detailHandles() {
5470
5780
  return detailHandles;
5471
5781
  },
5782
+ get selectedPart() {
5783
+ return parts.selected;
5784
+ },
5785
+ selectPart(part) {
5786
+ parts.select(part);
5787
+ },
5788
+ onPartSelect(listener) {
5789
+ return parts.onSelect(listener);
5790
+ },
5472
5791
  setDetailHandles(visible) {
5473
5792
  if (ctx.settled || visible === detailHandles) return;
5474
5793
  detailHandles = visible;
@@ -5542,6 +5861,40 @@ function runEdit(opts) {
5542
5861
  };
5543
5862
  let activeDrag = null;
5544
5863
  let activeOptionDrag = null;
5864
+ let activeModifierDrag = null;
5865
+ /**
5866
+ * Start the definition's Ctrl/⌘ + drag from vertex `index`; `false` when it
5867
+ * has none or declines this point, so the press becomes a plain drag.
5868
+ */
5869
+ function startModifierDrag(index, pixel, tolerance) {
5870
+ const hook = getControlMeasureModifierDrag(measure.kind);
5871
+ if (!hook) return false;
5872
+ const drag = beginModifierDrag({
5873
+ hook,
5874
+ controlPoints: workingPoints,
5875
+ options: workingOptions,
5876
+ index,
5877
+ downPixel: pixel,
5878
+ tolerance,
5879
+ projection: driver
5880
+ });
5881
+ if (!drag) return false;
5882
+ activeModifierDrag = drag;
5883
+ transient.emit("start", drag.preDragPoints, index);
5884
+ showModifierFrame(drag.first);
5885
+ dragInFlight = true;
5886
+ driver.setDragPanEnabled(false);
5887
+ return true;
5888
+ }
5889
+ /** Show a modifier-drag frame, selecting the part it names (e.g. a new flow pulled out). */
5890
+ function showModifierFrame(frame) {
5891
+ replaceWorkingPoints(frame.controlPoints);
5892
+ replaceWorkingOptions(frame.options);
5893
+ renderWorkingGraphic();
5894
+ renderHandlesLayer();
5895
+ recomputeDirty();
5896
+ if (frame.part !== void 0) parts.select(frame.part);
5897
+ }
5545
5898
  function optionsForOptionHandle(position, drag) {
5546
5899
  const patch = dragControlMeasureOptionHandle(measure.kind, workingPoints, drag.preDragOptions, drag.handleId, position, optionHandleContext());
5547
5900
  return patch ? {
@@ -5653,7 +6006,8 @@ function runEdit(opts) {
5653
6006
  const spineCount = workingPoints.length - trailingFixedSlots;
5654
6007
  if (index < 0 || index >= spineCount) return false;
5655
6008
  const minimum = rule?.minimumUserPoints ?? (isAreaKind ? 3 : 2);
5656
- return spineCount - 1 >= minimum;
6009
+ if (spineCount - 1 < minimum) return false;
6010
+ return topology.canDeleteVertex(index);
5657
6011
  }
5658
6012
  /**
5659
6013
  * Remove the vertex at `index` and commit through the normal gesture path so
@@ -5710,12 +6064,16 @@ function runEdit(opts) {
5710
6064
  }
5711
6065
  return;
5712
6066
  }
5713
- if (hit.kind === "vertex" && info?.altKey && canDeleteVertex(hit.index)) {
6067
+ const deleteOrReset = modifierHeld(info, keys().deleteOrReset);
6068
+ if (hit.kind === "vertex" && deleteOrReset && canDeleteVertex(hit.index)) {
5714
6069
  deleteVertex(hit.index);
5715
6070
  shell.suppressNextClickAway();
5716
6071
  return;
5717
6072
  }
5718
- if (hit.kind === "option" && hit.optionId && info?.altKey) {
6073
+ if (hit.kind === "vertex") parts.select(topology.partOf(hit.index));
6074
+ else if (hit.kind === "midpoint") parts.select(hit.segment?.part);
6075
+ if (hit.kind === "vertex" && modifierHeld(info, keys().modifierDrag) && startModifierDrag(hit.index, pixel, tol)) return;
6076
+ if (hit.kind === "option" && hit.optionId && deleteOrReset) {
5719
6077
  const patch = resetControlMeasureOptionHandle(measure.kind, workingPoints, workingOptions, hit.optionId, optionHandleContext());
5720
6078
  if (patch) {
5721
6079
  setOptions(patch, "gesture", "Reset option handle");
@@ -5746,13 +6104,14 @@ function runEdit(opts) {
5746
6104
  fsm,
5747
6105
  preDragPoints,
5748
6106
  preDragOptions: workingOptions,
5749
- controlPointIndex: hit.kind === "geometry" ? null : hit.kind === "midpoint" ? hit.index + 1 : hit.index
6107
+ controlPointIndex: hit.kind === "geometry" ? null : hit.kind === "midpoint" ? midpointInsertIndex(hit) : hit.index
5750
6108
  };
5751
6109
  transient.emit("start", fsm.kind === "midpoint" ? initialPoints : preDragPoints, activeDrag.controlPointIndex);
5752
6110
  if (fsm.kind === "midpoint") {
5753
6111
  followVertexChange({
5754
6112
  type: "insert",
5755
- index: hit.index + 1
6113
+ index: midpointInsertIndex(hit),
6114
+ ...hit.segment ? { segment: hit.index } : {}
5756
6115
  });
5757
6116
  workingPoints.splice(0, workingPoints.length, ...initialPoints);
5758
6117
  renderWorkingGraphic();
@@ -5805,7 +6164,7 @@ function runEdit(opts) {
5805
6164
  }
5806
6165
  function paintDragAt(resolvedPixel, info) {
5807
6166
  if (!activeDrag) return;
5808
- const snapshot = activeDrag.fsm.move(resolvedPixel, { constrainAngles: info?.shiftKey });
6167
+ const snapshot = activeDrag.fsm.move(resolvedPixel, { constrainAngles: constrainHeld(info) });
5809
6168
  workingPoints.splice(0, workingPoints.length, ...snapshot.points);
5810
6169
  renderWorkingGraphic();
5811
6170
  renderHandlesLayer();
@@ -5895,8 +6254,11 @@ function runEdit(opts) {
5895
6254
  renderHandlesLayer();
5896
6255
  }
5897
6256
  } else if (activeOptionDrag) paintOptionDragSnapshot(pixel);
5898
- else if (activeDrag) paintDragSnapshot(pixel, info);
5899
- else if (activeBoxDrag) paintBoxDragSnapshot(pixel, info, info?.shiftKey);
6257
+ else if (activeModifierDrag) {
6258
+ showModifierFrame(activeModifierDrag.move(pixel));
6259
+ transient.emit("move", workingPoints, null);
6260
+ } else if (activeDrag) paintDragSnapshot(pixel, info);
6261
+ else if (activeBoxDrag) paintBoxDragSnapshot(pixel, info, constrainHeld(info));
5900
6262
  };
5901
6263
  /** Reset drag-in-flight bookkeeping shared by every "gesture ended" path. */
5902
6264
  function endDragBookkeeping() {
@@ -5936,6 +6298,32 @@ function runEdit(opts) {
5936
6298
  }
5937
6299
  return;
5938
6300
  }
6301
+ if (activeModifierDrag) {
6302
+ const drag = activeModifierDrag;
6303
+ if (ctx.settled) {
6304
+ transient.emit("end", workingPoints, null);
6305
+ activeModifierDrag = null;
6306
+ dragInFlight = false;
6307
+ driver.setDragPanEnabled(true);
6308
+ return;
6309
+ }
6310
+ const frame = drag.end(pixel);
6311
+ activeModifierDrag = null;
6312
+ transient.emit("end", frame?.controlPoints ?? drag.preDragPoints, null);
6313
+ replaceWorkingPoints(drag.preDragPoints);
6314
+ replaceWorkingOptions(drag.preDragOptions);
6315
+ endDragBookkeeping();
6316
+ shell.suppressNextClickAway();
6317
+ if (frame) {
6318
+ replaceWorkingOptions(frame.options);
6319
+ commitGesture(frame.controlPoints, drag.preDragOptions);
6320
+ if (frame.part !== void 0) parts.select(frame.part);
6321
+ } else showModifierFrame({
6322
+ controlPoints: drag.preDragPoints,
6323
+ options: drag.preDragOptions
6324
+ });
6325
+ return;
6326
+ }
5939
6327
  if (activeDrag) {
5940
6328
  if (ctx.settled) {
5941
6329
  transient.emit("end", workingPoints, activeDrag.controlPointIndex);
@@ -5949,7 +6337,7 @@ function runEdit(opts) {
5949
6337
  driver.setDragPanEnabled(true);
5950
6338
  const snapped = snapDrag(pixel, (at) => reshapeTarget(at, info, controlPointIndex));
5951
6339
  deferred.finish(releaseDeferred(snapped.pixel, snapped.target), (finalPixel) => {
5952
- const next = fsm.end(finalPixel, { constrainAngles: info?.shiftKey });
6340
+ const next = fsm.end(finalPixel, { constrainAngles: constrainHeld(info) });
5953
6341
  transient.emit("end", next, controlPointIndex);
5954
6342
  replaceWorkingPoints(preDragPoints);
5955
6343
  commitGesture(next, preDragOptions);
@@ -5986,7 +6374,7 @@ function runEdit(opts) {
5986
6374
  };
5987
6375
  const snapped = snapDrag(pixel, (at) => translateTarget(at, info, drag));
5988
6376
  deferred.finish(releaseDeferred(snapped.pixel, snapped.target), (finalPixel) => {
5989
- const finalSnapshot = fsm.move(finalPixel, { constrainRotation: info?.shiftKey });
6377
+ const finalSnapshot = fsm.move(finalPixel, { constrainRotation: constrainHeld(info) });
5990
6378
  replaceWorkingPoints(preDragPoints);
5991
6379
  workingAmplifierPlacements = preDragAmplifierPlacements;
5992
6380
  const optionFold = foldsTransformIntoOptions && (fsm.kind === "rotate" || fsm.kind === "scale");
@@ -6020,6 +6408,7 @@ function runEdit(opts) {
6020
6408
  onMove: onDriverMove,
6021
6409
  onUp: onDriverUp,
6022
6410
  ownsGraphic: (id) => id === measure.id,
6411
+ onOwnClick: (event) => parts.select(partNearestPixel(event.pixel, topology.segments(), workingPoints, (p) => driver.toPixel(p))),
6023
6412
  close: () => {
6024
6413
  ctx.commit(rebuildRendered);
6025
6414
  },
@@ -6028,11 +6417,12 @@ function runEdit(opts) {
6028
6417
  facadeOnSettled: onSettled,
6029
6418
  emitSettle: (settlement) => settleFromInteraction(settlement, commitEmitter, settleEmitter),
6030
6419
  extraTeardown: () => {
6031
- if (activeDrag !== null || activeOptionDrag !== null || activeBoxDrag !== null || labels.dragging) {
6420
+ if (activeDrag !== null || activeOptionDrag !== null || activeModifierDrag !== null || activeBoxDrag !== null || labels.dragging) {
6032
6421
  transient.emit("end", workingPoints, activeDrag?.controlPointIndex ?? null);
6033
6422
  driver.setDragPanEnabled(true);
6034
6423
  activeDrag = null;
6035
6424
  activeOptionDrag = null;
6425
+ activeModifierDrag = null;
6036
6426
  activeBoxDrag = null;
6037
6427
  labels.endDrag();
6038
6428
  dragInFlight = false;
@@ -6590,6 +6980,7 @@ function defaultGroupSizeAnchor(graphics) {
6590
6980
  * a live session without a session boundary
6591
6981
  */
6592
6982
  function runGroupTransform(opts) {
6983
+ const constrainKey = () => opts.editModifiers().constrain;
6593
6984
  const { adapter, capability, imageCapability, markerCapability, graphics, graphicsLayer, previewLayer, handlesLayer, renderOptions: renderOpts, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, publishWorkingGraphics, settleWorkingGraphics, isOnGraphicsLayer, onSettled, onClickAwayGraphicsPick } = opts;
6594
6985
  assertCapabilityFor(graphics);
6595
6986
  validateHostResources(graphics);
@@ -7388,7 +7779,7 @@ function runGroupTransform(opts) {
7388
7779
  const boxDragPaintCoalescer = createFrameCoalescer(paintBoxDragSnapshot);
7389
7780
  const onDriverMove = (pixel, info) => {
7390
7781
  if (ctx.settled) return;
7391
- if (activeBoxDrag) boxDragPaintCoalescer.schedule(pixel, info?.shiftKey);
7782
+ if (activeBoxDrag) boxDragPaintCoalescer.schedule(pixel, modifierHeld(info, constrainKey()));
7392
7783
  };
7393
7784
  const onDriverUp = (pixel, info) => {
7394
7785
  if (!activeBoxDrag) return;
@@ -7413,7 +7804,7 @@ function runGroupTransform(opts) {
7413
7804
  shell.noteBodyClick();
7414
7805
  return;
7415
7806
  }
7416
- const finalSnapshot = fsm.move(pixel, { constrainRotation: info?.shiftKey });
7807
+ const finalSnapshot = fsm.move(pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
7417
7808
  const { scale, rotation } = boxScaleRotation(fsm.kind, finalSnapshot.box, preDragBox);
7418
7809
  const nextPointSymbolStateByMember = scalePointSymbolStates(preDragPointSymbolStateByMember, scale, rotation);
7419
7810
  applyConcatenatedPoints(preDragPoints);
@@ -7571,6 +7962,7 @@ function symbolBox(adapter, symbol, rendered, padding = 0) {
7571
7962
  };
7572
7963
  }
7573
7964
  function runPointSymbolEdit(opts) {
7965
+ const constrainKey = () => opts.editModifiers().constrain;
7574
7966
  const { adapter, capability, symbol, graphicsLayer, previewLayer, handlesLayer, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, settleToGraphics, publishWorkingGraphic, wasOnGraphicsLayer, onSettled, onClickAwayGraphicsPick, snap, deferredSnap } = opts;
7575
7967
  let modes = normalisePointModes(opts.modes ?? (symbol.offset ? ["transform", "offset"] : ["transform"]));
7576
7968
  let usesGraphicStack = wasOnGraphicsLayer;
@@ -7826,7 +8218,7 @@ function runPointSymbolEdit(opts) {
7826
8218
  }
7827
8219
  const render = capability.render(working);
7828
8220
  const modifier = opts.offsetDragModifier?.();
7829
- if (kind === "body" && modifier && info?.[`${modifier}Key`] && currentLayout.status !== "unsupported-presentation" && render.offset) offsetMode = true;
8221
+ if (kind === "body" && modifierHeld(info, modifier ?? false) && currentLayout.status !== "unsupported-presentation" && render.offset) offsetMode = true;
7830
8222
  if (!kind || offsetMode && !render.offset) return;
7831
8223
  const anchor = kind === "body" || kind === "location" || !working.offset ? currentLayout.actual : currentLayout.display;
7832
8224
  drag = {
@@ -7894,7 +8286,7 @@ function runPointSymbolEdit(opts) {
7894
8286
  }
7895
8287
  } else if (drag.kind === "rotate") {
7896
8288
  const rotation = drag.start.rotation + pointerAngle(pixel, drag.anchor) - drag.startPointerAngle;
7897
- next.rotation = normalizeRotation(info?.shiftKey ? constrainRotation(rotation) : rotation);
8289
+ next.rotation = normalizeRotation(modifierHeld(info, constrainKey()) ? constrainRotation(rotation) : rotation);
7898
8290
  } else {
7899
8291
  const distance = pixelDistance$1(pixel, drag.anchor);
7900
8292
  next.size = resizePointSymbolSize(drag.start.size, Math.max(.1, drag.start.size.value * (distance / drag.startDistance)));
@@ -8087,6 +8479,7 @@ function normaliseImageModes(input) {
8087
8479
  return modes.includes("delete") ? ["delete"] : [...new Set(modes)];
8088
8480
  }
8089
8481
  function runImageEdit(opts) {
8482
+ const constrainKey = () => opts.editModifiers().constrain;
8090
8483
  const { adapter, capability, image, graphicsLayer, previewLayer, handlesLayer, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, settleToGraphics, publishWorkingGraphic, wasOnGraphicsLayer, onSettled, onClickAwayGraphicsPick, snap } = opts;
8091
8484
  validateImageGraphic(image);
8092
8485
  let modes = normaliseImageModes(opts.modes);
@@ -8219,7 +8612,7 @@ function runImageEdit(opts) {
8219
8612
  const transformed = (pixel, info) => {
8220
8613
  if (!drag) return null;
8221
8614
  const next = cloneImageGraphic(drag.start);
8222
- const result = drag.fsm.move(pixel, { constrainRotation: info?.shiftKey });
8615
+ const result = drag.fsm.move(pixel, { constrainRotation: modifierHeld(info, constrainKey()) });
8223
8616
  next.position = [...result.points[0]];
8224
8617
  const delta = boxScaleRotation(drag.kind, result.box, drag.startBox);
8225
8618
  if (drag.kind === "scale") next.size = {
@@ -8411,6 +8804,7 @@ function normaliseMarkerModes(input) {
8411
8804
  return modes.includes("delete") ? ["delete"] : [...new Set(modes)];
8412
8805
  }
8413
8806
  function runMarkerEdit(opts) {
8807
+ const constrainKey = () => opts.editModifiers().constrain;
8414
8808
  const { adapter, capability, marker, graphicsLayer, previewLayer, handlesLayer, signal, closeOnClickAway = true, interactionStyle, onSession, handleIdPrefix, settleToGraphics, publishWorkingGraphic, wasOnGraphicsLayer, onSettled, onClickAwayGraphicsPick, snap } = opts;
8415
8809
  validateMarker(marker);
8416
8810
  let modes = normaliseMarkerModes(opts.modes);
@@ -8588,7 +8982,7 @@ function runMarkerEdit(opts) {
8588
8982
  next.position = snapTranslate(position, driver.toPixel(position) ?? pixel, info);
8589
8983
  } else if (drag.kind === "rotate") {
8590
8984
  const rotation = drag.start.rotation + pointerAngle(pixel, drag.anchor) - drag.startPointerAngle;
8591
- next.rotation = normalizeRotation(info?.shiftKey ? constrainRotation(rotation) : rotation);
8985
+ next.rotation = normalizeRotation(modifierHeld(info, constrainKey()) ? constrainRotation(rotation) : rotation);
8592
8986
  } else {
8593
8987
  const distance = pixelDistance$1(pixel, drag.anchor);
8594
8988
  next.size = resizePointSymbolSize(drag.start.size, Math.max(.1, drag.start.size.value * (distance / drag.startDistance)));
@@ -8781,6 +9175,9 @@ var TacticalDraw = class {
8781
9175
  defaultInteractionStyle;
8782
9176
  generateId;
8783
9177
  offsetDragModifier;
9178
+ editModifiers;
9179
+ /** Live read of the editor's modifier keys, so a change applies mid-edit. */
9180
+ currentEditModifiers = () => this.editModifiers;
8784
9181
  pointSymbols;
8785
9182
  images;
8786
9183
  markers;
@@ -8895,6 +9292,7 @@ var TacticalDraw = class {
8895
9292
  constructor(adapter, options) {
8896
9293
  this.adapter = adapter;
8897
9294
  this.offsetDragModifier = options?.offsetDragModifier ?? false;
9295
+ this.editModifiers = resolveEditModifiers(DEFAULT_EDIT_MODIFIERS, options?.editModifiers);
8898
9296
  this.symbolColors = options?.symbolColors ? { ...options.symbolColors } : void 0;
8899
9297
  this.labelSizeBand = options?.labelSizeBand ? { ...options.labelSizeBand } : void 0;
8900
9298
  this.labelFit = options?.labelFit ?? "shrink";
@@ -8903,7 +9301,8 @@ var TacticalDraw = class {
8903
9301
  this.sessionRenderOptions = {
8904
9302
  graphicsStyle: this.graphicsStyle,
8905
9303
  symbolColors: this.symbolColors,
8906
- highlightAppearance: { ...options?.highlightAppearance }
9304
+ highlightAppearance: { ...options?.highlightAppearance },
9305
+ context: { labelSizeBand: interactiveLabelSizeBand(this.labelSizeBand) }
8907
9306
  };
8908
9307
  this.defaultInteractionStyle = options?.interactionStyle;
8909
9308
  this.generateId = options?.generateId ?? (() => `td-${++this.idCounter}`);
@@ -8996,6 +9395,20 @@ var TacticalDraw = class {
8996
9395
  graphicUsesPinPresentation(graphic, presentation) {
8997
9396
  return (presentation ?? this.pins.resolve(graphic.id)).enabled && this.adapter.getPinPresentationCapability?.().status === "supported";
8998
9397
  }
9398
+ /**
9399
+ * Change the editor's modifier keys (see {@link TacticalDrawOptions.editModifiers}).
9400
+ * Roles the patch omits keep their current key. Applies from the next
9401
+ * pointer event, including in an active draw or edit. Throws a `RangeError`,
9402
+ * leaving the keys unchanged, when the result would be invalid.
9403
+ */
9404
+ setEditModifiers(modifiers) {
9405
+ this.assertAlive();
9406
+ this.editModifiers = resolveEditModifiers(this.editModifiers, modifiers);
9407
+ }
9408
+ /** The editor's current modifier keys, every role filled in (e.g. for hint text). */
9409
+ getEditModifiers() {
9410
+ return this.editModifiers;
9411
+ }
8999
9412
  /** Change the default shortcut for subsequent drags, including in an active edit. */
9000
9413
  setOffsetDragModifier(modifier) {
9001
9414
  this.assertAlive();
@@ -9150,7 +9563,10 @@ var TacticalDraw = class {
9150
9563
  }
9151
9564
  const render = renderMeasureForAdapter(this.adapter, graphic, {
9152
9565
  ...this.sessionRenderOptions,
9153
- context: { labelFit: this.labelFit }
9566
+ context: {
9567
+ ...this.sessionRenderOptions.context,
9568
+ labelFit: this.labelFit
9569
+ }
9154
9570
  });
9155
9571
  return {
9156
9572
  id: graphic.id,
@@ -9632,7 +10048,8 @@ var TacticalDraw = class {
9632
10048
  onSettled,
9633
10049
  onSession: this.trackSession(options?.onSession),
9634
10050
  seed: measureDraft.controlPoints,
9635
- snap: this.resolveSnap
10051
+ snap: this.resolveSnap,
10052
+ editModifiers: this.currentEditModifiers
9636
10053
  }) : runVariableLengthDraw({
9637
10054
  adapter: this.adapter,
9638
10055
  kind,
@@ -9650,7 +10067,8 @@ var TacticalDraw = class {
9650
10067
  guide: options?.guide,
9651
10068
  sizeAnchor: options?.sizeAnchor,
9652
10069
  onSettled,
9653
- snap: this.resolveSnap
10070
+ snap: this.resolveSnap,
10071
+ editModifiers: this.currentEditModifiers
9654
10072
  }), null, extraSettle);
9655
10073
  }
9656
10074
  edit(measure, options) {
@@ -9687,7 +10105,8 @@ var TacticalDraw = class {
9687
10105
  wasOnGraphicsLayer,
9688
10106
  onSettled,
9689
10107
  onClickAwayGraphicsPick: (event) => this.dispatchHostPick(this.graphicsLayer, event),
9690
- snap: this.resolveSnap
10108
+ snap: this.resolveSnap,
10109
+ editModifiers: this.currentEditModifiers
9691
10110
  }), (handle) => {
9692
10111
  handle.syncHostMembership(this.lastRenderedMeasures.some((graphic) => graphic.id === handle.measureId && isMarker(graphic)));
9693
10112
  this.activeEdit = handle;
@@ -9724,7 +10143,8 @@ var TacticalDraw = class {
9724
10143
  wasOnGraphicsLayer,
9725
10144
  onSettled,
9726
10145
  onClickAwayGraphicsPick: (event) => this.dispatchHostPick(this.graphicsLayer, event),
9727
- snap: this.resolveSnap
10146
+ snap: this.resolveSnap,
10147
+ editModifiers: this.currentEditModifiers
9728
10148
  }), (handle) => {
9729
10149
  handle.syncHostMembership(this.lastRenderedMeasures.some((graphic) => graphic.id === handle.measureId && isImageGraphic(graphic)));
9730
10150
  this.activeEdit = handle;
@@ -9770,6 +10190,7 @@ var TacticalDraw = class {
9770
10190
  onSettled,
9771
10191
  onClickAwayGraphicsPick: (event) => this.dispatchHostPick(this.graphicsLayer, event),
9772
10192
  snap: this.resolveSnap,
10193
+ editModifiers: this.currentEditModifiers,
9773
10194
  deferredSnap: this.resolveDeferredSnap
9774
10195
  }), (handle) => {
9775
10196
  handle.syncHostMembership(this.lastRenderedMeasures.some((graphic) => graphic.id === handle.measureId && isPointSymbol(graphic)));
@@ -9821,6 +10242,7 @@ var TacticalDraw = class {
9821
10242
  onSettled,
9822
10243
  onClickAwayGraphicsPick,
9823
10244
  snap: this.resolveSnap,
10245
+ editModifiers: this.currentEditModifiers,
9824
10246
  deferredSnap: this.resolveDeferredSnap
9825
10247
  }), (handle) => {
9826
10248
  this.activeEdit = handle;
@@ -9872,7 +10294,8 @@ var TacticalDraw = class {
9872
10294
  settleWorkingGraphics: (settlements) => this.settleWorkingGraphics(settlements),
9873
10295
  isOnGraphicsLayer,
9874
10296
  onSettled,
9875
- onClickAwayGraphicsPick
10297
+ onClickAwayGraphicsPick,
10298
+ editModifiers: this.currentEditModifiers
9876
10299
  }), (handle) => {
9877
10300
  this.activeTransform = handle;
9878
10301
  return () => {
@@ -10001,10 +10424,13 @@ var TacticalDraw = class {
10001
10424
  * This matters most for the active preview, since a click can land
10002
10425
  * anywhere across a rotated/offset label during an edit.
10003
10426
  *
10004
- * `tolerance` defaults to `pickHitTolerance(options?.originalEvent)` —
10005
- * pass the host's raw click event as `originalEvent` to get the same
10006
- * pointer-type-aware tolerance (4px mouse/pen, 12px touch) `onPick` uses;
10007
- * pass an explicit `tolerance` to override it outright.
10427
+ * `tolerance` defaults per layer and by pointer type — pass the host's raw
10428
+ * click event as `originalEvent` to get the right one: edit handles take
10429
+ * the edit session's own handle tolerance (12px mouse/pen, 22px touch), so
10430
+ * a pixel the edit would press as a handle is owned by `handles`; preview
10431
+ * and graphics take `pickHitTolerance` (4px mouse/pen, 12px touch), as
10432
+ * `onPick` does. Pass an explicit `tolerance` to override it for every
10433
+ * layer.
10008
10434
  *
10009
10435
  * `measureId` is set when the hit feature resolves to a control-measure id
10010
10436
  * via `tryControlMeasureIdFromFeature` — present for graphics/preview
@@ -10017,7 +10443,9 @@ var TacticalDraw = class {
10017
10443
  */
10018
10444
  ownsInteractionAt(pixel, options) {
10019
10445
  this.assertAlive();
10020
- const tolerance = options?.tolerance ?? pickHitTolerance(options?.originalEvent);
10446
+ const pointerType = pickPointerType(options?.originalEvent);
10447
+ const pickTolerance = options?.tolerance ?? pickHitTolerance(options?.originalEvent);
10448
+ const handleTolerance = options?.tolerance ?? (pointerType === "touch" ? 22 : 12);
10021
10449
  const toPixel = (lonLat) => this.adapter.getPixelFromCoordinate(lonLat);
10022
10450
  const layers = [
10023
10451
  {
@@ -10037,10 +10465,10 @@ var TacticalDraw = class {
10037
10465
  }
10038
10466
  ];
10039
10467
  const size = this.adapter.getViewportSize();
10040
- const context = {
10468
+ const pickContext = {
10041
10469
  pixel,
10042
- pointerType: pickPointerType(options?.originalEvent),
10043
- tolerance,
10470
+ pointerType,
10471
+ tolerance: pickTolerance,
10044
10472
  toPixel,
10045
10473
  viewport: {
10046
10474
  minX: 0,
@@ -10051,6 +10479,10 @@ var TacticalDraw = class {
10051
10479
  bearing: this.adapter.getBearing()
10052
10480
  };
10053
10481
  for (const { layer, layerId, labelFallback } of layers) {
10482
+ const context = layer === "handles" ? {
10483
+ ...pickContext,
10484
+ tolerance: handleTolerance
10485
+ } : pickContext;
10054
10486
  const features = this.adapter.getLayerFeatures(layerId);
10055
10487
  const geometryCandidate = evaluatePickCandidates(features.map((feature, index) => ({
10056
10488
  feature,
@@ -10344,6 +10776,18 @@ const BUILT_IN_INTERACTION_STYLE = {
10344
10776
  strokeColor: "#ffffff",
10345
10777
  strokeWidth: 2
10346
10778
  },
10779
+ snapTargetHandle: {
10780
+ pointRadius: 10,
10781
+ fillColor: "rgba(22, 163, 74, 0.12)",
10782
+ strokeColor: "#16a34a",
10783
+ strokeWidth: 1.5
10784
+ },
10785
+ activeSnapTargetHandle: {
10786
+ pointRadius: 13,
10787
+ fillColor: "rgba(22, 163, 74, 0.25)",
10788
+ strokeColor: "#16a34a",
10789
+ strokeWidth: 3
10790
+ },
10347
10791
  scaleHandle: {
10348
10792
  pointRadius: 5,
10349
10793
  fillColor: "#ffffff",
@@ -10364,6 +10808,8 @@ const HANDLE_SLOTS = [
10364
10808
  "unsetOptionHandle",
10365
10809
  "geometryHandle",
10366
10810
  "labelHandle",
10811
+ "snapTargetHandle",
10812
+ "activeSnapTargetHandle",
10367
10813
  "scaleHandle",
10368
10814
  "rotateHandle"
10369
10815
  ];
@@ -10669,4 +11115,4 @@ function nearestWorldCopyPosition(position, refLng) {
10669
11115
  return [nearestWorldCopyLng(position[0], refLng), ...position.slice(1)];
10670
11116
  }
10671
11117
  //#endregion
10672
- export { BaseMapAdapter, 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, 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, resizePointSymbolSize, resolveGroundTextSizePixels, resolveHighlightBands, resolveHighlightCasing, resolveMarkerRender, resolvePickPresentation, resolvePinPresentation, resolvePointSymbolOffset, resolveTextAppearance, resolveTextHaloWidth, resolveTextSizePixels, scalePointSymbolLayout, tryControlMeasureIdFromFeature, validateImageGraphic, validateMarker };
11118
+ 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 };