🎥 Make videos programmatically with React
split up into functions
Jonny Burgere4a7e650b98c
diff --git a/packages/paths/src/interpolate-path/array-of-length.ts b/packages/paths/src/interpolate-path/array-of-length.tsnew file mode 100644index 0000000000..d9bc26cbab--- /dev/null+++ b/packages/paths/src/interpolate-path/array-of-length.ts@@ -0,0 +1,8 @@+export function arrayOfLength<T>(length: number, value: T): T[] {+ const array = Array(length);+ for (let i = 0; i < length; i++) {+ array[i] = value;+ }++ return array;+}diff --git a/packages/paths/src/interpolate-path/convert-to-same-type.ts b/packages/paths/src/interpolate-path/convert-to-same-type.tsnew file mode 100644index 0000000000..2e5b583c31--- /dev/null+++ b/packages/paths/src/interpolate-path/convert-to-same-type.ts@@ -0,0 +1,74 @@+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.tsnew file mode 100644index 0000000000..a031f8ce79--- /dev/null+++ b/packages/paths/src/interpolate-path/extend-command.ts@@ -0,0 +1,81 @@+import {arrayOfLength} from './array-of-length';+import type {Command} from './command';+import {splitSegment} 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;+}diff --git a/packages/paths/src/interpolate-path/interpolate-path.ts b/packages/paths/src/interpolate-path/interpolate-path.tsindex 492f68fd31..577871b849 100644--- a/packages/paths/src/interpolate-path/interpolate-path.ts+++ b/packages/paths/src/interpolate-path/interpolate-path.ts@@ -33,254 +33,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.import {typeMap, type Command} from './command';import {commandToString} from './command-to-string';-import {splitCurve} from './split-curve';--const commandTokenRegex = /[MLCSTQAHVZmlcstqahv]|-?[\d.e+-]+/g;--function arrayOfLength<T>(length: number, value: T): T[] {- const array = Array(length);- for (let i = 0; i < length; i++) {- array[i] = value;- }-- return array;-}--/**- * 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- */-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;-}--/**- * Interpolate between command objects commandStart and commandEnd segmentCount times.- * If the types are L, Q, or C then the curves are split as per de Casteljau's algorithm.- * Otherwise we just copy commandStart segmentCount - 1 times, finally ending with commandEnd.- *- * @param {Object} commandStart Command object at the beginning of the segment- * @param {Object} commandEnd Command object at the end of the segment- * @param {Number} segmentCount The number of segments to split this into. If only 1- * Then [commandEnd] is returned.- * @return {Object[]} Array of ~segmentCount command objects between commandStart and- * commandEnd. (Can be segmentCount+1 objects if commandStart is type M).- */-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'- ) {- segments = segments.concat(- splitCurve(commandStart, 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;-}--/**- * 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- */-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;-}--/**- * 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- */-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;-}+import {convertToSameType} from './convert-to-same-type';+import {extend} from './extend-command';+import {pathCommandsFromString} from './path-commands-from-string';/*** Interpolate from A to B by extending A and B during interpolation to havediff --git a/packages/paths/src/interpolate-path/path-commands-from-string.ts b/packages/paths/src/interpolate-path/path-commands-from-string.tsnew file mode 100644index 0000000000..ba37dbe90c--- /dev/null+++ b/packages/paths/src/interpolate-path/path-commands-from-string.ts@@ -0,0 +1,44 @@+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/split-segment.ts b/packages/paths/src/interpolate-path/split-segment.tsnew file mode 100644index 0000000000..8e93a1dae1--- /dev/null+++ b/packages/paths/src/interpolate-path/split-segment.ts@@ -0,0 +1,50 @@+import {arrayOfLength} from './array-of-length';+import type {Command} from './command';+import {splitCurve} from './split-curve';++/**+ * Interpolate between command objects commandStart and commandEnd segmentCount times.+ * If the types are L, Q, or C then the curves are split as per de Casteljau's algorithm.+ * Otherwise we just copy commandStart segmentCount - 1 times, finally ending with commandEnd.+ *+ * @param {Object} commandStart Command object at the beginning of the segment+ * @param {Object} commandEnd Command object at the end of the segment+ * @param {Number} segmentCount The number of segments to split this into. If only 1+ * Then [commandEnd] is returned.+ * @return {Object[]} Array of ~segmentCount command objects between commandStart and+ * commandEnd. (Can be segmentCount+1 objects if commandStart is type M).+ */+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'+ ) {+ segments = segments.concat(+ splitCurve(commandStart, 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;+}