🎥 Make videos programmatically with React
random API
Jonny Burger9d8ec6c3d5c8
diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex cf75949377..a51fcd358c 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -9,6 +9,7 @@ export * from './IFrame';export * from './Img';export * from './internals';export * from './interpolate';+export * from './random';export * from './ready-manager';export {registerRoot} from './register-root';export {Sequence} from './sequencing';diff --git a/packages/core/src/random.ts b/packages/core/src/random.tsindex c575412794..2c41b75ed3 100644--- a/packages/core/src/random.ts+++ b/packages/core/src/random.ts@@ -18,18 +18,23 @@ function hashCode(str: string) {return hash;}-export const random = (input: number | string | null, dummy?: unknown) => {+/**+ * A deterministic pseudo-random number generator.+ * Pass in the same seed and get the same pseudorandom number.+ * See: https://remotion.dev/docs/random+ */+export const random = (seed: number | string | null, dummy?: unknown) => {if (dummy !== undefined) {throw new TypeError('random() takes only one argument');}- if (input === null) {+ if (seed === null) {return Math.random();}- if (typeof input === 'string') {- return mulberry32(hashCode(input));+ if (typeof seed === 'string') {+ return mulberry32(hashCode(seed));}- if (typeof input === 'number') {- return mulberry32(input * 10000000000);+ if (typeof seed === 'number') {+ return mulberry32(seed * 10000000000);}throw new Error('random() argument must be a number or a string');};diff --git a/packages/docs/docs/random.md b/packages/docs/docs/random.mdnew file mode 100644index 0000000000..0a33c1c31b--- /dev/null+++ b/packages/docs/docs/random.md@@ -0,0 +1,38 @@+---+id: random+title: random()+---++The `random()` API will give your deterministic pseudorandom values. Unlike the `Math.random()` function, Remotions function takes in a seed which can be a `number` or a `string`. If the seed is the same, the output is always the same.++```ts+const rand = random(1); // 0.07301638228818774+const rand = random(1); // still 0.07301638228818774+++const randomCoordinates = new Array(10).fill(true).map((a, i) => {+ return {+ x: random(`random-x-${i}`),+ y: random(`random--${i}`),+ };+}); // will always be [{x: 0.2887063352391124, y: 0.18660089606419206}, ...]++random() // Error: random() argument must be a number or a string+```++## Use cases++Randomness can be used to create to create interesting visualizations, such as particle effect for example. Since Remotion renders a video on multiple threads and opens the website multiple times, the value returned by a `Math.random()` call will not be the same across multiple threads, making it hard to create animations based on randomness. Using this API will ensure that the pseudorandom number will be the same always.++## Accessing true randomness++Calling `Math.random()` results in an ESLint warning in Remotion since often it leads to bugs in rendering. If you are sure you want a true random number, and want to bypass this message without adding an ignore comment, use `random(null)`++```ts+// Passing null will result in a different value every time.+random(null) === random(null) // false+```++## See also++- [Using randomness](using-randomness)diff --git a/packages/docs/docs/using-randomness.md b/packages/docs/docs/using-randomness.mdnew file mode 100644index 0000000000..6010880d44--- /dev/null+++ b/packages/docs/docs/using-randomness.md@@ -0,0 +1,50 @@+---+id: using-randomness+title: Using randomness+---++The following thing is an anti-pattern in Remotion:++```tsx+const MyComp: React.FC = () => {+ const randomValues = useState(() => {+ return new Array(10).fill(true).map((a, i) => {+ return {+ x: Math.random(),+ y: Math.random(),+ };+ });+ );+ // Do something with coordinates+}+```++While this will work during preview, it will break while rendering. The reason is that Remotion is spinning up multiple instances of the webpage to render frames in parallel, and the random values will be different on every instance.++## Fixing the problem++Use the [`random()`](random) API from Remotion to get deterministic pseudorandom values. Pass in a seed (number or string) and as long as the seed is the same, the return value will be the same.++```tsx {7,8}+import {random} from 'remotion';++const MyComp: React.FC = () => {+ // No need to use useState+ const randomValues = new Array(10).fill(true).map((a, i) => {+ return {+ x: random(`x-${i}`),+ y: random(`y-${i}`),+ };+ });+}+```++Now the random values will be the same on all threads.++## False positives++Did you get an ESLint warning when using `Math.random()`, but you are fully aware of the circumstances described above? Use `random(null)` to get a true random value without getting a warning.++## See also++- [random()](random)diff --git a/packages/docs/sidebars.js b/packages/docs/sidebars.jsindex 0502c43cab..4423b2b040 100644--- a/packages/docs/sidebars.js+++ b/packages/docs/sidebars.js@@ -23,6 +23,7 @@ module.exports = {"webpack","use-img-and-iframe","javascript",+ "using-randomness",],},{@@ -34,6 +35,7 @@ module.exports = {"continue-render","delay-render","interpolate",+ "random","register-root","spring","use-current-frame",diff --git a/packages/eslint-config/src/auto-import-rules.ts b/packages/eslint-config/src/auto-import-rules.tsindex 61599e043e..d4934618e9 100644--- a/packages/eslint-config/src/auto-import-rules.ts+++ b/packages/eslint-config/src/auto-import-rules.ts@@ -8,6 +8,7 @@ export const autoImports = {useCurrentFrame: "import {useCurrentFrame} from 'remotion'",useVideoConfig: "import {useVideoConfig} from 'remotion'",spring: "import {spring} from 'remotion'",+ random: "import {random} from 'remotion'",AbsoluteFill: "import {AbsoluteFill} from 'remotion'",Sequence: "import {Sequence} from 'remotion'",Composition: "import {Composition} from 'remotion'",diff --git a/packages/eslint-config/src/index.ts b/packages/eslint-config/src/index.tsindex 89dcff2e13..9c98c77d59 100644--- a/packages/eslint-config/src/index.ts+++ b/packages/eslint-config/src/index.ts@@ -39,7 +39,7 @@ const getRules = (typescript: boolean) => {// Enable Remotion specific rules"@remotion/no-mp4-import": "warn","@remotion/warn-native-media-tag": "warn",- "@remotion/determinstic-randomness": "warn",+ "@remotion/deterministic-randomness": "warn",};};diff --git a/packages/eslint-plugin/src/index.ts b/packages/eslint-plugin/src/index.tsindex 57c3a2f631..7354e7ac5d 100644--- a/packages/eslint-plugin/src/index.ts+++ b/packages/eslint-plugin/src/index.ts@@ -5,7 +5,7 @@ import warnNativeMediaTag from "./rules/warn-native-media-tag";const rules = {"no-mp4-import": nomp4Import,"warn-native-media-tag": warnNativeMediaTag,- "determistic-randomess": deterministicRandomness,+ "deterministic-randomness": deterministicRandomness,};export = {diff --git a/packages/eslint-plugin/src/rules/deterministic-randomness.ts b/packages/eslint-plugin/src/rules/deterministic-randomness.tsindex 38d31f278b..80feb982b9 100644--- a/packages/eslint-plugin/src/rules/deterministic-randomness.ts+++ b/packages/eslint-plugin/src/rules/deterministic-randomness.ts@@ -12,10 +12,11 @@ const DeterministicRandomness = ["The result of Math.random() will change between frames while rendering because multiple threads are used.","Use the `random()` API from Remotion to get a deterministic pseudorandom value.","If you are sure you want a true random value, use `random(null)` to hide this warning.",+ "See: https://remotion.dev/docs/using-randomness",].join("\n");export default createRule<Options, MessageIds>({- name: "determinstic-randomness",+ name: "deterministic-randomness",meta: {type: "problem",docs: {diff --git a/packages/eslint-plugin/src/tests/no-math-random.test.ts b/packages/eslint-plugin/src/tests/no-math-random.test.tsindex 0c6fdd96c9..6c6654d37d 100644--- a/packages/eslint-plugin/src/tests/no-math-random.test.ts+++ b/packages/eslint-plugin/src/tests/no-math-random.test.ts@@ -4,7 +4,7 @@ const ruleTester = new ESLintUtils.RuleTester({parser: "@typescript-eslint/parser",});-ruleTester.run("determinstic-randomness", rule, {+ruleTester.run("deterministic-randomness", rule, {valid: ['import {random} from "remotion";\nconst hi = random(null)'],invalid: [{