Skip to content

Visualize Your Ideas With Code

docs: add component documentation (#295)

Nick1ceb441cbda7
diff --git a/packages/docs/docs/advanced/custom-components.mdx b/packages/docs/docs/advanced/custom-components.mdx
new file mode 100644
index 00000000..705c1216
--- /dev/null
+++ b/packages/docs/docs/advanced/custom-components.mdx
@@ -0,0 +1,153 @@
+---
+slug: /custom-components
+---
+
+import AnimationPlayer from '@site/src/components/AnimationPlayer';
+import CodeBlock from '@theme/CodeBlock';
+import source from '!!raw-loader!@motion-canvas/examples/src/scenes/components-switch';
+
+# Components
+
+<AnimationPlayer name="components" banner />
+
+Components are classes like [Rect](/api/2d/components/Rect) and
+[Circle](/api/2d/component/Rect) that can abstract rendering and data
+functionality into reusable, modular pieces. To use a component in a scene, add
+it to the view and provide arguments to the component.
+
+```tsx
+<Switch initialState={false} />
+```
+
+To define what arguments a component will take, first define an interface. All
+properties of the interface must be wrapped in
+[SignalValue<>](/api/core/signals#SignalValue) as such:
+
+```tsx
+// You can extend an existing props interface
+// such as LayoutProps, ShapeProps or NodeProps to
+// include their properties alongside the ones you
+// define
+
+export interface SwitchProps extends NodeProps {
+ initialState?: SignalValue<boolean>;
+
+ // We dont use color here because we want
+ // to be able to pass hex strings and rgb
+ // values to accent rather than a `Color`
+ accent?: SignalValue<PossibleColor>;
+}
+```
+
+Next, create a class for your components. The component class must extend
+[Node](/api/2d/components/Node) or one of its subclasses. If you dont want to
+inherit any methods from an existing component, extend your class from `Node`.
+We advise extending from the component most similar to the component you are
+building. For instance, if you were to make a component including a
+[Layout](/api/2d/components/Layout), you should extend
+[Layout](/api/2d/components/Layout) and
+[LayoutProps](/api/2d/components/LayoutProps).
+
+```tsx
+export interface SwitchProps extends NodeProps { ... }
+
+export class Switch extends Node { ... }
+```
+
+To use the properties defined in the interface, your class _must_ contain a
+property with the same name. Motion Canvas provides type decorators to
+facilitate this like `@initial()` and `@signal()`. Click [here](/docs/signals)
+for more information on signals.
+
+Here is an example of how you would define such properties:
+
+```tsx
+export class Switch extends Node {
+ // @initial - optional, sets the property to an
+ // initial value if it was not provided.
+ // The @initial decorator is optional.
+ @initial(false)
+ // @signal - is required by motion canvas
+ // for every prop that was passed in.
+ @signal()
+ public declare readonly initialState: SimpleSignal<boolean, this>
+
+ @initial("#68ABDF")
+ @signal()
+ public declare readonly accent: ColorSignal<this>
+
+ ...
+
+}
+```
+
+Notice how colors are wrapped in `ColorSignal<>` while any other type (even
+user-defined ones) are wrapped in `SimpleSignal<>`. The type does not need to be
+passed to color signal as Motion Canvas knows that it must be of a
+color-resolvable type. In both, the class is passed at the end of the wrapper to
+register the signal to the class. Properties must be initialised with the
+`public`, `declare` and `readonly` keywords.
+
+Normal properties can be defined as normal. For example:
+
+```tsx
+public constructor(props?: SwitchProps) {
+ super({
+ // If you wanted to ensure that layout was always
+ // true for this component, you could add it here
+ // as such:
+
+ //layout: true
+ ...props
+ })
+ ...
+}
+```
+
+The `props` parameter can also be useful outside of the `super()` call to access
+your data elsewhere. For example, if you were building a component to display an
+array, you could use props to set the color of every
+[Rect](/api/2d/components/Rect) in the array.
+
+Now we can add elements to the view by using `this.add()`, much like you would
+add to a scene's view:
+
+```tsx
+public constructor(props?: SwitchProps) {
+
+ ...
+
+ this.add(
+ <Rect
+ ...
+ >
+ <Circle
+ ...
+ />
+ </Rect>
+ )
+}
+```
+
+Since this is a class, you can also add methods. This is especially useful when
+wanting to animate a component easily. Here is an example of a method for
+toggling our switch:
+
+```tsx
+public* toggle(Duration: number) {
+ yield* all(
+ tween(Duration, value => {
+ ...
+ }),
+
+ tween(Duration, value => {
+ ...
+ })
+ )
+ this.isOn = !this.isOn
+}
+```
+
+Here is the source code for the component we have built throughout this guide:
+
+<CodeBlock language="tsx">{source}</CodeBlock>
diff --git a/packages/examples/src/components.meta b/packages/examples/src/components.meta
new file mode 100644
index 00000000..0e33e3fe
--- /dev/null
+++ b/packages/examples/src/components.meta
@@ -0,0 +1,3 @@
+{
+ "version": 0
+}
\ No newline at end of file
diff --git a/packages/examples/src/components.ts b/packages/examples/src/components.ts
new file mode 100644
index 00000000..8d47a987
--- /dev/null
+++ b/packages/examples/src/components.ts
@@ -0,0 +1,9 @@
+import {makeProject} from '@motion-canvas/core';
+
+import scene from './scenes/components?scene';
+import {Vector2} from '@motion-canvas/core/lib/types';
+
+export default makeProject({
+ scenes: [scene],
+ size: new Vector2(960, 540),
+});
diff --git a/packages/examples/src/scenes/components-switch.tsx b/packages/examples/src/scenes/components-switch.tsx
new file mode 100644
index 00000000..d585e9f6
--- /dev/null
+++ b/packages/examples/src/scenes/components-switch.tsx
@@ -0,0 +1,83 @@
+import {Circle, Node, NodeProps, Rect} from '@motion-canvas/2d/lib/components';
+import {easeInOutCubic, tween} from '@motion-canvas/core/lib/tweening';
+import {
+ Color,
+ ColorSignal,
+ PossibleColor,
+} from '@motion-canvas/core/lib/types/Color';
+import {initial, signal} from '@motion-canvas/2d/lib/decorators';
+import {
+ createSignal,
+ SignalValue,
+ SimpleSignal,
+} from '@motion-canvas/core/lib/signals';
+import {createRef} from '@motion-canvas/core/lib/utils';
+import {all} from '@motion-canvas/core/lib/flow';
+
+export interface SwitchProps extends NodeProps {
+ initialState?: SignalValue<boolean>;
+ accent?: SignalValue<PossibleColor>;
+}
+
+export class Switch extends Node {
+ @initial(false)
+ @signal()
+ public declare readonly initialState: SimpleSignal<boolean, this>;
+
+ @initial('#68ABDF')
+ @signal()
+ public declare readonly accent: ColorSignal<this>;
+
+ private isOn: boolean;
+ private readonly indicatorPosition = createSignal(0);
+ private readonly offColor = new Color('#242424');
+ private readonly indicator = createRef<Circle>();
+ private readonly container = createRef<Rect>();
+
+ public constructor(props?: SwitchProps) {
+ super({
+ ...props,
+ });
+
+ this.indicatorPosition(this.initialState ? 50 : -50);
+ this.isOn = this.initialState();
+
+ this.add(
+ <Rect
+ ref={this.container}
+ fill={this.offColor}
+ size={[200, 100]}
+ radius={100}
+ >
+ <Circle
+ x={() => this.indicatorPosition()}
+ ref={this.indicator}
+ size={[80, 80]}
+ fill="#ffffff"
+ />
+ </Rect>,
+ );
+ }
+
+ public *toggle(Duration: number) {
+ yield* all(
+ tween(Duration, value => {
+ const oldColor = this.isOn ? this.accent() : this.offColor;
+ const newColor = this.isOn ? this.offColor : this.accent();
+
+ this.container().fill(
+ Color.lerp(oldColor, newColor, easeInOutCubic(value)),
+ );
+ }),
+
+ tween(Duration, value => {
+ const currentPos = this.indicator().position();
+
+ this.indicatorPosition(
+ easeInOutCubic(value, currentPos.x, this.isOn ? -50 : 50),
+ );
+ }),
+ );
+ this.isOn = !this.isOn;
+ }
+}
diff --git a/packages/examples/src/scenes/components.meta b/packages/examples/src/scenes/components.meta
new file mode 100644
index 00000000..0e33e3fe
--- /dev/null
+++ b/packages/examples/src/scenes/components.meta
@@ -0,0 +1,3 @@
+{
+ "version": 0
+}
\ No newline at end of file
diff --git a/packages/examples/src/scenes/components.tsx b/packages/examples/src/scenes/components.tsx
new file mode 100644
index 00000000..b621702d
--- /dev/null
+++ b/packages/examples/src/scenes/components.tsx
@@ -0,0 +1,17 @@
+import {makeScene2D} from '@motion-canvas/2d/lib/scenes';
+import {chain, loop, waitFor} from '@motion-canvas/core/lib/flow';
+import {createRef} from '@motion-canvas/core/lib/utils';
+import {Switch} from '@motion-canvas/examples/src/scenes/components-switch';
+// see this import for the component ^
+
+// usage of the component:
+export default makeScene2D(function* (view) {
+ const switchRef = createRef<Switch>();
+
+ view.add(<Switch ref={switchRef} initialState={true} />);
+
+ yield* switchRef().toggle(0.2);
+ yield* waitFor(1);
+ yield* switchRef().toggle(0.2);
+ yield* waitFor(1);
+});
diff --git a/packages/examples/vite.config.ts b/packages/examples/vite.config.ts
index 3ae6aa9c..21cdde4b 100644
--- a/packages/examples/vite.config.ts
+++ b/packages/examples/vite.config.ts
@@ -19,6 +19,7 @@ export default defineConfig({
'./src/positioning.ts',
'./src/media-image.ts',
'./src/media-video.ts',
+ './src/components.ts',
],
}),
],