-
Notifications
You must be signed in to change notification settings - Fork 18
/
pathToRelative.js
101 lines (93 loc) · 2.88 KB
/
pathToRelative.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import parsePathString from '../parser/parsePathString';
import clonePath from '../process/clonePath';
import isRelativeArray from '../util/isRelativeArray';
/**
* Parses a path string value or object and returns an array
* of segments, all converted to relative values.
*
* @param {string | SVGPath.pathArray} pathInput the path string | object
* @returns {SVGPath.relativeArray} the resulted `pathArray` with relative values
*/
export default function pathToRelative(pathInput) {
/* istanbul ignore else */
if (isRelativeArray(pathInput)) {
// @ts-ignore -- `isRelativeArray` checks if it's `pathArray`
return clonePath(pathInput);
}
const path = parsePathString(pathInput);
let x = 0; let y = 0;
let mx = 0; let my = 0;
// @ts-ignore -- this is actually a `relativeArray`
return path.map((segment) => {
const values = segment.slice(1).map(Number);
const [pathCommand] = segment;
/** @type {SVGPath.relativeCommand} */
// @ts-ignore
const relativeCommand = pathCommand.toLowerCase();
if (pathCommand === 'M') {
[x, y] = values;
mx = x;
my = y;
return ['M', x, y];
}
/** @type {SVGPath.relativeSegment} */
// @ts-ignore -- trust me DON'T CHANGE
let relativeSegment = [];
if (pathCommand !== relativeCommand) {
switch (relativeCommand) {
case 'a':
relativeSegment = [
relativeCommand, values[0], values[1], values[2],
values[3], values[4], values[5] - x, values[6] - y];
break;
case 'v':
relativeSegment = [relativeCommand, values[0] - y];
break;
case 'h':
relativeSegment = [relativeCommand, values[0] - x];
break;
default: {
// use brakets for `eslint: no-case-declaration`
// https://stackoverflow.com/a/50753272/803358
const relValues = values.map((n, j) => n - (j % 2 ? y : x));
// @ts-ignore for M, L, C, S, Q, T
relativeSegment = [relativeCommand, ...relValues];
// this branch makes no sense anymore
// if (relativeCommand === 'm') {
// [x, y] = values;
// mx = x;
// my = y;
// }
}
}
} else {
if (pathCommand === 'm') {
mx = values[0] + x;
my = values[1] + y;
}
// @ts-ignore
relativeSegment = [relativeCommand, ...values];
}
const segLength = relativeSegment.length;
switch (relativeCommand) {
case 'z':
x = mx;
y = my;
break;
case 'h':
// @ts-ignore
x += relativeSegment[1];
break;
case 'v':
// @ts-ignore
y += relativeSegment[1];
break;
default:
// @ts-ignore
x += relativeSegment[segLength - 2];
// @ts-ignore
y += relativeSegment[segLength - 1];
}
return relativeSegment;
});
}