@trackunit/react-map 0.2.296 → 0.2.297

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/index.cjs.js CHANGED
@@ -9610,14 +9610,14 @@ const groupKeyOf = (group) => group
9610
9610
  * time and only the ones that throw are skipped, so one degenerate neighbour costs the overlap with
9611
9611
  * that neighbour alone rather than every clip of the subject.
9612
9612
  */
9613
- const clipAgainstHigherRanked = (subject, clips) => {
9613
+ const clipAgainstHigherRanked = (subject, clips, polygonDifference) => {
9614
9614
  let fallbacks = 0;
9615
9615
  let lastError;
9616
9616
  const onFallback = (error) => {
9617
9617
  fallbacks += 1;
9618
9618
  lastError = error;
9619
9619
  };
9620
- const batched = geoJsonUtils.geoJsonPolygonDifference(subject, clips.map(clip => clip.geometry), onFallback);
9620
+ const batched = polygonDifference(subject, clips.map(clip => clip.geometry), onFallback);
9621
9621
  if (fallbacks === 0)
9622
9622
  return { geometry: batched, failure: null };
9623
9623
  // The batch failed: subtract one clip at a time and skip only the clips that throw on their own.
@@ -9627,7 +9627,7 @@ const clipAgainstHigherRanked = (subject, clips) => {
9627
9627
  if (current === null)
9628
9628
  break;
9629
9629
  const before = fallbacks;
9630
- const next = geoJsonUtils.geoJsonPolygonDifference(current, [clip.geometry], onFallback);
9630
+ const next = polygonDifference(current, [clip.geometry], onFallback);
9631
9631
  if (fallbacks > before) {
9632
9632
  skipped.push(clip.id);
9633
9633
  continue;
@@ -9639,7 +9639,7 @@ const clipAgainstHigherRanked = (subject, clips) => {
9639
9639
  };
9640
9640
  /** Promote `id` to the front of `order` (no-op if not present). */
9641
9641
  const promoteToFront = (order, id) => order.includes(id) ? [id, ...order.filter(item => item !== id)] : order;
9642
- const computePromotionGroupFills = ({ members, winnerId, restingPeerFills = new Map(), layerGeodesic, featureStyles, onDifferenceFallback, }) => {
9642
+ const computePromotionGroupFills = ({ members, winnerId, restingPeerFills = new Map(), layerGeodesic, featureStyles, polygonDifference = geoJsonUtils.geoJsonPolygonDifference, onDifferenceFallback, }) => {
9643
9643
  // Densify before peer-vs-winner clip so promotion clips follow great-circle
9644
9644
  // arcs. Always defer to densifyGeodesicFeatures' per-feature resolution
9645
9645
  // (geodesic override > layer default) rather than short-circuiting on
@@ -9680,7 +9680,7 @@ const computePromotionGroupFills = ({ members, winnerId, restingPeerFills = new
9680
9680
  subject = restingPolygonal;
9681
9681
  }
9682
9682
  const subjectMercator = geoJsonUtils.projectPolygonalToWebMercator(subject);
9683
- const clippedMercator = geoJsonUtils.geoJsonPolygonDifference(subjectMercator, [winnerMercator], error => {
9683
+ const clippedMercator = polygonDifference(subjectMercator, [winnerMercator], error => {
9684
9684
  onDifferenceFallback?.(memberId, error);
9685
9685
  });
9686
9686
  const clipped = clippedMercator === null ? null : geoJsonUtils.unprojectPolygonalFromWebMercator(clippedMercator);
@@ -9689,7 +9689,7 @@ const computePromotionGroupFills = ({ members, winnerId, restingPeerFills = new
9689
9689
  return result;
9690
9690
  };
9691
9691
  const computeFillTiling = (input) => {
9692
- const { features, viewportBounds, resolveStackOrder, selectedFeatureId, suppressedFeatureIds, layerGeodesic, featureStyles, } = input;
9692
+ const { features, viewportBounds, resolveStackOrder, selectedFeatureId, suppressedFeatureIds, layerGeodesic, featureStyles, polygonDifference = geoJsonUtils.geoJsonPolygonDifference, } = input;
9693
9693
  // Validation boundary (SAGA-664): validate each input feature's polygonal
9694
9694
  // geometry once here — O(n) — dropping malformed geometry. The downstream O(n²)
9695
9695
  // overlap loop then runs the pure predicates on trusted geometry without a
@@ -9807,7 +9807,7 @@ const computeFillTiling = (input) => {
9807
9807
  // Nothing above touches this member: no override, the adapter renders the full geometry.
9808
9808
  if (higherRanked.length === 0)
9809
9809
  continue;
9810
- const { geometry: clippedMercator, failure } = clipAgainstHigherRanked(mercatorOf(record), higherRanked.map(above => ({ id: above.id, geometry: mercatorOf(above) })));
9810
+ const { geometry: clippedMercator, failure } = clipAgainstHigherRanked(mercatorOf(record), higherRanked.map(above => ({ id: above.id, geometry: mercatorOf(above) })), polygonDifference);
9811
9811
  if (failure !== null) {
9812
9812
  differenceFailures.push({ featureId: id, clipFeatureIds: failure.clipFeatureIds, error: failure.error });
9813
9813
  }
@@ -12040,6 +12040,198 @@ const captureFillTilingDifferenceFailures = (differenceFailures, layerHandleId,
12040
12040
  }
12041
12041
  };
12042
12042
 
12043
+ /**
12044
+ * Clipper2 scales coordinates to integers by 10^precision. Fill tiling clips in Web Mercator
12045
+ * metres, so 3 keeps millimetres.
12046
+ */
12047
+ const MERCATOR_PRECISION = 3;
12048
+ /** Metres added around the subject bbox before trimming clips, so rect edges stay clear of subject vertices. */
12049
+ const RECT_CLIP_MARGIN = 1;
12050
+ const polygonsOf = (geometry) => geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
12051
+ const signedArea = (ring) => {
12052
+ let sum = 0;
12053
+ for (let i = 0; i + 1 < ring.length; i++) {
12054
+ const current = ring[i];
12055
+ const next = ring[i + 1];
12056
+ if (current === undefined || next === undefined)
12057
+ continue;
12058
+ sum += current[0] * next[1] - next[0] * current[1];
12059
+ }
12060
+ return sum / 2;
12061
+ };
12062
+ /**
12063
+ * GeoJSON rings become Clipper2 paths with the closing vertex dropped. Exterior rings are forced
12064
+ * counter-clockwise and holes clockwise so that NonZero winding matches polygon-clipping for
12065
+ * well-nested, non-overlapping holes: holes subtract, and clips that overlap each other still union.
12066
+ *
12067
+ * Known divergence for invalid hole configurations that the schema does not reject: NonZero sums
12068
+ * windings, so where two holes of one polygon overlap (winding −1) the area counts as filled, and
12069
+ * the part of a hole that pokes outside its exterior (winding −1 as well) is painted. polygon-clipping
12070
+ * excludes any region inside an interior ring instead. See the spec for the pinned numbers.
12071
+ */
12072
+ const appendRingsAsPaths = (clipper, paths, geometries) => {
12073
+ for (const geometry of geometries) {
12074
+ for (const rings of polygonsOf(geometry)) {
12075
+ rings.forEach((ring, ringIndex) => {
12076
+ const wantCounterClockwise = ringIndex === 0;
12077
+ const oriented = signedArea(ring) > 0 === wantCounterClockwise ? ring : [...ring].reverse();
12078
+ // Drop the closing vertex; Clipper2 paths are implicitly closed.
12079
+ const flat = [];
12080
+ for (const [x, y] of oriented.slice(0, -1))
12081
+ flat.push(x, y);
12082
+ const path = clipper.MakePathD(flat);
12083
+ paths.push_back(path);
12084
+ path.delete();
12085
+ });
12086
+ }
12087
+ }
12088
+ };
12089
+ /**
12090
+ * Closed GeoJSON ring from a tree node. `polygon()` hands out an owned copy whose `view()` is
12091
+ * x, y, z per vertex (Z build); it is released as soon as the coordinates are copied out.
12092
+ */
12093
+ const ringOf = (node) => {
12094
+ const path = node.polygon();
12095
+ try {
12096
+ const xyz = path.view();
12097
+ const ring = [];
12098
+ for (let i = 0; i + 2 < xyz.length; i += 3) {
12099
+ ring.push([xyz[i] ?? 0, xyz[i + 1] ?? 0]);
12100
+ }
12101
+ const first = ring[0];
12102
+ if (first !== undefined)
12103
+ ring.push(first);
12104
+ return ring;
12105
+ }
12106
+ finally {
12107
+ path.delete();
12108
+ }
12109
+ };
12110
+ /**
12111
+ * Walk the PolyTree: each child of an outer is a hole, each child of a hole is an island.
12112
+ * `child()` returns non-owning references into the tree and must not be deleted.
12113
+ */
12114
+ const collectPolygons = (node, into) => {
12115
+ const outerCount = node.count();
12116
+ for (let i = 0; i < outerCount; i++) {
12117
+ const outer = node.child(i);
12118
+ const rings = [ringOf(outer)];
12119
+ const holeCount = outer.count();
12120
+ for (let h = 0; h < holeCount; h++) {
12121
+ const hole = outer.child(h);
12122
+ rings.push(ringOf(hole));
12123
+ collectPolygons(hole, into);
12124
+ }
12125
+ into.push(rings);
12126
+ }
12127
+ };
12128
+ const bboxOf = (geometry) => {
12129
+ let minX = Infinity;
12130
+ let minY = Infinity;
12131
+ let maxX = -Infinity;
12132
+ let maxY = -Infinity;
12133
+ for (const rings of polygonsOf(geometry)) {
12134
+ const exterior = rings[0];
12135
+ if (exterior === undefined)
12136
+ continue;
12137
+ for (const [x, y] of exterior) {
12138
+ if (x < minX)
12139
+ minX = x;
12140
+ if (x > maxX)
12141
+ maxX = x;
12142
+ if (y < minY)
12143
+ minY = y;
12144
+ if (y > maxY)
12145
+ maxY = y;
12146
+ }
12147
+ }
12148
+ return [minX, minY, maxX, maxY];
12149
+ };
12150
+ /**
12151
+ * Build the difference function on an instantiated module. Throws (from Clipper2 or from the
12152
+ * bridge itself) propagate to the caller, which owns the fallback and the reporting; every embind
12153
+ * object is released in `finally` either way.
12154
+ */
12155
+ const createClipper2PolygonDifference = (clipper) => (subject, clips) => {
12156
+ if (clips.length === 0)
12157
+ return subject;
12158
+ const owned = [];
12159
+ try {
12160
+ const subjectPaths = new clipper.PathsD();
12161
+ owned.push(subjectPaths);
12162
+ appendRingsAsPaths(clipper, subjectPaths, [subject]);
12163
+ const clipPaths = new clipper.PathsD();
12164
+ owned.push(clipPaths);
12165
+ appendRingsAsPaths(clipper, clipPaths, clips);
12166
+ // Trim every clip to the subject's bbox first (O(n)), so a country-sized clip only
12167
+ // contributes the few edges near a site-sized subject.
12168
+ const [minX, minY, maxX, maxY] = bboxOf(subject);
12169
+ const rect = new clipper.RectD(minX - RECT_CLIP_MARGIN, minY - RECT_CLIP_MARGIN, maxX + RECT_CLIP_MARGIN, maxY + RECT_CLIP_MARGIN);
12170
+ owned.push(rect);
12171
+ const trimmedClips = clipper.RectClipPathsD(rect, clipPaths, MERCATOR_PRECISION);
12172
+ owned.push(trimmedClips);
12173
+ const solution = new clipper.PolyPathD();
12174
+ owned.push(solution);
12175
+ clipper.BooleanOpOutD(clipper.ClipType.Difference, clipper.FillRule.NonZero, subjectPaths, trimmedClips, solution, MERCATOR_PRECISION);
12176
+ const polygons = [];
12177
+ collectPolygons(solution, polygons);
12178
+ const [single] = polygons;
12179
+ if (single === undefined)
12180
+ return null;
12181
+ if (polygons.length === 1)
12182
+ return { type: "Polygon", coordinates: single };
12183
+ return { type: "MultiPolygon", coordinates: polygons };
12184
+ }
12185
+ finally {
12186
+ for (const object of owned)
12187
+ object.delete();
12188
+ }
12189
+ };
12190
+ let sharedEngine = null;
12191
+ let loadedEngine;
12192
+ let unusable = false;
12193
+ const createEngine = async (options) => {
12194
+ const { default: createClipper2Module } = await import('clipper2-wasm/dist/es/clipper2z.js');
12195
+ // Emscripten writes load failures and aborts to console.error as well as throwing. The thrown
12196
+ // error is what callers act on (rejected load, or a throw from the returned function that the
12197
+ // fill-tiling hook reports and falls back from), so keep the duplicate stderr channel quiet.
12198
+ const clipper = await createClipper2Module({ ...options, printErr: () => undefined });
12199
+ return createClipper2PolygonDifference(clipper);
12200
+ };
12201
+ /**
12202
+ * Polygon difference backed by Clipper2 compiled to WebAssembly: a drop-in for
12203
+ * `geoJsonPolygonDifference` in fill tiling, roughly 6× faster on the same inputs. Unlike
12204
+ * `geoJsonPolygonDifference` it throws on failure instead of returning the subject unclipped:
12205
+ * polygon-clipping is still available as an exact fallback, and an Emscripten abort disables the
12206
+ * module for good, so the caller decides how to degrade and report.
12207
+ *
12208
+ * The module (~210 KB) is fetched and instantiated on first call and shared afterwards, including a
12209
+ * failed load: callers keep `geoJsonPolygonDifference` until the promise resolves and stay on it for
12210
+ * the page lifetime if it rejects (no WebAssembly support, blocked asset, …). `options.wasmBinary`
12211
+ * bypasses the fetch; engines created with options are not shared.
12212
+ */
12213
+ const loadClipper2PolygonDifference = (options) => {
12214
+ if (unusable)
12215
+ return Promise.reject(new Error("Clipper2 was marked unusable after a runtime failure"));
12216
+ sharedEngine ?? (sharedEngine = createEngine(undefined).then(engine => {
12217
+ loadedEngine = engine;
12218
+ return engine;
12219
+ }));
12220
+ return sharedEngine;
12221
+ };
12222
+ /** The shared engine when it has already loaded, so a later mount can use it for its first pass. */
12223
+ const getLoadedClipper2PolygonDifference = () => loadedEngine;
12224
+ /**
12225
+ * Called when the shared engine threw: an Emscripten abort disables the module for the rest of the
12226
+ * page, so no later mount may adopt it and no reload is attempted.
12227
+ */
12228
+ const markClipper2PolygonDifferenceUnusable = () => {
12229
+ unusable = true;
12230
+ loadedEngine = undefined;
12231
+ };
12232
+ /** Whether the shared engine was marked unusable; callers stay on polygon-clipping silently. */
12233
+ const isClipper2PolygonDifferenceUnusable = () => unusable;
12234
+
12043
12235
  /** Lists the ids of features dropped from fill tiling, or a placeholder when none carry an id. */
12044
12236
  const formatDroppedInvalidFeatureIds = (dropped) => dropped
12045
12237
  .map(entry => (entry.feature.id !== undefined ? String(entry.feature.id) : undefined))
@@ -12241,6 +12433,13 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12241
12433
  const errorHandler = reactCoreHooks.useErrorHandlerOrNull();
12242
12434
  /** Handle/feature keys already reported to Sentry this session. */
12243
12435
  const sessionReportedDedupeKeysRef = react.useRef(new Set());
12436
+ /**
12437
+ * Clipper2 WebAssembly difference once loaded, wrapped so that a failure reports once and
12438
+ * hands the clip (and every later clip) back to polygon-clipping. `undefined` = default path.
12439
+ */
12440
+ const polygonDifferenceRef = react.useRef(undefined);
12441
+ /** Load lifecycle; `settled` (loaded, failed or unusable) means the effect never re-subscribes. */
12442
+ const clipper2StatusRef = react.useRef("idle");
12244
12443
  const tilingContentKey = react.useMemo(() => buildTilingContentKey(handles), [handles]);
12245
12444
  const tilingHandles = react.useMemo(() => handles.filter((handle) => handle.layerType === "shapes" && handle.overlap?.mode === "tile"), [handles]);
12246
12445
  const hasTilingHandles = tilingHandles.length > 0;
@@ -12382,6 +12581,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12382
12581
  restingPeerFills,
12383
12582
  layerGeodesic: handle?.style.geodesic,
12384
12583
  featureStyles: handle?.featureStyles,
12584
+ polygonDifference: polygonDifferenceRef.current,
12385
12585
  onDifferenceFallback: (featureId, error) => {
12386
12586
  unclippedPeerIds.push(featureId);
12387
12587
  if (errorHandler === null)
@@ -12499,6 +12699,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12499
12699
  suppressedFeatureIds: suppressedFillIdsByHandleRef.current?.get(handle.id),
12500
12700
  layerGeodesic: handle.style.geodesic,
12501
12701
  featureStyles: handle.featureStyles,
12702
+ polygonDifference: polygonDifferenceRef.current,
12502
12703
  });
12503
12704
  // The dev warnings live here, not in computeFillTiling: recompute runs from
12504
12705
  // effects and idle callbacks, so the pure function stays silent (SAGA-907).
@@ -12566,6 +12767,67 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12566
12767
  flushPendingRestingRecompute();
12567
12768
  }, IDLE_RECOMPUTE_DEBOUNCE_MS);
12568
12769
  }, [flushPendingRestingRecompute]);
12770
+ // Use the Clipper2 WebAssembly difference for the clip phase once a tiling layer exists. An engine
12771
+ // that already loaded (an earlier map on this page) is adopted synchronously here, before the
12772
+ // mount recompute below, so the first pass already uses it. Otherwise the load runs in the
12773
+ // background and the resting clips are re-tiled through the idle path when it resolves, so a load
12774
+ // finishing mid-pan never freezes the gesture. A failed load (no WebAssembly, blocked asset) or a
12775
+ // failing clip keeps polygon-clipping for the rest of this map's life, reported once each.
12776
+ react.useEffect(() => {
12777
+ if (!hasTilingHandles || clipper2StatusRef.current !== "idle")
12778
+ return;
12779
+ if (isClipper2PolygonDifferenceUnusable()) {
12780
+ // Another map on this page already hit a runtime failure and reported it.
12781
+ clipper2StatusRef.current = "settled";
12782
+ return;
12783
+ }
12784
+ const adopt = (clipper2Difference) => {
12785
+ clipper2StatusRef.current = "settled";
12786
+ polygonDifferenceRef.current = (subject, clips, onFallback) => {
12787
+ try {
12788
+ return clipper2Difference(subject, clips);
12789
+ }
12790
+ catch (error) {
12791
+ // An Emscripten abort disables the module for good: for this map and any later one.
12792
+ markClipper2PolygonDifferenceUnusable();
12793
+ polygonDifferenceRef.current = undefined;
12794
+ errorHandler?.captureException(new Error(`Clipper2 WebAssembly difference failed; fill tiling falls back to polygon-clipping: ${String(error)}`), { level: "warning", fingerprint: ["react-map", "fill-tiling", "clipper2-difference-failed"] });
12795
+ return geoJsonUtils.geoJsonPolygonDifference(subject, clips, onFallback);
12796
+ }
12797
+ };
12798
+ };
12799
+ const loaded = getLoadedClipper2PolygonDifference();
12800
+ if (loaded !== undefined) {
12801
+ adopt(loaded);
12802
+ return;
12803
+ }
12804
+ clipper2StatusRef.current = "loading";
12805
+ let cancelled = false;
12806
+ loadClipper2PolygonDifference()
12807
+ .then(clipper2Difference => {
12808
+ if (cancelled)
12809
+ return;
12810
+ adopt(clipper2Difference);
12811
+ // Re-tile the resting clips with the engine, but never mid-gesture: while the map moves the
12812
+ // existing `idle` handler flushes the pending recompute once the movement settles.
12813
+ lastComputeInputKeyRef.current = null;
12814
+ pendingRestingRecomputeRef.current = true;
12815
+ if (!isMapMovingRef.current)
12816
+ scheduleIdleRestingRecompute();
12817
+ })
12818
+ .catch((error) => {
12819
+ if (cancelled)
12820
+ return;
12821
+ clipper2StatusRef.current = "settled";
12822
+ errorHandler?.captureException(new Error(`Clipper2 WebAssembly engine failed to load; fill tiling stays on polygon-clipping: ${String(error)}`), { level: "warning", fingerprint: ["react-map", "fill-tiling", "clipper2-load-failed"] });
12823
+ });
12824
+ return () => {
12825
+ cancelled = true;
12826
+ // Unmounted mid-load: allow the next mount of a tiling layer to subscribe again.
12827
+ if (clipper2StatusRef.current === "loading")
12828
+ clipper2StatusRef.current = "idle";
12829
+ };
12830
+ }, [hasTilingHandles, scheduleIdleRestingRecompute, errorHandler]);
12569
12831
  const clearSelectionPromotion = react.useCallback((handleId, featureId) => {
12570
12832
  const groupKey = featureToGroupKeyByHandleRef.current.get(handleId)?.get(featureId);
12571
12833
  if (groupKey === undefined)