Visualize Your Ideas With Code
feat(2d): add default computed values for signals (#259)
DJ18f61a668420
diff --git a/packages/2d/src/components/Image.ts b/packages/2d/src/components/Image.tsindex 38f73ee6..2998583b 100644--- a/packages/2d/src/components/Image.ts+++ b/packages/2d/src/components/Image.ts@@ -120,9 +120,9 @@ export class Image extends Rect {protected override applyFlex() {super.applyFlex();const image = this.image();- this.element.style.aspectRatio = this.parseValue(- this.ratio() ?? image.naturalWidth / image.naturalHeight,- );+ this.element.style.aspectRatio = (+ this.ratio() ?? image.naturalWidth / image.naturalHeight+ ).toString();}/**diff --git a/packages/2d/src/components/Layout.ts b/packages/2d/src/components/Layout.tsindex cabf5038..332aa1ae 100644--- a/packages/2d/src/components/Layout.ts+++ b/packages/2d/src/components/Layout.ts@@ -1,6 +1,7 @@import {cloneable,computed,+ defaultStyle,initial,inspectable,signal,@@ -31,6 +32,7 @@ import {FlexWrap,LayoutMode,Length,+ LetterSpacing,TextWrap,} from '../partials';import {threadable} from '@motion-canvas/core/lib/decorators';@@ -154,25 +156,33 @@ export class Layout extends Node {@signal()public declare readonly columnGap: SimpleSignal<Length, this>;- @initial(null)+ @defaultStyle('font-family')@signal()- public declare readonly fontFamily: SimpleSignal<string | null, this>;- @initial(null)+ public declare readonly fontFamily: SimpleSignal<string, this>;+ @defaultStyle('font-size', parseFloat)@signal()- public declare readonly fontSize: SimpleSignal<number | null, this>;- @initial(null)+ public declare readonly fontSize: SimpleSignal<number, this>;+ @defaultStyle('font-style')@signal()- public declare readonly fontStyle: SimpleSignal<string | null, this>;- @initial(null)+ public declare readonly fontStyle: SimpleSignal<string, this>;+ @defaultStyle('font-weight', parseInt)@signal()- public declare readonly fontWeight: SimpleSignal<number | null, this>;- @initial(null)+ public declare readonly fontWeight: SimpleSignal<number, this>;+ @initial('120%')@signal()- public declare readonly lineHeight: SimpleSignal<number | null, this>;- @initial(null)+ public declare readonly lineHeight: SimpleSignal<Length, this>;+ @defaultStyle('letter-spacing', i => {+ if (i === 'normal') {+ return 'normal';+ }+ return parseFloat(i);+ })@signal()- public declare readonly letterSpacing: SimpleSignal<number | null, this>;- @initial(null)+ public declare readonly letterSpacing: SimpleSignal<LetterSpacing, this>;++ @defaultStyle('white-space', i => {+ return i === 'pre' ? 'pre' : i === 'normal';+ })@signal()public declare readonly textWrap: SimpleSignal<TextWrap, this>;@@ -674,15 +684,11 @@ export class Layout extends Node {this.position(this.position().add(newOffset).sub(oldOffset));}- protected parseValue(value: number | string | null): string {- return value === null ? '' : value.toString();- }-protected parsePixels(value: number | null): string {return value === null ? '' : `${value}px`;}- protected parseLength(value: null | number | string): string {+ protected parseLength(value: number | string | null): string {if (value === null) {return '';}@@ -702,8 +708,9 @@ export class Layout extends Node {this.element.style.maxWidth = this.parseLength(this.maxWidth());this.element.style.minWidth = this.parseLength(this.minWidth());this.element.style.maxHeight = this.parseLength(this.maxHeight());- this.element.style.minWidth = this.parseLength(this.minWidth());- this.element.style.aspectRatio = this.parseValue(this.ratio());+ this.element.style.minHeight = this.parseLength(this.minHeight()!);+ this.element.style.aspectRatio =+ this.ratio() === null ? '' : this.ratio()!.toString();this.element.style.marginTop = this.parsePixels(this.margin.top());this.element.style.marginBottom = this.parsePixels(this.margin.bottom());@@ -716,7 +723,7 @@ export class Layout extends Node {this.element.style.paddingRight = this.parsePixels(this.padding.right());this.element.style.flexDirection = this.direction();- this.element.style.flexBasis = this.parseLength(this.basis());+ this.element.style.flexBasis = this.parseLength(this.basis()!);this.element.style.flexWrap = this.wrap();this.element.style.justifyContent = this.justifyContent();@@ -729,29 +736,45 @@ export class Layout extends Node {this.element.style.flexGrow = '0';this.element.style.flexShrink = '0';} else {- this.element.style.flexGrow = this.parseValue(this.grow());- this.element.style.flexShrink = this.parseValue(this.shrink());+ this.element.style.flexGrow = this.grow().toString();+ this.element.style.flexShrink = this.shrink().toString();}}@computed()protected applyFont() {- this.element.style.fontFamily = this.parseValue(this.fontFamily());- this.element.style.fontSize = this.parsePixels(this.fontSize());- this.element.style.fontStyle = this.parseValue(this.fontStyle());- this.element.style.lineHeight = this.parsePixels(this.lineHeight());- this.element.style.fontWeight = this.parseValue(this.fontWeight());- this.element.style.letterSpacing = this.parsePixels(this.letterSpacing());-- const wrap = this.textWrap();- this.element.style.whiteSpace =- wrap === null- ? ''- : typeof wrap === 'boolean'- ? wrap- ? 'normal'- : 'nowrap'- : wrap;+ this.element.style.fontFamily = this.fontFamily.isInitial()+ ? ''+ : this.fontFamily();+ this.element.style.fontSize = this.fontSize.isInitial()+ ? ''+ : `${this.fontSize()}px`;+ this.element.style.fontStyle = this.fontStyle.isInitial()+ ? ''+ : this.fontStyle();+ this.element.style.lineHeight =+ typeof this.lineHeight() === 'string'+ ? (parseFloat(this.lineHeight() as string) / 100).toString()+ : `${this.lineHeight()}px`;+ this.element.style.fontWeight = this.fontWeight.isInitial()+ ? ''+ : this.fontWeight().toString();+ this.element.style.letterSpacing = this.letterSpacing.isInitial()+ ? ''+ : this.letterSpacing() === 'normal'+ ? 'normal'+ : `${this.letterSpacing()}px`;++ if (this.textWrap.isInitial()) {+ this.element.style.whiteSpace = '';+ } else {+ const wrap = this.textWrap();+ if (typeof wrap === 'boolean') {+ this.element.style.whiteSpace = wrap ? 'normal' : 'nowrap';+ } else {+ this.element.style.whiteSpace = wrap;+ }+ }}public override hit(position: Vector2): Node | null {diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.tsindex fa450108..0560ce61 100644--- a/packages/2d/src/components/Node.ts+++ b/packages/2d/src/components/Node.ts@@ -388,8 +388,18 @@ export class Node implements Promisable<Node> {this.view2D = scene.getView();this.creationStack = new Error().stack;initialize(this, {defaults: rest});- for (const {signal} of this) {+ for (const {key, signal, meta} of this) {signal.reset();+ if ((<any>rest)[key] !== undefined) {+ signal((<any>rest)[key]);+ }+ if (meta.compoundEntries !== undefined) {+ for (const [key, property] of meta.compoundEntries) {+ if (property in rest) {+ (<any>signal)[key]((<any>rest)[property]);+ }+ }+ }}this.add(children);if (spawner) {diff --git a/packages/2d/src/components/Video.ts b/packages/2d/src/components/Video.tsindex 6fe4b822..41311029 100644--- a/packages/2d/src/components/Video.ts+++ b/packages/2d/src/components/Video.ts@@ -182,9 +182,9 @@ export class Video extends Rect {protected override applyFlex() {super.applyFlex();const video = this.video();- this.element.style.aspectRatio = this.parseValue(- this.ratio() ?? video.videoWidth / video.videoHeight,- );+ this.element.style.aspectRatio = (+ this.ratio() ?? video.videoWidth / video.videoHeight+ ).toString();}protected setCurrentTime(value: number) {diff --git a/packages/2d/src/decorators/compound.ts b/packages/2d/src/decorators/compound.tsindex e23d470b..71f5539e 100644--- a/packages/2d/src/decorators/compound.ts+++ b/packages/2d/src/decorators/compound.ts@@ -35,7 +35,7 @@ export function compound(entries: Record<string, string>): PropertyDecorator {meta.compound = true;meta.compoundEntries = Object.entries(entries);- addInitializer(target, (instance: any, context: any) => {+ addInitializer(target, (instance: any) => {if (!meta.parser) {useLogger().error(`Missing parser decorator for "${key.toString()}"`);return;@@ -44,7 +44,7 @@ export function compound(entries: Record<string, string>): PropertyDecorator {const signalContext = new CompoundSignalContext(Object.keys(entries),meta.parser,- context.defaults[key] ?? meta.default,+ meta.default,meta.interpolationFunction ?? deepLerp,instance,);@@ -53,9 +53,6 @@ export function compound(entries: Record<string, string>): PropertyDecorator {for (const [key, property] of meta.compoundEntries) {patchSignal(signal[key].context, undefined, instance, property);- if (property in context.defaults) {- signal[key].context.setInitial(context.defaults[property]);- }}instance[key] = signal;diff --git a/packages/2d/src/decorators/defaultStyle.ts b/packages/2d/src/decorators/defaultStyle.tsnew file mode 100644index 00000000..39a1aa0e--- /dev/null+++ b/packages/2d/src/decorators/defaultStyle.ts@@ -0,0 +1,18 @@+import {capitalize} from '@motion-canvas/core/lib/utils';+import {Layout} from 'components';++export function defaultStyle<T>(+ styleName: string,+ parse: (value: string) => T = value => value as T,+): PropertyDecorator {+ return (target: any, key) => {+ target[`getDefault${capitalize(<string>key)}`] = function (this: Layout) {+ this.requestLayoutUpdate();+ const old = (<any>this.element.style)[styleName];+ (<any>this.element.style)[styleName] = '';+ const ret = parse.call(this, this.styles.getPropertyValue(styleName));+ (<any>this.element.style)[styleName] = old;+ return ret;+ };+ };+}diff --git a/packages/2d/src/decorators/index.ts b/packages/2d/src/decorators/index.tsindex 488f57ec..5ca87c32 100644--- a/packages/2d/src/decorators/index.ts+++ b/packages/2d/src/decorators/index.ts@@ -1,4 +1,5 @@export * from './canvasStyleSignal';+export * from './defaultStyle';export * from './colorSignal';export * from './compound';export * from './computed';diff --git a/packages/2d/src/decorators/signal.ts b/packages/2d/src/decorators/signal.tsindex 23467948..ce8e3757 100644--- a/packages/2d/src/decorators/signal.ts+++ b/packages/2d/src/decorators/signal.ts@@ -3,7 +3,7 @@ import {InterpolationFunction,} from '@motion-canvas/core/lib/tweening';import {addInitializer} from './initializers';-import {useLogger} from '@motion-canvas/core/lib/utils';+import {capitalize, useLogger} from '@motion-canvas/core/lib/utils';import {patchSignal} from '../utils/patchSignal';import {SignalContext} from '@motion-canvas/core/lib/signals';@@ -87,9 +87,11 @@ export function getPropertiesOf(export function signal<T>(): PropertyDecorator {return (target: any, key) => {const meta = getPropertyMetaOrCreate<T>(target, key);- addInitializer(target, (instance: any, context: any) => {+ addInitializer(target, (instance: any) => {+ const getDefault =+ instance[`getDefault${capitalize(key as string)}`]?.bind(instance);const signal = new SignalContext<T, T, any>(- context.defaults[key] ?? meta.default,+ getDefault ?? meta.default,meta.interpolationFunction ?? deepLerp,instance,);diff --git a/packages/2d/src/partials/types.ts b/packages/2d/src/partials/types.tsindex 009e6668..b3daa756 100644--- a/packages/2d/src/partials/types.ts+++ b/packages/2d/src/partials/types.ts@@ -32,7 +32,9 @@ export type FlexAlign =| 'stretch'| 'baseline';-export type TextWrap = boolean | 'pre' | null;+export type LetterSpacing = number | 'normal';++export type TextWrap = boolean | 'pre';export type LayoutMode = boolean | null;diff --git a/packages/core/src/signals/SignalContext.ts b/packages/core/src/signals/SignalContext.tsindex c5ce10b1..350f347a 100644--- a/packages/core/src/signals/SignalContext.ts+++ b/packages/core/src/signals/SignalContext.ts@@ -16,6 +16,7 @@ import {SignalValue,} from './types';import {isReactive} from './isReactive';+import {DEFAULT} from './symbols';export type SimpleSignal<TValue, TReturn = void> = Signal<TValue,@@ -41,6 +42,11 @@ export interface Signal<*/save(): TOwner;+ /**+ * {@inheritDoc SignalContext.isInitial}+ */+ isInitial(): boolean;+context: TContext;}@@ -66,6 +72,9 @@ export class SignalContext<Object.defineProperty(this.invokable, 'save', {value: this.save.bind(this),});+ Object.defineProperty(this.invokable, 'isInitial', {+ value: this.isInitial.bind(this),+ });if (this.initial !== undefined) {this.current = this.initial;@@ -101,7 +110,11 @@ export class SignalContext<this.markDirty();}- public set(value: SignalValue<TSetterValue>): TOwner {+ public set(value: SignalValue<TSetterValue> | typeof DEFAULT): TOwner {+ if (value === DEFAULT) {+ value = this.initial!;+ }+if (this.current === value) {return this.owner;}@@ -143,7 +156,7 @@ export class SignalContext<}protected override invoke(- value?: SignalValue<TSetterValue>,+ value?: SignalValue<TSetterValue> | typeof DEFAULT,duration?: number,timingFunction: TimingFunction = easeInOutCubic,interpolationFunction: InterpolationFunction<TValue> = this.interpolation,@@ -168,7 +181,7 @@ export class SignalContext<before?: ThreadGenerator,) {const animate = (- value: SignalValue<TSetterValue>,+ value: SignalValue<TSetterValue> | typeof DEFAULT,duration: number,timingFunction = defaultTimingFunction,interpolationFunction = defaultInterpolationFunction,@@ -194,11 +207,15 @@ export class SignalContext<}protected *tween(- value: SignalValue<TSetterValue>,+ value: SignalValue<TSetterValue> | typeof DEFAULT,duration: number,timingFunction: TimingFunction,interpolationFunction: InterpolationFunction<TValue>,): ThreadGenerator {+ if (value === DEFAULT) {+ value = this.initial!;+ }+yield* this.doTween(this.parse(isReactive(value) ? value() : value),duration,@@ -257,6 +274,27 @@ export class SignalContext<return this.set(this.get());}+ /**+ * Check if the signal is currently using its initial value.+ *+ * @example+ * ```ts+ *+ * const signal = createSignal(0);+ * signal.isInitial(); // true+ *+ * signal(5);+ * signal.isInitial(); // false+ *+ * signal(DEFAULT);+ * signal.isInitial(); // true+ * ```+ */+ public isInitial() {+ this.collect();+ return this.current === this.initial;+ }+/*** Get the raw value of this signal.*diff --git a/packages/core/src/signals/index.ts b/packages/core/src/signals/index.tsindex 073ed48d..ead236ae 100644--- a/packages/core/src/signals/index.ts+++ b/packages/core/src/signals/index.ts@@ -13,3 +13,4 @@ export * from './isReactive';export * from './SignalContext';export * from './DependencyContext';export * from './types';+export * from './symbols';diff --git a/packages/core/src/signals/symbols.ts b/packages/core/src/signals/symbols.tsnew file mode 100644index 00000000..df91b4d4--- /dev/null+++ b/packages/core/src/signals/symbols.ts@@ -0,0 +1 @@+export const DEFAULT = Symbol.for('@motion-canvas/core/signals/default');diff --git a/packages/core/src/signals/types.ts b/packages/core/src/signals/types.tsindex b77a0264..5535d350 100644--- a/packages/core/src/signals/types.ts+++ b/packages/core/src/signals/types.ts@@ -1,5 +1,6 @@import type {InterpolationFunction, TimingFunction} from '../tweening';import type {ThreadGenerator} from '../threading';+import {DEFAULT} from './symbols';export type SignalValue<TValue> = TValue | (() => TValue);export type SignalGenerator<@@ -10,7 +11,7 @@ export type SignalGenerator<};export interface SignalSetter<TValue, TOwner = void> {- (value: SignalValue<TValue>): TOwner;+ (value: SignalValue<TValue> | typeof DEFAULT): TOwner;}export interface SignalGetter<TValue> {@@ -19,7 +20,7 @@ export interface SignalGetter<TValue> {export interface SignalTween<TSetterValue, TValue extends TSetterValue> {(- value: SignalValue<TSetterValue>,+ value: SignalValue<TSetterValue> | typeof DEFAULT,time: number,timingFunction?: TimingFunction,interpolationFunction?: InterpolationFunction<TValue>,