Skip to content

🎥 Make videos programmatically with React

`@remotion/paths`: Fix parsing arc flags without separators

gjijaca5bf7c7844b
diff --git a/packages/paths/src/parse-path.ts b/packages/paths/src/parse-path.ts
index 7459b2f2b7..d2e723e275 100644
--- a/packages/paths/src/parse-path.ts
+++ b/packages/paths/src/parse-path.ts
@@ -59,13 +59,45 @@ const makeInstructions = (
const segmentRegExp = /([astvzqmhlc])([^astvzqmhlc]*)/gi;
const numberRegExp = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi;
+const arcNumberRegExp =
+ /[\s,]*([-+]?(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:e[-+]?\d+)?)/iy;
+const arcFlagRegExp = /[\s,]*([01])/y;
const parseValues = (
args: string,
instructionType: Instruction['type'] | 'z',
) => {
- const numbers = args.match(numberRegExp);
- if (!numbers) {
+ let numbers: string[] | null;
+ if (instructionType === 'A' || instructionType === 'a') {
+ // Arc flags are a single "0" or "1" and don't need a separator,
+ // e.g. "A1 1 0 011 1" (https://www.w3.org/TR/SVG2/paths.html#PathDataBNF)
+ numbers = [];
+ let match: RegExpExecArray | null;
+ let lastIndex = 0;
+ do {
+ const regExp =
+ numbers.length % 7 === 3 || numbers.length % 7 === 4
+ ? arcFlagRegExp
+ : arcNumberRegExp;
+ regExp.lastIndex = lastIndex;
+ match = regExp.exec(args);
+ if (match) {
+ numbers.push(match[1]);
+ lastIndex = regExp.lastIndex;
+ }
+ } while (match);
+
+ const rest = args.slice(lastIndex);
+ if (!/^[\s,]*$/.test(rest)) {
+ throw new Error(
+ `Malformed path data: ${instructionType} has an invalid value at "${rest.trim()}"`,
+ );
+ }
+ } else {
+ numbers = args.match(numberRegExp);
+ }
+
+ if (!numbers || numbers.length === 0) {
if (instructionType === 'Z' || instructionType === 'z') {
return [];
}
diff --git a/packages/paths/src/test/parse-path.test.ts b/packages/paths/src/test/parse-path.test.ts
index a577422270..dcca78fca5 100644
--- a/packages/paths/src/test/parse-path.test.ts
+++ b/packages/paths/src/test/parse-path.test.ts
@@ -14,3 +14,25 @@ test('Should catch invalid paths', () => {
/Malformed path data: L was expected to have numbers afterwards/,
);
});
+
+test('Should parse arc flags without separators', () => {
+ expect(parsePath('M 0 0 A 1 1 0 0140 40')).toEqual([
+ {type: 'M', x: 0, y: 0},
+ {
+ type: 'A',
+ rx: 1,
+ ry: 1,
+ xAxisRotation: 0,
+ largeArcFlag: false,
+ sweepFlag: true,
+ x: 40,
+ y: 40,
+ },
+ ]);
+ expect(parsePath('M10 10a20 20 0 0140 40 20 20 0 1140-40')).toEqual(
+ parsePath('M10 10a20 20 0 0 1 40 40 20 20 0 1 1 40 -40'),
+ );
+ expect(() => parsePath('M 0 0 A 1 1 0 2 1 40 40')).toThrow(
+ /Malformed path data: A has an invalid value at "2 1 40 40"/,
+ );
+});