@trackunit/react-map 0.2.295-alpha-b8d3d323d1a.0 → 0.2.296

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
@@ -9510,13 +9510,15 @@ const shapesUnderCursor = (position, features, options) => {
9510
9510
  };
9511
9511
  /**
9512
9512
  * Connected components of features that share fill area. Bbox prefilter then
9513
- * exact polygon intersection, mirroring `countOverlappingShapes`.
9513
+ * exact overlap predicate, mirroring `countOverlappingShapes`.
9514
9514
  *
9515
- * `getGeoJsonPolygonIntersection` delegates to `polygon-clipping`, which can throw
9516
- * `"Unable to complete output ring"` for degenerate but schema-valid geometry
9517
- * (SAGA-743). A throw here is treated as "no overlap" — the safe degradation for
9518
- * grouping — and recorded in `intersectionFailures` so the hook can report it
9519
- * (mirrors how `droppedInvalidFeatures` surfaces the sibling failure mode).
9515
+ * `polygonalGeometriesOverlap` answers the yes/no question without computing the
9516
+ * intersection geometry; only degenerate pairs (touching edges, shared vertices)
9517
+ * fall back to `polygon-clipping`, which can throw `"Unable to complete output ring"`
9518
+ * for degenerate but schema-valid geometry (SAGA-743). A throw here is treated as
9519
+ * "no overlap" — the safe degradation for grouping — and recorded in
9520
+ * `intersectionFailures` so the hook can report it (mirrors how
9521
+ * `droppedInvalidFeatures` surfaces the sibling failure mode).
9520
9522
  */
9521
9523
  const buildOverlapGroups = (records) => {
9522
9524
  const parent = records.map((_, index) => index);
@@ -9546,7 +9548,7 @@ const buildOverlapGroups = (records) => {
9546
9548
  continue;
9547
9549
  let overlaps;
9548
9550
  try {
9549
- overlaps = geoJsonUtils.getGeoJsonPolygonIntersection(a.geometry, b.geometry) !== null;
9551
+ overlaps = geoJsonUtils.polygonalGeometriesOverlap(a.geometry, b.geometry);
9550
9552
  }
9551
9553
  catch (error) {
9552
9554
  // polygon-clipping failed on this pair. Treat as no overlap (do not union)
@@ -9572,11 +9574,19 @@ const buildOverlapGroups = (records) => {
9572
9574
  });
9573
9575
  return { groups: [...groups.values()].filter(group => group.length >= 2), intersectionFailures };
9574
9576
  };
9577
+ /**
9578
+ * A geometry can only be contained in another when its bbox sits inside the other's bbox.
9579
+ * `computeBbox` never emits a wrapped (west > east) box; an antimeridian-split MultiPolygon gets a
9580
+ * conservative full-width box, which only makes this pre-test pass more often, never less.
9581
+ */
9582
+ const bboxMayBeContained = (inner, outer) => inner[0] >= outer[0] && inner[1] >= outer[1] && inner[2] <= outer[2] && inner[3] <= outer[3];
9575
9583
  const buildContendedShapes = (group) => group.map(record => {
9576
9584
  const containedIn = [];
9577
9585
  for (const other of group) {
9578
9586
  if (other.id === record.id)
9579
9587
  continue;
9588
+ if (!bboxMayBeContained(record.bbox, other.bbox))
9589
+ continue;
9580
9590
  // Pure predicate: geometry was validated once at the computeFillTiling
9581
9591
  // boundary, so this O(n²) loop performs no safeParse per pair (SAGA-664).
9582
9592
  if (geoJsonUtils.isFullyContainedInGeometry(record.geometry, other.geometry)) {
@@ -9594,16 +9604,42 @@ const groupKeyOf = (group) => group
9594
9604
  .map(record => record.id)
9595
9605
  .sort()
9596
9606
  .join("|");
9607
+ /**
9608
+ * `subject` minus all `clips`, in Web Mercator. `polygon-clipping` can throw for degenerate but
9609
+ * schema-valid geometry (SAGA-743); when the batched call fails, the clips are subtracted one at a
9610
+ * time and only the ones that throw are skipped, so one degenerate neighbour costs the overlap with
9611
+ * that neighbour alone rather than every clip of the subject.
9612
+ */
9613
+ const clipAgainstHigherRanked = (subject, clips) => {
9614
+ let fallbacks = 0;
9615
+ let lastError;
9616
+ const onFallback = (error) => {
9617
+ fallbacks += 1;
9618
+ lastError = error;
9619
+ };
9620
+ const batched = geoJsonUtils.geoJsonPolygonDifference(subject, clips.map(clip => clip.geometry), onFallback);
9621
+ if (fallbacks === 0)
9622
+ return { geometry: batched, failure: null };
9623
+ // The batch failed: subtract one clip at a time and skip only the clips that throw on their own.
9624
+ const skipped = [];
9625
+ let current = subject;
9626
+ for (const clip of clips) {
9627
+ if (current === null)
9628
+ break;
9629
+ const before = fallbacks;
9630
+ const next = geoJsonUtils.geoJsonPolygonDifference(current, [clip.geometry], onFallback);
9631
+ if (fallbacks > before) {
9632
+ skipped.push(clip.id);
9633
+ continue;
9634
+ }
9635
+ current = next;
9636
+ }
9637
+ // Only a clip that was actually dropped is a failure; a batch that throws while every clip succeeds alone is not.
9638
+ return { geometry: current, failure: skipped.length > 0 ? { clipFeatureIds: skipped, error: lastError } : null };
9639
+ };
9597
9640
  /** Promote `id` to the front of `order` (no-op if not present). */
9598
9641
  const promoteToFront = (order, id) => order.includes(id) ? [id, ...order.filter(item => item !== id)] : order;
9599
- /**
9600
- * Hover-promotion overlay for one overlap group: the winner renders at full
9601
- * geometry (caller removes its fill override). Each peer is clipped against the
9602
- * winner's full outline starting from its **resting** fill (when present), not
9603
- * its full geometry — so peer-to-peer overlap ownership from resting tiling is
9604
- * preserved and translucent fills do not compound under the winner.
9605
- */
9606
- const computePromotionGroupFills = (members, winnerId, restingPeerFills = new Map(), layerGeodesic = undefined, featureStyles = undefined) => {
9642
+ const computePromotionGroupFills = ({ members, winnerId, restingPeerFills = new Map(), layerGeodesic, featureStyles, onDifferenceFallback, }) => {
9607
9643
  // Densify before peer-vs-winner clip so promotion clips follow great-circle
9608
9644
  // arcs. Always defer to densifyGeodesicFeatures' per-feature resolution
9609
9645
  // (geodesic override > layer default) rather than short-circuiting on
@@ -9644,7 +9680,9 @@ const computePromotionGroupFills = (members, winnerId, restingPeerFills = new Ma
9644
9680
  subject = restingPolygonal;
9645
9681
  }
9646
9682
  const subjectMercator = geoJsonUtils.projectPolygonalToWebMercator(subject);
9647
- const clippedMercator = geoJsonUtils.geoJsonPolygonDifference(subjectMercator, [winnerMercator]);
9683
+ const clippedMercator = geoJsonUtils.geoJsonPolygonDifference(subjectMercator, [winnerMercator], error => {
9684
+ onDifferenceFallback?.(memberId, error);
9685
+ });
9648
9686
  const clipped = clippedMercator === null ? null : geoJsonUtils.unprojectPolygonalFromWebMercator(clippedMercator);
9649
9687
  result.set(memberId, clipped === null ? EMPTY_FILL : clipped);
9650
9688
  }
@@ -9708,12 +9746,23 @@ const computeFillTiling = (input) => {
9708
9746
  const fillGeometries = new Map();
9709
9747
  const featureToGroupKey = new Map();
9710
9748
  const featureZIndex = new Map();
9749
+ const differenceFailures = [];
9711
9750
  const { groups: overlapGroups, intersectionFailures } = buildOverlapGroups(records);
9712
9751
  // Failures are returned for the hook to warn about and report (SAGA-743).
9713
9752
  for (const group of overlapGroups) {
9714
9753
  const contended = buildContendedShapes(group);
9715
9754
  const recordById = new Map(group.map(record => [record.id, record]));
9716
9755
  const key = groupKeyOf(group);
9756
+ // Each member is projected at most once per recompute, however many subjects it clips.
9757
+ const mercatorById = new Map();
9758
+ const mercatorOf = (record) => {
9759
+ const cached = mercatorById.get(record.id);
9760
+ if (cached !== undefined)
9761
+ return cached;
9762
+ const projected = geoJsonUtils.projectPolygonalToWebMercator(record.geometry);
9763
+ mercatorById.set(record.id, projected);
9764
+ return projected;
9765
+ };
9717
9766
  for (const record of group) {
9718
9767
  featureToGroupKey.set(record.id, key);
9719
9768
  }
@@ -9733,7 +9782,8 @@ const computeFillTiling = (input) => {
9733
9782
  }
9734
9783
  }
9735
9784
  // Top feature (index 0) keeps its full fill. Each lower-ranked feature is
9736
- // clipped against the union of all features ranked above it.
9785
+ // clipped against the union of the features ranked above it whose bbox touches
9786
+ // its own — a higher-ranked member elsewhere in the group cannot cut it.
9737
9787
  for (let rank = 1; rank < order.length; rank++) {
9738
9788
  const id = order[rank];
9739
9789
  if (id === undefined)
@@ -9745,17 +9795,22 @@ const computeFillTiling = (input) => {
9745
9795
  for (let above = 0; above < rank; above++) {
9746
9796
  const aboveId = order[above];
9747
9797
  const aboveRecord = aboveId !== undefined ? recordById.get(aboveId) : undefined;
9748
- if (aboveRecord !== undefined)
9749
- higherRanked.push(aboveRecord.geometry);
9798
+ if (aboveRecord !== undefined && bboxesIntersect$1(record.bbox, aboveRecord.bbox)) {
9799
+ higherRanked.push(aboveRecord);
9800
+ }
9750
9801
  }
9751
9802
  // Clip in Web Mercator, not planar lng/lat. Google Maps and Mapbox both render
9752
9803
  // polygon edges as straight lines in Web Mercator, so a clip computed in lng/lat
9753
9804
  // produces boundary vertices that drift off the rendered edge of the covering
9754
9805
  // shape — visibly so on long, diagonal, high-latitude-span edges. Projecting
9755
9806
  // before the difference lands every cut exactly on the rendered edge (ADR-0021).
9756
- const subjectMercator = geoJsonUtils.projectPolygonalToWebMercator(record.geometry);
9757
- const clipsMercator = higherRanked.map(geoJsonUtils.projectPolygonalToWebMercator);
9758
- const clippedMercator = geoJsonUtils.geoJsonPolygonDifference(subjectMercator, clipsMercator);
9807
+ // Nothing above touches this member: no override, the adapter renders the full geometry.
9808
+ if (higherRanked.length === 0)
9809
+ continue;
9810
+ const { geometry: clippedMercator, failure } = clipAgainstHigherRanked(mercatorOf(record), higherRanked.map(above => ({ id: above.id, geometry: mercatorOf(above) })));
9811
+ if (failure !== null) {
9812
+ differenceFailures.push({ featureId: id, clipFeatureIds: failure.clipFeatureIds, error: failure.error });
9813
+ }
9759
9814
  const clipped = clippedMercator === null ? null : geoJsonUtils.unprojectPolygonalFromWebMercator(clippedMercator);
9760
9815
  fillGeometries.set(id, clipped === null ? EMPTY_FILL : clipped);
9761
9816
  }
@@ -9785,6 +9840,7 @@ const computeFillTiling = (input) => {
9785
9840
  featureZIndex,
9786
9841
  droppedInvalidFeatures,
9787
9842
  intersectionFailures,
9843
+ differenceFailures,
9788
9844
  };
9789
9845
  };
9790
9846
 
@@ -11404,11 +11460,12 @@ const buildOverlappingShapesCountMap = (features, featureBboxes, viewportBounds)
11404
11460
  if (isPolygonalA && isPolygonalB) {
11405
11461
  let overlaps;
11406
11462
  try {
11407
- overlaps = geoJsonUtils.getGeoJsonPolygonIntersection(geomA, geomB) !== null;
11463
+ overlaps = geoJsonUtils.polygonalGeometriesOverlap(geomA, geomB);
11408
11464
  }
11409
11465
  catch (error) {
11410
- // polygon-clipping failed on this pair (SAGA-743). Treat as no overlap so
11411
- // decoration counts degrade gracefully instead of crashing the map.
11466
+ // polygon-clipping failed on this pair (SAGA-743) while deciding a degenerate
11467
+ // (touching) overlap. Treat as no overlap so decoration counts degrade gracefully
11468
+ // instead of crashing the map.
11412
11469
  intersectionFailures.push({
11413
11470
  featureIdA: featureA.id !== undefined ? String(featureA.id) : `index:${i}`,
11414
11471
  featureIdB: featureB.id !== undefined ? String(featureB.id) : `index:${j}`,
@@ -11962,6 +12019,27 @@ const captureDroppedInvalidFillTilingFeatures = (droppedInvalidFeatures, layerHa
11962
12019
  }
11963
12020
  };
11964
12021
 
12022
+ /**
12023
+ * Report to Sentry each feature whose clip fell back to an unclipped fill because
12024
+ * `polygon-clipping` threw (SAGA-743), at most once per handle, channel and feature per session.
12025
+ * Note: `shapeFillTiling.ts` emits `console.warn` separately on both channels.
12026
+ */
12027
+ const captureFillTilingDifferenceFailures = (differenceFailures, layerHandleId, channel, sessionReportedDedupeKeys, report) => {
12028
+ for (const failure of differenceFailures) {
12029
+ const key = `${layerHandleId}:difference:${channel}:${failure.featureId}`;
12030
+ if (sessionReportedDedupeKeys.has(key))
12031
+ continue;
12032
+ sessionReportedDedupeKeys.add(key);
12033
+ report({
12034
+ layerHandleId,
12035
+ channel,
12036
+ featureId: failure.featureId,
12037
+ clipFeatureIds: [...failure.clipFeatureIds],
12038
+ message: failure.error instanceof Error ? failure.error.message : String(failure.error),
12039
+ });
12040
+ }
12041
+ };
12042
+
11965
12043
  /** Lists the ids of features dropped from fill tiling, or a placeholder when none carry an id. */
11966
12044
  const formatDroppedInvalidFeatureIds = (dropped) => dropped
11967
12045
  .map(entry => (entry.feature.id !== undefined ? String(entry.feature.id) : undefined))
@@ -12297,7 +12375,25 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12297
12375
  if (restingClip !== undefined)
12298
12376
  restingPeerFills.set(featureId, restingClip);
12299
12377
  }
12300
- const peerFills = computePromotionGroupFills(groupMembers, winnerId, restingPeerFills, handle?.style.geodesic, handle?.featureStyles);
12378
+ const unclippedPeerIds = [];
12379
+ const peerFills = computePromotionGroupFills({
12380
+ members: groupMembers,
12381
+ winnerId,
12382
+ restingPeerFills,
12383
+ layerGeodesic: handle?.style.geodesic,
12384
+ featureStyles: handle?.featureStyles,
12385
+ onDifferenceFallback: (featureId, error) => {
12386
+ unclippedPeerIds.push(featureId);
12387
+ if (errorHandler === null)
12388
+ return;
12389
+ captureFillTilingDifferenceFailures([{ featureId, clipFeatureIds: [winnerId], error }], handleId, "promotion", sessionReportedDedupeKeysRef.current, payload => {
12390
+ errorHandler.captureException(new Error(`polygon-clipping failed during fill-tiling promotion clip: ${JSON.stringify(payload)}`), { level: "warning", fingerprint: ["react-map", "fill-tiling", "difference-failure"] });
12391
+ });
12392
+ },
12393
+ });
12394
+ if (unclippedPeerIds.length > 0) {
12395
+ consoleWarnMap("useShapes", `polygon-clipping failed to clip ${unclippedPeerIds.length} peer(s) against promoted ${winnerId}; full fill kept: ${unclippedPeerIds.join(", ")}`);
12396
+ }
12301
12397
  modifiedFills.delete(winnerId);
12302
12398
  for (const [featureId, clip] of peerFills) {
12303
12399
  modifiedFills.set(featureId, clip);
@@ -12337,7 +12433,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12337
12433
  prevZIndexOverridesRef.current = nextZIndices;
12338
12434
  onZIndexChangeRef.current(nextZIndices);
12339
12435
  }
12340
- }, []);
12436
+ }, [errorHandler]);
12341
12437
  const recompute = react.useCallback(() => {
12342
12438
  const currentHandles = tilingHandlesRef.current;
12343
12439
  // Stable suppressed-key: per-handle sorted ids so suppression changes are
@@ -12396,7 +12492,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12396
12492
  const nextRestingFills = new Map();
12397
12493
  const nextRestingZIndices = new Map();
12398
12494
  for (const handle of currentHandles) {
12399
- const { fillGeometries, featureToGroupKey, featureZIndex, droppedInvalidFeatures, intersectionFailures } = computeFillTiling({
12495
+ const { fillGeometries, featureToGroupKey, featureZIndex, droppedInvalidFeatures, intersectionFailures, differenceFailures, } = computeFillTiling({
12400
12496
  features: handle.features.features,
12401
12497
  viewportBounds: GLOBAL_BOUNDS,
12402
12498
  resolveStackOrder: handle.overlap?.resolveStackOrder ?? defaultShapeStackOrder,
@@ -12412,6 +12508,9 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12412
12508
  if (intersectionFailures.length > 0) {
12413
12509
  consoleWarnMap("useShapes", `polygon-clipping failed on ${intersectionFailures.length} feature pair(s); treated as non-overlapping (full fill still renders): ${formatIntersectionFailurePairs(intersectionFailures)}`);
12414
12510
  }
12511
+ if (differenceFailures.length > 0) {
12512
+ 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(", ")}`);
12513
+ }
12415
12514
  if (errorHandler !== null && droppedInvalidFeatures.length > 0) {
12416
12515
  captureDroppedInvalidFillTilingFeatures(droppedInvalidFeatures, handle.id, sessionReportedDedupeKeysRef.current, payload => {
12417
12516
  errorHandler.captureException(new Error(`Schema-invalid polygonal geometry excluded from fill tiling: ${JSON.stringify(payload)}`), {
@@ -12428,6 +12527,14 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12428
12527
  });
12429
12528
  });
12430
12529
  }
12530
+ if (errorHandler !== null && differenceFailures.length > 0) {
12531
+ captureFillTilingDifferenceFailures(differenceFailures, handle.id, "resting", sessionReportedDedupeKeysRef.current, payload => {
12532
+ errorHandler.captureException(new Error(`polygon-clipping failed during fill-tiling clip: ${JSON.stringify(payload)}`), {
12533
+ level: "warning",
12534
+ fingerprint: ["react-map", "fill-tiling", "difference-failure"],
12535
+ });
12536
+ });
12537
+ }
12431
12538
  featureToGroupKeyByHandleRef.current.set(handle.id, new Map(featureToGroupKey));
12432
12539
  if (fillGeometries.size > 0) {
12433
12540
  nextRestingFills.set(handle.id, fillGeometries);
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) => {
9613
+ let fallbacks = 0;
9614
+ let lastError;
9615
+ const onFallback = (error) => {
9616
+ fallbacks += 1;
9617
+ lastError = error;
9618
+ };
9619
+ const batched = geoJsonPolygonDifference(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 = geoJsonPolygonDifference(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, 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,7 +9679,9 @@ 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 = geoJsonPolygonDifference(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
  }
@@ -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) })));
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,27 @@ 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
+
11964
12042
  /** Lists the ids of features dropped from fill tiling, or a placeholder when none carry an id. */
11965
12043
  const formatDroppedInvalidFeatureIds = (dropped) => dropped
11966
12044
  .map(entry => (entry.feature.id !== undefined ? String(entry.feature.id) : undefined))
@@ -12296,7 +12374,25 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12296
12374
  if (restingClip !== undefined)
12297
12375
  restingPeerFills.set(featureId, restingClip);
12298
12376
  }
12299
- const peerFills = computePromotionGroupFills(groupMembers, winnerId, restingPeerFills, handle?.style.geodesic, handle?.featureStyles);
12377
+ const unclippedPeerIds = [];
12378
+ const peerFills = computePromotionGroupFills({
12379
+ members: groupMembers,
12380
+ winnerId,
12381
+ restingPeerFills,
12382
+ layerGeodesic: handle?.style.geodesic,
12383
+ featureStyles: handle?.featureStyles,
12384
+ onDifferenceFallback: (featureId, error) => {
12385
+ unclippedPeerIds.push(featureId);
12386
+ if (errorHandler === null)
12387
+ return;
12388
+ captureFillTilingDifferenceFailures([{ featureId, clipFeatureIds: [winnerId], error }], handleId, "promotion", sessionReportedDedupeKeysRef.current, payload => {
12389
+ errorHandler.captureException(new Error(`polygon-clipping failed during fill-tiling promotion clip: ${JSON.stringify(payload)}`), { level: "warning", fingerprint: ["react-map", "fill-tiling", "difference-failure"] });
12390
+ });
12391
+ },
12392
+ });
12393
+ if (unclippedPeerIds.length > 0) {
12394
+ consoleWarnMap("useShapes", `polygon-clipping failed to clip ${unclippedPeerIds.length} peer(s) against promoted ${winnerId}; full fill kept: ${unclippedPeerIds.join(", ")}`);
12395
+ }
12300
12396
  modifiedFills.delete(winnerId);
12301
12397
  for (const [featureId, clip] of peerFills) {
12302
12398
  modifiedFills.set(featureId, clip);
@@ -12336,7 +12432,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12336
12432
  prevZIndexOverridesRef.current = nextZIndices;
12337
12433
  onZIndexChangeRef.current(nextZIndices);
12338
12434
  }
12339
- }, []);
12435
+ }, [errorHandler]);
12340
12436
  const recompute = useCallback(() => {
12341
12437
  const currentHandles = tilingHandlesRef.current;
12342
12438
  // Stable suppressed-key: per-handle sorted ids so suppression changes are
@@ -12395,7 +12491,7 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12395
12491
  const nextRestingFills = new Map();
12396
12492
  const nextRestingZIndices = new Map();
12397
12493
  for (const handle of currentHandles) {
12398
- const { fillGeometries, featureToGroupKey, featureZIndex, droppedInvalidFeatures, intersectionFailures } = computeFillTiling({
12494
+ const { fillGeometries, featureToGroupKey, featureZIndex, droppedInvalidFeatures, intersectionFailures, differenceFailures, } = computeFillTiling({
12399
12495
  features: handle.features.features,
12400
12496
  viewportBounds: GLOBAL_BOUNDS,
12401
12497
  resolveStackOrder: handle.overlap?.resolveStackOrder ?? defaultShapeStackOrder,
@@ -12411,6 +12507,9 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12411
12507
  if (intersectionFailures.length > 0) {
12412
12508
  consoleWarnMap("useShapes", `polygon-clipping failed on ${intersectionFailures.length} feature pair(s); treated as non-overlapping (full fill still renders): ${formatIntersectionFailurePairs(intersectionFailures)}`);
12413
12509
  }
12510
+ if (differenceFailures.length > 0) {
12511
+ 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(", ")}`);
12512
+ }
12414
12513
  if (errorHandler !== null && droppedInvalidFeatures.length > 0) {
12415
12514
  captureDroppedInvalidFillTilingFeatures(droppedInvalidFeatures, handle.id, sessionReportedDedupeKeysRef.current, payload => {
12416
12515
  errorHandler.captureException(new Error(`Schema-invalid polygonal geometry excluded from fill tiling: ${JSON.stringify(payload)}`), {
@@ -12427,6 +12526,14 @@ const useShapeFillTiling = ({ api, handles, onFillGeometriesChange, onZIndexOver
12427
12526
  });
12428
12527
  });
12429
12528
  }
12529
+ if (errorHandler !== null && differenceFailures.length > 0) {
12530
+ captureFillTilingDifferenceFailures(differenceFailures, handle.id, "resting", sessionReportedDedupeKeysRef.current, payload => {
12531
+ errorHandler.captureException(new Error(`polygon-clipping failed during fill-tiling clip: ${JSON.stringify(payload)}`), {
12532
+ level: "warning",
12533
+ fingerprint: ["react-map", "fill-tiling", "difference-failure"],
12534
+ });
12535
+ });
12536
+ }
12430
12537
  featureToGroupKeyByHandleRef.current.set(handle.id, new Map(featureToGroupKey));
12431
12538
  if (fillGeometries.size > 0) {
12432
12539
  nextRestingFills.set(handle.id, fillGeometries);
package/package.json CHANGED
@@ -1,23 +1,23 @@
1
1
  {
2
2
  "name": "@trackunit/react-map",
3
- "version": "0.2.295-alpha-b8d3d323d1a.0",
3
+ "version": "0.2.296",
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-alpha-b8d3d323d1a.0",
11
- "@trackunit/css-class-variance-utilities": "2.6.43-alpha-b8d3d323d1a.0",
12
- "@trackunit/react-form-components": "2.17.39-alpha-b8d3d323d1a.0",
13
- "@trackunit/react-core-hooks": "1.31.35-alpha-b8d3d323d1a.0",
14
- "@trackunit/geo-json-utils": "1.21.43-alpha-b8d3d323d1a.0",
15
- "@trackunit/i18n-library-translation": "2.14.35-alpha-b8d3d323d1a.0",
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.211-alpha-b8d3d323d1a.0",
18
- "@trackunit/react-map-color-utils": "0.0.184-alpha-b8d3d323d1a.0",
19
- "@trackunit/shared-utils": "1.22.43-alpha-b8d3d323d1a.0",
20
- "@trackunit/ui-design-tokens": "1.21.41-alpha-b8d3d323d1a.0",
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
22
  "es-toolkit": "^1.52.0",
23
23
  "tailwind-merge": "^3.7.0",
@@ -0,0 +1,11 @@
1
+ import type { FillTilingDifferenceFailure } from "./shapeFillTiling";
2
+ type ReportFillTilingDifferenceFailureEvent = (payload: Record<string, unknown>) => void;
3
+ /** Resting tiling (`computeFillTiling`) and hover/selection promotion clip on different inputs. */
4
+ export type FillTilingClipChannel = "resting" | "promotion";
5
+ /**
6
+ * Report to Sentry each feature whose clip fell back to an unclipped fill because
7
+ * `polygon-clipping` threw (SAGA-743), at most once per handle, channel and feature per session.
8
+ * Note: `shapeFillTiling.ts` emits `console.warn` separately on both channels.
9
+ */
10
+ export declare const captureFillTilingDifferenceFailures: (differenceFailures: ReadonlyArray<FillTilingDifferenceFailure>, layerHandleId: string, channel: FillTilingClipChannel, sessionReportedDedupeKeys: Set<string>, report: ReportFillTilingDifferenceFailureEvent) => void;
11
+ export {};
@@ -77,6 +77,22 @@ export type FillTilingResult = Readonly<{
77
77
  * `droppedInvalidFeatures`.
78
78
  */
79
79
  intersectionFailures: ReadonlyArray<FillTilingIntersectionFailure>;
80
+ /**
81
+ * Features whose clip threw inside `polygon-clipping` (SAGA-743). The feature kept
82
+ * its full fill, so translucent fills compound where it overlaps higher-ranked
83
+ * neighbours; surfaced here so the hook can report it.
84
+ */
85
+ differenceFailures: ReadonlyArray<FillTilingDifferenceFailure>;
86
+ }>;
87
+ export type FillTilingDifferenceFailure = Readonly<{
88
+ featureId: string;
89
+ /**
90
+ * Higher-ranked features whose clip threw and was skipped. Clips against the other
91
+ * higher-ranked neighbours still applied, so only the overlap with these compounds.
92
+ */
93
+ clipFeatureIds: ReadonlyArray<string>;
94
+ /** The error thrown by `polygon-clipping` (typically "Unable to complete output ring"). */
95
+ error: unknown;
80
96
  }>;
81
97
  export type DroppedInvalidFillTilingFeature = Readonly<{
82
98
  feature: GeoJsonFeature;
@@ -151,5 +167,15 @@ export declare const shapesUnderCursor: (position: GeoJsonPosition, features: Re
151
167
  * its full geometry — so peer-to-peer overlap ownership from resting tiling is
152
168
  * preserved and translucent fills do not compound under the winner.
153
169
  */
154
- export declare const computePromotionGroupFills: (members: ReadonlyArray<GeoJsonFeature>, winnerId: string, restingPeerFills?: ReadonlyMap<string, GeoJsonGeometry>, layerGeodesic?: boolean | undefined, featureStyles?: ReadonlyMap<string, ShapeStyle> | undefined) => ReadonlyMap<string, GeoJsonGeometry>;
170
+ export type PromotionGroupFillsInput = Readonly<{
171
+ members: ReadonlyArray<GeoJsonFeature>;
172
+ winnerId: string;
173
+ /** Resting (tiled) fill per peer; a peer without an entry is clipped from its full geometry. */
174
+ restingPeerFills?: ReadonlyMap<string, GeoJsonGeometry>;
175
+ layerGeodesic?: boolean;
176
+ featureStyles?: ReadonlyMap<string, ShapeStyle>;
177
+ /** Called when `polygon-clipping` threw for a peer and the peer kept its fill unclipped (SAGA-743). */
178
+ onDifferenceFallback?: (featureId: string, error: unknown) => void;
179
+ }>;
180
+ export declare const computePromotionGroupFills: ({ members, winnerId, restingPeerFills, layerGeodesic, featureStyles, onDifferenceFallback, }: PromotionGroupFillsInput) => ReadonlyMap<string, GeoJsonGeometry>;
155
181
  export declare const computeFillTiling: (input: FillTilingInput) => FillTilingResult;