svg-path-commander 1.0.5 → 2.0.0-alpha2

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.
Files changed (131) hide show
  1. package/README.md +26 -4
  2. package/dist/svg-path-commander.cjs +2 -0
  3. package/dist/svg-path-commander.cjs.map +1 -0
  4. package/dist/svg-path-commander.d.ts +454 -0
  5. package/dist/svg-path-commander.js +2 -3762
  6. package/dist/svg-path-commander.js.map +1 -0
  7. package/dist/svg-path-commander.mjs +1194 -0
  8. package/dist/svg-path-commander.mjs.map +1 -0
  9. package/package.json +39 -42
  10. package/src/convert/pathToAbsolute.ts +101 -0
  11. package/src/convert/{pathToCurve.js → pathToCurve.ts} +12 -14
  12. package/src/convert/pathToRelative.ts +92 -0
  13. package/src/convert/pathToString.ts +17 -0
  14. package/src/{svg-path-commander.js → index.ts} +143 -66
  15. package/src/interface.ts +129 -0
  16. package/src/math/distanceSquareRoot.ts +13 -0
  17. package/src/math/midPoint.ts +16 -0
  18. package/src/math/{polygonArea.js → polygonArea.ts} +6 -4
  19. package/src/math/{polygonLength.js → polygonLength.ts} +5 -3
  20. package/src/math/rotateVector.ts +16 -0
  21. package/src/options/options.ts +9 -0
  22. package/src/parser/error.ts +2 -0
  23. package/src/parser/finalizeSegment.ts +31 -0
  24. package/src/parser/{invalidPathValue.js → invalidPathValue.ts} +0 -0
  25. package/src/parser/{isArcCommand.js → isArcCommand.ts} +5 -4
  26. package/src/parser/isDigit.ts +12 -0
  27. package/src/parser/isDigitStart.ts +14 -0
  28. package/src/parser/isPathCommand.ts +28 -0
  29. package/src/parser/isSpace.ts +23 -0
  30. package/src/parser/paramsCount.ts +16 -0
  31. package/src/parser/paramsParser.ts +14 -0
  32. package/src/parser/{parsePathString.js → parsePathString.ts} +13 -7
  33. package/src/parser/pathParser.ts +29 -0
  34. package/src/parser/{scanFlag.js → scanFlag.ts} +8 -5
  35. package/src/parser/{scanParam.js → scanParam.ts} +12 -11
  36. package/src/parser/{scanSegment.js → scanSegment.ts} +9 -5
  37. package/src/parser/{skipSpaces.js → skipSpaces.ts} +5 -3
  38. package/src/process/{arcToCubic.js → arcToCubic.ts} +42 -28
  39. package/src/process/fixArc.ts +23 -0
  40. package/src/process/getSVGMatrix.ts +70 -0
  41. package/src/process/lineToCubic.ts +17 -0
  42. package/src/process/{normalizePath.js → normalizePath.ts} +10 -10
  43. package/src/process/normalizeSegment.ts +47 -0
  44. package/src/process/{optimizePath.js → optimizePath.ts} +18 -21
  45. package/src/process/{projection2d.js → projection2d.ts} +16 -15
  46. package/src/process/quadToCubic.ts +31 -0
  47. package/src/process/reverseCurve.ts +21 -0
  48. package/src/process/reversePath.ts +101 -0
  49. package/src/process/roundPath.ts +29 -0
  50. package/src/process/segmentToCubic.ts +46 -0
  51. package/src/process/shortenSegment.ts +79 -0
  52. package/src/process/splitCubic.ts +28 -0
  53. package/src/process/{splitPath.js → splitPath.ts} +9 -8
  54. package/src/process/{transformPath.js → transformPath.ts} +55 -48
  55. package/src/types.ts +193 -0
  56. package/src/util/getClosestPoint.ts +15 -0
  57. package/src/util/{getDrawDirection.js → getDrawDirection.ts} +7 -4
  58. package/src/util/getPathArea.ts +70 -0
  59. package/src/util/{getPathBBox.js → getPathBBox.ts} +16 -5
  60. package/src/util/getPointAtLength.ts +14 -0
  61. package/src/util/{getPropertiesAtLength.js → getPropertiesAtLength.ts} +28 -19
  62. package/src/util/{getPropertiesAtPoint.js → getPropertiesAtPoint.ts} +16 -12
  63. package/src/util/getSegmentAtLength.ts +15 -0
  64. package/src/util/getSegmentOfPoint.ts +18 -0
  65. package/src/util/{getTotalLength.js → getTotalLength.ts} +6 -4
  66. package/src/util/isAbsoluteArray.ts +18 -0
  67. package/src/util/{isCurveArray.js → isCurveArray.ts} +6 -4
  68. package/src/util/{isNormalizedArray.js → isNormalizedArray.ts} +4 -2
  69. package/src/util/isPathArray.ts +19 -0
  70. package/src/util/isPointInStroke.ts +15 -0
  71. package/src/util/isRelativeArray.ts +18 -0
  72. package/src/util/{isValidPath.js → isValidPath.ts} +5 -4
  73. package/src/util/{pathLengthFactory.js → pathLengthFactory.ts} +38 -31
  74. package/src/util/{segmentArcFactory.js → segmentArcFactory.ts} +71 -55
  75. package/src/util/segmentCubicFactory.ts +114 -0
  76. package/src/util/{segmentLineFactory.js → segmentLineFactory.ts} +10 -8
  77. package/src/util/{segmentQuadFactory.js → segmentQuadFactory.ts} +47 -32
  78. package/src/util/shapeToPath.ts +214 -0
  79. package/dist/svg-path-commander.es5.js +0 -3875
  80. package/dist/svg-path-commander.es5.min.js +0 -2
  81. package/dist/svg-path-commander.esm.js +0 -3754
  82. package/dist/svg-path-commander.esm.min.js +0 -2
  83. package/dist/svg-path-commander.min.js +0 -2
  84. package/src/convert/pathToAbsolute.js +0 -86
  85. package/src/convert/pathToRelative.js +0 -84
  86. package/src/convert/pathToString.js +0 -14
  87. package/src/index.js +0 -10
  88. package/src/math/distanceSquareRoot.js +0 -14
  89. package/src/math/epsilon.js +0 -8
  90. package/src/math/midPoint.js +0 -13
  91. package/src/math/rotateVector.js +0 -14
  92. package/src/options/options.js +0 -10
  93. package/src/parser/error.js +0 -2
  94. package/src/parser/finalizeSegment.js +0 -28
  95. package/src/parser/isDigit.js +0 -9
  96. package/src/parser/isDigitStart.js +0 -13
  97. package/src/parser/isPathCommand.js +0 -25
  98. package/src/parser/isSpace.js +0 -16
  99. package/src/parser/paramsCount.js +0 -9
  100. package/src/parser/paramsParser.js +0 -8
  101. package/src/parser/pathParser.js +0 -24
  102. package/src/process/clonePath.js +0 -9
  103. package/src/process/fixArc.js +0 -21
  104. package/src/process/fixPath.js +0 -31
  105. package/src/process/getSVGMatrix.js +0 -61
  106. package/src/process/lineToCubic.js +0 -30
  107. package/src/process/normalizeSegment.js +0 -45
  108. package/src/process/quadToCubic.js +0 -22
  109. package/src/process/reverseCurve.js +0 -18
  110. package/src/process/reversePath.js +0 -89
  111. package/src/process/roundPath.js +0 -26
  112. package/src/process/segmentToCubic.js +0 -46
  113. package/src/process/shortenSegment.js +0 -58
  114. package/src/process/splitCubic.js +0 -26
  115. package/src/util/getClosestPoint.js +0 -12
  116. package/src/util/getPathArea.js +0 -47
  117. package/src/util/getPointAtLength.js +0 -12
  118. package/src/util/getSegmentAtLength.js +0 -11
  119. package/src/util/getSegmentOfPoint.js +0 -12
  120. package/src/util/isAbsoluteArray.js +0 -14
  121. package/src/util/isPathArray.js +0 -14
  122. package/src/util/isPointInStroke.js +0 -13
  123. package/src/util/isRelativeArray.js +0 -14
  124. package/src/util/segmentCubicFactory.js +0 -97
  125. package/src/util/shapeToPath.js +0 -204
  126. package/src/util/util.js +0 -82
  127. package/src/version.js +0 -8
  128. package/types/index.d.ts +0 -120
  129. package/types/more/modules.ts +0 -82
  130. package/types/more/svg.d.ts +0 -211
  131. package/types/svg-path-commander.d.ts +0 -1089
@@ -1,3754 +0,0 @@
1
- /*!
2
- * SVGPathCommander v1.0.5 (http://thednp.github.io/svg-path-commander)
3
- * Copyright 2022 © thednp
4
- * Licensed under MIT (https://github.com/thednp/svg-path-commander/blob/master/LICENSE)
5
- */
6
- /**
7
- * SVGPathCommander default options
8
- * @type {SVGPath.options}
9
- */
10
- const defaultOptions = {
11
- origin: [0, 0, 0],
12
- round: 4,
13
- };
14
-
15
- /**
16
- * Segment params length
17
- * @type {Record<string, number>}
18
- */
19
- const paramsCount = {
20
- a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0,
21
- };
22
-
23
- /**
24
- * Breaks the parsing of a pathString once a segment is finalized.
25
- *
26
- * @param {SVGPath.PathParser} path the `PathParser` instance
27
- */
28
- function finalizeSegment(path) {
29
- let pathCommand = path.pathValue[path.segmentStart];
30
- let LK = pathCommand.toLowerCase();
31
- const { data } = path;
32
-
33
- while (data.length >= paramsCount[LK]) {
34
- // overloaded `moveTo`
35
- // https://github.com/rveciana/svg-path-properties/blob/master/src/parse.ts
36
- if (LK === 'm' && data.length > 2) {
37
- path.segments.push([pathCommand, ...data.splice(0, 2)]);
38
- LK = 'l';
39
- pathCommand = pathCommand === 'm' ? 'l' : 'L';
40
- } else {
41
- path.segments.push([pathCommand, ...data.splice(0, paramsCount[LK])]);
42
- }
43
-
44
- if (!paramsCount[LK]) {
45
- break;
46
- }
47
- }
48
- }
49
-
50
- const error = 'SVGPathCommander error';
51
-
52
- /**
53
- * Validates an A (arc-to) specific path command value.
54
- * Usually a `large-arc-flag` or `sweep-flag`.
55
- *
56
- * @param {SVGPath.PathParser} path the `PathParser` instance
57
- */
58
- function scanFlag(path) {
59
- const { index, pathValue } = path;
60
- const code = pathValue.charCodeAt(index);
61
-
62
- if (code === 0x30/* 0 */) {
63
- path.param = 0;
64
- path.index += 1;
65
- return;
66
- }
67
-
68
- if (code === 0x31/* 1 */) {
69
- path.param = 1;
70
- path.index += 1;
71
- return;
72
- }
73
-
74
- path.err = `${error}: invalid Arc flag "${pathValue[index]}", expecting 0 or 1 at index ${index}`;
75
- }
76
-
77
- /**
78
- * Checks if a character is a digit.
79
- *
80
- * @param {number} code the character to check
81
- * @returns {boolean} check result
82
- */
83
- function isDigit(code) {
84
- return (code >= 48 && code <= 57); // 0..9
85
- }
86
-
87
- const invalidPathValue = 'Invalid path value';
88
-
89
- /**
90
- * Validates every character of the path string,
91
- * every path command, negative numbers or floating point numbers.
92
- *
93
- * @param {SVGPath.PathParser} path the `PathParser` instance
94
- */
95
- function scanParam(path) {
96
- const { max, pathValue, index: start } = path;
97
- let index = start;
98
- let zeroFirst = false;
99
- let hasCeiling = false;
100
- let hasDecimal = false;
101
- let hasDot = false;
102
- let ch;
103
-
104
- if (index >= max) {
105
- // path.err = 'SvgPath: missed param (at pos ' + index + ')';
106
- path.err = `${error}: ${invalidPathValue} at index ${index}, "pathValue" is missing param`;
107
- return;
108
- }
109
- ch = pathValue.charCodeAt(index);
110
-
111
- if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
112
- index += 1;
113
- // ch = (index < max) ? pathValue.charCodeAt(index) : 0;
114
- ch = pathValue.charCodeAt(index);
115
- }
116
-
117
- // This logic is shamelessly borrowed from Esprima
118
- // https://github.com/ariya/esprimas
119
- if (!isDigit(ch) && ch !== 0x2E/* . */) {
120
- // path.err = 'SvgPath: param should start with 0..9 or `.` (at pos ' + index + ')';
121
- path.err = `${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" is not a number`;
122
- return;
123
- }
124
-
125
- if (ch !== 0x2E/* . */) {
126
- zeroFirst = (ch === 0x30/* 0 */);
127
- index += 1;
128
-
129
- ch = pathValue.charCodeAt(index);
130
-
131
- if (zeroFirst && index < max) {
132
- // decimal number starts with '0' such as '09' is illegal.
133
- if (ch && isDigit(ch)) {
134
- // path.err = 'SvgPath: numbers started with `0` such as `09`
135
- // are illegal (at pos ' + start + ')';
136
- path.err = `${error}: ${invalidPathValue} at index ${start}, "${pathValue[start]}" illegal number`;
137
- return;
138
- }
139
- }
140
-
141
- while (index < max && isDigit(pathValue.charCodeAt(index))) {
142
- index += 1;
143
- hasCeiling = true;
144
- }
145
-
146
- ch = pathValue.charCodeAt(index);
147
- }
148
-
149
- if (ch === 0x2E/* . */) {
150
- hasDot = true;
151
- index += 1;
152
- while (isDigit(pathValue.charCodeAt(index))) {
153
- index += 1;
154
- hasDecimal = true;
155
- }
156
-
157
- ch = pathValue.charCodeAt(index);
158
- }
159
-
160
- if (ch === 0x65/* e */ || ch === 0x45/* E */) {
161
- if (hasDot && !hasCeiling && !hasDecimal) {
162
- path.err = `${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" invalid float exponent`;
163
- return;
164
- }
165
-
166
- index += 1;
167
-
168
- ch = pathValue.charCodeAt(index);
169
-
170
- if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
171
- index += 1;
172
- }
173
- if (index < max && isDigit(pathValue.charCodeAt(index))) {
174
- while (index < max && isDigit(pathValue.charCodeAt(index))) {
175
- index += 1;
176
- }
177
- } else {
178
- path.err = `${error}: ${invalidPathValue} at index ${index}, "${pathValue[index]}" invalid integer exponent`;
179
- return;
180
- }
181
- }
182
-
183
- path.index = index;
184
- path.param = +path.pathValue.slice(start, index);
185
- }
186
-
187
- /**
188
- * Checks if the character is a space.
189
- *
190
- * @param {number} ch the character to check
191
- * @returns {boolean} check result
192
- */
193
- function isSpace(ch) {
194
- const specialSpaces = [
195
- 0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006,
196
- 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF];
197
- /* istanbul ignore next */
198
- return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029) // Line terminators
199
- // White spaces
200
- || (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0)
201
- || (ch >= 0x1680 && specialSpaces.includes(ch));
202
- }
203
-
204
- /**
205
- * Points the parser to the next character in the
206
- * path string every time it encounters any kind of
207
- * space character.
208
- *
209
- * @param {SVGPath.PathParser} path the `PathParser` instance
210
- */
211
- function skipSpaces(path) {
212
- const { pathValue, max } = path;
213
- while (path.index < max && isSpace(pathValue.charCodeAt(path.index))) {
214
- path.index += 1;
215
- }
216
- }
217
-
218
- /**
219
- * Checks if the character is a path command.
220
- *
221
- * @param {any} code the character to check
222
- * @returns {boolean} check result
223
- */
224
- function isPathCommand(code) {
225
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy
226
- switch (code | 0x20) {
227
- case 0x6D/* m */:
228
- case 0x7A/* z */:
229
- case 0x6C/* l */:
230
- case 0x68/* h */:
231
- case 0x76/* v */:
232
- case 0x63/* c */:
233
- case 0x73/* s */:
234
- case 0x71/* q */:
235
- case 0x74/* t */:
236
- case 0x61/* a */:
237
- // case 0x72/* r */:
238
- return true;
239
- default:
240
- return false;
241
- }
242
- }
243
-
244
- /**
245
- * Checks if the character is or belongs to a number.
246
- * [0-9]|+|-|.
247
- *
248
- * @param {number} code the character to check
249
- * @returns {boolean} check result
250
- */
251
- function isDigitStart(code) {
252
- return (code >= 48 && code <= 57) /* 0..9 */
253
- || code === 0x2B /* + */
254
- || code === 0x2D /* - */
255
- || code === 0x2E; /* . */
256
- }
257
-
258
- /**
259
- * Checks if the character is an A (arc-to) path command.
260
- *
261
- * @param {number} code the character to check
262
- * @returns {boolean} check result
263
- */
264
- function isArcCommand(code) {
265
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy
266
- return (code | 0x20) === 0x61;
267
- }
268
-
269
- /**
270
- * Scans every character in the path string to determine
271
- * where a segment starts and where it ends.
272
- *
273
- * @param {SVGPath.PathParser} path the `PathParser` instance
274
- */
275
- function scanSegment(path) {
276
- const { max, pathValue, index } = path;
277
- const cmdCode = pathValue.charCodeAt(index);
278
- const reqParams = paramsCount[pathValue[index].toLowerCase()];
279
-
280
- path.segmentStart = index;
281
-
282
- if (!isPathCommand(cmdCode)) {
283
- path.err = `${error}: ${invalidPathValue} "${pathValue[index]}" is not a path command`;
284
- return;
285
- }
286
-
287
- path.index += 1;
288
- skipSpaces(path);
289
-
290
- path.data = [];
291
-
292
- if (!reqParams) {
293
- // Z
294
- finalizeSegment(path);
295
- return;
296
- }
297
-
298
- for (;;) {
299
- for (let i = reqParams; i > 0; i -= 1) {
300
- if (isArcCommand(cmdCode) && (i === 3 || i === 4)) scanFlag(path);
301
- else scanParam(path);
302
-
303
- if (path.err.length) {
304
- return;
305
- }
306
- path.data.push(path.param);
307
-
308
- skipSpaces(path);
309
-
310
- // after ',' param is mandatory
311
- if (path.index < max && pathValue.charCodeAt(path.index) === 0x2C/* , */) {
312
- path.index += 1;
313
- skipSpaces(path);
314
- }
315
- }
316
-
317
- if (path.index >= path.max) {
318
- break;
319
- }
320
-
321
- // Stop on next segment
322
- if (!isDigitStart(pathValue.charCodeAt(path.index))) {
323
- break;
324
- }
325
- }
326
-
327
- finalizeSegment(path);
328
- }
329
-
330
- /**
331
- * Returns a clone of an existing `pathArray`.
332
- *
333
- * @param {SVGPath.pathArray | SVGPath.pathSegment} path the source `pathArray`
334
- * @returns {any} the cloned `pathArray`
335
- */
336
- function clonePath(path) {
337
- return path.map((x) => (Array.isArray(x) ? [...x] : x));
338
- }
339
-
340
- /**
341
- * The `PathParser` is used by the `parsePathString` static method
342
- * to generate a `pathArray`.
343
- *
344
- * @param {string} pathString
345
- */
346
- function PathParser(pathString) {
347
- /** @type {SVGPath.pathArray} */
348
- this.segments = [];
349
- /** @type {string} */
350
- this.pathValue = pathString;
351
- /** @type {number} */
352
- this.max = pathString.length;
353
- /** @type {number} */
354
- this.index = 0;
355
- /** @type {number} */
356
- this.param = 0.0;
357
- /** @type {number} */
358
- this.segmentStart = 0;
359
- /** @type {any} */
360
- this.data = [];
361
- /** @type {string} */
362
- this.err = '';
363
- }
364
-
365
- /**
366
- * Iterates an array to check if it's an actual `pathArray`.
367
- *
368
- * @param {string | SVGPath.pathArray} path the `pathArray` to be checked
369
- * @returns {boolean} iteration result
370
- */
371
- function isPathArray(path) {
372
- return Array.isArray(path) && path.every((seg) => {
373
- const lk = seg[0].toLowerCase();
374
- return paramsCount[lk] === seg.length - 1 && 'achlmqstvz'.includes(lk);
375
- });
376
- }
377
-
378
- /**
379
- * Parses a path string value and returns an array
380
- * of segments we like to call `pathArray`.
381
- *
382
- * @param {SVGPath.pathArray | string} pathInput the string to be parsed
383
- * @returns {SVGPath.pathArray | string} the resulted `pathArray` or error string
384
- */
385
- function parsePathString(pathInput) {
386
- if (isPathArray(pathInput)) {
387
- return clonePath(pathInput);
388
- }
389
-
390
- const path = new PathParser(pathInput);
391
-
392
- skipSpaces(path);
393
-
394
- while (path.index < path.max && !path.err.length) {
395
- scanSegment(path);
396
- }
397
-
398
- return path.err ? path.err : path.segments;
399
- }
400
-
401
- /**
402
- * Iterates an array to check if it's a `pathArray`
403
- * with all absolute values.
404
- *
405
- * @param {string | SVGPath.pathArray} path the `pathArray` to be checked
406
- * @returns {boolean} iteration result
407
- */
408
- function isAbsoluteArray(path) {
409
- return isPathArray(path)
410
- // `isPathArray` also checks if it's `Array`
411
- && path.every(([x]) => x === x.toUpperCase());
412
- }
413
-
414
- /**
415
- * Parses a path string value or object and returns an array
416
- * of segments, all converted to absolute values.
417
- *
418
- * @param {string | SVGPath.pathArray} pathInput the path string | object
419
- * @returns {SVGPath.absoluteArray} the resulted `pathArray` with absolute values
420
- */
421
- function pathToAbsolute(pathInput) {
422
- /* istanbul ignore else */
423
- if (isAbsoluteArray(pathInput)) {
424
- // `isAbsoluteArray` checks if it's `pathArray`
425
- return clonePath(pathInput);
426
- }
427
-
428
- const path = parsePathString(pathInput);
429
- let x = 0; let y = 0;
430
- let mx = 0; let my = 0;
431
-
432
- // the `absoluteSegment[]` is for sure an `absolutePath`
433
- return path.map((segment) => {
434
- const values = segment.slice(1).map(Number);
435
- const [pathCommand] = segment;
436
- /** @type {SVGPath.absoluteCommand} */
437
- const absCommand = pathCommand.toUpperCase();
438
-
439
- if (pathCommand === 'M') {
440
- [x, y] = values;
441
- mx = x;
442
- my = y;
443
- return ['M', x, y];
444
- }
445
- /** @type {SVGPath.absoluteSegment} */
446
- let absoluteSegment = [];
447
-
448
- if (pathCommand !== absCommand) {
449
- switch (absCommand) {
450
- case 'A':
451
- absoluteSegment = [
452
- absCommand, values[0], values[1], values[2],
453
- values[3], values[4], values[5] + x, values[6] + y];
454
- break;
455
- case 'V':
456
- absoluteSegment = [absCommand, values[0] + y];
457
- break;
458
- case 'H':
459
- absoluteSegment = [absCommand, values[0] + x];
460
- break;
461
- default: {
462
- // use brakets for `eslint: no-case-declaration`
463
- // https://stackoverflow.com/a/50753272/803358
464
- const absValues = values.map((n, j) => n + (j % 2 ? y : x));
465
- // for n, l, c, s, q, t
466
- absoluteSegment = [absCommand, ...absValues];
467
- }
468
- }
469
- } else {
470
- absoluteSegment = [absCommand, ...values];
471
- }
472
-
473
- const segLength = absoluteSegment.length;
474
- switch (absCommand) {
475
- case 'Z':
476
- x = mx;
477
- y = my;
478
- break;
479
- case 'H':
480
- [, x] = absoluteSegment;
481
- break;
482
- case 'V':
483
- [, y] = absoluteSegment;
484
- break;
485
- default:
486
- x = absoluteSegment[segLength - 2];
487
- y = absoluteSegment[segLength - 1];
488
-
489
- if (absCommand === 'M') {
490
- mx = x;
491
- my = y;
492
- }
493
- }
494
- return absoluteSegment;
495
- });
496
- }
497
-
498
- /**
499
- * Iterates an array to check if it's a `pathArray`
500
- * with relative values.
501
- *
502
- * @param {string | SVGPath.pathArray} path the `pathArray` to be checked
503
- * @returns {boolean} iteration result
504
- */
505
- function isRelativeArray(path) {
506
- return isPathArray(path)
507
- // `isPathArray` checks if it's `Array`
508
- && path.slice(1).every(([pc]) => pc === pc.toLowerCase());
509
- }
510
-
511
- /**
512
- * Parses a path string value or object and returns an array
513
- * of segments, all converted to relative values.
514
- *
515
- * @param {string | SVGPath.pathArray} pathInput the path string | object
516
- * @returns {SVGPath.relativeArray} the resulted `pathArray` with relative values
517
- */
518
- function pathToRelative(pathInput) {
519
- /* istanbul ignore else */
520
- if (isRelativeArray(pathInput)) {
521
- return clonePath(pathInput);
522
- }
523
-
524
- const path = parsePathString(pathInput);
525
- let x = 0; let y = 0;
526
- let mx = 0; let my = 0;
527
-
528
- return path.map((segment) => {
529
- const values = segment.slice(1).map(Number);
530
- const [pathCommand] = segment;
531
- /** @type {SVGPath.relativeCommand} */
532
- const relativeCommand = pathCommand.toLowerCase();
533
-
534
- if (pathCommand === 'M') {
535
- [x, y] = values;
536
- mx = x;
537
- my = y;
538
- return ['M', x, y];
539
- }
540
-
541
- /** @type {SVGPath.relativeSegment} */
542
- let relativeSegment = [];
543
-
544
- if (pathCommand !== relativeCommand) {
545
- switch (relativeCommand) {
546
- case 'a':
547
- relativeSegment = [
548
- relativeCommand, values[0], values[1], values[2],
549
- values[3], values[4], values[5] - x, values[6] - y];
550
- break;
551
- case 'v':
552
- relativeSegment = [relativeCommand, values[0] - y];
553
- break;
554
- case 'h':
555
- relativeSegment = [relativeCommand, values[0] - x];
556
- break;
557
- default: {
558
- // use brakets for `eslint: no-case-declaration`
559
- // https://stackoverflow.com/a/50753272/803358
560
- const relValues = values.map((n, j) => n - (j % 2 ? y : x));
561
- relativeSegment = [relativeCommand, ...relValues];
562
- }
563
- }
564
- } else {
565
- if (pathCommand === 'm') {
566
- mx = values[0] + x;
567
- my = values[1] + y;
568
- }
569
- relativeSegment = [relativeCommand, ...values];
570
- }
571
-
572
- const segLength = relativeSegment.length;
573
- switch (relativeCommand) {
574
- case 'z':
575
- x = mx;
576
- y = my;
577
- break;
578
- case 'h':
579
- x += relativeSegment[1];
580
- break;
581
- case 'v':
582
- y += relativeSegment[1];
583
- break;
584
- default:
585
- x += relativeSegment[segLength - 2];
586
- y += relativeSegment[segLength - 1];
587
- }
588
- return relativeSegment;
589
- });
590
- }
591
-
592
- /**
593
- * Splits an extended A (arc-to) segment into two cubic-bezier segments.
594
- *
595
- * @param {SVGPath.pathArray} path the `pathArray` this segment belongs to
596
- * @param {string[]} allPathCommands all previous path commands
597
- * @param {number} i the segment index
598
- */
599
-
600
- function fixArc(path, allPathCommands, i) {
601
- if (path[i].length > 7) {
602
- path[i].shift();
603
- const segment = path[i];
604
- let ni = i; // ESLint
605
- while (segment.length) {
606
- // if created multiple C:s, their original seg is saved
607
- allPathCommands[i] = 'A';
608
- path.splice(ni += 1, 0, ['C', ...segment.splice(0, 6)]);
609
- }
610
- path.splice(i, 1);
611
- }
612
- }
613
-
614
- /**
615
- * Iterates an array to check if it's a `pathArray`
616
- * with all segments are in non-shorthand notation
617
- * with absolute values.
618
- *
619
- * @param {string | SVGPath.pathArray} path the `pathArray` to be checked
620
- * @returns {boolean} iteration result
621
- */
622
- function isNormalizedArray(path) {
623
- // `isAbsoluteArray` also checks if it's `Array`
624
- return isAbsoluteArray(path) && path.every(([pc]) => 'ACLMQZ'.includes(pc));
625
- }
626
-
627
- /**
628
- * Iterates an array to check if it's a `pathArray`
629
- * with all C (cubic bezier) segments.
630
- *
631
- * @param {string | SVGPath.pathArray} path the `Array` to be checked
632
- * @returns {boolean} iteration result
633
- */
634
- function isCurveArray(path) {
635
- // `isPathArray` also checks if it's `Array`
636
- return isNormalizedArray(path) && path.every(([pc]) => 'MC'.includes(pc));
637
- }
638
-
639
- /**
640
- * Normalizes a single segment of a `pathArray` object.
641
- *
642
- * @param {SVGPath.pathSegment} segment the segment object
643
- * @param {any} params the coordinates of the previous segment
644
- * @returns {SVGPath.normalSegment} the normalized segment
645
- */
646
- function normalizeSegment(segment, params) {
647
- const [pathCommand] = segment;
648
- const {
649
- x1: px1, y1: py1, x2: px2, y2: py2,
650
- } = params;
651
- const values = segment.slice(1).map(Number);
652
- let result = segment;
653
-
654
- if (!'TQ'.includes(pathCommand)) {
655
- // optional but good to be cautious
656
- params.qx = null;
657
- params.qy = null;
658
- }
659
-
660
- if (pathCommand === 'H') {
661
- result = ['L', segment[1], py1];
662
- } else if (pathCommand === 'V') {
663
- result = ['L', px1, segment[1]];
664
- } else if (pathCommand === 'S') {
665
- const x1 = px1 * 2 - px2;
666
- const y1 = py1 * 2 - py2;
667
- params.x1 = x1;
668
- params.y1 = y1;
669
- result = ['C', x1, y1, ...values];
670
- } else if (pathCommand === 'T') {
671
- const qx = px1 * 2 - params.qx;
672
- const qy = py1 * 2 - params.qy;
673
- params.qx = qx;
674
- params.qy = qy;
675
- result = ['Q', qx, qy, ...values];
676
- } else if (pathCommand === 'Q') {
677
- const [nqx, nqy] = values;
678
- params.qx = nqx;
679
- params.qy = nqy;
680
- }
681
-
682
- return result;
683
- }
684
-
685
- /**
686
- * @type {SVGPath.parserParams}
687
- */
688
- const paramsParser = {
689
- x1: 0, y1: 0, x2: 0, y2: 0, x: 0, y: 0, qx: null, qy: null,
690
- };
691
-
692
- /**
693
- * Normalizes a `path` object for further processing:
694
- * * convert segments to absolute values
695
- * * convert shorthand path commands to their non-shorthand notation
696
- *
697
- * @param {string | SVGPath.pathArray} pathInput the string to be parsed or 'pathArray'
698
- * @returns {SVGPath.normalArray} the normalized `pathArray`
699
- */
700
- function normalizePath(pathInput) {
701
- if (isNormalizedArray(pathInput)) {
702
- return clonePath(pathInput);
703
- }
704
-
705
- /** @type {SVGPath.normalArray} */
706
- const path = pathToAbsolute(pathInput);
707
- const params = { ...paramsParser };
708
- const allPathCommands = [];
709
- const ii = path.length;
710
- let pathCommand = '';
711
-
712
- for (let i = 0; i < ii; i += 1) {
713
- [pathCommand] = path[i];
714
-
715
- // Save current path command
716
- allPathCommands[i] = pathCommand;
717
- path[i] = normalizeSegment(path[i], params);
718
-
719
- const segment = path[i];
720
- const seglen = segment.length;
721
-
722
- params.x1 = +segment[seglen - 2];
723
- params.y1 = +segment[seglen - 1];
724
- params.x2 = +(segment[seglen - 4]) || params.x1;
725
- params.y2 = +(segment[seglen - 3]) || params.y1;
726
- }
727
-
728
- return path;
729
- }
730
-
731
- /**
732
- * Returns an {x,y} vector rotated by a given
733
- * angle in radian.
734
- *
735
- * @param {number} x the initial vector x
736
- * @param {number} y the initial vector y
737
- * @param {number} rad the radian vector angle
738
- * @returns {{x: number, y: number}} the rotated vector
739
- */
740
- function rotateVector(x, y, rad) {
741
- const X = x * Math.cos(rad) - y * Math.sin(rad);
742
- const Y = x * Math.sin(rad) + y * Math.cos(rad);
743
- return { x: X, y: Y };
744
- }
745
-
746
- /**
747
- * Converts A (arc-to) segments to C (cubic-bezier-to).
748
- *
749
- * For more information of where this math came from visit:
750
- * http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
751
- *
752
- * @param {number} X1 the starting x position
753
- * @param {number} Y1 the starting y position
754
- * @param {number} RX x-radius of the arc
755
- * @param {number} RY y-radius of the arc
756
- * @param {number} angle x-axis-rotation of the arc
757
- * @param {number} LAF large-arc-flag of the arc
758
- * @param {number} SF sweep-flag of the arc
759
- * @param {number} X2 the ending x position
760
- * @param {number} Y2 the ending y position
761
- * @param {number[]=} recursive the parameters needed to split arc into 2 segments
762
- * @return {number[]} the resulting cubic-bezier segment(s)
763
- */
764
- function arcToCubic(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, recursive) {
765
- let x1 = X1; let y1 = Y1; let rx = RX; let ry = RY; let x2 = X2; let y2 = Y2;
766
- // for more information of where this Math came from visit:
767
- // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
768
- const d120 = (Math.PI * 120) / 180;
769
-
770
- const rad = (Math.PI / 180) * (+angle || 0);
771
- /** @type {number[]} */
772
- let res = [];
773
- let xy;
774
- let f1;
775
- let f2;
776
- let cx;
777
- let cy;
778
-
779
- if (!recursive) {
780
- xy = rotateVector(x1, y1, -rad);
781
- x1 = xy.x;
782
- y1 = xy.y;
783
- xy = rotateVector(x2, y2, -rad);
784
- x2 = xy.x;
785
- y2 = xy.y;
786
-
787
- const x = (x1 - x2) / 2;
788
- const y = (y1 - y2) / 2;
789
- let h = (x * x) / (rx * rx) + (y * y) / (ry * ry);
790
- if (h > 1) {
791
- h = Math.sqrt(h);
792
- rx *= h;
793
- ry *= h;
794
- }
795
- const rx2 = rx * rx;
796
- const ry2 = ry * ry;
797
-
798
- const k = (LAF === SF ? -1 : 1)
799
- * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x)
800
- / (rx2 * y * y + ry2 * x * x)));
801
-
802
- cx = ((k * rx * y) / ry) + ((x1 + x2) / 2);
803
- cy = ((k * -ry * x) / rx) + ((y1 + y2) / 2);
804
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
805
- f1 = Math.asin((((y1 - cy) / ry) * (10 ** 9) >> 0) / (10 ** 9));
806
- // eslint-disable-next-line no-bitwise -- Impossible to satisfy no-bitwise
807
- f2 = Math.asin((((y2 - cy) / ry) * (10 ** 9) >> 0) / (10 ** 9));
808
-
809
- f1 = x1 < cx ? Math.PI - f1 : f1;
810
- f2 = x2 < cx ? Math.PI - f2 : f2;
811
- if (f1 < 0) (f1 = Math.PI * 2 + f1);
812
- if (f2 < 0) (f2 = Math.PI * 2 + f2);
813
- if (SF && f1 > f2) {
814
- f1 -= Math.PI * 2;
815
- }
816
- if (!SF && f2 > f1) {
817
- f2 -= Math.PI * 2;
818
- }
819
- } else {
820
- [f1, f2, cx, cy] = recursive;
821
- }
822
- let df = f2 - f1;
823
- if (Math.abs(df) > d120) {
824
- const f2old = f2;
825
- const x2old = x2;
826
- const y2old = y2;
827
- f2 = f1 + d120 * (SF && f2 > f1 ? 1 : -1);
828
- x2 = cx + rx * Math.cos(f2);
829
- y2 = cy + ry * Math.sin(f2);
830
- res = arcToCubic(x2, y2, rx, ry, angle, 0, SF, x2old, y2old, [f2, f2old, cx, cy]);
831
- }
832
- df = f2 - f1;
833
- const c1 = Math.cos(f1);
834
- const s1 = Math.sin(f1);
835
- const c2 = Math.cos(f2);
836
- const s2 = Math.sin(f2);
837
- const t = Math.tan(df / 4);
838
- const hx = (4 / 3) * rx * t;
839
- const hy = (4 / 3) * ry * t;
840
- const m1 = [x1, y1];
841
- const m2 = [x1 + hx * s1, y1 - hy * c1];
842
- const m3 = [x2 + hx * s2, y2 - hy * c2];
843
- const m4 = [x2, y2];
844
- m2[0] = 2 * m1[0] - m2[0];
845
- m2[1] = 2 * m1[1] - m2[1];
846
- if (recursive) {
847
- return [...m2, ...m3, ...m4, ...res];
848
- }
849
- res = [...m2, ...m3, ...m4, ...res];
850
- const newres = [];
851
- for (let i = 0, ii = res.length; i < ii; i += 1) {
852
- newres[i] = i % 2
853
- ? rotateVector(res[i - 1], res[i], rad).y
854
- : rotateVector(res[i], res[i + 1], rad).x;
855
- }
856
- return newres;
857
- }
858
-
859
- /**
860
- * Converts a Q (quadratic-bezier) segment to C (cubic-bezier).
861
- *
862
- * @param {number} x1 curve start x
863
- * @param {number} y1 curve start y
864
- * @param {number} qx control point x
865
- * @param {number} qy control point y
866
- * @param {number} x2 curve end x
867
- * @param {number} y2 curve end y
868
- * @returns {number[]} the cubic-bezier segment
869
- */
870
- function quadToCubic(x1, y1, qx, qy, x2, y2) {
871
- const r13 = 1 / 3;
872
- const r23 = 2 / 3;
873
- return [
874
- r13 * x1 + r23 * qx, // cpx1
875
- r13 * y1 + r23 * qy, // cpy1
876
- r13 * x2 + r23 * qx, // cpx2
877
- r13 * y2 + r23 * qy, // cpy2
878
- x2, y2, // x,y
879
- ];
880
- }
881
-
882
- /**
883
- * Returns the coordinates of a specified distance
884
- * ratio between two points.
885
- *
886
- * @param {[number, number]} a the first point coordinates
887
- * @param {[number, number]} b the second point coordinates
888
- * @param {number} t the ratio
889
- * @returns {[number, number]} the midpoint coordinates
890
- */
891
- function midPoint(a, b, t) {
892
- const [ax, ay] = a; const [bx, by] = b;
893
- return [ax + (bx - ax) * t, ay + (by - ay) * t];
894
- }
895
-
896
- /**
897
- * Returns the square root of the distance
898
- * between two given points.
899
- *
900
- * @param {[number, number]} a the first point coordinates
901
- * @param {[number, number]} b the second point coordinates
902
- * @returns {number} the distance value
903
- */
904
- function distanceSquareRoot(a, b) {
905
- return Math.sqrt(
906
- (a[0] - b[0]) * (a[0] - b[0])
907
- + (a[1] - b[1]) * (a[1] - b[1]),
908
- );
909
- }
910
-
911
- /**
912
- * Returns a {x,y} point at a given length, the total length and
913
- * the minimum and maximum {x,y} coordinates of a line (L,V,H,Z) segment.
914
- *
915
- * @param {number} x1 the starting point X
916
- * @param {number} y1 the starting point Y
917
- * @param {number} x2 the ending point X
918
- * @param {number} y2 the ending point Y
919
- * @param {number=} distance the distance to point
920
- * @returns {SVGPath.lengthFactory} the segment length, point, min & max
921
- */
922
- function segmentLineFactory(x1, y1, x2, y2, distance) {
923
- const length = distanceSquareRoot([x1, y1], [x2, y2]);
924
- let point = { x: 0, y: 0 };
925
-
926
- /* istanbul ignore else */
927
- if (typeof distance === 'number') {
928
- if (distance <= 0) {
929
- point = { x: x1, y: y1 };
930
- } else if (distance >= length) {
931
- point = { x: x2, y: y2 };
932
- } else {
933
- const [x, y] = midPoint([x1, y1], [x2, y2], distance / length);
934
- point = { x, y };
935
- }
936
- }
937
-
938
- return {
939
- length,
940
- point,
941
- min: {
942
- x: Math.min(x1, x2),
943
- y: Math.min(y1, y2),
944
- },
945
- max: {
946
- x: Math.max(x1, x2),
947
- y: Math.max(y1, y2),
948
- },
949
- };
950
- }
951
-
952
- /**
953
- * Converts an L (line-to) segment to C (cubic-bezier).
954
- *
955
- * @param {number} x1 line start x
956
- * @param {number} y1 line start y
957
- * @param {number} x2 line end x
958
- * @param {number} y2 line end y
959
- * @returns {number[]} the cubic-bezier segment
960
- */
961
- function lineToCubic(x1, y1, x2, y2) {
962
- const t = 0.5;
963
- /** @type {[number, number]} */
964
- const p0 = [x1, y1];
965
- /** @type {[number, number]} */
966
- const p1 = [x2, y2];
967
- const p2 = midPoint(p0, p1, t);
968
- const p3 = midPoint(p1, p2, t);
969
- const p4 = midPoint(p2, p3, t);
970
- const p5 = midPoint(p3, p4, t);
971
- const p6 = midPoint(p4, p5, t);
972
- const seg1 = [...p0, ...p2, ...p4, ...p6, t];
973
- const cp1 = segmentLineFactory(...seg1).point;
974
- const seg2 = [...p6, ...p5, ...p3, ...p1, 0];
975
- const cp2 = segmentLineFactory(...seg2).point;
976
-
977
- return [cp1.x, cp1.y, cp2.x, cp2.y, x2, y2];
978
- }
979
-
980
- /**
981
- * Converts any segment to C (cubic-bezier).
982
- *
983
- * @param {SVGPath.pathSegment} segment the source segment
984
- * @param {SVGPath.parserParams} params the source segment parameters
985
- * @returns {SVGPath.cubicSegment | SVGPath.MSegment} the cubic-bezier segment
986
- */
987
- function segmentToCubic(segment, params) {
988
- const [pathCommand] = segment;
989
- const values = segment.slice(1).map(Number);
990
- const [x, y] = values;
991
- let args;
992
- const {
993
- x1: px1, y1: py1, x: px, y: py,
994
- } = params;
995
-
996
- if (!'TQ'.includes(pathCommand)) {
997
- params.qx = null;
998
- params.qy = null;
999
- }
1000
-
1001
- switch (pathCommand) {
1002
- case 'M':
1003
- params.x = x;
1004
- params.y = y;
1005
- return segment;
1006
- case 'A':
1007
- args = [px1, py1, ...values];
1008
- return ['C', ...arcToCubic(...args)];
1009
- case 'Q':
1010
- params.qx = x;
1011
- params.qy = y;
1012
- args = [px1, py1, ...values];
1013
- return ['C', ...quadToCubic(...args)];
1014
- case 'L':
1015
- return ['C', ...lineToCubic(px1, py1, x, y)];
1016
- case 'Z':
1017
- return ['C', ...lineToCubic(px1, py1, px, py)];
1018
- }
1019
- return segment;
1020
- }
1021
-
1022
- /**
1023
- * Parses a path string value or 'pathArray' and returns a new one
1024
- * in which all segments are converted to cubic-bezier.
1025
- *
1026
- * In addition, un-necessary `Z` segment is removed if previous segment
1027
- * extends to the `M` segment.
1028
- *
1029
- * @param {string | SVGPath.pathArray} pathInput the string to be parsed or 'pathArray'
1030
- * @returns {SVGPath.curveArray} the resulted `pathArray` converted to cubic-bezier
1031
- */
1032
- function pathToCurve(pathInput) {
1033
- /* istanbul ignore else */
1034
- if (isCurveArray(pathInput)) {
1035
- // `isCurveArray` checks if it's `pathArray`
1036
- return clonePath(pathInput);
1037
- }
1038
-
1039
- // const path = fixPath(normalizePath(pathInput));
1040
- const path = normalizePath(pathInput);
1041
- const params = { ...paramsParser };
1042
- const allPathCommands = [];
1043
- let pathCommand = ''; // ts-lint
1044
- let ii = path.length;
1045
-
1046
- for (let i = 0; i < ii; i += 1) {
1047
- [pathCommand] = path[i];
1048
- allPathCommands[i] = pathCommand;
1049
-
1050
- path[i] = segmentToCubic(path[i], params);
1051
-
1052
- fixArc(path, allPathCommands, i);
1053
- ii = path.length;
1054
-
1055
- const segment = path[i];
1056
- const seglen = segment.length;
1057
- params.x1 = +segment[seglen - 2];
1058
- params.y1 = +segment[seglen - 1];
1059
- params.x2 = +(segment[seglen - 4]) || params.x1;
1060
- params.y2 = +(segment[seglen - 3]) || params.y1;
1061
- }
1062
-
1063
- return path;
1064
- }
1065
-
1066
- /**
1067
- * Rounds the values of a `pathArray` instance to
1068
- * a specified amount of decimals and returns it.
1069
- *
1070
- * @param {SVGPath.pathArray} path the source `pathArray`
1071
- * @param {number | 'off'} roundOption the amount of decimals to round numbers to
1072
- * @returns {SVGPath.pathArray} the resulted `pathArray` with rounded values
1073
- */
1074
- function roundPath(path, roundOption) {
1075
- let { round } = defaultOptions;
1076
- if (roundOption === 'off' || round === 'off') return clonePath(path);
1077
- // round = roundOption >= 1 ? roundOption : round;
1078
- // allow for ZERO decimals
1079
- round = roundOption >= 0 ? roundOption : round;
1080
- // to round values to the power
1081
- // the `round` value must be integer
1082
- const pow = typeof round === 'number' && round >= 1 ? (10 ** round) : 1;
1083
-
1084
- return path.map((pi) => {
1085
- const values = pi.slice(1).map(Number)
1086
- .map((n) => (round ? (Math.round(n * pow) / pow) : Math.round(n)));
1087
- return [pi[0], ...values];
1088
- });
1089
- }
1090
-
1091
- /**
1092
- * Returns a valid `d` attribute string value created
1093
- * by rounding values and concatenating the `pathArray` segments.
1094
- *
1095
- * @param {SVGPath.pathArray} path the `pathArray` object
1096
- * @param {number | 'off'} round amount of decimals to round values to
1097
- * @returns {string} the concatenated path string
1098
- */
1099
- function pathToString(path, round) {
1100
- return roundPath(path, round)
1101
- .map((x) => x[0] + x.slice(1).join(' ')).join('');
1102
- }
1103
-
1104
- /**
1105
- * Reverses all segments of a `pathArray` and returns a new `pathArray` instance.
1106
- *
1107
- * @param {SVGPath.pathArray} pathInput the source `pathArray`
1108
- * @returns {SVGPath.pathArray} the reversed `pathArray`
1109
- */
1110
- function reversePath(pathInput) {
1111
- const absolutePath = pathToAbsolute(pathInput);
1112
- const isClosed = absolutePath.slice(-1)[0][0] === 'Z';
1113
-
1114
- const reversedPath = normalizePath(absolutePath).map((segment, i) => {
1115
- const [x, y] = segment.slice(-2).map(Number);
1116
- return {
1117
- seg: absolutePath[i], // absolute
1118
- n: segment, // normalized
1119
- c: absolutePath[i][0], // pathCommand
1120
- x, // x
1121
- y, // y
1122
- };
1123
- }).map((seg, i, path) => {
1124
- const segment = seg.seg;
1125
- const data = seg.n;
1126
- const prevSeg = i && path[i - 1];
1127
- const nextSeg = path[i + 1];
1128
- const pathCommand = seg.c;
1129
- const pLen = path.length;
1130
- /** @type {number} */
1131
- const x = i ? path[i - 1].x : path[pLen - 1].x;
1132
- const y = i ? path[i - 1].y : path[pLen - 1].y;
1133
- /** @type {SVGPath.pathSegment} */
1134
- let result = [];
1135
-
1136
- switch (pathCommand) {
1137
- case 'M':
1138
- result = isClosed ? ['Z'] : [pathCommand, x, y];
1139
- break;
1140
- case 'A':
1141
- result = [pathCommand, ...segment.slice(1, -3), (segment[5] === 1 ? 0 : 1), x, y];
1142
- break;
1143
- case 'C':
1144
- if (nextSeg && nextSeg.c === 'S') {
1145
- result = ['S', segment[1], segment[2], x, y];
1146
- } else {
1147
- result = [pathCommand, segment[3], segment[4], segment[1], segment[2], x, y];
1148
- }
1149
- break;
1150
- case 'S':
1151
- if ((prevSeg && 'CS'.includes(prevSeg.c)) && (!nextSeg || nextSeg.c !== 'S')) {
1152
- result = ['C', data[3], data[4], data[1], data[2], x, y];
1153
- } else {
1154
- result = [pathCommand, data[1], data[2], x, y];
1155
- }
1156
- break;
1157
- case 'Q':
1158
- if (nextSeg && nextSeg.c === 'T') {
1159
- result = ['T', x, y];
1160
- } else {
1161
- result = [pathCommand, ...segment.slice(1, -2), x, y];
1162
- }
1163
- break;
1164
- case 'T':
1165
- if ((prevSeg && 'QT'.includes(prevSeg.c)) && (!nextSeg || nextSeg.c !== 'T')) {
1166
- result = ['Q', data[1], data[2], x, y];
1167
- } else {
1168
- result = [pathCommand, x, y];
1169
- }
1170
- break;
1171
- case 'Z':
1172
- result = ['M', x, y];
1173
- break;
1174
- case 'H':
1175
- result = [pathCommand, x];
1176
- break;
1177
- case 'V':
1178
- result = [pathCommand, y];
1179
- break;
1180
- default:
1181
- result = [pathCommand, ...segment.slice(1, -2), x, y];
1182
- }
1183
-
1184
- return result;
1185
- });
1186
-
1187
- return isClosed ? reversedPath.reverse()
1188
- : [reversedPath[0], ...reversedPath.slice(1).reverse()];
1189
- }
1190
-
1191
- /**
1192
- * Split a path into an `Array` of sub-path strings.
1193
- *
1194
- * In the process, values are converted to absolute
1195
- * for visual consistency.
1196
- *
1197
- * @param {SVGPath.pathArray} pathInput the source `pathArray`
1198
- * @return {SVGPath.pathArray[]} an array with all sub-path strings
1199
- */
1200
- function splitPath(pathInput) {
1201
- /** @type {SVGPath.pathArray[]} */
1202
- const composite = [];
1203
- /** @type {SVGPath.pathArray} */
1204
- let path;
1205
- let pi = -1;
1206
-
1207
- pathInput.forEach((seg) => {
1208
- if (seg[0] === 'M') {
1209
- path = [seg];
1210
- pi += 1;
1211
- } else {
1212
- path = [...path, seg];
1213
- }
1214
- composite[pi] = path;
1215
- });
1216
-
1217
- return composite;
1218
- }
1219
-
1220
- /**
1221
- * Shorten a single segment of a `pathArray` object.
1222
- *
1223
- * @param {SVGPath.absoluteSegment} segment the `absoluteSegment` object
1224
- * @param {SVGPath.normalSegment} normalSegment the `normalSegment` object
1225
- * @param {any} params the coordinates of the previous segment
1226
- * @param {string} prevCommand the path command of the previous segment
1227
- * @returns {SVGPath.shortSegment | SVGPath.pathSegment} the shortened segment
1228
- */
1229
- function shortenSegment(segment, normalSegment, params, prevCommand) {
1230
- const [pathCommand] = segment;
1231
- const round4 = (/** @type {number} */n) => Math.round(n * (10 ** 4)) / 10 ** 4;
1232
- const segmentValues = segment.slice(1).map((n) => +n);
1233
- const normalValues = normalSegment.slice(1).map((n) => +n);
1234
- const {
1235
- x1: px1, y1: py1, x2: px2, y2: py2, x: px, y: py,
1236
- } = params;
1237
- let result = segment;
1238
- const [x, y] = normalValues.slice(-2);
1239
-
1240
- if (!'TQ'.includes(pathCommand)) {
1241
- // optional but good to be cautious
1242
- params.qx = null;
1243
- params.qy = null;
1244
- }
1245
-
1246
- if (['V', 'H', 'S', 'T', 'Z'].includes(pathCommand)) {
1247
- result = [pathCommand, ...segmentValues];
1248
- } else if (pathCommand === 'L') {
1249
- if (round4(px) === round4(x)) {
1250
- result = ['V', y];
1251
- } else if (round4(py) === round4(y)) {
1252
- result = ['H', x];
1253
- }
1254
- } else if (pathCommand === 'C') {
1255
- const [x1, y1] = normalValues;
1256
-
1257
- if ('CS'.includes(prevCommand)
1258
- && ((round4(x1) === round4(px1 * 2 - px2) && round4(y1) === round4(py1 * 2 - py2))
1259
- || (round4(px1) === round4(px2 * 2 - px) && round4(py1) === round4(py2 * 2 - py)))) {
1260
- result = ['S', ...normalValues.slice(-4)];
1261
- }
1262
- params.x1 = x1;
1263
- params.y1 = y1;
1264
- } else if (pathCommand === 'Q') {
1265
- const [qx, qy] = normalValues;
1266
- params.qx = qx;
1267
- params.qy = qy;
1268
-
1269
- if ('QT'.includes(prevCommand)
1270
- && ((round4(qx) === round4(px1 * 2 - px2) && round4(qy) === round4(py1 * 2 - py2))
1271
- || (round4(px1) === round4(px2 * 2 - px) && round4(py1) === round4(py2 * 2 - py)))) {
1272
- result = ['T', ...normalValues.slice(-2)];
1273
- }
1274
- }
1275
-
1276
- return result;
1277
- }
1278
-
1279
- /**
1280
- * Optimizes a `pathArray` object:
1281
- * * convert segments to shorthand if possible
1282
- * * select shortest segments from absolute and relative `pathArray`s
1283
- *
1284
- * TO DO
1285
- * * implement `auto` for rounding values based on pathBBox
1286
- * * also revers path check if it's smaller string, maybe?
1287
- *
1288
- * @param {SVGPath.pathArray} pathInput a string or `pathArray`
1289
- * @param {number | 'off'} round the amount of decimals to round values to
1290
- * @returns {SVGPath.pathArray} the optimized `pathArray`
1291
- */
1292
- function optimizePath(pathInput, round) {
1293
- const path = pathToAbsolute(pathInput);
1294
- const normalPath = normalizePath(path);
1295
- const params = { ...paramsParser };
1296
- const allPathCommands = [];
1297
- const ii = path.length;
1298
- let pathCommand = '';
1299
- let prevCommand = '';
1300
- let x = 0;
1301
- let y = 0;
1302
- let mx = 0;
1303
- let my = 0;
1304
-
1305
- for (let i = 0; i < ii; i += 1) {
1306
- [pathCommand] = path[i];
1307
-
1308
- // Save current path command
1309
- allPathCommands[i] = pathCommand;
1310
- // Get previous path command for `shortenSegment`
1311
- if (i) prevCommand = allPathCommands[i - 1];
1312
- path[i] = shortenSegment(path[i], normalPath[i], params, prevCommand);
1313
-
1314
- const segment = path[i];
1315
- const seglen = segment.length;
1316
-
1317
- // update C, S, Q, T specific params
1318
- params.x1 = +segment[seglen - 2];
1319
- params.y1 = +segment[seglen - 1];
1320
- params.x2 = +(segment[seglen - 4]) || params.x1;
1321
- params.y2 = +(segment[seglen - 3]) || params.y1;
1322
-
1323
- // update x, y params
1324
- switch (pathCommand) {
1325
- case 'Z':
1326
- x = mx;
1327
- y = my;
1328
- break;
1329
- case 'H':
1330
- [, x] = segment;
1331
- break;
1332
- case 'V':
1333
- [, y] = segment;
1334
- break;
1335
- default:
1336
- [x, y] = segment.slice(-2).map(Number);
1337
-
1338
- if (pathCommand === 'M') {
1339
- mx = x;
1340
- my = y;
1341
- }
1342
- }
1343
- params.x = x;
1344
- params.y = y;
1345
- }
1346
-
1347
- const absolutePath = roundPath(path, round);
1348
- const relativePath = roundPath(pathToRelative(path), round);
1349
-
1350
- return absolutePath.map((a, i) => {
1351
- if (i) {
1352
- return a.join('').length < relativePath[i].join('').length
1353
- ? a : relativePath[i];
1354
- }
1355
- return a;
1356
- });
1357
- }
1358
-
1359
- // DOMMatrix Static methods
1360
- // * `fromArray` is a more simple implementation, should also accept Float[32/64]Array;
1361
- // * `fromMatrix` load values from another CSSMatrix/DOMMatrix instance or JSON object;
1362
- // * `fromString` parses and loads values from any valid CSS transform string (TransformList).
1363
-
1364
- /**
1365
- * Creates a new mutable `CSSMatrix` instance given an array of 16/6 floating point values.
1366
- * This static method invalidates arrays that contain non-number elements.
1367
- *
1368
- * If the array has six values, the result is a 2D matrix; if the array has 16 values,
1369
- * the result is a 3D matrix. Otherwise, a TypeError exception is thrown.
1370
- *
1371
- * @param {CSSM.matrix | CSSM.matrix3d} array an `Array` to feed values from.
1372
- * @return {CSSMatrix} the resulted matrix.
1373
- */
1374
- function fromArray(array) {
1375
- const m = new CSSMatrix();
1376
- const a = Array.from(array);
1377
-
1378
- if (!a.every((n) => !Number.isNaN(n))) {
1379
- throw TypeError(`CSSMatrix: "${array}" must only have numbers.`);
1380
- }
1381
- if (a.length === 16) {
1382
- const [m11, m12, m13, m14,
1383
- m21, m22, m23, m24,
1384
- m31, m32, m33, m34,
1385
- m41, m42, m43, m44] = a;
1386
-
1387
- m.m11 = m11;
1388
- m.a = m11;
1389
-
1390
- m.m21 = m21;
1391
- m.c = m21;
1392
-
1393
- m.m31 = m31;
1394
-
1395
- m.m41 = m41;
1396
- m.e = m41;
1397
-
1398
- m.m12 = m12;
1399
- m.b = m12;
1400
-
1401
- m.m22 = m22;
1402
- m.d = m22;
1403
-
1404
- m.m32 = m32;
1405
-
1406
- m.m42 = m42;
1407
- m.f = m42;
1408
-
1409
- m.m13 = m13;
1410
- m.m23 = m23;
1411
- m.m33 = m33;
1412
- m.m43 = m43;
1413
- m.m14 = m14;
1414
- m.m24 = m24;
1415
- m.m34 = m34;
1416
- m.m44 = m44;
1417
- } else if (a.length === 6) {
1418
- const [M11, M12, M21, M22, M41, M42] = a;
1419
-
1420
- m.m11 = M11;
1421
- m.a = M11;
1422
-
1423
- m.m12 = M12;
1424
- m.b = M12;
1425
-
1426
- m.m21 = M21;
1427
- m.c = M21;
1428
-
1429
- m.m22 = M22;
1430
- m.d = M22;
1431
-
1432
- m.m41 = M41;
1433
- m.e = M41;
1434
-
1435
- m.m42 = M42;
1436
- m.f = M42;
1437
- } else {
1438
- throw new TypeError('CSSMatrix: expecting an Array of 6/16 values.');
1439
- }
1440
- return m;
1441
- }
1442
-
1443
- /**
1444
- * Creates a new mutable `CSSMatrix` instance given an existing matrix or a
1445
- * `DOMMatrix` instance which provides the values for its properties.
1446
- *
1447
- * @param {CSSMatrix | DOMMatrix | CSSM.JSONMatrix} m the source matrix to feed values from.
1448
- * @return {CSSMatrix} the resulted matrix.
1449
- */
1450
- function fromMatrix(m) {
1451
- const keys = Object.keys(new CSSMatrix());
1452
- if (typeof m === 'object' && keys.every((k) => k in m)) {
1453
- return fromArray(
1454
- [m.m11, m.m12, m.m13, m.m14,
1455
- m.m21, m.m22, m.m23, m.m24,
1456
- m.m31, m.m32, m.m33, m.m34,
1457
- m.m41, m.m42, m.m43, m.m44],
1458
- );
1459
- }
1460
- throw TypeError(`CSSMatrix: "${JSON.stringify(m)}" is not a DOMMatrix / CSSMatrix / JSON compatible object.`);
1461
- }
1462
-
1463
- /**
1464
- * Creates a new mutable `CSSMatrix` given any valid CSS transform string,
1465
- * or what we call `TransformList`:
1466
- *
1467
- * * `matrix(a, b, c, d, e, f)` - valid matrix() transform function
1468
- * * `matrix3d(m11, m12, m13, ...m44)` - valid matrix3d() transform function
1469
- * * `translate(tx, ty) rotateX(alpha)` - any valid transform function(s)
1470
- *
1471
- * @copyright thednp © 2021
1472
- *
1473
- * @param {string} source valid CSS transform string syntax.
1474
- * @return {CSSMatrix} the resulted matrix.
1475
- */
1476
- function fromString(source) {
1477
- if (typeof source !== 'string') {
1478
- throw TypeError(`CSSMatrix: "${source}" is not a string.`);
1479
- }
1480
- const str = String(source).replace(/\s/g, '');
1481
- let m = new CSSMatrix();
1482
- const invalidStringError = `CSSMatrix: invalid transform string "${source}"`;
1483
-
1484
- // const px = ['perspective'];
1485
- // const length = ['translate', 'translate3d', 'translateX', 'translateY', 'translateZ'];
1486
- // const deg = ['rotate', 'rotate3d', 'rotateX', 'rotateY', 'rotateZ', 'skew', 'skewX', 'skewY'];
1487
- // const abs = ['scale', 'scale3d', 'matrix', 'matrix3d'];
1488
- // const transformFunctions = px.concat(length, deg, abs);
1489
-
1490
- str.split(')').filter((f) => f).forEach((tf) => {
1491
- const [prop, value] = tf.split('(');
1492
-
1493
- // invalidate empty string
1494
- if (!value) throw TypeError(invalidStringError);
1495
-
1496
- const components = value.split(',')
1497
- .map((n) => (n.includes('rad') ? parseFloat(n) * (180 / Math.PI) : parseFloat(n)));
1498
-
1499
- const [x, y, z, a] = components;
1500
- const xyz = [x, y, z];
1501
- const xyza = [x, y, z, a];
1502
-
1503
- // single number value expected
1504
- if (prop === 'perspective' && x && [y, z].every((n) => n === undefined)) {
1505
- m.m34 = -1 / x;
1506
- // 6/16 number values expected
1507
- } else if (prop.includes('matrix') && [6, 16].includes(components.length)
1508
- && components.every((n) => !Number.isNaN(+n))) {
1509
- const values = components.map((n) => (Math.abs(n) < 1e-6 ? 0 : n));
1510
- // @ts-ignore -- conditions should suffice
1511
- m = m.multiply(fromArray(values));
1512
- // 3 values expected
1513
- } else if (prop === 'translate3d' && xyz.every((n) => !Number.isNaN(+n))) {
1514
- m = m.translate(x, y, z);
1515
- // single/double number value(s) expected
1516
- } else if (prop === 'translate' && x && z === undefined) {
1517
- m = m.translate(x, y || 0, 0);
1518
- // all 4 values expected
1519
- } else if (prop === 'rotate3d' && xyza.every((n) => !Number.isNaN(+n)) && a) {
1520
- m = m.rotateAxisAngle(x, y, z, a);
1521
- // single value expected
1522
- } else if (prop === 'rotate' && x && [y, z].every((n) => n === undefined)) {
1523
- m = m.rotate(0, 0, x);
1524
- // 3 values expected
1525
- } else if (prop === 'scale3d' && xyz.every((n) => !Number.isNaN(+n)) && xyz.some((n) => n !== 1)) {
1526
- m = m.scale(x, y, z);
1527
- // single value expected
1528
- } else if (prop === 'scale' && !Number.isNaN(x) && x !== 1 && z === undefined) {
1529
- const nosy = Number.isNaN(+y);
1530
- const sy = nosy ? x : y;
1531
- m = m.scale(x, sy, 1);
1532
- // single/double value expected
1533
- } else if (prop === 'skew' && (x || (!Number.isNaN(x) && y)) && z === undefined) {
1534
- m = m.skew(x, y || 0);
1535
- } else if (/[XYZ]/.test(prop) && x && [y, z].every((n) => n === undefined) // a single value expected
1536
- && ['translate', 'rotate', 'scale', 'skew'].some((p) => prop.includes(p))) {
1537
- if (['skewX', 'skewY'].includes(prop)) {
1538
- // @ts-ignore unfortunately
1539
- m = m[prop](x);
1540
- } else {
1541
- const fn = prop.replace(/[XYZ]/, '');
1542
- const axis = prop.replace(fn, '');
1543
- const idx = ['X', 'Y', 'Z'].indexOf(axis);
1544
- const def = fn === 'scale' ? 1 : 0;
1545
- const axeValues = [
1546
- idx === 0 ? x : def,
1547
- idx === 1 ? x : def,
1548
- idx === 2 ? x : def];
1549
- // @ts-ignore unfortunately
1550
- m = m[fn](...axeValues);
1551
- }
1552
- } else {
1553
- throw TypeError(invalidStringError);
1554
- }
1555
- });
1556
-
1557
- return m;
1558
- }
1559
-
1560
- /**
1561
- * Returns an *Array* containing elements which comprise the matrix.
1562
- * The method can return either the 16 elements or the 6 elements
1563
- * depending on the value of the `is2D` parameter.
1564
- *
1565
- * @param {CSSMatrix | DOMMatrix | CSSM.JSONMatrix} m the source matrix to feed values from.
1566
- * @param {boolean=} is2D *Array* representation of the matrix
1567
- * @return {CSSM.matrix | CSSM.matrix3d} an *Array* representation of the matrix
1568
- */
1569
- function toArray(m, is2D) {
1570
- if (is2D) {
1571
- return [m.a, m.b, m.c, m.d, m.e, m.f];
1572
- }
1573
- return [m.m11, m.m12, m.m13, m.m14,
1574
- m.m21, m.m22, m.m23, m.m24,
1575
- m.m31, m.m32, m.m33, m.m34,
1576
- m.m41, m.m42, m.m43, m.m44];
1577
- }
1578
-
1579
- // Transform Functions
1580
- // https://www.w3.org/TR/css-transforms-1/#transform-functions
1581
-
1582
- /**
1583
- * Creates a new `CSSMatrix` for the translation matrix and returns it.
1584
- * This method is equivalent to the CSS `translate3d()` function.
1585
- *
1586
- * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/translate3d
1587
- *
1588
- * @param {number} x the `x-axis` position.
1589
- * @param {number} y the `y-axis` position.
1590
- * @param {number} z the `z-axis` position.
1591
- * @return {CSSMatrix} the resulted matrix.
1592
- */
1593
- function Translate(x, y, z) {
1594
- const m = new CSSMatrix();
1595
- m.m41 = x;
1596
- m.e = x;
1597
- m.m42 = y;
1598
- m.f = y;
1599
- m.m43 = z;
1600
- return m;
1601
- }
1602
-
1603
- /**
1604
- * Creates a new `CSSMatrix` for the rotation matrix and returns it.
1605
- *
1606
- * http://en.wikipedia.org/wiki/Rotation_matrix
1607
- *
1608
- * @param {number} rx the `x-axis` rotation.
1609
- * @param {number} ry the `y-axis` rotation.
1610
- * @param {number} rz the `z-axis` rotation.
1611
- * @return {CSSMatrix} the resulted matrix.
1612
- */
1613
- function Rotate(rx, ry, rz) {
1614
- const m = new CSSMatrix();
1615
- const degToRad = Math.PI / 180;
1616
- const radX = rx * degToRad;
1617
- const radY = ry * degToRad;
1618
- const radZ = rz * degToRad;
1619
-
1620
- // minus sin() because of right-handed system
1621
- const cosx = Math.cos(radX);
1622
- const sinx = -Math.sin(radX);
1623
- const cosy = Math.cos(radY);
1624
- const siny = -Math.sin(radY);
1625
- const cosz = Math.cos(radZ);
1626
- const sinz = -Math.sin(radZ);
1627
-
1628
- const m11 = cosy * cosz;
1629
- const m12 = -cosy * sinz;
1630
-
1631
- m.m11 = m11;
1632
- m.a = m11;
1633
-
1634
- m.m12 = m12;
1635
- m.b = m12;
1636
-
1637
- m.m13 = siny;
1638
-
1639
- const m21 = sinx * siny * cosz + cosx * sinz;
1640
- m.m21 = m21;
1641
- m.c = m21;
1642
-
1643
- const m22 = cosx * cosz - sinx * siny * sinz;
1644
- m.m22 = m22;
1645
- m.d = m22;
1646
-
1647
- m.m23 = -sinx * cosy;
1648
-
1649
- m.m31 = sinx * sinz - cosx * siny * cosz;
1650
- m.m32 = sinx * cosz + cosx * siny * sinz;
1651
- m.m33 = cosx * cosy;
1652
-
1653
- return m;
1654
- }
1655
-
1656
- /**
1657
- * Creates a new `CSSMatrix` for the rotation matrix and returns it.
1658
- * This method is equivalent to the CSS `rotate3d()` function.
1659
- *
1660
- * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/rotate3d
1661
- *
1662
- * @param {number} x the `x-axis` vector length.
1663
- * @param {number} y the `y-axis` vector length.
1664
- * @param {number} z the `z-axis` vector length.
1665
- * @param {number} alpha the value in degrees of the rotation.
1666
- * @return {CSSMatrix} the resulted matrix.
1667
- */
1668
- function RotateAxisAngle(x, y, z, alpha) {
1669
- const m = new CSSMatrix();
1670
- const length = Math.sqrt(x * x + y * y + z * z);
1671
-
1672
- if (length === 0) {
1673
- // bad vector length, return identity
1674
- return m;
1675
- }
1676
-
1677
- const X = x / length;
1678
- const Y = y / length;
1679
- const Z = z / length;
1680
-
1681
- const angle = alpha * (Math.PI / 360);
1682
- const sinA = Math.sin(angle);
1683
- const cosA = Math.cos(angle);
1684
- const sinA2 = sinA * sinA;
1685
- const x2 = X * X;
1686
- const y2 = Y * Y;
1687
- const z2 = Z * Z;
1688
-
1689
- const m11 = 1 - 2 * (y2 + z2) * sinA2;
1690
- m.m11 = m11;
1691
- m.a = m11;
1692
-
1693
- const m12 = 2 * (X * Y * sinA2 + Z * sinA * cosA);
1694
- m.m12 = m12;
1695
- m.b = m12;
1696
-
1697
- m.m13 = 2 * (X * Z * sinA2 - Y * sinA * cosA);
1698
-
1699
- const m21 = 2 * (Y * X * sinA2 - Z * sinA * cosA);
1700
- m.m21 = m21;
1701
- m.c = m21;
1702
-
1703
- const m22 = 1 - 2 * (z2 + x2) * sinA2;
1704
- m.m22 = m22;
1705
- m.d = m22;
1706
-
1707
- m.m23 = 2 * (Y * Z * sinA2 + X * sinA * cosA);
1708
- m.m31 = 2 * (Z * X * sinA2 + Y * sinA * cosA);
1709
- m.m32 = 2 * (Z * Y * sinA2 - X * sinA * cosA);
1710
- m.m33 = 1 - 2 * (x2 + y2) * sinA2;
1711
-
1712
- return m;
1713
- }
1714
-
1715
- /**
1716
- * Creates a new `CSSMatrix` for the scale matrix and returns it.
1717
- * This method is equivalent to the CSS `scale3d()` function, except it doesn't
1718
- * accept {x, y, z} transform origin parameters.
1719
- *
1720
- * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/scale3d
1721
- *
1722
- * @param {number} x the `x-axis` scale.
1723
- * @param {number} y the `y-axis` scale.
1724
- * @param {number} z the `z-axis` scale.
1725
- * @return {CSSMatrix} the resulted matrix.
1726
- */
1727
- function Scale(x, y, z) {
1728
- const m = new CSSMatrix();
1729
- m.m11 = x;
1730
- m.a = x;
1731
-
1732
- m.m22 = y;
1733
- m.d = y;
1734
-
1735
- m.m33 = z;
1736
- return m;
1737
- }
1738
-
1739
- /**
1740
- * Creates a new `CSSMatrix` for the shear of both the `x-axis` and`y-axis`
1741
- * matrix and returns it. This method is equivalent to the CSS `skew()` function.
1742
- *
1743
- * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skew
1744
- *
1745
- * @param {number} angleX the X-angle in degrees.
1746
- * @param {number} angleY the Y-angle in degrees.
1747
- * @return {CSSMatrix} the resulted matrix.
1748
- */
1749
- function Skew(angleX, angleY) {
1750
- const m = new CSSMatrix();
1751
- if (angleX) {
1752
- const radX = (angleX * Math.PI) / 180;
1753
- const tX = Math.tan(radX);
1754
- m.m21 = tX;
1755
- m.c = tX;
1756
- }
1757
- if (angleY) {
1758
- const radY = (angleY * Math.PI) / 180;
1759
- const tY = Math.tan(radY);
1760
- m.m12 = tY;
1761
- m.b = tY;
1762
- }
1763
- return m;
1764
- }
1765
-
1766
- /**
1767
- * Creates a new `CSSMatrix` for the shear of the `x-axis` rotation matrix and
1768
- * returns it. This method is equivalent to the CSS `skewX()` function.
1769
- *
1770
- * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewX
1771
- *
1772
- * @param {number} angle the angle in degrees.
1773
- * @return {CSSMatrix} the resulted matrix.
1774
- */
1775
- function SkewX(angle) {
1776
- return Skew(angle, 0);
1777
- }
1778
-
1779
- /**
1780
- * Creates a new `CSSMatrix` for the shear of the `y-axis` rotation matrix and
1781
- * returns it. This method is equivalent to the CSS `skewY()` function.
1782
- *
1783
- * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewY
1784
- *
1785
- * @param {number} angle the angle in degrees.
1786
- * @return {CSSMatrix} the resulted matrix.
1787
- */
1788
- function SkewY(angle) {
1789
- return Skew(0, angle);
1790
- }
1791
-
1792
- /**
1793
- * Creates a new `CSSMatrix` resulted from the multiplication of two matrixes
1794
- * and returns it. Both matrixes are not changed.
1795
- *
1796
- * @param {CSSMatrix | DOMMatrix | CSSM.JSONMatrix} m1 the first matrix.
1797
- * @param {CSSMatrix | DOMMatrix | CSSM.JSONMatrix} m2 the second matrix.
1798
- * @return {CSSMatrix} the resulted matrix.
1799
- */
1800
- function Multiply(m1, m2) {
1801
- const m11 = m2.m11 * m1.m11 + m2.m12 * m1.m21 + m2.m13 * m1.m31 + m2.m14 * m1.m41;
1802
- const m12 = m2.m11 * m1.m12 + m2.m12 * m1.m22 + m2.m13 * m1.m32 + m2.m14 * m1.m42;
1803
- const m13 = m2.m11 * m1.m13 + m2.m12 * m1.m23 + m2.m13 * m1.m33 + m2.m14 * m1.m43;
1804
- const m14 = m2.m11 * m1.m14 + m2.m12 * m1.m24 + m2.m13 * m1.m34 + m2.m14 * m1.m44;
1805
-
1806
- const m21 = m2.m21 * m1.m11 + m2.m22 * m1.m21 + m2.m23 * m1.m31 + m2.m24 * m1.m41;
1807
- const m22 = m2.m21 * m1.m12 + m2.m22 * m1.m22 + m2.m23 * m1.m32 + m2.m24 * m1.m42;
1808
- const m23 = m2.m21 * m1.m13 + m2.m22 * m1.m23 + m2.m23 * m1.m33 + m2.m24 * m1.m43;
1809
- const m24 = m2.m21 * m1.m14 + m2.m22 * m1.m24 + m2.m23 * m1.m34 + m2.m24 * m1.m44;
1810
-
1811
- const m31 = m2.m31 * m1.m11 + m2.m32 * m1.m21 + m2.m33 * m1.m31 + m2.m34 * m1.m41;
1812
- const m32 = m2.m31 * m1.m12 + m2.m32 * m1.m22 + m2.m33 * m1.m32 + m2.m34 * m1.m42;
1813
- const m33 = m2.m31 * m1.m13 + m2.m32 * m1.m23 + m2.m33 * m1.m33 + m2.m34 * m1.m43;
1814
- const m34 = m2.m31 * m1.m14 + m2.m32 * m1.m24 + m2.m33 * m1.m34 + m2.m34 * m1.m44;
1815
-
1816
- const m41 = m2.m41 * m1.m11 + m2.m42 * m1.m21 + m2.m43 * m1.m31 + m2.m44 * m1.m41;
1817
- const m42 = m2.m41 * m1.m12 + m2.m42 * m1.m22 + m2.m43 * m1.m32 + m2.m44 * m1.m42;
1818
- const m43 = m2.m41 * m1.m13 + m2.m42 * m1.m23 + m2.m43 * m1.m33 + m2.m44 * m1.m43;
1819
- const m44 = m2.m41 * m1.m14 + m2.m42 * m1.m24 + m2.m43 * m1.m34 + m2.m44 * m1.m44;
1820
-
1821
- return fromArray(
1822
- [m11, m12, m13, m14,
1823
- m21, m22, m23, m24,
1824
- m31, m32, m33, m34,
1825
- m41, m42, m43, m44],
1826
- );
1827
- }
1828
-
1829
- /**
1830
- * Creates and returns a new `DOMMatrix` compatible instance
1831
- * with equivalent instance.
1832
- * @class CSSMatrix
1833
- *
1834
- * @author thednp <https://github.com/thednp/DOMMatrix/>
1835
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMMatrix
1836
- */
1837
-
1838
- class CSSMatrix {
1839
- /**
1840
- * @constructor
1841
- * @param {any} args accepts all parameter configurations:
1842
- * * valid CSS transform string,
1843
- * * CSSMatrix/DOMMatrix instance,
1844
- * * a 6/16 elements *Array*.
1845
- */
1846
- constructor(...args) {
1847
- const m = this;
1848
- // array 6
1849
- m.a = 1; m.b = 0;
1850
- m.c = 0; m.d = 1;
1851
- m.e = 0; m.f = 0;
1852
- // array 16
1853
- m.m11 = 1; m.m12 = 0; m.m13 = 0; m.m14 = 0;
1854
- m.m21 = 0; m.m22 = 1; m.m23 = 0; m.m24 = 0;
1855
- m.m31 = 0; m.m32 = 0; m.m33 = 1; m.m34 = 0;
1856
- m.m41 = 0; m.m42 = 0; m.m43 = 0; m.m44 = 1;
1857
-
1858
- if (args.length) {
1859
- const ARGS = [16, 6].some((l) => l === args.length) ? args : args[0];
1860
-
1861
- return m.setMatrixValue(ARGS);
1862
- }
1863
- return m;
1864
- }
1865
-
1866
- /**
1867
- * A `Boolean` whose value is `true` if the matrix is the identity matrix. The identity
1868
- * matrix is one in which every value is 0 except those on the main diagonal from top-left
1869
- * to bottom-right corner (in other words, where the offsets in each direction are equal).
1870
- *
1871
- * @return {boolean} the current property value
1872
- */
1873
- get isIdentity() {
1874
- const m = this;
1875
- return (m.m11 === 1 && m.m12 === 0 && m.m13 === 0 && m.m14 === 0
1876
- && m.m21 === 0 && m.m22 === 1 && m.m23 === 0 && m.m24 === 0
1877
- && m.m31 === 0 && m.m32 === 0 && m.m33 === 1 && m.m34 === 0
1878
- && m.m41 === 0 && m.m42 === 0 && m.m43 === 0 && m.m44 === 1);
1879
- }
1880
-
1881
- /**
1882
- * A `Boolean` flag whose value is `true` if the matrix was initialized as a 2D matrix
1883
- * and `false` if the matrix is 3D.
1884
- *
1885
- * @return {boolean} the current property value
1886
- */
1887
- get is2D() {
1888
- const m = this;
1889
- return (m.m31 === 0 && m.m32 === 0 && m.m33 === 1 && m.m34 === 0 && m.m43 === 0 && m.m44 === 1);
1890
- }
1891
-
1892
- /**
1893
- * The `setMatrixValue` method replaces the existing matrix with one computed
1894
- * in the browser. EG: `matrix(1,0.25,-0.25,1,0,0)`
1895
- *
1896
- * The method accepts any *Array* values, the result of
1897
- * `DOMMatrix` instance method `toFloat64Array()` / `toFloat32Array()` calls
1898
- * or `CSSMatrix` instance method `toArray()`.
1899
- *
1900
- * This method expects valid *matrix()* / *matrix3d()* string values, as well
1901
- * as other transform functions like *translateX(10px)*.
1902
- *
1903
- * @param {string | CSSM.matrix | CSSM.matrix3d | CSSMatrix | DOMMatrix | CSSM.JSONMatrix} source
1904
- * @return {CSSMatrix} the matrix instance
1905
- */
1906
- setMatrixValue(source) {
1907
- const m = this;
1908
-
1909
- // CSS transform string source - TransformList first
1910
- if (typeof source === 'string' && source.length && source !== 'none') {
1911
- return fromString(source);
1912
- }
1913
- // [Arguments list | Array] come second
1914
- if ([Array, Float64Array, Float32Array].some((a) => source instanceof a)) {
1915
- // @ts-ignore
1916
- return fromArray(source);
1917
- }
1918
- // new CSSMatrix(CSSMatrix | DOMMatrix | JSON) last
1919
- if ([CSSMatrix, DOMMatrix, Object].some((a) => source instanceof a)) {
1920
- // @ts-ignore
1921
- return fromMatrix(source);
1922
- }
1923
-
1924
- return m;
1925
- }
1926
-
1927
- /**
1928
- * Returns a *Float32Array* containing elements which comprise the matrix.
1929
- * The method can return either the 16 elements or the 6 elements
1930
- * depending on the value of the `is2D` parameter.
1931
- *
1932
- * @param {boolean=} is2D *Array* representation of the matrix
1933
- * @return {Float32Array} an *Array* representation of the matrix
1934
- */
1935
- toFloat32Array(is2D) {
1936
- return Float32Array.from(toArray(this, is2D));
1937
- }
1938
-
1939
- /**
1940
- * Returns a *Float64Array* containing elements which comprise the matrix.
1941
- * The method can return either the 16 elements or the 6 elements
1942
- * depending on the value of the `is2D` parameter.
1943
- *
1944
- * @param {boolean=} is2D *Array* representation of the matrix
1945
- * @return {Float64Array} an *Array* representation of the matrix
1946
- */
1947
- toFloat64Array(is2D) {
1948
- return Float64Array.from(toArray(this, is2D));
1949
- }
1950
-
1951
- /**
1952
- * Creates and returns a string representation of the matrix in `CSS` matrix syntax,
1953
- * using the appropriate `CSS` matrix notation.
1954
- *
1955
- * matrix3d *matrix3d(m11, m12, m13, m14, m21, ...)*
1956
- * matrix *matrix(a, b, c, d, e, f)*
1957
- *
1958
- * @return {string} a string representation of the matrix
1959
- */
1960
- toString() {
1961
- const m = this;
1962
- const { is2D } = m;
1963
- const values = m.toFloat64Array(is2D).join(', ');
1964
- const type = is2D ? 'matrix' : 'matrix3d';
1965
- return `${type}(${values})`;
1966
- }
1967
-
1968
- /**
1969
- * Returns a JSON representation of the `CSSMatrix` instance, a standard *Object*
1970
- * that includes `{a,b,c,d,e,f}` and `{m11,m12,m13,..m44}` properties as well
1971
- * as the `is2D` & `isIdentity` properties.
1972
- *
1973
- * The result can also be used as a second parameter for the `fromMatrix` static method
1974
- * to load values into another matrix instance.
1975
- *
1976
- * @return {CSSM.JSONMatrix} an *Object* with all matrix values.
1977
- */
1978
- toJSON() {
1979
- const m = this;
1980
- const { is2D, isIdentity } = m;
1981
- return { ...m, is2D, isIdentity };
1982
- }
1983
-
1984
- /**
1985
- * The Multiply method returns a new CSSMatrix which is the result of this
1986
- * matrix multiplied by the passed matrix, with the passed matrix to the right.
1987
- * This matrix is not modified.
1988
- *
1989
- * @param {CSSMatrix | DOMMatrix | CSSM.JSONMatrix} m2 CSSMatrix
1990
- * @return {CSSMatrix} The resulted matrix.
1991
- */
1992
- multiply(m2) {
1993
- return Multiply(this, m2);
1994
- }
1995
-
1996
- /**
1997
- * The translate method returns a new matrix which is this matrix post
1998
- * multiplied by a translation matrix containing the passed values. If the z
1999
- * component is undefined, a 0 value is used in its place. This matrix is not
2000
- * modified.
2001
- *
2002
- * @param {number} x X component of the translation value.
2003
- * @param {number=} y Y component of the translation value.
2004
- * @param {number=} z Z component of the translation value.
2005
- * @return {CSSMatrix} The resulted matrix
2006
- */
2007
- translate(x, y, z) {
2008
- const X = x;
2009
- let Y = y;
2010
- let Z = z;
2011
- if (Y === undefined) Y = 0;
2012
- if (Z === undefined) Z = 0;
2013
- return Multiply(this, Translate(X, Y, Z));
2014
- }
2015
-
2016
- /**
2017
- * The scale method returns a new matrix which is this matrix post multiplied by
2018
- * a scale matrix containing the passed values. If the z component is undefined,
2019
- * a 1 value is used in its place. If the y component is undefined, the x
2020
- * component value is used in its place. This matrix is not modified.
2021
- *
2022
- * @param {number} x The X component of the scale value.
2023
- * @param {number=} y The Y component of the scale value.
2024
- * @param {number=} z The Z component of the scale value.
2025
- * @return {CSSMatrix} The resulted matrix
2026
- */
2027
- scale(x, y, z) {
2028
- const X = x;
2029
- let Y = y;
2030
- let Z = z;
2031
- if (Y === undefined) Y = x;
2032
- if (Z === undefined) Z = 1; // Z must be 1 if undefined
2033
-
2034
- return Multiply(this, Scale(X, Y, Z));
2035
- }
2036
-
2037
- /**
2038
- * The rotate method returns a new matrix which is this matrix post multiplied
2039
- * by each of 3 rotation matrices about the major axes, first X, then Y, then Z.
2040
- * If the y and z components are undefined, the x value is used to rotate the
2041
- * object about the z axis, as though the vector (0,0,x) were passed. All
2042
- * rotation values are in degrees. This matrix is not modified.
2043
- *
2044
- * @param {number} rx The X component of the rotation, or Z if Y and Z are null.
2045
- * @param {number=} ry The (optional) Y component of the rotation value.
2046
- * @param {number=} rz The (optional) Z component of the rotation value.
2047
- * @return {CSSMatrix} The resulted matrix
2048
- */
2049
- rotate(rx, ry, rz) {
2050
- let RX = rx;
2051
- let RY = ry || 0;
2052
- let RZ = rz || 0;
2053
-
2054
- if (typeof rx === 'number' && ry === undefined && rz === undefined) {
2055
- RZ = RX; RX = 0; RY = 0;
2056
- }
2057
-
2058
- return Multiply(this, Rotate(RX, RY, RZ));
2059
- }
2060
-
2061
- /**
2062
- * The rotateAxisAngle method returns a new matrix which is this matrix post
2063
- * multiplied by a rotation matrix with the given axis and `angle`. The right-hand
2064
- * rule is used to determine the direction of rotation. All rotation values are
2065
- * in degrees. This matrix is not modified.
2066
- *
2067
- * @param {number} x The X component of the axis vector.
2068
- * @param {number} y The Y component of the axis vector.
2069
- * @param {number} z The Z component of the axis vector.
2070
- * @param {number} angle The angle of rotation about the axis vector, in degrees.
2071
- * @return {CSSMatrix} The resulted matrix
2072
- */
2073
- rotateAxisAngle(x, y, z, angle) {
2074
- if ([x, y, z, angle].some((n) => Number.isNaN(+n))) {
2075
- throw new TypeError('CSSMatrix: expecting 4 values');
2076
- }
2077
- return Multiply(this, RotateAxisAngle(x, y, z, angle));
2078
- }
2079
-
2080
- /**
2081
- * Specifies a skew transformation along the `x-axis` by the given angle.
2082
- * This matrix is not modified.
2083
- *
2084
- * @param {number} angle The angle amount in degrees to skew.
2085
- * @return {CSSMatrix} The resulted matrix
2086
- */
2087
- skewX(angle) {
2088
- return Multiply(this, SkewX(angle));
2089
- }
2090
-
2091
- /**
2092
- * Specifies a skew transformation along the `y-axis` by the given angle.
2093
- * This matrix is not modified.
2094
- *
2095
- * @param {number} angle The angle amount in degrees to skew.
2096
- * @return {CSSMatrix} The resulted matrix
2097
- */
2098
- skewY(angle) {
2099
- return Multiply(this, SkewY(angle));
2100
- }
2101
-
2102
- /**
2103
- * Specifies a skew transformation along both the `x-axis` and `y-axis`.
2104
- * This matrix is not modified.
2105
- *
2106
- * @param {number} angleX The X-angle amount in degrees to skew.
2107
- * @param {number} angleY The angle amount in degrees to skew.
2108
- * @return {CSSMatrix} The resulted matrix
2109
- */
2110
- skew(angleX, angleY) {
2111
- return Multiply(this, Skew(angleX, angleY));
2112
- }
2113
-
2114
- /**
2115
- * Transforms a specified vector using the matrix, returning a new
2116
- * {x,y,z,w} Tuple *Object* comprising the transformed vector.
2117
- * Neither the matrix nor the original vector are altered.
2118
- *
2119
- * The method is equivalent with `transformPoint()` method
2120
- * of the `DOMMatrix` constructor.
2121
- *
2122
- * @param {CSSM.PointTuple | DOMPoint} t Tuple with `{x,y,z,w}` components
2123
- * @return {CSSM.PointTuple | DOMPoint} the resulting Tuple
2124
- */
2125
- transformPoint(t) {
2126
- const m = this;
2127
-
2128
- const x = m.m11 * t.x + m.m21 * t.y + m.m31 * t.z + m.m41 * t.w;
2129
- const y = m.m12 * t.x + m.m22 * t.y + m.m32 * t.z + m.m42 * t.w;
2130
- const z = m.m13 * t.x + m.m23 * t.y + m.m33 * t.z + m.m43 * t.w;
2131
- const w = m.m14 * t.x + m.m24 * t.y + m.m34 * t.z + m.m44 * t.w;
2132
-
2133
- return t instanceof DOMPoint
2134
- ? new DOMPoint(x, y, z, w)
2135
- : {
2136
- x, y, z, w,
2137
- };
2138
- }
2139
- }
2140
-
2141
- // Add Transform Functions to CSSMatrix object
2142
- // without creating a TypeScript namespace.
2143
- Object.assign(CSSMatrix, {
2144
- Translate,
2145
- Rotate,
2146
- RotateAxisAngle,
2147
- Scale,
2148
- SkewX,
2149
- SkewY,
2150
- Skew,
2151
- Multiply,
2152
- fromArray,
2153
- fromMatrix,
2154
- fromString,
2155
- toArray,
2156
- });
2157
-
2158
- var version$1 = "1.0.3";
2159
-
2160
- /**
2161
- * A global namespace for library version.
2162
- * @type {string}
2163
- */
2164
- const Version$1 = version$1;
2165
-
2166
- /** @typedef {import('../types/index')} */
2167
-
2168
- Object.assign(CSSMatrix, { Version: Version$1 });
2169
-
2170
- /**
2171
- * Returns a transformation matrix to apply to `<path>` elements.
2172
- *
2173
- * @see SVGPath.transformObject
2174
- *
2175
- * @param {SVGPath.transformObject} transform the `transformObject`
2176
- * @returns {CSSMatrix} a new transformation matrix
2177
- */
2178
- function getSVGMatrix(transform) {
2179
- let matrix = new CSSMatrix();
2180
- const { origin } = transform;
2181
- const [originX, originY] = origin;
2182
- const { translate } = transform;
2183
- const { rotate } = transform;
2184
- const { skew } = transform;
2185
- const { scale } = transform;
2186
-
2187
- // set translate
2188
- if (Array.isArray(translate) && translate.every((x) => !Number.isNaN(+x))
2189
- && translate.some((x) => x !== 0)) {
2190
- matrix = matrix.translate(...translate);
2191
- } else if (typeof translate === 'number' && !Number.isNaN(translate)) {
2192
- matrix = matrix.translate(translate);
2193
- }
2194
-
2195
- if (rotate || skew || scale) {
2196
- // set SVG transform-origin, always defined
2197
- matrix = matrix.translate(originX, originY);
2198
-
2199
- // set rotation
2200
- if (Array.isArray(rotate) && rotate.every((x) => !Number.isNaN(+x))
2201
- && rotate.some((x) => x !== 0)) {
2202
- matrix = matrix.rotate(...rotate);
2203
- } else if (typeof rotate === 'number' && !Number.isNaN(rotate)) {
2204
- matrix = matrix.rotate(rotate);
2205
- }
2206
-
2207
- // set skew(s)
2208
- if (Array.isArray(skew) && skew.every((x) => !Number.isNaN(+x))
2209
- && skew.some((x) => x !== 0)) {
2210
- matrix = skew[0] ? matrix.skewX(skew[0]) : matrix;
2211
- matrix = skew[1] ? matrix.skewY(skew[1]) : matrix;
2212
- } else if (typeof skew === 'number' && !Number.isNaN(skew)) {
2213
- matrix = matrix.skewX(skew);
2214
- }
2215
-
2216
- // set scale
2217
- if (Array.isArray(scale) && scale.every((x) => !Number.isNaN(+x))
2218
- && scale.some((x) => x !== 1)) {
2219
- matrix = matrix.scale(...scale);
2220
- } else if (typeof scale === 'number' && !Number.isNaN(scale)) {
2221
- matrix = matrix.scale(scale);
2222
- }
2223
- // set SVG transform-origin
2224
- matrix = matrix.translate(-originX, -originY);
2225
- }
2226
-
2227
- return matrix;
2228
- }
2229
-
2230
- /**
2231
- * Transforms a specified point using a matrix, returning a new
2232
- * Tuple *Object* comprising of the transformed point.
2233
- * Neither the matrix nor the original point are altered.
2234
- *
2235
- * @copyright thednp © 2021
2236
- *
2237
- * @param {SVGPath.CSSMatrix} M CSSMatrix instance
2238
- * @param {[number, number, number, number]} v Tuple
2239
- * @return {[number, number, number, number]} the resulting Tuple
2240
- */
2241
- function translatePoint(M, v) {
2242
- let m = Translate(...v);
2243
-
2244
- [,,, m.m44] = v;
2245
- m = M.multiply(m);
2246
-
2247
- return [m.m41, m.m42, m.m43, m.m44];
2248
- }
2249
-
2250
- /**
2251
- * Returns the [x,y] projected coordinates for a given an [x,y] point
2252
- * and an [x,y,z] perspective origin point.
2253
- *
2254
- * Equation found here =>
2255
- * http://en.wikipedia.org/wiki/3D_projection#Diagram
2256
- * Details =>
2257
- * https://stackoverflow.com/questions/23792505/predicted-rendering-of-css-3d-transformed-pixel
2258
- *
2259
- * @param {SVGPath.CSSMatrix} m the transformation matrix
2260
- * @param {[number, number]} point2D the initial [x,y] coordinates
2261
- * @param {number[]} origin the [x,y,z] transform origin
2262
- * @returns {[number, number]} the projected [x,y] coordinates
2263
- */
2264
- function projection2d(m, point2D, origin) {
2265
- const [originX, originY, originZ] = origin;
2266
- const [x, y, z] = translatePoint(m, [...point2D, 0, 1]);
2267
-
2268
- const relativePositionX = x - originX;
2269
- const relativePositionY = y - originY;
2270
- const relativePositionZ = z - originZ;
2271
-
2272
- return [
2273
- // protect against division by ZERO
2274
- relativePositionX * (Math.abs(originZ) / Math.abs(relativePositionZ) || 1) + originX,
2275
- relativePositionY * (Math.abs(originZ) / Math.abs(relativePositionZ) || 1) + originY,
2276
- ];
2277
- }
2278
-
2279
- /**
2280
- * Apply a 2D / 3D transformation to a `pathArray` instance.
2281
- *
2282
- * Since *SVGElement* doesn't support 3D transformation, this function
2283
- * creates a 2D projection of the <path> element.
2284
- *
2285
- * @param {SVGPath.pathArray} path the `pathArray` to apply transformation
2286
- * @param {SVGPath.transformObject} transform the transform functions `Object`
2287
- * @returns {SVGPath.pathArray} the resulted `pathArray`
2288
- */
2289
- function transformPath(path, transform) {
2290
- let x = 0; let y = 0; let i; let j; let ii; let jj; let lx; let ly;
2291
- const absolutePath = pathToAbsolute(path);
2292
- const transformProps = transform && Object.keys(transform);
2293
-
2294
- // when used as a static method, invalidate somehow
2295
- if (!transform || !transformProps.length) return clonePath(absolutePath);
2296
-
2297
- const normalizedPath = normalizePath(absolutePath);
2298
- // transform origin is extremely important
2299
- if (!transform.origin) {
2300
- const { origin: defaultOrigin } = defaultOptions;
2301
- Object.assign(transform, { origin: defaultOrigin });
2302
- }
2303
- const matrixInstance = getSVGMatrix(transform);
2304
- const { origin } = transform;
2305
- const params = { ...paramsParser };
2306
- /** @type {SVGPath.pathSegment} */
2307
- let segment = [];
2308
- let seglen = 0;
2309
- let pathCommand = '';
2310
- /** @type {SVGPath.pathTransformList[]} */
2311
- let transformedPath = [];
2312
- const allPathCommands = []; // needed for arc to curve transformation
2313
-
2314
- if (!matrixInstance.isIdentity) {
2315
- for (i = 0, ii = absolutePath.length; i < ii; i += 1) {
2316
- segment = absolutePath[i];
2317
-
2318
- /* istanbul ignore else */
2319
- if (absolutePath[i]) [pathCommand] = segment;
2320
-
2321
- // REPLACE Arc path commands with Cubic Beziers
2322
- // we don't have any scripting know-how on 3d ellipse transformation
2323
- // Arc segments don't work 3D transformations or skews
2324
- /// ////////////////////////////////////////
2325
- allPathCommands[i] = pathCommand;
2326
-
2327
- if (pathCommand === 'A') {
2328
- segment = segmentToCubic(normalizedPath[i], params);
2329
-
2330
- absolutePath[i] = segmentToCubic(normalizedPath[i], params);
2331
- fixArc(absolutePath, allPathCommands, i);
2332
-
2333
- normalizedPath[i] = segmentToCubic(normalizedPath[i], params);
2334
- fixArc(normalizedPath, allPathCommands, i);
2335
- ii = Math.max(absolutePath.length, normalizedPath.length);
2336
- }
2337
-
2338
- /// ////////////////////////////////////////
2339
- segment = normalizedPath[i];
2340
- seglen = segment.length;
2341
-
2342
- params.x1 = +segment[seglen - 2];
2343
- params.y1 = +segment[seglen - 1];
2344
- params.x2 = +(segment[seglen - 4]) || params.x1;
2345
- params.y2 = +(segment[seglen - 3]) || params.y1;
2346
-
2347
- /** @type {SVGPath.pathTransformList} */
2348
- const result = {
2349
- s: absolutePath[i], c: absolutePath[i][0], x: params.x1, y: params.y1,
2350
- };
2351
-
2352
- transformedPath = [...transformedPath, ...[result]];
2353
- }
2354
-
2355
- return transformedPath.map((seg) => {
2356
- pathCommand = seg.c;
2357
- segment = seg.s;
2358
- switch (pathCommand) {
2359
- case 'L':
2360
- case 'H':
2361
- case 'V':
2362
- [lx, ly] = projection2d(matrixInstance, [seg.x, seg.y], origin);
2363
-
2364
- /* istanbul ignore else */
2365
- if (x !== lx && y !== ly) {
2366
- segment = ['L', lx, ly];
2367
- } else if (y === ly) {
2368
- segment = ['H', lx];
2369
- } else if (x === lx) {
2370
- segment = ['V', ly];
2371
- }
2372
-
2373
- x = lx; y = ly; // now update x and y
2374
-
2375
- return segment;
2376
- default:
2377
-
2378
- for (j = 1, jj = segment.length; j < jj; j += 2) {
2379
- [x, y] = projection2d(matrixInstance, [+segment[j], +segment[j + 1]], origin);
2380
- segment[j] = x;
2381
- segment[j + 1] = y;
2382
- }
2383
-
2384
- return segment;
2385
- }
2386
- });
2387
- }
2388
- return clonePath(absolutePath);
2389
- }
2390
-
2391
- /**
2392
- *
2393
- * @param {{x: number, y: number}} v0
2394
- * @param {{x: number, y: number}} v1
2395
- * @returns {{x: number, y: number}}
2396
- */
2397
- function angleBetween(v0, v1) {
2398
- const { x: v0x, y: v0y } = v0;
2399
- const { x: v1x, y: v1y } = v1;
2400
- const p = v0x * v1x + v0y * v1y;
2401
- const n = Math.sqrt((v0x ** 2 + v0y ** 2) * (v1x ** 2 + v1y ** 2));
2402
- const sign = v0x * v1y - v0y * v1x < 0 ? -1 : 1;
2403
- const angle = sign * Math.acos(p / n);
2404
-
2405
- return angle;
2406
- }
2407
-
2408
- /**
2409
- * Returns a {x,y} point at a given length, the total length and
2410
- * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
2411
- * @see https://github.com/MadLittleMods/svg-curve-lib/blob/master/src/js/svg-curve-lib.js
2412
- *
2413
- * @param {number} x1 the starting x position
2414
- * @param {number} y1 the starting y position
2415
- * @param {number} RX x-radius of the arc
2416
- * @param {number} RY y-radius of the arc
2417
- * @param {number} angle x-axis-rotation of the arc
2418
- * @param {number} LAF large-arc-flag of the arc
2419
- * @param {number} SF sweep-flag of the arc
2420
- * @param {number} x the ending x position
2421
- * @param {number} y the ending y position
2422
- * @param {number} t the point distance
2423
- * @returns {{x: number, y: number}} the requested point
2424
- */
2425
- function getPointAtArcSegmentLength(x1, y1, RX, RY, angle, LAF, SF, x, y, t) {
2426
- const {
2427
- abs, sin, cos, sqrt, PI,
2428
- } = Math;
2429
- let rx = abs(RX);
2430
- let ry = abs(RY);
2431
- const xRot = ((angle % 360) + 360) % 360;
2432
- const xRotRad = xRot * (PI / 180);
2433
-
2434
- if (x1 === x && y1 === y) {
2435
- return { x: x1, y: y1 };
2436
- }
2437
-
2438
- if (rx === 0 || ry === 0) {
2439
- return segmentLineFactory(x1, y1, x, y, t).point;
2440
- }
2441
-
2442
- const dx = (x1 - x) / 2;
2443
- const dy = (y1 - y) / 2;
2444
-
2445
- const transformedPoint = {
2446
- x: cos(xRotRad) * dx + sin(xRotRad) * dy,
2447
- y: -sin(xRotRad) * dx + cos(xRotRad) * dy,
2448
- };
2449
-
2450
- const radiiCheck = transformedPoint.x ** 2 / rx ** 2 + transformedPoint.y ** 2 / ry ** 2;
2451
-
2452
- if (radiiCheck > 1) {
2453
- rx *= sqrt(radiiCheck);
2454
- ry *= sqrt(radiiCheck);
2455
- }
2456
-
2457
- const cSquareNumerator = rx ** 2 * ry ** 2
2458
- - rx ** 2 * transformedPoint.y ** 2
2459
- - ry ** 2 * transformedPoint.x ** 2;
2460
-
2461
- const cSquareRootDenom = rx ** 2 * transformedPoint.y ** 2
2462
- + ry ** 2 * transformedPoint.x ** 2;
2463
-
2464
- let cRadicand = cSquareNumerator / cSquareRootDenom;
2465
- cRadicand = cRadicand < 0 ? 0 : cRadicand;
2466
- const cCoef = (LAF !== SF ? 1 : -1) * sqrt(cRadicand);
2467
- const transformedCenter = {
2468
- x: cCoef * ((rx * transformedPoint.y) / ry),
2469
- y: cCoef * (-(ry * transformedPoint.x) / rx),
2470
- };
2471
-
2472
- const center = {
2473
- x: cos(xRotRad) * transformedCenter.x
2474
- - sin(xRotRad) * transformedCenter.y + (x1 + x) / 2,
2475
- y: sin(xRotRad) * transformedCenter.x
2476
- + cos(xRotRad) * transformedCenter.y + (y1 + y) / 2,
2477
- };
2478
-
2479
- const startVector = {
2480
- x: (transformedPoint.x - transformedCenter.x) / rx,
2481
- y: (transformedPoint.y - transformedCenter.y) / ry,
2482
- };
2483
-
2484
- const startAngle = angleBetween({ x: 1, y: 0 }, startVector);
2485
-
2486
- const endVector = {
2487
- x: (-transformedPoint.x - transformedCenter.x) / rx,
2488
- y: (-transformedPoint.y - transformedCenter.y) / ry,
2489
- };
2490
-
2491
- let sweepAngle = angleBetween(startVector, endVector);
2492
- if (!SF && sweepAngle > 0) {
2493
- sweepAngle -= 2 * PI;
2494
- } else if (SF && sweepAngle < 0) {
2495
- sweepAngle += 2 * PI;
2496
- }
2497
- sweepAngle %= 2 * PI;
2498
-
2499
- const alpha = startAngle + sweepAngle * t;
2500
- const ellipseComponentX = rx * cos(alpha);
2501
- const ellipseComponentY = ry * sin(alpha);
2502
-
2503
- const point = {
2504
- x: cos(xRotRad) * ellipseComponentX
2505
- - sin(xRotRad) * ellipseComponentY
2506
- + center.x,
2507
- y: sin(xRotRad) * ellipseComponentX
2508
- + cos(xRotRad) * ellipseComponentY
2509
- + center.y,
2510
- };
2511
-
2512
- // to be used later
2513
- // point.ellipticalArcStartAngle = startAngle;
2514
- // point.ellipticalArcEndAngle = startAngle + sweepAngle;
2515
- // point.ellipticalArcAngle = alpha;
2516
-
2517
- // point.ellipticalArcCenter = center;
2518
- // point.resultantRx = rx;
2519
- // point.resultantRy = ry;
2520
-
2521
- return point;
2522
- }
2523
-
2524
- /**
2525
- * Returns a {x,y} point at a given length, the total length and
2526
- * the shape minimum and maximum {x,y} coordinates of an A (arc-to) segment.
2527
- *
2528
- * @param {number} X1 the starting x position
2529
- * @param {number} Y1 the starting y position
2530
- * @param {number} RX x-radius of the arc
2531
- * @param {number} RY y-radius of the arc
2532
- * @param {number} angle x-axis-rotation of the arc
2533
- * @param {number} LAF large-arc-flag of the arc
2534
- * @param {number} SF sweep-flag of the arc
2535
- * @param {number} X2 the ending x position
2536
- * @param {number} Y2 the ending y position
2537
- * @param {number} distance the point distance
2538
- * @returns {SVGPath.lengthFactory} the segment length, point, min & max
2539
- */
2540
- function segmentArcFactory(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, distance) {
2541
- const distanceIsNumber = typeof distance === 'number';
2542
- let x = X1; let y = Y1;
2543
- let LENGTH = 0;
2544
- let prev = [x, y, LENGTH];
2545
- let cur = [x, y];
2546
- let t = 0;
2547
- let POINT = { x: 0, y: 0 };
2548
- let POINTS = [{ x, y }];
2549
-
2550
- if (distanceIsNumber && distance <= 0) {
2551
- POINT = { x, y };
2552
- }
2553
-
2554
- const sampleSize = 300;
2555
- for (let j = 0; j <= sampleSize; j += 1) {
2556
- t = j / sampleSize;
2557
-
2558
- ({ x, y } = getPointAtArcSegmentLength(X1, Y1, RX, RY, angle, LAF, SF, X2, Y2, t));
2559
- POINTS = [...POINTS, { x, y }];
2560
- LENGTH += distanceSquareRoot(cur, [x, y]);
2561
- cur = [x, y];
2562
-
2563
- if (distanceIsNumber && LENGTH > distance && distance > prev[2]) {
2564
- const dv = (LENGTH - distance) / (LENGTH - prev[2]);
2565
-
2566
- POINT = {
2567
- x: cur[0] * (1 - dv) + prev[0] * dv,
2568
- y: cur[1] * (1 - dv) + prev[1] * dv,
2569
- };
2570
- }
2571
- prev = [x, y, LENGTH];
2572
- }
2573
-
2574
- if (distanceIsNumber && distance >= LENGTH) {
2575
- POINT = { x: X2, y: Y2 };
2576
- }
2577
-
2578
- return {
2579
- length: LENGTH,
2580
- point: POINT,
2581
- min: {
2582
- x: Math.min(...POINTS.map((n) => n.x)),
2583
- y: Math.min(...POINTS.map((n) => n.y)),
2584
- },
2585
- max: {
2586
- x: Math.max(...POINTS.map((n) => n.x)),
2587
- y: Math.max(...POINTS.map((n) => n.y)),
2588
- },
2589
- };
2590
- }
2591
-
2592
- /**
2593
- * Returns a {x,y} point at a given length, the total length and
2594
- * the minimum and maximum {x,y} coordinates of a C (cubic-bezier) segment.
2595
- *
2596
- * @param {number} x1 the starting point X
2597
- * @param {number} y1 the starting point Y
2598
- * @param {number} c1x the first control point X
2599
- * @param {number} c1y the first control point Y
2600
- * @param {number} c2x the second control point X
2601
- * @param {number} c2y the second control point Y
2602
- * @param {number} x2 the ending point X
2603
- * @param {number} y2 the ending point Y
2604
- * @param {number} t a [0-1] ratio
2605
- * @returns {{x: number, y: number}} the cubic-bezier segment length
2606
- */
2607
- function getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t) {
2608
- const t1 = 1 - t;
2609
- return {
2610
- x: (t1 ** 3) * x1
2611
- + 3 * (t1 ** 2) * t * c1x
2612
- + 3 * t1 * (t ** 2) * c2x
2613
- + (t ** 3) * x2,
2614
- y: (t1 ** 3) * y1
2615
- + 3 * (t1 ** 2) * t * c1y
2616
- + 3 * t1 * (t ** 2) * c2y
2617
- + (t ** 3) * y2,
2618
- };
2619
- }
2620
-
2621
- /**
2622
- * Returns the length of a C (cubic-bezier) segment
2623
- * or an {x,y} point at a given length.
2624
- *
2625
- * @param {number} x1 the starting point X
2626
- * @param {number} y1 the starting point Y
2627
- * @param {number} c1x the first control point X
2628
- * @param {number} c1y the first control point Y
2629
- * @param {number} c2x the second control point X
2630
- * @param {number} c2y the second control point Y
2631
- * @param {number} x2 the ending point X
2632
- * @param {number} y2 the ending point Y
2633
- * @param {number=} distance the point distance
2634
- * @returns {SVGPath.lengthFactory} the segment length, point, min & max
2635
- */
2636
- function segmentCubicFactory(x1, y1, c1x, c1y, c2x, c2y, x2, y2, distance) {
2637
- const distanceIsNumber = typeof distance === 'number';
2638
- let x = x1; let y = y1;
2639
- let LENGTH = 0;
2640
- let prev = [x, y, LENGTH];
2641
- let cur = [x, y];
2642
- let t = 0;
2643
- let POINT = { x: 0, y: 0 };
2644
- let POINTS = [{ x, y }];
2645
-
2646
- if (distanceIsNumber && distance <= 0) {
2647
- POINT = { x, y };
2648
- }
2649
-
2650
- const sampleSize = 300;
2651
- for (let j = 0; j <= sampleSize; j += 1) {
2652
- t = j / sampleSize;
2653
-
2654
- ({ x, y } = getPointAtCubicSegmentLength(x1, y1, c1x, c1y, c2x, c2y, x2, y2, t));
2655
- POINTS = [...POINTS, { x, y }];
2656
- LENGTH += distanceSquareRoot(cur, [x, y]);
2657
- cur = [x, y];
2658
-
2659
- if (distanceIsNumber && LENGTH > distance && distance > prev[2]) {
2660
- const dv = (LENGTH - distance) / (LENGTH - prev[2]);
2661
-
2662
- POINT = {
2663
- x: cur[0] * (1 - dv) + prev[0] * dv,
2664
- y: cur[1] * (1 - dv) + prev[1] * dv,
2665
- };
2666
- }
2667
- prev = [x, y, LENGTH];
2668
- }
2669
-
2670
- if (distanceIsNumber && distance >= LENGTH) {
2671
- POINT = { x: x2, y: y2 };
2672
- }
2673
-
2674
- return {
2675
- length: LENGTH,
2676
- point: POINT,
2677
- min: {
2678
- x: Math.min(...POINTS.map((n) => n.x)),
2679
- y: Math.min(...POINTS.map((n) => n.y)),
2680
- },
2681
- max: {
2682
- x: Math.max(...POINTS.map((n) => n.x)),
2683
- y: Math.max(...POINTS.map((n) => n.y)),
2684
- },
2685
- };
2686
- }
2687
-
2688
- /**
2689
- * Returns the {x,y} coordinates of a point at a
2690
- * given length of a quadratic-bezier segment.
2691
- *
2692
- * @see https://github.com/substack/point-at-length
2693
- *
2694
- * @param {number} x1 the starting point X
2695
- * @param {number} y1 the starting point Y
2696
- * @param {number} cx the control point X
2697
- * @param {number} cy the control point Y
2698
- * @param {number} x2 the ending point X
2699
- * @param {number} y2 the ending point Y
2700
- * @param {number} t a [0-1] ratio
2701
- * @returns {{x: number, y: number}} the requested {x,y} coordinates
2702
- */
2703
- function getPointAtQuadSegmentLength(x1, y1, cx, cy, x2, y2, t) {
2704
- const t1 = 1 - t;
2705
- return {
2706
- x: (t1 ** 2) * x1
2707
- + 2 * t1 * t * cx
2708
- + (t ** 2) * x2,
2709
- y: (t1 ** 2) * y1
2710
- + 2 * t1 * t * cy
2711
- + (t ** 2) * y2,
2712
- };
2713
- }
2714
-
2715
- /**
2716
- * Returns a {x,y} point at a given length, the total length and
2717
- * the minimum and maximum {x,y} coordinates of a Q (quadratic-bezier) segment.
2718
- *
2719
- * @param {number} x1 the starting point X
2720
- * @param {number} y1 the starting point Y
2721
- * @param {number} qx the control point X
2722
- * @param {number} qy the control point Y
2723
- * @param {number} x2 the ending point X
2724
- * @param {number} y2 the ending point Y
2725
- * @param {number=} distance the distance to point
2726
- * @returns {SVGPath.lengthFactory} the segment length, point, min & max
2727
- */
2728
- function segmentQuadFactory(x1, y1, qx, qy, x2, y2, distance) {
2729
- const distanceIsNumber = typeof distance === 'number';
2730
- let x = x1; let y = y1;
2731
- let LENGTH = 0;
2732
- let prev = [x, y, LENGTH];
2733
- let cur = [x, y];
2734
- let t = 0;
2735
- let POINT = { x: 0, y: 0 };
2736
- let POINTS = [{ x, y }];
2737
-
2738
- if (distanceIsNumber && distance <= 0) {
2739
- POINT = { x, y };
2740
- }
2741
-
2742
- const sampleSize = 300;
2743
- for (let j = 0; j <= sampleSize; j += 1) {
2744
- t = j / sampleSize;
2745
-
2746
- ({ x, y } = getPointAtQuadSegmentLength(x1, y1, qx, qy, x2, y2, t));
2747
- POINTS = [...POINTS, { x, y }];
2748
- LENGTH += distanceSquareRoot(cur, [x, y]);
2749
- cur = [x, y];
2750
-
2751
- if (distanceIsNumber && LENGTH > distance && distance > prev[2]) {
2752
- const dv = (LENGTH - distance) / (LENGTH - prev[2]);
2753
-
2754
- POINT = {
2755
- x: cur[0] * (1 - dv) + prev[0] * dv,
2756
- y: cur[1] * (1 - dv) + prev[1] * dv,
2757
- };
2758
- }
2759
- prev = [x, y, LENGTH];
2760
- }
2761
-
2762
- /* istanbul ignore else */
2763
- if (distanceIsNumber && distance >= LENGTH) {
2764
- POINT = { x: x2, y: y2 };
2765
- }
2766
-
2767
- return {
2768
- length: LENGTH,
2769
- point: POINT,
2770
- min: {
2771
- x: Math.min(...POINTS.map((n) => n.x)),
2772
- y: Math.min(...POINTS.map((n) => n.y)),
2773
- },
2774
- max: {
2775
- x: Math.max(...POINTS.map((n) => n.x)),
2776
- y: Math.max(...POINTS.map((n) => n.y)),
2777
- },
2778
- };
2779
- }
2780
-
2781
- /**
2782
- * Returns a {x,y} point at a given length
2783
- * of a shape, the shape total length and
2784
- * the shape minimum and maximum {x,y} coordinates.
2785
- *
2786
- * @param {string | SVGPath.pathArray} pathInput the `pathArray` to look into
2787
- * @param {number=} distance the length of the shape to look at
2788
- * @returns {SVGPath.lengthFactory} the path length, point, min & max
2789
- */
2790
- function pathLengthFactory(pathInput, distance) {
2791
- const path = normalizePath(pathInput);
2792
- const distanceIsNumber = typeof distance === 'number';
2793
- let isM;
2794
- let data = [];
2795
- let pathCommand;
2796
- let x = 0;
2797
- let y = 0;
2798
- let mx = 0;
2799
- let my = 0;
2800
- let seg;
2801
- let MIN = [];
2802
- let MAX = [];
2803
- let length = 0;
2804
- let min = { x: 0, y: 0 };
2805
- let max = min;
2806
- let point = min;
2807
- let POINT = min;
2808
- let LENGTH = 0;
2809
-
2810
- for (let i = 0, ll = path.length; i < ll; i += 1) {
2811
- seg = path[i];
2812
- [pathCommand] = seg;
2813
- isM = pathCommand === 'M';
2814
- data = !isM ? [x, y, ...seg.slice(1)] : data;
2815
-
2816
- // this segment is always ZERO
2817
- /* istanbul ignore else */
2818
- if (isM) {
2819
- // remember mx, my for Z
2820
- [, mx, my] = seg;
2821
- min = { x: mx, y: my };
2822
- max = min;
2823
- length = 0;
2824
-
2825
- if (distanceIsNumber && distance < 0.001) {
2826
- POINT = min;
2827
- }
2828
- } else if (pathCommand === 'L') {
2829
- ({
2830
- length, min, max, point,
2831
- } = segmentLineFactory(...data, (distance || 0) - LENGTH));
2832
- } else if (pathCommand === 'A') {
2833
- ({
2834
- length, min, max, point,
2835
- } = segmentArcFactory(...data, (distance || 0) - LENGTH));
2836
- } else if (pathCommand === 'C') {
2837
- ({
2838
- length, min, max, point,
2839
- } = segmentCubicFactory(...data, (distance || 0) - LENGTH));
2840
- } else if (pathCommand === 'Q') {
2841
- ({
2842
- length, min, max, point,
2843
- } = segmentQuadFactory(...data, (distance || 0) - LENGTH));
2844
- } else if (pathCommand === 'Z') {
2845
- data = [x, y, mx, my];
2846
- ({
2847
- length, min, max, point,
2848
- } = segmentLineFactory(...data, (distance || 0) - LENGTH));
2849
- }
2850
-
2851
- if (distanceIsNumber && LENGTH < distance && LENGTH + length >= distance) {
2852
- POINT = point;
2853
- }
2854
-
2855
- MAX = [...MAX, max];
2856
- MIN = [...MIN, min];
2857
- LENGTH += length;
2858
-
2859
- [x, y] = pathCommand !== 'Z' ? seg.slice(-2) : [mx, my];
2860
- }
2861
-
2862
- // native `getPointAtLength` behavior when the given distance
2863
- // is higher than total length
2864
- if (distanceIsNumber && distance >= LENGTH) {
2865
- POINT = { x, y };
2866
- }
2867
-
2868
- return {
2869
- length: LENGTH,
2870
- point: POINT,
2871
- min: {
2872
- x: Math.min(...MIN.map((n) => n.x)),
2873
- y: Math.min(...MIN.map((n) => n.y)),
2874
- },
2875
- max: {
2876
- x: Math.max(...MAX.map((n) => n.x)),
2877
- y: Math.max(...MAX.map((n) => n.y)),
2878
- },
2879
- };
2880
- }
2881
-
2882
- /**
2883
- * Returns the bounding box of a shape.
2884
- *
2885
- * @param {SVGPath.pathArray=} path the shape `pathArray`
2886
- * @returns {SVGPath.pathBBox} the length of the cubic-bezier segment
2887
- */
2888
- function getPathBBox(path) {
2889
- if (!path) {
2890
- return {
2891
- x: 0, y: 0, width: 0, height: 0, x2: 0, y2: 0, cx: 0, cy: 0, cz: 0,
2892
- };
2893
- }
2894
-
2895
- const {
2896
- min: { x: xMin, y: yMin },
2897
- max: { x: xMax, y: yMax },
2898
- } = pathLengthFactory(path);
2899
-
2900
- const width = xMax - xMin;
2901
- const height = yMax - yMin;
2902
-
2903
- return {
2904
- width,
2905
- height,
2906
- x: xMin,
2907
- y: yMin,
2908
- x2: xMax,
2909
- y2: yMax,
2910
- cx: xMin + width / 2,
2911
- cy: yMin + height / 2,
2912
- // an estimted guess
2913
- cz: Math.max(width, height) + Math.min(width, height) / 2,
2914
- };
2915
- }
2916
-
2917
- /**
2918
- * Returns the shape total length, or the equivalent to `shape.getTotalLength()`.
2919
- *
2920
- * The `normalizePath` version is lighter, faster, more efficient and more accurate
2921
- * with paths that are not `curveArray`.
2922
- *
2923
- * @param {string | SVGPath.pathArray} pathInput the target `pathArray`
2924
- * @returns {number} the shape total length
2925
- */
2926
- function getTotalLength(pathInput) {
2927
- return pathLengthFactory(pathInput).length;
2928
- }
2929
-
2930
- /**
2931
- * Returns [x,y] coordinates of a point at a given length of a shape.
2932
- *
2933
- * @param {string | SVGPath.pathArray} pathInput the `pathArray` to look into
2934
- * @param {number} distance the length of the shape to look at
2935
- * @returns {{x: number, y: number}} the requested {x, y} point coordinates
2936
- */
2937
- function getPointAtLength(pathInput, distance) {
2938
- return pathLengthFactory(pathInput, distance).point;
2939
- }
2940
-
2941
- /**
2942
- * Creates a new SVGPathCommander instance with the following properties:
2943
- * * segments: `pathArray`
2944
- * * round: number
2945
- * * origin: [number, number, number?]
2946
- *
2947
- * @class
2948
- * @author thednp <https://github.com/thednp/svg-path-commander>
2949
- * @returns {SVGPathCommander} a new SVGPathCommander instance
2950
- */
2951
- class SVGPathCommander {
2952
- /**
2953
- * @constructor
2954
- * @param {string} pathValue the path string
2955
- * @param {any} config instance options
2956
- */
2957
- constructor(pathValue, config) {
2958
- const instanceOptions = config || {};
2959
-
2960
- const undefPath = typeof pathValue === 'undefined';
2961
-
2962
- if (undefPath || !pathValue.length) {
2963
- throw TypeError(`${error}: "pathValue" is ${undefPath ? 'undefined' : 'empty'}`);
2964
- }
2965
-
2966
- const segments = parsePathString(pathValue);
2967
- if (typeof segments === 'string') {
2968
- throw TypeError(segments);
2969
- }
2970
-
2971
- /**
2972
- * @type {SVGPath.pathArray}
2973
- */
2974
- this.segments = segments;
2975
-
2976
- const {
2977
- width, height, cx, cy, cz,
2978
- } = this.getBBox();
2979
-
2980
- // set instance options.round
2981
- const { round: roundOption, origin: originOption } = instanceOptions;
2982
- let round;
2983
-
2984
- if (roundOption === 'auto') {
2985
- const pathScale = (`${Math.floor(Math.max(width, height))}`).length;
2986
- round = pathScale >= 4 ? 0 : 4 - pathScale;
2987
- } else if (Number.isInteger(roundOption) || roundOption === 'off') {
2988
- round = roundOption;
2989
- } else {
2990
- ({ round } = defaultOptions);
2991
- }
2992
-
2993
- // set instance options.origin
2994
- // the SVGPathCommander class will always override the default origin
2995
- let origin;
2996
- if (Array.isArray(originOption) && originOption.length >= 2) {
2997
- const [originX, originY, originZ] = originOption.map(Number);
2998
- origin = [
2999
- !Number.isNaN(originX) ? originX : cx,
3000
- !Number.isNaN(originY) ? originY : cy,
3001
- !Number.isNaN(originZ) ? originZ : cz,
3002
- ];
3003
- } else {
3004
- origin = [cx, cy, cz];
3005
- }
3006
-
3007
- /** @type {number | 'off'} */
3008
- this.round = round;
3009
- /** @type {[number, number, number=]} */
3010
- this.origin = origin;
3011
-
3012
- return this;
3013
- }
3014
-
3015
- /**
3016
- * Returns the path bounding box, equivalent to native `path.getBBox()`.
3017
- * @public
3018
- * @returns {SVGPath.pathBBox}
3019
- */
3020
- getBBox() {
3021
- return getPathBBox(this.segments);
3022
- }
3023
-
3024
- /**
3025
- * Returns the total path length, equivalent to native `path.getTotalLength()`.
3026
- * @public
3027
- * @returns {number}
3028
- */
3029
- getTotalLength() {
3030
- return getTotalLength(this.segments);
3031
- }
3032
-
3033
- /**
3034
- * Returns an `{x,y}` point in the path stroke at a given length,
3035
- * equivalent to the native `path.getPointAtLength()`.
3036
- *
3037
- * @public
3038
- * @param {number} length the length
3039
- * @returns {{x: number, y:number}} the requested point
3040
- */
3041
- getPointAtLength(length) {
3042
- return getPointAtLength(this.segments, length);
3043
- }
3044
-
3045
- /**
3046
- * Convert path to absolute values
3047
- * @public
3048
- */
3049
- toAbsolute() {
3050
- const { segments } = this;
3051
- this.segments = pathToAbsolute(segments);
3052
- return this;
3053
- }
3054
-
3055
- /**
3056
- * Convert path to relative values
3057
- * @public
3058
- */
3059
- toRelative() {
3060
- const { segments } = this;
3061
- this.segments = pathToRelative(segments);
3062
- return this;
3063
- }
3064
-
3065
- /**
3066
- * Convert path to cubic-bezier values. In addition, un-necessary `Z`
3067
- * segment is removed if previous segment extends to the `M` segment.
3068
- *
3069
- * @public
3070
- */
3071
- toCurve() {
3072
- const { segments } = this;
3073
- this.segments = pathToCurve(segments);
3074
- return this;
3075
- }
3076
-
3077
- /**
3078
- * Reverse the order of the segments and their values.
3079
- * @param {boolean} onlySubpath option to reverse all sub-paths except first
3080
- * @public
3081
- */
3082
- reverse(onlySubpath) {
3083
- this.toAbsolute();
3084
-
3085
- const { segments } = this;
3086
- const split = splitPath(segments);
3087
- const subPath = split.length > 1 ? split : 0;
3088
-
3089
- const absoluteMultiPath = subPath && clonePath(subPath).map((x, i) => {
3090
- if (onlySubpath) {
3091
- return i ? reversePath(x) : parsePathString(x);
3092
- }
3093
- return reversePath(x);
3094
- });
3095
-
3096
- let path = [];
3097
- if (subPath) {
3098
- path = absoluteMultiPath.flat(1);
3099
- } else {
3100
- path = onlySubpath ? segments : reversePath(segments);
3101
- }
3102
-
3103
- this.segments = clonePath(path);
3104
- return this;
3105
- }
3106
-
3107
- /**
3108
- * Normalize path in 2 steps:
3109
- * * convert `pathArray`(s) to absolute values
3110
- * * convert shorthand notation to standard notation
3111
- * @public
3112
- */
3113
- normalize() {
3114
- const { segments } = this;
3115
- this.segments = normalizePath(segments);
3116
- return this;
3117
- }
3118
-
3119
- /**
3120
- * Optimize `pathArray` values:
3121
- * * convert segments to absolute and/or relative values
3122
- * * select segments with shortest resulted string
3123
- * * round values to the specified `decimals` option value
3124
- * @public
3125
- */
3126
- optimize() {
3127
- const { segments } = this;
3128
-
3129
- this.segments = optimizePath(segments, this.round);
3130
- return this;
3131
- }
3132
-
3133
- /**
3134
- * Transform path using values from an `Object` defined as `transformObject`.
3135
- * @see SVGPath.transformObject for a quick refference
3136
- *
3137
- * @param {SVGPath.transformObject} source a `transformObject`as described above
3138
- * @public
3139
- */
3140
- transform(source) {
3141
- if (!source || typeof source !== 'object' || (typeof source === 'object'
3142
- && !['translate', 'rotate', 'skew', 'scale'].some((x) => x in source))) return this;
3143
-
3144
- /** @type {SVGPath.transformObject} */
3145
- const transform = {};
3146
- Object.keys(source).forEach((fn) => {
3147
- transform[fn] = Array.isArray(source[fn]) ? [...source[fn]] : Number(source[fn]);
3148
- });
3149
- const { segments } = this;
3150
-
3151
- // if origin is not specified
3152
- // it's important that we have one
3153
- const [cx, cy, cz] = this.origin;
3154
- const { origin } = transform;
3155
-
3156
- if (Array.isArray(origin) && origin.length >= 2) {
3157
- const [originX, originY, originZ] = origin.map(Number);
3158
- transform.origin = [
3159
- !Number.isNaN(originX) ? originX : cx,
3160
- !Number.isNaN(originY) ? originY : cy,
3161
- originZ || cz,
3162
- ];
3163
- } else {
3164
- transform.origin = [cx, cy, cz];
3165
- }
3166
-
3167
- this.segments = transformPath(segments, transform);
3168
- return this;
3169
- }
3170
-
3171
- /**
3172
- * Rotate path 180deg vertically
3173
- * @public
3174
- */
3175
- flipX() {
3176
- this.transform({ rotate: [0, 180, 0] });
3177
- return this;
3178
- }
3179
-
3180
- /**
3181
- * Rotate path 180deg horizontally
3182
- * @public
3183
- */
3184
- flipY() {
3185
- this.transform({ rotate: [180, 0, 0] });
3186
- return this;
3187
- }
3188
-
3189
- /**
3190
- * Export the current path to be used
3191
- * for the `d` (description) attribute.
3192
- * @public
3193
- * @return {String} the path string
3194
- */
3195
- toString() {
3196
- return pathToString(this.segments, this.round);
3197
- }
3198
- }
3199
-
3200
- /**
3201
- * Returns the area of a single cubic-bezier segment.
3202
- *
3203
- * http://objectmix.com/graphics/133553-area-closed-bezier-curve.html
3204
- *
3205
- * @param {number} x1 the starting point X
3206
- * @param {number} y1 the starting point Y
3207
- * @param {number} c1x the first control point X
3208
- * @param {number} c1y the first control point Y
3209
- * @param {number} c2x the second control point X
3210
- * @param {number} c2y the second control point Y
3211
- * @param {number} x2 the ending point X
3212
- * @param {number} y2 the ending point Y
3213
- * @returns {number} the area of the cubic-bezier segment
3214
- */
3215
- function getCubicSegArea(x1, y1, c1x, c1y, c2x, c2y, x2, y2) {
3216
- return (3 * ((y2 - y1) * (c1x + c2x) - (x2 - x1) * (c1y + c2y)
3217
- + (c1y * (x1 - c2x)) - (c1x * (y1 - c2y))
3218
- + (y2 * (c2x + x1 / 3)) - (x2 * (c2y + y1 / 3)))) / 20;
3219
- }
3220
-
3221
- /**
3222
- * Returns the area of a shape.
3223
- * @author Jürg Lehni & Jonathan Puckey
3224
- *
3225
- * @see https://github.com/paperjs/paper.js/blob/develop/src/path/Path.js
3226
- *
3227
- * @param {SVGPath.pathArray} path the shape `pathArray`
3228
- * @returns {number} the length of the cubic-bezier segment
3229
- */
3230
- function getPathArea(path) {
3231
- let x = 0; let y = 0; let len = 0;
3232
-
3233
- return pathToCurve(path).map((seg) => {
3234
- switch (seg[0]) {
3235
- case 'M':
3236
- [, x, y] = seg;
3237
- return 0;
3238
- default:
3239
- len = getCubicSegArea(x, y, ...seg.slice(1));
3240
- [x, y] = seg.slice(-2);
3241
- return len;
3242
- }
3243
- }).reduce((a, b) => a + b, 0);
3244
- }
3245
-
3246
- /**
3247
- * Check if a path is drawn clockwise and returns true if so,
3248
- * false otherwise.
3249
- *
3250
- * @param {SVGPath.pathArray} path the path string or `pathArray`
3251
- * @returns {boolean} true when clockwise or false if not
3252
- */
3253
- function getDrawDirection(path) {
3254
- return getPathArea(pathToCurve(path)) >= 0;
3255
- }
3256
-
3257
- /**
3258
- * Returns the segment, its index and length as well as
3259
- * the length to that segment at a given length in a path.
3260
- *
3261
- * @param {string | SVGPath.pathArray} pathInput target `pathArray`
3262
- * @param {number=} distance the given length
3263
- * @returns {SVGPath.segmentProperties=} the requested properties
3264
- */
3265
- function getPropertiesAtLength(pathInput, distance) {
3266
- const pathArray = parsePathString(pathInput);
3267
-
3268
- if (typeof pathArray === 'string') {
3269
- throw TypeError(pathArray);
3270
- }
3271
-
3272
- let pathTemp = [...pathArray];
3273
- let pathLength = getTotalLength(pathTemp);
3274
- let index = pathTemp.length - 1;
3275
- let lengthAtSegment = 0;
3276
- let length = 0;
3277
- let segment = pathArray[0];
3278
- const [x, y] = segment.slice(-2);
3279
- const point = { x, y };
3280
-
3281
- // If the path is empty, return 0.
3282
- if (index <= 0 || !distance || !Number.isFinite(distance)) {
3283
- return {
3284
- segment, index: 0, length, point, lengthAtSegment,
3285
- };
3286
- }
3287
-
3288
- if (distance >= pathLength) {
3289
- pathTemp = pathArray.slice(0, -1);
3290
- lengthAtSegment = getTotalLength(pathTemp);
3291
- length = pathLength - lengthAtSegment;
3292
- return {
3293
- segment: pathArray[index], index, length, lengthAtSegment,
3294
- };
3295
- }
3296
-
3297
- const segments = [];
3298
- while (index > 0) {
3299
- segment = pathTemp[index];
3300
- pathTemp = pathTemp.slice(0, -1);
3301
- lengthAtSegment = getTotalLength(pathTemp);
3302
- length = pathLength - lengthAtSegment;
3303
- pathLength = lengthAtSegment;
3304
- segments.push({
3305
- segment, index, length, lengthAtSegment,
3306
- });
3307
- index -= 1;
3308
- }
3309
-
3310
- return segments.find(({ lengthAtSegment: l }) => l <= distance);
3311
- }
3312
-
3313
- /**
3314
- * Returns the point and segment in path closest to a given point as well as
3315
- * the distance to the path stroke.
3316
- * @see https://bl.ocks.org/mbostock/8027637
3317
- *
3318
- * @param {string | SVGPath.pathArray} pathInput target `pathArray`
3319
- * @param {{x: number, y: number}} point the given point
3320
- * @returns {SVGPath.pointProperties} the requested properties
3321
- */
3322
- function getPropertiesAtPoint(pathInput, point) {
3323
- const path = (parsePathString(pathInput));
3324
- const normalPath = normalizePath(path);
3325
- const pathLength = getTotalLength(path);
3326
- /** @param {{x: number, y: number}} p */
3327
- const distanceTo = (p) => {
3328
- const dx = p.x - point.x;
3329
- const dy = p.y - point.y;
3330
- return dx * dx + dy * dy;
3331
- };
3332
- let precision = 8;
3333
- let scan;
3334
- let scanDistance = 0;
3335
- let closest;
3336
- let bestLength = 0;
3337
- let bestDistance = Infinity;
3338
-
3339
- // linear scan for coarse approximation
3340
- for (let scanLength = 0; scanLength <= pathLength; scanLength += precision) {
3341
- scan = getPointAtLength(normalPath, scanLength);
3342
- scanDistance = distanceTo(scan);
3343
- if (scanDistance < bestDistance) {
3344
- closest = scan;
3345
- bestLength = scanLength;
3346
- bestDistance = scanDistance;
3347
- }
3348
- }
3349
-
3350
- // binary search for precise estimate
3351
- precision /= 2;
3352
- let before;
3353
- let after;
3354
- let beforeLength = 0;
3355
- let afterLength = 0;
3356
- let beforeDistance = 0;
3357
- let afterDistance = 0;
3358
-
3359
- while (precision > 0.5) {
3360
- beforeLength = bestLength - precision;
3361
- before = getPointAtLength(normalPath, beforeLength);
3362
- beforeDistance = distanceTo(before);
3363
- afterLength = bestLength + precision;
3364
- after = getPointAtLength(normalPath, afterLength);
3365
- afterDistance = distanceTo(after);
3366
- if (beforeLength >= 0 && beforeDistance < bestDistance) {
3367
- closest = before;
3368
- bestLength = beforeLength;
3369
- bestDistance = beforeDistance;
3370
- } else if (afterLength <= pathLength && afterDistance < bestDistance) {
3371
- closest = after;
3372
- bestLength = afterLength;
3373
- bestDistance = afterDistance;
3374
- } else {
3375
- precision /= 2;
3376
- }
3377
- }
3378
-
3379
- const segment = getPropertiesAtLength(path, bestLength);
3380
- const distance = Math.sqrt(bestDistance);
3381
-
3382
- return { closest, distance, segment };
3383
- }
3384
-
3385
- /**
3386
- * Returns the point in path closest to a given point.
3387
- *
3388
- * @param {string | SVGPath.pathArray} pathInput target `pathArray`
3389
- * @param {{x: number, y: number}} point the given point
3390
- * @returns {{x: number, y: number}} the best match
3391
- */
3392
- function getClosestPoint(pathInput, point) {
3393
- return getPropertiesAtPoint(pathInput, point).closest;
3394
- }
3395
-
3396
- /**
3397
- * Returns the path segment which contains a given point.
3398
- *
3399
- * @param {string | SVGPath.pathArray} path the `pathArray` to look into
3400
- * @param {{x: number, y: number}} point the point of the shape to look for
3401
- * @returns {SVGPath.pathSegment?} the requested segment
3402
- */
3403
- function getSegmentOfPoint(path, point) {
3404
- return getPropertiesAtPoint(path, point).segment;
3405
- }
3406
-
3407
- /**
3408
- * Returns the segment at a given length.
3409
- * @param {string | SVGPath.pathArray} pathInput the target `pathArray`
3410
- * @param {number} distance the distance in path to look at
3411
- * @returns {SVGPath.pathSegment?} the requested segment
3412
- */
3413
- function getSegmentAtLength(pathInput, distance) {
3414
- return getPropertiesAtLength(pathInput, distance).segment;
3415
- }
3416
-
3417
- /**
3418
- * Checks if a given point is in the stroke of a path.
3419
- *
3420
- * @param {string | SVGPath.pathArray} pathInput target path
3421
- * @param {{x: number, y: number}} point the given `{x,y}` point
3422
- * @returns {boolean} the query result
3423
- */
3424
- function isPointInStroke(pathInput, point) {
3425
- const { distance } = getPropertiesAtPoint(pathInput, point);
3426
- return Math.abs(distance) < 0.001; // 0.01 might be more permissive
3427
- }
3428
-
3429
- /**
3430
- * Parses a path string value to determine its validity
3431
- * then returns true if it's valid or false otherwise.
3432
- *
3433
- * @param {string} pathString the path string to be parsed
3434
- * @returns {boolean} the path string validity
3435
- */
3436
- function isValidPath(pathString) {
3437
- if (typeof pathString !== 'string') {
3438
- return false;
3439
- }
3440
-
3441
- const path = new PathParser(pathString);
3442
-
3443
- skipSpaces(path);
3444
-
3445
- while (path.index < path.max && !path.err.length) {
3446
- scanSegment(path);
3447
- }
3448
-
3449
- return !path.err.length && 'mM'.includes(path.segments[0][0]);
3450
- }
3451
-
3452
- /**
3453
- * Supported shapes and their specific parameters.
3454
- * @type {Object.<string, string[]>}
3455
- */
3456
- const shapeParams = {
3457
- line: ['x1', 'y1', 'x2', 'y2'],
3458
- circle: ['cx', 'cy', 'r'],
3459
- ellipse: ['cx', 'cy', 'rx', 'ry'],
3460
- rect: ['width', 'height', 'x', 'y', 'rx', 'ry'],
3461
- polygon: ['points'],
3462
- polyline: ['points'],
3463
- glyph: ['d'],
3464
- };
3465
-
3466
- /**
3467
- * Returns a new `pathArray` from line attributes.
3468
- *
3469
- * @param {SVGPath.lineAttr} attr shape configuration
3470
- * @returns {SVGPath.pathArray} a new line `pathArray`
3471
- */
3472
- function getLinePath(attr) {
3473
- const {
3474
- x1, y1, x2, y2,
3475
- } = attr;
3476
- return [['M', x1, y1], ['L', x2, y2]];
3477
- }
3478
-
3479
- /**
3480
- * Returns a new `pathArray` like from polyline/polygon attributes.
3481
- *
3482
- * @param {SVGPath.polyAttr} attr shape configuration
3483
- * @return {SVGPath.pathArray} a new polygon/polyline `pathArray`
3484
- */
3485
- function getPolyPath(attr) {
3486
- /** @type {SVGPath.pathArray} */
3487
- const pathArray = [];
3488
- const points = (attr.points || '').trim().split(/[\s|,]/).map(Number);
3489
-
3490
- let index = 0;
3491
- while (index < points.length) {
3492
- pathArray.push([(index ? 'L' : 'M'), (points[index]), (points[index + 1])]);
3493
- index += 2;
3494
- }
3495
-
3496
- return attr.type === 'polygon' ? [...pathArray, ['z']] : pathArray;
3497
- }
3498
-
3499
- /**
3500
- * Returns a new `pathArray` from circle attributes.
3501
- *
3502
- * @param {SVGPath.circleAttr} attr shape configuration
3503
- * @return {SVGPath.pathArray} a circle `pathArray`
3504
- */
3505
- function getCirclePath(attr) {
3506
- const {
3507
- cx, cy, r,
3508
- } = attr;
3509
-
3510
- return [
3511
- ['M', (cx - r), cy],
3512
- ['a', r, r, 0, 1, 0, (2 * r), 0],
3513
- ['a', r, r, 0, 1, 0, (-2 * r), 0],
3514
- ];
3515
- }
3516
-
3517
- /**
3518
- * Returns a new `pathArray` from ellipse attributes.
3519
- *
3520
- * @param {SVGPath.ellipseAttr} attr shape configuration
3521
- * @return {SVGPath.pathArray} an ellipse `pathArray`
3522
- */
3523
- function getEllipsePath(attr) {
3524
- const {
3525
- cx, cy, rx, ry,
3526
- } = attr;
3527
-
3528
- return [
3529
- ['M', (cx - rx), cy],
3530
- ['a', rx, ry, 0, 1, 0, (2 * rx), 0],
3531
- ['a', rx, ry, 0, 1, 0, (-2 * rx), 0],
3532
- ];
3533
- }
3534
-
3535
- /**
3536
- * Returns a new `pathArray` like from rect attributes.
3537
- *
3538
- * @param {SVGPath.rectAttr} attr object with properties above
3539
- * @return {SVGPath.pathArray} a new `pathArray` from `<rect>` attributes
3540
- */
3541
- function getRectanglePath(attr) {
3542
- const x = +attr.x || 0;
3543
- const y = +attr.y || 0;
3544
- const w = +attr.width;
3545
- const h = +attr.height;
3546
- let rx = +attr.rx;
3547
- let ry = +attr.ry;
3548
-
3549
- // Validity checks from http://www.w3.org/TR/SVG/shapes.html#RectElement:
3550
- if (rx || ry) {
3551
- rx = !rx ? ry : rx;
3552
- ry = !ry ? rx : ry;
3553
-
3554
- /* istanbul ignore else */
3555
- if (rx * 2 > w) rx -= (rx * 2 - w) / 2;
3556
- /* istanbul ignore else */
3557
- if (ry * 2 > h) ry -= (ry * 2 - h) / 2;
3558
-
3559
- return [
3560
- ['M', x + rx, y],
3561
- ['h', w - rx * 2],
3562
- ['s', rx, 0, rx, ry],
3563
- ['v', h - ry * 2],
3564
- ['s', 0, ry, -rx, ry],
3565
- ['h', -w + rx * 2],
3566
- ['s', -rx, 0, -rx, -ry],
3567
- ['v', -h + ry * 2],
3568
- ['s', 0, -ry, rx, -ry],
3569
- ];
3570
- }
3571
-
3572
- return [
3573
- ['M', x, y],
3574
- ['h', w],
3575
- ['v', h],
3576
- ['H', x],
3577
- ['Z'],
3578
- ];
3579
- }
3580
-
3581
- /**
3582
- * Returns a new `<path>` element created from attributes of a `<line>`, `<polyline>`,
3583
- * `<polygon>`, `<rect>`, `<ellipse>`, `<circle>` or `<glyph>`. If `replace` parameter
3584
- * is `true`, it will replace the target.
3585
- *
3586
- * It can also work with an options object,
3587
- * @see SVGPath.shapeOps
3588
- *
3589
- * The newly created `<path>` element keeps all non-specific
3590
- * attributes like `class`, `fill`, etc.
3591
- *
3592
- * @param {SVGPath.shapeTypes | SVGPath.shapeOps} element target shape
3593
- * @param {boolean=} replace option to replace target
3594
- * @return {SVGPathElement | boolean} the newly created `<path>` element
3595
- */
3596
- function shapeToPath(element, replace) {
3597
- const supportedShapes = Object.keys(shapeParams);
3598
- const { tagName } = element;
3599
-
3600
- if (tagName && !supportedShapes.some((s) => tagName === s)) {
3601
- throw TypeError(`${error}: "${tagName}" is not SVGElement`);
3602
- }
3603
-
3604
- const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
3605
- /** @type {string} */
3606
- const type = tagName || element.type;
3607
- /** @type {any} disables TS checking for something that's specific to shape */
3608
- const config = {};
3609
- config.type = type;
3610
- const shapeAttrs = shapeParams[type];
3611
-
3612
- if (tagName) {
3613
- shapeAttrs.forEach((p) => { config[p] = element.getAttribute(p); });
3614
- // set no-specific shape attributes: fill, stroke, etc
3615
- Object.values(element.attributes).forEach(({ name, value }) => {
3616
- if (!shapeAttrs.includes(name)) path.setAttribute(name, value);
3617
- });
3618
- } else {
3619
- Object.assign(config, element);
3620
- // set no-specific shape attributes: fill, stroke, etc
3621
- Object.keys(config).forEach((k) => {
3622
- if (!shapeAttrs.includes(k) && k !== 'type') {
3623
- path.setAttribute(k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`), config[k]);
3624
- }
3625
- });
3626
- }
3627
-
3628
- // set d
3629
- let description;
3630
- const { round } = defaultOptions;
3631
-
3632
- /* istanbul ignore else */
3633
- if (type === 'circle') description = pathToString(getCirclePath(config), round);
3634
- else if (type === 'ellipse') description = pathToString(getEllipsePath(config), round);
3635
- else if (['polyline', 'polygon'].includes(type)) description = pathToString(getPolyPath(config), round);
3636
- else if (type === 'rect') description = pathToString(getRectanglePath(config), round);
3637
- else if (type === 'line') description = pathToString(getLinePath(config), round);
3638
- else if (type === 'glyph') description = tagName ? element.getAttribute('d') : element.d;
3639
-
3640
- // replace target element
3641
- if (isValidPath(description)) {
3642
- path.setAttribute('d', description);
3643
- if (replace && tagName) {
3644
- element.before(path, element);
3645
- element.remove();
3646
- }
3647
- return path;
3648
- }
3649
- return false;
3650
- }
3651
-
3652
- /**
3653
- * Reverses all segments of a `pathArray`
3654
- * which consists of only C (cubic-bezier) path commands.
3655
- *
3656
- * @param {SVGPath.curveArray} path the source `pathArray`
3657
- * @returns {SVGPath.curveArray} the reversed `pathArray`
3658
- */
3659
- function reverseCurve(path) {
3660
- const rotatedCurve = path.slice(1)
3661
- .map((x, i, curveOnly) => (!i
3662
- ? [...path[0].slice(1), ...x.slice(1)]
3663
- : [...curveOnly[i - 1].slice(-2), ...x.slice(1)]))
3664
- .map((x) => x.map((_, i) => x[x.length - i - 2 * (1 - (i % 2))]))
3665
- .reverse();
3666
-
3667
- return [['M', ...rotatedCurve[0].slice(0, 2)],
3668
- ...rotatedCurve.map((x) => ['C', ...x.slice(2)])];
3669
- }
3670
-
3671
- /**
3672
- * Checks a `pathArray` for an unnecessary `Z` segment
3673
- * and returns a new `pathArray` without it.
3674
- *
3675
- * The `pathInput` must be a single path, without
3676
- * sub-paths. For multi-path `<path>` elements,
3677
- * use `splitPath` first and apply this utility on each
3678
- * sub-path separately.
3679
- *
3680
- * @param {SVGPath.pathArray | string} pathInput the `pathArray` source
3681
- * @return {SVGPath.pathArray} a fixed `pathArray`
3682
- */
3683
- function fixPath(pathInput) {
3684
- const pathArray = parsePathString(pathInput);
3685
- const normalArray = normalizePath(pathArray);
3686
- const { length } = pathArray;
3687
- const isClosed = normalArray.slice(-1)[0][0] === 'Z';
3688
- const segBeforeZ = isClosed ? length - 2 : length - 1;
3689
-
3690
- const [mx, my] = normalArray[0].slice(1);
3691
- const [x, y] = normalArray[segBeforeZ].slice(-2);
3692
-
3693
- /* istanbul ignore else */
3694
- if (isClosed && mx === x && my === y) {
3695
- return pathArray.slice(0, -1);
3696
- }
3697
- return pathArray;
3698
- }
3699
-
3700
- /**
3701
- * @interface
3702
- */
3703
- const Util = {
3704
- CSSMatrix,
3705
- parsePathString,
3706
- isPathArray,
3707
- isCurveArray,
3708
- isAbsoluteArray,
3709
- isRelativeArray,
3710
- isNormalizedArray,
3711
- isValidPath,
3712
- pathToAbsolute,
3713
- pathToRelative,
3714
- pathToCurve,
3715
- pathToString,
3716
- getDrawDirection,
3717
- getPathArea,
3718
- getPathBBox,
3719
- pathLengthFactory,
3720
- getTotalLength,
3721
- getPointAtLength,
3722
- getClosestPoint,
3723
- getSegmentOfPoint,
3724
- getPropertiesAtPoint,
3725
- getPropertiesAtLength,
3726
- getSegmentAtLength,
3727
- isPointInStroke,
3728
- clonePath,
3729
- splitPath,
3730
- fixPath,
3731
- roundPath,
3732
- optimizePath,
3733
- reverseCurve,
3734
- reversePath,
3735
- normalizePath,
3736
- transformPath,
3737
- shapeToPath,
3738
- options: defaultOptions,
3739
- };
3740
-
3741
- var version = "1.0.5";
3742
-
3743
- /**
3744
- * A global namespace for library version.
3745
- * @type {string}
3746
- */
3747
- const Version = version;
3748
-
3749
- /** @typedef {import('../types/index')} */
3750
-
3751
- // Export to global
3752
- Object.assign(SVGPathCommander, Util, { Version });
3753
-
3754
- export { SVGPathCommander as default };