Skip to content

Visualize Your Ideas With Code

feat(2d): add cardinal points (#636)

Jacob2136a2558a9e
diff --git a/packages/2d/src/components/Layout.ts b/packages/2d/src/components/Layout.ts
index 3c55c015..9c19766b 100644
--- a/packages/2d/src/components/Layout.ts
+++ b/packages/2d/src/components/Layout.ts
@@ -1,7 +1,9 @@
import {
+ addInitializer,
cloneable,
computed,
defaultStyle,
+ getPropertyMeta,
initial,
inspectable,
signal,
@@ -18,6 +20,7 @@ import {
SpacingSignal,
Vector2,
Vector2Signal,
+ SimpleVector2Signal,
} from '@motion-canvas/core/lib/types';
import {
InterpolationFunction,
@@ -42,7 +45,7 @@ import {Node, NodeProps} from './Node';
import {drawLine, drawPivot} from '../utils';
import {spacingSignal} from '../decorators/spacingSignal';
import {
- createSignal,
+ isReactive,
Signal,
SignalValue,
SimpleSignal,
@@ -100,6 +103,78 @@ export interface LayoutProps extends NodeProps {
offsetX?: SignalValue<number>;
offsetY?: SignalValue<number>;
offset?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the top edge of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the top edge
+ * ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ top?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the bottom edge of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the bottom edge
+ * ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ bottom?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the left edge of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the left edge
+ * ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ left?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the right edge of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the right edge
+ * ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ right?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the top left corner of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the top left
+ * corner ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ topLeft?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the top right corner of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the top right
+ * corner ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ topRight?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the bottom left corner of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the bottom left
+ * corner ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ bottomLeft?: SignalValue<PossibleVector2>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * This shortcut property will set the node's position so that the bottom
+ * right corner ends up in the given place.
+ * If present, overrides the {@link NodeProps.position} property.
+ */
+ bottomRight?: SignalValue<PossibleVector2>;
clip?: SignalValue<boolean>;
}
@@ -446,23 +521,116 @@ export class Layout extends Node {
@vector2Signal('offset')
public declare readonly offset: Vector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the top edge ends up in the given place.
+ *
+ * When retrieved, it will return the position of the top edge in the parent
+ * space.
+ */
+ @originSignal(Origin.Top)
+ public declare readonly top: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the bottom edge ends up in the given place.
+ *
+ * When retrieved, it will return the position of the bottom edge in the
+ * parent space.
+ */
+ @originSignal(Origin.Bottom)
+ public declare readonly bottom: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the left edge ends up in the given place.
+ *
+ * When retrieved, it will return the position of the left edge in the parent
+ * space.
+ */
+ @originSignal(Origin.Left)
+ public declare readonly left: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the right edge ends up in the given place.
+ *
+ * When retrieved, it will return the position of the right edge in the parent
+ * space.
+ */
+ @originSignal(Origin.Right)
+ public declare readonly right: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the top left corner ends up in the given place.
+ *
+ * When retrieved, it will return the position of the top left corner in the
+ * parent space.
+ */
+ @originSignal(Origin.TopLeft)
+ public declare readonly topLeft: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the top right corner ends up in the given place.
+ *
+ * When retrieved, it will return the position of the top right corner in the
+ * parent space.
+ */
+ @originSignal(Origin.TopRight)
+ public declare readonly topRight: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the bottom left corner ends up in the given place.
+ *
+ * When retrieved, it will return the position of the bottom left corner in
+ * the parent space.
+ */
+ @originSignal(Origin.BottomLeft)
+ public declare readonly bottomLeft: SimpleVector2Signal<this>;
+ /**
+ * The position of the bottom right corner of this node.
+ *
+ * @remarks
+ * When set, this shortcut property will modify the node's position so that
+ * the bottom right corner ends up in the given place.
+ *
+ * When retrieved, it will return the position of the bottom right corner in
+ * the parent space.
+ */
+ @originSignal(Origin.BottomRight)
+ public declare readonly bottomRight: SimpleVector2Signal<this>;
+
@initial(false)
@signal()
public declare readonly clip: SimpleSignal<boolean, this>;
- public element: HTMLElement;
- public styles: CSSStyleDeclaration;
+ public declare element: HTMLElement;
+ public declare styles: CSSStyleDeclaration;
- protected readonly sizeLockCounter = createSignal(0);
+ @initial(0)
+ @signal()
+ protected declare readonly sizeLockCounter: SimpleSignal<number, this>;
- public constructor({tagName = 'div', ...props}: LayoutProps) {
+ public constructor(props: LayoutProps) {
super(props);
-
- this.element = document.createElement(tagName);
- this.element.style.display = 'flex';
- this.element.style.boxSizing = 'border-box';
-
- this.styles = getComputedStyle(this.element);
}
public lockSize() {
@@ -515,11 +683,16 @@ export class Layout extends Node {
public override localToParent(): DOMMatrix {
const matrix = new DOMMatrix();
- const offset = this.size().mul(this.offset()).scale(-0.5);
+
matrix.translateSelf(this.position.x(), this.position.y());
matrix.rotateSelf(0, 0, this.rotation());
matrix.scaleSelf(this.scale.x(), this.scale.y());
- matrix.translateSelf(offset.x, offset.y);
+
+ const offset = this.offset();
+ if (!offset.exactlyEquals(Vector2.zero)) {
+ const translate = this.size().mul(offset).scale(-0.5);
+ matrix.translateSelf(translate.x, translate.y);
+ }
return matrix;
}
@@ -826,3 +999,37 @@ export class Layout extends Node {
return null;
}
}
+
+function originSignal(origin: Origin): PropertyDecorator {
+ return (target, key) => {
+ signal()(target, key);
+ cloneable(false)(target, key);
+ const meta = getPropertyMeta<any>(target, key);
+ meta!.getter = function (this: Layout) {
+ return this.getOriginDelta(origin).transformAsPoint(this.localToParent());
+ };
+ meta!.setter = function (
+ this: Layout,
+ value: SignalValue<PossibleVector2>,
+ ) {
+ this.position(
+ isReactive(value)
+ ? () =>
+ this.getOriginDelta(origin)
+ .transform(this.localToParent())
+ .flipped.add(value())
+ : this.getOriginDelta(origin)
+ .transform(this.localToParent())
+ .flipped.add(value),
+ );
+ return this;
+ };
+ };
+}
+
+addInitializer<Layout>(Layout.prototype, instance => {
+ instance.element = document.createElement('div');
+ instance.element.style.display = 'flex';
+ instance.element.style.boxSizing = 'border-box';
+ instance.styles = getComputedStyle(instance.element);
+});
diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.ts
index fc0537ca..34d9d036 100644
--- a/packages/2d/src/components/Node.ts
+++ b/packages/2d/src/components/Node.ts
@@ -139,11 +139,13 @@ export class Node implements Promisable<Node> {
return new Vector2(matrix.m41, matrix.m42);
}
- protected setAbsolutePosition(value: SignalValue<Vector2>) {
+ protected setAbsolutePosition(value: SignalValue<PossibleVector2>) {
if (isReactive(value)) {
- this.position(() => value().transformAsPoint(this.worldToParent()));
+ this.position(() =>
+ new Vector2(value()).transformAsPoint(this.worldToParent()),
+ );
} else {
- this.position(value.transformAsPoint(this.worldToParent()));
+ this.position(new Vector2(value).transformAsPoint(this.worldToParent()));
}
}
@@ -243,11 +245,11 @@ export class Node implements Promisable<Node> {
);
}
- protected setAbsoluteScale(value: SignalValue<Vector2>) {
+ protected setAbsoluteScale(value: SignalValue<PossibleVector2>) {
if (isReactive(value)) {
- this.scale(() => this.getRelativeScale(value()));
+ this.scale(() => this.getRelativeScale(new Vector2(value())));
} else {
- this.scale(this.getRelativeScale(value));
+ this.scale(this.getRelativeScale(new Vector2(value)));
}
}
diff --git a/packages/2d/src/decorators/compound.ts b/packages/2d/src/decorators/compound.ts
index 71f5539e..907430e0 100644
--- a/packages/2d/src/decorators/compound.ts
+++ b/packages/2d/src/decorators/compound.ts
@@ -48,7 +48,7 @@ export function compound(entries: Record<string, string>): PropertyDecorator {
meta.interpolationFunction ?? deepLerp,
instance,
);
- patchSignal(signalContext, meta.parser, instance, <string>key);
+ patchSignal(signalContext, meta, instance, <string>key);
const signal = signalContext.toSignal();
for (const [key, property] of meta.compoundEntries) {
diff --git a/packages/2d/src/decorators/signal.test.ts b/packages/2d/src/decorators/signal.test.ts
new file mode 100644
index 00000000..d264946b
--- /dev/null
+++ b/packages/2d/src/decorators/signal.test.ts
@@ -0,0 +1,89 @@
+import {beforeEach, describe, expect, test, vi} from 'vitest';
+import {initial, initializeSignals, parser, signal} from './signal';
+import {DEFAULT, SimpleSignal} from '@motion-canvas/core/lib/signals';
+
+interface OwnerProps {
+ integer?: number;
+ custom?: number;
+}
+
+class Owner {
+ @initial(2.2)
+ @parser((value: number) => Math.round(value))
+ @signal()
+ public declare readonly integer: SimpleSignal<number>;
+
+ @initial(0)
+ @signal()
+ public declare readonly custom: SimpleSignal<number>;
+ public getCustom() {
+ return 4;
+ }
+ public setCustom() {
+ // do nothing
+ }
+
+ public constructor(props: OwnerProps = {}) {
+ initializeSignals(this, props);
+ }
+}
+
+const GetterMock = vi.spyOn(Owner.prototype, 'getCustom');
+const SetterMock = vi.spyOn(Owner.prototype, 'setCustom');
+
+describe('signal', () => {
+ beforeEach(() => {
+ GetterMock.mockClear();
+ SetterMock.mockClear();
+ });
+
+ test('Has initial value', () => {
+ const instance = new Owner();
+
+ expect(instance.integer()).toBe(2);
+ expect(instance.integer.isInitial()).toBe(true);
+ });
+
+ test('Overrides the value', () => {
+ const instance = new Owner({integer: 4});
+
+ expect(instance.integer()).toBe(4);
+ expect(instance.integer.isInitial()).toBe(false);
+ });
+
+ test('Resets the value to default', () => {
+ const instance = new Owner({integer: 4});
+ instance.integer(DEFAULT);
+
+ expect(instance.integer()).toBe(2);
+ expect(instance.integer.isInitial()).toBe(true);
+ });
+
+ test('Parses the value', () => {
+ const instance = new Owner();
+ instance.integer(2.7);
+
+ expect(instance.integer()).toBe(3);
+ });
+
+ test('Uses the custom getter', () => {
+ const instance = new Owner();
+ const value = instance.custom();
+
+ expect(value).toBe(4);
+ expect(GetterMock).toBeCalledTimes(1);
+ });
+
+ test('Calls the setter with the initial value', () => {
+ new Owner();
+
+ expect(SetterMock).toBeCalledWith(0);
+ });
+
+ test('Uses the setter', () => {
+ const instance = new Owner({custom: 1});
+ instance.custom(2);
+
+ expect(SetterMock).toBeCalledTimes(3);
+ });
+});
diff --git a/packages/2d/src/decorators/signal.ts b/packages/2d/src/decorators/signal.ts
index 4e7090bd..dafbe5e9 100644
--- a/packages/2d/src/decorators/signal.ts
+++ b/packages/2d/src/decorators/signal.ts
@@ -1,6 +1,7 @@
import {
deepLerp,
InterpolationFunction,
+ TimingFunction,
} from '@motion-canvas/core/lib/tweening';
import {addInitializer, initialize} from './initializers';
import {capitalize, useLogger} from '@motion-canvas/core/lib/utils';
@@ -11,6 +12,14 @@ export interface PropertyMetadata<T> {
default?: T;
interpolationFunction?: InterpolationFunction<T>;
parser?: (value: any) => T;
+ getter?: () => T;
+ setter?: (value: any) => void;
+ tweener?: (
+ value: T,
+ duration: number,
+ timingFunction: TimingFunction,
+ interpolationFunction: InterpolationFunction<T>,
+ ) => void;
cloneable?: boolean;
inspectable?: boolean;
compoundParent?: string;
@@ -113,7 +122,7 @@ export function signal<T>(): PropertyDecorator {
meta.interpolationFunction ?? deepLerp,
instance,
);
- patchSignal(signal, meta.parser, instance, <string>key);
+ patchSignal(signal, meta, instance, <string>key);
instance[key] = signal.toSignal();
});
};
diff --git a/packages/2d/src/utils/patchSignal.ts b/packages/2d/src/utils/patchSignal.ts
index 029de666..53d0bb46 100644
--- a/packages/2d/src/utils/patchSignal.ts
+++ b/packages/2d/src/utils/patchSignal.ts
@@ -1,29 +1,30 @@
import {capitalize} from '@motion-canvas/core/lib/utils';
import {SignalContext} from '@motion-canvas/core/lib/signals';
+import {PropertyMetadata} from '../decorators';
export function patchSignal<TSetterValue, TValue extends TSetterValue>(
signal: SignalContext<TSetterValue, TValue>,
- parser?: (value: TSetterValue) => TValue,
+ meta: Partial<PropertyMetadata<TValue>> = {},
owner?: any,
name?: string,
) {
- if (parser) {
- signal.setParser(parser.bind(owner));
+ if (meta.parser) {
+ signal.setParser(meta.parser.bind(owner));
}
if (name && owner) {
- const setter = owner?.[`set${capitalize(name)}`];
+ const setter = meta.setter ?? owner?.[`set${capitalize(name)}`];
if (setter) {
signal.set = (...args: any[]) => {
setter.apply(owner, args);
return owner;
};
}
- const getter = owner?.[`get${capitalize(name)}`];
+ const getter = meta.getter ?? owner?.[`get${capitalize(name)}`];
if (getter) {
signal.get = getter.bind(owner);
}
- const tweener = owner?.[`tween${capitalize(name)}`];
+ const tweener = meta.tweener ?? owner?.[`tween${capitalize(name)}`];
if (tweener) {
signal.doTween = tweener.bind(owner);
}
diff --git a/packages/docs/docs/getting-started/layouts.mdx b/packages/docs/docs/getting-started/layouts.mdx
index 646b5c4b..822697f7 100644
--- a/packages/docs/docs/getting-started/layouts.mdx
+++ b/packages/docs/docs/getting-started/layouts.mdx
@@ -70,6 +70,58 @@ class has additional `size` and `offset` properties:
<ApiSnippet url={'/api/2d/components/Layout#offset'} />
<hr />
+## Cardinal directions
+
+Layout nodes come with a set of helper properties that let you position them in
+respect to their edges/corners. In the example below we use them to place two
+squares on the left and right side of a gray rectangle. The yellow square is
+positioned so that its right edge is in the same place as the left edge of the
+rectangle. Meanwhile, the red square is placed so that its bottom left corner
+aligns with the bottom right corner of the rectangle. All possible directions
+include: [`top`](/api/2d/components/Layout#top),
+[`bottom`](/api/2d/components/Layout#bottom),
+[`left`](/api/2d/components/Layout#left),
+[`right`](/api/2d/components/Layout#right),
+[`topLeft`](/api/2d/components/Layout#topLeft),
+[`topRight`](/api/2d/components/Layout#topRight),
+[`bottomLeft`](/api/2d/components/Layout#bottomLeft), and
+[`bottomRight`](/api/2d/components/Layout#bottomRight).
+
+```tsx editor
+import {makeScene2D} from '@motion-canvas/2d';
+import {Circle, Rect} from '@motion-canvas/2d/lib';
+import {createRef} from '@motion-canvas/core/lib/utils';
+
+export default makeScene2D(function* (view) {
+ const rect = createRef<Circle>();
+
+ view.add(
+ <>
+ <Rect
+ ref={rect}
+ width={200}
+ height={100}
+ rotation={-10}
+ fill={'#333333'}
+ />
+ <Rect
+ size={50}
+ fill={'#e6a700'}
+ rotation={-10}
+ // Try changing "right" to "top"
+ right={rect().left()}
+ />
+ <Rect
+ size={100}
+ fill={'#e13238'}
+ rotation={10}
+ bottomLeft={rect().bottomRight()}
+ />
+ </>,
+ );
+});
+```
+
## Flexbox configuration
Most flexbox attributes available in CSS are available as