Skip to content

Visualize Your Ideas With Code

feat: simplify size access (#65)

Jacob3315e64641e9
diff --git a/packages/2d/src/components/Circle.ts b/packages/2d/src/components/Circle.ts
index df5b8958..d0824ae1 100644
--- a/packages/2d/src/components/Circle.ts
+++ b/packages/2d/src/components/Circle.ts
@@ -16,8 +16,7 @@ export class Circle extends Node<CircleProps> {
context.save();
this.transformContext(context);
- const width = this.width();
- const height = this.height();
+ const {width, height} = this.computedLayout();
context.save();
context.fillStyle = this.fill();
diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.ts
index 8914dbde..c7ad2e2c 100644
--- a/packages/2d/src/components/Node.ts
+++ b/packages/2d/src/components/Node.ts
@@ -13,8 +13,14 @@ import {
Signal,
SignalValue,
} from '@motion-canvas/core/lib/utils';
-import {map, vector2dLerp, sizeLerp} from '@motion-canvas/core/lib/tweening';
-import {Layout, LayoutProps} from '../layout';
+import {
+ vector2dLerp,
+ sizeLerp,
+ InterpolationFunction,
+ TimingFunction,
+ tween,
+} from '@motion-canvas/core/lib/tweening';
+import {Layout, LayoutProps, Length, ResolvedLayoutMode} from '../layout';
import {ComponentChild, ComponentChildren} from './types';
import {threadable} from '@motion-canvas/core/lib/decorators';
import {ThreadGenerator} from '@motion-canvas/core/lib/threading';
@@ -25,8 +31,8 @@ export interface NodeProps {
x?: number;
y?: number;
position?: Vector2;
- width?: number;
- height?: number;
+ width?: Length;
+ height?: Length;
size?: Size;
rotation?: number;
offsetX?: number;
@@ -45,101 +51,166 @@ export class Node<TProps extends NodeProps = NodeProps> {
@property(0)
public declare readonly x: Signal<number, this>;
- protected readonly customX = createSignal(0, map, this);
-
- protected getX(): number {
- const mode = this.realMode();
- const parent = this.parent();
- if (mode === 'enabled' && parent) {
- const parentLayout = parent.computedLayout();
- const thisLayout = this.computedLayout();
-
- const offsetX = (thisLayout.width / 2) * this.offsetX();
-
- return (
- thisLayout.x -
- parentLayout.x -
- (parentLayout.width - thisLayout.width) / 2 +
- offsetX
- );
- } else {
- return this.customX();
- }
+ public saveX() {
+ this.x(this.computedX());
}
- protected setX(value: SignalValue<number>) {
- this.customX(value);
+ @computed()
+ protected computedX(): number {
+ return this.computedLayout().x;
}
@property(0)
public declare readonly y: Signal<number, this>;
- protected readonly customY = createSignal(0, map, this);
- protected getY(): number {
- const mode = this.realMode();
- const parent = this.parent();
+ public saveY() {
+ this.y(this.computedY());
+ }
- if (mode === 'enabled' && parent) {
- const parentLayout = parent.computedLayout();
- const thisLayout = this.computedLayout();
+ @computed()
+ protected computedY(): number {
+ return this.computedLayout().y;
+ }
- const offsetX = (thisLayout.width / 2) * this.offsetX();
+ @property(null)
+ public declare readonly width: Signal<Length, this>;
- return (
- thisLayout.y -
- parentLayout.y -
- (parentLayout.height - thisLayout.height) / 2 +
- offsetX
- );
+ @threadable()
+ protected *tweenWidth(
+ value: SignalValue<Length>,
+ time: number,
+ timingFunction: TimingFunction,
+ interpolationFunction: InterpolationFunction<Length>,
+ ): ThreadGenerator {
+ const width = this.width();
+ let from: number;
+ if (typeof width === 'number') {
+ from = width;
+ } else {
+ from = this.computedWidth();
+ }
+
+ let to: number;
+ if (typeof value === 'number') {
+ to = value;
} else {
- return this.customY();
+ this.width(value);
+ to = this.computedWidth();
}
+
+ this.width(from);
+ this.layout.lockSize();
+ yield* tween(time, value =>
+ this.width(interpolationFunction(from, to, timingFunction(value))),
+ );
+ this.width(value);
+ this.layout.releaseSize();
}
- protected setY(value: SignalValue<number>) {
- this.customY(value);
+ public saveWidth() {
+ this.width(this.computedWidth());
}
- @property(0)
- public declare readonly width: Signal<number, this>;
- protected readonly customWidth = createSignal(0, map, this);
+ protected computedWidth(): number {
+ return this.computedLayout().width;
+ }
- protected getWidth(): number {
- const mode = this.realMode();
+ @property(null)
+ public declare readonly height: Signal<Length, this>;
- if (mode === 'disabled') {
- return this.customWidth();
+ @threadable()
+ protected *tweenHeight(
+ value: SignalValue<Length>,
+ time: number,
+ timingFunction: TimingFunction,
+ interpolationFunction: InterpolationFunction<Length>,
+ ): ThreadGenerator {
+ const height = this.height();
+ let from: number;
+ if (typeof height === 'number') {
+ from = height;
} else {
- return this.computedLayout().width;
+ from = this.computedHeight();
}
+
+ let to: number;
+ if (typeof value === 'number') {
+ to = value;
+ } else {
+ this.height(value);
+ to = this.computedHeight();
+ }
+
+ this.height(from);
+ this.layout.lockSize();
+ yield* tween(time, value =>
+ this.height(interpolationFunction(from, to, timingFunction(value))),
+ );
+ this.height(value);
+ this.layout.releaseSize();
}
- protected setWidth(value: SignalValue<number>) {
- this.customWidth(value);
+ public saveHeight() {
+ this.width(this.computedHeight());
}
- @property(0)
- public declare readonly height: Signal<number, this>;
- protected readonly customHeight = createSignal(0, map, this);
+ protected computedHeight(): number {
+ return this.computedLayout().height;
+ }
- protected getHeight(): number {
- const mode = this.realMode();
+ @compound(['width', 'height'])
+ @property(undefined, sizeLerp)
+ public declare readonly size: Signal<{width: Length; height: Length}, this>;
+
+ @threadable()
+ protected *tweenSize(
+ value: SignalValue<Size>,
+ time: number,
+ timingFunction: TimingFunction,
+ interpolationFunction: InterpolationFunction<Size>,
+ ): ThreadGenerator {
+ const size = this.size();
+ let from: Size;
+ if (typeof size.height !== 'number' || typeof size.width !== 'number') {
+ from = this.computedSize();
+ } else {
+ from = <Size>size;
+ }
- if (mode === 'disabled') {
- return this.customHeight();
+ let to: Size;
+ if (
+ typeof value === 'object' &&
+ typeof value.height === 'number' &&
+ typeof value.width === 'number'
+ ) {
+ to = value;
} else {
- return this.computedLayout().height;
+ this.size(value);
+ to = this.computedSize();
}
+
+ this.size(from);
+ this.layout.lockSize();
+ yield* tween(time, value =>
+ this.size(interpolationFunction(from, to, timingFunction(value))),
+ );
+ this.layout.releaseSize();
+ this.size(value);
}
- protected setHeight(value: SignalValue<number>) {
- this.customHeight(value);
+ public saveSize() {
+ this.size(this.computedSize());
}
- @compound(['width', 'height'])
- @property(undefined, sizeLerp)
- public declare readonly size: Signal<Size, this>;
+ @computed()
+ protected computedSize(): Size {
+ const layout = this.computedLayout();
+ return {
+ height: layout.height,
+ width: layout.width,
+ };
+ }
@property(0)
public declare readonly rotation: Signal<number, this>;
@@ -209,6 +280,32 @@ export class Node<TProps extends NodeProps = NodeProps> {
this.append(children);
}
+ /**
+ * Get the resolved layout mode of this node.
+ *
+ * @remarks
+ * When the mode is `null`, its value will be inherited from the parent.
+ *
+ * Use {@link Layout.mode} to get the raw mode set for this node (without
+ * inheritance).
+ */
+ @computed()
+ public mode(): ResolvedLayoutMode {
+ const parent = this.parent();
+ const parentMode = parent?.mode();
+ let mode = this.layout.mode();
+
+ if (mode === null) {
+ if (!parentMode || parentMode === 'disabled') {
+ mode = 'disabled';
+ } else {
+ mode = 'enabled';
+ }
+ }
+
+ return mode;
+ }
+
@computed()
protected localToWorld(): DOMMatrix {
const parent = this.parent();
@@ -226,27 +323,50 @@ export class Node<TProps extends NodeProps = NodeProps> {
@computed()
protected localToParent(): DOMMatrix {
const matrix = new DOMMatrix();
- matrix.translateSelf(this.x(), this.y());
+ const layout = this.computedLayout();
+ matrix.translateSelf(layout.x, layout.y);
matrix.rotateSelf(0, 0, this.rotation());
matrix.scaleSelf(this.scaleX(), this.scaleY());
matrix.translateSelf(
- (this.width() / -2) * this.offsetX(),
- (this.height() / -2) * this.offsetY(),
+ (layout.width / -2) * this.offsetX(),
+ (layout.height / -2) * this.offsetY(),
);
return matrix;
}
+ /**
+ * Get the position and size of this node relative to its parent.
+ */
@computed()
protected computedLayout(): Rect {
this.requestLayoutUpdate();
const rect = this.layout.getComputedLayout();
- return {
- x: rect.x,
- y: rect.y,
+ const mode = this.mode();
+ if (mode !== 'enabled') {
+ return {
+ x: this.x(),
+ y: this.y(),
+ width: rect.width,
+ height: rect.height,
+ };
+ }
+
+ const layout = {
+ x: rect.x + (rect.width / 2) * this.offsetX(),
+ y: rect.y + (rect.height / 2) * this.offsetY(),
width: rect.width,
height: rect.height,
};
+
+ const parent = this.parent();
+ if (parent) {
+ const parentRect = parent.layout.getComputedLayout();
+ layout.x -= parentRect.x + (parentRect.width - rect.width) / 2;
+ layout.y -= parentRect.y + (parentRect.height - rect.height) / 2;
+ }
+
+ return layout;
}
/**
@@ -269,7 +389,7 @@ export class Node<TProps extends NodeProps = NodeProps> {
@computed()
protected updateLayout() {
this.applyLayoutChanges();
- this.layout.apply();
+ this.layout.setWidth(this.width()).setHeight(this.height()).apply();
for (const child of this.children()) {
child.updateLayout();
}
@@ -316,25 +436,8 @@ export class Node<TProps extends NodeProps = NodeProps> {
public removeChildren() {
for (const node of this.children()) {
- node.moveTo(null);
- }
- }
-
- @computed()
- public realMode() {
- const parent = this.parent();
- const parentMode = parent?.realMode();
- let mode = this.layout.mode();
-
- if (mode === null) {
- if (!parentMode || parentMode === 'disabled') {
- mode = 'disabled';
- } else {
- mode = 'enabled';
- }
+ node.remove();
}
-
- return mode;
}
public render(context: CanvasRenderingContext2D) {
@@ -359,26 +462,6 @@ export class Node<TProps extends NodeProps = NodeProps> {
matrix.f,
);
}
-
- @threadable()
- public *tweenSize(update: (node: this) => void): ThreadGenerator {
- const mode = this.realMode();
- const initialSize = this.size();
-
- if (mode === 'disabled') {
- update(this);
- const toSize = this.size();
- this.size(initialSize);
- yield* this.size(toSize, 2);
- } else {
- this.layout.width(null).height(null);
- update(this);
- const toSize = this.size();
- this.layout.size(initialSize);
- yield* this.layout.size(toSize, 2);
- this.layout.width(null).height(null);
- }
- }
}
/*@__PURE__*/
diff --git a/packages/2d/src/components/Rect.ts b/packages/2d/src/components/Rect.ts
index e1f88e79..77453dcc 100644
--- a/packages/2d/src/components/Rect.ts
+++ b/packages/2d/src/components/Rect.ts
@@ -16,8 +16,7 @@ export class Rect extends Node<RectProps> {
context.save();
this.transformContext(context);
- const width = this.width();
- const height = this.height();
+ const {width, height} = this.computedLayout();
context.save();
context.fillStyle = this.fill();
diff --git a/packages/2d/src/decorators/property.ts b/packages/2d/src/decorators/property.ts
index 9daedd0d..9d980308 100644
--- a/packages/2d/src/decorators/property.ts
+++ b/packages/2d/src/decorators/property.ts
@@ -129,7 +129,7 @@ export function createProperty<
* The class using this decorator can implement the following methods:
* - `get[PropertyName]` - A property getter.
* - `get[PropertyName]` - A property setter.
- * - `tween[PropertyName]` - a tween provider.
+ * - `tween[PropertyName]` - A tween provider.
*
* See the {@link PropertyOwner} type for more detailed method signatures.
*
diff --git a/packages/2d/src/layout/Layout.ts b/packages/2d/src/layout/Layout.ts
index 2fdbc39d..099d2c5b 100644
--- a/packages/2d/src/layout/Layout.ts
+++ b/packages/2d/src/layout/Layout.ts
@@ -1,8 +1,13 @@
-import {compound, computed, initialize, property} from '../decorators';
-import {Signal} from '@motion-canvas/core/lib/utils';
-import {Rect, Size} from '@motion-canvas/core/lib/types';
-import {AlignItems, FlexDirection, JustifyContent, LayoutMode} from './types';
-import {sizeLerp} from '@motion-canvas/core/lib/tweening';
+import {computed, initialize, property} from '../decorators';
+import {createSignal, Signal} from '@motion-canvas/core/lib/utils';
+import {Rect} from '@motion-canvas/core/lib/types';
+import {
+ AlignItems,
+ FlexDirection,
+ JustifyContent,
+ LayoutMode,
+ Length,
+} from './types';
export interface LayoutProps {
mode?: LayoutMode;
@@ -25,13 +30,6 @@ export interface LayoutProps {
export class Layout {
@property(null)
public declare readonly mode: Signal<LayoutMode, this>;
- @property(null)
- public declare readonly width: Signal<null | number | `${number}%`, this>;
- @property(null)
- public declare readonly height: Signal<null | number | `${number}%`, this>;
- @property(undefined, sizeLerp)
- @compound(['width', 'height'])
- public declare readonly size: Signal<Size, this>;
@property(0)
public declare readonly marginTop: Signal<number, this>;
@@ -61,6 +59,7 @@ export class Layout {
public declare readonly alignItems: Signal<AlignItems, this>;
public readonly element: HTMLDivElement;
+ private sizeLockCounter = createSignal(0);
public constructor(props: LayoutProps) {
this.element = document.createElement('div');
@@ -74,6 +73,14 @@ export class Layout {
return `${value}px`;
}
+ public lockSize() {
+ this.sizeLockCounter(this.sizeLockCounter() + 1);
+ }
+
+ public releaseSize() {
+ this.sizeLockCounter(this.sizeLockCounter() - 1);
+ }
+
public getComputedLayout(): Rect {
const rect = this.element.getBoundingClientRect();
return {
@@ -84,13 +91,7 @@ export class Layout {
};
}
- @computed()
- public apply() {
- const mode = this.mode();
- this.element.style.position =
- mode === 'disabled' || mode === 'root' ? 'absolute' : '';
-
- const width = this.width();
+ public setWidth(width: Length): this {
if (width === null) {
this.element.style.width = 'auto';
} else if (typeof width === 'string') {
@@ -99,7 +100,10 @@ export class Layout {
this.element.style.width = this.toPixels(width);
}
- const height = this.height();
+ return this;
+ }
+
+ public setHeight(height: Length): this {
if (height === null) {
this.element.style.height = 'auto';
} else if (typeof height === 'string') {
@@ -108,6 +112,15 @@ export class Layout {
this.element.style.height = this.toPixels(height);
}
+ return this;
+ }
+
+ @computed()
+ public apply() {
+ const mode = this.mode();
+ this.element.style.position =
+ mode === 'disabled' || mode === 'root' ? 'absolute' : 'relative';
+
this.element.style.marginTop = this.toPixels(this.marginTop());
this.element.style.marginBottom = this.toPixels(this.marginBottom());
this.element.style.marginLeft = this.toPixels(this.marginLeft());
@@ -120,5 +133,8 @@ export class Layout {
this.element.style.aspectRatio = this.ratio();
this.element.style.justifyContent = this.justifyContent();
this.element.style.alignItems = this.alignItems();
+
+ this.element.style.flexGrow = this.sizeLockCounter() > 0 ? '0' : '';
+ this.element.style.flexShrink = this.sizeLockCounter() > 0 ? '0' : '';
}
}
diff --git a/packages/2d/src/layout/types.ts b/packages/2d/src/layout/types.ts
index 19b6416e..d24a5643 100644
--- a/packages/2d/src/layout/types.ts
+++ b/packages/2d/src/layout/types.ts
@@ -18,4 +18,7 @@ export type AlignItems =
| 'space-between'
| 'space-around';
-export type LayoutMode = 'disabled' | 'enabled' | 'root' | 'pop' | null;
+export type ResolvedLayoutMode = 'disabled' | 'enabled' | 'root' | 'pop';
+export type LayoutMode = ResolvedLayoutMode | null;
+
+export type Length = number | `${number}%` | null;
diff --git a/packages/2d/src/scenes/TwoDView.ts b/packages/2d/src/scenes/TwoDView.ts
index e58ed0f3..ea736c28 100644
--- a/packages/2d/src/scenes/TwoDView.ts
+++ b/packages/2d/src/scenes/TwoDView.ts
@@ -1,10 +1,11 @@
import {Node} from '../components';
-export class TwoDView extends Node<any> {
+export class TwoDView extends Node {
private static frameID = 'motion-canvas-2d-frame';
public constructor() {
- super({layout: {width: 1920, height: 1080}, mode: 'none'});
+ // TODO Sync with the project size
+ super({width: 1920, height: 1080});
let frame = document.querySelector<HTMLIFrameElement>(
`#${TwoDView.frameID}`,
@@ -28,10 +29,7 @@ export class TwoDView extends Node<any> {
}
public override render(context: CanvasRenderingContext2D) {
- this.x();
- this.y();
- this.width();
- this.height();
+ this.computedLayout();
super.render(context);
}
}