svg-path-commander 2.3.5 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/util.js CHANGED
@@ -1,34 +1,9 @@
1
1
  /*!
2
- * SVGPathCommander UTIL v2.3.5 (http://thednp.github.io/svg-path-commander)
2
+ * SVGPathCommander UTIL v2.4.0 (http://thednp.github.io/svg-path-commander)
3
3
  * Copyright 2026 © thednp
4
4
  * Licensed under MIT (https://github.com/thednp/svg-path-commander/blob/master/LICENSE)
5
5
  */
6
6
  import CSSMatrix from "@thednp/dommatrix";
7
- // src/math/midPoint.ts
8
- /**
9
- * Returns the coordinates of a specified distance
10
- * ratio between two points.
11
- *
12
- * @param a the first point coordinates
13
- * @param b the second point coordinates
14
- * @param t the ratio
15
- * @returns the midpoint coordinates
16
- */
17
- const midPoint = ([ax, ay], [bx, by], t) => {
18
- return [ax + (bx - ax) * t, ay + (by - ay) * t];
19
- };
20
- // src/math/distanceSquareRoot.ts
21
- /**
22
- * Returns the square root of the distance
23
- * between two given points.
24
- *
25
- * @param a the first point coordinates
26
- * @param b the second point coordinates
27
- * @returns the distance value
28
- */
29
- const distanceSquareRoot = (a, b) => {
30
- return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));
31
- };
32
7
  // src/math/lineTools.ts
33
8
  /**
34
9
  * Returns length for line segments (MoveTo, LineTo).
@@ -40,7 +15,9 @@ const distanceSquareRoot = (a, b) => {
40
15
  * @returns the line segment length
41
16
  */
42
17
  const getLineLength = (x1, y1, x2, y2) => {
43
- return distanceSquareRoot([x1, y1], [x2, y2]);
18
+ const dx = x1 - x2;
19
+ const dy = y1 - y2;
20
+ return Math.sqrt(dx * dx + dy * dy);
44
21
  };
45
22
  /**
46
23
  * Returns a point along the line segments (MoveTo, LineTo).
@@ -58,7 +35,7 @@ const getPointAtLineLength = (x1, y1, x2, y2, distance) => {
58
35
  y: y1
59
36
  };
60
37
  if (typeof distance === "number") {
61
- const length = distanceSquareRoot([x1, y1], [x2, y2]);
38
+ const length = getLineLength(x1, y1, x2, y2);
62
39
  if (distance <= 0) point = {
63
40
  x: x1,
64
41
  y: y1
@@ -68,10 +45,10 @@ const getPointAtLineLength = (x1, y1, x2, y2, distance) => {
68
45
  y: y2
69
46
  };
70
47
  else {
71
- const [x, y] = midPoint([x1, y1], [x2, y2], distance / length);
48
+ const ratio = distance / length;
72
49
  point = {
73
- x,
74
- y
50
+ x: x1 + (x2 - x1) * ratio,
51
+ y: y1 + (y2 - y1) * ratio
75
52
  };
76
53
  }
77
54
  }
@@ -274,6 +251,62 @@ const bezierLengthAtT = (derivativeFn, t) => {
274
251
  return z * sum;
275
252
  };
276
253
  /**
254
+ * Returns the speed of a Bezier segment at a given ratio, without allocating
255
+ * a point for it.
256
+ *
257
+ * The quadrature of the length samples the speed of the curve at every one of
258
+ * its points, and a point per sample is a lot of garbage for a long path. The
259
+ * arithmetic is the one of `computeBezier`, so the length of a curve is the
260
+ * same.
261
+ *
262
+ * @param points the control points of the derivative of the curve
263
+ * @param t the sampled point ratio
264
+ * @returns the speed of the curve at the ratio
265
+ */
266
+ const bezierSpeed = (points, t) => {
267
+ const order = points.length - 1;
268
+ const mt = 1 - t;
269
+ if (order === 1) {
270
+ const x = mt * points[0].x + t * points[1].x;
271
+ const y = mt * points[0].y + t * points[1].y;
272
+ return Math.sqrt(x * x + y * y);
273
+ }
274
+ if (order === 2) {
275
+ const mt2 = mt * mt;
276
+ const t2 = t * t;
277
+ const a = mt2;
278
+ const b = mt * t * 2;
279
+ const c = t2;
280
+ const x = a * points[0].x + b * points[1].x + c * points[2].x;
281
+ const y = a * points[0].y + b * points[1].y + c * points[2].y;
282
+ return Math.sqrt(x * x + y * y);
283
+ }
284
+ const d = computeBezier(points, t);
285
+ return Math.sqrt(d.x * d.x + d.y * d.y);
286
+ };
287
+ /**
288
+ * Returns the arc length of a Bezier segment from its start point
289
+ * up to a given `t` ratio, from the control points of its derivative.
290
+ *
291
+ * The integration of the speed `|B'(t)|` over the `[0, t]` interval is done
292
+ * with the Gauss-Legendre quadrature, and the speed is computed without
293
+ * allocating a point for it.
294
+ *
295
+ * @param points the control points of the derivative of the curve
296
+ * @param t the sampled point ratio in `[0-1]`
297
+ * @returns the arc length up to parameter `t`
298
+ */
299
+ const bezierLengthAtPoints = (points, t) => {
300
+ const z = t / 2;
301
+ const len = Tvalues.length;
302
+ let sum = 0;
303
+ for (let i = 0, tMid; i < len; i++) {
304
+ tMid = z * Tvalues[i] + z;
305
+ sum += Cvalues[i] * bezierSpeed(points, tMid);
306
+ }
307
+ return z * sum;
308
+ };
309
+ /**
277
310
  * Builds the Bezier points array from a curve coordinates array.
278
311
  * @param curve cubic / quad bezier segment
279
312
  */
@@ -295,9 +328,7 @@ const getBezierPoints = (curve) => {
295
328
  */
296
329
  const getBezierLengthAtT = (curve, t) => {
297
330
  const dpoints = deriveBezier(getBezierPoints(curve));
298
- return bezierLengthAtT((ratio) => {
299
- return computeBezier(dpoints[0], ratio);
300
- }, t);
331
+ return bezierLengthAtPoints(dpoints[0], t);
301
332
  };
302
333
  /**
303
334
  * Returns the `t` parameter of a Bezier segment at which the cumulative
@@ -308,15 +339,12 @@ const getBezierLengthAtT = (curve, t) => {
308
339
  * @returns the `t` parameter in `[0-1]`
309
340
  */
310
341
  const getTAtBezierLength = (curve, distance) => {
311
- const dpoints = deriveBezier(getBezierPoints(curve));
312
- const derivativeFn = (ratio) => {
313
- return computeBezier(dpoints[0], ratio);
314
- };
342
+ const points = deriveBezier(getBezierPoints(curve))[0];
315
343
  let lo = 0;
316
344
  let hi = 1;
317
345
  for (let i = 0; i < 25; i += 1) {
318
346
  const mid = (lo + hi) / 2;
319
- if (bezierLengthAtT(derivativeFn, mid) < distance) lo = mid;
347
+ if (bezierLengthAtPoints(points, mid) < distance) lo = mid;
320
348
  else hi = mid;
321
349
  }
322
350
  return (lo + hi) / 2;
@@ -328,9 +356,7 @@ const getTAtBezierLength = (curve, distance) => {
328
356
  const getBezierLength = (curve) => {
329
357
  const points = getBezierPoints(curve);
330
358
  const dpoints = deriveBezier(points);
331
- return bezierLength((t) => {
332
- return computeBezier(dpoints[0], t);
333
- });
359
+ return bezierLengthAtPoints(dpoints[0], 1);
334
360
  };
335
361
  /** The precision threshold to consider a cubic polynomial as quadratic. */
336
362
  const CBEZIER_MINMAX_EPSILON = 1e-8;
@@ -473,7 +499,7 @@ const angleBetween = (v0, v1) => {
473
499
  const { x: v1x, y: v1y } = v1;
474
500
  const p = v0x * v1x + v0y * v1y;
475
501
  const n = Math.sqrt((v0x ** 2 + v0y ** 2) * (v1x ** 2 + v1y ** 2));
476
- return (v0x * v1y - v0y * v1x < 0 ? -1 : 1) * Math.acos(p / n);
502
+ return (v0x * v1y - v0y * v1x < 0 ? -1 : 1) * Math.acos(Math.min(1, Math.max(-1, p / n)));
477
503
  };
478
504
  /**
479
505
  * Returns the following properties for an Arc segment: center, start angle,
@@ -575,6 +601,8 @@ const getArcProps = (x1, y1, RX, RY, angle, LAF, SF, x, y) => {
575
601
  * @returns the length of the Arc segment
576
602
  */
577
603
  const getArcLength = (x1, y1, RX, RY, angle, LAF, SF, x, y) => {
604
+ const { abs } = Math;
605
+ if (RX === 0 || RY === 0) return abs(Math.sqrt((x - x1) ** 2 + (y - y1) ** 2));
578
606
  const { rx, ry, startAngle, endAngle } = getArcProps(x1, y1, RX, RY, angle, LAF, SF, x, y);
579
607
  return Math.abs(arcLengthBetween(rx, ry, startAngle, endAngle));
580
608
  };
@@ -602,6 +630,7 @@ const getPointAtArcLength = (x1, y1, RX, RY, angle, LAF, SF, x, y, distance) =>
602
630
  if (typeof distance === "number") {
603
631
  const sweepAngle = endAngle - startAngle;
604
632
  const length = Math.abs(arcLengthBetween(rx, ry, startAngle, endAngle));
633
+ if (rx === 0 || ry === 0) return getPointAtLineLength(x1, y1, x, y, distance);
605
634
  if (distance <= 0) point = {
606
635
  x: x1,
607
636
  y: y1
@@ -611,11 +640,6 @@ const getPointAtArcLength = (x1, y1, RX, RY, angle, LAF, SF, x, y, distance) =>
611
640
  y
612
641
  };
613
642
  else {
614
- if (x1 === x && y1 === y) return {
615
- x,
616
- y
617
- };
618
- if (rx === 0 || ry === 0) return getPointAtLineLength(x1, y1, x, y, distance);
619
643
  const { PI, cos, sin } = Math;
620
644
  const xRotRad = (angle % 360 + 360) % 360 * (PI / 180);
621
645
  let lo = 0;
@@ -654,9 +678,21 @@ const getPointAtArcLength = (x1, y1, RX, RY, angle, LAF, SF, x, y, distance) =>
654
678
  * @returns the extrema of the Arc segment
655
679
  */
656
680
  const getArcBBox = (x1, y1, RX, RY, angle, LAF, SF, x, y) => {
681
+ const { min, max, tan, atan2, cos, PI } = Math;
682
+ if (x1 === x && y1 === y) return [
683
+ x1,
684
+ y1,
685
+ x,
686
+ y
687
+ ];
688
+ if (RX === 0 || RY === 0) return [
689
+ min(x1, x),
690
+ min(y1, y),
691
+ max(x1, x),
692
+ max(y1, y)
693
+ ];
657
694
  const { center, rx, ry, startAngle, endAngle } = getArcProps(x1, y1, RX, RY, angle, LAF, SF, x, y);
658
695
  const deltaAngle = endAngle - startAngle;
659
- const { min, max, tan, atan2, cos, PI } = Math;
660
696
  const { x: cx, y: cy } = center;
661
697
  const alpha = angle * PI / 180;
662
698
  const tangent = tan(alpha);
@@ -674,51 +710,43 @@ const getArcBBox = (x1, y1, RX, RY, angle, LAF, SF, x, y) => {
674
710
  const leftAngle = flipped ? angle1 : angle2;
675
711
  const topAngle = flipped ? angle3 : angle4;
676
712
  const bottomAngle = flipped ? angle4 : angle3;
677
- const xArray = [x];
678
- const yArray = [y];
679
- let xMin = min(x1, x);
680
- let xMax = max(x1, x);
681
- let yMin = min(y1, y);
682
- let yMax = max(y1, y);
683
- const angleAfterStart = endAngle - deltaAngle * 1e-5;
684
- const pP2 = arcPoint(cx, cy, rx, ry, alpha, angleAfterStart);
685
- const angleBeforeEnd = endAngle - deltaAngle * .99999;
686
- const pP3 = arcPoint(cx, cy, rx, ry, alpha, angleBeforeEnd);
713
+ const xArray = [x1, x];
714
+ const yArray = [y1, y];
715
+ const span = Math.abs(deltaAngle);
716
+ const clockwise = deltaAngle >= 0;
687
717
  /**
688
- * expected extremes
689
- * if leaving inner bounding box
690
- * (between segment start and end point)
691
- * otherwise exclude elliptic extreme points
718
+ * tells if an extremum of the ellipse is on the arc, the offset of the
719
+ * extremum is measured from the start of the arc, in the direction of
720
+ * the sweep
692
721
  */
693
- if (pP2[0] > xMax || pP3[0] > xMax) {
694
- const p1 = arcPoint(cx, cy, rx, ry, alpha, rightAngle);
695
- xArray.push(p1[0]);
696
- yArray.push(p1[1]);
697
- }
698
- if (pP2[0] < xMin || pP3[0] < xMin) {
699
- const p2 = arcPoint(cx, cy, rx, ry, alpha, leftAngle);
700
- xArray.push(p2[0]);
701
- yArray.push(p2[1]);
702
- }
703
- if (pP2[1] < yMin || pP3[1] < yMin) {
704
- const p4 = arcPoint(cx, cy, rx, ry, alpha, topAngle);
705
- xArray.push(p4[0]);
706
- yArray.push(p4[1]);
707
- }
708
- if (pP2[1] > yMax || pP3[1] > yMax) {
709
- const p3 = arcPoint(cx, cy, rx, ry, alpha, bottomAngle);
710
- xArray.push(p3[0]);
711
- yArray.push(p3[1]);
712
- }
713
- xMin = min.apply([], xArray);
714
- yMin = min.apply([], yArray);
715
- xMax = max.apply([], xArray);
716
- yMax = max.apply([], yArray);
722
+ const isOnArc = (extremum) => {
723
+ return (clockwise ? ((extremum - startAngle) % (2 * PI) + 2 * PI) % (2 * PI) : ((startAngle - extremum) % (2 * PI) + 2 * PI) % (2 * PI)) <= span + 1e-9;
724
+ };
725
+ if (isOnArc(rightAngle)) {
726
+ const p = arcPoint(cx, cy, rx, ry, alpha, rightAngle);
727
+ xArray.push(p[0]);
728
+ yArray.push(p[1]);
729
+ }
730
+ if (isOnArc(leftAngle)) {
731
+ const p = arcPoint(cx, cy, rx, ry, alpha, leftAngle);
732
+ xArray.push(p[0]);
733
+ yArray.push(p[1]);
734
+ }
735
+ if (isOnArc(topAngle)) {
736
+ const p = arcPoint(cx, cy, rx, ry, alpha, topAngle);
737
+ xArray.push(p[0]);
738
+ yArray.push(p[1]);
739
+ }
740
+ if (isOnArc(bottomAngle)) {
741
+ const p = arcPoint(cx, cy, rx, ry, alpha, bottomAngle);
742
+ xArray.push(p[0]);
743
+ yArray.push(p[1]);
744
+ }
717
745
  return [
718
- xMin,
719
- yMin,
720
- xMax,
721
- yMax
746
+ min(...xArray),
747
+ min(...yArray),
748
+ max(...xArray),
749
+ max(...yArray)
722
750
  ];
723
751
  };
724
752
  /** The tools for elliptical arc computation. */
@@ -984,6 +1012,18 @@ const quadTools = {
984
1012
  getQuadBBox,
985
1013
  getQuadLength
986
1014
  };
1015
+ // src/math/distanceSquareRoot.ts
1016
+ /**
1017
+ * Returns the square root of the distance
1018
+ * between two given points.
1019
+ *
1020
+ * @param a the first point coordinates
1021
+ * @param b the second point coordinates
1022
+ * @returns the distance value
1023
+ */
1024
+ const distanceSquareRoot = (a, b) => {
1025
+ return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]));
1026
+ };
987
1027
  // src/math/polygonTools.ts
988
1028
  /**
989
1029
  * d3-polygon-area
@@ -1046,6 +1086,19 @@ const polygonTools = {
1046
1086
  polygonLength,
1047
1087
  polygonCentroid
1048
1088
  };
1089
+ // src/math/midPoint.ts
1090
+ /**
1091
+ * Returns the coordinates of a specified distance
1092
+ * ratio between two points.
1093
+ *
1094
+ * @param a the first point coordinates
1095
+ * @param b the second point coordinates
1096
+ * @param t the ratio
1097
+ * @returns the midpoint coordinates
1098
+ */
1099
+ const midPoint = ([ax, ay], [bx, by], t) => {
1100
+ return [ax + (bx - ax) * t, ay + (by - ay) * t];
1101
+ };
1049
1102
  // src/math/rotateVector.ts
1050
1103
  /**
1051
1104
  * Returns an {x,y} vector rotated by a given
@@ -1090,6 +1143,21 @@ const paramsCounts = {
1090
1143
  v: 1,
1091
1144
  z: 0
1092
1145
  };
1146
+ /**
1147
+ * The number of parameters of every command, by character code.
1148
+ *
1149
+ * The parser looks the number of the parameters of a command up for every
1150
+ * segment it scans, and the lookup by character code spares it the
1151
+ * lowercasing of the command and the lookup of the string.
1152
+ *
1153
+ * @internal
1154
+ */
1155
+ const paramsCountsByCode = new Uint8Array(128);
1156
+ for (const [command, count] of Object.entries(paramsCounts)) {
1157
+ const code = command.charCodeAt(0);
1158
+ paramsCountsByCode[code] = count;
1159
+ paramsCountsByCode[code - 32] = count;
1160
+ }
1093
1161
  // src/parser/finalizeSegment.ts
1094
1162
  /**
1095
1163
  * Breaks the parsing of a pathString once a segment is finalized.
@@ -1098,28 +1166,29 @@ const paramsCounts = {
1098
1166
  */
1099
1167
  const finalizeSegment = (path) => {
1100
1168
  let pathCommand = path.pathValue[path.segmentStart];
1101
- let relativeCommand = pathCommand.toLowerCase();
1102
1169
  const { data } = path;
1103
1170
  let index = 0;
1104
- while (data.length - index >= paramsCounts[relativeCommand]) {
1105
- if (relativeCommand === "m" && data.length - index > 2) {
1171
+ let paramCount = paramsCountsByCode[pathCommand.charCodeAt(0) | 32];
1172
+ let isMove = pathCommand === "m" || pathCommand === "M";
1173
+ while (data.length - index >= paramCount) {
1174
+ if (isMove && data.length - index > 2) {
1106
1175
  const segment = new Array(3);
1107
1176
  segment[0] = pathCommand;
1108
1177
  segment[1] = data[index];
1109
1178
  segment[2] = data[index + 1];
1110
1179
  path.segments.push(segment);
1111
1180
  index += 2;
1112
- relativeCommand = "l";
1181
+ isMove = false;
1113
1182
  pathCommand = pathCommand === "m" ? "l" : "L";
1183
+ paramCount = 2;
1114
1184
  } else {
1115
- const paramCount = paramsCounts[relativeCommand];
1116
1185
  const segment = new Array(paramCount + 1);
1117
1186
  segment[0] = pathCommand;
1118
1187
  for (let i = 0; i < paramCount; i += 1) segment[i + 1] = data[index + i];
1119
1188
  path.segments.push(segment);
1120
1189
  index += paramCount;
1121
1190
  }
1122
- if (!paramsCounts[relativeCommand]) break;
1191
+ if (!paramCount) break;
1123
1192
  }
1124
1193
  };
1125
1194
  // src/util/error.ts
@@ -1170,7 +1239,6 @@ const invalidPathValue = "Invalid path value";
1170
1239
  const scanParam = (path) => {
1171
1240
  const { max, pathValue, index: start } = path;
1172
1241
  let index = start;
1173
- let zeroFirst = false;
1174
1242
  let hasCeiling = false;
1175
1243
  let hasDecimal = false;
1176
1244
  let hasDot = false;
@@ -1189,15 +1257,8 @@ const scanParam = (path) => {
1189
1257
  return;
1190
1258
  }
1191
1259
  if (ch !== 46) {
1192
- zeroFirst = ch === 48;
1193
1260
  index += 1;
1194
1261
  ch = pathValue.charCodeAt(index);
1195
- if (zeroFirst && index < max) {
1196
- if (ch && isDigit(ch)) {
1197
- path.err = `${error}: ${invalidPathValue} at index ${start}, "${pathValue[start]}" illegal number`;
1198
- return;
1199
- }
1200
- }
1201
1262
  while (index < max && isDigit(pathValue.charCodeAt(index))) {
1202
1263
  index += 1;
1203
1264
  hasCeiling = true;
@@ -1229,6 +1290,7 @@ const scanParam = (path) => {
1229
1290
  }
1230
1291
  path.index = index;
1231
1292
  path.param = scanNumber(pathValue, start, index);
1293
+ if (!Number.isFinite(path.param)) path.err = `${error}: ${invalidPathValue} at index ${start}, "${pathValue.slice(start, index)}" is not a finite number`;
1232
1294
  };
1233
1295
  /**
1234
1296
  * Converts a validated number substring to a Number without
@@ -1285,40 +1347,48 @@ const scanNumber = (str, start, end) => {
1285
1347
  };
1286
1348
  // src/parser/isSpace.ts
1287
1349
  /**
1350
+ * The characters the SVG path grammar accepts as white space.
1351
+ *
1352
+ * The set is built once, at module level: the parser calls `isSpace` for
1353
+ * every single character of a path, and building the list on every call
1354
+ * made the tokenizer allocate its way through a path.
1355
+ */
1356
+ const spaces = new Set([
1357
+ 5760,
1358
+ 6158,
1359
+ 8192,
1360
+ 8193,
1361
+ 8194,
1362
+ 8195,
1363
+ 8196,
1364
+ 8197,
1365
+ 8198,
1366
+ 8199,
1367
+ 8200,
1368
+ 8201,
1369
+ 8202,
1370
+ 8239,
1371
+ 8287,
1372
+ 12288,
1373
+ 65279,
1374
+ 10,
1375
+ 13,
1376
+ 8232,
1377
+ 8233,
1378
+ 32,
1379
+ 9,
1380
+ 11,
1381
+ 12,
1382
+ 160
1383
+ ]);
1384
+ /**
1288
1385
  * Checks if the character is a space.
1289
1386
  *
1290
1387
  * @param ch the character to check
1291
1388
  * @returns check result
1292
1389
  */
1293
1390
  const isSpace = (ch) => {
1294
- return [
1295
- 5760,
1296
- 6158,
1297
- 8192,
1298
- 8193,
1299
- 8194,
1300
- 8195,
1301
- 8196,
1302
- 8197,
1303
- 8198,
1304
- 8199,
1305
- 8200,
1306
- 8201,
1307
- 8202,
1308
- 8239,
1309
- 8287,
1310
- 12288,
1311
- 65279,
1312
- 10,
1313
- 13,
1314
- 8232,
1315
- 8233,
1316
- 32,
1317
- 9,
1318
- 11,
1319
- 12,
1320
- 160
1321
- ].includes(ch);
1391
+ return spaces.has(ch);
1322
1392
  };
1323
1393
  // src/parser/skipSpaces.ts
1324
1394
  /**
@@ -1399,7 +1469,7 @@ const isMoveCommand = (code) => {
1399
1469
  const scanSegment = (path) => {
1400
1470
  const { max, pathValue, index, segments } = path;
1401
1471
  const cmdCode = pathValue.charCodeAt(index);
1402
- const reqParams = paramsCounts[pathValue[index].toLowerCase()];
1472
+ const reqParams = paramsCountsByCode[cmdCode];
1403
1473
  path.segmentStart = index;
1404
1474
  if (!isPathCommand(cmdCode)) {
1405
1475
  path.err = `${error}: ${invalidPathValue} "${pathValue[index]}" is not a path command at index ${index}`;
@@ -1460,7 +1530,11 @@ var PathParser = class {
1460
1530
  *
1461
1531
  * If parameter value is already a `PathArray`,
1462
1532
  * return a clone of it.
1463
-
1533
+ *
1534
+ * A path must begin with a moveto command, so a path that starts with another
1535
+ * command is in error. A leading relative moveto is a pair of absolute
1536
+ * coordinates, so it is rewritten as an absolute one.
1537
+ *
1464
1538
  * @example
1465
1539
  * parsePathString("M 0 0L50 50")
1466
1540
  * // => [["M",0,0],["L",50,50]]
@@ -1469,35 +1543,50 @@ var PathParser = class {
1469
1543
  * @returns the resulted `pathArray` or error string
1470
1544
  */
1471
1545
  const parsePathString = (pathInput) => {
1472
- if (typeof pathInput !== "string") return pathInput.slice(0);
1473
- const path = new PathParser(pathInput);
1474
- skipSpaces(path);
1475
- while (path.index < path.max && !path.err.length) scanSegment(path);
1476
- if (!path.err.length) {
1477
- if (path.segments.length)
1546
+ let path;
1547
+ if (typeof pathInput !== "string") path = pathInput.slice(0);
1548
+ else {
1549
+ const parser = new PathParser(pathInput);
1550
+ skipSpaces(parser);
1551
+ while (parser.index < parser.max && !parser.err.length) scanSegment(parser);
1552
+ if (parser.err.length) throw TypeError(parser.err);
1553
+ path = parser.segments;
1554
+ }
1555
+ const first = path[0];
1556
+ if (!first) return path;
1557
+ if (typeof first[0] !== "string") throw new TypeError(`${error}: invalid path segment at index 0`);
1558
+ if (first[0] === "m")
1478
1559
  /**
1479
- * force absolute first M
1480
- * getPathBBox calculation requires first segment to be absolute
1481
- * @see https://github.com/thednp/svg-path-commander/pull/49
1482
- */
1483
- path.segments[0][0] = "M";
1484
- } else throw TypeError(path.err);
1485
- return path.segments;
1560
+ * force absolute first M
1561
+ * getPathBBox calculation requires first segment to be absolute
1562
+ * @see https://github.com/thednp/svg-path-commander/pull/49
1563
+ */
1564
+ path[0] = [
1565
+ "M",
1566
+ first[1],
1567
+ first[2]
1568
+ ];
1569
+ else if (first[0] !== "M") throw new TypeError(`${error}: path data must begin with a moveto command`);
1570
+ return path;
1486
1571
  };
1487
1572
  // src/process/absolutizeSegment.ts
1488
1573
  /**
1489
1574
  * Returns an absolute segment of a `PathArray` object.
1490
1575
  *
1576
+ * The current point of a path starts at the origin, so the first segment
1577
+ * of a path is absolutized against `[0, 0]`: a relative moveto at the
1578
+ * start of a path is an absolute one, as the SVG spec requires.
1579
+ *
1491
1580
  * @param segment the segment object
1492
- * @param index the segment index
1581
+ * @param _index the segment index
1493
1582
  * @param lastX the last known X value
1494
1583
  * @param lastY the last known Y value
1495
1584
  * @returns the absolute segment
1496
1585
  */
1497
- const absolutizeSegment = (segment, index, lastX, lastY) => {
1586
+ const absolutizeSegment = (segment, _index, lastX, lastY) => {
1498
1587
  const [pathCommand] = segment;
1499
1588
  const absCommand = pathCommand.toUpperCase();
1500
- if (index === 0 || absCommand === pathCommand) return segment;
1589
+ if (absCommand === pathCommand) return segment;
1501
1590
  if (absCommand === "A") return [
1502
1591
  absCommand,
1503
1592
  segment[1],
@@ -1567,7 +1656,8 @@ const iterate = (path, iterator) => {
1567
1656
  let i = 0;
1568
1657
  while (i < path.length) {
1569
1658
  const segment = path[i];
1570
- const [pathCommand] = segment;
1659
+ const pathCommand = segment[0];
1660
+ if (typeof pathCommand !== "string") throw new TypeError(`${error}: invalid path segment at index ${i}`);
1571
1661
  const commandCode = pathCommand.charCodeAt(0);
1572
1662
  const isRelative = commandCode >= 97;
1573
1663
  const absCommand = isRelative ? String.fromCharCode(commandCode - 32) : pathCommand;
@@ -1666,6 +1756,28 @@ const pathToRelative = (pathInput) => {
1666
1756
  const path = parsePathString(pathInput);
1667
1757
  return iterate(path, relativizeSegment);
1668
1758
  };
1759
+ // src/process/lineToCubic.ts
1760
+ /**
1761
+ * Converts an L (line-to) segment to C (cubic-bezier).
1762
+ *
1763
+ * @param x1 line start x
1764
+ * @param y1 line start y
1765
+ * @param x2 line end x
1766
+ * @param y2 line end y
1767
+ * @returns the cubic-bezier segment
1768
+ */
1769
+ const lineToCubic = (x1, y1, x2, y2) => {
1770
+ const c1 = midPoint([x1, y1], [x2, y2], 1 / 3);
1771
+ const c2 = midPoint([x1, y1], [x2, y2], 2 / 3);
1772
+ return [
1773
+ c1[0],
1774
+ c1[1],
1775
+ c2[0],
1776
+ c2[1],
1777
+ x2,
1778
+ y2
1779
+ ];
1780
+ };
1669
1781
  // src/process/arcToCubic.ts
1670
1782
  /**
1671
1783
  * Converts A (arc-to) segments to C (cubic-bezier-to).
@@ -1688,11 +1800,12 @@ const pathToRelative = (pathInput) => {
1688
1800
  const arcToCubic = (X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, recursive) => {
1689
1801
  let x1 = X1;
1690
1802
  let y1 = Y1;
1691
- let rx = RX;
1692
- let ry = RY;
1803
+ let rx = Math.abs(RX);
1804
+ let ry = Math.abs(RY);
1693
1805
  let x2 = X2;
1694
1806
  let y2 = Y2;
1695
1807
  const d120 = Math.PI * 120 / 180;
1808
+ if (!recursive && (rx === 0 || ry === 0)) return lineToCubic(X1, Y1, X2, Y2);
1696
1809
  const rad = Math.PI / 180 * (+angle || 0);
1697
1810
  let res = [];
1698
1811
  let xy;
@@ -1802,32 +1915,13 @@ const quadToCubic = (x1, y1, qx, qy, x2, y2) => {
1802
1915
  y2
1803
1916
  ];
1804
1917
  };
1805
- // src/process/lineToCubic.ts
1806
- /**
1807
- * Converts an L (line-to) segment to C (cubic-bezier).
1808
- *
1809
- * @param x1 line start x
1810
- * @param y1 line start y
1811
- * @param x2 line end x
1812
- * @param y2 line end y
1813
- * @returns the cubic-bezier segment
1814
- */
1815
- const lineToCubic = (x1, y1, x2, y2) => {
1816
- const c1 = midPoint([x1, y1], [x2, y2], 1 / 3);
1817
- const c2 = midPoint([x1, y1], [x2, y2], 2 / 3);
1818
- return [
1819
- c1[0],
1820
- c1[1],
1821
- c2[0],
1822
- c2[1],
1823
- x2,
1824
- y2
1825
- ];
1826
- };
1827
1918
  // src/process/segmentToCubic.ts
1828
1919
  /**
1829
1920
  * Converts any segment to C (cubic-bezier).
1830
1921
  *
1922
+ * A segment that is already a cubic, or a command the converter does not
1923
+ * handle, is returned unchanged.
1924
+ *
1831
1925
  * @param segment the source segment
1832
1926
  * @param params the source segment parameters
1833
1927
  * @returns the cubic-bezier segment
@@ -1870,18 +1964,28 @@ const normalizeSegment = (segment, params, prevCommand) => {
1870
1964
  const absCommand = pathCommand.toUpperCase();
1871
1965
  const isRelative = pathCommand !== absCommand;
1872
1966
  const { x, y } = params;
1873
- const values = segment.slice(1);
1874
- let absValues = values.map((n, j) => n + (isRelative ? j % 2 ? y : x : 0));
1875
1967
  if (!"TQ".includes(absCommand)) {
1876
1968
  params.qx = null;
1877
1969
  params.qy = null;
1878
1970
  }
1879
- if (absCommand === "A") {
1880
- absValues = values.slice(0, -2).concat(values[5] + (isRelative ? x : 0), values[6] + (isRelative ? y : 0));
1881
- return ["A"].concat(absValues);
1882
- } else if (absCommand === "H") return [
1971
+ const absolute = (index) => {
1972
+ const value = segment[index];
1973
+ if (!isRelative) return value;
1974
+ return index % 2 === 1 ? value + x : value + y;
1975
+ };
1976
+ if (absCommand === "A") return [
1977
+ "A",
1978
+ segment[1],
1979
+ segment[2],
1980
+ segment[3],
1981
+ segment[4],
1982
+ segment[5],
1983
+ segment[6] + (isRelative ? x : 0),
1984
+ segment[7] + (isRelative ? y : 0)
1985
+ ];
1986
+ else if (absCommand === "H") return [
1883
1987
  "L",
1884
- segment[1] + (isRelative ? x : 0),
1988
+ absolute(1),
1885
1989
  y
1886
1990
  ];
1887
1991
  else if (absCommand === "V") return [
@@ -1891,22 +1995,34 @@ const normalizeSegment = (segment, params, prevCommand) => {
1891
1995
  ];
1892
1996
  else if (absCommand === "L") return [
1893
1997
  "L",
1894
- segment[1] + (isRelative ? x : 0),
1895
- segment[2] + (isRelative ? y : 0)
1998
+ absolute(1),
1999
+ absolute(2)
1896
2000
  ];
1897
2001
  else if (absCommand === "M") return [
1898
2002
  "M",
1899
- segment[1] + (isRelative ? x : 0),
1900
- segment[2] + (isRelative ? y : 0)
2003
+ absolute(1),
2004
+ absolute(2)
2005
+ ];
2006
+ else if (absCommand === "C") return [
2007
+ "C",
2008
+ absolute(1),
2009
+ absolute(2),
2010
+ absolute(3),
2011
+ absolute(4),
2012
+ absolute(5),
2013
+ absolute(6)
1901
2014
  ];
1902
- else if (absCommand === "C") return ["C"].concat(absValues);
1903
2015
  else if (absCommand === "S") {
1904
2016
  const canReflect = prevCommand != null && "CS".includes(prevCommand);
1905
2017
  return [
1906
2018
  "C",
1907
2019
  canReflect && params.x2 != null ? x * 2 - params.x2 : x,
1908
- canReflect && params.y2 != null ? y * 2 - params.y2 : y
1909
- ].concat(absValues);
2020
+ canReflect && params.y2 != null ? y * 2 - params.y2 : y,
2021
+ absolute(1),
2022
+ absolute(2),
2023
+ absolute(3),
2024
+ absolute(4)
2025
+ ];
1910
2026
  } else if (absCommand === "T") {
1911
2027
  const qx = params.qx != null ? x * 2 - params.qx : x;
1912
2028
  const qy = params.qy != null ? y * 2 - params.qy : y;
@@ -1915,13 +2031,22 @@ const normalizeSegment = (segment, params, prevCommand) => {
1915
2031
  return [
1916
2032
  "Q",
1917
2033
  qx,
1918
- qy
1919
- ].concat(absValues);
2034
+ qy,
2035
+ absolute(1),
2036
+ absolute(2)
2037
+ ];
1920
2038
  } else if (absCommand === "Q") {
1921
- const [nqx, nqy] = absValues;
2039
+ const nqx = absolute(1);
2040
+ const nqy = absolute(2);
1922
2041
  params.qx = nqx;
1923
2042
  params.qy = nqy;
1924
- return ["Q"].concat(absValues);
2043
+ return [
2044
+ "Q",
2045
+ nqx,
2046
+ nqy,
2047
+ absolute(3),
2048
+ absolute(4)
2049
+ ];
1925
2050
  } else if (absCommand === "Z") return ["Z"];
1926
2051
  return segment;
1927
2052
  };
@@ -1953,7 +2078,7 @@ const paramsParser = {
1953
2078
  * @example
1954
2079
  * ```ts
1955
2080
  * pathToCurve('M10 50q15 -25 30 0')
1956
- * // => [['M', 10, 50], ['C', 25, 25, 40, 50, 40, 50]]
2081
+ * // => [['M', 10, 50], ['C', 20, 33.3333, 30, 33.3333, 40, 50]]
1957
2082
  * ```
1958
2083
  */
1959
2084
  const pathToCurve = (pathInput) => {
@@ -1970,8 +2095,11 @@ const pathToCurve = (pathInput) => {
1970
2095
  }
1971
2096
  let result = segmentToCubic(normalSegment, params);
1972
2097
  if (result[0] === "C" && result.length > 7) {
1973
- path.splice(index + 1, 0, ["C"].concat(result.slice(7)));
1974
- result = result.slice(0, 7);
2098
+ const values = result;
2099
+ const segments = [];
2100
+ for (let i = 7; i < values.length; i += 6) segments.push(["C"].concat(values.slice(i, i + 6)));
2101
+ path.splice(index + 1, 0, ...segments);
2102
+ result = values.slice(0, 7);
1975
2103
  }
1976
2104
  const seglen = result.length;
1977
2105
  params.x1 = +result[seglen - 2];
@@ -2037,6 +2165,20 @@ const pathToString = (path, roundOption) => {
2037
2165
  };
2038
2166
  // src/util/getPathBBox.ts
2039
2167
  /**
2168
+ * The bounding box of an empty path.
2169
+ */
2170
+ const emptyBBox = {
2171
+ x: 0,
2172
+ y: 0,
2173
+ width: 0,
2174
+ height: 0,
2175
+ x2: 0,
2176
+ y2: 0,
2177
+ cx: 0,
2178
+ cy: 0,
2179
+ cz: 0
2180
+ };
2181
+ /**
2040
2182
  * Calculates the bounding box of a path.
2041
2183
  *
2042
2184
  * @param pathInput - The path string or PathArray
@@ -2049,18 +2191,9 @@ const pathToString = (path, roundOption) => {
2049
2191
  * ```
2050
2192
  */
2051
2193
  const getPathBBox = (pathInput) => {
2052
- if (!pathInput) return {
2053
- x: 0,
2054
- y: 0,
2055
- width: 0,
2056
- height: 0,
2057
- x2: 0,
2058
- y2: 0,
2059
- cx: 0,
2060
- cy: 0,
2061
- cz: 0
2062
- };
2194
+ if (!pathInput) return { ...emptyBBox };
2063
2195
  const path = parsePathString(pathInput);
2196
+ if (!path.length) return { ...emptyBBox };
2064
2197
  let pathCommand = "M";
2065
2198
  let mx = 0;
2066
2199
  let my = 0;
@@ -2158,21 +2291,22 @@ const getPathBBox = (pathInput) => {
2158
2291
  cz: Math.max(width, height) + Math.min(width, height) / 2
2159
2292
  };
2160
2293
  };
2161
- // src/util/getTotalLength.ts
2294
+ // src/util/measureSegments.ts
2162
2295
  /**
2163
- * Returns the total length of a path, equivalent to `shape.getTotalLength()`.
2296
+ * Measures every segment of a path in a single pass.
2164
2297
  *
2165
- * @param pathInput - The target path string or PathArray
2166
- * @returns The total length of the path
2298
+ * This is the one source of truth for the length math: it absolutises relative
2299
+ * segments, rewrites `H`/`V` to `L` and carries the reflectable control-point
2300
+ * state for `S`/`T`, exactly like `getTotalLength` does. Every consumer that
2301
+ * needs per-segment lengths reads them from here so they cannot disagree with
2302
+ * each other.
2167
2303
  *
2168
- * @example
2169
- * ```ts
2170
- * getTotalLength('M0 0L100 0L100 100L0 100Z')
2171
- * // => 300
2172
- * ```
2304
+ * @param pathInput - the target path string or `PathArray`
2305
+ * @returns the measured segments, in path order
2173
2306
  */
2174
- const getTotalLength = (pathInput) => {
2307
+ const measureSegments = (pathInput) => {
2175
2308
  const path = parsePathString(pathInput);
2309
+ const measures = [];
2176
2310
  let paramX1 = 0;
2177
2311
  let paramY1 = 0;
2178
2312
  let paramX2 = 0;
@@ -2184,9 +2318,9 @@ const getTotalLength = (pathInput) => {
2184
2318
  let my = 0;
2185
2319
  let totalLength = 0;
2186
2320
  iterate(path, (seg, index, lastX, lastY) => {
2187
- [pathCommand] = seg;
2321
+ pathCommand = seg[0];
2188
2322
  const absCommand = pathCommand.toUpperCase();
2189
- const absoluteSegment = absCommand !== pathCommand ? absolutizeSegment(seg, index, lastX, lastY) : seg.slice(0);
2323
+ const absoluteSegment = absCommand !== pathCommand ? absolutizeSegment(seg, index, lastX, lastY) : seg;
2190
2324
  const normalSegment = absCommand === "V" ? [
2191
2325
  "L",
2192
2326
  lastX,
@@ -2196,194 +2330,686 @@ const getTotalLength = (pathInput) => {
2196
2330
  absoluteSegment[1],
2197
2331
  lastY
2198
2332
  ] : absoluteSegment;
2199
- [pathCommand] = normalSegment;
2333
+ pathCommand = normalSegment[0];
2200
2334
  if (!"TQ".includes(absCommand)) {
2201
2335
  paramQX = null;
2202
2336
  paramQY = null;
2203
2337
  }
2204
- if (pathCommand === "M") [, mx, my] = normalSegment;
2205
- else if (pathCommand === "L") totalLength += getLineLength(lastX, lastY, normalSegment[1], normalSegment[2]);
2206
- else if (pathCommand === "A") totalLength += getArcLength(lastX, lastY, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4], normalSegment[5], normalSegment[6], normalSegment[7]);
2338
+ let length = 0;
2339
+ let geometry = normalSegment;
2340
+ if (pathCommand === "M") {
2341
+ mx = normalSegment[1];
2342
+ my = normalSegment[2];
2343
+ } else if (pathCommand === "L") length = getLineLength(lastX, lastY, normalSegment[1], normalSegment[2]);
2344
+ else if (pathCommand === "A") length = getArcLength(lastX, lastY, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4], normalSegment[5], normalSegment[6], normalSegment[7]);
2207
2345
  else if (pathCommand === "S") {
2208
2346
  const cp1x = paramX1 * 2 - paramX2;
2209
2347
  const cp1y = paramY1 * 2 - paramY2;
2210
- totalLength += getCubicLength(lastX, lastY, cp1x, cp1y, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4]);
2211
- } else if (pathCommand === "C") totalLength += getCubicLength(lastX, lastY, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4], normalSegment[5], normalSegment[6]);
2348
+ geometry = [
2349
+ "C",
2350
+ cp1x,
2351
+ cp1y,
2352
+ normalSegment[1],
2353
+ normalSegment[2],
2354
+ normalSegment[3],
2355
+ normalSegment[4]
2356
+ ];
2357
+ length = getCubicLength(lastX, lastY, cp1x, cp1y, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4]);
2358
+ } else if (pathCommand === "C") length = getCubicLength(lastX, lastY, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4], normalSegment[5], normalSegment[6]);
2212
2359
  else if (pathCommand === "T") {
2213
2360
  paramQX = paramQX === null ? lastX : paramX1 * 2 - paramQX;
2214
2361
  paramQY = paramQY === null ? lastY : paramY1 * 2 - paramQY;
2215
- totalLength += getQuadLength(lastX, lastY, paramQX, paramQY, normalSegment[1], normalSegment[2]);
2362
+ geometry = [
2363
+ "Q",
2364
+ paramQX,
2365
+ paramQY,
2366
+ normalSegment[1],
2367
+ normalSegment[2]
2368
+ ];
2369
+ length = getQuadLength(lastX, lastY, paramQX, paramQY, normalSegment[1], normalSegment[2]);
2216
2370
  } else if (pathCommand === "Q") {
2217
2371
  paramQX = normalSegment[1];
2218
2372
  paramQY = normalSegment[2];
2219
- totalLength += getQuadLength(lastX, lastY, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4]);
2220
- } else if (pathCommand === "Z") totalLength += getLineLength(lastX, lastY, mx, my);
2221
- [paramX1, paramY1] = pathCommand === "Z" ? [mx, my] : normalSegment.slice(-2);
2222
- [paramX2, paramY2] = pathCommand === "C" ? [normalSegment[3], normalSegment[4]] : pathCommand === "S" ? [normalSegment[1], normalSegment[2]] : [paramX1, paramY1];
2373
+ length = getQuadLength(lastX, lastY, normalSegment[1], normalSegment[2], normalSegment[3], normalSegment[4]);
2374
+ } else if (pathCommand === "Z") length = getLineLength(lastX, lastY, mx, my);
2375
+ const endX = pathCommand === "Z" ? mx : geometry[geometry.length - 2];
2376
+ const endY = pathCommand === "Z" ? my : geometry[geometry.length - 1];
2377
+ measures.push({
2378
+ segment: seg,
2379
+ index,
2380
+ length,
2381
+ lengthAtSegment: totalLength,
2382
+ startX: lastX,
2383
+ startY: lastY,
2384
+ endX,
2385
+ endY,
2386
+ geometry
2387
+ });
2388
+ totalLength += length;
2389
+ if (pathCommand === "Z") {
2390
+ paramX1 = mx;
2391
+ paramY1 = my;
2392
+ } else {
2393
+ paramX1 = normalSegment[normalSegment.length - 2];
2394
+ paramY1 = normalSegment[normalSegment.length - 1];
2395
+ }
2396
+ if (pathCommand === "C") {
2397
+ paramX2 = normalSegment[3];
2398
+ paramY2 = normalSegment[4];
2399
+ } else if (pathCommand === "S") {
2400
+ paramX2 = normalSegment[1];
2401
+ paramY2 = normalSegment[2];
2402
+ } else {
2403
+ paramX2 = paramX1;
2404
+ paramY2 = paramY1;
2405
+ }
2223
2406
  });
2224
- return totalLength;
2407
+ return measures;
2225
2408
  };
2226
- // src/util/distanceEpsilon.ts
2227
- /** Small threshold value used for floating-point distance comparisons in path calculations. */
2228
- const DISTANCE_EPSILON = 1e-5;
2229
- // src/process/normalizePath.ts
2409
+ // src/util/getTotalLength.ts
2230
2410
  /**
2231
- * Parses a path string or PathArray, then iterates the result for:
2232
- * * converting segments to absolute values
2233
- * * converting shorthand commands to their non-shorthand notation
2411
+ * Returns the total length of a path, equivalent to `shape.getTotalLength()`.
2234
2412
  *
2235
- * @param pathInput - The path string or PathArray
2236
- * @returns The normalized PathArray
2413
+ * @param pathInput - The target path string or PathArray
2414
+ * @returns the total length of the path
2237
2415
  *
2238
2416
  * @example
2239
2417
  * ```ts
2240
- * normalizePath('M10 90s20 -80 40 -80s20 80 40 80')
2241
- * // => [['M', 10, 90], ['C', 30, 90, 25, 10, 50, 10], ['C', 75, 10, 70, 90, 90, 90]]
2418
+ * getTotalLength('M0 0L100 0L100 100L0 100Z')
2419
+ * // => 400
2242
2420
  * ```
2243
2421
  */
2244
- const normalizePath = (pathInput) => {
2245
- const path = parsePathString(pathInput);
2246
- const params = { ...paramsParser };
2247
- let prevCommand = null;
2248
- return iterate(path, (seg, _, lastX, lastY) => {
2249
- params.x = lastX;
2250
- params.y = lastY;
2251
- const result = normalizeSegment(seg, params, prevCommand);
2252
- const seglen = result.length;
2253
- params.x1 = +result[seglen - 2];
2254
- params.y1 = +result[seglen - 1];
2255
- if (result[0] === "C" || result[0] === "Q") {
2256
- params.x2 = +result[seglen - 4];
2257
- params.y2 = +result[seglen - 3];
2258
- } else {
2259
- params.x2 = null;
2260
- params.y2 = null;
2261
- }
2262
- prevCommand = result[0];
2263
- return result;
2264
- });
2422
+ const getTotalLength = (pathInput) => {
2423
+ const measures = measureSegments(pathInput);
2424
+ const last = measures[measures.length - 1];
2425
+ return last ? last.lengthAtSegment + last.length : 0;
2265
2426
  };
2266
- // src/util/getPointAtLength.ts
2427
+ // src/util/distanceEpsilon.ts
2428
+ /** Small threshold value used for floating-point distance comparisons in path calculations. */
2429
+ const DISTANCE_EPSILON = 1e-5;
2430
+ // src/util/pathLengthTable.ts
2267
2431
  /**
2268
- * Returns [x,y] coordinates of a point at a given length along a path.
2432
+ * Measures every segment of a normalized path in a single pass.
2269
2433
  *
2270
- * @param pathInput - The PathArray or path string to look into
2271
- * @param distance - The distance along the path
2272
- * @returns The requested {x, y} point coordinates
2434
+ * A normalized path holds absolute `M`, `L`, `C`, `Q`, `A` and `Z` segments
2435
+ * only, so no relative offsets and no shorthand control point reflections
2436
+ * have to be resolved here — the length of a segment is exactly the length
2437
+ * the point lookup at that distance will use.
2273
2438
  *
2274
- * @example
2275
- * ```ts
2276
- * getPointAtLength('M0 0L100 0L100 100Z', 50)
2277
- * // => { x: 50, y: 0 }
2278
- * ```
2439
+ * @param path - the normalized path to measure
2440
+ * @returns the length table of the path
2279
2441
  */
2280
- const getPointAtLength = (pathInput, distance) => {
2281
- const path = normalizePath(pathInput);
2282
- let isM = false;
2283
- let data = [];
2284
- let [mx, my] = path[0].slice(1);
2285
- const distanceIsNumber = typeof distance === "number";
2286
- let point = {
2287
- x: mx,
2288
- y: my
2289
- };
2290
- let length = 0;
2291
- let POINT = point;
2442
+ const buildPathLengthTable = (path) => {
2443
+ const measures = [];
2444
+ let x = 0;
2445
+ let y = 0;
2446
+ let mx = 0;
2447
+ let my = 0;
2292
2448
  let totalLength = 0;
2293
- if (!distanceIsNumber || distance < 1e-5) return point;
2294
- iterate(path, (seg, _, lastX, lastY) => {
2295
- const pathCommand = seg[0];
2296
- isM = pathCommand === "M";
2297
- data = !isM ? [lastX, lastY].concat(seg.slice(1)) : data;
2298
- if (isM) {
2299
- [, mx, my] = seg;
2300
- point = {
2301
- x: mx,
2302
- y: my
2303
- };
2304
- length = 0;
2305
- } else if (pathCommand === "L") {
2306
- point = getPointAtLineLength(data[0], data[1], data[2], data[3], distance - totalLength);
2307
- length = getLineLength(data[0], data[1], data[2], data[3]);
2308
- } else if (pathCommand === "A") {
2309
- point = getPointAtArcLength(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8], distance - totalLength);
2310
- length = getArcLength(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]);
2311
- } else if (pathCommand === "C") {
2312
- point = getPointAtCubicLength(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7], distance - totalLength);
2313
- length = getCubicLength(data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
2314
- } else if (pathCommand === "Q") {
2315
- point = getPointAtQuadLength(data[0], data[1], data[2], data[3], data[4], data[5], distance - totalLength);
2316
- length = getQuadLength(data[0], data[1], data[2], data[3], data[4], data[5]);
2317
- } else if (pathCommand === "Z") {
2318
- data = [
2319
- lastX,
2320
- lastY,
2321
- mx,
2322
- my
2323
- ];
2324
- point = getPointAtLineLength(data[0], data[1], data[2], data[3], distance - totalLength);
2325
- length = getLineLength(data[0], data[1], data[2], data[3]);
2449
+ let movetoCount = 0;
2450
+ for (const [index, segment] of path.entries()) {
2451
+ const command = segment[0];
2452
+ const measure = {
2453
+ segment,
2454
+ index,
2455
+ startX: x,
2456
+ startY: y,
2457
+ endX: x,
2458
+ endY: y,
2459
+ length: 0,
2460
+ lengthAtSegment: totalLength,
2461
+ geometry: segment
2462
+ };
2463
+ if (command === "M") {
2464
+ mx = segment[1];
2465
+ my = segment[2];
2466
+ measure.endX = mx;
2467
+ measure.endY = my;
2468
+ movetoCount += 1;
2469
+ } else if (command === "L") {
2470
+ measure.endX = segment[1];
2471
+ measure.endY = segment[2];
2472
+ measure.length = getLineLength(x, y, measure.endX, measure.endY);
2473
+ } else if (command === "C") {
2474
+ measure.endX = segment[5];
2475
+ measure.endY = segment[6];
2476
+ measure.length = getCubicLength(x, y, segment[1], segment[2], segment[3], segment[4], measure.endX, measure.endY);
2477
+ } else if (command === "Q") {
2478
+ measure.endX = segment[3];
2479
+ measure.endY = segment[4];
2480
+ measure.length = getQuadLength(x, y, segment[1], segment[2], measure.endX, measure.endY);
2481
+ } else if (command === "A") {
2482
+ measure.endX = segment[6];
2483
+ measure.endY = segment[7];
2484
+ measure.length = getArcLength(x, y, segment[1], segment[2], segment[3], segment[4], segment[5], measure.endX, measure.endY);
2485
+ } else if (command === "Z") {
2486
+ measure.endX = mx;
2487
+ measure.endY = my;
2488
+ measure.length = getLineLength(x, y, mx, my);
2326
2489
  }
2327
- if (totalLength < distance) POINT = point;
2328
- else return false;
2329
- totalLength += length;
2330
- });
2331
- return POINT;
2490
+ measures.push(measure);
2491
+ totalLength += measure.length;
2492
+ x = measure.endX;
2493
+ y = measure.endY;
2494
+ }
2495
+ const [startX, startY] = path[0]?.slice(1) ?? [];
2496
+ const last = measures[measures.length - 1];
2497
+ const isLoop = movetoCount === 1 && !!last && Math.hypot(last.endX - startX, last.endY - startY) <= 1e-5;
2498
+ return {
2499
+ measures,
2500
+ totalLength,
2501
+ startX,
2502
+ startY,
2503
+ isLoop
2504
+ };
2505
+ };
2506
+ /**
2507
+ * Builds the length table of a path from the shared measure pass.
2508
+ *
2509
+ * The measure pass resolves the relative offsets and the shorthand control
2510
+ * point reflections of a path and holds the length of every segment, so the
2511
+ * table can be built from it without measuring the path a second time. The
2512
+ * measures of the pass are the measures of the table: the geometry of a
2513
+ * measure is the normalized segment, so the table holds the same segments and
2514
+ * the same lengths as the one built from a normalized path.
2515
+ *
2516
+ * @param segmentMeasures - the measured segments of the path
2517
+ * @returns the length table of the path
2518
+ */
2519
+ const buildPathLengthTableFromMeasures = (segmentMeasures) => {
2520
+ let movetoCount = 0;
2521
+ for (const measure of segmentMeasures) if (measure.geometry[0] === "M") movetoCount += 1;
2522
+ const first = segmentMeasures[0];
2523
+ const last = segmentMeasures[segmentMeasures.length - 1];
2524
+ const startX = first?.endX ?? 0;
2525
+ const startY = first?.endY ?? 0;
2526
+ return {
2527
+ measures: segmentMeasures,
2528
+ totalLength: last ? last.lengthAtSegment + last.length : 0,
2529
+ startX,
2530
+ startY,
2531
+ isLoop: movetoCount === 1 && !!last && Math.hypot(last.endX - startX, last.endY - startY) <= 1e-5
2532
+ };
2533
+ };
2534
+ /**
2535
+ * Returns the point of a measured path at a given distance.
2536
+ *
2537
+ * The segment is found with a binary search over the accumulated lengths:
2538
+ * it is the last segment whose accumulated length is still below the
2539
+ * distance, which is the same segment the linear walk over the path would
2540
+ * have stopped at.
2541
+ *
2542
+ * @param table - the length table of the path
2543
+ * @param distance - the distance along the path
2544
+ * @returns the requested {x, y} point coordinates
2545
+ */
2546
+ const getPointAtTable = (table, distance) => {
2547
+ const { measures, startX, startY } = table;
2548
+ if (!measures.length) return {
2549
+ x: 0,
2550
+ y: 0
2551
+ };
2552
+ if (typeof distance !== "number" || Number.isNaN(distance) || distance < 1e-5) return {
2553
+ x: startX,
2554
+ y: startY
2555
+ };
2556
+ let low = 0;
2557
+ let high = measures.length - 1;
2558
+ while (low < high) {
2559
+ const mid = low + high + 1 >> 1;
2560
+ if (measures[mid].lengthAtSegment < distance) low = mid;
2561
+ else high = mid - 1;
2562
+ }
2563
+ const measure = measures[low];
2564
+ const { geometry: segment, startX: x1, startY: y1, endX, endY } = measure;
2565
+ const command = segment[0];
2566
+ const offset = distance - measure.lengthAtSegment;
2567
+ if (command === "M") return {
2568
+ x: endX,
2569
+ y: endY
2570
+ };
2571
+ if (command === "L") return getPointAtLineLength(x1, y1, endX, endY, offset);
2572
+ if (command === "C") return getPointAtCubicLength(x1, y1, segment[1], segment[2], segment[3], segment[4], endX, endY, offset);
2573
+ if (command === "Q") return getPointAtQuadLength(x1, y1, segment[1], segment[2], endX, endY, offset);
2574
+ if (command === "A") return getPointAtArcLength(x1, y1, segment[1], segment[2], segment[3], segment[4], segment[5], endX, endY, offset);
2575
+ return getPointAtLineLength(x1, y1, endX, endY, offset);
2576
+ };
2577
+ // src/util/segmentFrame.ts
2578
+ /**
2579
+ * Returns a value without a negative zero.
2580
+ *
2581
+ * The negative zero is a valid number, but it is a surprise in a result:
2582
+ * `Object.is(-0, 0)` is false, so a deep comparison of two equal frames
2583
+ * would fail.
2584
+ *
2585
+ * @param value the value to clean
2586
+ * @returns the value without a negative zero
2587
+ */
2588
+ const cleanZero = (value) => value === 0 ? 0 : value;
2589
+ /**
2590
+ * Returns the unit vector of a direction.
2591
+ *
2592
+ * A direction without a length has no unit vector, so the zero vector is
2593
+ * returned for it.
2594
+ *
2595
+ * @param x the X component of the direction
2596
+ * @param y the Y component of the direction
2597
+ * @returns the unit vector of the direction
2598
+ */
2599
+ const normalizeVector = (x, y) => {
2600
+ const length = Math.sqrt(x * x + y * y);
2601
+ return length > 0 ? {
2602
+ x: cleanZero(x / length),
2603
+ y: cleanZero(y / length)
2604
+ } : {
2605
+ x: 0,
2606
+ y: 0
2607
+ };
2608
+ };
2609
+ /**
2610
+ * Returns the frame of a point with a given direction.
2611
+ *
2612
+ * The normal is the left normal of the tangent, so it points to the left of
2613
+ * the direction of the path, and the angle is the angle of the tangent in
2614
+ * degrees, in the `-180` to `180` range.
2615
+ *
2616
+ * @param point the point of the frame
2617
+ * @param x the X component of the direction
2618
+ * @param y the Y component of the direction
2619
+ * @returns the frame of the point
2620
+ */
2621
+ const frameFrom = (point, x, y) => {
2622
+ const tangent = normalizeVector(x, y);
2623
+ return {
2624
+ point: {
2625
+ x: cleanZero(point.x),
2626
+ y: cleanZero(point.y)
2627
+ },
2628
+ tangent,
2629
+ normal: {
2630
+ x: cleanZero(-tangent.y),
2631
+ y: cleanZero(tangent.x)
2632
+ },
2633
+ angle: Math.atan2(tangent.y, tangent.x) * 180 / Math.PI
2634
+ };
2635
+ };
2636
+ /**
2637
+ * Returns the frame of a line segment at a given distance.
2638
+ *
2639
+ * @param startX the X coordinate the segment starts at
2640
+ * @param startY the Y coordinate the segment starts at
2641
+ * @param endX the X coordinate the segment ends at
2642
+ * @param endY the Y coordinate the segment ends at
2643
+ * @param offset the distance from the start of the segment
2644
+ * @param length the length of the segment
2645
+ * @returns the frame of the segment
2646
+ */
2647
+ const lineFrame = (startX, startY, endX, endY, offset, length) => {
2648
+ const dx = endX - startX;
2649
+ const dy = endY - startY;
2650
+ const ratio = length > 0 ? Math.min(Math.max(offset / length, 0), 1) : 0;
2651
+ return frameFrom({
2652
+ x: startX + dx * ratio,
2653
+ y: startY + dy * ratio
2654
+ }, dx, dy);
2655
+ };
2656
+ /**
2657
+ * Returns the frame of a cubic Bezier segment at a given distance.
2658
+ *
2659
+ * The `t` ratio of the point is found once and shared with the tangent, so
2660
+ * the point and the frame always describe the very same spot on the curve.
2661
+ *
2662
+ * @param coords the coordinates of the segment
2663
+ * @param offset the distance from the start of the segment
2664
+ * @param length the length of the segment
2665
+ * @returns the frame of the segment
2666
+ */
2667
+ const cubicFrame = (coords, offset, length) => {
2668
+ const t = offset <= 0 ? 0 : offset >= length ? 1 : getTAtBezierLength(coords, offset);
2669
+ const point = getPointAtCubicSegmentLength(coords, t);
2670
+ const derivative = computeBezier(deriveBezier(getBezierPoints(coords))[0], t);
2671
+ return frameFrom(point, derivative.x, derivative.y);
2672
+ };
2673
+ /**
2674
+ * Returns the frame of a quadratic Bezier segment at a given distance.
2675
+ *
2676
+ * @param coords the coordinates of the segment
2677
+ * @param offset the distance from the start of the segment
2678
+ * @param length the length of the segment
2679
+ * @returns the frame of the segment
2680
+ */
2681
+ const quadFrame = (coords, offset, length) => {
2682
+ const t = offset <= 0 ? 0 : offset >= length ? 1 : getTAtBezierLength(coords, offset);
2683
+ const point = getPointAtQuadSegmentLength(coords, t);
2684
+ const derivative = computeBezier(deriveBezier(getBezierPoints(coords))[0], t);
2685
+ return frameFrom(point, derivative.x, derivative.y);
2686
+ };
2687
+ /**
2688
+ * Returns the frame of an elliptical arc segment at a given distance.
2689
+ *
2690
+ * The parametric angle of the arc is found once and shared with the tangent,
2691
+ * which is the derivative of the ellipse at that angle.
2692
+ *
2693
+ * @param startX the X coordinate the segment starts at
2694
+ * @param startY the Y coordinate the segment starts at
2695
+ * @param RX the radius on X axis
2696
+ * @param RY the radius on Y axis
2697
+ * @param rotation the ellipse rotation in degrees
2698
+ * @param LAF the large arc flag
2699
+ * @param SF the sweep flag
2700
+ * @param endX the X coordinate the segment ends at
2701
+ * @param endY the Y coordinate the segment ends at
2702
+ * @param offset the distance from the start of the segment
2703
+ * @param length the length of the segment
2704
+ * @returns the frame of the segment
2705
+ */
2706
+ const arcFrame = (startX, startY, RX, RY, rotation, LAF, SF, endX, endY, offset, length) => {
2707
+ const { center, rx, ry, startAngle, endAngle } = getArcProps(startX, startY, RX, RY, rotation, LAF, SF, endX, endY);
2708
+ if (rx === 0 || ry === 0) return lineFrame(startX, startY, endX, endY, offset, length);
2709
+ const sweepAngle = endAngle - startAngle;
2710
+ const { PI, cos, sin } = Math;
2711
+ const xRotRad = (rotation % 360 + 360) % 360 * (PI / 180);
2712
+ const tangentAt = (alpha) => {
2713
+ const cosA = cos(alpha);
2714
+ const sinA = sin(alpha);
2715
+ return {
2716
+ x: -cos(xRotRad) * rx * sinA - sin(xRotRad) * ry * cosA,
2717
+ y: -sin(xRotRad) * rx * sinA + cos(xRotRad) * ry * cosA
2718
+ };
2719
+ };
2720
+ const pointAt = (alpha) => {
2721
+ const ellipseX = rx * cos(alpha);
2722
+ const ellipseY = ry * sin(alpha);
2723
+ return {
2724
+ x: cos(xRotRad) * ellipseX - sin(xRotRad) * ellipseY + center.x,
2725
+ y: sin(xRotRad) * ellipseX + cos(xRotRad) * ellipseY + center.y
2726
+ };
2727
+ };
2728
+ if (length <= 0) return frameFrom({
2729
+ x: startX,
2730
+ y: startY
2731
+ }, 0, 0);
2732
+ const direction = sweepAngle < 0 ? -1 : 1;
2733
+ if (offset <= 0) {
2734
+ const tangent = tangentAt(startAngle);
2735
+ return frameFrom({
2736
+ x: startX,
2737
+ y: startY
2738
+ }, direction * tangent.x, direction * tangent.y);
2739
+ }
2740
+ if (offset >= length) {
2741
+ const tangent = tangentAt(endAngle);
2742
+ return frameFrom({
2743
+ x: endX,
2744
+ y: endY
2745
+ }, direction * tangent.x, direction * tangent.y);
2746
+ }
2747
+ let lo = 0;
2748
+ let hi = 1;
2749
+ for (let i = 0; i < 25; i += 1) {
2750
+ const mid = (lo + hi) / 2;
2751
+ if (Math.abs(arcLengthBetween(rx, ry, startAngle, startAngle + sweepAngle * mid)) < offset) lo = mid;
2752
+ else hi = mid;
2753
+ }
2754
+ const alpha = startAngle + sweepAngle * ((lo + hi) / 2);
2755
+ const tangent = tangentAt(alpha);
2756
+ return frameFrom(pointAt(alpha), direction * tangent.x, direction * tangent.y);
2757
+ };
2758
+ /**
2759
+ * Returns the frame of a path segment at a given distance.
2760
+ *
2761
+ * The segment has to be an absolute one, with the shorthand commands
2762
+ * expanded, so the geometry and the length of the segment agree.
2763
+ *
2764
+ * @param geometry the absolute segment
2765
+ * @param startX the X coordinate the segment starts at
2766
+ * @param startY the Y coordinate the segment starts at
2767
+ * @param endX the X coordinate the segment ends at
2768
+ * @param endY the Y coordinate the segment ends at
2769
+ * @param offset the distance from the start of the segment
2770
+ * @param length the length of the segment
2771
+ * @returns the frame of the segment
2772
+ */
2773
+ const getSegmentFrame = (geometry, startX, startY, endX, endY, offset, length) => {
2774
+ const command = geometry[0];
2775
+ if (command === "M") return frameFrom({
2776
+ x: endX,
2777
+ y: endY
2778
+ }, 0, 0);
2779
+ if (command === "L" || command === "Z") return lineFrame(startX, startY, endX, endY, offset, length);
2780
+ if (command === "C") {
2781
+ const coords = [
2782
+ startX,
2783
+ startY,
2784
+ geometry[1],
2785
+ geometry[2],
2786
+ geometry[3],
2787
+ geometry[4],
2788
+ endX,
2789
+ endY
2790
+ ];
2791
+ return cubicFrame(coords, offset, length);
2792
+ }
2793
+ if (command === "Q") {
2794
+ const coords = [
2795
+ startX,
2796
+ startY,
2797
+ geometry[1],
2798
+ geometry[2],
2799
+ endX,
2800
+ endY
2801
+ ];
2802
+ return quadFrame(coords, offset, length);
2803
+ }
2804
+ return arcFrame(startX, startY, geometry[1], geometry[2], geometry[3], geometry[4], geometry[5], endX, endY, offset, length);
2332
2805
  };
2333
2806
  // src/util/getPropertiesAtLength.ts
2334
2807
  /**
2808
+ * Returns the length of a measured segment.
2809
+ *
2810
+ * The length is taken from the accumulated lengths, the total up to the
2811
+ * segment minus the total before it, and not from the length the segment
2812
+ * was measured with: the two differ in the last bits, and this keeps the
2813
+ * result identical to the one the previous implementation returned.
2814
+ *
2815
+ * @param measure - the measured segment
2816
+ * @returns the length of the segment
2817
+ */
2818
+ const segmentLength = (measure) => measure.lengthAtSegment + measure.length - measure.lengthAtSegment;
2819
+ /**
2820
+ * Returns the frame of a measured segment at a given distance.
2821
+ *
2822
+ * @param measure - the measured segment
2823
+ * @param offset - the distance from the start of the segment
2824
+ * @returns the frame of the segment
2825
+ */
2826
+ const frameOf = (measure, offset = 0) => {
2827
+ if (!measure) return {
2828
+ point: {
2829
+ x: 0,
2830
+ y: 0
2831
+ },
2832
+ tangent: {
2833
+ x: 0,
2834
+ y: 0
2835
+ },
2836
+ normal: {
2837
+ x: 0,
2838
+ y: 0
2839
+ },
2840
+ angle: 0
2841
+ };
2842
+ return getSegmentFrame(measure.geometry, measure.startX, measure.startY, measure.endX, measure.endY, offset, measure.length);
2843
+ };
2844
+ const getPropertiesFromMeasure = (measure, offset) => ({
2845
+ segment: measure.segment,
2846
+ index: measure.index,
2847
+ length: segmentLength(measure),
2848
+ lengthAtSegment: measure.lengthAtSegment,
2849
+ ...frameOf(measure, offset)
2850
+ });
2851
+ /**
2335
2852
  * Returns the segment, its index and length as well as
2336
2853
  * the length to that segment at a given length in a path.
2337
2854
  *
2338
- * @param pathInput target `pathArray`
2339
- * @param distance the given length
2855
+ * The point at the given length is returned with the frame of the path at
2856
+ * that point: the unit tangent vector, the unit normal vector and the angle
2857
+ * of the tangent in degrees.
2858
+ *
2859
+ * @param measures - the measured segments of the path
2860
+ * @param distance - the given length
2340
2861
  * @returns the requested properties
2341
2862
  */
2342
- const getPropertiesAtLength = (pathInput, distance) => {
2343
- const pathArray = parsePathString(pathInput);
2344
- let pathTemp = pathArray.slice(0);
2345
- let pathLength = getTotalLength(pathTemp);
2346
- let index = pathTemp.length - 1;
2347
- let lengthAtSegment = 0;
2348
- let length = 0;
2349
- let segment = pathArray[0];
2350
- if (index <= 0 || !distance || !Number.isFinite(distance)) return {
2863
+ const getPropertiesFromMeasures = (measures, distance) => {
2864
+ const lastIndex = measures.length - 1;
2865
+ const segment = measures[0]?.segment ?? [
2866
+ "M",
2867
+ 0,
2868
+ 0
2869
+ ];
2870
+ if (lastIndex <= 0 || !distance || distance < 0) return {
2351
2871
  segment,
2352
2872
  index: 0,
2353
- length,
2354
- lengthAtSegment
2873
+ length: 0,
2874
+ lengthAtSegment: 0,
2875
+ ...frameOf(measures[0])
2355
2876
  };
2356
- if (distance >= pathLength) {
2357
- pathTemp = pathArray.slice(0, -1);
2358
- lengthAtSegment = getTotalLength(pathTemp);
2359
- length = pathLength - lengthAtSegment;
2360
- segment = pathArray[index];
2361
- return {
2362
- segment,
2363
- index,
2364
- length,
2365
- lengthAtSegment
2366
- };
2367
- }
2368
- const segments = [];
2369
- while (index > 0) {
2370
- segment = pathTemp[index];
2371
- pathTemp = pathTemp.slice(0, -1);
2372
- lengthAtSegment = getTotalLength(pathTemp);
2373
- length = pathLength - lengthAtSegment;
2374
- pathLength = lengthAtSegment;
2375
- segments.push({
2376
- segment,
2377
- index,
2378
- length,
2379
- lengthAtSegment
2380
- });
2381
- index -= 1;
2877
+ const last = measures[lastIndex];
2878
+ if (distance >= last.lengthAtSegment + last.length) return {
2879
+ segment: last.segment,
2880
+ index: last.index,
2881
+ length: segmentLength(last),
2882
+ lengthAtSegment: last.lengthAtSegment,
2883
+ ...frameOf(last, distance - last.lengthAtSegment)
2884
+ };
2885
+ let index = 1;
2886
+ for (let i = lastIndex; i > 0; i--) if (measures[i].lengthAtSegment <= distance) {
2887
+ index = i;
2888
+ break;
2382
2889
  }
2383
- return segments.find(({ lengthAtSegment: l }) => l <= distance);
2890
+ const measure = measures[index];
2891
+ return {
2892
+ segment: measure.segment,
2893
+ index: measure.index,
2894
+ length: segmentLength(measure),
2895
+ lengthAtSegment: measure.lengthAtSegment,
2896
+ ...frameOf(measure, distance - measure.lengthAtSegment)
2897
+ };
2898
+ };
2899
+ /**
2900
+ * Returns the segment, its index and length as well as
2901
+ * the length to that segment at a given length in a path.
2902
+ *
2903
+ * The point at the given length is returned with the frame of the path at
2904
+ * that point: the unit tangent vector, the unit normal vector and the angle
2905
+ * of the tangent in degrees.
2906
+ *
2907
+ * @param pathInput target `pathArray`
2908
+ * @param distance the given length
2909
+ * @returns the requested properties
2910
+ */
2911
+ const getPropertiesAtLength = (pathInput, distance) => {
2912
+ return getPropertiesFromMeasures(measureSegments(pathInput), distance);
2384
2913
  };
2385
2914
  // src/util/getPropertiesAtPoint.ts
2386
2915
  /**
2916
+ * The relative difference below which two distances are the same.
2917
+ *
2918
+ * The distance of a point to a path is squared, so the noise of the floating
2919
+ * point arithmetic is relative to the distance itself. A path that runs at
2920
+ * a constant distance from the point — a circle around it — has no minimum at
2921
+ * all, and the noise of the samples must not be read as one.
2922
+ */
2923
+ const distanceEpsilon = 1e-7;
2924
+ /**
2925
+ * The precision of the refinement of the closest point.
2926
+ *
2927
+ * The precision is relative to the length of the path: a path of a few units
2928
+ * needs a finer precision than a path of thousands of units, and the answer
2929
+ * of a short path is expected to be as exact as the answer of a long one. The
2930
+ * relative floor is capped, so a very long path does not trade the accuracy
2931
+ * of its distance for a path-relative length precision.
2932
+ */
2933
+ const precisionShare = 1e-9;
2934
+ const maxPrecisionFloor = 1e-6;
2935
+ /**
2936
+ * The number of samples of the coarse scan of a short path.
2937
+ *
2938
+ * The scan of the path is spread over its length, so a short path is sampled
2939
+ * more densely than a long one: the place where the path passes closest to
2940
+ * the point must not fall between two samples of the scan.
2941
+ */
2942
+ const minSamples = 64;
2943
+ /**
2944
+ * The maximum number of samples of the coarse scan of a path.
2945
+ *
2946
+ * The scan is dense enough to find the place where the path passes closest
2947
+ * to the point, but it stays bounded for a long path: the length of the path
2948
+ * is divided into this many intervals at most.
2949
+ */
2950
+ const maxSamples = 4096;
2951
+ /**
2952
+ * The step of the coarse scan of a long path, in units of length.
2953
+ */
2954
+ const maxScanStep = 8;
2955
+ /**
2956
+ * Finds the index of the segment a distance falls into.
2957
+ *
2958
+ * The segment is the last one whose accumulated length is below the
2959
+ * distance, the same segment the lookup of a point at that distance uses.
2960
+ *
2961
+ * @param measures - the measured segments of the path
2962
+ * @param distance - the distance along the path
2963
+ * @returns the index of the segment
2964
+ */
2965
+ const findSegmentIndex$1 = (measures, distance) => {
2966
+ if (distance <= 0) return 0;
2967
+ let low = 0;
2968
+ let high = measures.length - 1;
2969
+ while (low < high) {
2970
+ const mid = low + high + 1 >> 1;
2971
+ if (measures[mid].lengthAtSegment <= distance) low = mid;
2972
+ else high = mid - 1;
2973
+ }
2974
+ return low;
2975
+ };
2976
+ /**
2977
+ * Returns the closest point of a straight segment.
2978
+ *
2979
+ * The projection of the point on the line of the segment is the closest
2980
+ * point of the segment when it falls on the segment, and the closest end of
2981
+ * the segment when it does not. The projection is computed along the direction
2982
+ * of the segment, so a point that is on the segment is answered with itself.
2983
+ *
2984
+ * @param point - the point to project
2985
+ * @param startX - the X coordinate of the start of the segment
2986
+ * @param startY - the Y coordinate of the start of the segment
2987
+ * @param endX - the X coordinate of the end of the segment
2988
+ * @param endY - the Y coordinate of the end of the segment
2989
+ * @returns the closest point of the segment and its position on the segment
2990
+ */
2991
+ const projectOnSegment = (point, startX, startY, endX, endY) => {
2992
+ const dx = endX - startX;
2993
+ const dy = endY - startY;
2994
+ const length = Math.hypot(dx, dy);
2995
+ if (!length) return {
2996
+ point: {
2997
+ x: startX,
2998
+ y: startY
2999
+ },
3000
+ ratio: 0
3001
+ };
3002
+ const ratio = ((point.x - startX) * dx + (point.y - startY) * dy) / (length * length);
3003
+ const clamped = Math.max(0, Math.min(1, ratio));
3004
+ return {
3005
+ point: {
3006
+ x: startX + dx * clamped,
3007
+ y: startY + dy * clamped
3008
+ },
3009
+ ratio: clamped
3010
+ };
3011
+ };
3012
+ /**
2387
3013
  * Returns the point and segment in path closest to a given point as well as
2388
3014
  * the distance to the path stroke.
2389
3015
  *
@@ -2395,60 +3021,161 @@ const getPropertiesAtLength = (pathInput, distance) => {
2395
3021
  */
2396
3022
  const getPropertiesAtPoint = (pathInput, point) => {
2397
3023
  const path = parsePathString(pathInput);
2398
- const normalPath = normalizePath(path);
2399
- const pathLength = getTotalLength(normalPath);
3024
+ if (!path.length) return {
3025
+ closest: {
3026
+ x: 0,
3027
+ y: 0
3028
+ },
3029
+ distance: Infinity
3030
+ };
3031
+ const segmentMeasures = measureSegments(path);
3032
+ const table = buildPathLengthTableFromMeasures(segmentMeasures);
3033
+ const pathLength = table.totalLength;
3034
+ const isLoop = table.isLoop;
2400
3035
  const distanceTo = (p) => {
2401
3036
  const dx = p.x - point.x;
2402
3037
  const dy = p.y - point.y;
2403
3038
  return dx * dx + dy * dy;
2404
3039
  };
2405
- let precision = 8;
2406
- let scan;
2407
- let closest = {
3040
+ const scanStep = pathLength ? Math.max(pathLength / maxSamples, Math.min(maxScanStep, pathLength / minSamples)) : maxScanStep;
3041
+ const candidates = [];
3042
+ let bestLength = 0;
3043
+ let bestDistance = Infinity;
3044
+ let bestPoint = {
2408
3045
  x: 0,
2409
3046
  y: 0
2410
3047
  };
2411
- let scanDistance = 0;
2412
- let bestLength = 0;
2413
- let bestDistance = Infinity;
2414
- for (let scanLength = 0; scanLength <= pathLength; scanLength += precision) {
2415
- scan = getPointAtLength(normalPath, scanLength);
2416
- scanDistance = distanceTo(scan);
3048
+ let previousDistance = Infinity;
3049
+ let lastLength = 0;
3050
+ let lastDistance = Infinity;
3051
+ let lastPoint = {
3052
+ x: 0,
3053
+ y: 0
3054
+ };
3055
+ let lastScannedLength = -1;
3056
+ const scan = (scanLength) => {
3057
+ if (scanLength <= lastScannedLength) return;
3058
+ lastScannedLength = scanLength;
3059
+ const scanPoint = getPointAtTable(table, scanLength);
3060
+ const scanDistance = distanceTo(scanPoint);
3061
+ if (lastDistance < scanDistance - scanDistance * distanceEpsilon && lastDistance <= previousDistance + previousDistance * distanceEpsilon) candidates.push({
3062
+ length: lastLength,
3063
+ distance: lastDistance,
3064
+ point: lastPoint
3065
+ });
3066
+ previousDistance = lastDistance;
3067
+ lastLength = scanLength;
3068
+ lastDistance = scanDistance;
3069
+ lastPoint = scanPoint;
2417
3070
  if (scanDistance < bestDistance) {
2418
- closest = scan;
2419
3071
  bestLength = scanLength;
2420
3072
  bestDistance = scanDistance;
3073
+ bestPoint = scanPoint;
3074
+ }
3075
+ };
3076
+ for (const measure of segmentMeasures) {
3077
+ const segmentStart = measure.lengthAtSegment;
3078
+ const segmentEnd = segmentStart + measure.length;
3079
+ for (let scanLength = segmentStart; scanLength < segmentEnd; scanLength += scanStep) scan(scanLength);
3080
+ scan(segmentEnd);
3081
+ }
3082
+ if (lastDistance < previousDistance - previousDistance * distanceEpsilon) candidates.push({
3083
+ length: lastLength,
3084
+ distance: lastDistance,
3085
+ point: lastPoint
3086
+ });
3087
+ const refine = (start) => {
3088
+ let { length, distance } = start;
3089
+ let closest = start.point;
3090
+ let precision = scanStep / 2;
3091
+ let beforeLength = 0;
3092
+ let afterLength = 0;
3093
+ const precisionFloor = Math.min(Math.max(pathLength * precisionShare, 1e-9), maxPrecisionFloor);
3094
+ while (precision > precisionFloor) {
3095
+ beforeLength = length - precision;
3096
+ afterLength = length + precision;
3097
+ if (beforeLength < 0) beforeLength = isLoop ? beforeLength + pathLength : -1;
3098
+ if (afterLength > pathLength) afterLength = isLoop ? afterLength - pathLength : pathLength + 1;
3099
+ const before = beforeLength >= 0 && beforeLength <= pathLength ? getPointAtTable(table, beforeLength) : null;
3100
+ const after = afterLength >= 0 && afterLength <= pathLength ? getPointAtTable(table, afterLength) : null;
3101
+ const beforeDistance = before ? distanceTo(before) : Infinity;
3102
+ const afterDistance = after ? distanceTo(after) : Infinity;
3103
+ if (before && beforeDistance < distance) {
3104
+ closest = before;
3105
+ length = beforeLength;
3106
+ distance = beforeDistance;
3107
+ } else if (after && afterDistance < distance) {
3108
+ closest = after;
3109
+ length = afterLength;
3110
+ distance = afterDistance;
3111
+ } else precision /= 2;
3112
+ }
3113
+ const measure = segmentMeasures[findSegmentIndex$1(segmentMeasures, length)];
3114
+ const command = measure.geometry[0];
3115
+ if (command === "L" || command === "Z") {
3116
+ const { point: projected, ratio } = projectOnSegment(point, measure.startX, measure.startY, measure.endX, measure.endY);
3117
+ const dx = point.x - projected.x;
3118
+ const dy = point.y - projected.y;
3119
+ const projectedDistance = dx * dx + dy * dy;
3120
+ if (projectedDistance < distance) {
3121
+ closest = projected;
3122
+ distance = projectedDistance;
3123
+ length = measure.lengthAtSegment + ratio * measure.length;
3124
+ }
3125
+ }
3126
+ return {
3127
+ closest,
3128
+ distance,
3129
+ length,
3130
+ measure
3131
+ };
3132
+ };
3133
+ const best = refine({
3134
+ length: bestLength,
3135
+ distance: bestDistance,
3136
+ point: bestPoint
3137
+ });
3138
+ let closest = best.closest;
3139
+ let closestDistance = best.distance;
3140
+ let closestLength = best.length;
3141
+ let closestMeasure = best.measure;
3142
+ candidates.sort((a, b) => a.distance - b.distance);
3143
+ for (const candidate of candidates) {
3144
+ const refined = refine(candidate);
3145
+ if (refined.distance < closestDistance) {
3146
+ closest = refined.closest;
3147
+ closestDistance = refined.distance;
3148
+ closestLength = refined.length;
3149
+ closestMeasure = refined.measure;
2421
3150
  }
2422
3151
  }
2423
- precision /= 2;
2424
- let before;
2425
- let after;
2426
- let beforeLength = 0;
2427
- let afterLength = 0;
2428
- let beforeDistance = 0;
2429
- let afterDistance = 0;
2430
- while (precision > 1e-6) {
2431
- beforeLength = bestLength - precision;
2432
- before = getPointAtLength(normalPath, beforeLength);
2433
- beforeDistance = distanceTo(before);
2434
- afterLength = bestLength + precision;
2435
- after = getPointAtLength(normalPath, afterLength);
2436
- afterDistance = distanceTo(after);
2437
- if (beforeLength >= 0 && beforeDistance < bestDistance) {
2438
- closest = before;
2439
- bestLength = beforeLength;
2440
- bestDistance = beforeDistance;
2441
- } else if (afterLength <= pathLength && afterDistance < bestDistance) {
2442
- closest = after;
2443
- bestLength = afterLength;
2444
- bestDistance = afterDistance;
2445
- } else precision /= 2;
2446
- if (precision < 1e-5) break;
2447
- }
2448
- const segment = getPropertiesAtLength(path, bestLength);
3152
+ for (const measure of segmentMeasures) {
3153
+ const command = measure.geometry[0];
3154
+ let projected;
3155
+ let ratio = 0;
3156
+ if (command === "M") projected = {
3157
+ x: measure.endX,
3158
+ y: measure.endY
3159
+ };
3160
+ else if (command === "L" || command === "Z") {
3161
+ const projection = projectOnSegment(point, measure.startX, measure.startY, measure.endX, measure.endY);
3162
+ projected = projection.point;
3163
+ ratio = projection.ratio;
3164
+ } else continue;
3165
+ const dx = point.x - projected.x;
3166
+ const dy = point.y - projected.y;
3167
+ const projectedDistance = dx * dx + dy * dy;
3168
+ if (!Number.isFinite(projectedDistance) || projectedDistance >= closestDistance) continue;
3169
+ const projectedLength = measure.lengthAtSegment + ratio * measure.length;
3170
+ closest = projected;
3171
+ closestDistance = projectedDistance;
3172
+ closestLength = projectedLength;
3173
+ closestMeasure = measure;
3174
+ }
3175
+ const segment = getPropertiesFromMeasure(closestMeasure, Math.max(0, Math.min(closestMeasure.length, closestLength - closestMeasure.lengthAtSegment)));
2449
3176
  return {
2450
3177
  closest,
2451
- distance: Math.sqrt(bestDistance),
3178
+ distance: Math.sqrt(closestDistance),
2452
3179
  segment
2453
3180
  };
2454
3181
  };
@@ -2495,14 +3222,25 @@ const getCubicSegArea = (x1, y1, c1x, c1y, c2x, c2y, x2, y2) => {
2495
3222
  * @example
2496
3223
  * ```ts
2497
3224
  * getPathArea([['M', 0, 0], ['L', 100, 0], ['L', 100, 100], ['L', 0, 100], ['Z']])
2498
- * // => -10000 (counter-clockwise square)
3225
+ * // => 10000 (clockwise square)
2499
3226
  * ```
2500
3227
  */
2501
- const getPathArea = (path) => {
3228
+ const getPathArea = (path) => getCurveArea(pathToCurve(path));
3229
+ /**
3230
+ * Returns the signed area of a path that is already made of cubic beziers.
3231
+ *
3232
+ * The conversion is the expensive part of the area calculation, so it is
3233
+ * kept out of this function: a caller that already has a curve array does
3234
+ * not have to convert it a second time.
3235
+ *
3236
+ * @param path - The curve PathArray
3237
+ * @returns The signed area of the shape
3238
+ */
3239
+ const getCurveArea = (path) => {
2502
3240
  let x = 0;
2503
3241
  let y = 0;
2504
3242
  let len = 0;
2505
- return pathToCurve(path).map((seg) => {
3243
+ return path.map((seg) => {
2506
3244
  switch (seg[0]) {
2507
3245
  case "M":
2508
3246
  [, x, y] = seg;
@@ -2523,7 +3261,76 @@ const getPathArea = (path) => {
2523
3261
  * @returns true when clockwise or false if not
2524
3262
  */
2525
3263
  const getDrawDirection = (path) => {
2526
- return getPathArea(pathToCurve(path)) >= 0;
3264
+ return getCurveArea(pathToCurve(path)) >= 0;
3265
+ };
3266
+ // src/process/normalizePath.ts
3267
+ /**
3268
+ * Parses a path string or PathArray, then iterates the result for:
3269
+ * * converting segments to absolute values
3270
+ * * converting shorthand commands to their non-shorthand notation
3271
+ *
3272
+ * @param pathInput - The path string or PathArray
3273
+ * @returns The normalized PathArray
3274
+ *
3275
+ * @example
3276
+ * ```ts
3277
+ * normalizePath('M10 90s20 -80 40 -80s20 80 40 80')
3278
+ * // => [['M', 10, 90], ['C', 10, 90, 30, 10, 50, 10], ['C', 70, 10, 70, 90, 90, 90]]
3279
+ * ```
3280
+ */
3281
+ const normalizePath = (pathInput) => {
3282
+ const path = parsePathString(pathInput);
3283
+ const params = { ...paramsParser };
3284
+ let prevCommand = null;
3285
+ return iterate(path, (seg, _, lastX, lastY) => {
3286
+ params.x = lastX;
3287
+ params.y = lastY;
3288
+ const result = normalizeSegment(seg, params, prevCommand);
3289
+ const seglen = result.length;
3290
+ params.x1 = +result[seglen - 2];
3291
+ params.y1 = +result[seglen - 1];
3292
+ if (result[0] === "C" || result[0] === "Q") {
3293
+ params.x2 = +result[seglen - 4];
3294
+ params.y2 = +result[seglen - 3];
3295
+ } else {
3296
+ params.x2 = null;
3297
+ params.y2 = null;
3298
+ }
3299
+ prevCommand = result[0];
3300
+ return result;
3301
+ });
3302
+ };
3303
+ // src/util/getPointAtLength.ts
3304
+ /**
3305
+ * Returns [x,y] coordinates of a point at a given length along a path.
3306
+ *
3307
+ * @param pathInput - The PathArray or path string to look into
3308
+ * @param distance - The distance along the path
3309
+ * @returns The requested {x, y} point coordinates
3310
+ *
3311
+ * @example
3312
+ * ```ts
3313
+ * getPointAtLength('M0 0L100 0L100 100Z', 50)
3314
+ * // => { x: 50, y: 0 }
3315
+ * ```
3316
+ */
3317
+ const getPointAtLength = (pathInput, distance) => {
3318
+ return getPointAtNormalizedLength(normalizePath(pathInput), distance);
3319
+ };
3320
+ /**
3321
+ * Returns [x,y] coordinates of a point at a given length along a path
3322
+ * that is already normalized.
3323
+ *
3324
+ * The normalization is the expensive part of the lookup, so it is kept
3325
+ * out of this function: a caller that already has a normalized path does
3326
+ * not have to normalize it again for every point it looks up.
3327
+ *
3328
+ * @param path - The normalized PathArray to look into
3329
+ * @param distance - The distance along the path
3330
+ * @returns The requested {x, y} point coordinates
3331
+ */
3332
+ const getPointAtNormalizedLength = (path, distance) => {
3333
+ return getPointAtTable(buildPathLengthTable(path), distance);
2527
3334
  };
2528
3335
  // src/util/getSegmentAtLength.ts
2529
3336
  /**
@@ -2556,7 +3363,9 @@ const getSegmentOfPoint = (path, point) => {
2556
3363
  */
2557
3364
  const isPathArray = (path) => {
2558
3365
  return Array.isArray(path) && path.every((seg) => {
2559
- const lk = seg[0].toLowerCase();
3366
+ const command = seg?.[0];
3367
+ if (typeof command !== "string") return false;
3368
+ const lk = command.toLowerCase();
2560
3369
  return paramsCounts[lk] === seg.length - 1 && "achlmqstvz".includes(lk) && seg.slice(1).every(Number.isFinite);
2561
3370
  }) && path.length > 0;
2562
3371
  };
@@ -2577,34 +3386,268 @@ const isAbsoluteArray = (path) => {
2577
3386
  * with all segments in non-shorthand notation
2578
3387
  * with absolute values.
2579
3388
  *
2580
- * @param path - the array to be checked
2581
- * @returns true if the array is a normalized path array
3389
+ * @param path - the array to be checked
3390
+ * @returns true if the array is a normalized path array
3391
+ */
3392
+ const isNormalizedArray = (path) => {
3393
+ return isAbsoluteArray(path) && path.every(([pc]) => "ACLMQZ".includes(pc));
3394
+ };
3395
+ // src/util/isCurveArray.ts
3396
+ /**
3397
+ * Iterates an array to check if it's a `pathArray`
3398
+ * with all C (cubic bezier) segments.
3399
+ *
3400
+ * @param path the `Array` to be checked
3401
+ * @returns iteration result
3402
+ */
3403
+ const isCurveArray = (path) => {
3404
+ return isNormalizedArray(path) && path.every(([pc]) => "MC".includes(pc));
3405
+ };
3406
+ // src/util/isPointInStroke.ts
3407
+ /**
3408
+ * Checks if a given point is in the stroke of a path.
3409
+ *
3410
+ * Without a width the point has to be on the path itself, within the
3411
+ * distance epsilon of it. With a width the stroke is the band around the
3412
+ * path: the point is in the stroke when it is at most half the width away
3413
+ * from the path. The ends of an open path are treated as if the stroke had
3414
+ * round caps, so a point beyond the end of the path is in the stroke too.
3415
+ *
3416
+ * @param pathInput target path
3417
+ * @param point the given `{x,y}` point
3418
+ * @param options the options of the test
3419
+ * @returns the query result
3420
+ *
3421
+ * @example
3422
+ * ```ts
3423
+ * isPointInStroke('M0 0L100 0', { x: 50, y: 0 });
3424
+ * // => true
3425
+ * isPointInStroke('M0 0L100 0', { x: 50, y: 5 }, { width: 10 });
3426
+ * // => true
3427
+ * ```
3428
+ */
3429
+ const isPointInStroke = (pathInput, point, options) => {
3430
+ const { width = 0 } = options ?? {};
3431
+ if (typeof width !== "number" || !Number.isFinite(width) || width < 0) throw TypeError(`${error}: width must be a number greater than or equal to 0`);
3432
+ const { distance } = getPropertiesAtPoint(pathInput, point);
3433
+ if (!width) return distance < DISTANCE_EPSILON;
3434
+ return distance <= width / 2;
3435
+ };
3436
+ // src/process/flattenPath.ts
3437
+ /**
3438
+ * Returns the number of intervals a cubic segment is split into.
3439
+ *
3440
+ * The second differences of the control points bound the distance of the
3441
+ * curve to its chord, and the distance of a piece of the curve to the chord
3442
+ * of the piece falls with the square of the number of the pieces, so the
3443
+ * number of the intervals is the square root of the ratio of the bound to
3444
+ * the tolerance.
3445
+ *
3446
+ * @param coords - the coordinates of the cubic segment
3447
+ * @param tolerance - the maximum distance between the curve and its chords
3448
+ * @returns the number of intervals
3449
+ */
3450
+ const getIntervalCount = (coords, tolerance) => {
3451
+ const [x1, y1, c1x, c1y, c2x, c2y, x2, y2] = coords;
3452
+ const d1 = Math.hypot(x1 - 2 * c1x + c2x, y1 - 2 * c1y + c2y);
3453
+ const d2 = Math.hypot(c1x - 2 * c2x + x2, c1y - 2 * c2y + y2);
3454
+ const flatness = .75 * Math.max(d1, d2);
3455
+ if (flatness <= tolerance) return 1;
3456
+ return Math.ceil(Math.sqrt(flatness / tolerance));
3457
+ };
3458
+ /**
3459
+ * Flattens a path into polygons, one for every sub-path.
3460
+ *
3461
+ * The curves of the path are split into chords that stay within the
3462
+ * tolerance of the curve, and every sub-path is closed, the way a fill
3463
+ * closes an open path.
3464
+ *
3465
+ * @param path - the curve path to flatten
3466
+ * @param tolerance - the maximum distance between the curve and its chords
3467
+ * @returns the polygons of the path
3468
+ */
3469
+ const flattenPath = (path, tolerance) => {
3470
+ const polygons = [];
3471
+ let points = [];
3472
+ let current = {
3473
+ x: 0,
3474
+ y: 0
3475
+ };
3476
+ for (const segment of path) {
3477
+ if (segment[0] === "M") {
3478
+ if (points.length > 1) polygons.push(points);
3479
+ current = {
3480
+ x: segment[1],
3481
+ y: segment[2]
3482
+ };
3483
+ points = [current];
3484
+ continue;
3485
+ }
3486
+ const coords = [
3487
+ current.x,
3488
+ current.y,
3489
+ segment[1],
3490
+ segment[2],
3491
+ segment[3],
3492
+ segment[4],
3493
+ segment[5],
3494
+ segment[6]
3495
+ ];
3496
+ const count = getIntervalCount(coords, tolerance);
3497
+ for (let i = 1; i <= count; i += 1) {
3498
+ const point = getPointAtCubicSegmentLength(coords, i / count);
3499
+ points.push(point);
3500
+ }
3501
+ current = {
3502
+ x: segment[5],
3503
+ y: segment[6]
3504
+ };
3505
+ }
3506
+ if (points.length > 1) polygons.push(points);
3507
+ return polygons;
3508
+ };
3509
+ // src/math/distanceToSegment.ts
3510
+ /**
3511
+ * Returns the distance from a point to a line segment.
3512
+ *
3513
+ * The distance is the one to the segment, not to the infinite line: a point
3514
+ * beyond the end of the segment is at the distance to that end.
3515
+ *
3516
+ * @param point - the point to measure
3517
+ * @param start - the start of the segment
3518
+ * @param end - the end of the segment
3519
+ * @returns the distance from the point to the segment
3520
+ */
3521
+ const distanceToSegment = (point, start, end) => {
3522
+ const dx = end.x - start.x;
3523
+ const dy = end.y - start.y;
3524
+ const lengthSquared = dx * dx + dy * dy;
3525
+ if (lengthSquared === 0) {
3526
+ const px = point.x - start.x;
3527
+ const py = point.y - start.y;
3528
+ return Math.sqrt(px * px + py * py);
3529
+ }
3530
+ let ratio = ((point.x - start.x) * dx + (point.y - start.y) * dy) / lengthSquared;
3531
+ ratio = ratio < 0 ? 0 : ratio > 1 ? 1 : ratio;
3532
+ const px = point.x - (start.x + dx * ratio);
3533
+ const py = point.y - (start.y + dy * ratio);
3534
+ return Math.sqrt(px * px + py * py);
3535
+ };
3536
+ // src/math/pointInPolygon.ts
3537
+ /**
3538
+ * Returns the number of times a ray from a point crosses a polygon.
3539
+ *
3540
+ * The ray goes to the right, so every edge of the polygon that crosses the
3541
+ * height of the point after it is counted. The parity of the count is the
3542
+ * answer of the `evenodd` fill rule.
3543
+ *
3544
+ * @param polygon - the polygon to test
3545
+ * @param point - the point to test
3546
+ * @returns the number of crossings
3547
+ */
3548
+ const getPolygonCrossings = (polygon, point) => {
3549
+ const { x, y } = point;
3550
+ const count = polygon.length;
3551
+ let crossings = 0;
3552
+ for (let i = 0; i < count; i += 1) {
3553
+ const j = (i + 1) % count;
3554
+ const current = polygon[i];
3555
+ const next = polygon[j];
3556
+ if (current.y > y === next.y > y) continue;
3557
+ if (x < (next.x - current.x) * (y - current.y) / (next.y - current.y) + current.x) crossings += 1;
3558
+ }
3559
+ return crossings;
3560
+ };
3561
+ /**
3562
+ * Returns the winding number of a polygon around a point.
3563
+ *
3564
+ * Every edge that crosses the height of the point counts, the direction of
3565
+ * the crossing decides the sign of the count. The winding number is zero
3566
+ * outside of the polygon and it is not zero inside of it, whatever the
3567
+ * direction of the polygon is, so its sign is the direction of the shape.
3568
+ *
3569
+ * @param polygon - the polygon to test
3570
+ * @param point - the point to test
3571
+ * @returns the winding number
3572
+ */
3573
+ const getPolygonWindingNumber = (polygon, point) => {
3574
+ const { x, y } = point;
3575
+ const count = polygon.length;
3576
+ let winding = 0;
3577
+ for (let i = 0; i < count; i += 1) {
3578
+ const j = (i + 1) % count;
3579
+ const current = polygon[i];
3580
+ const next = polygon[j];
3581
+ const side = (next.x - current.x) * (y - current.y) - (next.y - current.y) * (x - current.x);
3582
+ if (current.y <= y) {
3583
+ if (next.y > y && side > 0) winding += 1;
3584
+ } else if (next.y <= y && side < 0) winding -= 1;
3585
+ }
3586
+ return winding;
3587
+ };
3588
+ /**
3589
+ * Checks if a point is on the boundary of a polygon.
3590
+ *
3591
+ * @param polygon - the polygon to test
3592
+ * @param point - the point to test
3593
+ * @param epsilon - the maximum distance to the boundary
3594
+ * @returns whether the point is on the boundary
2582
3595
  */
2583
- const isNormalizedArray = (path) => {
2584
- return isAbsoluteArray(path) && path.every(([pc]) => "ACLMQZ".includes(pc));
3596
+ const isPointOnPolygon = (polygon, point, epsilon) => {
3597
+ const count = polygon.length;
3598
+ for (let i = 0; i < count; i += 1) {
3599
+ const j = (i + 1) % count;
3600
+ if (distanceToSegment(point, polygon[i], polygon[j]) <= epsilon) return true;
3601
+ }
3602
+ return false;
2585
3603
  };
2586
- // src/util/isCurveArray.ts
3604
+ // src/util/isPointInPath.ts
2587
3605
  /**
2588
- * Iterates an array to check if it's a `pathArray`
2589
- * with all C (cubic bezier) segments.
3606
+ * The distance a point can be from the boundary of a shape and still be on it.
2590
3607
  *
2591
- * @param path the `Array` to be checked
2592
- * @returns iteration result
3608
+ * The tolerance of the flattening is the error of the approximation, not the
3609
+ * width of the boundary, so the boundary is tested with a tight distance.
2593
3610
  */
2594
- const isCurveArray = (path) => {
2595
- return isNormalizedArray(path) && path.every(([pc]) => "MC".includes(pc));
2596
- };
2597
- // src/util/isPointInStroke.ts
3611
+ const boundaryEpsilon = 1e-9;
2598
3612
  /**
2599
- * Checks if a given point is in the stroke of a path.
3613
+ * Checks if a given point is inside a path.
3614
+ *
3615
+ * The path is flattened into polygons and the point is tested against them
3616
+ * with the fill rule of the path: the `nonzero` rule counts the windings of
3617
+ * the polygons around the point, the `evenodd` rule counts the crossings of
3618
+ * the polygons with a ray from the point. A point on the boundary of the
3619
+ * shape is inside of it, the way the browser answers it.
3620
+ *
3621
+ * The curves of the path are approximated with chords that stay within the
3622
+ * tolerance of the curve, so the answer is exact except for the points that
3623
+ * are within the tolerance of the boundary of a curve.
2600
3624
  *
2601
3625
  * @param pathInput target path
2602
3626
  * @param point the given `{x,y}` point
3627
+ * @param options the options of the test
2603
3628
  * @returns the query result
3629
+ *
3630
+ * @example
3631
+ * ```ts
3632
+ * isPointInPath('M0 0L100 0L100 100L0 100Z', { x: 50, y: 50 });
3633
+ * // => true
3634
+ * ```
2604
3635
  */
2605
- const isPointInStroke = (pathInput, point) => {
2606
- const { distance } = getPropertiesAtPoint(pathInput, point);
2607
- return Math.abs(distance) < DISTANCE_EPSILON;
3636
+ const isPointInPath = (pathInput, point, options) => {
3637
+ const { fillRule = "nonzero", tolerance = .1 } = options ?? {};
3638
+ if (fillRule !== "nonzero" && fillRule !== "evenodd") throw TypeError(`${error}: fillRule must be "nonzero" or "evenodd"`);
3639
+ if (typeof tolerance !== "number" || !Number.isFinite(tolerance) || tolerance <= 0) throw TypeError(`${error}: tolerance must be a positive number`);
3640
+ const path = pathToCurve(pathInput);
3641
+ if (!path.length) return false;
3642
+ const polygons = flattenPath(path, tolerance);
3643
+ let crossings = 0;
3644
+ let winding = 0;
3645
+ for (const polygon of polygons) {
3646
+ if (isPointOnPolygon(polygon, point, boundaryEpsilon)) return true;
3647
+ crossings += getPolygonCrossings(polygon, point);
3648
+ winding += getPolygonWindingNumber(polygon, point);
3649
+ }
3650
+ return fillRule === "evenodd" ? crossings % 2 === 1 : winding !== 0;
2608
3651
  };
2609
3652
  // src/util/isPolygonArray.ts
2610
3653
  /**
@@ -2648,7 +3691,7 @@ const isValidPath = (pathString) => {
2648
3691
  const path = new PathParser(pathString);
2649
3692
  skipSpaces(path);
2650
3693
  while (path.index < path.max && !path.err.length) scanSegment(path);
2651
- return !path.err.length && "mM".includes(path.segments[0][0]);
3694
+ return !path.err.length && !!path.segments.length && "mM".includes(path.segments[0][0]);
2652
3695
  };
2653
3696
  // src/util/isMultiPath.ts
2654
3697
  /**
@@ -2662,15 +3705,14 @@ const isMultiPath = (path) => {
2662
3705
  const matches = path.match(/[Mm]/g);
2663
3706
  return matches ? matches.length > 1 : false;
2664
3707
  }
2665
- if (isPathArray(path)) {
2666
- let moveCount = 0;
2667
- for (const segment of path) if (segment[0].toUpperCase() === "M") {
2668
- moveCount++;
2669
- if (moveCount > 1) return true;
2670
- }
2671
- return false;
3708
+ if (!Array.isArray(path)) throw new TypeError(error + ": expected string or PathArray");
3709
+ if (!isPathArray(path)) return false;
3710
+ let moveCount = 0;
3711
+ for (const segment of path) if (segment[0].toUpperCase() === "M") {
3712
+ moveCount++;
3713
+ if (moveCount > 1) return true;
2672
3714
  }
2673
- throw new TypeError(error + ": expected string or PathArray");
3715
+ return false;
2674
3716
  };
2675
3717
  // src/util/isClosedPath.ts
2676
3718
  /**
@@ -2679,6 +3721,7 @@ const isMultiPath = (path) => {
2679
3721
  * @returns true if the path is closed
2680
3722
  */
2681
3723
  const isClosedPath = (path) => {
3724
+ if (!path.length) return false;
2682
3725
  return path[path.length - 1][0].toUpperCase() === "Z";
2683
3726
  };
2684
3727
  // src/util/shapeParams.ts
@@ -2770,15 +3813,17 @@ const getPolyPath = (attr) => {
2770
3813
  const pathArray = [];
2771
3814
  const points = (attr.points || "").trim().split(/[\s|,]/).map((a) => +a);
2772
3815
  let index = 0;
2773
- while (index < points.length) {
2774
- pathArray.push([
2775
- index ? "L" : "M",
2776
- points[index],
2777
- points[index + 1]
3816
+ while (index + 1 < points.length) {
3817
+ const x = points[index];
3818
+ const y = points[index + 1];
3819
+ if (Number.isFinite(x) && Number.isFinite(y)) pathArray.push([
3820
+ pathArray.length ? "L" : "M",
3821
+ x,
3822
+ y
2778
3823
  ]);
2779
3824
  index += 2;
2780
3825
  }
2781
- return attr.type === "polygon" ? [...pathArray, ["z"]] : pathArray;
3826
+ return attr.type === "polygon" && pathArray.length ? [...pathArray, ["z"]] : pathArray;
2782
3827
  };
2783
3828
  /**
2784
3829
  * Returns a new PathArray from circle attributes.
@@ -2880,6 +3925,12 @@ const getEllipsePath = (attr) => {
2880
3925
  /**
2881
3926
  * Returns a new PathArray from rect attributes.
2882
3927
  *
3928
+ * The corners of a rounded rectangle are elliptical arcs, one for every
3929
+ * corner, and the radius of the corners follows the rules of the spec: a
3930
+ * missing radius takes the value of the other one, an explicit zero
3931
+ * disables the rounding and a radius bigger than half of the size of the
3932
+ * rectangle is clamped to it.
3933
+ *
2883
3934
  * @param attr - Object with x, y, width, height, and optional rx/ry
2884
3935
  * @returns A new PathArray from `<rect>` attributes
2885
3936
  *
@@ -2894,11 +3945,13 @@ const getRectanglePath = (attr) => {
2894
3945
  const y = +attr.y || 0;
2895
3946
  const w = +attr.width;
2896
3947
  const h = +attr.height;
2897
- let rx = +(attr.rx || 0);
2898
- let ry = +(attr.ry || rx);
2899
- if (rx || ry) {
2900
- if (rx * 2 > w) rx -= (rx * 2 - w) / 2;
2901
- if (ry * 2 > h) ry -= (ry * 2 - h) / 2;
3948
+ const rxValue = attr.rx === void 0 || attr.rx === null ? void 0 : +attr.rx;
3949
+ const ryValue = attr.ry === void 0 || attr.ry === null ? void 0 : +attr.ry;
3950
+ let rx = rxValue ?? ryValue ?? 0;
3951
+ let ry = ryValue ?? rxValue ?? 0;
3952
+ if (rx > 0 && ry > 0) {
3953
+ rx = Math.min(rx, w / 2);
3954
+ ry = Math.min(ry, h / 2);
2902
3955
  return [
2903
3956
  [
2904
3957
  "M",
@@ -2907,36 +3960,49 @@ const getRectanglePath = (attr) => {
2907
3960
  ],
2908
3961
  ["h", w - rx * 2],
2909
3962
  [
2910
- "s",
3963
+ "a",
2911
3964
  rx,
3965
+ ry,
2912
3966
  0,
3967
+ 0,
3968
+ 1,
2913
3969
  rx,
2914
3970
  ry
2915
3971
  ],
2916
3972
  ["v", h - ry * 2],
2917
3973
  [
2918
- "s",
2919
- 0,
3974
+ "a",
3975
+ rx,
2920
3976
  ry,
3977
+ 0,
3978
+ 0,
3979
+ 1,
2921
3980
  -rx,
2922
3981
  ry
2923
3982
  ],
2924
3983
  ["h", -w + rx * 2],
2925
3984
  [
2926
- "s",
2927
- -rx,
3985
+ "a",
3986
+ rx,
3987
+ ry,
2928
3988
  0,
3989
+ 0,
3990
+ 1,
2929
3991
  -rx,
2930
3992
  -ry
2931
3993
  ],
2932
3994
  ["v", -h + ry * 2],
2933
3995
  [
2934
- "s",
3996
+ "a",
3997
+ rx,
3998
+ ry,
3999
+ 0,
2935
4000
  0,
2936
- -ry,
4001
+ 1,
2937
4002
  rx,
2938
4003
  -ry
2939
- ]
4004
+ ],
4005
+ ["Z"]
2940
4006
  ];
2941
4007
  }
2942
4008
  return [
@@ -3051,6 +4117,418 @@ const shapeToPath = (element, replace, ownerDocument) => {
3051
4117
  }
3052
4118
  return false;
3053
4119
  };
4120
+ // src/process/offsetNodes.ts
4121
+ /**
4122
+ * Returns the sampled points of the drawable segments of a sub-path.
4123
+ *
4124
+ * A line gives its two end points, a curve gives `steps` samples spread
4125
+ * evenly over its length. The tangent of every sample is the tangent of the
4126
+ * path at that point, so the normal of the sample is the direction the path
4127
+ * is offset to.
4128
+ *
4129
+ * The first point of a segment is a corner when the segment follows another
4130
+ * one, and the closing segment of a closed sub-path ends with a corner that
4131
+ * joins the last segment to the first one.
4132
+ *
4133
+ * @param measures - the measured segments of the sub-path
4134
+ * @param steps - the number of the intervals a curve is sampled with
4135
+ * @returns the sampled points of the sub-path
4136
+ */
4137
+ const getOffsetNodes = (measures, steps) => {
4138
+ const nodes = [];
4139
+ for (const measure of measures) {
4140
+ const command = measure.geometry[0];
4141
+ if (command === "M") continue;
4142
+ if (measure.length <= 0) continue;
4143
+ const isFirst = nodes.length === 0;
4144
+ if (command === "L" || command === "Z") {
4145
+ const dx = measure.endX - measure.startX;
4146
+ const dy = measure.endY - measure.startY;
4147
+ const length = Math.sqrt(dx * dx + dy * dy);
4148
+ const tx = dx / length;
4149
+ const ty = dy / length;
4150
+ nodes.push({
4151
+ x: measure.startX,
4152
+ y: measure.startY,
4153
+ tx,
4154
+ ty,
4155
+ corner: !isFirst
4156
+ });
4157
+ nodes.push({
4158
+ x: measure.endX,
4159
+ y: measure.endY,
4160
+ tx,
4161
+ ty,
4162
+ corner: false
4163
+ });
4164
+ continue;
4165
+ }
4166
+ for (let i = 0; i <= steps; i += 1) {
4167
+ const frame = getSegmentFrame(measure.geometry, measure.startX, measure.startY, measure.endX, measure.endY, measure.length * i / steps, measure.length);
4168
+ nodes.push({
4169
+ x: frame.point.x,
4170
+ y: frame.point.y,
4171
+ tx: frame.tangent.x,
4172
+ ty: frame.tangent.y,
4173
+ corner: !isFirst && i === 0
4174
+ });
4175
+ }
4176
+ }
4177
+ const last = measures[measures.length - 1];
4178
+ if (nodes.length && last && last.geometry[0] === "Z") {
4179
+ const first = nodes[0];
4180
+ nodes.push({
4181
+ x: first.x,
4182
+ y: first.y,
4183
+ tx: first.tx,
4184
+ ty: first.ty,
4185
+ corner: true
4186
+ });
4187
+ }
4188
+ return nodes;
4189
+ };
4190
+ // src/process/offsetJoin.ts
4191
+ /**
4192
+ * The angle of an arc of a round join or a round cap, in radians.
4193
+ *
4194
+ * The arcs are emitted as straight lines, and the smaller the angle the
4195
+ * closer the result is to the arc it stands for.
4196
+ */
4197
+ const arcStep = Math.PI / 8;
4198
+ /**
4199
+ * Returns the signed angle between two directions, in radians.
4200
+ *
4201
+ * The angle is the turn of the path at a corner: it is positive when the
4202
+ * path turns towards the positive angle direction, and it is in the `-PI` to
4203
+ * `PI` range.
4204
+ *
4205
+ * @param from - the direction the path comes from
4206
+ * @param to - the direction the path goes to
4207
+ * @returns the signed angle between the two directions
4208
+ */
4209
+ const signedTurn = (from, to) => {
4210
+ const dot = from.tx * to.tx + from.ty * to.ty;
4211
+ const cross = from.tx * to.ty - from.ty * to.tx;
4212
+ return Math.atan2(cross, dot);
4213
+ };
4214
+ /**
4215
+ * Returns the intersection of two lines, if they have one.
4216
+ *
4217
+ * @param x1 - the X coordinate of the first point
4218
+ * @param y1 - the Y coordinate of the first point
4219
+ * @param dx1 - the X component of the direction of the first line
4220
+ * @param dy1 - the Y component of the direction of the first line
4221
+ * @param x2 - the X coordinate of the second point
4222
+ * @param y2 - the Y coordinate of the second point
4223
+ * @param dx2 - the X component of the direction of the second line
4224
+ * @param dy2 - the Y component of the direction of the second line
4225
+ * @returns the intersection of the two lines, or `null`
4226
+ */
4227
+ const intersectLines = (x1, y1, dx1, dy1, x2, y2, dx2, dy2) => {
4228
+ const denominator = dx1 * dy2 - dy1 * dx2;
4229
+ if (Math.abs(denominator) < 1e-12) return null;
4230
+ const ratio = ((x2 - x1) * dy2 - (y2 - y1) * dx2) / denominator;
4231
+ return [x1 + dx1 * ratio, y1 + dy1 * ratio];
4232
+ };
4233
+ /**
4234
+ * Returns the points of a join between two offset lines.
4235
+ *
4236
+ * The join is placed on the outer side of a corner, where the two offset
4237
+ * lines do not cross: the `miter` join is the intersection of the two
4238
+ * lines, the `bevel` join is the straight line between the two offset
4239
+ * points and the `round` join is an arc of the offset radius around the
4240
+ * corner.
4241
+ *
4242
+ * @param cornerX - the X coordinate of the corner of the path
4243
+ * @param cornerY - the Y coordinate of the corner of the path
4244
+ * @param from - the end of the incoming offset line
4245
+ * @param to - the start of the outgoing offset line
4246
+ * @param distance - the offset distance
4247
+ * @param join - the join type
4248
+ * @param miterLimit - the ratio of the miter length to the offset distance
4249
+ * @returns the points of the join
4250
+ */
4251
+ const getJoinPoints = (cornerX, cornerY, from, to, distance, join, miterLimit) => {
4252
+ if (join === "round") {
4253
+ const turn = signedTurn(from, to);
4254
+ const startAngle = Math.atan2(from.y - cornerY, from.x - cornerX);
4255
+ const steps = Math.max(1, Math.ceil(Math.abs(turn) / arcStep));
4256
+ const points = [];
4257
+ for (let i = 1; i < steps; i += 1) {
4258
+ const angle = startAngle + turn * i / steps;
4259
+ points.push([cornerX + Math.cos(angle) * distance, cornerY + Math.sin(angle) * distance]);
4260
+ }
4261
+ return points;
4262
+ }
4263
+ if (join === "miter") {
4264
+ const miter = intersectLines(from.x, from.y, from.tx, from.ty, to.x, to.y, to.tx, to.ty);
4265
+ if (miter) {
4266
+ if (Math.hypot(miter[0] - cornerX, miter[1] - cornerY) <= miterLimit * distance) return [miter];
4267
+ }
4268
+ }
4269
+ return [];
4270
+ };
4271
+ /**
4272
+ * Returns the points of a cap at the end of an open path.
4273
+ *
4274
+ * The `butt` cap is the straight line between the two offset points, the
4275
+ * `square` cap extends the path by the offset distance and the `round` cap
4276
+ * is a half circle of the offset radius around the end of the path.
4277
+ *
4278
+ * @param centerX - the X coordinate of the end of the path
4279
+ * @param centerY - the Y coordinate of the end of the path
4280
+ * @param from - the first offset point of the cap
4281
+ * @param to - the last offset point of the cap
4282
+ * @param distance - the offset distance
4283
+ * @param cap - the cap type
4284
+ * @param extensionX - the X component of the direction the cap extends to
4285
+ * @param extensionY - the Y component of the direction the cap extends to
4286
+ * @returns the points of the cap
4287
+ */
4288
+ const getCapPoints = (centerX, centerY, from, to, distance, cap, extensionX, extensionY) => {
4289
+ if (cap === "butt") return [];
4290
+ if (cap === "square") return [[from[0] + extensionX * distance, from[1] + extensionY * distance], [to[0] + extensionX * distance, to[1] + extensionY * distance]];
4291
+ const startAngle = Math.atan2(from[1] - centerY, from[0] - centerX);
4292
+ const sweep = -Math.PI;
4293
+ const steps = Math.max(1, Math.ceil(Math.abs(sweep) / arcStep));
4294
+ const points = [];
4295
+ for (let i = 1; i < steps; i += 1) {
4296
+ const angle = startAngle + sweep * i / steps;
4297
+ points.push([centerX + Math.cos(angle) * distance, centerY + Math.sin(angle) * distance]);
4298
+ }
4299
+ return points;
4300
+ };
4301
+ // src/process/offsetPath.ts
4302
+ /** The sides an offset can be created on. */
4303
+ const sides = [
4304
+ "left",
4305
+ "right",
4306
+ "both"
4307
+ ];
4308
+ /** The join types of an offset. */
4309
+ const joins = [
4310
+ "round",
4311
+ "miter",
4312
+ "bevel"
4313
+ ];
4314
+ /** The cap types of an offset. */
4315
+ const caps = [
4316
+ "butt",
4317
+ "square",
4318
+ "round"
4319
+ ];
4320
+ /**
4321
+ * Returns the options of the path offsetting, with the defaults applied.
4322
+ *
4323
+ * @param options - the options of the offset
4324
+ * @returns the resolved options
4325
+ */
4326
+ const resolveOptions = (options) => {
4327
+ const { side = "left", join = "miter", miterLimit = 4, cap = "butt", steps = 16, precision = 4 } = options;
4328
+ if (!sides.includes(side)) throw TypeError(`${error}: side must be one of "left", "right" or "both"`);
4329
+ if (!joins.includes(join)) throw TypeError(`${error}: join must be one of "round", "miter" or "bevel"`);
4330
+ if (!caps.includes(cap)) throw TypeError(`${error}: cap must be one of "butt", "square" or "round"`);
4331
+ if (typeof miterLimit !== "number" || !Number.isFinite(miterLimit) || miterLimit <= 0) throw TypeError(`${error}: miterLimit must be a positive number`);
4332
+ if (!Number.isInteger(steps) || steps < 1) throw TypeError(`${error}: steps must be an integer greater than 0`);
4333
+ if (!Number.isInteger(precision) || precision < 0) throw TypeError(`${error}: precision must be an integer of 0 or more`);
4334
+ return {
4335
+ side,
4336
+ join,
4337
+ miterLimit,
4338
+ cap,
4339
+ steps,
4340
+ precision
4341
+ };
4342
+ };
4343
+ /**
4344
+ * Groups the measured segments of a path into its sub-paths.
4345
+ *
4346
+ * @param measures - the measured segments of the path
4347
+ * @returns the measured segments of every sub-path
4348
+ */
4349
+ const groupSubPaths = (measures) => {
4350
+ const groups = [];
4351
+ let group = [];
4352
+ for (const measure of measures) {
4353
+ if (measure.geometry[0] === "M" && group.length) {
4354
+ groups.push(group);
4355
+ group = [];
4356
+ }
4357
+ group.push(measure);
4358
+ }
4359
+ if (group.length) groups.push(group);
4360
+ return groups;
4361
+ };
4362
+ /**
4363
+ * Returns the offset polyline of one side of a sub-path.
4364
+ *
4365
+ * Every node is shifted along the normal of the path. At a corner the two
4366
+ * offset lines meet: on the outer side of the turn the join is applied, and
4367
+ * on the inner side of the turn the offset lines cross before the corner, so
4368
+ * the curve is trimmed at their intersection.
4369
+ *
4370
+ * @param nodes - the sampled points of the sub-path
4371
+ * @param side - `1` for the left side of the path, `-1` for the right side
4372
+ * @param distance - the offset distance
4373
+ * @param options - the resolved options of the offset
4374
+ * @param closed - whether the sub-path is closed
4375
+ * @returns the points of the offset polyline
4376
+ */
4377
+ const buildSidePolyline = (nodes, side, distance, options, closed) => {
4378
+ const { join, miterLimit } = options;
4379
+ const offsets = nodes.map((node) => ({
4380
+ x: node.x - side * node.ty * distance,
4381
+ y: node.y + side * node.tx * distance,
4382
+ tx: node.tx,
4383
+ ty: node.ty
4384
+ }));
4385
+ const points = [[offsets[0].x, offsets[0].y]];
4386
+ for (let i = 1; i < offsets.length; i += 1) {
4387
+ const from = offsets[i - 1];
4388
+ const to = offsets[i];
4389
+ let trimmed = false;
4390
+ if (nodes[i].corner) {
4391
+ const turn = signedTurn(from, to);
4392
+ if (Math.abs(turn) > 1e-9) {
4393
+ if (side * turn < 0) points.push(...getJoinPoints(nodes[i].x, nodes[i].y, from, to, distance, join, miterLimit));
4394
+ else {
4395
+ const intersection = intersectLines(from.x, from.y, from.tx, from.ty, to.x, to.y, to.tx, to.ty);
4396
+ if (intersection) {
4397
+ points[points.length - 1] = intersection;
4398
+ if (closed && i === offsets.length - 1) points[0] = intersection;
4399
+ trimmed = true;
4400
+ }
4401
+ }
4402
+ }
4403
+ }
4404
+ if (!trimmed) {
4405
+ const point = [to.x, to.y];
4406
+ if (!samePoint(points[points.length - 1], point)) points.push(point);
4407
+ }
4408
+ }
4409
+ return points;
4410
+ };
4411
+ /**
4412
+ * Returns whether two points are the same point.
4413
+ *
4414
+ * @param a - the first point
4415
+ * @param b - the second point
4416
+ * @returns whether the points are the same
4417
+ */
4418
+ const samePoint = (a, b) => Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9;
4419
+ /**
4420
+ * Returns a coordinate of the result, rounded and without a negative zero.
4421
+ *
4422
+ * @param value - the coordinate
4423
+ * @param precision - the number of the decimals of the result
4424
+ * @returns the rounded coordinate
4425
+ */
4426
+ const roundCoordinate = (value, precision) => cleanZero(roundTo(value, precision));
4427
+ /**
4428
+ * Returns the segments of an offset polyline.
4429
+ *
4430
+ * @param points - the points of the polyline
4431
+ * @param closed - whether the polyline is closed
4432
+ * @param precision - the number of the decimals of the result
4433
+ * @returns the segments of the polyline
4434
+ */
4435
+ const toSegments$1 = (points, closed, precision) => {
4436
+ const last = points[points.length - 1];
4437
+ const list = closed && points.length > 1 && samePoint(points[0], last) ? points.slice(0, -1) : points;
4438
+ const segments = [];
4439
+ if (!list.length) return segments;
4440
+ segments.push([
4441
+ "M",
4442
+ roundCoordinate(list[0][0], precision),
4443
+ roundCoordinate(list[0][1], precision)
4444
+ ]);
4445
+ for (let i = 1; i < list.length; i += 1) segments.push([
4446
+ "L",
4447
+ roundCoordinate(list[i][0], precision),
4448
+ roundCoordinate(list[i][1], precision)
4449
+ ]);
4450
+ if (closed) segments.push(["Z"]);
4451
+ return segments;
4452
+ };
4453
+ /**
4454
+ * Offsets a path along its normals.
4455
+ *
4456
+ * The path is sampled along its length, every sample is shifted along the
4457
+ * normal of the path and the result is a path of straight lines. The
4458
+ * corners of the path are joined with the `join` option, and the ends of an
4459
+ * open path are capped with the `cap` option.
4460
+ *
4461
+ * The `side` option is literal: the left side is the left normal of the
4462
+ * direction of travel, the same normal `getPropertiesAtLength()` returns.
4463
+ * The `both` side is the outline of the stroke, the band between the two
4464
+ * sides of the path.
4465
+ *
4466
+ * The offset is not cleaned up: an offset distance larger than the local
4467
+ * radius of curvature of the path produces a self-crossing curve.
4468
+ *
4469
+ * @param pathInput - the path string or `PathArray`
4470
+ * @param distance - the offset distance
4471
+ * @param options - the options of the offset
4472
+ * @returns the offset path
4473
+ *
4474
+ * @example
4475
+ * ```ts
4476
+ * offsetPath('M0 0L100 0', 10)
4477
+ * // => [['M', 0, 10], ['L', 100, 10]]
4478
+ * ```
4479
+ */
4480
+ const offsetPath = (pathInput, distance, options) => {
4481
+ if (typeof distance !== "number" || !Number.isFinite(distance)) throw TypeError(`${error}: distance must be a number`);
4482
+ if (distance < 0) throw TypeError(`${error}: distance must be a positive number`);
4483
+ const resolved = resolveOptions(options ?? {});
4484
+ if (distance === 0) return parsePathString(pathInput);
4485
+ const measures = measureSegments(pathInput);
4486
+ const groups = groupSubPaths(measures);
4487
+ const result = [];
4488
+ for (const group of groups) {
4489
+ const nodes = getOffsetNodes(group, resolved.steps);
4490
+ const last = group[group.length - 1];
4491
+ const closed = Boolean(last && last.geometry[0] === "Z");
4492
+ if (!nodes.length) {
4493
+ const first = group[0];
4494
+ result.push([
4495
+ "M",
4496
+ first.endX,
4497
+ first.endY
4498
+ ]);
4499
+ continue;
4500
+ }
4501
+ if (resolved.side === "both") {
4502
+ const left = buildSidePolyline(nodes, 1, distance, resolved, closed);
4503
+ const right = buildSidePolyline(nodes, -1, distance, resolved, closed);
4504
+ if (closed) {
4505
+ const leftArea = Math.abs(polygonArea(left));
4506
+ const rightArea = Math.abs(polygonArea(right));
4507
+ const outer = leftArea >= rightArea ? left : right;
4508
+ const inner = leftArea >= rightArea ? right : left;
4509
+ result.push(...toSegments$1(outer, true, resolved.precision));
4510
+ result.push(...toSegments$1([...inner].reverse(), true, resolved.precision));
4511
+ continue;
4512
+ }
4513
+ const start = nodes[0];
4514
+ const end = nodes[nodes.length - 1];
4515
+ const endCap = getCapPoints(end.x, end.y, left[left.length - 1], right[right.length - 1], distance, resolved.cap, end.tx, end.ty);
4516
+ const startCap = getCapPoints(start.x, start.y, right[0], left[0], distance, resolved.cap, -start.tx, -start.ty);
4517
+ const ring = [
4518
+ ...left,
4519
+ ...endCap,
4520
+ ...[...right].reverse(),
4521
+ ...startCap
4522
+ ];
4523
+ result.push(...toSegments$1(ring, true, resolved.precision));
4524
+ continue;
4525
+ }
4526
+ const side = resolved.side === "left" ? 1 : -1;
4527
+ const polyline = buildSidePolyline(nodes, side, distance, resolved, closed);
4528
+ result.push(...toSegments$1(polyline, closed, resolved.precision));
4529
+ }
4530
+ return result;
4531
+ };
3054
4532
  // src/process/shortenSegment.ts
3055
4533
  /**
3056
4534
  * Shorten a single segment of a `pathArray` object.
@@ -3106,8 +4584,26 @@ const shortenSegment = (segment, normalSegment, params, prevCommand) => {
3106
4584
  * @returns The rounded segment
3107
4585
  */
3108
4586
  const roundSegment = (segment, roundOption) => {
3109
- const values = segment.slice(1).map((n) => roundTo(n, roundOption));
3110
- return [segment[0]].concat(values);
4587
+ const result = new Array(segment.length);
4588
+ for (let i = 0; i < segment.length; i += 1) result[i] = i === 0 ? segment[0] : roundTo(segment[i], roundOption);
4589
+ return result;
4590
+ };
4591
+ // src/process/segmentStringLength.ts
4592
+ /**
4593
+ * Returns the length of the string representation of a path segment.
4594
+ *
4595
+ * The string of a segment is its command followed by its values, without a
4596
+ * separator, so its length is the length of the command plus the length of
4597
+ * every value. The string itself is not needed to know its length, so it is
4598
+ * not built.
4599
+ *
4600
+ * @param segment - The path segment to measure
4601
+ * @returns The length of the string of the segment
4602
+ */
4603
+ const segmentStringLength = (segment) => {
4604
+ let length = String(segment[0]).length;
4605
+ for (let i = 1; i < segment.length; i += 1) length += String(segment[i]).length;
4606
+ return length;
3111
4607
  };
3112
4608
  // src/process/optimizePath.ts
3113
4609
  /**
@@ -3122,7 +4618,7 @@ const roundSegment = (segment, roundOption) => {
3122
4618
  * @example
3123
4619
  * ```ts
3124
4620
  * optimizePath('M10 10L10 10L90 90', 2)
3125
- * // => [['M', 10, 10], ['l', 0, 0], ['l', 80, 80]]
4621
+ * // => [['M', 10, 10], ['v', 0], ['l', 80, 80]]
3126
4622
  * ```
3127
4623
  */
3128
4624
  const optimizePath = (pathInput, roundOption) => {
@@ -3143,11 +4639,10 @@ const optimizePath = (pathInput, roundOption) => {
3143
4639
  if (i) {
3144
4640
  const shortSegment = shortenSegment(seg, normalizedSegment, optimParams, prevCommand);
3145
4641
  const absSegment = roundSegment(shortSegment, round);
3146
- const absString = absSegment.join("");
4642
+ const absLength = segmentStringLength(absSegment);
3147
4643
  const relativeSegment = relativizeSegment(shortSegment, i, lastX, lastY);
3148
4644
  const relSegment = roundSegment(relativeSegment, round);
3149
- const relString = relSegment.join("");
3150
- result = absString.length < relString.length ? absSegment : relSegment;
4645
+ result = absLength < segmentStringLength(relSegment) ? absSegment : relSegment;
3151
4646
  }
3152
4647
  const seglen = normalizedSegment.length;
3153
4648
  optimParams.x1 = +normalizedSegment[seglen - 2];
@@ -3162,6 +4657,31 @@ const optimizePath = (pathInput, roundOption) => {
3162
4657
  return result;
3163
4658
  });
3164
4659
  };
4660
+ // src/process/joinPath.ts
4661
+ /**
4662
+ * Joins two paths into a single path with two sub-paths.
4663
+ *
4664
+ * Both paths have to be valid paths, so they begin with a moveto command,
4665
+ * and the result holds absolute values.
4666
+ *
4667
+ * @param pathA - the first path string or `PathArray`
4668
+ * @param pathB - the second path string or `PathArray`
4669
+ * @returns the joined path
4670
+ *
4671
+ * @example
4672
+ * ```ts
4673
+ * joinPath('M0 0L100 0', 'M0 100L100 100')
4674
+ * // => [
4675
+ * // ['M', 0, 0], ['L', 100, 0],
4676
+ * // ['M', 0, 100], ['L', 100, 100]
4677
+ * // ]
4678
+ * ```
4679
+ */
4680
+ const joinPath = (pathA, pathB) => {
4681
+ const first = pathToAbsolute(parsePathString(pathA));
4682
+ const second = pathToAbsolute(parsePathString(pathB));
4683
+ return [...first, ...second];
4684
+ };
3165
4685
  // src/process/reversePath.ts
3166
4686
  /**
3167
4687
  * Reverses the segments of a single sub-path and returns a new PathArray
@@ -3170,7 +4690,7 @@ const optimizePath = (pathInput, roundOption) => {
3170
4690
  * @param absolutePath - The absolute PathArray of a single sub-path
3171
4691
  * @returns The reversed PathArray
3172
4692
  */
3173
- const reverseSubPath = (absolutePath) => {
4693
+ const reverseSubPath$1 = (absolutePath) => {
3174
4694
  const normalizedPath = normalizePath(absolutePath);
3175
4695
  const pLen = absolutePath.length;
3176
4696
  const isClosed = absolutePath[pLen - 1][0] === "Z";
@@ -3273,20 +4793,22 @@ const reverseSubPath = (absolutePath) => {
3273
4793
  y
3274
4794
  ];
3275
4795
  break;
3276
- case "T":
3277
- if (prevCommand && "QT".includes(prevCommand) && (!nextSeg || nextCommand !== "T")) result = [
3278
- "Q",
3279
- normalizedSegment[1],
3280
- normalizedSegment[2],
4796
+ case "T": {
4797
+ const prevIsQuad = Boolean(prevCommand && "QT".includes(prevCommand));
4798
+ if (Boolean(nextSeg && nextCommand === "T") || !prevIsQuad && !Boolean(nextSeg && nextCommand === "Q")) result = [
4799
+ pathCommand,
3281
4800
  x,
3282
4801
  y
3283
4802
  ];
3284
4803
  else result = [
3285
- pathCommand,
4804
+ "Q",
4805
+ normalizedSegment[1],
4806
+ normalizedSegment[2],
3286
4807
  x,
3287
4808
  y
3288
4809
  ];
3289
4810
  break;
4811
+ }
3290
4812
  case "Z":
3291
4813
  result = [
3292
4814
  "M",
@@ -3320,7 +4842,7 @@ const reverseSubPath = (absolutePath) => {
3320
4842
  * @example
3321
4843
  * ```ts
3322
4844
  * reversePath([['M', 0, 0], ['L', 100, 0], ['L', 100, 100], ['L', 0, 100], ['Z']])
3323
- * // => [['M', 0, 100], ['L', 0, 0], ['L', 100, 0], ['L', 100, 100], ['Z']]
4845
+ * // => [['M', 0, 100], ['L', 100, 100], ['L', 100, 0], ['L', 0, 0], ['Z']]
3324
4846
  * ```
3325
4847
  */
3326
4848
  const reversePath = (pathInput) => {
@@ -3335,7 +4857,7 @@ const reversePath = (pathInput) => {
3335
4857
  subPath.push(segment);
3336
4858
  }
3337
4859
  if (subPath.length) subPaths.push(subPath);
3338
- const reversed = subPaths.map((path) => reverseSubPath(path));
4860
+ const reversed = subPaths.map((path) => reverseSubPath$1(path));
3339
4861
  return reversed.length === 1 ? reversed[0] : reversed.flat();
3340
4862
  };
3341
4863
  // src/process/splitPath.ts
@@ -3345,6 +4867,9 @@ const reversePath = (pathInput) => {
3345
4867
  * In the process, values are converted to absolute
3346
4868
  * for visual consistency.
3347
4869
  *
4870
+ * A path must begin with a moveto command, so a path that does not is
4871
+ * rejected by the parser.
4872
+ *
3348
4873
  * @param pathInput - The source path string or PathArray
3349
4874
  * @returns An array of sub-path PathArrays
3350
4875
  *
@@ -3359,14 +4884,14 @@ const reversePath = (pathInput) => {
3359
4884
  */
3360
4885
  const splitPath = (pathInput) => {
3361
4886
  const composite = [];
3362
- const parsedPath = parsePathString(pathInput);
4887
+ const segments = parsePathString(pathInput);
3363
4888
  let path = [];
3364
4889
  let pi = -1;
3365
4890
  let x = 0;
3366
4891
  let y = 0;
3367
4892
  let mx = 0;
3368
4893
  let my = 0;
3369
- iterate(parsedPath, (seg, _, prevX, prevY) => {
4894
+ iterate(segments, (seg, _index, prevX, prevY) => {
3370
4895
  const cmd = seg[0];
3371
4896
  const absCommand = cmd.toUpperCase();
3372
4897
  const isRelative = cmd === cmd.toLowerCase();
@@ -3378,11 +4903,11 @@ const splitPath = (pathInput) => {
3378
4903
  y += isRelative ? prevY : 0;
3379
4904
  mx = x;
3380
4905
  my = y;
3381
- path = [isRelative ? [
3382
- absCommand,
3383
- mx,
3384
- my
3385
- ] : seg];
4906
+ path = [[
4907
+ "M",
4908
+ x,
4909
+ y
4910
+ ]];
3386
4911
  } else {
3387
4912
  if (absCommand === "Z") {
3388
4913
  x = mx;
@@ -3398,29 +4923,55 @@ const splitPath = (pathInput) => {
3398
4923
  x += isRelative ? prevX : 0;
3399
4924
  y += isRelative ? prevY : 0;
3400
4925
  }
3401
- path.push(seg);
4926
+ path.push(absolutizeSegment(seg, _index, prevX, prevY));
3402
4927
  }
3403
4928
  composite[pi] = path;
3404
4929
  });
3405
4930
  return composite;
3406
4931
  };
4932
+ // src/process/reverseSubPath.ts
4933
+ /**
4934
+ * Reverses the sub-path at a given index of a path.
4935
+ *
4936
+ * The other sub-paths are left untouched, and the result holds absolute
4937
+ * values.
4938
+ *
4939
+ * @param pathInput - the path string or `PathArray`
4940
+ * @param index - the zero-based index of the sub-path to reverse
4941
+ * @returns the path with the sub-path reversed
4942
+ *
4943
+ * @example
4944
+ * ```ts
4945
+ * reverseSubPath('M0 0L100 0ZM0 100L100 100', 1)
4946
+ * // => [
4947
+ * // ['M', 0, 0], ['L', 100, 0], ['Z'],
4948
+ * // ['M', 100, 100], ['L', 0, 100]
4949
+ * // ]
4950
+ * ```
4951
+ */
4952
+ const reverseSubPath = (pathInput, index) => {
4953
+ const subPaths = splitPath(pathInput);
4954
+ if (!Number.isInteger(index) || index < 0 || index >= subPaths.length) throw TypeError(`${error}: index must be a number within the range of the sub-paths`);
4955
+ const reversed = reversePath(subPaths[index]);
4956
+ return [
4957
+ ...subPaths.slice(0, index),
4958
+ reversed,
4959
+ ...subPaths.slice(index + 1)
4960
+ ].flat();
4961
+ };
3407
4962
  // src/process/getSVGMatrix.ts
3408
4963
  /**
3409
4964
  * Returns a transformation matrix to apply to `<path>` elements.
3410
4965
  *
3411
- * @see TransformObjectValues
4966
+ * @see TransformObject
3412
4967
  *
3413
4968
  * @param transform the `transformObject`
3414
4969
  * @returns a new transformation matrix
3415
4970
  */
3416
4971
  const getSVGMatrix = (transform) => {
3417
4972
  let matrix = new CSSMatrix();
3418
- const { origin } = transform;
3419
- const [originX, originY] = origin;
3420
- const { translate } = transform;
3421
- const { rotate } = transform;
3422
- const { skew } = transform;
3423
- const { scale } = transform;
4973
+ const [originX, originY] = transform.origin ?? defaultOptions.origin;
4974
+ const { translate, rotate, skew, scale } = transform;
3424
4975
  if (Array.isArray(translate) && translate.length >= 2 && translate.every((x) => !Number.isNaN(+x)) && translate.some((x) => x !== 0)) matrix = matrix.translate(...translate);
3425
4976
  else if (typeof translate === "number" && !Number.isNaN(translate)) matrix = matrix.translate(translate);
3426
4977
  if (rotate || skew || scale) {
@@ -3491,7 +5042,10 @@ const projection2d = (m, point2D, origin) => {
3491
5042
  const relativePositionX = x - originX;
3492
5043
  const relativePositionY = y - originY;
3493
5044
  const relativePositionZ = z - originZ;
3494
- return [relativePositionX * (Math.abs(originZ) / Math.abs(relativePositionZ) || 1) + originX, relativePositionY * (Math.abs(originZ) / Math.abs(relativePositionZ) || 1) + originY];
5045
+ const numerator = Math.abs(originZ);
5046
+ const denominator = Math.abs(relativePositionZ);
5047
+ const factor = numerator === 0 || denominator === 0 ? 1 : numerator / denominator;
5048
+ return [relativePositionX * factor + originX, relativePositionY * factor + originY];
3495
5049
  };
3496
5050
  // src/process/transformPath.ts
3497
5051
  /**
@@ -3525,7 +5079,7 @@ const transform2D = (path, a, b, c, d, e, f, originX, originY) => {
3525
5079
  const commandCode = pathCommand.charCodeAt(0);
3526
5080
  const isRelative = commandCode >= 97;
3527
5081
  const absCommand = isRelative ? String.fromCharCode(commandCode - 32) : pathCommand;
3528
- const outCommand = i === 0 && isRelative ? pathCommand : absCommand;
5082
+ const outCommand = absCommand;
3529
5083
  if (absCommand === "Z") {
3530
5084
  result.push(["Z"]);
3531
5085
  ox = omx;
@@ -3662,16 +5216,18 @@ const transform2D = (path, a, b, c, d, e, f, originX, originY) => {
3662
5216
  * @example
3663
5217
  * ```ts
3664
5218
  * transformPath('M0 0L100 0L100 100L0 100Z', { translate: [10, 20], scale: 2 })
3665
- * // => [['M', 10, 20], ['L', 210, 20], ['L', 210, 220], ['L', 10, 220], ['Z']]
5219
+ * // => [['M', 10, 20], ['H', 210], ['V', 220], ['H', 10], ['Z']]
3666
5220
  * ```
3667
5221
  */
3668
5222
  const transformPath = (pathInput, transform) => {
3669
5223
  const path = parsePathString(pathInput);
3670
5224
  const transformProps = transform && Object.keys(transform);
3671
5225
  if (!transform || transformProps && !transformProps.length) return path.slice(0);
3672
- if (!transform.origin) Object.assign(transform, { origin: defaultOptions.origin });
3673
- const origin = transform.origin;
3674
- const matrixInstance = getSVGMatrix(transform);
5226
+ const origin = (transform.origin ?? defaultOptions.origin).slice(0);
5227
+ const matrixInstance = getSVGMatrix({
5228
+ ...transform,
5229
+ origin
5230
+ });
3675
5231
  if (matrixInstance.isIdentity) return path.slice(0);
3676
5232
  if (matrixInstance.is2D) return transform2D(path, matrixInstance.a, matrixInstance.b, matrixInstance.c, matrixInstance.d, matrixInstance.e, matrixInstance.f, origin[0], origin[1]);
3677
5233
  let x = 0;
@@ -3725,31 +5281,468 @@ const transformPath = (pathInput, transform) => {
3725
5281
  * @param path the source `pathArray`
3726
5282
  * @returns the reversed `pathArray`
3727
5283
  */
3728
- const reverseCurve = (path) => {
3729
- const rotatedCurve = path.slice(1).map((x, i, curveOnly) => !i ? path[0].slice(1).concat(x.slice(1)) : curveOnly[i - 1].slice(-2).concat(x.slice(1))).map((x) => x.map((_, i) => x[x.length - i - 2 * (1 - i % 2)])).reverse();
3730
- return [["M"].concat(rotatedCurve[0].slice(0, 2))].concat(rotatedCurve.map((x) => ["C"].concat(x.slice(2))));
3731
- };
3732
- // src/process/roundPath.ts
5284
+ const reverseCurve = (path) => {
5285
+ const rotatedCurve = path.slice(1).map((x, i, curveOnly) => !i ? path[0].slice(1).concat(x.slice(1)) : curveOnly[i - 1].slice(-2).concat(x.slice(1))).map((x) => x.map((_, i) => x[x.length - i - 2 * (1 - i % 2)])).reverse();
5286
+ return [["M"].concat(rotatedCurve[0].slice(0, 2))].concat(rotatedCurve.map((x) => ["C"].concat(x.slice(2))));
5287
+ };
5288
+ // src/process/roundPath.ts
5289
+ /**
5290
+ * Rounds the values of a `pathArray` instance to
5291
+ * a specified amount of decimals and returns it.
5292
+ *
5293
+ * @param path the source `pathArray`
5294
+ * @param roundOption the amount of decimals to round numbers to
5295
+ * @returns the resulted `pathArray` with rounded values
5296
+ */
5297
+ const roundPath = (path, roundOption) => {
5298
+ let { round } = defaultOptions;
5299
+ round = roundOption === "off" ? roundOption : typeof roundOption === "number" && roundOption >= 0 ? roundOption : typeof round === "number" && round >= 0 ? round : "off";
5300
+ if (round === "off") return path.slice(0);
5301
+ return iterate(path.slice(0), (segment) => {
5302
+ return roundSegment(segment, round);
5303
+ });
5304
+ };
5305
+ // src/process/splitSubPaths.ts
5306
+ /**
5307
+ * Splits a normalized path into its sub-paths.
5308
+ *
5309
+ * A sub-path begins with a moveto command, so the path is split at every
5310
+ * moveto: the close segment of a sub-path belongs to the sub-path it closes.
5311
+ *
5312
+ * @param path - the normalized path to split
5313
+ * @returns the sub-paths of the path
5314
+ *
5315
+ * @example
5316
+ * ```ts
5317
+ * splitSubPaths([["M", 0, 0], ["L", 10, 0], ["Z"], ["M", 20, 0], ["L", 30, 0]]);
5318
+ * // => [
5319
+ * // [["M", 0, 0], ["L", 10, 0], ["Z"]],
5320
+ * // [["M", 20, 0], ["L", 30, 0]],
5321
+ * // ]
5322
+ * ```
5323
+ */
5324
+ const splitSubPaths = (path) => {
5325
+ const result = [];
5326
+ let current = [];
5327
+ for (const segment of path) if (segment[0] === "M") {
5328
+ if (current.length) result.push(current);
5329
+ current = [segment];
5330
+ } else current.push(segment);
5331
+ if (current.length) result.push(current);
5332
+ return result;
5333
+ };
5334
+ // src/process/samplePath.ts
5335
+ /**
5336
+ * Returns the number of samples of a segment.
5337
+ *
5338
+ * The samples are spread over the parameter of the segment, so their number
5339
+ * grows with the length of the segment: a straight segment needs none, a
5340
+ * curve needs one every step.
5341
+ *
5342
+ * @param length - the length of the segment
5343
+ * @param step - the maximum distance between two samples
5344
+ * @returns the number of samples of the segment
5345
+ */
5346
+ const sampleCount = (length, step) => Math.max(2, Math.ceil(length / step));
5347
+ /**
5348
+ * Returns the points of a normalized path, sampled along its segments.
5349
+ *
5350
+ * The samples are the points the simplification measures: they sit on the
5351
+ * path itself, so the distance between the path and the result is measured
5352
+ * against the path and not against an approximation of it.
5353
+ *
5354
+ * A straight segment needs no sample of its own, the chord of a straight
5355
+ * segment is the segment: the same goes for the close segment, the
5356
+ * deviation of a chord from a straight line is at its ends and the ends are
5357
+ * the samples of the segments around it.
5358
+ *
5359
+ * @param path - the normalized path to sample
5360
+ * @param step - the maximum distance between two samples
5361
+ * @returns the samples of the path, in path order
5362
+ */
5363
+ const samplePath = (path, step) => {
5364
+ const { measures } = buildPathLengthTable(path);
5365
+ const samples = [];
5366
+ for (const measure of measures) {
5367
+ const { geometry: segment, startX, startY, endX, endY, length } = measure;
5368
+ const command = segment[0];
5369
+ if (command === "Z") {
5370
+ samples.push({
5371
+ x: endX,
5372
+ y: endY
5373
+ });
5374
+ continue;
5375
+ }
5376
+ if (command === "M" || command === "L") samples.push({
5377
+ x: endX,
5378
+ y: endY
5379
+ });
5380
+ else if (command === "C") {
5381
+ const count = sampleCount(length, step);
5382
+ const coords = [
5383
+ startX,
5384
+ startY,
5385
+ segment[1],
5386
+ segment[2],
5387
+ segment[3],
5388
+ segment[4],
5389
+ endX,
5390
+ endY
5391
+ ];
5392
+ for (let i = 1; i < count; i += 1) samples.push(getPointAtCubicSegmentLength(coords, i / count));
5393
+ samples.push({
5394
+ x: endX,
5395
+ y: endY
5396
+ });
5397
+ } else if (command === "Q") {
5398
+ const count = sampleCount(length, step);
5399
+ const coords = [
5400
+ startX,
5401
+ startY,
5402
+ segment[1],
5403
+ segment[2],
5404
+ endX,
5405
+ endY
5406
+ ];
5407
+ for (let i = 1; i < count; i += 1) samples.push(getPointAtQuadSegmentLength(coords, i / count));
5408
+ samples.push({
5409
+ x: endX,
5410
+ y: endY
5411
+ });
5412
+ } else {
5413
+ const rx = segment[1];
5414
+ const ry = segment[2];
5415
+ const angle = segment[3];
5416
+ if (rx === 0 || ry === 0) {
5417
+ samples.push({
5418
+ x: endX,
5419
+ y: endY
5420
+ });
5421
+ continue;
5422
+ }
5423
+ const { center, rx: radiusX, ry: radiusY, startAngle, endAngle } = getArcProps(startX, startY, rx, ry, angle, segment[4], segment[5], endX, endY);
5424
+ const count = sampleCount(length, step);
5425
+ const alpha = (angle % 360 + 360) % 360 * (Math.PI / 180);
5426
+ const sweep = endAngle - startAngle;
5427
+ for (let i = 1; i < count; i += 1) {
5428
+ const [x, y] = arcPoint(center.x, center.y, radiusX, radiusY, alpha, startAngle + sweep * i / count);
5429
+ samples.push({
5430
+ x,
5431
+ y
5432
+ });
5433
+ }
5434
+ samples.push({
5435
+ x: endX,
5436
+ y: endY
5437
+ });
5438
+ }
5439
+ }
5440
+ return samples;
5441
+ };
5442
+ // src/process/douglasPeucker.ts
5443
+ /**
5444
+ * Returns the indexes of the points that have to be kept to approximate a
5445
+ * polyline within a given tolerance, with the Douglas-Peucker algorithm.
5446
+ *
5447
+ * The first and the last point of the polyline are always kept, the points
5448
+ * in between are kept when they are further from the chord between the two
5449
+ * points around them than the tolerance.
5450
+ *
5451
+ * @see https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm
5452
+ *
5453
+ * @param points - the points of the polyline
5454
+ * @param tolerance - the maximum distance from the simplified polyline
5455
+ * @returns the indexes of the points to keep, in order
5456
+ */
5457
+ const douglasPeucker = (points, tolerance) => {
5458
+ if (points.length < 3) return points.map((_point, index) => index);
5459
+ const keep = points.map(() => false);
5460
+ keep[0] = true;
5461
+ keep[points.length - 1] = true;
5462
+ const stack = [0, points.length - 1];
5463
+ while (stack.length) {
5464
+ const last = stack.pop();
5465
+ const first = stack.pop();
5466
+ const start = points[first];
5467
+ const end = points[last];
5468
+ let maxDistance = 0;
5469
+ let index = -1;
5470
+ for (let i = first + 1; i < last; i += 1) {
5471
+ const distance = distanceToSegment(points[i], start, end);
5472
+ if (distance > maxDistance) {
5473
+ maxDistance = distance;
5474
+ index = i;
5475
+ }
5476
+ }
5477
+ if (index === -1 || maxDistance <= tolerance) continue;
5478
+ keep[index] = true;
5479
+ const span = last - first;
5480
+ const edge = span >> 3;
5481
+ if (span > 8 && (index - first < edge || last - index < edge)) {
5482
+ const middle = first + (span >> 1);
5483
+ keep[middle] = true;
5484
+ if (index < middle) stack.push(middle, last, index, middle, first, index);
5485
+ else stack.push(index, last, middle, index, first, middle);
5486
+ } else stack.push(index, last, first, index);
5487
+ }
5488
+ return points.map((_point, index) => index).filter((index) => keep[index]);
5489
+ };
5490
+ // src/process/fitCubic.ts
5491
+ const MAX_ITERATIONS = 4;
5492
+ const subtract = (a, b) => ({
5493
+ x: a.x - b.x,
5494
+ y: a.y - b.y
5495
+ });
5496
+ const add = (a, b) => ({
5497
+ x: a.x + b.x,
5498
+ y: a.y + b.y
5499
+ });
5500
+ const scale = (point, value) => ({
5501
+ x: point.x * value,
5502
+ y: point.y * value
5503
+ });
5504
+ const dot = (a, b) => a.x * b.x + a.y * b.y;
5505
+ const distance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
5506
+ const normalize = (point) => {
5507
+ const length = Math.hypot(point.x, point.y);
5508
+ return length ? scale(point, 1 / length) : {
5509
+ x: 0,
5510
+ y: 0
5511
+ };
5512
+ };
5513
+ const negate = (point) => ({
5514
+ x: -point.x,
5515
+ y: -point.y
5516
+ });
5517
+ const chordParameters = (points) => {
5518
+ const parameters = [0];
5519
+ for (let i = 1; i < points.length; i += 1) parameters.push(parameters[i - 1] + distance(points[i - 1], points[i]));
5520
+ const total = parameters[parameters.length - 1];
5521
+ return parameters.map((parameter) => parameter / total);
5522
+ };
5523
+ const evaluate = (curve, t) => {
5524
+ const u = 1 - t;
5525
+ return add(add(scale(curve[0], u ** 3), scale(curve[1], 3 * u * u * t)), add(scale(curve[2], 3 * u * t * t), scale(curve[3], t ** 3)));
5526
+ };
5527
+ const generateCurve = (points, parameters, leftTangent, rightTangent) => {
5528
+ const first = points[0];
5529
+ const last = points[points.length - 1];
5530
+ const segmentLength = distance(first, last);
5531
+ if (points.length === 2) {
5532
+ const handle = segmentLength / 3;
5533
+ return [
5534
+ first,
5535
+ add(first, scale(leftTangent, handle)),
5536
+ add(last, scale(rightTangent, handle)),
5537
+ last
5538
+ ];
5539
+ }
5540
+ let c00 = 0;
5541
+ let c01 = 0;
5542
+ let c11 = 0;
5543
+ let x0 = 0;
5544
+ let x1 = 0;
5545
+ for (let i = 0; i < points.length; i += 1) {
5546
+ const t = parameters[i];
5547
+ const u = 1 - t;
5548
+ const b0 = u ** 3;
5549
+ const b1 = 3 * u * u * t;
5550
+ const b2 = 3 * u * t * t;
5551
+ const b3 = t ** 3;
5552
+ const a0 = scale(leftTangent, b1);
5553
+ const a1 = scale(rightTangent, b2);
5554
+ const tmp = subtract(points[i], add(scale(first, b0 + b1), scale(last, b2 + b3)));
5555
+ c00 += dot(a0, a0);
5556
+ c01 += dot(a0, a1);
5557
+ c11 += dot(a1, a1);
5558
+ x0 += dot(a0, tmp);
5559
+ x1 += dot(a1, tmp);
5560
+ }
5561
+ const determinant = c00 * c11 - c01 * c01;
5562
+ let alphaLeft = determinant ? (x0 * c11 - x1 * c01) / determinant : 0;
5563
+ let alphaRight = determinant ? (c00 * x1 - c01 * x0) / determinant : 0;
5564
+ const epsilon = 1e-6 * segmentLength;
5565
+ if (alphaLeft < epsilon || alphaRight < epsilon) {
5566
+ alphaLeft = segmentLength / 3;
5567
+ alphaRight = alphaLeft;
5568
+ }
5569
+ return [
5570
+ first,
5571
+ add(first, scale(leftTangent, alphaLeft)),
5572
+ add(last, scale(rightTangent, alphaRight)),
5573
+ last
5574
+ ];
5575
+ };
5576
+ const findMaxError = (points, curve, parameters) => {
5577
+ let error = 0;
5578
+ let split = points.length >> 1;
5579
+ for (let i = 1; i < points.length - 1; i += 1) {
5580
+ const point = evaluate(curve, parameters[i]);
5581
+ const current = (point.x - points[i].x) ** 2 + (point.y - points[i].y) ** 2;
5582
+ if (current > error) {
5583
+ error = current;
5584
+ split = i;
5585
+ }
5586
+ }
5587
+ return {
5588
+ error,
5589
+ split
5590
+ };
5591
+ };
5592
+ const refineParameter = (curve, point, parameter) => {
5593
+ const t = parameter;
5594
+ const u = 1 - t;
5595
+ const q = evaluate(curve, t);
5596
+ const q1 = add(add(scale(subtract(curve[1], curve[0]), 3 * u * u), scale(subtract(curve[2], curve[1]), 6 * u * t)), scale(subtract(curve[3], curve[2]), 3 * t * t));
5597
+ const q2 = add(scale(add(subtract(curve[2], scale(curve[1], 2)), curve[0]), 6 * u), scale(add(subtract(curve[3], scale(curve[2], 2)), curve[1]), 6 * t));
5598
+ const difference = subtract(q, point);
5599
+ const denominator = dot(q1, q1) + dot(q2, difference);
5600
+ return denominator ? t - dot(q1, difference) / denominator : t;
5601
+ };
5602
+ const reparameterize = (curve, points, parameters) => parameters.map((parameter, index) => index === 0 || index === points.length - 1 ? parameter : refineParameter(curve, points[index], parameter));
5603
+ const toSegments = (curves) => curves.map((curve) => [
5604
+ "C",
5605
+ curve[1].x,
5606
+ curve[1].y,
5607
+ curve[2].x,
5608
+ curve[2].y,
5609
+ curve[3].x,
5610
+ curve[3].y
5611
+ ]);
5612
+ const fitCubic = (points, tolerance) => {
5613
+ const error = tolerance * tolerance;
5614
+ const curves = [];
5615
+ const fit = (range, leftTangent, rightTangent) => {
5616
+ const parameters = chordParameters(range);
5617
+ let curve = generateCurve(range, parameters, leftTangent, rightTangent);
5618
+ let maximum = findMaxError(range, curve, parameters);
5619
+ if (maximum.error <= error || range.length === 2) {
5620
+ curves.push(curve);
5621
+ return;
5622
+ }
5623
+ let currentParameters = parameters;
5624
+ for (let i = 0; i < MAX_ITERATIONS; i += 1) {
5625
+ currentParameters = reparameterize(curve, range, currentParameters);
5626
+ curve = generateCurve(range, currentParameters, leftTangent, rightTangent);
5627
+ maximum = findMaxError(range, curve, currentParameters);
5628
+ if (maximum.error <= error) {
5629
+ curves.push(curve);
5630
+ return;
5631
+ }
5632
+ }
5633
+ const split = maximum.split;
5634
+ const centerTangent = normalize(subtract(range[split - 1], range[split + 1]));
5635
+ fit(range.slice(0, split + 1), leftTangent, centerTangent);
5636
+ fit(range.slice(split), negate(centerTangent), rightTangent);
5637
+ };
5638
+ fit(points, normalize(subtract(points[1], points[0])), normalize(subtract(points[points.length - 2], points[points.length - 1])));
5639
+ return toSegments(curves);
5640
+ };
5641
+ // src/process/simplifyPath.ts
5642
+ /**
5643
+ * The default tolerance of the simplification.
5644
+ */
5645
+ const defaultTolerance = 1;
5646
+ /**
5647
+ * The maximum number of samples of a path.
5648
+ *
5649
+ * The samples are the measurements of the algorithm, so their number grows
5650
+ * with the length of the path and shrinks with the tolerance: a very long
5651
+ * path with a very small tolerance would need millions of samples, so the
5652
+ * sampling is capped and the step grows to fit.
5653
+ */
5654
+ const MAX_SAMPLES = 2e4;
5655
+ /**
5656
+ * The share of the tolerance the samples are spread with.
5657
+ *
5658
+ * The curve is sampled with a step of a sixteenth of the tolerance, so the
5659
+ * deviation of the curve between two samples is a fraction of the tolerance
5660
+ * itself: a range is only accepted when the curve stays within four fifths
5661
+ * of the tolerance from the chord, so the result cannot exceed it.
5662
+ */
5663
+ const SAMPLE_SHARE = 16;
5664
+ /**
5665
+ * The share of the tolerance a range of the path may use.
5666
+ *
5667
+ * The samples are a discretization of the path, so the deviation between two
5668
+ * samples is not measured: the range is accepted at four fifths of the
5669
+ * tolerance, so the result stays within the tolerance even when the curve
5670
+ * bulges a little between two samples.
5671
+ */
5672
+ const ACCEPTANCE = .8;
3733
5673
  /**
3734
- * Rounds the values of a `pathArray` instance to
3735
- * a specified amount of decimals and returns it.
5674
+ * Simplifies a path within a geometric tolerance.
3736
5675
  *
3737
- * @param path the source `pathArray`
3738
- * @param roundOption the amount of decimals to round numbers to
3739
- * @returns the resulted `pathArray` with rounded values
5676
+ * Straight-line runs are reduced with Douglas-Peucker. Curve runs are fitted
5677
+ * with cubic Béziers, while arcs and original curves are preserved whenever
5678
+ * fitting would not reduce the segment count. Every source sub-path and its
5679
+ * closure are retained.
5680
+ *
5681
+ * The tolerance is the target geometric error of the sampled fitting. A
5682
+ * smaller tolerance keeps more detail, a bigger one removes more.
5683
+ *
5684
+ * @param pathInput - the target path string or PathArray
5685
+ * @param options - the tolerance of the simplification, or the options
5686
+ * @returns the simplified path
5687
+ *
5688
+ * @example
5689
+ * ```ts
5690
+ * simplifyPath("M0 0L10 0L20 0L30 0", 1)
5691
+ * // => [['M', 0, 0], ['L', 30, 0]]
5692
+ * ```
3740
5693
  */
3741
- const roundPath = (path, roundOption) => {
3742
- let { round } = defaultOptions;
3743
- round = roundOption === "off" ? roundOption : typeof roundOption === "number" && roundOption >= 0 ? roundOption : typeof round === "number" && round >= 0 ? round : "off";
3744
- if (round === "off") return path.slice(0);
3745
- return iterate(path, (segment) => {
3746
- return roundSegment(segment, round);
3747
- });
5694
+ const simplifyPath = (pathInput, options) => {
5695
+ const tolerance = typeof options === "number" ? options : options?.tolerance ?? defaultTolerance;
5696
+ if (!Number.isFinite(tolerance) || tolerance <= 0) throw new TypeError(`${error}: tolerance must be a positive number`);
5697
+ const normalized = normalizePath(pathInput);
5698
+ if (!normalized.length) return [];
5699
+ const result = [];
5700
+ for (const subPath of splitSubPaths(normalized)) {
5701
+ const closed = subPath[subPath.length - 1][0] === "Z";
5702
+ const straight = subPath.slice(1).every((segment) => segment[0] === "L" || segment[0] === "Z" || segment[0] === "A" && (segment[1] === 0 || segment[2] === 0));
5703
+ const { totalLength } = buildPathLengthTable(subPath);
5704
+ const step = Math.max(tolerance / SAMPLE_SHARE, totalLength / MAX_SAMPLES);
5705
+ const samples = samplePath(subPath, step);
5706
+ const start = samples[0];
5707
+ if (straight) {
5708
+ const kept = douglasPeucker(samples, tolerance * ACCEPTANCE);
5709
+ result.push([
5710
+ "M",
5711
+ start.x,
5712
+ start.y
5713
+ ]);
5714
+ const end = closed ? kept.length - 1 : kept.length;
5715
+ for (let i = 1; i < end; i += 1) {
5716
+ const point = samples[kept[i]];
5717
+ result.push([
5718
+ "L",
5719
+ point.x,
5720
+ point.y
5721
+ ]);
5722
+ }
5723
+ if (closed) result.push(["Z"]);
5724
+ continue;
5725
+ }
5726
+ const originalCount = subPath.length - 1 - (closed ? 1 : 0);
5727
+ const points = samples.filter((point, index) => index === 0 || point.x !== samples[index - 1].x || point.y !== samples[index - 1].y);
5728
+ const curves = originalCount > 1 && points.length > 1 ? fitCubic(points, tolerance * ACCEPTANCE) : [];
5729
+ if (!curves.length || curves.length >= originalCount) {
5730
+ result.push(...subPath);
5731
+ continue;
5732
+ }
5733
+ result.push([
5734
+ "M",
5735
+ start.x,
5736
+ start.y
5737
+ ], ...curves);
5738
+ if (closed) result.push(["Z"]);
5739
+ }
5740
+ return result;
3748
5741
  };
3749
5742
  // src/morph/fixPath.ts
3750
5743
  /**
3751
5744
  * Checks a `PathArray` for an unnecessary `Z` segment
3752
- * and removes it. The `PathArray` is modified in place.
5745
+ * and returns a copy without it. The input is not modified.
3753
5746
  * In short, if the segment before `Z` extends to `M`,
3754
5747
  * the `Z` segment must be removed.
3755
5748
  *
@@ -3759,7 +5752,7 @@ const roundPath = (path, roundOption) => {
3759
5752
  * sub-path separately.
3760
5753
  *
3761
5754
  * @param pathInput the `pathArray` source
3762
- * @returns void
5755
+ * @returns the fixed path
3763
5756
  */
3764
5757
  const fixPath = (pathInput) => {
3765
5758
  const pathArray = parsePathString(pathInput);
@@ -3771,6 +5764,7 @@ const fixPath = (pathInput) => {
3771
5764
  const [x, y] = normalArray[segBeforeZ].slice(-2);
3772
5765
  if (mx === x && my === y) pathArray.splice(length - 1, 1);
3773
5766
  }
5767
+ return pathArray;
3774
5768
  };
3775
5769
  // src/morph/splitCubicSegment.ts
3776
5770
  /**
@@ -3862,15 +5856,13 @@ function splitLineToCount(x1, y1, x2, y2, count) {
3862
5856
  y2
3863
5857
  ]];
3864
5858
  const result = [];
3865
- const dx = x2 - x1;
3866
- const dy = y2 - y1;
3867
5859
  let currentX = x1;
3868
5860
  let currentY = y1;
3869
5861
  let i = 0;
3870
5862
  while (i < count) {
3871
5863
  const t = 1 / (count - i);
3872
- const nextX = x1 + t * dx;
3873
- const nextY = y1 + t * dy;
5864
+ const nextX = currentX + t * (x2 - currentX);
5865
+ const nextY = currentY + t * (y2 - currentY);
3874
5866
  result.push([
3875
5867
  currentX,
3876
5868
  currentY,
@@ -3895,54 +5887,46 @@ function splitLineToCount(x1, y1, x2, y2, count) {
3895
5887
  * @returns an array of numbers reprezenting the sub-segment count for each segment
3896
5888
  */
3897
5889
  function getPathSplits(path, target) {
3898
- if (target <= 1) throw new TypeError(`${error}: target must be >= 2`);
3899
- const totalLength = getTotalLength(path);
3900
- if (totalLength === 0) return Array(path.length).fill(1);
3901
- const idealSegLen = totalLength / target;
3902
- const isPoly = isPolylineArray(path);
3903
- const splits = [1];
3904
- const lengths = [0];
3905
- iterate(path, (seg, i, prevX, prevY) => {
3906
- if (i > 0) {
3907
- const [endX, endY] = seg.slice(-2);
3908
- const segLen = isPoly ? getLineLength(prevX, prevY, endX, endY) : getCubicLength(prevX, prevY, seg[1], seg[2], seg[3], seg[4], seg[5], seg[6]);
3909
- lengths.push(segLen);
3910
- splits.push(1);
3911
- }
3912
- });
5890
+ if (!Number.isFinite(target)) throw new TypeError(`${error}: target must be a finite number`);
5891
+ if (target < 2) throw new TypeError(`${error}: target must be >= 2`);
5892
+ const measures = measureSegments(path);
5893
+ const segmentCount = measures.length;
5894
+ if (!segmentCount) return [];
5895
+ const lengths = measures.map(({ length }) => length);
5896
+ const totalLength = lengths.reduce((total, length) => total + length, 0);
5897
+ if (!totalLength) return Array(segmentCount).fill(1);
5898
+ const effectiveTarget = Math.max(Math.floor(target), segmentCount);
5899
+ const idealSegLen = totalLength / effectiveTarget;
5900
+ const splits = Array(segmentCount).fill(1);
3913
5901
  let totalAllocated = 1;
3914
- for (let i = 1; i < lengths.length; i++) {
5902
+ for (let i = 1; i < segmentCount; i += 1) {
3915
5903
  const segLen = lengths[i];
3916
5904
  const desired = segLen > idealSegLen ? Math.round(segLen / idealSegLen) : 1;
3917
5905
  splits[i] = desired;
3918
5906
  totalAllocated += desired;
3919
5907
  }
3920
- let diff = target - totalAllocated;
5908
+ let diff = effectiveTarget - totalAllocated;
3921
5909
  if (diff !== 0) {
3922
5910
  const candidates = [];
3923
- for (let i = 1; i < lengths.length; i++) if (lengths[i] > 0) candidates.push([i, lengths[i]]);
3924
- const cLen = candidates.length;
5911
+ for (let i = 1; i < segmentCount; i += 1) if (lengths[i] > 0) candidates.push([i, lengths[i]]);
3925
5912
  if (diff < 0) {
3926
5913
  candidates.sort((a, b) => a[1] - b[1]);
3927
- for (let i = 0; i < cLen; i++) {
3928
- const idx = candidates[i][0];
3929
- if (splits[idx] > 1 && candidates[i][1] > 0) {
3930
- splits[idx]--;
3931
- diff++;
5914
+ while (diff < 0) {
5915
+ let changed = false;
5916
+ for (const [index] of candidates) if (splits[index] > 1) {
5917
+ splits[index] -= 1;
5918
+ diff += 1;
5919
+ changed = true;
5920
+ if (diff === 0) break;
3932
5921
  }
3933
- if (diff === 0) break;
3934
- else if (i === cLen - 1) i = 0;
5922
+ if (!changed) break;
3935
5923
  }
3936
- } else if (diff > 0) {
5924
+ } else {
3937
5925
  candidates.sort((a, b) => b[1] - a[1]);
3938
- for (let i = 0; i < cLen; i++) {
3939
- const idx = candidates[i][0];
3940
- if (candidates[i][1] > 0) {
3941
- splits[idx]++;
3942
- diff--;
3943
- }
5926
+ while (diff > 0) for (const [index] of candidates) {
5927
+ splits[index] += 1;
5928
+ diff -= 1;
3944
5929
  if (diff === 0) break;
3945
- else if (i === cLen - 1) i = 0;
3946
5930
  }
3947
5931
  }
3948
5932
  }
@@ -4076,8 +6060,6 @@ function splitCurvePathToCount(path, target) {
4076
6060
  * Samples points from a path to form a polygon approximation.
4077
6061
  * Collects endpoints of each segment (M start + ends of L/C/etc).
4078
6062
  *
4079
- * If `sampleSize` parameter is provided, it will return a polygon
4080
- * equivalent to the original `PathArray`.
4081
6063
  * @param path `PolygonPathArray` or `CurvePathArray`
4082
6064
  * @returns Array of [x, y] points
4083
6065
  */
@@ -4091,45 +6073,112 @@ function samplePolygon(path) {
4091
6073
  points.push([mx, my]);
4092
6074
  } else if (cmd === "L") points.push([seg[1], seg[2]]);
4093
6075
  else if (cmd === "C") points.push([seg[5], seg[6]]);
6076
+ else if (cmd === "Q") points.push([seg[3], seg[4]]);
4094
6077
  else if (cmd === "A") points.push([seg[6], seg[7]]);
4095
6078
  else if (cmd === "Z") points.push([mx, my]);
4096
- else throw new TypeError(`${error}: path command "${cmd}" is not supported`);
6079
+ else throw new TypeError(`${error}: path command "${String(cmd)}" is not supported`);
4097
6080
  });
4098
6081
  return points;
4099
6082
  }
4100
6083
  // src/morph/getRotatedPath.ts
4101
6084
  /**
4102
- * Returns all possible rotations of a path (line or curve) by shifting the start point.
4103
- * Each rotation is a new PathArray starting at a different original segment.
6085
+ * Returns a single rotation of a path (line or curve) by shifting the start point.
6086
+ * The rotation starts at the end of the segment at `idx` and continues with the
6087
+ * following segments, wrapping around the end of the path.
4104
6088
  *
4105
- * @param path PathArray (M + L/C + optional Z) — must be single subpath, normalized
4106
- * @returns PathArray[] — array of all possible rotations
6089
+ * @param a PathArray (M + L/C + optional Z) — must be single subpath, normalized
6090
+ * @param idx the index of the segment the rotation starts at
6091
+ * @returns PathArray — the rotation of the path
4107
6092
  */
4108
- function getRotations(a) {
6093
+ function getRotation(a, idx) {
4109
6094
  const pathLen = a.length;
4110
6095
  const pointCount = pathLen - 1;
4111
- let path;
4112
- const result = [];
4113
- for (let idx = 0; idx < pathLen; idx++) {
4114
- path = [];
4115
- for (let i = 0; i < pathLen; i++) {
4116
- let oldSegIdx = idx + i;
4117
- let seg;
4118
- if (i === 0 || a[oldSegIdx] && a[oldSegIdx][0] === "M") {
4119
- seg = a[oldSegIdx];
4120
- path.push(["M", ...seg.slice(-2)]);
4121
- continue;
4122
- }
4123
- if (oldSegIdx >= pathLen) oldSegIdx -= pointCount;
4124
- path.push(a[oldSegIdx]);
6096
+ const path = [];
6097
+ for (let i = 0; i < pathLen; i++) {
6098
+ let oldSegIdx = idx + i;
6099
+ let seg;
6100
+ if (i === 0 || a[oldSegIdx] && a[oldSegIdx][0] === "M") {
6101
+ seg = a[oldSegIdx];
6102
+ path.push(["M", ...seg.slice(-2)]);
6103
+ continue;
4125
6104
  }
4126
- result.push(path);
6105
+ if (oldSegIdx >= pathLen) oldSegIdx -= pointCount;
6106
+ path.push(a[oldSegIdx]);
4127
6107
  }
4128
- return result;
6108
+ return path;
4129
6109
  }
6110
+ const getSegmentDistanceSquared = (a, b) => {
6111
+ let distance = 0;
6112
+ for (let i = 1; i < a.length; i += 1) {
6113
+ const delta = Number(a[i]) - Number(b[i]);
6114
+ distance += delta * delta;
6115
+ }
6116
+ return distance;
6117
+ };
6118
+ const getStartDistanceSquared = (a, b) => {
6119
+ const dx = Number(a[a.length - 2]) - Number(b[b.length - 2]);
6120
+ const dy = Number(a[a.length - 1]) - Number(b[b.length - 1]);
6121
+ return dx * dx + dy * dy;
6122
+ };
6123
+ /**
6124
+ * Finds the rotation of `pathA` that matches `pathB` best by minimizing the sum
6125
+ * of squared distances between all corresponding coordinates, including the
6126
+ * control points of the curves.
6127
+ *
6128
+ * The rotations are not materialized: the segment at index `j` of the rotation
6129
+ * that starts at `idx` is the segment at index `1 + ((idx + i - 1) mod
6130
+ * pointCount)` of the source path, so the sum can be computed from the source
6131
+ * path alone.
6132
+ *
6133
+ * A rotation whose running sum is already worse than the best rotation found so
6134
+ * far cannot become the best one — the terms of the sum are squared distances,
6135
+ * so the sum only grows — and the rotation is dropped right there.
6136
+ *
6137
+ * The rotations are checked in the order of their first term, the distance
6138
+ * between the start of the rotation and the start of the reference path: the
6139
+ * rotation that matches best is usually the one that starts closest, so it is
6140
+ * usually found early and the rest of the rotations are dropped right away.
6141
+ *
6142
+ * @param pathA the path to rotate
6143
+ * @param pathB the reference path
6144
+ * @returns the index of the best rotation
6145
+ */
6146
+ const getBestRotationIndex = (pathA, pathB) => {
6147
+ const pathLen = pathA.length;
6148
+ const pointCount = pathLen - 1;
6149
+ const firstTerms = [];
6150
+ const order = [];
6151
+ for (let idx = 0; idx < pathLen; idx++) {
6152
+ firstTerms.push(getStartDistanceSquared(pathA[idx], pathB[0]));
6153
+ order.push(idx);
6154
+ }
6155
+ order.sort((a, b) => {
6156
+ const first = firstTerms[a];
6157
+ const second = firstTerms[b];
6158
+ if (first < second) return -1;
6159
+ if (first > second) return 1;
6160
+ return a - b;
6161
+ });
6162
+ let bestIndex = 0;
6163
+ let minDistanceSq = Infinity;
6164
+ for (const idx of order) {
6165
+ let sumDistSq = firstTerms[idx];
6166
+ if (sumDistSq > minDistanceSq) continue;
6167
+ for (let i = 1; i < pathLen; i++) {
6168
+ const j = 1 + (idx + i - 1) % pointCount;
6169
+ sumDistSq += getSegmentDistanceSquared(pathA[j], pathB[i]);
6170
+ if (sumDistSq > minDistanceSq) break;
6171
+ }
6172
+ if (sumDistSq < minDistanceSq || sumDistSq === minDistanceSq && idx < bestIndex) {
6173
+ minDistanceSq = sumDistSq;
6174
+ bestIndex = idx;
6175
+ }
6176
+ }
6177
+ return bestIndex;
6178
+ };
4130
6179
  /**
4131
- * Finds the best rotation of pathA to match pathB by minimizing sum of squared distances
4132
- * between corresponding endpoints.
6180
+ * Finds the best rotation of pathA to match pathB by minimizing the sum of squared distances
6181
+ * between corresponding coordinates, including curve control points.
4133
6182
  *
4134
6183
  * Works with both polygon (L) and curve (C) arrays.
4135
6184
  *
@@ -4138,40 +6187,473 @@ function getRotations(a) {
4138
6187
  * @returns PathArray — best rotation of pathA
4139
6188
  */
4140
6189
  function getRotatedPath(pathA, pathB, computedRotations) {
4141
- const rotations = computedRotations || getRotations(pathA);
4142
6190
  if (pathA.length !== pathB.length) throw new TypeError(error + ": paths must have the same number of segments after equalization");
4143
- let bestIndex = 0;
4144
- let minDistanceSq = Infinity;
4145
- for (let ri = 0; ri < rotations.length; ri++) {
4146
- const rotation = rotations[ri];
4147
- const rLen = rotation.length;
4148
- let sumDistSq = 0;
4149
- for (let i = 0; i < rLen; i++) {
4150
- const segA = rotation[i];
4151
- const segB = pathB[i];
4152
- const endA = segA.slice(-2);
4153
- const endB = segB.slice(-2);
4154
- const dx = endA[0] - endB[0];
4155
- const dy = endA[1] - endB[1];
4156
- sumDistSq += dx * dx + dy * dy;
4157
- }
4158
- if (sumDistSq < minDistanceSq) {
4159
- minDistanceSq = sumDistSq;
4160
- bestIndex = ri;
6191
+ if (computedRotations) {
6192
+ let bestIndex = 0;
6193
+ let minDistanceSq = Infinity;
6194
+ for (let ri = 0; ri < computedRotations.length; ri++) {
6195
+ const rotation = computedRotations[ri];
6196
+ let sumDistSq = 0;
6197
+ for (let i = 0; i < rotation.length; i++) sumDistSq += getSegmentDistanceSquared(rotation[i], pathB[i]);
6198
+ if (sumDistSq < minDistanceSq) {
6199
+ minDistanceSq = sumDistSq;
6200
+ bestIndex = ri;
6201
+ }
4161
6202
  }
6203
+ return computedRotations[bestIndex];
4162
6204
  }
4163
- return rotations[bestIndex];
6205
+ return getRotation(pathA, getBestRotationIndex(pathA, pathB));
4164
6206
  }
6207
+ // src/morph/resamplePath.ts
6208
+ /**
6209
+ * The share of a span used by the control points of a fallback curve.
6210
+ */
6211
+ const CONTROL_SHARE = 3;
6212
+ /**
6213
+ * The distance below which two lengths are the same.
6214
+ */
6215
+ const LENGTH_EPSILON = 1e-9;
6216
+ /**
6217
+ * Distributes a number of intervals among a number of spans.
6218
+ *
6219
+ * The intervals are shared in proportion to the length of the spans, so the
6220
+ * spacing of the intervals stays the same over the whole path. The spans
6221
+ * that lose a fraction of an interval share it out, the one with the
6222
+ * biggest fraction gets it.
6223
+ *
6224
+ * @param lengths - the length of every span
6225
+ * @param extra - the number of intervals to distribute
6226
+ * @returns the number of extra intervals of every span
6227
+ */
6228
+ const distributeIntervals = (lengths, extra) => {
6229
+ const shares = lengths.map(() => 0);
6230
+ if (extra <= 0) return shares;
6231
+ const total = lengths.reduce((sum, length) => sum + length, 0);
6232
+ if (total <= 0) return shares;
6233
+ const remainders = [];
6234
+ let used = 0;
6235
+ for (let i = 0; i < lengths.length; i += 1) {
6236
+ const exact = lengths[i] / total * extra;
6237
+ const whole = Math.floor(exact);
6238
+ shares[i] = whole;
6239
+ used += whole;
6240
+ remainders.push({
6241
+ index: i,
6242
+ remainder: exact - whole
6243
+ });
6244
+ }
6245
+ remainders.sort((a, b) => b.remainder - a.remainder || a.index - b.index);
6246
+ let left = extra - used;
6247
+ for (let i = 0; left > 0 && remainders.length; i = (i + 1) % remainders.length) {
6248
+ shares[remainders[i].index] += 1;
6249
+ left -= 1;
6250
+ }
6251
+ return shares;
6252
+ };
6253
+ /**
6254
+ * Builds the lengths of the knots of a resampled path.
6255
+ *
6256
+ * The source segment boundaries are knots too, so every result span belongs
6257
+ * to one source segment. The intervals between the boundaries are shared in
6258
+ * proportion to their length, so the spacing of the knots stays the same over
6259
+ * the whole path.
6260
+ *
6261
+ * When the source segments do not fit into the requested intervals, the knots
6262
+ * are spread evenly and the shape of the path is approximated by its chords.
6263
+ *
6264
+ * @param totalLength - the length of the path
6265
+ * @param intervals - the number of intervals of the result
6266
+ * @param boundaries - the length of every source segment boundary
6267
+ * @returns the length of every knot of the result, in path order
6268
+ */
6269
+ const buildKnots = (totalLength, intervals, boundaries) => {
6270
+ const breakpoints = [0];
6271
+ for (const boundary of boundaries) if (boundary > breakpoints[breakpoints.length - 1] + LENGTH_EPSILON) breakpoints.push(boundary);
6272
+ breakpoints.push(totalLength);
6273
+ const spanCount = breakpoints.length - 1;
6274
+ const knots = [];
6275
+ if (spanCount > intervals) {
6276
+ for (let i = 0; i <= intervals; i += 1) knots.push(totalLength * i / intervals);
6277
+ return knots;
6278
+ }
6279
+ const lengths = breakpoints.slice(1).map((value, index) => value - breakpoints[index]);
6280
+ const shares = distributeIntervals(lengths, intervals - spanCount);
6281
+ for (let i = 0; i < spanCount; i += 1) {
6282
+ const from = breakpoints[i];
6283
+ const to = breakpoints[i + 1];
6284
+ const count = shares[i] + 1;
6285
+ for (let j = 0; j < count; j += 1) knots.push(from + (to - from) * j / count);
6286
+ }
6287
+ knots.push(totalLength);
6288
+ return knots;
6289
+ };
6290
+ /**
6291
+ * Finds the index of the segment a distance falls into.
6292
+ *
6293
+ * The segment is the last one whose accumulated length is below the
6294
+ * distance, the same segment the linear walk over the path would have
6295
+ * stopped at. A distance at the end of a segment belongs to the segment
6296
+ * before it, so the frame at that distance is the frame at the end of the
6297
+ * segment.
6298
+ *
6299
+ * @param measures - the measured segments of the path
6300
+ * @param distance - the distance along the path
6301
+ * @returns the index of the segment
6302
+ */
6303
+ const findSegmentIndex = (measures, distance) => {
6304
+ let low = 0;
6305
+ let high = measures.length - 1;
6306
+ while (low < high) {
6307
+ const mid = low + high + 1 >> 1;
6308
+ if (measures[mid].lengthAtSegment < distance) low = mid;
6309
+ else high = mid - 1;
6310
+ }
6311
+ return low;
6312
+ };
6313
+ /**
6314
+ * Returns the direction of the path after a segment.
6315
+ *
6316
+ * The segments without a direction are skipped, so the direction of the
6317
+ * path is the direction of the first segment that has one.
6318
+ *
6319
+ * @param measures - the measured segments of the path
6320
+ * @param index - the index of the segment
6321
+ * @returns the direction of the path, or `null` when the path has none
6322
+ */
6323
+ const findNextDirection = (measures, index) => {
6324
+ for (let i = index + 1; i < measures.length; i += 1) {
6325
+ const measure = measures[i];
6326
+ if (measure.length <= 0) continue;
6327
+ const tangent = getSegmentFrame(measure.geometry, measure.startX, measure.startY, measure.endX, measure.endY, 0, measure.length).tangent;
6328
+ if (tangent.x || tangent.y) return tangent;
6329
+ }
6330
+ return null;
6331
+ };
6332
+ /**
6333
+ * The share of the length of a path the end of the path can be over.
6334
+ *
6335
+ * The length of a path is the sum of the lengths of its segments, so the end
6336
+ * of the path can be a fraction over the end of its last segment. The point
6337
+ * at the end of the path is the end point of the path, not a point a
6338
+ * fraction before it.
6339
+ */
6340
+ const END_EPSILON = 1e-9;
6341
+ /**
6342
+ * Returns the frame of a path at a given length.
6343
+ *
6344
+ * @param table - the length table of the path
6345
+ * @param distance - the distance along the path
6346
+ * @returns the frame of the path at the given length
6347
+ */
6348
+ const getFrameAt = (table, distance) => {
6349
+ const { measures, totalLength } = table;
6350
+ const index = findSegmentIndex(measures, distance);
6351
+ const measure = measures[index];
6352
+ const rawOffset = distance - measure.lengthAtSegment;
6353
+ const offset = totalLength - distance <= totalLength * END_EPSILON ? measure.length : Math.min(Math.max(rawOffset, 0), measure.length);
6354
+ const frame = getSegmentFrame(measure.geometry, measure.startX, measure.startY, measure.endX, measure.endY, offset, measure.length);
6355
+ let outgoing = frame.tangent;
6356
+ if (offset >= measure.length) {
6357
+ const next = findNextDirection(measures, index);
6358
+ if (next) outgoing = next;
6359
+ }
6360
+ return {
6361
+ point: frame.point,
6362
+ incoming: frame.tangent,
6363
+ outgoing
6364
+ };
6365
+ };
6366
+ /**
6367
+ * Returns the control lengths of a fallback curve.
6368
+ *
6369
+ * @param fromLength - the length of the start of the span
6370
+ * @param toLength - the length of the end of the span
6371
+ * @param from - the frame at the start of the span
6372
+ * @param to - the frame at the end of the span
6373
+ * @returns the length of the control point at each end of the span
6374
+ */
6375
+ const getFallbackCurveControls = (fromLength, toLength, from, to) => {
6376
+ const fallback = Math.max(0, toLength - fromLength) / CONTROL_SHARE;
6377
+ const hasFromDirection = from.outgoing.x !== 0 || from.outgoing.y !== 0;
6378
+ const hasToDirection = to.incoming.x !== 0 || to.incoming.y !== 0;
6379
+ return {
6380
+ start: hasFromDirection ? fallback : 0,
6381
+ end: hasToDirection ? fallback : 0
6382
+ };
6383
+ };
6384
+ /**
6385
+ * Returns the internal boundaries of the measured source segments.
6386
+ *
6387
+ * @param measures - the measured segments of the path
6388
+ * @param totalLength - the length of the path
6389
+ * @returns the length of every internal segment boundary
6390
+ */
6391
+ const getSegmentBoundaries = (measures, totalLength) => {
6392
+ const boundaries = [];
6393
+ for (const measure of measures) {
6394
+ if (measure.geometry[0] === "M" || measure.length <= 0) continue;
6395
+ const end = measure.lengthAtSegment + measure.length;
6396
+ if (end > LENGTH_EPSILON && end < totalLength - LENGTH_EPSILON) boundaries.push(end);
6397
+ }
6398
+ return boundaries;
6399
+ };
6400
+ /**
6401
+ * Finds the source curve that holds a distance.
6402
+ *
6403
+ * @param measures - the measured curve segments of the path
6404
+ * @param distance - the distance along the path
6405
+ * @returns the index of the curve segment
6406
+ */
6407
+ const findCurveSegmentIndex = (measures, distance) => {
6408
+ let low = 0;
6409
+ let high = measures.length - 1;
6410
+ let result = 0;
6411
+ while (low <= high) {
6412
+ const mid = low + high >> 1;
6413
+ if (measures[mid].lengthAtSegment <= distance) {
6414
+ result = mid;
6415
+ low = mid + 1;
6416
+ } else high = mid - 1;
6417
+ }
6418
+ return result;
6419
+ };
6420
+ /**
6421
+ * Extracts the exact cubic curve of a source span.
6422
+ *
6423
+ * @param measures - the measured curve segments of the path
6424
+ * @param fromLength - the length of the start of the span
6425
+ * @param toLength - the length of the end of the span
6426
+ * @returns the exact cubic segment, or `null` when the span crosses a source boundary
6427
+ */
6428
+ const getExactCurveSegment = (measures, fromLength, toLength) => {
6429
+ const measure = measures[findCurveSegmentIndex(measures, fromLength)];
6430
+ const segmentStart = measure.lengthAtSegment;
6431
+ if (toLength > segmentStart + measure.length + LENGTH_EPSILON) return null;
6432
+ const geometry = measure.geometry;
6433
+ const coordinates = [
6434
+ measure.startX,
6435
+ measure.startY,
6436
+ geometry[1],
6437
+ geometry[2],
6438
+ geometry[3],
6439
+ geometry[4],
6440
+ measure.endX,
6441
+ measure.endY
6442
+ ];
6443
+ const fromOffset = fromLength - segmentStart;
6444
+ const toOffset = toLength - segmentStart;
6445
+ const t0 = fromOffset <= LENGTH_EPSILON ? 0 : getTAtBezierLength(coordinates, Math.min(fromOffset, measure.length));
6446
+ const t1 = toOffset >= measure.length - LENGTH_EPSILON ? 1 : getTAtBezierLength(coordinates, Math.max(0, toOffset));
6447
+ let span;
6448
+ if (t0 <= 0) {
6449
+ const [first] = splitCubicSegment(...coordinates, t1);
6450
+ span = first;
6451
+ } else {
6452
+ const [, tail] = splitCubicSegment(...coordinates, t0);
6453
+ const ratio = Math.max(0, Math.min(1, (t1 - t0) / (1 - t0)));
6454
+ const [first] = splitCubicSegment(...tail, ratio);
6455
+ span = first;
6456
+ }
6457
+ return [
6458
+ "C",
6459
+ span[2],
6460
+ span[3],
6461
+ span[4],
6462
+ span[5],
6463
+ span[6],
6464
+ span[7]
6465
+ ];
6466
+ };
6467
+ /**
6468
+ * Resamples a measured path to a given number of points, spread evenly by
6469
+ * length.
6470
+ *
6471
+ * The path is measured along its length and the points of the result are
6472
+ * spread evenly over it, so the distance between two points of the result
6473
+ * is the same over the whole path. The source segment boundaries are points
6474
+ * of the result too, so the shape of the path keeps its vertices.
6475
+ *
6476
+ * The result is a polyline, or a path of cubic Bezier segments when the
6477
+ * curve mode is used. Every cubic of the result is the exact piece of the
6478
+ * source curve between two knots.
6479
+ *
6480
+ * @param table - the length table of the path
6481
+ * @param count - the number of points of the result
6482
+ * @param mode - the type of the segments of the result
6483
+ * @returns the resampled path
6484
+ */
6485
+ const resampleFromTable = (table, count, mode) => {
6486
+ const { measures, totalLength } = table;
6487
+ if (!measures.length) return [];
6488
+ const intervals = Math.max(1, Math.floor(count)) - 1;
6489
+ if (totalLength <= 0) return [[
6490
+ "M",
6491
+ measures[0].endX,
6492
+ measures[0].endY
6493
+ ]];
6494
+ if (intervals <= 0) return [[
6495
+ "M",
6496
+ table.startX,
6497
+ table.startY
6498
+ ]];
6499
+ const boundaries = getSegmentBoundaries(measures, totalLength);
6500
+ const knots = buildKnots(totalLength, intervals, boundaries);
6501
+ const frames = knots.map((knot) => getFrameAt(table, knot));
6502
+ const curveMeasures = mode === "curve" ? measures.filter((measure) => measure.geometry[0] === "C" && measure.length > LENGTH_EPSILON) : [];
6503
+ const start = frames[0].point;
6504
+ const result = [[
6505
+ "M",
6506
+ start.x,
6507
+ start.y
6508
+ ]];
6509
+ for (let i = 1; i < knots.length; i += 1) {
6510
+ const from = frames[i - 1];
6511
+ const to = frames[i];
6512
+ if (mode === "curve") {
6513
+ const exact = getExactCurveSegment(curveMeasures, knots[i - 1], knots[i]);
6514
+ if (exact) {
6515
+ result.push(exact);
6516
+ continue;
6517
+ }
6518
+ const controls = getFallbackCurveControls(knots[i - 1], knots[i], from, to);
6519
+ const c1x = from.point.x + from.outgoing.x * controls.start;
6520
+ const c1y = from.point.y + from.outgoing.y * controls.start;
6521
+ const c2x = to.point.x - to.incoming.x * controls.end;
6522
+ const c2y = to.point.y - to.incoming.y * controls.end;
6523
+ result.push([
6524
+ "C",
6525
+ c1x,
6526
+ c1y,
6527
+ c2x,
6528
+ c2y,
6529
+ to.point.x,
6530
+ to.point.y
6531
+ ]);
6532
+ } else result.push([
6533
+ "L",
6534
+ to.point.x,
6535
+ to.point.y
6536
+ ]);
6537
+ }
6538
+ return mode === "curve" ? result : result;
6539
+ };
6540
+ /**
6541
+ * Resamples a normalized sub-path to a given number of points, spread evenly
6542
+ * by length.
6543
+ *
6544
+ * @param path - the normalized sub-path to resample
6545
+ * @param count - the number of points of the result
6546
+ * @param mode - the type of the segments of the result
6547
+ * @returns the resampled path
6548
+ */
6549
+ const resampleNormalizedPath = (path, count, mode) => {
6550
+ const source = mode === "curve" ? pathToCurve(path) : path;
6551
+ return resampleFromTable(buildPathLengthTable(source), count, mode);
6552
+ };
6553
+ /**
6554
+ * Resamples a path to a given number of points, spread evenly by length.
6555
+ *
6556
+ * The path is measured along its length and the points of the result are
6557
+ * spread evenly over it, so the distance between two points of the result
6558
+ * is the same over the whole path. The source segment boundaries are points
6559
+ * of the result too, so the shape of the path keeps its vertices.
6560
+ *
6561
+ * Every sub-path of the path is resampled on its own, so the sub-paths of
6562
+ * the result are the sub-paths of the source: a path with several sub-paths
6563
+ * keeps its shape, the points of a sub-path are not shared with the others.
6564
+ *
6565
+ * The result is a polyline, or a path of cubic Bezier segments when the
6566
+ * curve mode is used. Every cubic of the result is the exact piece of the
6567
+ * source curve between two knots.
6568
+ *
6569
+ * @param pathInput - the target path string or PathArray
6570
+ * @param count - the number of points of every sub-path of the result
6571
+ * @param mode - the type of the segments of the result
6572
+ * @returns the resampled path
6573
+ *
6574
+ * @example
6575
+ * ```ts
6576
+ * resamplePath("M0 0L100 0L100 100", 3)
6577
+ * // => [['M', 0, 0], ['L', 100, 0], ['L', 100, 100]]
6578
+ * ```
6579
+ */
6580
+ const resamplePath = (pathInput, count, mode = "line") => {
6581
+ const path = normalizePath(pathInput);
6582
+ const result = [];
6583
+ for (const subPath of splitSubPaths(path)) result.push(...resampleNormalizedPath(subPath, count, mode));
6584
+ return result;
6585
+ };
4165
6586
  // src/morph/equalizeSegments.ts
4166
6587
  const equalizeSegmentsDefaults = {
4167
6588
  mode: "auto",
6589
+ strategy: "segment",
6590
+ align: true,
4168
6591
  sampleSize: 10,
4169
6592
  roundValues: 4,
4170
6593
  reverse: true,
4171
- close: false,
4172
6594
  target: void 0
4173
6595
  };
4174
6596
  /**
6597
+ * Returns the start and the end point of a path.
6598
+ *
6599
+ * A closed path ends at the start of its sub-path, so the end point of a
6600
+ * path that ends with a close command is the start of the sub-path it
6601
+ * belongs to.
6602
+ *
6603
+ * @param path - the path to read
6604
+ * @returns the start and the end point of the path
6605
+ */
6606
+ const getPathEnds = (path) => {
6607
+ const first = path[0];
6608
+ const start = {
6609
+ x: first[1],
6610
+ y: first[2]
6611
+ };
6612
+ let subStart = start;
6613
+ let end = start;
6614
+ for (const segment of path) {
6615
+ const command = segment[0];
6616
+ if (command === "M") {
6617
+ subStart = {
6618
+ x: segment[1],
6619
+ y: segment[2]
6620
+ };
6621
+ end = subStart;
6622
+ } else if (command === "Z") end = subStart;
6623
+ else end = {
6624
+ x: segment[segment.length - 2],
6625
+ y: segment[segment.length - 1]
6626
+ };
6627
+ }
6628
+ return {
6629
+ start,
6630
+ end
6631
+ };
6632
+ };
6633
+ /**
6634
+ * Returns the distance between two points.
6635
+ *
6636
+ * @param a - the first point
6637
+ * @param b - the second point
6638
+ * @returns the distance between the points
6639
+ */
6640
+ const getDistance = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
6641
+ /**
6642
+ * Returns the number of points the arc length strategy uses.
6643
+ *
6644
+ * The number of points of the result is the number of the segments of the
6645
+ * bigger path, so every source segment can have its own span in the result.
6646
+ *
6647
+ * @param table1 - the length table of the first path
6648
+ * @param table2 - the length table of the second path
6649
+ * @param target - the requested number of points
6650
+ * @returns the number of points of the result
6651
+ */
6652
+ const getArcLengthCount = (table1, table2, target) => {
6653
+ if (typeof target === "number") return Math.max(2, Math.floor(target));
6654
+ return Math.max(table1.measures.length, table2.measures.length, 2);
6655
+ };
6656
+ /**
4175
6657
  * Equalizes two paths for morphing (single subpath only).
4176
6658
  *
4177
6659
  * @see https://minus-ze.ro/posts/morphing-arbitrary-paths-in-svg/
@@ -4187,23 +6669,55 @@ const equalizeSegmentsDefaults = {
4187
6669
  * ```
4188
6670
  */
4189
6671
  const equalizeSegments = (path1, path2, initialCfg = {}) => {
4190
- const { close, mode, reverse, roundValues, target: initialTarget } = Object.assign(equalizeSegmentsDefaults, initialCfg);
4191
- let p1 = normalizePath(path1);
4192
- let p2 = normalizePath(path2);
4193
- fixPath(p1);
4194
- fixPath(p2);
4195
- let bothPoly = (isPolygonArray(p1) || isPolylineArray(p1)) && (isPolygonArray(p2) || isPolylineArray(p2));
4196
- if (bothPoly && mode === "auto") {
6672
+ const { align, close, mode, reverse, roundValues, strategy, target: initialTarget } = {
6673
+ ...equalizeSegmentsDefaults,
6674
+ ...initialCfg
6675
+ };
6676
+ const normalized1 = normalizePath(path1);
6677
+ const normalized2 = normalizePath(path2);
6678
+ const shouldClose = close ?? (isClosedPath(normalized1) || isClosedPath(normalized2));
6679
+ let p1 = fixPath(normalized1);
6680
+ let p2 = fixPath(normalized2);
6681
+ const bothPoly = (isPolygonArray(p1) || isPolylineArray(p1)) && (isPolygonArray(p2) || isPolylineArray(p2));
6682
+ const area1 = polygonArea(samplePolygon(p1));
6683
+ const area2 = polygonArea(samplePolygon(p2));
6684
+ if (reverse !== false && Math.sign(area1) !== Math.sign(area2)) {
6685
+ if (reverse === "auto") {
6686
+ const ends1 = getPathEnds(p1);
6687
+ const ends2 = getPathEnds(p2);
6688
+ if (getDistance(ends1.end, ends2.start) < getDistance(ends1.start, ends2.end)) p1 = reversePath(p1);
6689
+ else p2 = reversePath(p2);
6690
+ } else p2 = reversePath(p2);
6691
+ }
6692
+ if (strategy === "arcLength") {
6693
+ const resampleMode = mode === "curve" ? "curve" : mode === "line" ? "line" : bothPoly ? "line" : "curve";
6694
+ const source1 = resampleMode === "curve" ? pathToCurve(p1) : p1;
6695
+ const source2 = resampleMode === "curve" ? pathToCurve(p2) : p2;
6696
+ const table1 = buildPathLengthTable(source1);
6697
+ const table2 = buildPathLengthTable(source2);
6698
+ const count = getArcLengthCount(table1, table2, initialTarget);
6699
+ let equalP1 = resampleFromTable(table1, count, resampleMode);
6700
+ let equalP2 = resampleFromTable(table2, count, resampleMode);
6701
+ if (align !== false) equalP2 = getRotatedPath(equalP2, equalP1);
6702
+ if (typeof roundValues === "number" && roundValues !== 4) {
6703
+ equalP1 = roundPath(equalP1, roundValues);
6704
+ equalP2 = roundPath(equalP2, roundValues);
6705
+ }
6706
+ if (shouldClose) {
6707
+ equalP1.push(["Z"]);
6708
+ equalP2.push(["Z"]);
6709
+ }
6710
+ return [equalP1, equalP2];
6711
+ }
6712
+ let bothPolyline = bothPoly;
6713
+ if (bothPolyline && mode !== "curve") {
4197
6714
  p1 = pathToPolyline(p1);
4198
6715
  p2 = pathToPolyline(p2);
4199
6716
  } else {
4200
- bothPoly = false;
6717
+ bothPolyline = false;
4201
6718
  p1 = pathToCurve(p1);
4202
6719
  p2 = pathToCurve(p2);
4203
6720
  }
4204
- const area1 = polygonArea(samplePolygon(p1));
4205
- const area2 = polygonArea(samplePolygon(p2));
4206
- if (reverse !== false && Math.sign(area1) !== Math.sign(area2)) p2 = reversePath(p2);
4207
6721
  const segCount1 = p1.length;
4208
6722
  const segCount2 = p2.length;
4209
6723
  const minTarget = Math.max(segCount1, segCount2);
@@ -4217,19 +6731,19 @@ const equalizeSegments = (path1, path2, initialCfg = {}) => {
4217
6731
  else console.warn("equalizeSegments \"target\" option: " + initialTarget + ", expected >= " + minTarget);
4218
6732
  let equalP1 = p1;
4219
6733
  let equalP2 = p2;
4220
- if (bothPoly) {
6734
+ if (bothPolyline) {
4221
6735
  equalP1 = splitLinePathToCount(p1, target);
4222
6736
  equalP2 = splitLinePathToCount(p2, target);
4223
6737
  } else {
4224
6738
  equalP1 = splitCurvePathToCount(p1, target);
4225
6739
  equalP2 = splitCurvePathToCount(p2, target);
4226
6740
  }
4227
- equalP2 = getRotatedPath(equalP2, equalP1);
6741
+ if (align !== false) equalP2 = getRotatedPath(equalP2, equalP1);
4228
6742
  if (typeof roundValues === "number" && roundValues !== 4) {
4229
6743
  equalP1 = roundPath(equalP1, roundValues);
4230
6744
  equalP2 = roundPath(equalP2, roundValues);
4231
6745
  }
4232
- if (close) {
6746
+ if (shouldClose) {
4233
6747
  equalP1.push(["Z"]);
4234
6748
  equalP2.push(["Z"]);
4235
6749
  }
@@ -4347,47 +6861,47 @@ function getBestMatch(target, candidates) {
4347
6861
  return null;
4348
6862
  }
4349
6863
  /**
4350
- * Matches paths from two sets by proximity and size similarity.
4351
- * Unmatched paths receive placeholder paths at their centroid.
6864
+ * Matches path features by proximity and size similarity.
4352
6865
  *
4353
6866
  * @param fromPaths - Source path features to match from
4354
6867
  * @param toPaths - Target path features to match to
4355
- * @returns Array of paired NormalArrays [from, to]
6868
+ * @returns the matched pairs and the unmatched features
4356
6869
  */
4357
- function matchPaths(fromPaths, toPaths) {
6870
+ function matchPathFeatures(fromPaths, toPaths) {
6871
+ const from = [...fromPaths].sort((a, b) => b.size - a.size);
6872
+ const to = [...toPaths].sort((a, b) => b.size - a.size);
4358
6873
  const pairs = [];
4359
- fromPaths.sort((a, b) => b.size - a.size);
4360
- toPaths.sort((a, b) => b.size - a.size);
4361
- while (fromPaths.length > 0) {
4362
- const from = fromPaths.shift();
4363
- const bestTo = getBestMatch(from, toPaths);
4364
- if (bestTo) pairs.push([from.path, bestTo.path]);
4365
- else {
4366
- const fromCentroid = [from.bbox.cx, from.bbox.cy];
4367
- pairs.push([from.path, createPlaceholder(fromCentroid)]);
4368
- }
6874
+ const unmatchedFrom = [];
6875
+ while (from.length > 0) {
6876
+ const fromPath = from.shift();
6877
+ const bestTo = getBestMatch(fromPath, to);
6878
+ if (bestTo) pairs.push([fromPath, bestTo]);
6879
+ else unmatchedFrom.push(fromPath);
4369
6880
  }
4370
- while (toPaths.length > 0) {
4371
- const to = toPaths.shift();
4372
- const toCentroid = [to.bbox.cx, to.bbox.cy];
4373
- pairs.push([createPlaceholder(toCentroid), to.path]);
4374
- }
4375
- return pairs;
6881
+ return {
6882
+ pairs,
6883
+ unmatchedFrom,
6884
+ unmatchedTo: to
6885
+ };
4376
6886
  }
4377
6887
  // src/morph/classifyPaths.ts
4378
6888
  /**
4379
6889
  * Classifies paths into outer (containing) and inner (hole) paths.
4380
6890
  *
6891
+ * A path is an inner path when it is contained by another path of the
6892
+ * same set. The winding of a contour is not used for the classification:
6893
+ * the shoelace sign only tells the direction of the contour, and in the
6894
+ * SVG coordinate system (y pointing down) the usual outer contour has a
6895
+ * *negative* signed area.
6896
+ *
4381
6897
  * @param paths - Array of normalized path arrays to classify
4382
6898
  * @returns Object with `outers` (containing shapes) and `inners` (holes)
4383
6899
  */
4384
6900
  const classifyPaths = (paths) => {
4385
- const outers = [];
4386
- const inners = [];
4387
- for (const path of paths) {
6901
+ const features = paths.map((path) => {
4388
6902
  const signedArea = polygonArea(samplePolygon(path));
4389
6903
  const bbox = getPathBBox(path);
4390
- const feature = {
6904
+ return {
4391
6905
  isPoly: isPolygonArray(path) || isPolylineArray(path),
4392
6906
  size: bbox.width * bbox.height,
4393
6907
  path,
@@ -4395,9 +6909,16 @@ const classifyPaths = (paths) => {
4395
6909
  area: Math.abs(signedArea),
4396
6910
  bbox
4397
6911
  };
4398
- if (signedArea > 0) outers.push(feature);
4399
- else inners.push(feature);
4400
- }
6912
+ });
6913
+ const outers = [];
6914
+ const inners = [];
6915
+ for (const feature of features) if (features.some((other) => other !== feature && other.area > feature.area && isPointInsideBBox([
6916
+ other.bbox.x,
6917
+ other.bbox.y,
6918
+ other.bbox.x2,
6919
+ other.bbox.y2
6920
+ ], [feature.bbox.cx, feature.bbox.cy]))) inners.push(feature);
6921
+ else outers.push(feature);
4401
6922
  return {
4402
6923
  outers,
4403
6924
  inners
@@ -4406,18 +6927,34 @@ const classifyPaths = (paths) => {
4406
6927
  // src/morph/equalizePaths.ts
4407
6928
  const equalizePathsDefaults = {
4408
6929
  mode: "auto",
6930
+ strategy: "segment",
6931
+ align: true,
4409
6932
  roundValues: 4,
4410
- close: false,
4411
6933
  sampleSize: 10
4412
6934
  };
6935
+ const getPrimaryOuter = (outers) => {
6936
+ let primary;
6937
+ for (const outer of outers) if (!primary || outer.size > primary.size) primary = outer;
6938
+ return primary;
6939
+ };
6940
+ const getOuterDirection = (outers) => {
6941
+ const primary = getPrimaryOuter(outers);
6942
+ if (!primary) return 0;
6943
+ return Math.sign(getPathArea(primary.path));
6944
+ };
4413
6945
  /**
4414
6946
  * Equalizes two paths for morphing (single/multi subpath).
4415
6947
  *
6948
+ * Multi-subpath paths are reversed as whole paths, so an outer contour keeps
6949
+ * its relationship with its holes. Outer contours only match outer contours
6950
+ * and holes only match holes: an unmatched contour collapses at its own
6951
+ * centroid instead of taking the opposite fill role.
6952
+ *
4416
6953
  * @see https://minus-ze.ro/posts/morphing-arbitrary-paths-in-svg/
4417
6954
  * @param pathInput1 - First path string or PathArray
4418
6955
  * @param pathInput2 - Second path string or PathArray
4419
6956
  * @param initialCfg - Configuration options for equalization
4420
- * @returns Tuple of two equalized MorphPathArrays
6957
+ * @returns Tuple of two equalized PathArrays
4421
6958
  *
4422
6959
  * @example
4423
6960
  * ```ts
@@ -4426,26 +6963,61 @@ const equalizePathsDefaults = {
4426
6963
  * ```
4427
6964
  */
4428
6965
  const equalizePaths = (pathInput1, pathInput2, initialCfg = {}) => {
4429
- const cfg = Object.assign(equalizePathsDefaults, initialCfg);
6966
+ const cfg = {
6967
+ ...equalizePathsDefaults,
6968
+ ...initialCfg
6969
+ };
4430
6970
  const p1 = normalizePath(pathInput1);
4431
6971
  const p2 = normalizePath(pathInput2);
4432
6972
  const multi1 = isMultiPath(p1);
4433
6973
  const multi2 = isMultiPath(p2);
4434
6974
  if (!multi1 && !multi2) return equalizeSegments(p1, p2, cfg);
4435
- const globalArea1 = polygonArea(samplePolygon(p1));
4436
- const globalArea2 = polygonArea(samplePolygon(p2));
4437
6975
  let path1 = p1;
4438
6976
  let path2 = p2;
4439
- if (Math.sign(globalArea1) < 0) path1 = reversePath(path1);
4440
- if (Math.sign(globalArea2) < 0) path2 = reversePath(path2);
4441
- const multiPath1 = splitPath(path1);
4442
- const multiPath2 = splitPath(path2);
4443
- const { outers: outers1, inners: inners1 } = classifyPaths(multiPath1);
4444
- const { outers: outers2, inners: inners2 } = classifyPaths(multiPath2);
4445
- const outerPairs = matchPaths(outers1, outers2);
4446
- const innerPairs = matchPaths(inners1, inners2);
6977
+ let multiPath1 = splitPath(path1);
6978
+ let multiPath2 = splitPath(path2);
6979
+ let classified1 = classifyPaths(multiPath1);
6980
+ let classified2 = classifyPaths(multiPath2);
6981
+ if (cfg.reverse === void 0) {
6982
+ const globalArea1 = polygonArea(samplePolygon(p1));
6983
+ const globalArea2 = polygonArea(samplePolygon(p2));
6984
+ if (Math.sign(globalArea1) < 0) path1 = reversePath(path1);
6985
+ if (Math.sign(globalArea2) < 0) path2 = reversePath(path2);
6986
+ } else if (cfg.reverse === true || cfg.reverse === "auto") {
6987
+ const direction1 = getOuterDirection(classified1.outers);
6988
+ const direction2 = getOuterDirection(classified2.outers);
6989
+ if (direction1 && direction2 && direction1 !== direction2) {
6990
+ let reverseFirst = false;
6991
+ if (cfg.reverse === "auto") {
6992
+ const outer1 = getPrimaryOuter(classified1.outers);
6993
+ const outer2 = getPrimaryOuter(classified2.outers);
6994
+ const ends1 = getPathEnds(outer1.path);
6995
+ const ends2 = getPathEnds(outer2.path);
6996
+ reverseFirst = getDistance(ends1.end, ends2.start) < getDistance(ends1.start, ends2.end);
6997
+ }
6998
+ if (reverseFirst) path1 = reversePath(path1);
6999
+ else path2 = reversePath(path2);
7000
+ }
7001
+ }
7002
+ if (path1 !== p1 || path2 !== p2) {
7003
+ multiPath1 = splitPath(path1);
7004
+ multiPath2 = splitPath(path2);
7005
+ classified1 = classifyPaths(multiPath1);
7006
+ classified2 = classifyPaths(multiPath2);
7007
+ }
7008
+ const outerMatches = matchPathFeatures(classified1.outers, classified2.outers);
7009
+ const innerMatches = matchPathFeatures(classified1.inners, classified2.inners);
7010
+ const contourPairs = [...outerMatches.pairs, ...innerMatches.pairs].map(([from, to]) => [from.path, to.path]);
7011
+ for (const feature of [...outerMatches.unmatchedFrom, ...innerMatches.unmatchedFrom]) {
7012
+ const centroid = [feature.bbox.cx, feature.bbox.cy];
7013
+ contourPairs.push([feature.path, createPlaceholder(centroid)]);
7014
+ }
7015
+ for (const feature of [...outerMatches.unmatchedTo, ...innerMatches.unmatchedTo]) {
7016
+ const centroid = [feature.bbox.cx, feature.bbox.cy];
7017
+ contourPairs.push([createPlaceholder(centroid), feature.path]);
7018
+ }
4447
7019
  const equalizedPairs = [];
4448
- for (const [from, to] of [...outerPairs, ...innerPairs]) {
7020
+ for (const [from, to] of contourPairs) {
4449
7021
  const [eqFrom, eqTo] = equalizeSegments(from, to, {
4450
7022
  ...cfg,
4451
7023
  reverse: false
@@ -4454,6 +7026,86 @@ const equalizePaths = (pathInput1, pathInput2, initialCfg = {}) => {
4454
7026
  }
4455
7027
  return [equalizedPairs.map((p) => p[0]).flat(), equalizedPairs.map((p) => p[1]).flat()];
4456
7028
  };
7029
+ // src/morph/equalize.ts
7030
+ const equalizeDefaults = {
7031
+ points: "auto",
7032
+ strategy: "segment",
7033
+ align: true,
7034
+ reverse: "auto",
7035
+ mode: "auto",
7036
+ roundValues: 4
7037
+ };
7038
+ /**
7039
+ * Equalizes two paths for morphing.
7040
+ *
7041
+ * The two paths are brought to the same shape, so they can be morphed into
7042
+ * each other: they hold the same number of segments of the same type, their
7043
+ * winding is the same and their points are aligned.
7044
+ *
7045
+ * A path with a single sub-path is equalized on its own, a path with more
7046
+ * sub-paths is split into sub-paths, the sub-paths are matched by their
7047
+ * shape and every pair is equalized on its own. Multi-subpath paths are
7048
+ * reversed as whole paths, so an outer contour keeps its relationship with
7049
+ * its holes. Outer contours only match outer contours and holes only match
7050
+ * holes: an unmatched contour collapses at its own centroid instead of
7051
+ * taking the opposite fill role.
7052
+ *
7053
+ * The `strategy` option decides how the points of the paths are placed:
7054
+ * - `segment` splits the segments of the paths, so the points of the result
7055
+ * are the points of the paths;
7056
+ * - `arcLength` distributes the points of the result along the length of
7057
+ * the paths. The source segment boundaries and corners are points of the
7058
+ * result too when the requested count allows it, so the shape of the paths
7059
+ * keeps its vertices.
7060
+ *
7061
+ * The `points` option is the number of points of the result. The automatic
7062
+ * mode uses the number of points of the bigger path.
7063
+ *
7064
+ * The `reverse` option decides what happens when the two paths draw in
7065
+ * opposite directions: `true` reverses the second path, `false` leaves the
7066
+ * paths as they are and `auto` reverses the path that leaves the two paths
7067
+ * closest to each other.
7068
+ *
7069
+ * @see https://minus-ze.ro/posts/morphing-arbitrary-paths-in-svg/
7070
+ *
7071
+ * @param pathInput1 - First path string or PathArray
7072
+ * @param pathInput2 - Second path string or PathArray
7073
+ * @param initialCfg - Configuration options for equalization
7074
+ * @returns Tuple of two equalized PathArrays
7075
+ *
7076
+ * @example
7077
+ * ```ts
7078
+ * const [eq1, eq2] = equalize('M0 0L100 0L50 100Z', 'M0 0L100 0L100 100L0 100Z')
7079
+ * // eq1.length === eq2.length — ready for morphing
7080
+ * ```
7081
+ */
7082
+ const equalize = (pathInput1, pathInput2, initialCfg = {}) => {
7083
+ const { align, close, mode, points, reverse, roundValues, strategy } = {
7084
+ ...equalizeDefaults,
7085
+ ...initialCfg
7086
+ };
7087
+ if (typeof points === "number" && (!Number.isFinite(points) || points < 2)) throw new TypeError(`${error}: points must be a number greater than 1`);
7088
+ const p1 = normalizePath(pathInput1);
7089
+ const p2 = normalizePath(pathInput2);
7090
+ if (isMultiPath(p1) || isMultiPath(p2)) return equalizePaths(p1, p2, {
7091
+ align,
7092
+ close,
7093
+ mode,
7094
+ reverse,
7095
+ roundValues,
7096
+ strategy,
7097
+ target: typeof points === "number" ? points : void 0
7098
+ });
7099
+ return equalizeSegments(p1, p2, {
7100
+ align,
7101
+ close,
7102
+ mode,
7103
+ reverse,
7104
+ roundValues,
7105
+ strategy,
7106
+ target: typeof points === "number" ? points : void 0
7107
+ });
7108
+ };
4457
7109
  // src/intersect/interHelper.ts
4458
7110
  const intersect = (x1, y1, x2, y2, x3, y3, x4, y4) => {
4459
7111
  if (Math.max(x1, x2) < Math.min(x3, x4) || Math.min(x1, x2) > Math.max(x3, x4) || Math.max(y1, y2) < Math.min(y3, y4) || Math.min(y1, y2) > Math.max(y3, y4)) return;
@@ -4625,6 +7277,6 @@ const pathsIntersection = (pathInput1, pathInput2, justCount = true) => {
4625
7277
  }
4626
7278
  return justCount ? countResult : pointsResult;
4627
7279
  };
4628
- export { PathParser, absolutizeSegment, arcToCubic, arcTools, bezierTools, boundingBoxIntersect, cubicTools, DISTANCE_EPSILON as distanceEpsilon, distanceSquareRoot, equalizePaths, equalizeSegments, finalizeSegment, fixPath, getClosestPoint, getDrawDirection, getPathArea, getPathBBox, getPointAtLength, getPropertiesAtLength, getPropertiesAtPoint, getSVGMatrix, getSegmentAtLength, getSegmentOfPoint, getTotalLength, invalidPathValue, isAbsoluteArray, isArcCommand, isClosedPath, isCurveArray, isDigit, isDigitStart, isMoveCommand, isMultiPath, isNormalizedArray, isPathArray, isPathCommand, isPointInStroke, isPointInsideBBox, isPolygonArray, isPolylineArray, isRelativeArray, isSpace, isValidPath, iterate, lineToCubic, lineTools, midPoint, normalizePath, normalizeSegment, optimizePath, paramsCounts, paramsParser, parsePathString, pathToAbsolute, pathToCurve, pathToRelative, pathToString, pathsIntersection, polygonTools, projection2d, quadToCubic, quadTools, relativizeSegment, reverseCurve, reversePath, rotateVector, roundPath, roundSegment, roundTo, scanFlag, scanParam, scanSegment, segmentToCubic, shapeParams, shapeToPath, shapeToPathArray, shortenSegment, skipSpaces, splitCubicSegment, splitPath, transformPath };
7280
+ export { PathParser, absolutizeSegment, arcToCubic, arcTools, bezierTools, boundingBoxIntersect, cubicTools, DISTANCE_EPSILON as distanceEpsilon, distanceSquareRoot, equalize, equalizePaths, equalizeSegments, finalizeSegment, fixPath, getClosestPoint, getDrawDirection, getPathArea, getPathBBox, getPointAtLength, getPropertiesAtLength, getPropertiesAtPoint, getSVGMatrix, getSegmentAtLength, getSegmentOfPoint, getTotalLength, invalidPathValue, isAbsoluteArray, isArcCommand, isClosedPath, isCurveArray, isDigit, isDigitStart, isMoveCommand, isMultiPath, isNormalizedArray, isPathArray, isPathCommand, isPointInPath, isPointInStroke, isPointInsideBBox, isPolygonArray, isPolylineArray, isRelativeArray, isSpace, isValidPath, iterate, joinPath, lineToCubic, lineTools, midPoint, normalizePath, normalizeSegment, offsetPath, optimizePath, paramsCounts, paramsParser, parsePathString, pathToAbsolute, pathToCurve, pathToRelative, pathToString, pathsIntersection, polygonTools, projection2d, quadToCubic, quadTools, relativizeSegment, resamplePath, reverseCurve, reversePath, reverseSubPath, rotateVector, roundPath, roundSegment, roundTo, scanFlag, scanParam, scanSegment, segmentToCubic, shapeParams, shapeToPath, shapeToPathArray, shortenSegment, simplifyPath, skipSpaces, splitCubicSegment, splitPath, transformPath };
4629
7281
 
4630
7282
  //# sourceMappingURL=util.js.map