Visualize Your Ideas With Code
feat(core): helper methods for references (#775)
Jacob3255add1b05a
diff --git a/packages/core/src/utils/createRefArray.ts b/packages/core/src/utils/createRefArray.tsnew file mode 100644index 00000000..18d44b0a--- /dev/null+++ b/packages/core/src/utils/createRefArray.ts@@ -0,0 +1,62 @@+import {Reference} from './createRef';++type ProxyTarget<T> = {+ (): void;+ array: T[];+};++export type ReferenceArray<T> = T[] & Reference<T>;++/**+ * Create an array of references.+ *+ * @remarks+ * The returned object is both an array and a reference that can be passed+ * directly to the `ref` property of a node.+ *+ * @example+ * ```tsx+ * const labels = createRefArray<Txt>();+ *+ * view.add(['A', 'B'].map(text => <Txt ref={labels}>{text}</Txt>));+ * view.add(<Txt ref={labels}>C</Txt>);+ *+ * // accessing the references individually:+ * yield* labels[0].text('A changes', 0.3);+ * yield* labels[1].text('B changes', 0.3);+ * yield* labels[2].text('C changes', 0.3);+ *+ * // accessing all references at once:+ * yield* all(...labels.map(label => label.fill('white', 0.3)));+ * ```+ */+export function createRefArray<T>(): ReferenceArray<T> {+ const target = function () {+ // do nothing+ } as ProxyTarget<T>;+ target.array = [];+ return new Proxy(target, Handler) as unknown as ReferenceArray<T>;+}++const Handler: ProxyHandler<ProxyTarget<any>> = {+ apply(target, _, argArray) {+ if (argArray.length === 0) {+ return target.array[0];+ }++ target.array.push(...argArray);+ },++ get(target, property, receiver) {+ const value = Reflect.get(target.array, property, receiver);+ if (typeof value === 'function') {+ return value.bind(target.array);+ }++ return value;+ },++ set(target, property, value, receiver) {+ return Reflect.set(target.array, property, value, receiver);+ },+};diff --git a/packages/core/src/utils/createRefMap.ts b/packages/core/src/utils/createRefMap.tsnew file mode 100644index 00000000..db4849fe--- /dev/null+++ b/packages/core/src/utils/createRefMap.ts@@ -0,0 +1,97 @@+import {createRef, Reference} from './createRef';++export type ReferenceMap<T> = Map<string, Reference<T>> &+ Record<string, Reference<T>> & {+ /**+ * Maps the references in this group to a new array.+ *+ * @param callback - The function to transform each reference.+ *+ * @returns An array of the transformed references.+ */+ mapRefs<TValue>(callback: (value: T, index: number) => TValue): TValue[];+ };++/**+ * Create a group of references.+ *+ * @remarks+ * The returned object lets you easily create multiple references to the same+ * type without initializing them individually.+ *+ * You can retrieve references by accessing the object's properties. If the+ * reference for a given property does not exist, it will be created+ * automatically.+ *+ * @example+ * ```tsx+ * const labels = createRefMap<Txt>();+ *+ * view.add(+ * <>+ * <Txt ref={labels.a}>A</Txt>+ * <Txt ref={labels.b}>B</Txt>+ * <Txt ref={labels.c}>C</Txt>+ * </>,+ * );+ *+ * // accessing the references individually:+ * yield* labels.a().text('A changes', 0.3);+ * yield* labels.b().text('B changes', 0.3);+ * yield* labels.c().text('C changes', 0.3);+ *+ * // checking if the given reference exists:+ * if ('d' in labels) {+ * yield* labels.d().text('D changes', 0.3);+ * }+ *+ * // accessing all references at once:+ * yield* all(...labels.mapRefs(label => label.fill('white', 0.3)));+ * ```+ */+export function createRefMap<T>(): ReferenceMap<T> {+ const group = new Map<string, Reference<T>>();+ group.entries();+ return new Proxy(group, Handler) as ReferenceMap<T>;+}++const Handler: ProxyHandler<Map<string, Reference<any>>> = {+ get(target, property) {+ if (Reflect.has(target, property)) {+ return Reflect.get(target, property);+ }++ if (property === 'mapRefs') {+ return function <TValue>(+ callback: (value: any, index: number) => TValue,+ ): TValue[] {+ const result: TValue[] = [];+ for (const value of target.values()) {+ result.push(callback(value(), result.length));+ }+ return result;+ };+ }++ if (typeof property === 'string') {+ let value = target.get(property);+ if (!value) {+ value = createRef();+ target.set(property, value);+ }+ return value;+ }+ },++ has(target, property) {+ if (Reflect.has(target, property)) {+ return true;+ }++ if (typeof property === 'string') {+ return target.has(property);+ }++ return false;+ },+};diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.tsindex b7ff27f7..1c43a863 100644--- a/packages/core/src/utils/index.ts+++ b/packages/core/src/utils/index.ts@@ -17,6 +17,8 @@ export * from './Semaphore';export * from './usePlayback';export * from './useRandom';export * from './createRef';+export * from './createRefArray';+export * from './createRefMap';export * from './useScene';export * from './useThread';export * from './useTime';diff --git a/packages/docs/docs/getting-started/references.mdx b/packages/docs/docs/getting-started/references.mdxindex e6fab10c..61af391f 100644--- a/packages/docs/docs/getting-started/references.mdx+++ b/packages/docs/docs/getting-started/references.mdx@@ -175,6 +175,34 @@ In JavaScript, arrays are objects whose properties are their indices. Socircle. As a result, we end up with an array of size `10` filled with circlesthat we can use to animate all of them.+You can also use the [`createRefArray()`](/api/core/utils#createRefArray) helper+function to achieve the same result:++```tsx+import {createRefArray, range} from '@motion-canvas/core';++// ...++const circles = createRefArray<Circle>();+view.add(+ <Layout>+ {range(10).map(() => (+ <Circle ref={circles} />+ ))}+ </Layout>,+);+```++This time we don't specify the index. Whenever we pass the `circles` array to+the `ref` property, the newly created circle will be appended to our array.++:::tip++Check out [the looping section in the flow guide](/docs/flow#looping) to see how+an array of references can be used to orchestrate animations.++:::+### Custom functions`makeRef()` can also be used to return more than one reference from a custom@@ -210,6 +238,58 @@ rectangle with some text inside. When using the component, we use the `refs`property to pass the `label` object created by us. `makeRef()` is then used tofill this object with all the necessary references.+## `createRefMap()` function++As the scene grows in complexity, declaring a reference for each node can become+tedious. The [`createRefMap()`](/api/core/utils#createRefMap) helper function+lets us group references together based on the type of the node:++```tsx+import {createRefMap} from '@motion-canvas/core';++// ...++const labels = createRefMap<Txt>();+view.add(+ <>+ <Txt ref={labels.a}>A</Txt>+ <Txt ref={labels.b}>B</Txt>+ <Txt ref={labels.c}>C</Txt>+ </>,+);+```++The returned object is a map that can store however many references we need. In+the above example, we assign three `Txt` references under the keys `a`, `b`, and+`c`. Simply accessing a property of the map, like `labels.a` will create a+reference for us. The names of the properties are arbitrary and can be anything+we want.++Later on, we can retrieve the references using the same keys:++```tsx+yield * labels.a().text('A changes', 0.3);+yield * labels.b().text('B changes', 0.3);+yield * labels.c().text('C changes', 0.3);+```++To check if a reference exists, we can use the `in` operator. This will avoid+creating a reference:++```tsx+if ('d' in labels) {+ yield * labels.d().text('D changes', 0.3);+}+```++The returned object comes with a `mapRefs` method that lets us map over all+references in the map. It's similar to the [Array.prototype.map][array map]+function:++```ts+yield * all(...labels.mapRefs(label => label.fill('white', 0.3)));+```+## `makeRefs()` functionLooking at the previous example, you may notice that we had to define the `refs`@@ -265,3 +345,6 @@ function Label({const label = makeRefs<typeof Label>();view.add(<Label refs={label}>HELLO</Label>);```++[array map]:+ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map