Skip to content

🎥 Make videos programmatically with React

better SVG parsing

Jonny Burger4bf1d55fef27
diff --git a/packages/paths/src/get-bounding-box.ts b/packages/paths/src/get-bounding-box.ts
index 132eafe321..f223ef63a8 100644
--- a/packages/paths/src/get-bounding-box.ts
+++ b/packages/paths/src/get-bounding-box.ts
@@ -1,7 +1,8 @@
-import type {BoundingBox} from './helpers/types';
-import {unarc} from './helpers/unarc';
+import {parsePath} from './helpers/parse';
+import type {AbsoluteInstruction, BoundingBox} from './helpers/types';
+import {removeArcInstructions} from './helpers/unarc';
+import {unshort} from './helpers/unshort';
import {normalizePath} from './normalize-path';
-import {unshort} from './unshort';
type minMax = [min: number, max: number];
@@ -89,69 +90,69 @@ export const getBoundingBox = (d: string): BoundingBox => {
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
- const abs = normalizePath(d);
- const unarced = unarc(abs);
+ const parsed = parsePath(normalizePath(d)) as AbsoluteInstruction[];
+ const unarced = removeArcInstructions(parsed);
const unshortened = unshort(unarced);
let x = 0;
let y = 0;
for (const seg of unshortened) {
- switch (seg[0]) {
+ switch (seg.type) {
case 'M':
case 'L': {
- if (minX > seg[1]) {
- minX = seg[1];
+ if (minX > seg.x) {
+ minX = seg.x;
}
- if (minY > seg[2]) {
- minY = seg[2];
+ if (minY > seg.y) {
+ minY = seg.y;
}
- if (maxX < seg[1]) {
- maxX = seg[1];
+ if (maxX < seg.x) {
+ maxX = seg.x;
}
- if (maxY < seg[2]) {
- maxY = seg[2];
+ if (maxY < seg.y) {
+ maxY = seg.y;
}
- x = seg[1];
- y = seg[2];
+ x = seg.x;
+ y = seg.y;
break;
}
case 'V': {
- if (minY > seg[1]) {
- minY = seg[1];
+ if (minY > seg.y) {
+ minY = seg.y;
}
- if (maxY < seg[1]) {
- maxY = seg[1];
+ if (maxY < seg.y) {
+ maxY = seg.y;
}
- y = seg[1];
+ y = seg.y;
break;
}
case 'H': {
- if (minX > seg[1]) {
- minX = seg[1];
+ if (minX > seg.x) {
+ minX = seg.x;
}
- if (maxX < seg[1]) {
- maxX = seg[1];
+ if (maxX < seg.x) {
+ maxX = seg.x;
}
- x = seg[1];
+ x = seg.x;
break;
}
case 'C': {
- const cxMinMax = minmaxC([x, seg[1], seg[3], seg[5]]);
+ const cxMinMax = minmaxC([x, seg.cp1x, seg.cp2x, seg.x]);
if (minX > cxMinMax[0]) {
minX = cxMinMax[0];
}
@@ -160,7 +161,7 @@ export const getBoundingBox = (d: string): BoundingBox => {
maxX = cxMinMax[1];
}
- const cyMinMax = minmaxC([y, seg[2], seg[4], seg[6]]);
+ const cyMinMax = minmaxC([y, seg.cp1y, seg.cp2y, seg.y]);
if (minY > cyMinMax[0]) {
minY = cyMinMax[0];
}
@@ -169,14 +170,14 @@ export const getBoundingBox = (d: string): BoundingBox => {
maxY = cyMinMax[1];
}
- x = seg[5];
- y = seg[6];
+ x = seg.x;
+ y = seg.y;
break;
}
case 'Q': {
- const qxMinMax = minmaxQ([x, seg[1], seg[3]]);
+ const qxMinMax = minmaxQ([x, seg.cpx, seg.x]);
if (minX > qxMinMax[0]) {
minX = qxMinMax[0];
}
@@ -185,7 +186,7 @@ export const getBoundingBox = (d: string): BoundingBox => {
maxX = qxMinMax[1];
}
- const qyMinMax = minmaxQ([y, seg[2], seg[4]]);
+ const qyMinMax = minmaxQ([y, seg.cpy, seg.y]);
if (minY > qyMinMax[0]) {
minY = qyMinMax[0];
}
@@ -194,8 +195,8 @@ export const getBoundingBox = (d: string): BoundingBox => {
maxY = qyMinMax[1];
}
- x = seg[3];
- y = seg[4];
+ x = seg.x;
+ y = seg.y;
break;
}
@@ -204,7 +205,7 @@ export const getBoundingBox = (d: string): BoundingBox => {
break;
default:
- throw new Error(`Unknown instruction ${seg[0]}`);
+ throw new Error(`Unknown instruction ${seg.type}`);
}
}
diff --git a/packages/paths/src/get-subpaths.ts b/packages/paths/src/get-subpaths.ts
index 17cfe115e5..993009fa4e 100644
--- a/packages/paths/src/get-subpaths.ts
+++ b/packages/paths/src/get-subpaths.ts
@@ -1,4 +1,5 @@
import {construct} from './helpers/construct';
+import {serializePath} from './helpers/serialize';
/**
* Splits a valid SVG path into it's parts.
@@ -8,9 +9,7 @@ import {construct} from './helpers/construct';
export const getSubpaths = (path: string): string[] => {
const {segments} = construct(path);
- return segments
- .map((seg) => {
- return seg.map((s) => s.join(' '));
- })
- .map((_s) => _s.join(' '));
+ return segments.map((seg) => {
+ return serializePath(seg);
+ });
};
diff --git a/packages/paths/src/helpers/construct.ts b/packages/paths/src/helpers/construct.ts
index 923d2dc371..aa3844f87b 100644
--- a/packages/paths/src/helpers/construct.ts
+++ b/packages/paths/src/helpers/construct.ts
@@ -3,9 +3,8 @@
import {makeArc} from './arc';
import {makeBezier} from './bezier';
import {makeLinearPosition} from './linear';
-import type {Instruction} from './parse';
import {parsePath} from './parse';
-import type {Point, PointArray, Properties} from './types';
+import type {Instruction, Point, PointArray, Properties} from './types';
export const construct = (string: string) => {
let length = 0;
@@ -23,112 +22,154 @@ export const construct = (string: string) => {
for (let i = 0; i < parsed.length; i++) {
const instruction = parsed[i];
- if (instruction[0].toLowerCase() !== 'm' && segments.length > 0) {
+ if (
+ instruction.type !== 'm' &&
+ instruction.type !== 'M' &&
+ segments.length > 0
+ ) {
segments[segments.length - 1].push(instruction);
}
// moveTo
- if (instruction[0] === 'M') {
- cur = [instruction[1], instruction[2]];
+ if (instruction.type === 'M') {
+ cur = [instruction.x, instruction.y];
ringStart = [cur[0], cur[1]];
segments.push([instruction]);
functions.push(null);
if (i === 0) {
- initial_point = {x: instruction[1], y: instruction[2]};
+ initial_point = {x: instruction.x, y: instruction.y};
}
- } else if (instruction[0] === 'm') {
- cur = [instruction[1] + cur[0], instruction[2] + cur[1]];
+ } else if (instruction.type === 'm') {
+ cur = [instruction.dx + cur[0], instruction.dy + cur[1]];
ringStart = [cur[0], cur[1]];
- segments.push([['M', cur[0], cur[1]]]);
+ segments.push([{type: 'M', x: cur[0], y: cur[1]}]);
functions.push(null);
// lineTo
- } else if (instruction[0] === 'L') {
+ } else if (instruction.type === 'L') {
length += Math.sqrt(
- (cur[0] - instruction[1]) ** 2 + (cur[1] - instruction[2]) ** 2
+ (cur[0] - instruction.x) ** 2 + (cur[1] - instruction.y) ** 2
);
functions.push(
- makeLinearPosition(cur[0], instruction[1], cur[1], instruction[2])
+ makeLinearPosition({
+ x0: cur[0],
+ x1: instruction.x,
+ y0: cur[1],
+ y1: instruction.y,
+ })
);
- cur = [instruction[1], instruction[2]];
- } else if (instruction[0] === 'l') {
- length += Math.sqrt(instruction[1] ** 2 + instruction[2] ** 2);
+ cur = [instruction.x, instruction.y];
+ } else if (instruction.type === 'l') {
+ length += Math.sqrt(instruction.dx ** 2 + instruction.dy ** 2);
functions.push(
- makeLinearPosition(
- cur[0],
- instruction[1] + cur[0],
- cur[1],
- instruction[2] + cur[1]
- )
+ makeLinearPosition({
+ x0: cur[0],
+ x1: instruction.dx + cur[0],
+ y0: cur[1],
+ y1: instruction.dy + cur[1],
+ })
);
- cur = [instruction[1] + cur[0], instruction[2] + cur[1]];
- } else if (instruction[0] === 'H') {
- length += Math.abs(cur[0] - instruction[1]);
+ cur = [instruction.dx + cur[0], instruction.dy + cur[1]];
+ } else if (instruction.type === 'H') {
+ length += Math.abs(cur[0] - instruction.x);
functions.push(
- makeLinearPosition(cur[0], instruction[1], cur[1], cur[1])
+ makeLinearPosition({
+ x0: cur[0],
+ x1: instruction.x,
+ y0: cur[1],
+ y1: cur[1],
+ })
);
- cur[0] = instruction[1];
- } else if (instruction[0] === 'h') {
- length += Math.abs(instruction[1]);
+ cur[0] = instruction.x;
+ } else if (instruction.type === 'h') {
+ length += Math.abs(instruction.dx);
functions.push(
- makeLinearPosition(cur[0], cur[0] + instruction[1], cur[1], cur[1])
+ makeLinearPosition({
+ x0: cur[0],
+ x1: cur[0] + instruction.dx,
+ y0: cur[1],
+ y1: cur[1],
+ })
);
- cur[0] = instruction[1] + cur[0];
- } else if (instruction[0] === 'V') {
- length += Math.abs(cur[1] - instruction[1]);
+ cur[0] = instruction.dx + cur[0];
+ } else if (instruction.type === 'V') {
+ length += Math.abs(cur[1] - instruction.y);
functions.push(
- makeLinearPosition(cur[0], cur[0], cur[1], instruction[1])
+ makeLinearPosition({
+ x0: cur[0],
+ x1: cur[0],
+ y0: cur[1],
+ y1: instruction.y,
+ })
);
- cur[1] = instruction[1];
- } else if (instruction[0] === 'v') {
- length += Math.abs(instruction[1]);
+ cur[1] = instruction.y;
+ } else if (instruction.type === 'v') {
+ length += Math.abs(instruction.dy);
functions.push(
- makeLinearPosition(cur[0], cur[0], cur[1], cur[1] + instruction[1])
+ makeLinearPosition({
+ x0: cur[0],
+ x1: cur[0],
+ y0: cur[1],
+ y1: cur[1] + instruction.dy,
+ })
);
- cur[1] = instruction[1] + cur[1];
+ cur[1] = instruction.dy + cur[1];
// Close path
- } else if (instruction[0] === 'z' || instruction[0] === 'Z') {
+ } else if (instruction.type === 'z' || instruction.type === 'Z') {
length += Math.sqrt(
(ringStart[0] - cur[0]) ** 2 + (ringStart[1] - cur[1]) ** 2
);
functions.push(
- makeLinearPosition(cur[0], ringStart[0], cur[1], ringStart[1])
+ makeLinearPosition({
+ x0: cur[0],
+ x1: ringStart[0],
+ y0: cur[1],
+ y1: ringStart[1],
+ })
);
cur = [ringStart[0], ringStart[1]];
// Cubic Bezier curves
- } else if (instruction[0] === 'C') {
+ } else if (instruction.type === 'C') {
curve = makeBezier({
ax: cur[0],
ay: cur[1],
- bx: instruction[1],
- by: instruction[2],
- cx: instruction[3],
- cy: instruction[4],
- dx: instruction[5],
- dy: instruction[6],
+ bx: instruction.cp1x,
+ by: instruction.cp1y,
+ cx: instruction.cp2x,
+ cy: instruction.cp2y,
+ dx: instruction.x,
+ dy: instruction.y,
});
length += curve.getTotalLength();
- cur = [instruction[5], instruction[6]];
+ cur = [instruction.x, instruction.y];
functions.push(curve);
- } else if (instruction[0] === 'c') {
+ } else if (instruction.type === 'c') {
curve = makeBezier({
ax: cur[0],
ay: cur[1],
- bx: cur[0] + instruction[1],
- by: cur[1] + instruction[2],
- cx: cur[0] + instruction[3],
- cy: cur[1] + instruction[4],
- dx: cur[0] + instruction[5],
- dy: cur[1] + instruction[6],
+ bx: cur[0] + instruction.cp1dx,
+ by: cur[1] + instruction.cp1dy,
+ cx: cur[0] + instruction.cp2dx,
+ cy: cur[1] + instruction.cp2dy,
+ dx: cur[0] + instruction.dx,
+ dy: cur[1] + instruction.dy,
});
if (curve.getTotalLength() > 0) {
length += curve.getTotalLength();
functions.push(curve);
- cur = [instruction[5] + cur[0], instruction[6] + cur[1]];
+ cur = [instruction.dx + cur[0], instruction.dy + cur[1]];
} else {
- functions.push(makeLinearPosition(cur[0], cur[0], cur[1], cur[1]));
+ functions.push(
+ makeLinearPosition({x0: cur[0], x1: cur[0], y0: cur[1], y1: cur[1]})
+ );
}
- } else if (instruction[0] === 'S') {
- if (i > 0 && ['C', 'c', 'S', 's'].indexOf(parsed[i - 1][0]) > -1) {
+ } else if (instruction.type === 'S') {
+ const prev = parsed[i - 1];
+ const prevWasCurve =
+ prev.type === 'C' ||
+ prev.type === 'c' ||
+ prev.type === 'S' ||
+ prev.type === 's';
+ if (i > 0 && prevWasCurve) {
if (curve) {
const c = curve.getC();
curve = makeBezier({
@@ -136,10 +177,10 @@ export const construct = (string: string) => {
ay: cur[1],
bx: 2 * cur[0] - c.x,
by: 2 * cur[1] - c.y,
- cx: instruction[1],
- cy: instruction[2],
- dx: instruction[3],
- dy: instruction[4],
+ cx: instruction.cpx,
+ cy: instruction.cpy,
+ dx: instruction.x,
+ dy: instruction.y,
});
}
} else {
@@ -148,21 +189,27 @@ export const construct = (string: string) => {
ay: cur[1],
bx: cur[0],
by: cur[1],
- cx: instruction[1],
- cy: instruction[2],
- dx: instruction[3],
- dy: instruction[4],
+ cx: instruction.cpx,
+ cy: instruction.cpy,
+ dx: instruction.x,
+ dy: instruction.y,
});
}
if (curve) {
length += curve.getTotalLength();
- cur = [instruction[3], instruction[4]];
+ cur = [instruction.x, instruction.y];
functions.push(curve);
}
- } else if (instruction[0] === 's') {
- // 240 225
- if (i > 0 && ['C', 'c', 'S', 's'].indexOf(parsed[i - 1][0]) > -1) {
+ } else if (instruction.type === 's') {
+ const prev = parsed[i - 1];
+ const prevWasCurve =
+ prev.type === 'C' ||
+ prev.type === 'c' ||
+ prev.type === 'S' ||
+ prev.type === 's';
+
+ if (i > 0 && prevWasCurve) {
if (curve) {
const c = curve.getC();
const d = curve.getD();
@@ -171,10 +218,10 @@ export const construct = (string: string) => {
ay: cur[1],
bx: cur[0] + d.x - c.x,
by: cur[1] + d.y - c.y,
- cx: cur[0] + instruction[1],
- cy: cur[1] + instruction[2],
- dx: cur[0] + instruction[3],
- dy: cur[1] + instruction[4],
+ cx: cur[0] + instruction.cpdx,
+ cy: cur[1] + instruction.cpdy,
+ dx: cur[0] + instruction.dx,
+ dy: cur[1] + instruction.dy,
});
}
} else {
@@ -183,38 +230,38 @@ export const construct = (string: string) => {
ay: cur[1],
bx: cur[0],
by: cur[1],
- cx: cur[0] + instruction[1],
- cy: cur[1] + instruction[2],
- dx: cur[0] + instruction[3],
- dy: cur[1] + instruction[4],
+ cx: cur[0] + instruction.cpdx,
+ cy: cur[1] + instruction.cpdy,
+ dx: cur[0] + instruction.dx,
+ dy: cur[1] + instruction.dy,
});
}
if (curve) {
length += curve.getTotalLength();
- cur = [instruction[3] + cur[0], instruction[4] + cur[1]];
+ cur = [instruction.dx + cur[0], instruction.dy + cur[1]];
functions.push(curve);
}
}
// Quadratic Bezier curves
- else if (instruction[0] === 'Q') {
- if (cur[0] === instruction[1] && cur[1] === instruction[2]) {
- const linearCurve = makeLinearPosition(
- instruction[1],
- instruction[3],
- instruction[2],
- instruction[4]
- );
+ else if (instruction.type === 'Q') {
+ if (cur[0] === instruction.cpx && cur[1] === instruction.cpy) {
+ const linearCurve = makeLinearPosition({
+ x0: instruction.cpx,
+ x1: instruction.x,
+ y0: instruction.cpy,
+ y1: instruction.y,
+ });
length += linearCurve.getTotalLength();
functions.push(linearCurve);
} else {
curve = makeBezier({
ax: cur[0],
ay: cur[1],
- bx: instruction[1],
- by: instruction[2],
- cx: instruction[3],
- cy: instruction[4],
+ bx: instruction.cpx,
+ by: instruction.cpy,
+ cx: instruction.x,
+ cy: instruction.y,
dx: null,
dy: null,
});
@@ -222,26 +269,26 @@ export const construct = (string: string) => {
functions.push(curve);
}
- cur = [instruction[3], instruction[4]];
- prev_point = [instruction[1], instruction[2]];
- } else if (instruction[0] === 'q') {
- if (instruction[1] === 0 && instruction[2] === 0) {
- const linearCurve = makeLinearPosition(
- cur[0] + instruction[1],
- cur[0] + instruction[3],
- cur[1] + instruction[2],
- cur[1] + instruction[4]
- );
+ cur = [instruction.x, instruction.y];
+ prev_point = [instruction.cpx, instruction.cpy];
+ } else if (instruction.type === 'q') {
+ if (instruction.cpdx === 0 && instruction.cpdy === 0) {
+ const linearCurve = makeLinearPosition({
+ x0: cur[0] + instruction.cpdx,
+ x1: cur[0] + instruction.cpdy,
+ y0: cur[1] + instruction.dx,
+ y1: cur[1] + instruction.dy,
+ });
length += linearCurve.getTotalLength();
functions.push(linearCurve);
} else {
curve = makeBezier({
ax: cur[0],
ay: cur[1],
- bx: cur[0] + instruction[1],
- by: cur[1] + instruction[2],
- cx: cur[0] + instruction[3],
- cy: cur[1] + instruction[4],
+ bx: cur[0] + instruction.cpdx,
+ by: cur[1] + instruction.cpdy,
+ cx: cur[0] + instruction.dx,
+ cy: cur[1] + instruction.dy,
dx: null,
dy: null,
});
@@ -249,93 +296,105 @@ export const construct = (string: string) => {
functions.push(curve);
}
- prev_point = [cur[0] + instruction[1], cur[1] + instruction[2]];
- cur = [instruction[3] + cur[0], instruction[4] + cur[1]];
- } else if (instruction[0] === 'T') {
- if (i > 0 && ['Q', 'q', 'T', 't'].indexOf(parsed[i - 1][0]) > -1) {
+ prev_point = [cur[0] + instruction.cpdx, cur[1] + instruction.cpdy];
+ cur = [instruction.dx + cur[0], instruction.dy + cur[1]];
+ } else if (instruction.type === 'T') {
+ const prev = parsed[i - 1];
+ const prevWasQ =
+ prev.type === 'Q' ||
+ prev.type === 'q' ||
+ prev.type === 'T' ||
+ prev.type === 't';
+ if (i > 0 && prevWasQ) {
curve = makeBezier({
ax: cur[0],
ay: cur[1],
bx: 2 * cur[0] - prev_point[0],
by: 2 * cur[1] - prev_point[1],
- cx: instruction[1],
- cy: instruction[2],
+ cx: instruction.x,
+ cy: instruction.y,
dx: null,
dy: null,
});
functions.push(curve);
length += curve.getTotalLength();
} else {
- const linearCurve = makeLinearPosition(
- cur[0],
- instruction[1],
- cur[1],
- instruction[2]
- );
+ const linearCurve = makeLinearPosition({
+ x0: cur[0],
+ x1: instruction.x,
+ y0: cur[1],
+ y1: instruction.y,
+ });
functions.push(linearCurve);
length += linearCurve.getTotalLength();
}
prev_point = [2 * cur[0] - prev_point[0], 2 * cur[1] - prev_point[1]];
- cur = [instruction[1], instruction[2]];
- } else if (instruction[0] === 't') {
- if (i > 0 && ['Q', 'q', 'T', 't'].indexOf(parsed[i - 1][0]) > -1) {
+ cur = [instruction.x, instruction.y];
+ } else if (instruction.type === 't') {
+ const prev = parsed[i - 1];
+ const prevWasQ =
+ prev.type === 'Q' ||
+ prev.type === 'q' ||
+ prev.type === 'T' ||
+ prev.type === 't';
+ if (i > 0 && prevWasQ) {
curve = makeBezier({
ax: cur[0],
ay: cur[1],
bx: 2 * cur[0] - prev_point[0],
by: 2 * cur[1] - prev_point[1],
- cx: cur[0] + instruction[1],
- cy: cur[1] + instruction[2],
+ cx: cur[0] + instruction.dx,
+ cy: cur[1] + instruction.dy,
dx: null,
dy: null,
});
length += curve.getTotalLength();
functions.push(curve);
} else {
- const linearCurve = makeLinearPosition(
- cur[0],
- cur[0] + instruction[1],
- cur[1],
- cur[1] + instruction[2]
- );
+ const linearCurve = makeLinearPosition({
+ x0: cur[0],
+ x1: cur[0] + instruction.dx,
+ y0: cur[1],
+ y1: cur[1] + instruction.dy,
+ });
length += linearCurve.getTotalLength();
functions.push(linearCurve);
}
prev_point = [2 * cur[0] - prev_point[0], 2 * cur[1] - prev_point[1]];
- cur = [instruction[1] + cur[0], instruction[2] + cur[1]];
- } else if (instruction[0] === 'A') {
+ cur = [instruction.dx + cur[0], instruction.dy + cur[1]];
+ } else if (instruction.type === 'A') {
const arcCurve = makeArc({
x0: cur[0],
y0: cur[1],
- rx: instruction[1],
- ry: instruction[2],
- xAxisRotate: instruction[3],
- LargeArcFlag: instruction[4] === 1,
- SweepFlag: instruction[5] === 1,
- x1: instruction[6],
- y1: instruction[7],
+ rx: instruction.rx,
+ ry: instruction.ry,
+ xAxisRotate: instruction.xAxisRotation,
+ LargeArcFlag: instruction.largeArcFlag,
+ SweepFlag: instruction.sweepFlag,
+ x1: instruction.x,
+ y1: instruction.y,
});
length += arcCurve.getTotalLength();
- cur = [instruction[6], instruction[7]];
+ cur = [instruction.x, instruction.y];
functions.push(arcCurve);
- } else if (instruction[0] === 'a') {
+ } else if (instruction.type === 'a') {
const arcCurve = makeArc({
x0: cur[0],
y0: cur[1],
- rx: instruction[1],
- ry: instruction[2],
- xAxisRotate: instruction[3],
- LargeArcFlag: instruction[4] === 1,
- SweepFlag: instruction[5] === 1,
- x1: cur[0] + instruction[6],
- y1: cur[1] + instruction[7],
+ rx: instruction.rx,
+ ry: instruction.ry,
+ xAxisRotate: instruction.xAxisRotation,
+ LargeArcFlag: instruction.largeArcFlag,
+ SweepFlag: instruction.sweepFlag,
+ x1: cur[0] + instruction.dx,
+ y1: cur[1] + instruction.dy,
});
length += arcCurve.getTotalLength();
- cur = [cur[0] + instruction[6], cur[1] + instruction[7]];
+ cur = [cur[0] + instruction.dx, cur[1] + instruction.dy];
functions.push(arcCurve);
}
diff --git a/packages/paths/src/helpers/iterate.ts b/packages/paths/src/helpers/iterate.ts
index 97c18d1d89..9e43b71b21 100644
--- a/packages/paths/src/helpers/iterate.ts
+++ b/packages/paths/src/helpers/iterate.ts
@@ -1,54 +1,41 @@
-import type {Instruction} from './parse';
+import type {AbsoluteInstruction, UnarcedAbsoluteInstruction} from './types';
-export const iterateOverSegments = ({
+export const iterateOverSegments = <T extends UnarcedAbsoluteInstruction>({
segments,
iterate,
}: {
- segments: Instruction[];
+ segments: AbsoluteInstruction[];
iterate: (options: {
- segment: Instruction;
+ segment: AbsoluteInstruction;
x: number;
y: number;
- }) => Instruction[];
-}): Instruction[] => {
+ }) => T[];
+}): T[] => {
let x = 0;
let y = 0;
const newSegments = segments.map((s) => {
const newSeg = iterate({segment: s, x, y});
- switch (s[0]) {
+ switch (s.type) {
case 'M':
+ case 'A':
+ case 'C':
+ case 'Q':
+ case 'S':
+ case 'T':
case 'L': {
- x = s[1];
- y = s[2];
- break;
- }
-
- case 'A': {
- x = s[6];
- y = s[7];
+ x = s.x;
+ y = s.y;
break;
}
case 'V': {
- y = s[1];
+ y = s.y;
break;
}
case 'H': {
- x = s[1];
- break;
- }
-
- case 'C': {
- x = s[5];
- y = s[6];
- break;
- }
-
- case 'Q': {
- x = s[3];
- y = s[4];
+ x = s.x;
break;
}
@@ -57,7 +44,8 @@ export const iterateOverSegments = ({
}
default:
- throw new Error(`Unexpected instruction ${s[0]}`);
+ // @ts-expect-error
+ throw new Error(`Unexpected instruction ${s.type}`);
}
return newSeg;
diff --git a/packages/paths/src/helpers/linear.ts b/packages/paths/src/helpers/linear.ts
index 8ce4820390..fd11082cd8 100644
--- a/packages/paths/src/helpers/linear.ts
+++ b/packages/paths/src/helpers/linear.ts
@@ -1,12 +1,17 @@
// Copied from: https://github.com/rveciana/svg-path-properties
import type {Point, PointProperties} from './types';
-export const makeLinearPosition = (
- x0: number,
- x1: number,
- y0: number,
- y1: number
-) => {
+export const makeLinearPosition = ({
+ x0,
+ x1,
+ y0,
+ y1,
+}: {
+ x0: number;
+ x1: number;
+ y0: number;
+ y1: number;
+}) => {
const getTotalLength = () => {
return Math.sqrt((x0 - x1) ** 2 + (y0 - y1) ** 2);
};
diff --git a/packages/paths/src/helpers/parse.ts b/packages/paths/src/helpers/parse.ts
index 195d553251..7ec0706013 100644
--- a/packages/paths/src/helpers/parse.ts
+++ b/packages/paths/src/helpers/parse.ts
@@ -1,67 +1,324 @@
// Copied from: https://github.com/rveciana/svg-path-properties
-import type {pathOrders} from './types';
+import type {Instruction} from './types';
-const length: {[key in pathOrders]: number} = {
+const length: {[key in Instruction['type']]: number} = {
a: 7,
+ A: 7,
+ C: 6,
c: 6,
+ H: 1,
h: 1,
+ L: 2,
l: 2,
+ M: 2,
m: 2,
+ Q: 4,
q: 4,
+ S: 4,
s: 4,
+ T: 2,
t: 2,
+ V: 1,
v: 1,
+ Z: 0,
z: 0,
};
+
+const chunkExact = (
+ array: number[],
+ instruction: Instruction['type']
+): number[][] => {
+ const chunks: number[][] = [];
+ const expectedSize = length[instruction];
+
+ if (array.length % expectedSize !== 0) {
+ throw new Error(
+ `Expected number of arguments of SVG instruction "${instruction} ${array.join(
+ ' '
+ )}" to be a multiple of ${expectedSize}`
+ );
+ }
+
+ for (let i = 0; i < array.length; i += expectedSize) {
+ chunks.push(array.slice(i, i + expectedSize));
+ }
+
+ return chunks;
+};
+
+const makeInstructions = (
+ arr: number[],
+ instruction: Instruction['type'],
+ cb: (args: number[]) => Instruction
+) => {
+ return chunkExact(arr, instruction).map((args) => {
+ return cb(args);
+ });
+};
+
const segmentRegExp = /([astvzqmhlc])([^astvzqmhlc]*)/gi;
const numberRegExp = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;
-export type Instruction = [string, ...number[]];
-
export const parsePath = (path: string): Instruction[] => {
- const segments = (path && path.length > 0 ? path : 'M0,0').match(
- segmentRegExp
- );
+ if (!path) {
+ throw new Error('No path provided');
+ }
+
+ const segments = path.match(segmentRegExp);
if (!segments) {
throw new Error(`No path elements found in string ${path}`);
}
- return segments.reduce(
- (segmentsArray: [string, ...Array<number>][], segmentString: string) => {
- let command = segmentString.charAt(0);
- let type: pathOrders = command.toLowerCase() as pathOrders;
- const args = parseValues(segmentString.substr(1));
+ return segments
+ .map((segmentString: string): Instruction[] => {
+ const command = segmentString.charAt(0) as Instruction['type'];
+ const args = parseValues(segmentString.substring(1), command);
// overloaded moveTo
- if (type === 'm' && args.length > 2) {
- segmentsArray.push([command, ...args.splice(0, 2)]);
- type = 'l';
- command = command === 'm' ? 'l' : 'L';
+ if (command === 'M' && args.length > 2) {
+ const segmentsArray: Instruction[] = [];
+ segmentsArray.push({
+ type: command,
+ x: args[0],
+ y: args[1],
+ });
+ segmentsArray.push(
+ ...makeInstructions(args.slice(2), 'L', (numbers) => ({
+ type: 'L',
+ x: numbers[0],
+ y: numbers[1],
+ }))
+ );
+
+ return segmentsArray;
+ }
+
+ if (command === 'm' && args.length > 2) {
+ const segmentsArray: Instruction[] = [];
+ segmentsArray.push({
+ type: command,
+ dx: args[0],
+ dy: args[1],
+ });
+ segmentsArray.push(
+ ...makeInstructions(args.slice(2), 'l', (numbers) => ({
+ type: 'l',
+ dx: numbers[0],
+ dy: numbers[1],
+ }))
+ );
+
+ return segmentsArray;
+ }
+
+ if (command === 'Z') {
+ return [
+ {
+ type: 'Z',
+ },
+ ];
+ }
+
+ if (command === 'z') {
+ return [
+ {
+ type: 'z',
+ },
+ ];
+ }
+
+ if (command === 'A') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ rx: numbers[0],
+ ry: numbers[1],
+ xAxisRotation: numbers[2],
+ largeArcFlag: numbers[3] === 1,
+ sweepFlag: numbers[4] === 1,
+ x: numbers[5],
+ y: numbers[6],
+ }));
+ }
+
+ if (command === 'a') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ rx: numbers[0],
+ ry: numbers[1],
+ xAxisRotation: numbers[2],
+ largeArcFlag: numbers[3] === 1,
+ sweepFlag: numbers[4] === 1,
+ dx: numbers[5],
+ dy: numbers[6],
+ }));
+ }
+
+ if (command === 'C') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ cp1x: numbers[0],
+ cp1y: numbers[1],
+ cp2x: numbers[2],
+ cp2y: numbers[3],
+ x: numbers[4],
+ y: numbers[5],
+ }));
+ }
+
+ if (command === 'c') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ cp1dx: numbers[0],
+ cp1dy: numbers[1],
+ cp2dx: numbers[2],
+ cp2dy: numbers[3],
+ dx: numbers[4],
+ dy: numbers[5],
+ }));
}
- while (args.length >= 0) {
- if (args.length === length[type]) {
- segmentsArray.push([command, ...args.splice(0, length[type])]);
- break;
- }
+ if (command === 'S') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ cpx: numbers[0],
+ cpy: numbers[1],
+ x: numbers[2],
+ y: numbers[3],
+ }));
+ }
+
+ if (command === 's') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ cpdx: numbers[0],
+ cpdy: numbers[1],
+ dx: numbers[2],
+ dy: numbers[3],
+ }));
+ }
+
+ if (command === 'H') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ x: numbers[0],
+ }));
+ }
+
+ if (command === 'h') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ dx: numbers[0],
+ }));
+ }
- if (args.length < length[type]) {
- throw new Error(
- `Malformed path data: "${command}" must have ${length[type]} elements and has ${args.length}: ${segmentString}`
- );
- }
+ if (command === 'V') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ y: numbers[0],
+ }));
+ }
- segmentsArray.push([command, ...args.splice(0, length[type])]);
+ if (command === 'v') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ dy: numbers[0],
+ }));
}
- return segmentsArray;
- },
- []
- );
+ if (command === 'L') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ x: numbers[0],
+ y: numbers[1],
+ }));
+ }
+
+ if (command === 'M') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ x: numbers[0],
+ y: numbers[1],
+ }));
+ }
+
+ if (command === 'm') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ dx: numbers[0],
+ dy: numbers[1],
+ }));
+ }
+
+ if (command === 'l') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ dx: numbers[0],
+ dy: numbers[1],
+ }));
+ }
+
+ if (command === 'Q') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ cpx: numbers[0],
+ cpy: numbers[1],
+ x: numbers[2],
+ y: numbers[3],
+ }));
+ }
+
+ if (command === 'q') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ cpdx: numbers[0],
+ cpdy: numbers[1],
+ dx: numbers[2],
+ dy: numbers[3],
+ }));
+ }
+
+ if (command === 'T') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ x: numbers[0],
+ y: numbers[1],
+ }));
+ }
+
+ if (command === 't') {
+ return makeInstructions(args, command, (numbers) => ({
+ type: command,
+ dx: numbers[0],
+ dy: numbers[1],
+ }));
+ }
+
+ throw new Error(`Invalid path element ${segmentString}`);
+ }, [])
+ .flat(1);
};
-const parseValues = (args: string) => {
+const parseValues = (args: string, instructionType: Instruction['type']) => {
const numbers = args.match(numberRegExp);
- return numbers ? numbers.map(Number) : [];
+ if (!numbers) {
+ if (instructionType === 'Z' || instructionType === 'z') {
+ return [];
+ }
+
+ throw new Error(
+ `Malformed path data: ${instructionType} was expected to have numbers afterwards`
+ );
+ }
+
+ const expectedArguments = length[instructionType];
+ if (numbers.length % expectedArguments !== 0) {
+ throw new Error(
+ `Malformed path data: ${instructionType} was expected to have a multiple of ${expectedArguments} numbers, but got "${instructionType} ${numbers.join(
+ ' '
+ )} instead"`
+ );
+ }
+
+ return numbers.map(Number);
};
diff --git a/packages/paths/src/helpers/serialize.ts b/packages/paths/src/helpers/serialize.ts
new file mode 100644
index 0000000000..c35471c615
--- /dev/null
+++ b/packages/paths/src/helpers/serialize.ts
@@ -0,0 +1,102 @@
+import type {Instruction} from './types';
+
+const serializeInstruction = (instruction: Instruction): string => {
+ if (instruction.type === 'A') {
+ return `A ${instruction.rx} ${instruction.ry} ${
+ instruction.xAxisRotation
+ } ${Number(instruction.largeArcFlag)} ${Number(instruction.sweepFlag)} ${
+ instruction.x
+ } ${instruction.y}`;
+ }
+
+ if (instruction.type === 'a') {
+ return `a ${instruction.rx} ${instruction.ry} ${
+ instruction.xAxisRotation
+ } ${Number(instruction.largeArcFlag)} ${Number(instruction.sweepFlag)} ${
+ instruction.dx
+ } ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'C') {
+ return `C ${instruction.cp1x} ${instruction.cp1y} ${instruction.cp2x} ${instruction.cp2y} ${instruction.x} ${instruction.y}`;
+ }
+
+ if (instruction.type === 'c') {
+ return `c ${instruction.cp1dx} ${instruction.cp1dy} ${instruction.cp2dx} ${instruction.cp2dy} ${instruction.dx} ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'S') {
+ return `S ${instruction.cpx} ${instruction.cpy} ${instruction.x} ${instruction.y}`;
+ }
+
+ if (instruction.type === 's') {
+ return `s ${instruction.cpdx} ${instruction.cpdy} ${instruction.dx} ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'Q') {
+ return `Q ${instruction.cpx} ${instruction.cpy} ${instruction.x} ${instruction.y}`;
+ }
+
+ if (instruction.type === 'q') {
+ return `q ${instruction.cpdx} ${instruction.cpdy} ${instruction.dx} ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'z') {
+ return 'z';
+ }
+
+ if (instruction.type === 'Z') {
+ return 'Z';
+ }
+
+ if (instruction.type === 'H') {
+ return `H ${instruction.x}`;
+ }
+
+ if (instruction.type === 'h') {
+ return `h ${instruction.dx}`;
+ }
+
+ if (instruction.type === 'V') {
+ return `V ${instruction.y}`;
+ }
+
+ if (instruction.type === 'v') {
+ return `v ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'L') {
+ return `L ${instruction.x} ${instruction.y}`;
+ }
+
+ if (instruction.type === 'l') {
+ return `l ${instruction.dx} ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'M') {
+ return `M ${instruction.x} ${instruction.y}`;
+ }
+
+ if (instruction.type === 'm') {
+ return `m ${instruction.dx} ${instruction.dy}`;
+ }
+
+ if (instruction.type === 'T') {
+ return `T ${instruction.x} ${instruction.y}`;
+ }
+
+ if (instruction.type === 't') {
+ return `t ${instruction.dx} ${instruction.dy}`;
+ }
+
+ // @ts-expect-error
+ throw new Error(`Unknown instruction type: ${instruction.type}`);
+};
+
+export const serializePath = (path: Instruction[]): string => {
+ return path
+ .map((p) => {
+ return serializeInstruction(p);
+ })
+ .join(' ');
+};
diff --git a/packages/paths/src/helpers/types.ts b/packages/paths/src/helpers/types.ts
index 5107e7f2fc..49c25e6cf0 100644
--- a/packages/paths/src/helpers/types.ts
+++ b/packages/paths/src/helpers/types.ts
@@ -24,16 +24,130 @@ export interface PointProperties {
tangentY: number;
}
-export type pathOrders =
- | 'a'
- | 'c'
- | 'h'
- | 'l'
- | 'm'
- | 'q'
- | 's'
- | 't'
- | 'v'
- | 'z';
-
export type BoundingBox = {x1: number; y1: number; x2: number; y2: number};
+
+export type UnarcedAbsoluteInstruction =
+ | {
+ type: 'M';
+ x: number;
+ y: number;
+ }
+ | {
+ type: 'L';
+ x: number;
+ y: number;
+ }
+ | {
+ type: 'H';
+ x: number;
+ }
+ | {
+ type: 'V';
+ y: number;
+ }
+ | {
+ type: 'C';
+ cp1x: number;
+ cp1y: number;
+ cp2x: number;
+ cp2y: number;
+ x: number;
+ y: number;
+ }
+ | {
+ type: 'S';
+ cpx: number;
+ cpy: number;
+ x: number;
+ y: number;
+ }
+ | {
+ type: 'Q';
+ cpx: number;
+ cpy: number;
+ x: number;
+ y: number;
+ }
+ | {
+ type: 'T';
+ x: number;
+ y: number;
+ }
+ | {
+ type: 'Z';
+ };
+
+export type AbsoluteInstruction =
+ | UnarcedAbsoluteInstruction
+ | {
+ type: 'A';
+ rx: number;
+ ry: number;
+ xAxisRotation: number;
+ largeArcFlag: boolean;
+ sweepFlag: boolean;
+ x: number;
+ y: number;
+ };
+
+export type Instruction =
+ | AbsoluteInstruction
+ | {
+ type: 'm';
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 'l';
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 'h';
+ dx: number;
+ }
+ | {
+ type: 'v';
+ dy: number;
+ }
+ | {
+ type: 'c';
+ cp1dx: number;
+ cp1dy: number;
+ cp2dx: number;
+ cp2dy: number;
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 's';
+ cpdx: number;
+ cpdy: number;
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 'q';
+ cpdx: number;
+ cpdy: number;
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 't';
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 'a';
+ rx: number;
+ ry: number;
+ xAxisRotation: number;
+ largeArcFlag: boolean;
+ sweepFlag: boolean;
+ dx: number;
+ dy: number;
+ }
+ | {
+ type: 'z';
+ };
diff --git a/packages/paths/src/helpers/unarc.ts b/packages/paths/src/helpers/unarc.ts
index 62f2986010..70b7f7621a 100644
--- a/packages/paths/src/helpers/unarc.ts
+++ b/packages/paths/src/helpers/unarc.ts
@@ -1,6 +1,5 @@
import {iterateOverSegments} from './iterate';
-import type {Instruction} from './parse';
-import {parsePath} from './parse';
+import type {AbsoluteInstruction, UnarcedAbsoluteInstruction} from './types';
const TAU = Math.PI * 2;
@@ -24,13 +23,13 @@ function approximate_unit_arc(theta1: number, delta_theta: number) {
];
}
-function a2c({
+function arcToCircle({
x1,
y1,
x2,
y2,
- fa,
- fs,
+ largeArcFlag,
+ sweepFlag,
rx,
ry,
phi,
@@ -39,8 +38,8 @@ function a2c({
y1: number;
x2: number;
y2: number;
- fa: number;
- fs: number;
+ largeArcFlag: boolean;
+ sweepFlag: boolean;
rx: number;
ry: number;
phi: number;
@@ -76,7 +75,18 @@ function a2c({
// Get center parameters (cx, cy, theta1, delta_theta)
//
- const cc = get_arc_center({x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi});
+ const cc = get_arc_center({
+ x1,
+ y1,
+ x2,
+ y2,
+ largeArcFlag,
+ sweepFlag,
+ rx,
+ ry,
+ sin_phi,
+ cos_phi,
+ });
const result = [];
let theta1 = cc[2];
@@ -119,38 +129,52 @@ function a2c({
}
// Requires path to be normalized
-export const unarc = (d: string) => {
- const segments = parsePath(d);
-
- return iterateOverSegments({
+export const removeArcInstructions = (
+ segments: AbsoluteInstruction[]
+): UnarcedAbsoluteInstruction[] => {
+ return iterateOverSegments<UnarcedAbsoluteInstruction>({
segments,
iterate: ({segment, x, y}) => {
- if (segment[0] !== 'A') {
+ if (segment.type !== 'A') {
return [segment];
}
- const nextX = segment[6];
- const nextY = segment[7];
- const new_segments = a2c({
+ const nextX = segment.x;
+ const nextY = segment.y;
+ const new_segments = arcToCircle({
x1: x,
y1: y,
x2: nextX,
y2: nextY,
- fa: segment[4],
- fs: segment[5],
- rx: segment[1],
- ry: segment[2],
- phi: segment[3],
+ largeArcFlag: segment.largeArcFlag,
+ sweepFlag: segment.sweepFlag,
+ rx: segment.rx,
+ ry: segment.ry,
+ phi: segment.xAxisRotation,
});
// Degenerated arcs can be ignored by renderer, but should not be dropped
// to avoid collisions with `S A S` and so on. Replace with empty line.
if (new_segments.length === 0) {
- return [['L', segment[6], segment[7]]];
+ return [
+ {
+ type: 'L',
+ x: segment.x,
+ y: segment.y,
+ },
+ ];
}
- const result = new_segments.map((_s) => {
- return ['C', _s[2], _s[3], _s[4], _s[5], _s[6], _s[7]] as Instruction;
+ const result = new_segments.map((_s): UnarcedAbsoluteInstruction => {
+ return {
+ type: 'C',
+ cp1x: _s[2],
+ cp1y: _s[3],
+ cp2x: _s[4],
+ cp2y: _s[5],
+ x: _s[6],
+ y: _s[7],
+ };
});
return result;
},
@@ -162,8 +186,8 @@ function get_arc_center({
y1,
x2,
y2,
- fa,
- fs,
+ largeArcFlag,
+ sweepFlag,
rx,
ry,
sin_phi,
@@ -173,8 +197,8 @@ function get_arc_center({
y1: number;
x2: number;
y2: number;
- fa: number;
- fs: number;
+ largeArcFlag: boolean;
+ sweepFlag: boolean;
rx: number;
ry: number;
sin_phi: number;
@@ -207,7 +231,7 @@ function get_arc_center({
}
radicant /= rx_sq * y1p_sq + ry_sq * x1p_sq;
- radicant = Math.sqrt(radicant) * (fa === fs ? -1 : 1);
+ radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1);
const cxp = ((radicant * rx) / ry) * y1p;
const cyp = ((radicant * -ry) / rx) * x1p;
@@ -232,11 +256,11 @@ function get_arc_center({
const theta1 = unit_vector_angle(1, 0, v1x, v1y);
let delta_theta = unit_vector_angle(v1x, v1y, v2x, v2y);
- if (fs === 0 && delta_theta > 0) {
+ if (sweepFlag === false && delta_theta > 0) {
delta_theta -= TAU;
}
- if (fs === 1 && delta_theta < 0) {
+ if (sweepFlag === true && delta_theta < 0) {
delta_theta += TAU;
}
diff --git a/packages/paths/src/helpers/unshort.ts b/packages/paths/src/helpers/unshort.ts
index 3758b02fee..561d5aeb9a 100644
--- a/packages/paths/src/helpers/unshort.ts
+++ b/packages/paths/src/helpers/unshort.ts
@@ -1,4 +1,4 @@
-import type {Instruction} from './parse';
+import type {Instruction} from './types';
// Requires that the path is already normalized
export const unshort = function (segments: Instruction[]): Instruction[] {
@@ -7,57 +7,10 @@ export const unshort = function (segments: Instruction[]): Instruction[] {
let curControlX = 0;
let curControlY = 0;
- let x = 0;
- let y = 0;
-
const newSegments = segments.slice(0);
for (let i = 0; i < newSegments.length; i++) {
const s = newSegments[i];
- const name = s[0];
- switch (s[0]) {
- case 'M':
- case 'L': {
- x = s[1];
- y = s[2];
- break;
- }
-
- case 'V': {
- y = s[1];
-
- break;
- }
-
- case 'H': {
- x = s[1];
-
- break;
- }
-
- case 'C': {
- x = s[5];
- y = s[6];
-
- break;
- }
-
- case 'Q': {
- x = s[3];
- y = s[4];
-
- break;
- }
-
- case 'Z':
- break;
-
- default:
- throw new Error('Unexpected command: ' + s[0]);
- }
-
- const nameUC = name.toUpperCase();
- let isRelative;
// First command MUST be M|m, it's safe to skip.
// Protect from access to [-1] for sure.
@@ -65,18 +18,14 @@ export const unshort = function (segments: Instruction[]): Instruction[] {
continue;
}
- if (nameUC === 'T') {
+ if (s.type === 'T') {
// quadratic curve
- isRelative = name === 't';
const prevSegment = newSegments[i - 1];
- if (prevSegment[0] === 'Q') {
- prevControlX = prevSegment[1] - x;
- prevControlY = prevSegment[2] - y;
- } else if (prevSegment[0] === 'q') {
- prevControlX = prevSegment[1] - prevSegment[3];
- prevControlY = prevSegment[2] - prevSegment[4];
+ if (prevSegment.type === 'Q') {
+ prevControlX = prevSegment.cpx;
+ prevControlY = prevSegment.cpy;
} else {
prevControlX = 0;
prevControlY = 0;
@@ -85,30 +34,21 @@ export const unshort = function (segments: Instruction[]): Instruction[] {
curControlX = -prevControlX;
curControlY = -prevControlY;
- if (!isRelative) {
- curControlX += x;
- curControlY += y;
- }
-
- newSegments[i] = [
- isRelative ? 'q' : 'Q',
- curControlX,
- curControlY,
- s[1],
- s[2],
- ];
- } else if (nameUC === 'S') {
+ newSegments[i] = {
+ type: 'Q',
+ cpx: curControlX,
+ cpy: curControlY,
+ x: s.x,
+ y: s.y,
+ };
+ } else if (s.type === 'S') {
// cubic curve
- isRelative = name === 's';
const prevSegment = newSegments[i - 1];
- if (prevSegment[0] === 'C') {
- prevControlX = prevSegment[3] - x;
- prevControlY = prevSegment[4] - y;
- } else if (prevSegment[0] === 'c') {
- prevControlX = prevSegment[3] - prevSegment[5];
- prevControlY = prevSegment[4] - prevSegment[6];
+ if (prevSegment.type === 'C') {
+ prevControlX = prevSegment.cp2x;
+ prevControlY = prevSegment.cp2y;
} else {
prevControlX = 0;
prevControlY = 0;
@@ -117,20 +57,15 @@ export const unshort = function (segments: Instruction[]): Instruction[] {
curControlX = -prevControlX;
curControlY = -prevControlY;
- if (!isRelative) {
- curControlX += x;
- curControlY += y;
- }
-
- newSegments[i] = [
- isRelative ? 'c' : 'C',
- curControlX,
- curControlY,
- s[1],
- s[2],
- s[3],
- s[4],
- ];
+ newSegments[i] = {
+ type: 'C',
+ cp1x: curControlX,
+ cp1y: curControlY,
+ cp2x: s.cpx,
+ cp2y: s.cpy,
+ x: s.x,
+ y: s.y,
+ };
}
}
diff --git a/packages/paths/src/test/translate-path.test.ts b/packages/paths/src/test/translate-path.test.ts
index 59f00373a5..46058018c1 100644
--- a/packages/paths/src/test/translate-path.test.ts
+++ b/packages/paths/src/test/translate-path.test.ts
@@ -42,5 +42,5 @@ test('Should be able to translate example path, update x', () => {
test('Translation should throw error', () => {
expect(() => {
translatePath('remotion', 10, 0);
- }).toThrow('Malformed path data: "m" must have 2 elements and has 0: mo');
+ }).toThrow('Malformed path data: m was expected to have numbers afterwards');
});
diff --git a/packages/paths/src/translate-path.ts b/packages/paths/src/translate-path.ts
index 38824f399d..107c240879 100644
--- a/packages/paths/src/translate-path.ts
+++ b/packages/paths/src/translate-path.ts
@@ -1,51 +1,68 @@
// Copied partially from https://github.com/michaelrhodes/translate-svg-path/blob/master/index.js
-import type {Instruction} from './helpers/parse';
import {parsePath} from './helpers/parse';
+import {serializePath} from './helpers/serialize';
+import type {Instruction} from './helpers/types';
-const serialize = (path: (Instruction | number[])[]) => {
- return path.reduce((str: string, seg: Instruction | number[]) => {
- return (str + ' ' + seg[0] + ' ' + seg.slice(1).join(' ')).trim();
- }, '');
-};
-
-const translateSegments = (path: string, x: number, y: number) => {
- const segments = parsePath(path);
-
- return segments.map((segment) => {
- const cmd = segment[0];
-
+const translateSegments = (segments: Instruction[], x: number, y: number) => {
+ return segments.map((segment): Instruction => {
// Shift coords only for commands with absolute values
- if ('ACHLMRQSTVZ'.indexOf(cmd) === -1) {
+ if (
+ segment.type === 'a' ||
+ segment.type === 'c' ||
+ segment.type === 'v' ||
+ segment.type === 's' ||
+ segment.type === 'z' ||
+ segment.type === 'h' ||
+ segment.type === 'l' ||
+ segment.type === 'm' ||
+ segment.type === 'q' ||
+ segment.type === 't'
+ ) {
return segment;
}
- const name = cmd.toLowerCase();
-
// V is the only command, with shifted coords parity
- if (name === 'v') {
- segment[1] = (segment[1] as number) + (y as number);
- return segment;
+ if (segment.type === 'V') {
+ return {
+ type: 'V',
+ y: segment.y + y,
+ };
+ }
+
+ if (segment.type === 'H') {
+ return {
+ type: 'H',
+ x: segment.x + x,
+ };
}
// ARC is: ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y]
// touch x, y only
- if (name === 'a') {
- segment[6] = (segment[6] as number) + x;
- segment[7] = (segment[7] as number) + (y ?? 0);
- return segment;
+ if (segment.type === 'A') {
+ return {
+ type: 'A',
+ rx: segment.rx,
+ ry: segment.ry,
+ largeArcFlag: segment.largeArcFlag,
+ sweepFlag: segment.sweepFlag,
+ xAxisRotation: segment.xAxisRotation,
+ x: segment.x + x,
+ y: segment.y + y,
+ };
}
- // All other commands have [cmd, x1, y1, x2, y2, x3, y3, ...] format
- return segment.map((val, i) => {
- if (!i) {
- return val as number;
- }
+ if (segment.type === 'Z') {
+ return segment;
+ }
- return i % 2 ? (val as number) + x : (val as number) + (y ?? 0);
- });
+ return {
+ ...segment,
+ x: segment.x + x,
+ y: segment.y + y,
+ };
});
};
export const translatePath = (path: string, x: number, y: number) => {
- return serialize(translateSegments(path, x, y));
+ return serializePath(translateSegments(parsePath(path), x, y));
};
diff --git a/packages/shapes/package.json b/packages/shapes/package.json
index 44477ab01e..dc9420c516 100644
--- a/packages/shapes/package.json
+++ b/packages/shapes/package.json
@@ -43,5 +43,8 @@
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
+ },
+ "dependencies": {
+ "@remotion/paths": "3.3.39"
}
}
diff --git a/packages/shapes/src/utils/instructions.ts b/packages/shapes/src/utils/instructions.ts
index 5227d8f894..059055df94 100644
--- a/packages/shapes/src/utils/instructions.ts
+++ b/packages/shapes/src/utils/instructions.ts
@@ -1,46 +1,4 @@
-export type Instruction =
- | {
- type: 'M';
- x: number;
- y: number;
- }
- | {
- type: 'L';
- x: number;
- y: number;
- }
- | {
- type: 'C';
- cp1x: number;
- cp1y: number;
- cp2x: number;
- cp2y: number;
- x: number;
- y: number;
- }
- | {
- type: 'a';
- rx: number;
- ry: number;
- xAxisRotation: number;
- largeArcFlag: boolean;
- sweepFlag: boolean;
- x: number;
- y: number;
- }
- | {
- type: 'A';
- rx: number;
- ry: number;
- xAxisRotation: number;
- largeArcFlag: boolean;
- sweepFlag: boolean;
- x: number;
- y: number;
- }
- | {
- type: 'z';
- };
+import type {Instruction} from '@remotion/paths';
export const serializeInstructions = (instructions: Instruction[]) => {
return instructions.map((i) => serializeInstruction(i)).join(' ');
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7c0c700c01..eca70679ae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -949,6 +949,7 @@ importers:
packages/shapes:
specifiers:
'@jonny/eslint-config': 3.0.266
+ '@remotion/paths': 3.3.39
'@testing-library/react': ^13.4.0
'@types/node': ^16.7.5
'@types/react': 18.0.26
@@ -960,6 +961,8 @@ importers:
react-dom: 18.0.0
typescript: ^4.7.0
vitest: 0.24.3
+ dependencies:
+ '@remotion/paths': link:../paths
devDependencies:
'@jonny/eslint-config': 3.0.266_t54va6jeo5lf3vtqih5uiyrm5e
'@testing-library/react': 13.4.0_zpnidt7m3osuk7shl3s4oenomq