🎥 Make videos programmatically with React
to new
Jonny Burgerb638981b6cdf
diff --git a/packages/paths/src/interpolate-path/command-to-string.ts b/packages/paths/src/interpolate-path/command-to-string.tsdeleted file mode 100644index 9d93120e3a..0000000000--- a/packages/paths/src/interpolate-path/command-to-string.ts+++ /dev/null@@ -1,13 +0,0 @@-import type {Command} from './command';-import {typeMap} from './command';--/**- * Converts a command object to a string to be used in a `d` attribute- * @param {Object} command A command object- * @return {String} The string for the `d` attribute- */-export function commandToString(command: Command) {- return `${command.type} ${typeMap[command.type]- .map((p) => command[p as keyof Command])- .join(' ')}`;-}diff --git a/packages/paths/src/interpolate-path/command.ts b/packages/paths/src/interpolate-path/command.tsdeleted file mode 100644index e79c48975d..0000000000--- a/packages/paths/src/interpolate-path/command.ts+++ /dev/null@@ -1,37 +0,0 @@-/**- * List of params for each command type in a path `d` attribute- */-export const typeMap = {- M: ['x', 'y'],- L: ['x', 'y'],- H: ['x'],- V: ['y'],- C: ['x1', 'y1', 'x2', 'y2', 'x', 'y'],- S: ['x2', 'y2', 'x', 'y'],- Q: ['x1', 'y1', 'x', 'y'],- T: ['x', 'y'],- A: ['rx', 'ry', 'xAxisRotation', 'largeArcFlag', 'sweepFlag', 'x', 'y'],- Z: [],- m: ['x', 'y'],- l: ['x', 'y'],- h: ['x'],- v: ['y'],- c: ['x1', 'y1', 'x2', 'y2', 'x', 'y'],- s: ['x2', 'y2', 'x', 'y'],- q: ['x1', 'y1', 'x', 'y'],- t: ['x', 'y'],- a: ['rx', 'ry', 'xAxisRotation', 'largeArcFlag', 'sweepFlag', 'x', 'y'],- z: [],-};-export type Command = {- x2?: number | undefined;- y2?: number | undefined;- x1?: number | undefined;- y1?: number | undefined;- x?: number;- y?: number;- xAxisRotate?: number;- largeArcFlag?: boolean;- sweepFlag?: boolean;- type: keyof typeof typeMap;-};diff --git a/packages/paths/src/interpolate-path/convert-to-same-instruction-type.ts b/packages/paths/src/interpolate-path/convert-to-same-instruction-type.tsindex 17042b061b..64e80d3fc9 100644--- a/packages/paths/src/interpolate-path/convert-to-same-instruction-type.ts+++ b/packages/paths/src/interpolate-path/convert-to-same-instruction-type.ts@@ -7,6 +7,8 @@ import type {const convertToLCommand = (command: ReducedInstruction): LInstruction => {if (command.type === 'M' || command.type === 'L' || command.type === 'Z') {+ console.log({command});+throw new Error('unexpected');}@@ -110,15 +112,15 @@ export function convertToSameInstructionType(}if (aCommand.type === 'C') {- return convertToCCommand(aCommand);+ return convertToCCommand(bCommand);}if (aCommand.type === 'L') {- return convertToLCommand(aCommand);+ return convertToLCommand(bCommand);}if (aCommand.type === 'Q') {- return convertToQCommand(aCommand);+ return convertToQCommand(bCommand);}if (aCommand.type === 'Z') {diff --git a/packages/paths/src/interpolate-path/convert-to-same-type.ts b/packages/paths/src/interpolate-path/convert-to-same-type.tsdeleted file mode 100644index 2e5b583c31..0000000000--- a/packages/paths/src/interpolate-path/convert-to-same-type.ts+++ /dev/null@@ -1,74 +0,0 @@-import type {Command} from './command';--/**- * Converts command A to have the same type as command B.- *- * e.g., L0,5 -> C0,5,0,5,0,5- *- * Uses these rules:- * x1 <- x- * x2 <- x- * y1 <- y- * y2 <- y- * rx <- 0- * ry <- 0- * xAxisRotation <- read from B- * largeArcFlag <- read from B- * sweepflag <- read from B- *- * @param {Object} aCommand Command object from path `d` attribute- * @param {Object} bCommand Command object from path `d` attribute to match against- * @return {Object} aCommand converted to type of bCommand- */-export function convertToSameType(aCommand: Command, bCommand: Command) {- const conversionMap = {- x1: 'x',- y1: 'y',- x2: 'x',- y2: 'y',- } as const;-- const readFromBKeys = ['xAxisRotation', 'largeArcFlag', 'sweepFlag'];-- // convert (but ignore M types)- if (aCommand.type !== bCommand.type && bCommand.type.toUpperCase() !== 'M') {- const aConverted: Command = {- type: bCommand.type,- };- Object.keys(bCommand).forEach((bKey) => {- const bValue = bCommand[bKey as keyof Command];- // first read from the A command- let aValue = aCommand[bKey as keyof Command];-- // if it is one of these values, read from B no matter what- if (aValue === undefined) {- if (readFromBKeys.includes(bKey)) {- aValue = bValue;- } else {- // if it wasn't in the A command, see if an equivalent was- if (- aValue === undefined &&- conversionMap[bKey as keyof typeof conversionMap]- ) {- aValue =- aCommand[conversionMap[bKey as keyof typeof conversionMap]];- }-- // if it doesn't have a converted value, use 0- if (aValue === undefined) {- aValue = 0;- }- }- }-- // @ts-expect-error- aConverted[bKey as keyof Command] = aValue;- });-- // update the type to match B- aConverted.type = bCommand.type;- aCommand = aConverted;- }-- return aCommand;-}diff --git a/packages/paths/src/interpolate-path/extend-command.ts b/packages/paths/src/interpolate-path/extend-command.tsindex 5c723f0207..f711745053 100644--- a/packages/paths/src/interpolate-path/extend-command.ts+++ b/packages/paths/src/interpolate-path/extend-command.ts@@ -1,85 +1,6 @@import type {ReducedInstruction} from '../helpers/types';import {arrayOfLength} from './array-of-length';-import type {Command} from './command';-import {splitSegment, splitSegmentInstructions} from './split-segment';--/**- * Extends an array of commandsToExtend to the length of the referenceCommands by- * splitting segments until the number of commands match. Ensures all the actual- * points of commandsToExtend are in the extended array.- *- * @param {Object[]} commandsToExtend The command object array to extend- * @param {Object[]} referenceCommands The command object array to match in length- * @return {Object[]} The extended commandsToExtend array- */-export function extend(- commandsToExtend: Command[],- referenceCommands: Command[],-) {- // compute insertion points:- // number of segments in the path to extend- const numSegmentsToExtend = commandsToExtend.length - 1;-- // number of segments in the reference path.- const numReferenceSegments = referenceCommands.length - 1;-- // this value is always between [0, 1].- const segmentRatio = numSegmentsToExtend / numReferenceSegments;-- // create a map, mapping segments in referenceCommands to how many points- // should be added in that segment (should always be >= 1 since we need each- // point itself).- // 0 = segment 0-1, 1 = segment 1-2, n-1 = last vertex- const countPointsPerSegment = arrayOfLength<undefined>(- numReferenceSegments,- undefined,- ).reduce(- (accum, _d, i) => {- const insertIndex = Math.floor(segmentRatio * i);-- accum[insertIndex] = (accum[insertIndex] || 0) + 1;-- return accum;- },- [] as (undefined | number)[],- );-- // extend each segment to have the correct number of points for a smooth interpolation- const extended = countPointsPerSegment.reduce(- (_extended, segmentCount, i) => {- // if last command, just add `segmentCount` number of times- if (i === commandsToExtend.length - 1) {- const lastCommandCopies = arrayOfLength(segmentCount as number, {- ...commandsToExtend[commandsToExtend.length - 1],- });-- // convert M to L- if (lastCommandCopies[0].type === 'M') {- lastCommandCopies.forEach((d) => {- d.type = 'L';- });- }-- return _extended.concat(lastCommandCopies);- }-- // otherwise, split the segment segmentCount times.- return _extended.concat(- splitSegment(- commandsToExtend[i],- commandsToExtend[i + 1],- segmentCount as number,- ),- );- },- [] as Command[],- );-- // add in the very first point since splitSegment only adds in the ones after it- extended.unshift(commandsToExtend[0]);-- return extended;-}+import {splitSegmentInstructions} from './split-segment';/*** Extends an array of commandsToExtend to the length of the referenceCommands bydiff --git a/packages/paths/src/interpolate-path/interpolate-commands.ts b/packages/paths/src/interpolate-path/interpolate-commands.tsdeleted file mode 100644index c92825ab89..0000000000--- a/packages/paths/src/interpolate-path/interpolate-commands.ts+++ /dev/null@@ -1,131 +0,0 @@-import {typeMap, type Command} from './command';-import {convertToSameType} from './convert-to-same-type';-import {extend} from './extend-command';--/**- * Interpolate from A to B by extending A and B during interpolation to have- * the same number of points. This allows for a smooth transition when they- * have a different number of points.- *- * Ignores the `Z` command in paths unless both A and B end with it.- *- * This function works directly with arrays of command objects instead of with- * path `d` strings (see interpolatePath for working with `d` strings).- *- * @param {Object[]} aCommandsInput Array of path commands- * @param {Object[]} bCommandsInput Array of path commands- * @returns {Function} Interpolation function that maps t ([0, 1]) to an array of path commands.- */-export function interpolatePathCommands(- aCommandsInput: Command[],- bCommandsInput: Command[],-) {- // make a copy so we don't mess with the input arrays- let aCommands =- aCommandsInput === null || aCommandsInput === undefined- ? []- : aCommandsInput.slice();- let bCommands =- bCommandsInput === null || bCommandsInput === undefined- ? []- : bCommandsInput.slice();-- // both input sets are empty, so we don't interpolate- if (!aCommands.length && !bCommands.length) {- return function () {- return [];- };- }-- // do we add Z during interpolation? yes if both have it. (we'd expect both to have it or not)- const addZ =- (aCommands.length === 0 || aCommands[aCommands.length - 1].type === 'Z') &&- (bCommands.length === 0 || bCommands[bCommands.length - 1].type === 'Z');-- // we temporarily remove Z- if (aCommands.length > 0 && aCommands[aCommands.length - 1].type === 'Z') {- aCommands.pop();- }-- if (bCommands.length > 0 && bCommands[bCommands.length - 1].type === 'Z') {- bCommands.pop();- }-- // if A is empty, treat it as if it used to contain just the first point- // of B. This makes it so the line extends out of from that first point.- if (!aCommands.length) {- aCommands.push(bCommands[0]);-- // otherwise if B is empty, treat it as if it contains the first point- // of A. This makes it so the line retracts into the first point.- } else if (!bCommands.length) {- bCommands.push(aCommands[0]);- }-- // extend to match equal size- const numPointsToExtend = Math.abs(bCommands.length - aCommands.length);-- if (numPointsToExtend !== 0) {- // B has more points than A, so add points to A before interpolating- if (bCommands.length > aCommands.length) {- aCommands = extend(aCommands, bCommands);-- // else if A has more points than B, add more points to B- } else if (bCommands.length < aCommands.length) {- bCommands = extend(bCommands, aCommands);- }- }-- // commands have same length now.- // convert commands in A to the same type as those in B- aCommands = aCommands.map((aCommand, i) =>- convertToSameType(aCommand, bCommands[i]),- );-- // create mutable interpolated command objects- const interpolatedCommands = aCommands.map((aCommand) => ({...aCommand}));-- if (addZ) {- interpolatedCommands.push({type: 'Z'});- aCommands.push({type: 'Z'}); // required for when returning at t == 0- }-- return function (t: number) {- // at 1 return the final value without the extensions used during interpolation- if (t === 1) {- return bCommandsInput === null || bCommandsInput === undefined- ? []- : bCommandsInput;- }-- // work with aCommands directly since interpolatedCommands are mutated- if (t === 0) {- return aCommands;- }-- // interpolate the commands using the mutable interpolated command objs- for (let i = 0; i < interpolatedCommands.length; ++i) {- // if (interpolatedCommands[i].type === 'Z') continue;-- const aCommand = aCommands[i];- const bCommand = bCommands[i];- const interpolatedCommand = interpolatedCommands[i];- for (const arg of typeMap[- interpolatedCommand.type as keyof typeof typeMap- ]) {- // @ts-expect-error- interpolatedCommand[arg] =- (1 - t) * (aCommand[arg as keyof Command] as number) +- t * (bCommand[arg as keyof Command] as number);-- // do not use floats for flags (#27), round to integer- if (arg === 'largeArcFlag' || arg === 'sweepFlag') {- // @ts-expect-error- interpolatedCommand[arg] = Math.round(interpolatedCommand[arg]);- }- }- }-- return interpolatedCommands;- };-}diff --git a/packages/paths/src/interpolate-path/interpolate-instructions.ts b/packages/paths/src/interpolate-path/interpolate-instructions.tsindex 73639faa07..c881934df5 100644--- a/packages/paths/src/interpolate-path/interpolate-instructions.ts+++ b/packages/paths/src/interpolate-path/interpolate-instructions.ts@@ -96,9 +96,7 @@ export function interpolateInstructions(return function (t: number) {// at 1 return the final value without the extensions used during interpolationif (t === 1) {- return bCommandsInput === null || bCommandsInput === undefined- ? []- : bCommandsInput;+ return bCommandsInput;}// work with aCommands directly since interpolatedCommands are mutateddiff --git a/packages/paths/src/interpolate-path/interpolate-path.ts b/packages/paths/src/interpolate-path/interpolate-path.tsindex 2376784e4f..78e10b22b6 100644--- a/packages/paths/src/interpolate-path/interpolate-path.ts+++ b/packages/paths/src/interpolate-path/interpolate-path.ts@@ -31,9 +31,10 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/-import {commandToString} from './command-to-string';-import {interpolatePathCommands} from './interpolate-commands';-import {pathCommandsFromString} from './path-commands-from-string';+import {parsePath} from '../parse-path';+import {reduceInstructions} from '../reduce-instructions';+import {serializeInstructions} from '../serialize-instructions';+import {interpolateInstructions} from './interpolate-instructions';/*** @description Interpolates between two SVG paths.@@ -56,25 +57,19 @@ export const interpolatePath = (return firstPath;}- const aCommands = pathCommandsFromString(firstPath);+ const aCommands = reduceInstructions(parsePath(firstPath));if (aCommands.length === 0) {throw new TypeError(`SVG Path "${firstPath}" is not valid`);}- const bCommands = pathCommandsFromString(secondPath);+ const bCommands = reduceInstructions(parsePath(secondPath));if (bCommands.length === 0) {throw new TypeError(`SVG Path "${secondPath}" is not valid`);}- const commandInterpolator = interpolatePathCommands(aCommands, bCommands);+ const commandInterpolator = interpolateInstructions(aCommands, bCommands);const interpolatedCommands = commandInterpolator(value);- // convert to a string (fastest concat: https://jsperf.com/join-concat/150)-- return interpolatedCommands- .map((c) => {- return commandToString(c);- })- .join(' ');+ return serializeInstructions(interpolatedCommands);};diff --git a/packages/paths/src/interpolate-path/path-commands-from-string.ts b/packages/paths/src/interpolate-path/path-commands-from-string.tsdeleted file mode 100644index ba37dbe90c..0000000000--- a/packages/paths/src/interpolate-path/path-commands-from-string.ts+++ /dev/null@@ -1,44 +0,0 @@-import {typeMap, type Command} from './command';--const commandTokenRegex = /[MLCSTQAHVZmlcstqahv]|-?[\d.e+-]+/g;--/**- * Takes a path `d` string and converts it into an array of command- * objects. Drops the `Z` character.- *- * @param {String|null} d A path `d` string- */-export function pathCommandsFromString(d: string | null) {- // split into valid tokens- const tokens = (d || '').match(commandTokenRegex) || [];- const commands = [];- let commandArgs: string[];- let command: Command;-- // iterate over each token, checking if we are at a new command- // by presence in the typeMap- for (let i = 0; i < tokens.length; ++i) {- commandArgs = typeMap[tokens[i] as keyof typeof typeMap];-- // new command found:- if (commandArgs) {- command = {- type: tokens[i] as Command['type'],- };-- // add each of the expected args for this command:- for (let a = 0; a < commandArgs.length; ++a) {- // @ts-expect-error- command[commandArgs[a] as keyof Command] = Number(tokens[i + a + 1]);- }-- // need to increment our token index appropriately since- // we consumed token args- i += commandArgs.length;-- commands.push(command);- }- }-- return commands;-}diff --git a/packages/paths/src/interpolate-path/points-to-command.ts b/packages/paths/src/interpolate-path/points-to-command.tsindex 4eb87e08b5..a8e7988942 100644--- a/packages/paths/src/interpolate-path/points-to-command.ts+++ b/packages/paths/src/interpolate-path/points-to-command.ts@@ -1,44 +1,4 @@import type {ReducedInstruction} from '../helpers/types';-import type {Command} from './command';--/**- * Convert segments represented as points back into a command object- *- * @param {Number[][]} points Array of [x,y] points: [start, control1, control2, ..., end]- * Represents a segment- * @return {Object} A command object representing the segment.- */-export function pointsToCommand(points: number[][]): Command {- let x2: number | undefined;- let y2: number | undefined;- let x1: number | undefined;- let y1: number | undefined;-- if (points.length === 4) {- x2 = points[2][0];- y2 = points[2][1];- }-- if (points.length >= 3) {- x1 = points[1][0];- y1 = points[1][1];- }-- const x = points[points.length - 1][0];- const y = points[points.length - 1][1];-- let type: 'C' | 'Q' | 'L' = 'L';-- if (points.length === 4) {- // start, control1, control2, end- type = 'C';- } else if (points.length === 3) {- // start, control, end- type = 'Q';- }-- return {x2, y2, x1, y1, x, y, type};-}/*** Convert segments represented as points back into a command objectdiff --git a/packages/paths/src/interpolate-path/split-curve.ts b/packages/paths/src/interpolate-path/split-curve.tsindex 833d47c9ec..236d50106e 100644--- a/packages/paths/src/interpolate-path/split-curve.ts+++ b/packages/paths/src/interpolate-path/split-curve.ts@@ -37,41 +37,9 @@ import type {QInstruction,ReducedInstruction,} from '../helpers/types';-import type {Command} from './command';-import {pointsToCommand, pointsToInstruction} from './points-to-command';+import {pointsToInstruction} from './points-to-command';import {splitCurveAsPoints} from './split-curve-as-points';-/**- * Convert command objects to arrays of points, run de Casteljau's algorithm on it- * to split into to the desired number of segments.- *- * @param {Object} commandStart The start command object- * @param {Object} commandEnd The end command object- * @param {Number} segmentCount The number of segments to create- * @return {Object[]} An array of commands representing the segments in sequence- */-export const splitCurve = (- commandStartX: number,- commandStartY: number,- commandEnd: Command,- segmentCount: number,-): Command[] => {- const points = [[commandStartX, commandStartY]] as number[][];- if (commandEnd.x1 !== null && commandEnd.x1 !== undefined) {- points.push([commandEnd.x1, commandEnd.y1 as number]);- }-- if (commandEnd.x2 !== null && commandEnd.x2 !== undefined) {- points.push([commandEnd.x2, commandEnd.y2 as number]);- }-- points.push([commandEnd.x as number, commandEnd.y as number]);-- return splitCurveAsPoints(points, segmentCount).map((p) =>- pointsToCommand(p),- );-};-/*** Convert command objects to arrays of points, run de Casteljau's algorithm on it* to split into to the desired number of segments.diff --git a/packages/paths/src/interpolate-path/split-segment.ts b/packages/paths/src/interpolate-path/split-segment.tsindex 32c45acfcf..8222304801 100644--- a/packages/paths/src/interpolate-path/split-segment.ts+++ b/packages/paths/src/interpolate-path/split-segment.ts@@ -1,7 +1,6 @@import type {ReducedInstruction} from '../helpers/types';import {arrayOfLength} from './array-of-length';-import type {Command} from './command';-import {splitCurve, splitCurveInstructions} from './split-curve';+import {splitCurveInstructions} from './split-curve';/*** Interpolate between command objects commandStart and commandEnd segmentCount times.@@ -16,49 +15,6 @@ import {splitCurve, splitCurveInstructions} from './split-curve';* commandEnd. (Can be segmentCount+1 objects if commandStart is type M).*/-// TODO: Delete and replace-export function splitSegment(- commandStart: Command,- commandEnd: Command,- segmentCount: number,-) {- let segments: Command[] = [];-- // line, quadratic bezier, or cubic bezier- if (- commandEnd.type === 'L' ||- commandEnd.type === 'Q' ||- commandEnd.type === 'C'- ) {- if (commandStart.type !== 'Z') {- segments = segments.concat(- splitCurve(- commandStart.x as number,- commandStart.y as number,- commandEnd,- segmentCount,- ),- );- }-- // general case - just copy the same point- } else {- const copyCommand = {...commandStart};-- // convert M to L- if (copyCommand.type === 'M') {- copyCommand.type = 'L';- }-- segments = segments.concat(- arrayOfLength(segmentCount - 1, undefined).map(() => copyCommand),- );- segments.push(commandEnd);- }-- return segments;-}-export function splitSegmentInstructions(commandStart: ReducedInstruction,commandEnd: ReducedInstruction,