Visualize Your Ideas With Code
feat: add base class for shapes (#67)
Jacobd38c1724e129
diff --git a/packages/2d/src/components/Circle.ts b/packages/2d/src/components/Circle.tsindex d0824ae1..4a9676f1 100644--- a/packages/2d/src/components/Circle.ts+++ b/packages/2d/src/components/Circle.ts@@ -1,35 +1,10 @@-import {Node, NodeProps} from './Node';-import {Signal} from '@motion-canvas/core/lib/utils';-import {property} from '../decorators';-import {NodeChildren} from './types';--export interface CircleProps extends NodeProps {- children?: NodeChildren;- fill?: string;-}--export class Circle extends Node<CircleProps> {- @property('#ffffff')- public declare readonly fill: Signal<string, this>;-- public override render(context: CanvasRenderingContext2D) {- context.save();- this.transformContext(context);+import {Shape} from './Shape';+export class Circle extends Shape {+ protected getPath(): Path2D {+ const path = new Path2D();const {width, height} = this.computedLayout();-- context.save();- context.fillStyle = this.fill();- context.beginPath();- context.ellipse(0, 0, width / 2, height / 2, 0, 0, Math.PI * 2);- context.closePath();- context.fill();- context.restore();-- for (const child of this.children()) {- child.render(context);- }-- context.restore();+ path.ellipse(0, 0, width / 2, height / 2, 0, 0, Math.PI * 2);+ return path;}}diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.tsindex b28a7505..38e7bb13 100644--- a/packages/2d/src/components/Node.ts+++ b/packages/2d/src/components/Node.ts@@ -27,7 +27,7 @@ import {tween,map,} from '@motion-canvas/core/lib/tweening';-import {Layout, LayoutProps, Length, ResolvedLayoutMode} from '../layout';+import {Layout, LayoutProps, Length, ResolvedLayoutMode} from '../partials';import {ComponentChild, ComponentChildren} from './types';import {threadable} from '@motion-canvas/core/lib/decorators';import {ThreadGenerator} from '@motion-canvas/core/lib/threading';diff --git a/packages/2d/src/components/Rect.ts b/packages/2d/src/components/Rect.tsindex 77453dcc..bb380830 100644--- a/packages/2d/src/components/Rect.ts+++ b/packages/2d/src/components/Rect.ts@@ -1,32 +1,10 @@-import {Node, NodeProps} from './Node';-import {Signal} from '@motion-canvas/core/lib/utils';-import {property} from '../decorators';-import {NodeChildren} from './types';--export interface RectProps extends NodeProps {- children?: NodeChildren;- fill: string;-}--export class Rect extends Node<RectProps> {- @property('#ffffff')- public declare readonly fill: Signal<string, this>;-- public override render(context: CanvasRenderingContext2D) {- context.save();- this.transformContext(context);+import {Shape} from './Shape';+export class Rect extends Shape {+ protected getPath(): Path2D {+ const path = new Path2D();const {width, height} = this.computedLayout();-- context.save();- context.fillStyle = this.fill();- context.fillRect(-width / 2, -height / 2, width, height);- context.restore();-- for (const child of this.children()) {- child.render(context);- }-- context.restore();+ path.rect(-width / 2, -height / 2, width, height);+ return path;}}diff --git a/packages/2d/src/components/Shape.ts b/packages/2d/src/components/Shape.tsnew file mode 100644index 00000000..50defad6--- /dev/null+++ b/packages/2d/src/components/Shape.ts@@ -0,0 +1,107 @@+import {Node, NodeProps} from './Node';+import {Gradient, Pattern} from '../partials';+import {compound, property} from '../decorators';+import {Signal} from '@motion-canvas/core/lib/utils';+import {Vector2} from '@motion-canvas/core/lib/types';+import {vector2dLerp} from '@motion-canvas/core/lib/tweening';++export type CanvasStyle = null | string | Gradient | Pattern;++export interface ShapeProps extends NodeProps {+ fill?: CanvasStyle;+ stroke?: CanvasStyle;+ lineWidth?: number;+ lineJoin?: CanvasLineJoin;+ lineCap?: CanvasLineCap;+ lineDash?: number[];+ lineDashOffset?: number;+ shadowColor?: string;+ shadowBlur?: number;+ shadowOffsetX?: number;+ shadowOffsetY?: number;+ shadowOffset?: Vector2;+}++export abstract class Shape<T extends ShapeProps = ShapeProps> extends Node<T> {+ @property(null)+ public declare readonly fill: Signal<CanvasStyle, this>;+ @property(null)+ public declare readonly stroke: Signal<CanvasStyle, this>;+ @property(0)+ public declare readonly lineWidth: Signal<number, this>;+ @property('miter')+ public declare readonly lineJoin: Signal<CanvasLineJoin, this>;+ @property('butt')+ public declare readonly lineCap: Signal<CanvasLineCap, this>;+ @property([])+ public declare readonly lineDash: Signal<number[], this>;+ @property(0)+ public declare readonly lineDashOffset: Signal<number, this>;+ @property('')+ public declare readonly shadowColor: Signal<string, this>;+ @property(0)+ public declare readonly shadowBlur: Signal<number, this>;+ @property(0)+ public declare readonly shadowOffsetX: Signal<number, this>;+ @property(0)+ public declare readonly shadowOffsetY: Signal<number, this>;+ @compound({x: 'shadowOffsetX', y: 'shadowOffsetY'})+ @property(undefined, vector2dLerp)+ public declare readonly shadowOffset: Signal<Vector2, this>;++ protected parseCanvasStyle(+ style: CanvasStyle,+ context: CanvasRenderingContext2D,+ ): string | CanvasGradient | CanvasPattern {+ if (style === null) {+ return '';+ }+ if (typeof style === 'string') {+ return style;+ }+ if (style instanceof Gradient) {+ return style.canvasGradient(context);+ }+ return style.canvasPattern(context) ?? '';+ }++ protected applyFill(context: CanvasRenderingContext2D) {+ context.fillStyle = this.parseCanvasStyle(this.fill(), context);+ context.shadowColor = this.shadowColor();+ context.shadowBlur = this.shadowBlur();+ context.shadowOffsetX = this.shadowOffsetX();+ context.shadowOffsetY = this.shadowOffsetY();+ }++ protected applyStroke(context: CanvasRenderingContext2D) {+ context.strokeStyle = this.parseCanvasStyle(this.stroke(), context);+ context.lineWidth = this.lineWidth();+ context.lineJoin = this.lineJoin();+ context.lineCap = this.lineCap();+ context.setLineDash(this.lineDash());+ context.lineDashOffset = this.lineDashOffset();+ }++ public override render(context: CanvasRenderingContext2D) {+ context.save();+ this.transformContext(context);++ const path = this.getPath();+ context.save();+ this.applyFill(context);+ context.fill(path);+ context.restore();+ context.save();+ this.applyStroke(context);+ context.stroke(path);+ context.restore();++ for (const child of this.children()) {+ child.render(context);+ }++ context.restore();+ }++ protected abstract getPath(): Path2D;+}diff --git a/packages/2d/src/layout/index.ts b/packages/2d/src/layout/index.tsdeleted file mode 100644index ee3cd08a..00000000--- a/packages/2d/src/layout/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export * from './Layout';-export * from './types';diff --git a/packages/2d/src/partials/Gradient.ts b/packages/2d/src/partials/Gradient.tsnew file mode 100644index 00000000..94a4fce6--- /dev/null+++ b/packages/2d/src/partials/Gradient.ts@@ -0,0 +1,97 @@+import {compound, computed, initialize, property} from '../decorators';+import {Vector2} from '@motion-canvas/core/lib/types';+import {Signal} from '@motion-canvas/core/lib/utils';+import {vector2dLerp} from '@motion-canvas/core/lib/tweening';++export type GradientType = 'linear' | 'conic' | 'radial';++export interface GradientStop {+ offset: number;+ color: string;+}++export interface GradientProps {+ type?: GradientType;+ fromX?: number;+ fromY?: number;+ from?: Vector2;+ toX?: number;+ toY?: number;+ to?: Vector2;+ angle?: number;+ fromRadius?: number;+ toRadius?: number;+ stops?: GradientStop[];+}++export class Gradient {+ @property('linear')+ public declare readonly type: Signal<GradientType, this>;++ @property(0)+ public declare readonly fromX: Signal<number, this>;+ @property(0)+ public declare readonly fromY: Signal<number, this>;+ @compound({x: 'fromX', y: 'fromY'})+ @property(undefined, vector2dLerp)+ public declare readonly from: Signal<Vector2, this>;++ @property(0)+ public declare readonly toX: Signal<number, this>;+ @property(0)+ public declare readonly toY: Signal<number, this>;+ @compound({x: 'toX', y: 'toY'})+ @property(undefined, vector2dLerp)+ public declare readonly to: Signal<Vector2, this>;++ @property(0)+ public declare readonly angle: Signal<number, this>;+ @property(0)+ public declare readonly fromRadius: Signal<number, this>;+ @property(0)+ public declare readonly toRadius: Signal<number, this>;+ @property([])+ public declare readonly stops: Signal<GradientStop[], this>;++ public constructor(props: GradientProps) {+ initialize(this, {defaults: props});+ }++ @computed()+ public canvasGradient(context: CanvasRenderingContext2D): CanvasGradient {+ let gradient: CanvasGradient;+ switch (this.type()) {+ case 'linear':+ gradient = context.createLinearGradient(+ this.fromX(),+ this.fromY(),+ this.toX(),+ this.toY(),+ );+ break;+ case 'conic':+ gradient = context.createConicGradient(+ this.angle(),+ this.fromX(),+ this.fromY(),+ );+ break;+ case 'radial':+ gradient = context.createRadialGradient(+ this.fromX(),+ this.fromY(),+ this.fromRadius(),+ this.toX(),+ this.toY(),+ this.toRadius(),+ );+ break;+ }++ for (const {offset, color} of this.stops()) {+ gradient.addColorStop(offset, color);+ }++ return gradient;+ }+}diff --git a/packages/2d/src/layout/Layout.ts b/packages/2d/src/partials/Layout.tssimilarity index 100%rename from packages/2d/src/layout/Layout.tsrename to packages/2d/src/partials/Layout.tsdiff --git a/packages/2d/src/partials/Pattern.ts b/packages/2d/src/partials/Pattern.tsnew file mode 100644index 00000000..50a1f50f--- /dev/null+++ b/packages/2d/src/partials/Pattern.ts@@ -0,0 +1,33 @@+import {computed, initialize, property} from '../decorators';+import {Signal} from '@motion-canvas/core/lib/utils';++export type CanvasRepetition =+ | null+ | 'repeat'+ | 'repeat-x'+ | 'repeat-y'+ | 'no-repeat';++// TODO Support custom transformation matrices+export interface PatternProps {+ image: CanvasImageSource;+ repetition?: CanvasRepetition;+}++export class Pattern {+ @property()+ public declare readonly image: Signal<CanvasImageSource, this>;+ @property(null)+ public declare readonly repetition: Signal<CanvasRepetition, this>;++ public constructor(props: PatternProps) {+ initialize(this, {defaults: props});+ }++ @computed()+ public canvasPattern(+ context: CanvasRenderingContext2D,+ ): CanvasPattern | null {+ return context.createPattern(this.image(), this.repetition());+ }+}diff --git a/packages/2d/src/partials/index.ts b/packages/2d/src/partials/index.tsnew file mode 100644index 00000000..a917521b--- /dev/null+++ b/packages/2d/src/partials/index.ts@@ -0,0 +1,4 @@+export * from './Gradient';+export * from './Layout';+export * from './Pattern';+export * from './types';diff --git a/packages/2d/src/layout/types.ts b/packages/2d/src/partials/types.tssimilarity index 100%rename from packages/2d/src/layout/types.tsrename to packages/2d/src/partials/types.tsdiff --git a/packages/core/src/utils/createComputed.ts b/packages/core/src/utils/createComputed.tsindex 47943b3c..4cafa051 100644--- a/packages/core/src/utils/createComputed.ts+++ b/packages/core/src/utils/createComputed.ts@@ -1,15 +1,10 @@import {FlagDispatcher, Subscribable} from '../events';-import {- collect,- finishCollecting,- SignalGetter,- startCollecting,-} from './createSignal';+import {collect, finishCollecting, startCollecting} from './createSignal';-export type Computed<TValue> = SignalGetter<TValue>;+export type Computed<TValue> = (...args: any[]) => TValue;export function createComputed<TValue>(- factory: SignalGetter<TValue>,+ factory: Computed<TValue>,): Computed<TValue> {let last: TValue;const dependencies = new Set<Subscribable<void>>();@@ -19,12 +14,12 @@ export function createComputed<TValue>(event.raise();}- const handler = <Computed<TValue>>function handler() {+ const handler = <Computed<TValue>>function handler(...args: any[]) {if (event.isRaised()) {dependencies.forEach(dep => dep.unsubscribe(markDirty));dependencies.clear();startCollecting([dependencies, markDirty]);- last = factory();+ last = factory(...args);finishCollecting([dependencies, markDirty]);}event.reset();