@trackunit/react-map 0.2.295 → 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.esm.js CHANGED
@@ -15,7 +15,7 @@ import { z } from 'zod';
15
15
  import { readLocalStorageValue, nonNullable } from '@trackunit/shared-utils';
16
16
  import { PieChart } from 'react-minimal-pie-chart';
17
17
  import { tailwindPalette } from '@trackunit/ui-design-tokens';
18
- import { lngLatToMercatorPxWS, validateBboxWithFallback, extractPositionsFromGeometry, geoJsonPositionSchema, validateFeatureCollection, EMPTY_FEATURE_COLLECTION, splitAntimeridianCrossingFeatures, validateBbox, projectPolygonalToWebMercator, geoJsonPolygonDifference, unprojectPolygonalFromWebMercator, geoJsonPolygonSchema, geoJsonMultiPolygonSchema, distanceToGeoJsonPolygonBoundary, getGeoJsonPolygonIntersection, isFullyContainedInGeometry, isGeoJsonPointInPolygon, isBboxInsideFeatureCollection, extractEdges, computeGeometryCentroid, mercatorPxToLngLatWS, isPositionInsideRing, lngLatToWebMercatorPx, edgePixelLength, isFullyContainedInGeoJsonGeometry } from '@trackunit/geo-json-utils';
18
+ import { lngLatToMercatorPxWS, validateBboxWithFallback, extractPositionsFromGeometry, geoJsonPositionSchema, validateFeatureCollection, EMPTY_FEATURE_COLLECTION, splitAntimeridianCrossingFeatures, validateBbox, projectPolygonalToWebMercator, geoJsonPolygonDifference, unprojectPolygonalFromWebMercator, geoJsonPolygonSchema, geoJsonMultiPolygonSchema, distanceToGeoJsonPolygonBoundary, polygonalGeometriesOverlap, isFullyContainedInGeometry, isGeoJsonPointInPolygon, isBboxInsideFeatureCollection, extractEdges, computeGeometryCentroid, mercatorPxToLngLatWS, isPositionInsideRing, lngLatToWebMercatorPx, edgePixelLength, isFullyContainedInGeoJsonGeometry } from '@trackunit/geo-json-utils';
19
19
  import { darkenColor, lightenColor } from '@trackunit/react-map-color-utils';
20
20
 
21
21
  var defaultTranslations = {
@@ -9509,13 +9509,15 @@ const shapesUnderCursor = (position, features, options) => {
9509
9509
  };
9510
9510
  /**
9511
9511
  * Connected components of features that share fill area. Bbox prefilter then
9512
- * exact polygon intersection, mirroring `countOverlappingShapes`.
9512
+ * exact overlap predicate, mirroring `countOverlappingShapes`.
9513
9513
  *
9514
- * `getGeoJsonPolygonIntersection` delegates to `polygon-clipping`, which can throw
9515
- * `"Unable to complete output ring"` for degenerate but schema-valid geometry
9516
- * (SAGA-743). A throw here is treated as "no overlap" — the safe degradation for
9517
- * grouping — and recorded in `intersectionFailures` so the hook can report it
9518
- * (mirrors how `droppedInvalidFeatures` surfaces the sibling failure mode).
9514
+ * `polygonalGeometriesOverlap` answers the yes/no question without computing the
9515
+ * intersection geometry; only degenerate pairs (touching edges, shared vertices)
9516
+ * fall back to `polygon-clipping`, which can throw `"Unable to complete output ring"`
9517
+ * for degenerate but schema-valid geometry (SAGA-743). A throw here is treated as
9518
+ * "no overlap" — the safe degradation for grouping — and recorded in
9519
+ * `intersectionFailures` so the hook can report it (mirrors how
9520
+ * `droppedInvalidFeatures` surfaces the sibling failure mode).
9519
9521
  */
9520
9522
  const buildOverlapGroups = (records) => {
9521
9523
  const parent = records.map((_, index) => index);
@@ -9545,7 +9547,7 @@ const buildOverlapGroups = (records) => {
9545
9547
  continue;
9546
9548
  let overlaps;
9547
9549
  try {
9548
- overlaps = getGeoJsonPolygonIntersection(a.geometry, b.geometry) !== null;
9550
+ overlaps = polygonalGeometriesOverlap(a.geometry, b.geometry);
9549
9551
  }
9550
9552
  catch (error) {
9551
9553
  // polygon-clipping failed on this pair. Treat as no overlap (do not union)
@@ -9571,11 +9573,19 @@ const buildOverlapGroups = (records) => {
9571
9573
  });
9572
9574
  return { groups: [...groups.values()].filter(group => group.length >= 2), intersectionFailures };
9573
9575
  };
9576
+ /**
9577
+ * A geometry can only be contained in another when its bbox sits inside the other's bbox.
9578
+ * `computeBbox` never emits a wrapped (west > east) box; an antimeridian-split MultiPolygon gets a
9579
+ * conservative full-width box, which only makes this pre-test pass more often, never less.
9580
+ */
9581
+ const bboxMayBeContained = (inner, outer) => inner[0] >= outer[0] && inner[1] >= outer[1] && inner[2] <= outer[2] && inner[3] <= outer[3];
9574
9582
  const buildContendedShapes = (group) => group.map(record => {
9575
9583
  const containedIn = [];
9576
9584
  for (const other of group) {
9577
9585
  if (other.id === record.id)
9578
9586
  continue;
9587
+ if (!bboxMayBeContained(record.bbox, other.bbox))
9588
+ continue;
9579
9589
  // Pure predicate: geometry was validated once at the computeFillTiling
9580
9590
  // boundary, so this O(n²) loop performs no safeParse per pair (SAGA-664).
9581
9591
  if (isFullyContainedInGeometry(record.geometry, other.geometry)) {
@@ -9593,16 +9603,42 @@ const groupKeyOf = (group) => group
9593
9603
  .map(record => record.id)
9594
9604
  .sort()
9595
9605
  .join("|");
9606
+ /**
9607
+ * `subject` minus all `clips`, in Web Mercator. `polygon-clipping` can throw for degenerate but
9608
+ * schema-valid geometry (SAGA-743); when the batched call fails, the clips are subtracted one at a
9609
+ * time and only the ones that throw are skipped, so one degenerate neighbour costs the overlap with
9610
+ * that neighbour alone rather than every clip of the subject.
9611
+ */
9612
+ const clipAgainstHigherRanked = (subject, clips, polygonDifference) => {
9613
+ let fallbacks = 0;
9614
+ let lastError;
9615
+ const onFallback = (error) => {
9616
+ fallbacks += 1;
9617
+ lastError = error;
9618
+ };
9619
+ const batched = polygonDifference(subject, clips.map(clip => clip.geometry), onFallback);
9620
+ if (fallbacks === 0)
9621
+ return { geometry: batched, failure: null };
9622
+ // The batch failed: subtract one clip at a time and skip only the clips that throw on their own.
9623
+ const skipped = [];
9624
+ let current = subject;
9625
+ for (const clip of clips) {
9626
+ if (current === null)
9627
+ break;
9628
+ const before = fallbacks;
9629
+ const next = polygonDifference(current, [clip.geometry], onFallback);
9630
+ if (fallbacks > before) {
9631
+ skipped.push(clip.id);
9632
+ continue;
9633
+ }
9634
+ current = next;
9635
+ }
9636
+ // Only a clip that was actually dropped is a failure; a batch that throws while every clip succeeds alone is not.
9637
+ return { geometry: current, failure: skipped.length > 0 ? { clipFeatureIds: skipped, error: lastError } : null };
9638
+ };
9596
9639
  /** Promote `id` to the front of `order` (no-op if not present). */
9597
9640
  const promoteToFront = (order, id) => order.includes(id) ? [id, ...order.filter(item => item !== id)] : order;
9598
- /**
9599
- * Hover-promotion overlay for one overlap group: the winner renders at full
9600
- * geometry (caller removes its fill override). Each peer is clipped against the
9601
- * winner's full outline starting from its **resting** fill (when present), not
9602
- * its full geometry — so peer-to-peer overlap ownership from resting tiling is
9603
- * preserved and translucent fills do not compound under the winner.
9604
- */
9605
- const computePromotionGroupFills = (members, winnerId, restingPeerFills = new Map(), layerGeodesic = undefined, featureStyles = undefined) => {
9641
+ const computePromotionGroupFills = ({ members, winnerId, restingPeerFills = new Map(), layerGeodesic, featureStyles, polygonDifference = geoJsonPolygonDifference, onDifferenceFallback, }) => {
9606
9642
  // Densify before peer-vs-winner clip so promotion clips follow great-circle
9607
9643
  // arcs. Always defer to densifyGeodesicFeatures' per-feature resolution
9608
9644
  // (geodesic override > layer default) rather than short-circuiting on
@@ -9643,14 +9679,16 @@ const computePromotionGroupFills = (members, winnerId, restingPeerFills = new Ma
9643
9679
  subject = restingPolygonal;
9644
9680
  }
9645
9681
  const subjectMercator = projectPolygonalToWebMercator(subject);
9646
- const clippedMercator = geoJsonPolygonDifference(subjectMercator, [winnerMercator]);
9682
+ const clippedMercator = polygonDifference(subjectMercator, [winnerMercator], error => {
9683
+ onDifferenceFallback?.(memberId, error);
9684
+ });
9647
9685
  const clipped = clippedMercator === null ? null : unprojectPolygonalFromWebMercator(clippedMercator);
9648
9686
  result.set(memberId, clipped === null ? EMPTY_FILL : clipped);
9649
9687
  }
9650
9688
  return result;
9651
9689
  };
9652
9690
  const computeFillTiling = (input) => {
9653
- const { features, viewportBounds, resolveStackOrder, selectedFeatureId, suppressedFeatureIds, layerGeodesic, featureStyles, } = input;
9691
+ const { features, viewportBounds, resolveStackOrder, selectedFeatureId, suppressedFeatureIds, layerGeodesic, featureStyles, polygonDifference = geoJsonPolygonDifference, } = input;
9654
9692
  // Validation boundary (SAGA-664): validate each input feature's polygonal
9655
9693
  // geometry once here — O(n) — dropping malformed geometry. The downstream O(n²)
9656
9694
  // overlap loop then runs the pure predicates on trusted geometry without a
@@ -9707,12 +9745,23 @@ const computeFillTiling = (input) => {
9707
9745
  const fillGeometries = new Map();
9708
9746
  const featureToGroupKey = new Map();
9709
9747
  const featureZIndex = new Map();
9748
+ const differenceFailures = [];
9710
9749
  const { groups: overlapGroups, intersectionFailures } = buildOverlapGroups(records);
9711
9750
  // Failures are returned for the hook to warn about and report (SAGA-743).
9712
9751
  for (const group of overlapGroups) {
9713
9752
  const contended = buildContendedShapes(group);
9714
9753
  const recordById = new Map(group.map(record => [record.id, record]));
9715
9754
  const key = groupKeyOf(group);
9755
+ // Each member is projected at most once per recompute, however many subjects it clips.
9756
+ const mercatorById = new Map();
9757
+ const mercatorOf = (record) => {
9758
+ const cached = mercatorById.get(record.id);
9759
+ if (cached !== undefined)
9760
+ return cached;
9761
+ const projected = projectPolygonalToWebMercator(record.geometry);
9762
+ mercatorById.set(record.id, projected);
9763
+ return projected;
9764
+ };
9716
9765
  for (const record of group) {
9717
9766
  featureToGroupKey.set(record.id, key);
9718
9767
  }
@@ -9732,7 +9781,8 @@ const computeFillTiling = (input) => {
9732
9781
  }
9733
9782
  }
9734
9783
  // Top feature (index 0) keeps its full fill. Each lower-ranked feature is
9735
- // clipped against the union of all features ranked above it.
9784
+ // clipped against the union of the features ranked above it whose bbox touches
9785
+ // its own — a higher-ranked member elsewhere in the group cannot cut it.
9736
9786
  for (let rank = 1; rank < order.length; rank++) {
9737
9787
  const id = order[rank];
9738
9788
  if (id === undefined)
@@ -9744,17 +9794,22 @@ const computeFillTiling = (input) => {
9744
9794
  for (let above = 0; above < rank; above++) {
9745
9795
  const aboveId = order[above];
9746
9796
  const aboveRecord = aboveId !== undefined ? recordById.get(aboveId) : undefined;
9747
- if (aboveRecord !== undefined)
9748
- higherRanked.push(aboveRecord.geometry);
9797
+ if (aboveRecord !== undefined && bboxesIntersect$1(record.bbox, aboveRecord.bbox)) {
9798
+ higherRanked.push(aboveRecord);
9799
+ }
9749
9800
  }
9750
9801
  // Clip in Web Mercator, not planar lng/lat. Google Maps and Mapbox both render
9751
9802
  // polygon edges as straight lines in Web Mercator, so a clip computed in lng/lat
9752
9803
  // produces boundary vertices that drift off the rendered edge of the covering
9753
9804
  // shape — visibly so on long, diagonal, high-latitude-span edges. Projecting
9754
9805
  // before the difference lands every cut exactly on the rendered edge (ADR-0021).
9755
- const subjectMercator = projectPolygonalToWebMercator(record.geometry);
9756
- const clipsMercator = higherRanked.map(projectPolygonalToWebMercator);
9757
- const clippedMercator = geoJsonPolygonDifference(subjectMercator, clipsMercator);
9806
+ // Nothing above touches this member: no override, the adapter renders the full geometry.
9807
+ if (higherRanked.length === 0)
9808
+ continue;
9809
+ const { geometry: clippedMercator, failure } = clipAgainstHigherRanked(mercatorOf(record), higherRanked.map(above => ({ id: above.id, geometry: mercatorOf(above) })), polygonDifference);
9810
+ if (failure !== null) {
9811
+ differenceFailures.push({ featureId: id, clipFeatureIds: failure.clipFeatureIds, error: failure.error });
9812
+ }
9758
9813
  const clipped = clippedMercator === null ? null : unprojectPolygonalFromWebMercator(clippedMercator);
9759
9814
  fillGeometries.set(id, clipped === null ? EMPTY_FILL : clipped);
9760
9815
  }
@@ -9784,6 +9839,7 @@ const computeFillTiling = (input) => {
9784
9839
  featureZIndex,
9785
9840
  droppedInvalidFeatures,
9786
9841
  intersectionFailures,
9842
+ differenceFailures,
9787
9843
  };
9788
9844
  };
9789
9845
 
@@ -11403,11 +11459,12 @@ const buildOverlappingShapesCountMap = (features, featureBboxes, viewportBounds)
11403
11459
  if (isPolygonalA && isPolygonalB) {
11404
11460
  let overlaps;
11405
11461
  try {
11406
- overlaps = getGeoJsonPolygonIntersection(geomA, geomB) !== null;
11462
+ overlaps = polygonalGeometriesOverlap(geomA, geomB);
11407
11463
  }
11408
11464
  catch (error) {
11409
- // polygon-clipping failed on this pair (SAGA-743). Treat as no overlap so
11410
- // decoration counts degrade gracefully instead of crashing the map.
11465
+ // polygon-clipping failed on this pair (SAGA-743) while deciding a degenerate
11466
+ // (touching) overlap. Treat as no overlap so decoration counts degrade gracefully
11467
+ // instead of crashing the map.
11411
11468
  intersectionFailures.push({
11412
11469
  featureIdA: featureA.id !== undefined ? String(featureA.id) : `index:${i}`,
11413
11470
  featureIdB: featureB.id !== undefined ? String(featureB.id) : `index:${j}`,
@@ -11961,6 +12018,219 @@ const captureDroppedInvalidFillTilingFeatures = (droppedInvalidFeatures, layerHa
11961
12018
  }
11962
12019
  };
11963
12020
 
12021
+ /**
12022
+ * Report to Sentry each feature whose clip fell back to an unclipped fill because
12023
+ * `polygon-clipping` threw (SAGA-743), at most once per handle, channel and feature per session.
12024
+ * Note: `shapeFillTiling.ts` emits `console.warn` separately on both channels.
12025
+ */
12026
+ const captureFillTilingDifferenceFailures = (differenceFailures, layerHandleId, channel, sessionReportedDedupeKeys, report) => {
12027
+ for (const failure of differenceFailures) {
12028
+ const key = `${layerHandleId}:difference:${channel}:${failure.featureId}`;
12029
+ if (sessionReportedDedupeKeys.has(key))
12030
+ continue;
12031
+ sessionReportedDedupeKeys.add(key);
12032
+ report({
12033
+ layerHandleId,
12034
+ channel,
12035
+ featureId: failure.featureId,
12036
+ clipFeatureIds: [...failure.clipFeatureIds],
12037
+ message: failure.error instanceof Error ? failure.error.message : String(failure.error),
12038
+ });
12039
+ }
12040
+ };
12041
+
12042
+ /**
12043
+ * Clipper2 scales coordinates to integers by 10^precision. Fill tiling clips in Web Mercator
12044
+ * metres, so 3 keeps millimetres.
12045
+ */
12046
+ const MERCATOR_PRECISION = 3;
12047
+ /** Metres added around the subject bbox before trimming clips, so rect edges stay clear of subject vertices. */
12048
+ const RECT_CLIP_MARGIN = 1;
12049
+ const polygonsOf = (geometry) => geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates;
12050
+ const signedArea = (ring) => {
12051
+ let sum = 0;
12052
+ for (let i = 0; i + 1 < ring.length; i++) {
12053
+ const current = ring[i];
12054
+ const next = ring[i + 1];
12055
+ if (current === undefined || next === undefined)
12056
+ continue;
12057
+ sum += current[0] * next[1] - next[0] * current[1];
12058
+ }
12059
+ return sum / 2;
12060
+ };
12061
+ /**
12062
+ * GeoJSON rings become Clipper2 paths with the closing vertex dropped. Exterior rings are forced
12063
+ * counter-clockwise and holes clockwise so that NonZero winding matches polygon-clipping for
12064
+ * well-nested, non-overlapping holes: holes subtract, and clips that overlap each other still union.
12065
+ *
12066
+ * Known divergence for invalid hole configurations that the schema does not reject: NonZero sums
12067
+ * windings, so where two holes of one polygon overlap (winding −1) the area counts as filled, and
12068
+ * the part of a hole that pokes outside its exterior (winding −1 as well) is painted. polygon-clipping
12069
+ * excludes any region inside an interior ring instead. See the spec for the pinned numbers.
12070
+ */
12071
+ const appendRingsAsPaths = (clipper, paths, geometries) => {
12072
+ for (const geometry of geometries) {
12073
+ for (const rings of polygonsOf(geometry)) {
12074
+ rings.forEach((ring, ringIndex) => {
12075
+ const wantCounterClockwise = ringIndex === 0;
12076
+ const oriented = signedArea(ring) > 0 === wantCounterClockwise ? ring : [...ring].reverse();
12077
+ // Drop the closing vertex; Clipper2 paths are implicitly closed.
12078
+ const flat = [];
12079
+ for (const [x, y] of oriented.slice(0, -1))
12080
+ flat.push(x, y);
12081
+ const path = clipper.MakePathD(flat);
12082
+ paths.push_back(path);
12083
+ path.delete();
12084
+ });
12085
+ }
12086
+ }
12087
+ };
12088
+ /**
12089
+ * Closed GeoJSON ring from a tree node. `polygon()` hands out an owned copy whose `view()` is
12090
+ * x, y, z per vertex (Z build); it is released as soon as the coordinates are copied out.
12091
+ */
12092
+ const ringOf = (node) => {
12093
+ const path = node.polygon();
12094
+ try {
12095
+ const xyz = path.view();
12096
+ const ring = [];
12097
+ for (let i = 0; i + 2 < xyz.length; i += 3) {
12098
+ ring.push([xyz[i] ?? 0, xyz[i + 1] ?? 0]);
12099
+ }
12100
+ const first = ring[0];
12101
+ if (first !== undefined)
12102
+ ring.push(first);
12103
+ return ring;
12104
+ }
12105
+ finally {
12106
+ path.delete();
12107
+ }
12108
+ };
12109
+ /**
12110
+ * Walk the PolyTree: each child of an outer is a hole, each child of a hole is an island.
12111
+ * `child()` returns non-owning references into the tree and must not be deleted.
12112
+ */
12113
+ const collectPolygons = (node, into) => {
12114
+ const outerCount = node.count();
12115
+ for (let i = 0; i < outerCount; i++) {
12116
+ const outer = node.child(i);
12117
+ const rings = [ringOf(outer)];
12118
+ const holeCount = outer.count();
12119
+ for (let h = 0; h < holeCount; h++) {
12120
+ const hole = outer.child(h);
12121
+ rings.push(ringOf(hole));
12122
+ collectPolygons(hole, into);
12123
+ }
12124
+ into.push(rings);
12125
+ }
12126
+ };
12127
+ const bboxOf = (geometry) => {
12128
+ let minX = Infinity;
12129
+ let minY = Infinity;
12130
+ let maxX = -Infinity;
12131
+ let maxY = -Infinity;
12132
+ for (const rings of polygonsOf(geometry)) {
12133
+ const exterior = rings[0];
12134
+ if (exterior === undefined)
12135
+ continue;
12136
+ for (const [x, y] of exterior) {
12137
+ if (x < minX)
12138
+ minX = x;
12139
+ if (x > maxX)
12140
+ maxX = x;
12141
+ if (y < minY)
12142
+ minY = y;
12143
+ if (y > maxY)
12144
+ maxY = y;
12145
+ }
12146
+ }
12147
+ return [minX, minY, maxX, maxY];
12148
+ };
12149
+ /**
12150
+ * Build the difference function on an instantiated module. Throws (from Clipper2 or from the
12151
+ * bridge itself) propagate to the caller, which owns the fallback and the reporting; every embind
12152
+ * object is released in `finally` either way.
12153
+ */
12154
+ const createClipper2PolygonDifference = (clipper) => (subject, clips) => {
12155
+ if (clips.length === 0)
12156
+ return subject;
12157
+ const owned = [];
12158
+ try {
12159
+ const subjectPaths = new clipper.PathsD();
12160
+ owned.push(subjectPaths);
12161
+ appendRingsAsPaths(clipper, subjectPaths, [subject]);
12162
+ const clipPaths = new clipper.PathsD();
12163
+ owned.push(clipPaths);
12164
+ appendRingsAsPaths(clipper, clipPaths, clips);
12165
+ // Trim every clip to the subject's bbox first (O(n)), so a country-sized clip only
12166
+ // contributes the few edges near a site-sized subject.
12167
+ const [minX, minY, maxX, maxY] = bboxOf(subject);
12168
+ const rect = new clipper.RectD(minX - RECT_CLIP_MARGIN, minY - RECT_CLIP_MARGIN, maxX + RECT_CLIP_MARGIN, maxY + RECT_CLIP_MARGIN);
12169
+ owned.push(rect);
12170
+ const trimmedClips = clipper.RectClipPathsD(rect, clipPaths, MERCATOR_PRECISION);
12171
+ owned.push(trimmedClips);
12172
+ const solution = new clipper.PolyPathD();
12173
+ owned.push(solution);
12174
+ clipper.BooleanOpOutD(clipper.ClipType.Difference, clipper.FillRule.NonZero, subjectPaths, trimmedClips, solution, MERCATOR_PRECISION);
12175
+ const polygons = [];
12176
+ collectPolygons(solution, polygons);
12177
+ const [single] = polygons;
12178
+ if (single === undefined)
12179
+ return null;
12180
+ if (polygons.length === 1)
12181
+ return { type: "Polygon", coordinates: single };
12182
+ return { type: "MultiPolygon", coordinates: polygons };
12183
+ }
12184
+ finally {
12185
+ for (const object of owned)
12186
+ object.delete();
12187
+ }
12188
+ };
12189
+ let sharedEngine = null;
12190
+ let loadedEngine;
12191
+ let unusable = false;
12192
+ const createEngine = async (options) => {
12193
+ const { default: createClipper2Module } = await import('clipper2-wasm/dist/es/clipper2z.js');
12194
+ // Emscripten writes load failures and aborts to console.error as well as throwing. The thrown
12195
+ // error is what callers act on (rejected load, or a throw from the returned function that the
12196
+ // fill-tiling hook reports and falls back from), so keep the duplicate stderr channel quiet.
12197
+ const clipper = await createClipper2Module({ ...options, printErr: () => undefined });
12198
+ return createClipper2PolygonDifference(clipper);
12199
+ };
12200
+ /**
12201
+ * Polygon difference backed by Clipper2 compiled to WebAssembly: a drop-in for
12202
+ * `geoJsonPolygonDifference` in fill tiling, roughly 6× faster on the same inputs. Unlike
12203
+ * `geoJsonPolygonDifference` it throws on failure instead of returning the subject unclipped:
12204
+ * polygon-clipping is still available as an exact fallback, and an Emscripten abort disables the
12205
+ * module for good, so the caller decides how to degrade and report.
12206
+ *
12207
+ * The module (~210 KB) is fetched and instantiated on first call and shared afterwards, including a
12208
+ * failed load: callers keep `geoJsonPolygonDifference` until the promise resolves and stay on it for
12209
+ * the page lifetime if it rejects (no WebAssembly support, blocked asset, …). `options.wasmBinary`
12210
+ * bypasses the fetch; engines created with options are not shared.
12211
+ */
12212
+ const loadClipper2PolygonDifference = (options) => {
12213
+ if (unusable)
12214
+ return Promise.reject(new Error("Clipper2 was marked unusable after a runtime failure"));
12215
+ sharedEngine ?? (sharedEngine = createEngine(undefined).then(engine => {
12216
+ loadedEngine = engine;
12217
+ return engine;
12218
+ }));
12219
+ return sharedEngine;
12220
+ };
12221
+ /** The shared engine when it has already loaded, so a later mount can use it for its first pass. */
12222
+ const getLoadedClipper2PolygonDifference = () => loadedEngine;
12223
+ /**
12224
+ * Called when the shared engine threw: an Emscripten abort disables the module for the rest of the
12225
+ * page, so no later mount may adopt it and no reload is attempted.
12226
+ */
12227
+ const markClipper2PolygonDifferenceUnusable = () => {
12228
+ unusable = true;
12229
+ loadedEngine = undefined;
12230
+ };
12231
+ /** Whether the shared engine was marked unusable; callers stay on polygon-clipping silently. */
12232
+ const isClipper2PolygonDifferenceUnusable = () => unusable;
12233
+
11964
12234
  /** Lists the ids of features dropped from fill tiling, or a placeholder when none carry an id. */
11965
12235
  const formatDroppedInvalidFeatureIds = (dropped) => dropped
11966
12236
  .map(entry => (entry.feature.id !== undefined ? String(entry.feature.id) : undefined))
@@ -12162,6 +12432,13 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12162
12432
  const errorHandler = useErrorHandlerOrNull();
12163
12433
  /** Handle/feature keys already reported to Sentry this session. */
12164
12434
  const sessionReportedDedupeKeysRef = useRef(new Set());
12435
+ /**
12436
+ * Clipper2 WebAssembly difference once loaded, wrapped so that a failure reports once and
12437
+ * hands the clip (and every later clip) back to polygon-clipping. `undefined` = default path.
12438
+ */
12439
+ const polygonDifferenceRef = useRef(undefined);
12440
+ /** Load lifecycle; `settled` (loaded, failed or unusable) means the effect never re-subscribes. */
12441
+ const clipper2StatusRef = useRef("idle");
12165
12442
  const tilingContentKey = useMemo(() => buildTilingContentKey(handles), [handles]);
12166
12443
  const tilingHandles = useMemo(() => handles.filter((handle) => handle.layerType === "shapes" && handle.overlap?.mode === "tile"), [handles]);
12167
12444
  const hasTilingHandles = tilingHandles.length > 0;
@@ -12296,7 +12573,26 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12296
12573
  if (restingClip !== undefined)
12297
12574
  restingPeerFills.set(featureId, restingClip);
12298
12575
  }
12299
- const peerFills = computePromotionGroupFills(groupMembers, winnerId, restingPeerFills, handle?.style.geodesic, handle?.featureStyles);
12576
+ const unclippedPeerIds = [];
12577
+ const peerFills = computePromotionGroupFills({
12578
+ members: groupMembers,
12579
+ winnerId,
12580
+ restingPeerFills,
12581
+ layerGeodesic: handle?.style.geodesic,
12582
+ featureStyles: handle?.featureStyles,
12583
+ polygonDifference: polygonDifferenceRef.current,
12584
+ onDifferenceFallback: (featureId, error) => {
12585
+ unclippedPeerIds.push(featureId);
12586
+ if (errorHandler === null)
12587
+ return;
12588
+ captureFillTilingDifferenceFailures([{ featureId, clipFeatureIds: [winnerId], error }], handleId, "promotion", sessionReportedDedupeKeysRef.current, payload => {
12589
+ errorHandler.captureException(new Error(`polygon-clipping failed during fill-tiling promotion clip: ${JSON.stringify(payload)}`), { level: "warning", fingerprint: ["react-map", "fill-tiling", "difference-failure"] });
12590
+ });
12591
+ },
12592
+ });
12593
+ if (unclippedPeerIds.length > 0) {
12594
+ consoleWarnMap("useShapes", `polygon-clipping failed to clip ${unclippedPeerIds.length} peer(s) against promoted ${winnerId}; full fill kept: ${unclippedPeerIds.join(", ")}`);
12595
+ }
12300
12596
  modifiedFills.delete(winnerId);
12301
12597
  for (const [featureId, clip] of peerFills) {
12302
12598
  modifiedFills.set(featureId, clip);
@@ -12336,7 +12632,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12336
12632
  prevZIndexOverridesRef.current = nextZIndices;
12337
12633
  onZIndexChangeRef.current(nextZIndices);
12338
12634
  }
12339
- }, []);
12635
+ }, [errorHandler]);
12340
12636
  const recompute = useCallback(() => {
12341
12637
  const currentHandles = tilingHandlesRef.current;
12342
12638
  // Stable suppressed-key: per-handle sorted ids so suppression changes are
@@ -12395,13 +12691,14 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12395
12691
  const nextRestingFills = new Map();
12396
12692
  const nextRestingZIndices = new Map();
12397
12693
  for (const handle of currentHandles) {
12398
- const { fillGeometries, featureToGroupKey, featureZIndex, droppedInvalidFeatures, intersectionFailures } = computeFillTiling({
12694
+ const { fillGeometries, featureToGroupKey, featureZIndex, droppedInvalidFeatures, intersectionFailures, differenceFailures, } = computeFillTiling({
12399
12695
  features: handle.features.features,
12400
12696
  viewportBounds: GLOBAL_BOUNDS,
12401
12697
  resolveStackOrder: handle.overlap?.resolveStackOrder ?? defaultShapeStackOrder,
12402
12698
  suppressedFeatureIds: suppressedFillIdsByHandleRef.current?.get(handle.id),
12403
12699
  layerGeodesic: handle.style.geodesic,
12404
12700
  featureStyles: handle.featureStyles,
12701
+ polygonDifference: polygonDifferenceRef.current,
12405
12702
  });
12406
12703
  // The dev warnings live here, not in computeFillTiling: recompute runs from
12407
12704
  // effects and idle callbacks, so the pure function stays silent (SAGA-907).
@@ -12411,6 +12708,9 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12411
12708
  if (intersectionFailures.length > 0) {
12412
12709
  consoleWarnMap("useShapes", `polygon-clipping failed on ${intersectionFailures.length} feature pair(s); treated as non-overlapping (full fill still renders): ${formatIntersectionFailurePairs(intersectionFailures)}`);
12413
12710
  }
12711
+ if (differenceFailures.length > 0) {
12712
+ consoleWarnMap("useShapes", `polygon-clipping failed to clip ${differenceFailures.length} feature(s) against a degenerate neighbour; that overlap is left unclipped: ${differenceFailures.map(failure => failure.featureId).join(", ")}`);
12713
+ }
12414
12714
  if (errorHandler !== null && droppedInvalidFeatures.length > 0) {
12415
12715
  captureDroppedInvalidFillTilingFeatures(droppedInvalidFeatures, handle.id, sessionReportedDedupeKeysRef.current, payload => {
12416
12716
  errorHandler.captureException(new Error(`Schema-invalid polygonal geometry excluded from fill tiling: ${JSON.stringify(payload)}`), {
@@ -12427,6 +12727,14 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12427
12727
  });
12428
12728
  });
12429
12729
  }
12730
+ if (errorHandler !== null && differenceFailures.length > 0) {
12731
+ captureFillTilingDifferenceFailures(differenceFailures, handle.id, "resting", sessionReportedDedupeKeysRef.current, payload => {
12732
+ errorHandler.captureException(new Error(`polygon-clipping failed during fill-tiling clip: ${JSON.stringify(payload)}`), {
12733
+ level: "warning",
12734
+ fingerprint: ["react-map", "fill-tiling", "difference-failure"],
12735
+ });
12736
+ });
12737
+ }
12430
12738
  featureToGroupKeyByHandleRef.current.set(handle.id, new Map(featureToGroupKey));
12431
12739
  if (fillGeometries.size > 0) {
12432
12740
  nextRestingFills.set(handle.id, fillGeometries);
@@ -12458,6 +12766,67 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12458
12766
  flushPendingRestingRecompute();
12459
12767
  }, IDLE_RECOMPUTE_DEBOUNCE_MS);
12460
12768
  }, [flushPendingRestingRecompute]);
12769
+ // Use the Clipper2 WebAssembly difference for the clip phase once a tiling layer exists. An engine
12770
+ // that already loaded (an earlier map on this page) is adopted synchronously here, before the
12771
+ // mount recompute below, so the first pass already uses it. Otherwise the load runs in the
12772
+ // background and the resting clips are re-tiled through the idle path when it resolves, so a load
12773
+ // finishing mid-pan never freezes the gesture. A failed load (no WebAssembly, blocked asset) or a
12774
+ // failing clip keeps polygon-clipping for the rest of this map's life, reported once each.
12775
+ useEffect(() => {
12776
+ if (!hasTilingHandles || clipper2StatusRef.current !== "idle")
12777
+ return;
12778
+ if (isClipper2PolygonDifferenceUnusable()) {
12779
+ // Another map on this page already hit a runtime failure and reported it.
12780
+ clipper2StatusRef.current = "settled";
12781
+ return;
12782
+ }
12783
+ const adopt = (clipper2Difference) => {
12784
+ clipper2StatusRef.current = "settled";
12785
+ polygonDifferenceRef.current = (subject, clips, onFallback) => {
12786
+ try {
12787
+ return clipper2Difference(subject, clips);
12788
+ }
12789
+ catch (error) {
12790
+ // An Emscripten abort disables the module for good: for this map and any later one.
12791
+ markClipper2PolygonDifferenceUnusable();
12792
+ polygonDifferenceRef.current = undefined;
12793
+ 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"] });
12794
+ return geoJsonPolygonDifference(subject, clips, onFallback);
12795
+ }
12796
+ };
12797
+ };
12798
+ const loaded = getLoadedClipper2PolygonDifference();
12799
+ if (loaded !== undefined) {
12800
+ adopt(loaded);
12801
+ return;
12802
+ }
12803
+ clipper2StatusRef.current = "loading";
12804
+ let cancelled = false;
12805
+ loadClipper2PolygonDifference()
12806
+ .then(clipper2Difference => {
12807
+ if (cancelled)
12808
+ return;
12809
+ adopt(clipper2Difference);
12810
+ // Re-tile the resting clips with the engine, but never mid-gesture: while the map moves the
12811
+ // existing `idle` handler flushes the pending recompute once the movement settles.
12812
+ lastComputeInputKeyRef.current = null;
12813
+ pendingRestingRecomputeRef.current = true;
12814
+ if (!isMapMovingRef.current)
12815
+ scheduleIdleRestingRecompute();
12816
+ })
12817
+ .catch((error) => {
12818
+ if (cancelled)
12819
+ return;
12820
+ clipper2StatusRef.current = "settled";
12821
+ 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"] });
12822
+ });
12823
+ return () => {
12824
+ cancelled = true;
12825
+ // Unmounted mid-load: allow the next mount of a tiling layer to subscribe again.
12826
+ if (clipper2StatusRef.current === "loading")
12827
+ clipper2StatusRef.current = "idle";
12828
+ };
12829
+ }, [hasTilingHandles, scheduleIdleRestingRecompute, errorHandler]);
12461
12830
  const clearSelectionPromotion = useCallback((handleId, featureId) => {
12462
12831
  const groupKey = featureToGroupKeyByHandleRef.current.get(handleId)?.get(featureId);
12463
12832
  if (groupKey === undefined)
package/package.json CHANGED
@@ -1,24 +1,25 @@
1
1
  {
2
2
  "name": "@trackunit/react-map",
3
- "version": "0.2.295",
3
+ "version": "0.2.297",
4
4
  "repository": "https://github.com/Trackunit/manager",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "engines": {
7
7
  "node": ">=24.x"
8
8
  },
9
9
  "dependencies": {
10
- "@trackunit/react-components": "6.0.37",
11
- "@trackunit/css-class-variance-utilities": "2.6.42",
12
- "@trackunit/react-form-components": "2.17.39",
13
- "@trackunit/react-core-hooks": "1.31.34",
14
- "@trackunit/geo-json-utils": "1.21.42",
15
- "@trackunit/i18n-library-translation": "2.14.34",
10
+ "@trackunit/react-components": "6.0.38",
11
+ "@trackunit/css-class-variance-utilities": "2.6.43",
12
+ "@trackunit/react-form-components": "2.17.40",
13
+ "@trackunit/react-core-hooks": "1.31.35",
14
+ "@trackunit/geo-json-utils": "1.21.43",
15
+ "@trackunit/i18n-library-translation": "2.14.35",
16
16
  "react-minimal-pie-chart": "^8.4.0",
17
- "@trackunit/react-map-adapter-shared": "0.0.210",
18
- "@trackunit/react-map-color-utils": "0.0.183",
19
- "@trackunit/shared-utils": "1.22.42",
20
- "@trackunit/ui-design-tokens": "1.21.40",
17
+ "@trackunit/react-map-adapter-shared": "0.0.211",
18
+ "@trackunit/react-map-color-utils": "0.0.184",
19
+ "@trackunit/shared-utils": "1.22.43",
20
+ "@trackunit/ui-design-tokens": "1.21.41",
21
21
  "@floating-ui/react": "^0.26.25",
22
+ "clipper2-wasm": "0.4.0",
22
23
  "es-toolkit": "^1.52.0",
23
24
  "tailwind-merge": "^3.7.0",
24
25
  "zod": "^3.25.76"
@@ -0,0 +1,18 @@
1
+ import { type GeoJsonFeature } from "@trackunit/geo-json-utils";
2
+ export type DenseGeofenceFixtureOptions = Readonly<{
3
+ seed?: number;
4
+ /** Include a few 100–300 km polygons that get geodesically densified and overlap everything. */
5
+ regionalPolygons?: boolean;
6
+ /** 1 = one metro area (~63×67 km); 3 = ~190×200 km. */
7
+ spread?: number;
8
+ }>;
9
+ /**
10
+ * Deterministic, dense, overlapping geofence layer: 60 % circle geofences 300 m–15 km (32–150
11
+ * vertices), 37 % irregular drawn sites with 12–60 vertices, 3 % regional polygons.
12
+ */
13
+ export declare const denseGeofenceFixture: (count: number, { seed, regionalPolygons, spread }?: DenseGeofenceFixtureOptions) => Array<GeoJsonFeature>;
14
+ /**
15
+ * The Clipper2 `.wasm` next to the ES build. vitest-jsdom cannot fetch it, so specs hand the
16
+ * binary over the way a bundler would.
17
+ */
18
+ export declare const readClipper2WasmBinary: () => ArrayBuffer;