svg-path-commander 2.3.5 → 2.4.1

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