Visualize Your Ideas With Code
feat(2d): nested Txt nodes (#861)
Jacobf2786d0cd0d0
diff --git a/packages/2d/src/components/Layout.ts b/packages/2d/src/components/Layout.tsindex 702a05c0..9c2daa53 100644--- a/packages/2d/src/components/Layout.ts+++ b/packages/2d/src/components/Layout.ts@@ -5,6 +5,7 @@ import {defaultStyle,getPropertyMeta,initial,+ interpolation,signal,Vector2LengthSignal,vector2Signal,@@ -25,6 +26,7 @@ import {InterpolationFunction,TimingFunction,tween,+ boolLerp,} from '@motion-canvas/core/lib/tweening';import {FlexItems,@@ -179,6 +181,7 @@ export interface LayoutProps extends NodeProps {export class Layout extends Node {@initial(null)+ @interpolation(boolLerp)@signal()public declare readonly layout: SimpleSignal<LayoutMode, this>;@@ -628,6 +631,7 @@ export class Layout extends Node {public constructor(props: LayoutProps) {super(props);+ this.element.dataset.motionCanvasKey = this.key;}public lockSize() {diff --git a/packages/2d/src/components/Node.ts b/packages/2d/src/components/Node.tsindex 4c854945..f99f0bec 100644--- a/packages/2d/src/components/Node.ts+++ b/packages/2d/src/components/Node.ts@@ -417,6 +417,10 @@ export class Node implements Promisable<Node> {@signal()public declare readonly children: Signal<ComponentChildren, Node[], this>;protected setChildren(value: SignalValue<ComponentChildren>) {+ if (this.children.context.raw() === value) {+ return;+ }+this.children.context.setter(value);if (!isReactive(value)) {this.spawnChildren(false, value);@@ -1079,12 +1083,19 @@ export class Node implements Promisable<Node> {* node to be garbage collected.*/public dispose() {+ if (!this.unregister) {+ return;+ }+this.stateStack = [];this.unregister();this.unregister = null!;for (const {signal} of this) {signal?.context.dispose();}+ for (const child of this.realChildren) {+ child.dispose();+ }}/**diff --git a/packages/2d/src/components/Txt.test.tsx b/packages/2d/src/components/Txt.test.tsxnew file mode 100644index 00000000..9aebed30--- /dev/null+++ b/packages/2d/src/components/Txt.test.tsx@@ -0,0 +1,81 @@+import {describe, it, expect, vi} from 'vitest';+import {mockScene2D} from './__tests__/mockScene2D';+import {Txt} from './Txt';+import {TxtLeaf} from './TxtLeaf';+import {generatorTest} from './__tests__/generatorTest';+import {linear, waitFor} from '@motion-canvas/core';++describe('Txt', () => {+ mockScene2D();++ it('Handle plain text', () => {+ const node = (<Txt lineWidth={8}>test</Txt>) as Txt;++ const parseSpy = vi.spyOn(node as any, 'parseChildren');+ const leaf = node.childAs<TxtLeaf>(0);++ expect(node.text()).toBe('test');+ expect(node.lineWidth()).toBe(8);+ expect(node.children().length).toBe(1);+ expect(leaf).toBeInstanceOf(TxtLeaf);+ expect(leaf!.text()).toBe('test');+ expect(leaf!.lineWidth()).toBe(8);++ node.lineWidth(16);+ node.text('changed');++ expect(node.childAs(0)).toBe(leaf);+ expect(leaf!.lineWidth()).toBe(16);+ expect(leaf!.text()).toBe('changed');++ // Parsing should not happen when operating exclusively on simple text+ expect(parseSpy).toHaveBeenCalledTimes(0);+ });++ it('Handle complex text', () => {+ const node = (+ <Txt lineWidth={8}>+ Apple <Txt>Banana</Txt> Cherry+ </Txt>+ ) as Txt;++ const first = node.childAs<TxtLeaf>(0);+ const second = node.childAs<Txt>(1);+ const third = node.childAs<TxtLeaf>(2);++ expect(node.text()).toBe('Apple Banana Cherry');+ expect(node.lineWidth()).toBe(8);+ expect(node.children().length).toBe(3);+ expect(first).toBeInstanceOf(TxtLeaf);+ expect(first!.text()).toBe('Apple ');+ expect(first!.lineWidth()).toBe(8);++ expect(second).toBeInstanceOf(Txt);+ expect(second!.text()).toBe('Banana');+ expect(second!.lineWidth()).toBe(8);++ expect(third).toBeInstanceOf(TxtLeaf);+ expect(third!.text()).toBe(' Cherry');+ expect(third!.lineWidth()).toBe(8);+ });++ it(+ 'Tween complex to simple text',+ generatorTest(function* () {+ const node = (+ <Txt>+ <Txt>Apple</Txt> Banana+ </Txt>+ ) as Txt;++ yield node.text('Simple', 2, linear);+ yield* waitFor(1);++ const leaf = node.childAs<TxtLeaf>(0)!;++ expect(node.children().length).toBe(1);+ expect(node.text()).toBe('Apple Ban');+ expect(leaf.text()).toBe('Apple Ban');+ }),+ );+});diff --git a/packages/2d/src/components/Txt.ts b/packages/2d/src/components/Txt.tsindex d57ca3a1..0a1acf02 100644--- a/packages/2d/src/components/Txt.ts+++ b/packages/2d/src/components/Txt.ts@@ -1,167 +1,194 @@-import {computed, initial, interpolation, signal} from '../decorators';-import {textLerp} from '@motion-canvas/core/lib/tweening';+import {computed, initial, signal} from '../decorators';+import {+ InterpolationFunction,+ TimingFunction,+} from '@motion-canvas/core/lib/tweening';import {Shape, ShapeProps} from './Shape';-import {BBox} from '@motion-canvas/core/lib/types';-import {SignalValue, SimpleSignal} from '@motion-canvas/core/lib/signals';-import {View2D} from './View2D';-import {lazy} from '@motion-canvas/core/lib/decorators';+import {SignalValue} from '@motion-canvas/core/lib/signals';+import {threadable} from '@motion-canvas/core/lib/decorators';+import {ThreadGenerator} from '@motion-canvas/core/lib/threading';+import {all, DEFAULT, SimpleSignal} from '@motion-canvas/core';+import {Node} from './Node';+import {ComponentChildren} from './types';+import {TxtLeaf} from './TxtLeaf';+import {is} from '../utils';+import {capitalize} from '@motion-canvas/core/lib/utils';++type TxtChildren = string | Node | (string | Node)[];+type AnyTxt = Txt | TxtLeaf;export interface TxtProps extends ShapeProps {- children?: string;+ children?: TxtChildren;text?: SignalValue<string>;}export class Txt extends Shape {- @lazy(() => {- const formatter = document.createElement('div');- View2D.shadowRoot.append(formatter);- return formatter;- })- protected static formatter: HTMLDivElement;-- @lazy(() => {- try {- return new (Intl as any).Segmenter(undefined, {- granularity: 'grapheme',- });- } catch (e) {- return null;- }- })- protected static readonly segmenter: any;+ /**+ * Create a bold text node.+ *+ * @remarks+ * This is a shortcut for+ * ```tsx+ * <Txt fontWeight={700} />+ * ```+ *+ * @param props - Additional text properties.+ */+ public static b(props: TxtProps) {+ return new Txt({...props, fontWeight: 700});+ }++ /**+ * Create an italic text node.+ *+ * @remarks+ * This is a shortcut for+ * ```tsx+ * <Txt fontStyle={'italic'} />+ * ```+ *+ * @param props - Additional text properties.+ */+ public static i(props: TxtProps) {+ return new Txt({...props, fontStyle: 'italic'});+ }@initial('')- @interpolation(textLerp)@signal()public declare readonly text: SimpleSignal<string, this>;- public constructor({children, ...rest}: TxtProps) {- super(rest);- if (children) {- this.text(children);- }+ protected getText(): string {+ return this.innerText();}- protected override draw(context: CanvasRenderingContext2D) {- this.requestFontUpdate();- this.applyStyle(context);- this.applyText(context);- context.font = this.styles.font;- if ('letterSpacing' in context) {- context.letterSpacing = `${this.letterSpacing()}px`;- }-- const parentRect = this.element.getBoundingClientRect();- const {width, height} = this.size();- const range = document.createRange();- let line = '';- const lineRect = new BBox();- for (const childNode of this.element.childNodes) {- if (!childNode.textContent) {- continue;+ protected setText(value: SignalValue<string>) {+ const children = this.children();+ let leaf: TxtLeaf | null = null;+ for (let i = 0; i < children.length; i++) {+ const child = children[i];+ if (leaf === null && child instanceof TxtLeaf) {+ leaf = child;+ } else {+ child.parent(null);}+ }- range.selectNodeContents(childNode);- const rangeRect = range.getBoundingClientRect();+ if (leaf === null) {+ leaf = new TxtLeaf({text: value});+ leaf.parent(this);+ } else {+ leaf.text(value);+ }- const x = width / -2 + rangeRect.left - parentRect.left;- const y = height / -2 + rangeRect.top - parentRect.top;+ this.setParsedChildren([leaf]);+ }- if (lineRect.y === y) {- lineRect.width += rangeRect.width;- line += childNode.textContent;- } else {- this.drawText(context, line, lineRect);- lineRect.x = x;- lineRect.y = y;- lineRect.width = rangeRect.width;- lineRect.height = rangeRect.height;- line = childNode.textContent;- }+ protected override setChildren(value: SignalValue<ComponentChildren>) {+ if (this.children.context.raw() === value) {+ return;}- this.drawText(context, line, lineRect);+ if (typeof value === 'string') {+ this.text(value);+ } else {+ super.setChildren(value);+ }}- protected drawText(- context: CanvasRenderingContext2D,- text: string,- box: BBox,- ) {- const y = box.y + box.height / 2;- context.save();- context.textBaseline = 'middle';-- if (this.lineWidth() <= 0) {- context.fillText(text, box.x, y);- } else if (this.strokeFirst()) {- context.strokeText(text, box.x, y);- context.fillText(text, box.x, y);- } else {- context.fillText(text, box.x, y);- context.strokeText(text, box.x, y);+ @threadable()+ protected *tweenText(+ value: SignalValue<string>,+ time: number,+ timingFunction: TimingFunction,+ interpolationFunction: InterpolationFunction<string>,+ ): ThreadGenerator {+ const children = this.children();+ if (children.length !== 1 || !(children[0] instanceof TxtLeaf)) {+ this.text.save();}- context.restore();- }+ const leaf = this.childAs<TxtLeaf>(0)!;+ const oldText = leaf.text.context.raw();+ const oldSize = this.size.context.raw();+ leaf.text(value);+ const newSize = this.size();+ leaf.text(oldText ?? DEFAULT);++ yield* all(+ this.size(newSize, time, timingFunction),+ leaf.text(value, time, timingFunction, interpolationFunction),+ );- protected override getCacheBBox(): BBox {- const size = this.computedSize();- const range = document.createRange();- range.selectNodeContents(this.element);- const bbox = range.getBoundingClientRect();-- const lineWidth = this.lineWidth();- // We take the default value of the miterLimit as 10.- const miterLimitCoefficient = this.lineJoin() === 'miter' ? 0.5 * 10 : 0.5;-- return new BBox(- -size.width / 2,- -size.height / 2,- bbox.width,- bbox.height,- ).expand(lineWidth * miterLimitCoefficient);+ this.children.context.setter(value);+ this.size(oldSize);}- @computed()- protected formattedText() {- Txt.formatter.innerText = this.text();- return Txt.formatter.innerText;+ protected getLayout(): boolean {+ return true;}- protected override updateLayout() {- this.applyFont();- this.applyFlex();+ public constructor({children, text, ...props}: TxtProps) {+ super(props);+ this.children(text ?? children);+ }- // Make sure the text is aligned correctly even if the text is smaller than- // the container.- if (this.justifyContent.isInitial()) {- this.element.style.justifyContent =- this.styles.getPropertyValue('text-align');+ @computed()+ protected innerText(): string {+ const children = this.childrenAs<Txt | TxtLeaf>();+ let text = '';+ for (const child of children) {+ text += child.text();}- const wrap =- this.styles.whiteSpace !== 'nowrap' && this.styles.whiteSpace !== 'pre';+ return text;+ }- if (wrap) {- this.element.innerText = '';+ @computed()+ protected parentTxt() {+ const parent = this.parent();+ return parent instanceof Txt ? parent : null;+ }- if (Txt.segmenter) {- for (const word of Txt.segmenter.segment(this.formattedText())) {- this.element.appendChild(document.createTextNode(word.segment));- }- } else {- for (const word of this.formattedText().split('')) {- this.element.appendChild(document.createTextNode(word));- }- }- } else if (this.styles.whiteSpace === 'pre') {- this.element.innerText = '';- for (const line of this.text().split('\n')) {- this.element.appendChild(document.createTextNode(line + '\n'));+ protected override parseChildren(children: ComponentChildren): AnyTxt[] {+ const result: AnyTxt[] = [];+ const array = Array.isArray(children) ? children : [children];+ for (const child of array) {+ if (child instanceof Txt || child instanceof TxtLeaf) {+ result.push(child);+ } else if (typeof child === 'string') {+ result.push(new TxtLeaf({text: child}));}- } else {- this.element.innerText = this.formattedText();}++ return result;+ }++ protected override applyFlex() {+ super.applyFlex();+ this.element.style.display = this.findAncestor(is(Txt))+ ? 'inline'+ : 'block';+ }++ protected override draw(context: CanvasRenderingContext2D) {+ this.drawChildren(context);}}++[+ 'fill',+ 'stroke',+ 'lineWidth',+ 'strokeFirst',+ 'lineCap',+ 'lineJoin',+ 'lineDash',+ 'lineDashOffset',+].forEach(prop => {+ (Txt.prototype as any)[`getDefault${capitalize(prop)}`] = function (+ this: Txt,+ initial: unknown,+ ) {+ return (this.parentTxt() as any)?.[prop]() ?? initial;+ };+});diff --git a/packages/2d/src/components/TxtLeaf.ts b/packages/2d/src/components/TxtLeaf.tsnew file mode 100644index 00000000..87216119--- /dev/null+++ b/packages/2d/src/components/TxtLeaf.ts@@ -0,0 +1,195 @@+import {computed, initial, interpolation, signal} from '../decorators';+import {textLerp} from '@motion-canvas/core/lib/tweening';+import {Shape, ShapeProps} from './Shape';+import {BBox} from '@motion-canvas/core/lib/types';+import {SignalValue, SimpleSignal} from '@motion-canvas/core/lib/signals';+import {View2D} from './View2D';+import {lazy} from '@motion-canvas/core/lib/decorators';+import {Txt} from './Txt';+import {capitalize} from '@motion-canvas/core/lib/utils';++export interface TxtLeafProps extends ShapeProps {+ children?: string;+ text?: SignalValue<string>;+}++export class TxtLeaf extends Shape {+ @lazy(() => {+ const formatter = document.createElement('span');+ View2D.shadowRoot.append(formatter);+ return formatter;+ })+ protected static formatter: HTMLDivElement;++ @lazy(() => {+ try {+ return new (Intl as any).Segmenter(undefined, {+ granularity: 'grapheme',+ });+ } catch (e) {+ return null;+ }+ })+ protected static readonly segmenter: any;++ @initial('')+ @interpolation(textLerp)+ @signal()+ public declare readonly text: SimpleSignal<string, this>;++ public constructor({children, ...rest}: TxtLeafProps) {+ super(rest);+ if (children) {+ this.text(children);+ }+ }++ @computed()+ protected parentTxt() {+ const parent = this.parent();+ return parent instanceof Txt ? parent : null;+ }++ protected override draw(context: CanvasRenderingContext2D) {+ this.requestFontUpdate();+ this.applyStyle(context);+ this.applyText(context);+ context.font = this.styles.font;+ if ('letterSpacing' in context) {+ context.letterSpacing = `${this.letterSpacing()}px`;+ }++ const parentRect = this.element.getBoundingClientRect();+ const {width, height} = this.size();+ const range = document.createRange();+ let line = '';+ const lineRect = new BBox();+ for (const childNode of this.element.childNodes) {+ if (!childNode.textContent) {+ continue;+ }++ range.selectNodeContents(childNode);+ const rangeRect = range.getBoundingClientRect();++ const x = width / -2 + rangeRect.left - parentRect.left;+ const y = height / -2 + rangeRect.top - parentRect.top;++ if (lineRect.y === y) {+ lineRect.width += rangeRect.width;+ line += childNode.textContent;+ } else {+ this.drawText(context, line, lineRect);+ lineRect.x = x;+ lineRect.y = y;+ lineRect.width = rangeRect.width;+ lineRect.height = rangeRect.height;+ line = childNode.textContent;+ }+ }++ this.drawText(context, line, lineRect);+ }++ protected drawText(+ context: CanvasRenderingContext2D,+ text: string,+ box: BBox,+ ) {+ const y = box.y + box.height / 2;+ context.save();+ context.textBaseline = 'middle';+ text = text.replace(/\s+/g, ' ');++ if (this.lineWidth() <= 0) {+ context.fillText(text, box.x, y);+ } else if (this.strokeFirst()) {+ context.strokeText(text, box.x, y);+ context.fillText(text, box.x, y);+ } else {+ context.fillText(text, box.x, y);+ context.strokeText(text, box.x, y);+ }++ context.restore();+ }++ protected override getCacheBBox(): BBox {+ const size = this.computedSize();+ const range = document.createRange();+ range.selectNodeContents(this.element);+ const bbox = range.getBoundingClientRect();++ const lineWidth = this.lineWidth();+ // We take the default value of the miterLimit as 10.+ const miterLimitCoefficient = this.lineJoin() === 'miter' ? 0.5 * 10 : 0.5;++ return new BBox(+ -size.width / 2,+ -size.height / 2,+ bbox.width,+ bbox.height,+ ).expand(lineWidth * miterLimitCoefficient);+ }++ protected override applyFlex() {+ super.applyFlex();+ this.element.style.display = 'inline';+ }++ protected override updateLayout() {+ this.applyFont();+ this.applyFlex();++ // Make sure the text is aligned correctly even if the text is smaller than+ // the container.+ if (this.justifyContent.isInitial()) {+ this.element.style.justifyContent =+ this.styles.getPropertyValue('text-align');+ }++ const wrap =+ this.styles.whiteSpace !== 'nowrap' && this.styles.whiteSpace !== 'pre';++ if (wrap) {+ this.element.innerText = '';++ if (TxtLeaf.segmenter) {+ for (const word of TxtLeaf.segmenter.segment(this.text())) {+ this.element.appendChild(document.createTextNode(word.segment));+ }+ } else {+ for (const word of this.text().split('')) {+ this.element.appendChild(document.createTextNode(word));+ }+ }+ } else if (this.styles.whiteSpace === 'pre') {+ this.element.innerText = '';+ for (const line of this.text().split('\n')) {+ this.element.appendChild(document.createTextNode(line + '\n'));+ }+ } else {+ this.element.innerText = this.text();+ }+ }+}++[+ 'fill',+ 'stroke',+ 'lineWidth',+ 'strokeFirst',+ 'lineCap',+ 'lineJoin',+ 'lineDash',+ 'lineDashOffset',+].forEach(prop => {+ (TxtLeaf.prototype as any)[`get${capitalize(prop)}`] = function (+ this: TxtLeaf,+ ) {+ return (+ (this.parentTxt() as any)?.[prop]() ??+ (this as any)[prop].context.getInitial()+ );+ };+});diff --git a/packages/2d/src/decorators/signal.ts b/packages/2d/src/decorators/signal.tsindex 1e72a4fc..5b5e4cdf 100644--- a/packages/2d/src/decorators/signal.ts+++ b/packages/2d/src/decorators/signal.ts@@ -7,6 +7,7 @@ import {addInitializer, initialize} from './initializers';import {capitalize, useLogger} from '@motion-canvas/core/lib/utils';import {makeSignalExtensions} from '../utils/makeSignalExtensions';import {SignalContext} from '@motion-canvas/core/lib/signals';+import {SignalValue} from '@motion-canvas/core';export interface PropertyMetadata<T> {default?: T;@@ -113,12 +114,19 @@ export function initializeSignals(instance: any, props: Record<string, any>) {*/export function signal<T>(): PropertyDecorator {return (target: any, key) => {+ // FIXME property metadata is not inherited+ // Consider retrieving it inside the initializer using the instance and not+ // the class.const meta = getPropertyMetaOrCreate<T>(target, key);addInitializer(target, (instance: any) => {- const getDefault =- instance[`getDefault${capitalize(key as string)}`]?.bind(instance);+ let initial: SignalValue<T> = meta.default!;+ const defaultMethod = instance[`getDefault${capitalize(key as string)}`];+ if (defaultMethod) {+ initial = () => defaultMethod.call(instance, meta.default);+ }+const signal = new SignalContext<T, T, any>(- getDefault ?? meta.default,+ initial,meta.interpolationFunction ?? deepLerp,instance,meta.parser?.bind(instance),diff --git a/packages/2d/src/utils/is.ts b/packages/2d/src/utils/is.tsindex 3202a29b..595c8c68 100644--- a/packages/2d/src/utils/is.ts+++ b/packages/2d/src/utils/is.ts@@ -4,12 +4,8 @@** @param klass - The class to check against.*/-export function is<- T extends- // NOTE This is the one specific case where the Function type is actually- // desired. Hence, the eslint-disable-next-line.- // eslint-disable-next-line @typescript-eslint/ban-types- Function,->(klass: T): (object: any) => object is T {+export function is<T>(+ klass: new (...args: any[]) => T,+): (object: any) => object is T {return (object): object is T => object instanceof klass;}diff --git a/packages/core/src/signals/SignalContext.ts b/packages/core/src/signals/SignalContext.tsindex 213c92b9..98923b01 100644--- a/packages/core/src/signals/SignalContext.ts+++ b/packages/core/src/signals/SignalContext.ts@@ -59,6 +59,7 @@ export class SignalContext<protected extensions: SignalExtensions<TSetterValue, TValue>;protected current: SignalValue<TSetterValue> | undefined;protected last: TValue | undefined;+ protected tweening = false;public constructor(private initial: SignalValue<TSetterValue> | undefined,@@ -248,6 +249,7 @@ export class SignalContext<value = this.initial!;}+ this.tweening = true;yield* this.extensions.tweener(value,duration,@@ -255,6 +257,7 @@ export class SignalContext<interpolationFunction,);this.set(value);+ this.tweening = false;}public *tweener(@@ -340,6 +343,13 @@ export class SignalContext<return this.current === this.initial;}+ /**+ * Get the initial value of this signal.+ */+ public getInitial() {+ return this.initial;+ }+/*** Get the raw value of this signal.*@@ -366,4 +376,11 @@ export class SignalContext<public raw() {return this.current;}++ /**+ * Is the signal undergoing a tween?+ */+ public isTweening() {+ return this.tweening;+ }}diff --git a/packages/core/src/tweening/interpolationFunctions.ts b/packages/core/src/tweening/interpolationFunctions.tsindex 39fc13a2..b856e69e 100644--- a/packages/core/src/tweening/interpolationFunctions.ts+++ b/packages/core/src/tweening/interpolationFunctions.ts@@ -139,6 +139,10 @@ export function deepLerp(return to;}+export function boolLerp<T>(from: T, to: T, value: number): T {+ return value < 0.5 ? from : to;+}+export function map(from: number, to: number, value: number) {return from + (to - from) * value;}