svg-path-commander 1.0.4 → 2.0.0-alpha1

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