Skip to content

🎥 Make videos programmatically with React

simplify instructions

Jonny Burgera41ed45335bc
diff --git a/packages/paths/src/helpers/construct.ts b/packages/paths/src/helpers/construct.ts
index 1f18221f25..6fbec04890 100644
--- a/packages/paths/src/helpers/construct.ts
+++ b/packages/paths/src/helpers/construct.ts
@@ -114,7 +114,7 @@ export const construct = (string: string) => {
);
cur[1] = instruction.dy + cur[1];
// Close path
- } else if (instruction.type === 'z' || instruction.type === 'Z') {
+ } else if (instruction.type === 'Z') {
length += Math.sqrt(
(ringStart[0] - cur[0]) ** 2 + (ringStart[1] - cur[1]) ** 2
);
diff --git a/packages/paths/src/helpers/types.ts b/packages/paths/src/helpers/types.ts
index 081a1dd2c4..edef47b104 100644
--- a/packages/paths/src/helpers/types.ts
+++ b/packages/paths/src/helpers/types.ts
@@ -147,7 +147,4 @@ export type Instruction =
sweepFlag: boolean;
dx: number;
dy: number;
- }
- | {
- type: 'z';
};
diff --git a/packages/paths/src/normalize-path.ts b/packages/paths/src/normalize-path.ts
index 8eae08df55..a0b32d69ba 100644
--- a/packages/paths/src/normalize-path.ts
+++ b/packages/paths/src/normalize-path.ts
@@ -1,306 +1,174 @@
+import type {AbsoluteInstruction, Instruction} from './helpers/types';
+import {parsePath} from './parse-path';
+import {serializeInstructions} from './serialize-instructions';
+
/**
* Removes all relative coordinates from an SVG path and converts them into absolute coordinates.
* @param {string} path A valid SVG path
* @link https://remotion.dev/docs/paths/normalize-path
*/
-export const normalizePath = (path: string) => {
- // preprocess "d" so that we have spaces between values
- path = path
- .replace(/,/g, ' ')
- .replace(/([^eE])-/g, '$1 -')
- .replace(/\s*([achlmqstvzACHLMQSTVZ])\s*/g, ' $1 ')
- .replace(/\s+/g, ' ');
+export const normalizePath = (path: string): string => {
+ const instructions = parsePath(path);
+ const normalized = normalizeInstructions(instructions);
+ return serializeInstructions(normalized);
+};
+
+export const normalizeInstructions = (
+ instructions: Instruction[]
+): AbsoluteInstruction[] => {
+ // Extended properties must already be normalized
+ const normalized: AbsoluteInstruction[] = [];
- // set up the variables used in this function
- const instructions = path
- .replace(/([achlmqstvzACHLMQSTVZ])\s?/g, '|$1')
- .split('|');
- const instructionLength = instructions.length;
- let i;
- let instruction;
- let op;
- let lop;
- let alen;
- let a;
- let sx = 0;
- let sy = 0;
let x = 0;
let y = 0;
- let cx = 0;
- let cy = 0;
- let cx2 = 0;
- let cy2 = 0;
- let rx = 0;
- let ry = 0;
- let xrot = 0;
- let lflag: string | number = 0;
- let sweep: string | number = 0;
- let normalized = '';
-
- // we run through the instruction list starting at 1, not 0,
- // because we split up "|M x y ...." so the first element will
- // always be an empty string. By design.
- for (i = 1; i < instructionLength; i++) {
- // which instruction is this?
- instruction = instructions[i];
- op = instruction.substring(0, 1);
- lop = op.toLowerCase();
-
- // what are the arguments? note that we need to convert
- // all strings into numbers, or + will do silly things.
- const oargs = instruction
- .replace(op, '')
- .trim()
- .split(' ')
- .filter((v) => {
- return v !== '';
- });
- const args = oargs.map((_a) => parseFloat(String(_a)));
- alen = args.length;
-
- // we could use a switch, but elaborate code in a "case" with
- // fallthrough is just horrid to read. So let's use ifthen
- // statements instead.
-
- // moveto command (plus possible lineto)
- if (lop === 'm') {
- normalized += 'M ';
- if (op === 'm') {
- x += args[0];
- y += args[1];
- } else {
- x = args[0];
- y = args[1];
- }
-
- // records start position, for dealing
- // with the shape close operator ('Z')
- sx = x;
- sy = y;
- normalized += x + ' ' + y + ' ';
- if (alen > 2) {
- for (a = 0; a < alen; a += 2) {
- // eslint-disable-next-line max-depth
- if (op === 'm') {
- x += args[a];
- y += args[a + 1];
- } else {
- x = args[a];
- y = args[a + 1];
- }
-
- normalized += 'L ' + x + ' ' + y + ' ';
- }
- }
+ const initialX = 0;
+ const initialY = 0;
+
+ for (let i = 0; i < instructions.length; i++) {
+ const instruction = instructions[i];
+ if (
+ instruction.type === 'A' ||
+ instruction.type === 'C' ||
+ instruction.type === 'L' ||
+ instruction.type === 'M' ||
+ instruction.type === 'Q' ||
+ instruction.type === 'S' ||
+ instruction.type === 'T'
+ ) {
+ normalized.push(instruction);
+ x = instruction.x;
+ y = instruction.y;
+ continue;
}
- // lineto commands
- else if (lop === 'l') {
- for (a = 0; a < alen; a += 2) {
- if (op === 'l') {
- x += args[a];
- y += args[a + 1];
- } else {
- x = args[a];
- y = args[a + 1];
- }
-
- normalized += 'L ' + x + ' ' + y + ' ';
+ if (
+ instruction.type === 'a' ||
+ instruction.type === 'c' ||
+ instruction.type === 'l' ||
+ instruction.type === 'm' ||
+ instruction.type === 'q' ||
+ instruction.type === 's' ||
+ instruction.type === 't'
+ ) {
+ x += instruction.dx;
+ y += instruction.dy;
+ if (instruction.type === 'a') {
+ normalized.push({
+ type: 'A',
+ largeArcFlag: instruction.largeArcFlag,
+ rx: instruction.rx,
+ ry: instruction.ry,
+ sweepFlag: instruction.sweepFlag,
+ xAxisRotation: instruction.xAxisRotation,
+ x,
+ y,
+ });
+ continue;
}
- } else if (lop === 'h') {
- for (a = 0; a < alen; a++) {
- if (op === 'h') {
- x += args[a];
- } else {
- x = args[a];
- }
- normalized += 'L ' + x + ' ' + y + ' ';
+ if (instruction.type === 'c') {
+ normalized.push({
+ type: 'C',
+ cp1x: instruction.cp1dx + x,
+ cp1y: instruction.cp1dy + y,
+ cp2x: instruction.cp2dx + x,
+ cp2y: instruction.cp2dy + y,
+ x,
+ y,
+ });
+ continue;
}
- } else if (lop === 'v') {
- for (a = 0; a < alen; a++) {
- if (op === 'v') {
- y += args[a];
- } else {
- y = args[a];
- }
- normalized += 'L ' + x + ' ' + y + ' ';
+ if (instruction.type === 'l') {
+ normalized.push({
+ type: 'L',
+ x,
+ y,
+ });
+ continue;
}
- }
-
- // quadratic curveto commands
- else if (lop === 'q') {
- for (a = 0; a < alen; a += 4) {
- if (op === 'q') {
- cx = x + args[a];
- cy = y + args[a + 1];
- x += args[a + 2];
- y += args[a + 3];
- } else {
- cx = args[a];
- cy = args[a + 1];
- x = args[a + 2];
- y = args[a + 3];
- }
- normalized += 'Q ' + cx + ' ' + cy + ' ' + x + ' ' + y + ' ';
+ if (instruction.type === 'm') {
+ normalized.push({
+ type: 'M',
+ x,
+ y,
+ });
+ continue;
}
- } else if (lop === 't') {
- for (a = 0; a < alen; a += 2) {
- // reflect previous cx/cy over x/y
- cx = x + (x - cx);
- cy = y + (y - cy);
- // then get real end point
- if (op === 't') {
- x += args[a];
- y += args[a + 1];
- } else {
- x = args[a];
- y = args[a + 1];
- }
- normalized += 'Q ' + cx + ' ' + cy + ' ' + x + ' ' + y + ' ';
+ if (instruction.type === 'q') {
+ normalized.push({
+ type: 'Q',
+ cpx: instruction.cpdx + x,
+ cpy: instruction.cpdy + y,
+ x,
+ y,
+ });
+ continue;
}
- }
-
- // cubic curveto commands
- else if (lop === 'c') {
- for (a = 0; a < alen; a += 6) {
- if (op === 'c') {
- cx = x + args[a];
- cy = y + args[a + 1];
- cx2 = x + args[a + 2];
- cy2 = y + args[a + 3];
- x += args[a + 4];
- y += args[a + 5];
- } else {
- cx = args[a];
- cy = args[a + 1];
- cx2 = args[a + 2];
- cy2 = args[a + 3];
- x = args[a + 4];
- y = args[a + 5];
- }
- normalized +=
- 'C ' +
- cx +
- ' ' +
- cy +
- ' ' +
- cx2 +
- ' ' +
- cy2 +
- ' ' +
- x +
- ' ' +
- y +
- ' ';
+ if (instruction.type === 's') {
+ normalized.push({
+ type: 'S',
+ cpx: instruction.cpdx + x,
+ cpy: instruction.cpdy + y,
+ x,
+ y,
+ });
+ continue;
}
- } else if (lop === 's') {
- for (a = 0; a < alen; a += 4) {
- // reflect previous cx2/cy2 over x/y
- cx = x + (x - cx2);
- cy = y + (y - cy2);
- // then get real control and end point
- if (op === 's') {
- cx2 = x + args[a];
- cy2 = y + args[a + 1];
- x += args[a + 2];
- y += args[a + 3];
- } else {
- cx2 = args[a];
- cy2 = args[a + 1];
- x = args[a + 2];
- y = args[a + 3];
- }
- normalized +=
- 'C ' +
- cx +
- ' ' +
- cy +
- ' ' +
- cx2 +
- ' ' +
- cy2 +
- ' ' +
- x +
- ' ' +
- y +
- ' ';
+ if (instruction.type === 't') {
+ normalized.push({
+ type: 'T',
+ x,
+ y,
+ });
+ continue;
}
}
- // rx ry x-axis-rotation large-arc-flag sweep-flag x y
- // a 25,25 -30 0, 1 50,-25
-
- // arc command
- else if (lop === 'a') {
- for (a = 0; a < alen; a += 7) {
- rx = args[a];
- ry = args[a + 1];
- xrot = args[a + 2];
-
- lflag = oargs[a + 3]; // we need the original string to deal with leading zeroes
- let fixed = false;
-
- if (lflag.length > 1) {
- const b1 = parseInt(lflag[0], 10);
- const b2 = parseInt(lflag[1], 10);
- let rest;
- // eslint-disable-next-line max-depth
- if (lflag.length > 2) rest = parseFloat(lflag.substring(2));
- args[a + 3] = b1;
- args.splice(a + 4, 0, b2);
- // eslint-disable-next-line max-depth
- if (rest !== undefined) args.splice(a + 5, 0, rest);
- fixed = true;
- }
-
- lflag = args[a + 3];
+ if (instruction.type === 'H') {
+ normalized.push(instruction);
+ x = instruction.x;
+ continue;
+ }
- sweep = fixed ? args[a + 4] : oargs[a + 4]; // we need the original string to deal with leading zeroes
- if (!fixed && (sweep as string).length > 1) {
- args[a + 4] = parseInt((sweep as string)[0], 10);
- args.splice(a + 5, 0, parseFloat((sweep as string).substring(1)));
- }
+ if (instruction.type === 'V') {
+ normalized.push(instruction);
+ y = instruction.y;
+ continue;
+ }
- sweep = args[a + 4];
+ if (instruction.type === 'Z') {
+ normalized.push(instruction);
+ x = initialX;
+ y = initialY;
+ continue;
+ }
- if (op === 'a') {
- x += args[a + 5];
- y += args[a + 6];
- } else {
- x = args[a + 5];
- y = args[a + 6];
- }
+ if (instruction.type === 'h') {
+ x += instruction.dx;
+ normalized.push({
+ type: 'H',
+ x,
+ });
+ continue;
+ }
- normalized +=
- 'A ' +
- rx +
- ' ' +
- ry +
- ' ' +
- xrot +
- ' ' +
- lflag +
- ' ' +
- sweep +
- ' ' +
- x +
- ' ' +
- y +
- ' ';
- }
- } else if (lop === 'z') {
- normalized += 'Z ';
- // not unimportant: path closing changes the current x/y coordinate
- x = sx;
- y = sy;
+ if (instruction.type === 'v') {
+ y += instruction.dy;
+ normalized.push({
+ type: 'V',
+ y,
+ });
+ continue;
}
+
+ // @ts-expect-error
+ throw new Error('Unknown instruction type: ' + instruction.type);
}
- return normalized.trim();
+ return normalized;
};
diff --git a/packages/paths/src/parse-path.ts b/packages/paths/src/parse-path.ts
index 3280ecb57e..42ce3461cf 100644
--- a/packages/paths/src/parse-path.ts
+++ b/packages/paths/src/parse-path.ts
@@ -2,7 +2,7 @@
import type {Instruction} from './helpers/types';
-const length: {[key in Instruction['type']]: number} = {
+const length: {[key in Instruction['type'] | 'z']: number} = {
a: 7,
A: 7,
C: 6,
@@ -72,7 +72,7 @@ export const parsePath = (path: string): Instruction[] => {
return segments
.map((segmentString: string): Instruction[] => {
- const command = segmentString.charAt(0) as Instruction['type'];
+ const command = segmentString.charAt(0) as Instruction['type'] | 'z';
const args = parseValues(segmentString.substring(1), command);
// overloaded moveTo
@@ -120,14 +120,6 @@ export const parsePath = (path: string): Instruction[] => {
];
}
- if (command === 'z') {
- return [
- {
- type: 'z',
- },
- ];
- }
-
if (command === 'A') {
return makeInstructions(args, command, (numbers) => ({
type: command,
@@ -299,7 +291,10 @@ export const parsePath = (path: string): Instruction[] => {
.flat(1);
};
-const parseValues = (args: string, instructionType: Instruction['type']) => {
+const parseValues = (
+ args: string,
+ instructionType: Instruction['type'] | 'z'
+) => {
const numbers = args.match(numberRegExp);
if (!numbers) {
if (instructionType === 'Z' || instructionType === 'z') {
diff --git a/packages/paths/src/serialize-instructions.ts b/packages/paths/src/serialize-instructions.ts
index 3a5782528e..4efc890438 100644
--- a/packages/paths/src/serialize-instructions.ts
+++ b/packages/paths/src/serialize-instructions.ts
@@ -41,10 +41,6 @@ const serializeInstruction = (instruction: Instruction): string => {
return `q ${instruction.cpdx} ${instruction.cpdy} ${instruction.dx} ${instruction.dy}`;
}
- if (instruction.type === 'z') {
- return 'z';
- }
-
if (instruction.type === 'Z') {
return 'Z';
}
diff --git a/packages/paths/src/simplify-instructions.ts b/packages/paths/src/simplify-instructions.ts
index 338a0c586e..19b011187d 100644
--- a/packages/paths/src/simplify-instructions.ts
+++ b/packages/paths/src/simplify-instructions.ts
@@ -1,12 +1,10 @@
import {removeATSHVInstructions} from './helpers/remove-a-s-t-curves';
-import type {AbsoluteInstruction, Instruction} from './helpers/types';
-import {normalizePath} from './normalize-path';
-import {parsePath} from './parse-path';
-import {serializeInstructions} from './serialize-instructions';
+import type {Instruction, ReducedInstruction} from './helpers/types';
+import {normalizeInstructions} from './normalize-path';
-export const simplifyInstructions = (instruction: Instruction[]) => {
- const serialized = serializeInstructions(instruction);
- const simplified = normalizePath(serialized);
- const parsed = parsePath(simplified) as AbsoluteInstruction[];
- return removeATSHVInstructions(parsed);
+export const simplifyInstructions = (
+ instruction: Instruction[]
+): ReducedInstruction[] => {
+ const simplified = normalizeInstructions(instruction);
+ return removeATSHVInstructions(simplified);
};
diff --git a/packages/paths/src/test/serialize-instructions.test.ts b/packages/paths/src/test/serialize-instructions.test.ts
index f507ecd7d2..0192839fa1 100644
--- a/packages/paths/src/test/serialize-instructions.test.ts
+++ b/packages/paths/src/test/serialize-instructions.test.ts
@@ -10,10 +10,10 @@ test('Should serialize instructions', () => {
y: 100,
},
{
- type: 'z',
+ type: 'Z',
},
])
- ).toBe('M 100 100 z');
+ ).toBe('M 100 100 Z');
});
test('Should not serialize bad instructions', () => {
diff --git a/packages/paths/src/translate-path.ts b/packages/paths/src/translate-path.ts
index e89c7f4e72..eb41174419 100644
--- a/packages/paths/src/translate-path.ts
+++ b/packages/paths/src/translate-path.ts
@@ -11,7 +11,6 @@ const translateSegments = (segments: Instruction[], x: number, y: number) => {
segment.type === 'c' ||
segment.type === 'v' ||
segment.type === 's' ||
- segment.type === 'z' ||
segment.type === 'h' ||
segment.type === 'l' ||
segment.type === 'm' ||