import * as _twick_core from '@twick/core'; import { SimpleSignal, SignalValue, Vector2, BBox, Spacing, SerializedVector2, Signal, TimingFunction, ThreadGenerator, PossibleVector2, Vector2Signal, Color, PossibleColor, ColorSignal, InterpolationFunction, SignalContext, GeneratorScene, Inspectable, FullSceneDescription, ThreadGeneratorFactory, Scene, InspectedElement, InspectedAttributes, AssetInfo, DescriptionOf } from '@twick/core'; import { R as Rect, a as RectProps, S as Segment, C as CurvePoint, b as CurveProfile, c as Curve, D as DesiredLength, d as CurveProps, e as Shape, f as ShapeProps, N as NodeProps, g as Node, h as ComponentChildren, V as View2D, P as PossibleCanvasStyle, G as Gradient, i as Pattern, j as CanvasStyle } from './jsx-dev-runtime-EZGUDKMi.cjs'; export { ae as CanvasRepetition, s as CanvasStyleSignal, m as ComponentChild, r as CurveDrawingInfo, a0 as FILTERS, a2 as Filter, $ as FilterName, a1 as FilterProps, u as FiltersSignal, v as FiltersSignalContext, ai as FlexBasis, aj as FlexContent, ag as FlexDirection, ak as FlexItems, ah as FlexWrap, _ as Fragment, F as FunctionComponent, ad as GradientProps, ac as GradientStop, ab as GradientType, Z as JSX, J as JSXProps, k as Layout, am as LayoutMode, L as LayoutProps, an as Length, ao as LengthLimit, x as NODE_NAME, n as NodeChildren, p as NodeConstructor, l as NodeState, af as PatternProps, z as PropertyMetadata, o as PropsOf, al as TextWrap, W as Vector2LengthSignal, q as View2DProps, aa as blur, a6 as brightness, t as canvasStyleSignal, T as cloneable, a7 as contrast, w as filtersSignal, E as getPropertiesOf, A as getPropertyMeta, B as getPropertyMetaOrCreate, a5 as grayscale, a9 as hue, K as initial, H as initializeSignals, U as inspectable, M as interpolation, a3 as invert, Y as jsx, Y as jsxs, y as nodeName, O as parser, a8 as saturate, a4 as sepia, I as signal, X as vector2Signal, Q as wrapper } from './jsx-dev-runtime-EZGUDKMi.cjs'; import { HighlightStyle } from '@codemirror/language'; import { Tree, Parser } from '@lezer/common'; import { OptionList } from 'mathjax-full/js/util/Options'; declare function colorSignal(): PropertyDecorator; /** * Create a compound property decorator. * * @remarks * This decorator turns a given property into a signal consisting of one or more * nested signals. * * @example * ```ts * class Example { * \@compound({x: 'scaleX', y: 'scaleY'}) * public declare readonly scale: Signal; * * public setScale() { * this.scale({x: 7, y: 3}); * // same as: * this.scale.x(7).scale.y(3); * } * } * ``` * * @param entries - A record mapping the property in the compound object to the * corresponding property on the owner node. */ declare function compound(entries: Record): PropertyDecorator; /** * Create a computed method decorator. * * @remarks * This decorator turns the given method into a computed value. * See {@link createComputed} for more information. */ declare function computed(): MethodDecorator; declare function defaultStyle(styleName: string, parse?: (value: string) => T): PropertyDecorator; type Initializer = (instance: T, context?: any) => void; declare function addInitializer(target: any, initializer: Initializer): void; declare function initialize(target: any, context?: any): void; interface MediaProps extends RectProps { src?: SignalValue; loop?: SignalValue; playbackRate?: number; volume?: number; time?: SignalValue; play?: boolean; awaitCanPlay?: SignalValue; allowVolumeAmplificationInPreview?: SignalValue; /** Timeline time when this clip starts; when set, syncToCurrentTime(globalTime) uses clip-relative time. */ clipStart?: number; /** * Timeline time when this clip ends (non-inclusive). * When set (together with clipStart), rendering/asset collection will only consider this media * active for globalTime in [clipStart, clipEnd). */ clipEnd?: number; /** Start offset in the media file (e.g. trim); used with clipStart for sync. */ trimStart?: number; } declare abstract class Media extends Rect { readonly src: SimpleSignal; readonly loop: SimpleSignal; readonly playbackRate: SimpleSignal; protected readonly time: SimpleSignal; protected readonly playing: SimpleSignal; protected readonly awaitCanPlay: SimpleSignal; protected readonly allowVolumeAmplificationInPreview: SimpleSignal; protected volume: number; protected static readonly amplificationPool: Record; protected lastTime: number; private isSchedulingPlay; /** When set, syncToCurrentTime(globalTime) converts to clip-relative time. */ protected clipStart: number | undefined; /** When set, clip is only active before this global time (non-inclusive). */ protected clipEnd: number | undefined; /** Used with clipStart for sync (trim offset in source). */ protected trimStart: number; constructor(props: MediaProps); isPlaying(): boolean; isActiveAtGlobalTime(globalTime: number): boolean; getCurrentTime(): number; getDuration(): number; getVolume(): number; getUrl(): string; dispose(): void; completion(): number; protected abstract mediaElement(): HTMLMediaElement; protected abstract seekedMedia(): HTMLMediaElement; protected abstract fastSeekedMedia(): HTMLMediaElement; /** * Sync the underlying media element to the given time (e.g. draw/playback time). * Used for both Video and Audio. When `time` is passed (e.g. from Scene2D.draw), that * value is used so sync does not depend on the node's time signal. * If this node has clipStart set, global time is converted to clip-relative time: * syncTime = trimStart + (time - clipStart) * playbackRate. * When omitted, falls back to this.time(). * When waitForSeek is true, returns a promise that resolves when the seek completes so * the draw can wait and show the correct frame/sample when paused. */ syncToCurrentTime(time?: number, options?: { waitForSeek?: boolean; }): void | Promise; protected abstract draw(context: CanvasRenderingContext2D): Promise; protected setCurrentTime(value: number, options?: { skipCollectPromise?: boolean; }): Promise; setVolume(volume: number): void; protected amplify(node: HTMLMediaElement, volume: number): void; protected setPlaybackRate(playbackRate: number): void; protected scheduleSeek(time: number): void; /** * Waits for the canplay event to be fired before calling onCanPlay. * * If the media is already ready to play, onCanPlay is called immediately. * @param onCanPlay - The function to call when the media is ready to play. * @returns */ protected waitForCanPlay(media: HTMLMediaElement, onCanPlay: () => void): void; /** * Returns true if we should wait for the media to be ready to play. */ protected waitForCanPlayNecessary(media: HTMLMediaElement): boolean; play(): void; protected schedulePlay(): void; private simplePlay; private actuallyPlay; pause(): void; clampTime(time: number): number; protected collectAsyncResources(): void; protected autoPlayBasedOnTwick(): void; protected getErrorReason(errCode?: number): string; protected isIOS(): boolean; } declare class Audio extends Media { private static readonly pool; constructor(props: MediaProps); dispose(): void; protected mediaElement(): HTMLAudioElement; protected seekedMedia(): HTMLAudioElement; protected fastSeekedMedia(): HTMLAudioElement; protected audio(): HTMLAudioElement; protected seekedAudio(): HTMLAudioElement; protected fastSeekedAudio(): HTMLAudioElement; protected draw(context: CanvasRenderingContext2D): Promise; } declare class CircleSegment extends Segment { private center; private radius; private from; private to; private counter; private readonly length; private readonly angle; readonly points: Vector2[]; constructor(center: Vector2, radius: number, from: Vector2, to: Vector2, counter: boolean); get arcLength(): number; draw(context: CanvasRenderingContext2D | Path2D, from: number, to: number): [CurvePoint, CurvePoint]; getPoint(distance: number): CurvePoint; } /** * A polynomial in the form ax^3 + bx^2 + cx + d up to a cubic polynomial. * * Source code liberally taken from: * https://github.com/FreyaHolmer/Mathfs/blob/master/Runtime/Curves/Polynomial.cs */ declare class Polynomial { readonly c0: number; readonly c1: number; readonly c2: number; readonly c3: number; /** * Constructs a constant polynomial * * @param c0 - The constant coefficient */ static constant(c0: number): Polynomial; /** * Constructs a linear polynomial * * @param c0 - The constant coefficient * @param c1 - The linear coefficient */ static linear(c0: number, c1: number): Polynomial; /** * Constructs a quadratic polynomial * * @param c0 - The constant coefficient * @param c1 - The linear coefficient * @param c2 - The quadratic coefficient */ static quadratic(c0: number, c1: number, c2: number): Polynomial; /** * Constructs a cubic polynomial * * @param c0 - The constant coefficient * @param c1 - The linear coefficient * @param c2 - The quadratic coefficient * @param c3 - The cubic coefficient */ static cubic(c0: number, c1: number, c2: number, c3: number): Polynomial; /** * The degree of the polynomial */ get degree(): number; /** * @param c0 - The constant coefficient */ constructor(c0: number); /** * @param c0 - The constant coefficient * @param c1 - The linear coefficient */ constructor(c0: number, c1: number); /** * @param c0 - The constant coefficient * @param c1 - The linear coefficient * @param c2 - The quadratic coefficient */ constructor(c0: number, c1: number, c2: number); /** * @param c0 - The constant coefficient * @param c1 - The linear coefficient * @param c2 - The quadratic coefficient * @param c3 - The cubic coefficient */ constructor(c0: number, c1: number, c2: number, c3: number); /** * Return the nth derivative of the polynomial. * * @param n - The number of times to differentiate the polynomial. */ differentiate(n?: number): Polynomial; /** * Evaluate the polynomial at the given value t. * * @param t - The value to sample at */ eval(t: number): number; /** * Evaluate the nth derivative of the polynomial at the given value t. * * @param t - The value to sample at * @param derivative - The derivative of the polynomial to sample from */ eval(t: number, derivative: number): number; /** * Split the polynomial into two polynomials of the same overall shape. * * @param u - The point at which to split the polynomial. */ split(u: number): [Polynomial, Polynomial]; /** * Calculate the roots (values where this polynomial = 0). * * @remarks * Depending on the degree of the polynomial, returns between 0 and 3 results. */ roots(): number[]; /** * Calculate the local extrema of the polynomial. */ localExtrema(): number[]; /** * Calculate the local extrema of the polynomial in the unit interval. */ localExtrema01(): number[]; /** * Return the output value range within the unit interval. */ outputRange01(): number[]; private solveCubicRoots; private solveDepressedCubicRoots; private solveQuadraticRoots; private solveLinearRoot; private almostZero; } declare class Polynomial2D { readonly c0: Vector2 | Polynomial; readonly c1: Vector2 | Polynomial; readonly c2?: Vector2 | undefined; readonly c3?: Vector2 | undefined; readonly x: Polynomial; readonly y: Polynomial; constructor(c0: Vector2, c1: Vector2, c2: Vector2, c3: Vector2); constructor(c0: Vector2, c1: Vector2, c2: Vector2); constructor(x: Polynomial, y: Polynomial); eval(t: number, derivative?: number): Vector2; split(u: number): [Polynomial2D, Polynomial2D]; differentiate(n?: number): Polynomial2D; evalDerivative(t: number): Vector2; /** * Calculate the tight axis-aligned bounds of the curve in the unit interval. */ getBounds(): BBox; } /** * Class to uniformly sample points on a given polynomial curve. * * @remarks * In order to uniformly sample points from non-linear curves, this sampler * re-parameterizes the curve by arclength. */ declare class UniformPolynomialCurveSampler { private readonly curve; private sampledDistances; /** * @param curve - The curve to sample * @param samples - How many points to sample from the provided curve. The * more points get sampled, the higher the resolution–and * therefore precision–of the sampler. */ constructor(curve: PolynomialSegment, samples?: number); /** * Discard all previously sampled points and resample the provided number of * points from the curve. * * @param samples - The number of points to sample. */ resample(samples: number): void; /** * Return the point at the provided distance along the sampled curve's * arclength. * * @param distance - The distance along the curve's arclength for which to * retrieve the point. */ pointAtDistance(distance: number): CurvePoint; /** * Return the t value for the point at the provided distance along the sampled * curve's arc length. * * @param distance - The distance along the arclength */ distanceToT(distance: number): number; } declare abstract class PolynomialSegment extends Segment { protected readonly curve: Polynomial2D; protected readonly length: number; protected readonly pointSampler: UniformPolynomialCurveSampler; get arcLength(): number; abstract get points(): Vector2[]; protected constructor(curve: Polynomial2D, length: number); getBBox(): BBox; /** * Evaluate the polynomial at the given t value. * * @param t - The t value at which to evaluate the curve. */ eval(t: number): CurvePoint; /** * Split the curve into two separate polynomials at the given t value. The two * resulting curves form the same overall shape as the original curve. * * @param t - The t value at which to split the curve. */ abstract split(t: number): [PolynomialSegment, PolynomialSegment]; getPoint(distance: number): CurvePoint; transformPoints(matrix: DOMMatrix): Vector2[]; /** * Return the tangent of the point that sits at the provided t value on the * curve. * * @param t - The t value at which to evaluate the curve. */ tangent(t: number): Vector2; draw(context: CanvasRenderingContext2D | Path2D, start?: number, end?: number, move?: boolean): [CurvePoint, CurvePoint]; protected abstract doDraw(context: CanvasRenderingContext2D | Path2D): void; } /** * A spline segment representing a cubic Bézier curve. */ declare class CubicBezierSegment extends PolynomialSegment { readonly p0: Vector2; readonly p1: Vector2; readonly p2: Vector2; readonly p3: Vector2; private static el; get points(): Vector2[]; constructor(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2); split(t: number): [PolynomialSegment, PolynomialSegment]; protected doDraw(context: CanvasRenderingContext2D | Path2D): void; protected static getLength(p0: Vector2, p1: Vector2, p2: Vector2, p3: Vector2): number; } type KnotAutoHandles = { start: number; end: number; }; interface KnotInfo { position: Vector2; startHandle: Vector2; endHandle: Vector2; auto: KnotAutoHandles; } /** * Calculate the curve profile of a spline based on a set of knots. * * @param knots - The knots defining the spline * @param closed - Whether the spline should be closed or not * @param smoothness - The desired smoothness of the spline when using auto * calculated handles. */ declare function getBezierSplineProfile(knots: KnotInfo[], closed: boolean, smoothness: number): CurveProfile; declare function getCircleProfile(size: Vector2, startAngle: number, endAngle: number, closed: boolean, counterclockwise?: boolean): CurveProfile; declare function getPointAtDistance(profile: CurveProfile, distance: number): CurvePoint; declare function getPolylineProfile(points: readonly Vector2[], radius: number, closed: boolean): CurveProfile; declare function getRectProfile(rect: BBox, radius: Spacing, smoothCorners: boolean, cornerSharpness: number): CurveProfile; declare class LineSegment extends Segment { readonly from: Vector2; readonly to: Vector2; private readonly length; private readonly vector; private readonly normal; readonly points: Vector2[]; constructor(from: Vector2, to: Vector2); get arcLength(): number; draw(context: CanvasRenderingContext2D | Path2D, start?: number, end?: number, move?: boolean): [CurvePoint, CurvePoint]; getPoint(distance: number): CurvePoint; } /** * A spline segment representing a quadratic Bézier curve. */ declare class QuadBezierSegment extends PolynomialSegment { readonly p0: Vector2; readonly p1: Vector2; readonly p2: Vector2; private static el; get points(): Vector2[]; constructor(p0: Vector2, p1: Vector2, p2: Vector2); split(t: number): [PolynomialSegment, PolynomialSegment]; protected static getLength(p0: Vector2, p1: Vector2, p2: Vector2): number; protected doDraw(context: CanvasRenderingContext2D | Path2D): void; } interface BezierOverlayInfo { curve: Path2D; handleLines: Path2D; controlPoints: Vector2[]; startPoint: Vector2; endPoint: Vector2; } declare abstract class Bezier extends Curve { profile(): CurveProfile; protected abstract segment(): PolynomialSegment; protected abstract overlayInfo(matrix: DOMMatrix): BezierOverlayInfo; protected childrenBBox(): BBox; protected desiredSize(): SerializedVector2; protected offsetComputedLayout(box: BBox): BBox; drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix): void; } interface CircleProps extends CurveProps { /** * {@inheritDoc Circle.startAngle} */ startAngle?: SignalValue; /** * {@inheritDoc Circle.endAngle} */ endAngle?: SignalValue; /** * {@inheritDoc Circle.counterclockwise} */ counterclockwise?: SignalValue; /** * {@inheritDoc Circle.closed} */ closed?: SignalValue; } /** * A node for drawing circular shapes. * * @remarks * This node can be used to render shapes such as: circle, ellipse, arc, and * sector (pie chart). * * @preview * ```tsx editor * // snippet Simple circle * import {makeScene2D, Circle} from '@twick/2d'; * * export default makeScene2D(function* (view) { * view.add( * * ); * }); * * // snippet Ellipse * import {makeScene2D, Circle} from '@twick/2d'; * * export default makeScene2D(function* (view) { * view.add( * * ); * }); * * // snippet Sector (pie chart): * import {makeScene2D, Circle} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const ref = createRef(); * view.add( * * ); * * yield* ref().startAngle(270, 2).to(30, 2); * }); * * // snippet Arc: * import {makeScene2D, Circle} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const ref = createRef(); * view.add( * * ); * * yield* ref().startAngle(-270, 2).to(-90, 2); * }); * * // snippet Curve properties: * import {makeScene2D, Circle} from '@twick/2d'; * import {all, createRef, easeInCubic, easeOutCubic} from '@twick/core'; * * export default makeScene2D(function* (view) { * const ref = createRef(); * view.add( * , * ); * * yield* all(ref().start(1, 1), ref().rotation(180, 1, easeInCubic)); * ref().start(0).end(0); * yield* all(ref().end(1, 1), ref().rotation(360, 1, easeOutCubic)); * }); * ``` */ declare class Circle extends Curve { /** * The starting angle in degrees for the circle sector. * * @remarks * This property can be used together with {@link startAngle} to turn this * circle into a sector (when using fill) or an arc (when using stroke). * * @defaultValue 0 */ readonly startAngle: SimpleSignal; /** * The ending angle in degrees for the circle sector. * * @remarks * This property can be used together with {@link endAngle} to turn this * circle into a sector (when using fill) or an arc (when using stroke). * * @defaultValue 360 */ readonly endAngle: SimpleSignal; /** * Whether the circle sector should be drawn counterclockwise. * * @remarks * By default, the circle begins at {@link startAngle} and is drawn clockwise * until reaching {@link endAngle}. Setting this property to true will reverse * this direction. */ readonly counterclockwise: SimpleSignal; /** * Whether the path of this circle should be closed. * * @remarks * When set to true, the path of this circle will start and end at the center. * This can be used to fine-tune how sectors are rendered. * * @example * A closed circle will look like a pie chart: * ```tsx * * ``` * An open one will look like an arc: * ```tsx * * ``` * * @defaultValue false */ readonly closed: SimpleSignal; constructor(props: CircleProps); profile(): CurveProfile; protected desiredSize(): SerializedVector2; protected offsetComputedLayout(box: BBox): BBox; protected childrenBBox(): BBox; protected getPath(): Path2D; protected getRipplePath(): Path2D; protected getCacheBBox(): BBox; protected createPath(expand?: number): Path2D; } interface DrawTokenHook { (ctx: CanvasRenderingContext2D, text: string, position: Vector2, color: string, selection: number): void; } /** * Describes custom drawing logic used by the Code node. */ interface DrawHooks { /** * Custom drawing logic for individual code tokens. * * @example * ```ts * token(ctx, text, position, color, selection) { * const blur = map(3, 0, selection); * const alpha = map(0.5, 1, selection); * ctx.globalAlpha *= alpha; * ctx.filter = `blur(${blur}px)`; * ctx.fillStyle = color; * ctx.fillText(text, position.x, position.y); * } * ``` */ token: DrawTokenHook; } interface CodeProps extends ShapeProps { /** * {@inheritDoc Code.highlighter} */ highlighter?: SignalValue; /** * {@inheritDoc Code.code} */ code?: SignalValue; /** * {@inheritDoc Code.selection} */ selection?: SignalValue; /** * {@inheritDoc Code.drawHooks} */ drawHooks?: SignalValue; } /** * A node for displaying and animating code. * * @experimental * * @preview * ```tsx editor * import {parser} from '@lezer/javascript'; * import {Code, LezerHighlighter, makeScene2D} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * LezerHighlighter.registerParser(parser); * const code = createRef(); * * view.add( * , * ); * * yield* code() * .code( * `\ * function hello() { * console.warn('Hello World'); * }`, * 1, * ) * .wait(0.5) * .back(1) * .wait(0.5); * }); * ``` */ declare class Code extends Shape { /** * Create a standalone code signal. * * @param initial - The initial code. * @param highlighter - Custom highlighter to use. */ static createSignal(initial: PossibleCodeScope, highlighter?: SignalValue): CodeSignal; static defaultHighlighter: CodeHighlighter | null; /** * The code highlighter to use for this code node. * * @remarks * Defaults to a shared {@link code.LezerHighlighter}. */ readonly highlighter: SimpleSignal; /** * The code to display. */ readonly code: CodeSignal; /** * Custom drawing logic for the code. * * @remarks * Check out {@link DrawHooks} for available render hooks. * * @example * Make the unselected code blurry and transparent: * ```tsx * * ``` */ readonly drawHooks: SimpleSignal; protected setDrawHooks(value: DrawHooks): void; /** * The currently selected code range. * * @remarks * Either a single {@link code.CodeRange} or an array of them * describing which parts of the code should be visually emphasized. * * You can use {@link code.word} and * {@link code.lines} to quickly create ranges. * * @example * The following will select the word "console" in the code. * Both lines and columns are 0-based. So it will select a 7-character-long * (`7`) word in the second line (`1`) starting at the third character (`2`). * ```tsx * { * console.log('Hello'); * }`} * // ... * /> * ``` */ readonly selection: Signal; oldSelection: CodeSelection | null; selectionProgress: SimpleSignal; protected tweenSelection(value: CodeRange[], duration: number, timingFunction: TimingFunction): ThreadGenerator; /** * Get the currently displayed code as a string. */ parsed(): string; highlighterCache(): { before: unknown; after: unknown; } | null; private cursorCache; private get cursor(); constructor(props: CodeProps); /** * Create a child code signal. * * @param initial - The initial code. */ createSignal(initial: PossibleCodeScope): CodeSignal; /** * Find all code ranges that match the given pattern. * * @param pattern - Either a string or a regular expression to match. */ findAllRanges(pattern: string | RegExp): CodeRange[]; /** * Find the first code range that matches the given pattern. * * @param pattern - Either a string or a regular expression to match. */ findFirstRange(pattern: string | RegExp): CodeRange; /** * Find the last code range that matches the given pattern. * * @param pattern - Either a string or a regular expression to match. */ findLastRange(pattern: string | RegExp): CodeRange; /** * Return the bounding box of the given point (character) in the code. * * @remarks * The returned bound box is in local space of the `Code` node. * * @param point - The point to get the bounding box for. */ getPointBbox(point: CodePoint): BBox; /** * Return bounding boxes of all characters in the selection. * * @remarks * The returned bound boxes are in local space of the `Code` node. * Each line of code has a separate bounding box. * * @param selection - The selection to get the bounding boxes for. */ getSelectionBbox(selection: PossibleCodeSelection): BBox[]; protected drawingInfo(): { fragments: CodeFragmentDrawingInfo[]; verticalOffset: number; fontHeight: number; }; protected desiredSize(): SerializedVector2; protected draw(context: CanvasRenderingContext2D): Promise; protected applyText(context: CanvasRenderingContext2D): void; protected collectAsyncResources(): void; } interface CubicBezierProps extends CurveProps { p0?: SignalValue; p0X?: SignalValue; p0Y?: SignalValue; p1?: SignalValue; p1X?: SignalValue; p1Y?: SignalValue; p2?: SignalValue; p2X?: SignalValue; p2Y?: SignalValue; p3?: SignalValue; p3X?: SignalValue; p3Y?: SignalValue; } /** * A node for drawing a cubic Bézier curve. * * @preview * ```tsx editor * import {makeScene2D, CubicBezier} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const bezier = createRef(); * * view.add( * * ); * * yield* bezier().end(1, 1); * yield* bezier().start(1, 1).to(0, 1); * }); * ``` */ declare class CubicBezier extends Bezier { /** * The start point of the Bézier curve. */ readonly p0: Vector2Signal; /** * The first control point of the Bézier curve. */ readonly p1: Vector2Signal; /** * The second control point of the Bézier curve. */ readonly p2: Vector2Signal; /** * The end point of the Bézier curve. */ readonly p3: Vector2Signal; constructor(props: CubicBezierProps); protected segment(): PolynomialSegment; protected overlayInfo(matrix: DOMMatrix): BezierOverlayInfo; } interface GridProps extends ShapeProps { /** * {@inheritDoc Grid.spacing} */ spacing?: SignalValue; /** * {@inheritDoc Grid.start} */ start?: SignalValue; /** * {@inheritDoc Grid.end} */ end?: SignalValue; } /** * A node for drawing a two-dimensional grid. * * @preview * ```tsx editor * import {Grid, makeScene2D} from '@twick/2d'; * import {all, createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const grid = createRef(); * * view.add( * , * ); * * yield* all( * grid().end(0.5, 1).to(1, 1).wait(1), * grid().start(0.5, 1).to(0, 1).wait(1), * ); * }); * ``` */ declare class Grid extends Shape { /** * The spacing between the grid lines. */ readonly spacing: Vector2Signal; /** * The percentage that should be clipped from the beginning of each grid line. * * @remarks * The portion of each grid line that comes before the given percentage will * be made invisible. * * This property is useful for animating the grid appearing on-screen. */ readonly start: SimpleSignal; /** * The percentage that should be clipped from the end of each grid line. * * @remarks * The portion of each grid line that comes after the given percentage will * be made invisible. * * This property is useful for animating the grid appearing on-screen. */ readonly end: SimpleSignal; constructor(props: GridProps); protected drawShape(context: CanvasRenderingContext2D): void; private mapPoints; } interface ImgProps extends RectProps { /** * {@inheritDoc Img.src} */ src?: SignalValue; /** * {@inheritDoc Img.alpha} */ alpha?: SignalValue; /** * {@inheritDoc Img.smoothing} */ smoothing?: SignalValue; } /** * A node for displaying images. * * @preview * ```tsx editor * import {Img} from '@twick/2d'; * import {all, waitFor} from '@twick/core'; * import {createRef} from '@twick/core'; * import {makeScene2D} from '@twick/2d'; * * export default makeScene2D(function* (view) { * const ref = createRef(); * yield view.add( * , * ); * * // set the background using the color sampled from the image: * ref().fill(ref().getColorAtPoint(0)); * * yield* all( * ref().size([100, 100], 1).to([300, null], 1), * ref().radius(50, 1).to(20, 1), * ref().alpha(0, 1).to(1, 1), * ); * yield* waitFor(0.5); * }); * ``` */ declare class Img extends Rect { private static pool; /** * The source of this image. * * @example * Using a local image: * ```tsx * import image from './example.png'; * // ... * view.add() * ``` * Loading an image from the internet: * ```tsx * view.add() * ``` */ readonly src: SimpleSignal; /** * The alpha value of this image. * * @remarks * Unlike opacity, the alpha value affects only the image itself, leaving the * fill, stroke, and children intact. */ readonly alpha: SimpleSignal; /** * Whether the image should be smoothed. * * @remarks * When disabled, the image will be scaled using the nearest neighbor * interpolation with no smoothing. The resulting image will appear pixelated. * * @defaultValue true */ readonly smoothing: SimpleSignal; constructor(props: ImgProps); protected desiredSize(): SerializedVector2; protected image(): HTMLImageElement; protected imageCanvas(): CanvasRenderingContext2D; protected filledImageCanvas(): CanvasRenderingContext2D; protected draw(context: CanvasRenderingContext2D): Promise; protected applyFlex(): void; /** * Get color of the image at the given position. * * @param position - The position in local space at which to sample the color. */ getColorAtPoint(position: PossibleVector2): Color; /** * The natural size of this image. * * @remarks * The natural size is the size of the source image unaffected by the size * and scale properties. */ naturalSize(): Vector2; /** * Get color of the image at the given pixel. * * @param position - The pixel's position. */ getPixelColor(position: PossibleVector2): Color; protected collectAsyncResources(): void; } interface IconProps extends ImgProps { /** * {@inheritDoc Icon.icon} */ icon: SignalValue; /** * {@inheritDoc Icon.color} */ color?: SignalValue; } /** * An Icon Component that provides easy access to over 150k icons. * See https://icones.js.org/collection/all for all available Icons. */ declare class Icon extends Img { /** * The identifier of the icon. * * @remarks * You can find identifiers on [Icônes](https://icones.js.org). * They can look like this: * * `mdi:language-typescript` * * `ph:anchor-simple-bold` * * `ph:activity-bold` */ icon: SimpleSignal; /** * The color of the icon * * @remarks * Provide the color in one of the following formats: * * named color like `red`, `darkgray`, … * * hexadecimal string with # like `#bada55`, `#141414` * Value can be either RGB or RGBA: `#bada55`, `#bada55aa` (latter is partially transparent) * The shorthand version (e.g. `#abc` for `#aabbcc` is also possible.) * * @defaultValue 'white' */ color: ColorSignal; constructor(props: IconProps); /** * Create the URL that will be used as the Image source * @returns Address to Iconify API for the requested Icon. */ protected svgUrl(): string; /** * overrides `Image.src` getter */ protected getSrc(): string; /** * overrides `Image.src` setter to warn the user that the value * is not used */ protected setSrc(src: string | null): void; } interface KnotProps extends NodeProps { /** * {@inheritDoc Knot.startHandle} */ startHandle?: SignalValue; /** * {@inheritDoc Knot.endHandle} */ endHandle?: SignalValue; /** * {@inheritDoc Knot.auto} */ auto?: SignalValue; startHandleAuto?: SignalValue; endHandleAuto?: SignalValue; } type KnotAuto = { startHandle: number; endHandle: number; }; type PossibleKnotAuto = KnotAuto | number | [number, number]; type KnotAutoSignal = Signal & { endHandle: Signal; startHandle: Signal; }; /** * A node representing a knot of a {@link Spline}. */ declare class Knot extends Node { /** * The position of the knot's start handle. The position is provided relative * to the knot's position. * * @remarks * By default, the position of the start handle will be the mirrored position * of the {@link endHandle}. * * If neither an end handle nor a start handle is provided, the positions of * the handles gets calculated automatically to create smooth curve through * the knot. The smoothness of the resulting curve can be controlled via the * {@link Spline.smoothness} property. * * It is also possible to blend between a user-defined position and the * auto-calculated position by using the {@link auto} property. * * @defaultValue Mirrored position of the endHandle. */ readonly startHandle: Vector2Signal; /** * The position of the knot's end handle. The position is provided relative * to the knot's position. * * @remarks * By default, the position of the end handle will be the mirrored position * of the {@link startHandle}. * * If neither an end handle nor a start handle is provided, the positions of * the handles gets calculated automatically to create smooth curve through * the knot. The smoothness of the resulting curve can be controlled via the * {@link Spline.smoothness} property. * * It is also possible to blend between a user-defined position and the * auto-calculated position by using the {@link auto} property. * * @defaultValue Mirrored position of the startHandle. */ readonly endHandle: Vector2Signal; /** * How much to blend between the user-provided handles and the auto-calculated * handles. * * @remarks * This property has no effect if no explicit handles are provided for the * knot. * * @defaultValue 0 */ readonly auto: KnotAutoSignal; get startHandleAuto(): Signal>; get endHandleAuto(): Signal>; constructor(props: KnotProps); points(): KnotInfo; private getDefaultEndHandle; private getDefaultStartHandle; } interface LatexProps extends ImgProps { tex?: SignalValue; renderProps?: SignalValue; } /** * A node for rendering equations with LaTeX. * * @preview * ```tsx editor * import {Latex, makeScene2D} from '@twick/2d'; * * export default makeScene2D(function* (view) { * view.add( * , * ); * }); * ``` */ declare class Latex extends Img { private static svgContentsPool; private static mathJaxInitialized; private static adaptor; private static jaxDocument; private static initializeMathJax; private readonly imageElement; readonly options: SimpleSignal; readonly tex: SimpleSignal; constructor(props: LatexProps); protected image(): HTMLImageElement; } interface LineProps extends CurveProps { /** * {@inheritDoc Line.radius} */ radius?: SignalValue; /** * {@inheritDoc Line.points} */ points?: SignalValue[]>; } /** * A node for drawing lines and polygons. * * @remarks * This node can be used to render any polygonal shape defined by a set of * points. * * @preview * ```tsx editor * // snippet Simple line * import {makeScene2D, Line} from '@twick/2d'; * * export default makeScene2D(function* (view) { * view.add( * , * ); * }); * * // snippet Polygon * import {makeScene2D, Line} from '@twick/2d'; * * export default makeScene2D(function* (view) { * view.add( * , * ); * }); * * // snippet Using signals * import {makeScene2D, Line} from '@twick/2d'; * import {createSignal} from '@twick/core'; * * export default makeScene2D(function* (view) { * const tip = createSignal(-150); * view.add( * [tip(), -70], * ]} * stroke={'lightseagreen'} * lineWidth={8} * closed * />, * ); * * yield* tip(150, 1).back(1); * }); * * // snippet Tweening points * import {makeScene2D, Line} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const line = createRef(); * view.add( * , * ); * * yield* line() * .points( * [ * [-150, 0], * [0, 100], * [150, 0], * [150, -70], * [-150, -70], * ], * 2, * ) * .back(2); * }); * ``` */ declare class Line extends Curve { /** * Rotate the points to minimize the overall distance traveled when tweening. * * @param points - The points to rotate. * @param reference - The reference points to which the distance is measured. * @param closed - Whether the points form a closed polygon. */ private static rotatePoints; /** * Distribute additional points along the polyline. * * @param points - The points of a polyline along which new points should be * distributed. * @param count - The number of points to add. */ private static distributePoints; /** * The radius of the line's corners. */ readonly radius: SimpleSignal; /** * The points of the line. * * @remarks * When set to `null`, the Line will use the positions of its children as * points. */ readonly points: SimpleSignal[] | null, this>; protected tweenPoints(value: SignalValue[] | null>, time: number, timingFunction: TimingFunction): ThreadGenerator; private tweenedPoints; constructor(props: LineProps); protected childrenBBox(): BBox; parsedPoints(): Vector2[]; profile(): CurveProfile; protected lineWidthCoefficient(): number; drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix): void; private parsePoints; } interface PathProps extends CurveProps { data: SignalValue; } declare class Path extends Curve { private currentProfile; readonly data: SimpleSignal; constructor(props: PathProps); profile(): CurveProfile; protected childrenBBox(): BBox; protected lineWidthCoefficient(): number; protected processSubpath(path: Path2D, startPoint: Vector2 | null, endPoint: Vector2 | null): void; protected tweenData(newPath: SignalValue, time: number, timingFunction: TimingFunction): Generator | _twick_core.Promisable, void, any>; drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix): void; } interface PolygonProps extends CurveProps { /** * {@inheritDoc Polygon.sides} */ sides?: SignalValue; /** * {@inheritDoc Polygon.radius} */ radius?: SignalValue; } /** * A node for drawing regular polygons. * * @remarks * This node can be used to render shapes such as: triangle, pentagon, * hexagon and more. * * Note that the polygon is inscribed in a circle defined by the height * and width. If height and width are unequal, the polygon is inscribed * in the resulting ellipse. * * Since the polygon is inscribed in the circle, the actual displayed * height and width may differ somewhat from the bounding rectangle. This * will be particularly noticeable if the number of sides is low, e.g. for a * triangle. * * @preview * ```tsx editor * // snippet Polygon * import {makeScene2D, Polygon} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const ref = createRef(); * view.add( * * ); * * yield* ref().sides(3, 2).to(6, 2); * }); * * // snippet Pentagon outline * import {makeScene2D, Polygon} from '@twick/2d'; * * export default makeScene2D(function* (view) { * view.add( * * ); * }); * ``` */ declare class Polygon extends Curve { /** * The number of sides of the polygon. * * @remarks * For example, a value of 6 creates a hexagon. * * @example * ```tsx * * ``` */ readonly sides: SimpleSignal; /** * The radius of the polygon's corners. * * @example * ```tsx * * ``` */ readonly radius: SimpleSignal; constructor(props: PolygonProps); profile(): CurveProfile; protected desiredSize(): SerializedVector2; protected offsetComputedLayout(box: BBox): BBox; protected childrenBBox(): BBox; protected requiresProfile(): boolean; protected getPath(): Path2D; protected getRipplePath(): Path2D; protected createPath(expand?: number): Path2D; } interface QuadBezierProps extends CurveProps { p0?: SignalValue; p0X?: SignalValue; p0Y?: SignalValue; p1?: SignalValue; p1X?: SignalValue; p1Y?: SignalValue; p2?: SignalValue; p2X?: SignalValue; p2Y?: SignalValue; } /** * A node for drawing a quadratic Bézier curve. * * @preview * ```tsx editor * import {makeScene2D, QuadBezier} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const bezier = createRef(); * * view.add( * * ); * * yield* bezier().end(1, 1); * yield* bezier().start(1, 1).to(0, 1); * }); * ``` */ declare class QuadBezier extends Bezier { /** * The start point of the Bézier curve. */ readonly p0: Vector2Signal; /** * The control point of the Bézier curve. */ readonly p1: Vector2Signal; /** * The end point of the Bézier curve. */ readonly p2: Vector2Signal; constructor(props: QuadBezierProps); protected segment(): PolynomialSegment; protected overlayInfo(matrix: DOMMatrix): BezierOverlayInfo; } interface RayProps extends CurveProps { /** * {@inheritDoc Ray.from} */ from?: SignalValue; fromX?: SignalValue; fromY?: SignalValue; /** * {@inheritDoc Ray.to} */ to?: SignalValue; toX?: SignalValue; toY?: SignalValue; } /** * A node for drawing an individual line segment. * * @preview * ```tsx editor * import {makeScene2D} from '@twick/2d'; * import {Ray} from '@twick/2d'; * import {createRef} from '@twick/core'; * * export default makeScene2D(function* (view) { * const ray = createRef(); * * view.add( * , * ); * * yield* ray().start(1, 1); * yield* ray().start(0).end(0).start(1, 1); * }); * ``` */ declare class Ray extends Curve { /** * The starting point of the ray. */ readonly from: Vector2Signal; /** * The ending point of the ray. */ readonly to: Vector2Signal; constructor(props: RayProps); protected childrenBBox(): BBox; profile(): CurveProfile; drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix): void; } interface RiveProps extends RectProps { src?: SignalValue; artboardId?: SignalValue; animationId?: SignalValue; } declare class Rive extends Rect { readonly src: SimpleSignal; readonly artboardId: SimpleSignal; readonly animationId: SimpleSignal; protected readonly time: SimpleSignal; protected currentTime: number; protected lastTime: number; constructor(props: RiveProps); private rive; protected draw(context: CanvasRenderingContext2D): Promise; private getArtboard; private getAnimation; } interface SplineProps extends CurveProps { /** * {@inheritDoc Spline.smoothness} */ smoothness?: SignalValue; /** * {@inheritDoc Spline.points} */ points?: SignalValue>; } /** * A node for drawing a smooth line through a number of points. * * @remarks * This node uses Bézier curves for drawing each segment of the spline. * * @example * Defining knots using the `points` property. This will automatically * calculate the handle positions for each knot do draw a smooth curve. You * can control the smoothness of the resulting curve via the * {@link Spline.smoothness} property: * * ```tsx * * ``` * * Defining knots with {@link Knot} nodes: * * ```tsx * * * * * * * * ``` */ declare class Spline extends Curve { /** * The smoothness of the spline when using auto-calculated handles. * * @remarks * This property is only applied to knots that don't use explicit handles. * * @defaultValue 0.4 */ readonly smoothness: SimpleSignal; /** * The knots of the spline as an array of knots with auto-calculated handles. * * @remarks * You can control the smoothness of the resulting curve * via the {@link smoothness} property. */ readonly points: SimpleSignal[] | null, this>; constructor(props: SplineProps); profile(): CurveProfile; knots(): KnotInfo[]; protected childrenBBox(): BBox; protected lineWidthCoefficient(): number; protected desiredSize(): SerializedVector2; protected offsetComputedLayout(box: BBox): BBox; private getTightBBox; drawOverlay(context: CanvasRenderingContext2D, matrix: DOMMatrix): void; private isKnot; } /** * Represent SVG shape. * This only used single time because `node` may have reference to parent SVG renderer. */ interface SVGShape { id: string; shape: Node; } /** * Data of SVGShape. * This can used many times because it do not reference parent SVG. * This must build into SVGShape */ interface SVGShapeData { id: string; type: new (props: NodeProps) => Node; props: ShapeProps; children?: SVGShapeData[]; } /** * Represent SVG document that contains SVG shapes. * This only used single time because `nodes` have reference to parent SVG renderer. */ interface SVGDocument { size: Vector2; nodes: SVGShape[]; } /** * Data of SVGDocument. * This can used many times because it do not reference parent SVG. * This must build into SVGDocument */ interface SVGDocumentData { size: Vector2; nodes: SVGShapeData[]; } interface SVGProps extends ShapeProps { svg: SignalValue; } /** A Node for drawing and animating SVG images. @remarks If you're not interested in animating SVG, you can use {@link Img} instead. */ declare class SVG extends Shape { protected static containerElement: HTMLDivElement; private static svgNodesPool; /** * SVG string to be rendered */ readonly svg: SimpleSignal; /** * Child to wrap all SVG node */ wrapper: Node; private lastTweenTargetSrc; private lastTweenTargetDocument; constructor(props: SVGProps); /** * Get all SVG nodes with the given id. * @param id - An id to query. */ getChildrenById(id: string): Node[]; protected desiredSize(): SerializedVector2; protected getCurrentSize(): { x: number | null; y: number | null; }; protected calculateWrapperScale(documentSize: Vector2, parentSize: SerializedVector2): Vector2; /** * Convert `SVGDocumentData` to `SVGDocument`. * @param data - `SVGDocumentData` to convert. */ protected buildDocument(data: SVGDocumentData): SVGDocument; /** * Convert `SVGShapeData` to `SVGShape`. * @param data - `SVGShapeData` to convert. */ protected buildShape({ id, type, props, children }: SVGShapeData): SVGShape; /** * Convert an SVG string to `SVGDocument`. * @param svg - An SVG string to be parsed. */ protected parseSVG(svg: string): SVGDocument; /** * Create a tweening list to tween between two SVG nodes. * @param from - The initial node, * @param to - The final node. * @param duration - The duration of the tween. * @param timing - The timing function. */ protected generateTransformer(from: Node, to: Node, duration: number, timing: TimingFunction): Generator; protected tweenSvg(value: SignalValue, time: number, timingFunction: TimingFunction): Generator | _twick_core.Promisable, void, any>; private wrapperScale; /** * Get the current `SVGDocument`. */ private document; /** * Get current document nodes. */ private documentNodes; /** * Convert SVG colors in Shape properties to Motion Canvas colors. * @param param - Shape properties. * @returns Converted Shape properties. */ private processElementStyle; /** * Parse an SVG string as `SVGDocumentData`. * @param svg - And SVG string to be parsed. * @returns `SVGDocumentData` that can be used to build SVGDocument. */ protected static parseSVGData(svg: string): SVGDocumentData; /** * Get position, rotation and scale from Matrix transformation as Shape properties * @param transform - Matrix transformation * @returns MotionCanvas Shape properties */ protected static getMatrixTransformation(transform: DOMMatrix): ShapeProps; /** * Convert an SVG color into a Motion Canvas color. * @param color - SVG color. * @returns Motion Canvas color. */ private static processSVGColor; /** * Get the final transformation matrix for the given SVG element. * @param element - SVG element. * @param parentTransform - The transformation matrix of the parent. */ private static getElementTransformation; private static parseLineCap; private static parseLineJoin; private static parseLineDash; private static parseDashOffset; private static parseOpacity; /** * Convert the SVG element's style to a Motion Canvas Shape properties. * @param element - An SVG element whose style should be converted. * @param inheritedStyle - The parent style that should be inherited. */ private static getElementStyle; /** * Extract `SVGShapeData` list from the SVG element's children. * This will not extract the current element's shape. * @param element - An element whose children will be extracted. * @param svgRoot - The SVG root ("svg" tag) of the element. * @param parentTransform - The transformation matrix applied to the parent. * @param inheritedStyle - The style of the current SVG `element` that the children should inherit. */ private static extractGroupNodes; /** * Parse a number from an SVG element attribute. * @param element - SVG element whose attribute will be parsed. * @param name - The name of the attribute to parse. * @returns a parsed number or `0` if the attribute is not defined. */ private static parseNumberAttribute; /** * Extract `SVGShapeData` list from the SVG element. * This will also recursively extract shapes from its children. * @param child - An SVG element to extract. * @param svgRoot - The SVG root ("svg" tag) of the element. * @param parentTransform - The transformation matrix applied to the parent. * @param inheritedStyle - The style of the parent SVG element that the element should inherit. */ private static extractElementNodes; } interface TxtLeafProps extends ShapeProps { children?: string; text?: SignalValue; } declare const TXT_TYPE: unique symbol; declare class TxtLeaf extends Shape { protected static readonly segmenter: any; readonly text: SimpleSignal; constructor({ children, ...rest }: TxtLeafProps); protected parentTxt(): (Node & Record) | null; protected draw(context: CanvasRenderingContext2D): Promise; protected drawText(context: CanvasRenderingContext2D, text: string, box: BBox): Promise; protected getCacheBBox(): BBox; protected applyFlex(): void; protected updateLayout(): void; } type TxtChildren = string | Node | (string | Node)[]; type AnyTxt = Txt | TxtLeaf; interface TxtProps extends ShapeProps { children?: TxtChildren; text?: SignalValue; } declare class Txt extends Shape { readonly [TXT_TYPE] = true; /** * Create a bold text node. * * @remarks * This is a shortcut for * ```tsx * * ``` * * @param props - Additional text properties. */ static b(props: TxtProps): Txt; /** * Create an italic text node. * * @remarks * This is a shortcut for * ```tsx * * ``` * * @param props - Additional text properties. */ static i(props: TxtProps): Txt; readonly text: SimpleSignal; protected getText(): string; protected setText(value: SignalValue): void; protected setChildren(value: SignalValue): void; protected tweenText(value: SignalValue, time: number, timingFunction: TimingFunction, interpolationFunction: InterpolationFunction): ThreadGenerator; protected getLayout(): boolean; constructor({ children, text, ...props }: TxtProps); protected innerText(): string; protected parentTxt(): Txt | null; protected parseChildren(children: ComponentChildren): AnyTxt[]; protected applyFlex(): void; protected draw(context: CanvasRenderingContext2D): Promise; } interface VideoProps extends MediaProps { /** * {@inheritDoc Video.alpha} */ alpha?: SignalValue; /** * {@inheritDoc Video.smoothing} */ smoothing?: SignalValue; /** * {@inheritDoc Video.decoder} */ decoder?: SignalValue<'web' | 'ffmpeg' | 'slow' | null>; } declare class Video extends Media { /** * The alpha value of this video. * * @remarks * Unlike opacity, the alpha value affects only the video itself, leaving the * fill, stroke, and children intact. */ readonly alpha: SimpleSignal; /** * Whether the video should be smoothed. * * @remarks * When disabled, the video will be scaled using the nearest neighbor * interpolation with no smoothing. The resulting video will appear pixelated. * * @defaultValue true */ readonly smoothing: SimpleSignal; /** * Which decoder to use during rendering. The `web` decoder is the fastest * but only supports MP4 files. The `ffmpeg` decoder is slower and more resource * intensive but supports more formats. The `slow` decoder is the slowest but * supports all formats. * * @defaultValue null */ readonly decoder: SimpleSignal<'web' | 'ffmpeg' | 'slow' | null, this>; detectedFileType: 'mp4' | 'webm' | 'hls' | 'mov' | 'unknown'; private fileTypeWasDetected; /** * Static pool of video elements cached by source URL. * Multiple Video components with the same src will share the same HTMLVideoElement * to avoid duplicate network requests and improve performance. */ private static readonly pool; private static readonly imageCommunication; constructor(props: VideoProps); dispose(): void; /** * Creates a video element with CORS fallback handling. * First tries with crossOrigin='anonymous', and if that fails due to CORS, * falls back to creating a video without crossOrigin. */ private createVideoElement; protected desiredSize(): SerializedVector2; protected mediaElement(): HTMLVideoElement; protected seekedMedia(): HTMLVideoElement; protected fastSeekedMedia(): HTMLVideoElement; /** * Generates a normalized cache key based on the video source URL. * This ensures that all Video elements with the same src share the same HTMLVideoElement. */ private getCacheKey; private video; protected seekedVideo(): HTMLVideoElement; protected fastSeekedVideo(): HTMLVideoElement; protected lastFrame: ImageBitmap | null; protected webcodecSeekedVideo(): Promise; protected ffmpegSeekedVideo(): Promise; protected seekFunction(): Promise; protected draw(context: CanvasRenderingContext2D): Promise; protected applyFlex(): void; remove(): this; private handleUnknownFileType; private detectFileType; } interface CodeMetrics { content: string; newRows: number; endColumn: number; firstWidth: number; maxWidth: number; lastWidth: number; } interface CodeFragment { before: CodeMetrics; after: CodeMetrics; } interface RawCodeFragment { before: string; after: string; } type PossibleCodeFragment = CodeFragment | CodeMetrics | RawCodeFragment | string; declare function metricsToFragment(value: CodeMetrics): CodeFragment; declare function parseCodeFragment(value: PossibleCodeFragment, context: CanvasRenderingContext2D, monoWidth: number): CodeFragment; /** * Create a code fragment that represents an insertion of code. * * @remarks * Can be used in conjunction with {@link code.CodeSignalHelpers.edit}. * * @param code - The code to insert. */ declare function insert(code: string): RawCodeFragment; /** * Create a code fragment that represents a change from one piece of code to * another. * * @remarks * Can be used in conjunction with {@link code.CodeSignalHelpers.edit}. * * @param before - The code to change from. * @param after - The code to change to. */ declare function replace(before: string, after: string): RawCodeFragment; /** * Create a code fragment that represents a removal of code. * * @remarks * Can be used in conjunction with {@link code.CodeSignalHelpers.edit}. * * @param code - The code to remove. */ declare function remove(code: string): RawCodeFragment; interface CodeScope { progress: SignalValue; fragments: CodeTag[]; } type PossibleCodeScope = CodeScope | CodeTag[] | string; type CodeTag = SignalValue; declare function CODE(strings: TemplateStringsArray, ...tags: CodeTag[]): CodeTag[]; declare function isCodeScope(value: any): value is CodeScope; declare function parseCodeScope(value: PossibleCodeScope): CodeScope; type IsAfterPredicate = ((scope: CodeScope) => boolean) | boolean; declare function resolveScope(scope: CodeScope, isAfter: IsAfterPredicate): string; declare function resolveCodeTag(wrapped: CodeTag, after: boolean, isAfter?: IsAfterPredicate): string; interface CodeFragmentDrawingInfo { text: string; position: Vector2; characterSize: Vector2; cursor: Vector2; fill: string; time: number; alpha: number; } /** * A stateful class for recursively traversing a code scope. * * @internal */ declare class CodeCursor { private readonly node; cursor: Vector2; beforeCursor: Vector2; afterCursor: Vector2; beforeIndex: number; afterIndex: number; private context; private monoWidth; private maxWidth; private lineHeight; private fallbackFill; private caches; private highlighter; private selection; private selectionProgress; private globalProgress; private fragmentDrawingInfo; private fontHeight; private verticalOffset; constructor(node: Code); /** * Prepare the cursor for the next traversal. * * @param context - The context used to measure and draw the code. */ setupMeasure(context: CanvasRenderingContext2D): void; setupDraw(context: CanvasRenderingContext2D): void; /** * Measure the desired size of the code scope. * * @remarks * The result can be retrieved with {@link getSize}. * * @param scope - The code scope to measure. */ measureSize(scope: CodeScope): void; /** * Get the size measured by the cursor. */ getSize(): { x: number; y: number; }; /** * Get the drawing information created by the cursor. */ getDrawingInfo(): { fragments: CodeFragmentDrawingInfo[]; verticalOffset: number; fontHeight: number; }; /** * Draw the given code scope. * * @param scope - The code scope to draw. */ drawScope(scope: CodeScope): void; private drawToken; private calculateWidth; private calculateMaxWidth; private currentProgress; private processSelection; private isSelected; } type CodeTokenizer = (input: string) => string[]; /** * Default tokenizer function used by ownerless code signals. * * @param input - The code to tokenize. */ declare function defaultTokenize(input: string): string[]; /** * A function that compares two code snippets and returns a list of * {@link CodeTag}s describing a transition between them. */ type CodeDiffer = ( /** * The original code scope. */ from: CodeScope, /** * The new code scope. */ to: CodeScope, /** * The inherited tokenizer to use. */ tokenize: CodeTokenizer) => CodeTag[]; /** * Default diffing function utilizing {@link code.patienceDiff}. * * @param from - The original code scope. * @param to - The new code scope. * @param tokenize - The inherited tokenizer to use. */ declare function defaultDiffer(from: CodeScope, to: CodeScope, tokenize: CodeTokenizer): CodeTag[]; /** * Describes the result of a highlight operation. */ interface HighlightResult { /** * The color of the code at the given index. */ color: string | null; /** * The number of characters to skip ahead. * * @remarks * This should be used to skip to the end of the currently highlighted token. * The returned style will be used for the skipped characters, and they will * be drawn as one continuous string keeping emojis and ligatures intact. * * The returned value is the number of characters to skip ahead, not the * index of the end of the token. */ skipAhead: number; } /** * Describes custom highlighters used by the Code node. * * @typeParam T - The type of the cache used by the highlighter. */ interface CodeHighlighter { /** * Initializes the highlighter. * * @remarks * This method is called when collecting async resources for the node. * It can be called multiple times so caching the initialization is * recommended. * * If initialization is asynchronous, a promise should be registered using * {@link DependencyContext.collectPromise} and the value of `false` should * be returned. The hook will be called again when the promise resolves. * This process can be repeated until the value of `true` is returned which * will mark the highlighter as ready. */ initialize(): boolean; /** * Prepares the code for highlighting. * * @remarks * This method is called each time the code changes. It can be used to do * any preprocessing of the code before highlighting. The result of this * method is cached and passed to {@link highlight} when the code is * highlighted. * * @param code - The code to prepare. * @param dialect - The language in which the code is written. */ prepare(code: string): T; /** * Highlights the code at the given index. * * @param index - The index of the code to highlight. * @param cache - The result of {@link prepare}. */ highlight(index: number, cache: T): HighlightResult; /** * Tokenize the code. * * @param code - The code to tokenize. * @param dialect - The language in which the code is written. */ tokenize(code: string): string[]; } type CodePoint = [number, number]; type CodeRange = [CodePoint, CodePoint]; declare function isCodeRange(value: unknown): value is CodeRange; /** * Create a code range that spans the given lines. * * @param from - The line from which the range starts. * @param to - The line at which the range ends. If omitted, the range will * cover only one line. */ declare function lines(from: number, to?: number): CodeRange; /** * Create a code range that highlights the given word. * * @param line - The line at which the word appears. * @param from - The column at which the word starts. * @param length - The length of the word. If omitted, the range will cover the * rest of the line. */ declare function word(line: number, from: number, length?: number): CodeRange; /** * Create a custom selection range. * * @param startLine - The line at which the selection starts. * @param startColumn - The column at which the selection starts. * @param endLine - The line at which the selection ends. * @param endColumn - The column at which the selection ends. */ declare function pointToPoint(startLine: number, startColumn: number, endLine: number, endColumn: number): CodeRange; declare function isPointInCodeRange(point: CodePoint, range: CodeRange): boolean; declare function consolidateCodeRanges(ranges: CodeRange[]): CodeRange[]; declare function inverseCodeRange(ranges: CodeRange[]): CodeRange[]; /** * Find all code ranges that match the given pattern. * * @param code - The code to search in. * @param pattern - Either a string or a regular expression to search for. * @param limit - An optional limit on the number of ranges to find. */ declare function findAllCodeRanges(code: string, pattern: string | RegExp, limit?: number): CodeRange[]; type CodeSelection = CodeRange[]; type PossibleCodeSelection = CodeRange | CodeRange[]; declare function parseCodeSelection(value: PossibleCodeSelection): CodeSelection; declare function isPointInCodeSelection(point: CodePoint, selection: CodeSelection): boolean; interface CodeModifier { (code: string): TOwner; (code: string, duration: number): ThreadGenerator; (duration?: number): TagGenerator; } interface CodeInsert { (point: CodePoint, code: string): TOwner; (point: CodePoint, code: string, duration: number): ThreadGenerator; } interface CodeRemove { (range: CodeRange): TOwner; (range: CodeRange, duration: number): ThreadGenerator; } interface CodeReplace { (range: CodeRange, code: string): TOwner; (range: CodeRange, code: string, duration: number): ThreadGenerator; } type TagGenerator = (strings: TemplateStringsArray, ...tags: CodeTag[]) => ThreadGenerator; interface CodeSignalHelpers { edit(duration?: number): TagGenerator; append: CodeModifier; prepend: CodeModifier; insert: CodeInsert; remove: CodeRemove; replace: CodeReplace; } type CodeSignal = Signal> & CodeSignalHelpers; declare class CodeSignalContext extends SignalContext implements CodeSignalHelpers { private readonly highlighter?; private readonly progress; constructor(initial: PossibleCodeScope, owner: TOwner, highlighter?: SignalValue | undefined); tweener(value: SignalValue, duration: number, timingFunction: TimingFunction): ThreadGenerator; edit(duration?: number): TagGenerator; append(code: string): TOwner; append(code: string, duration: number): ThreadGenerator; append(duration?: number): TagGenerator; prepend(code: string): TOwner; prepend(code: string, duration: number): ThreadGenerator; prepend(duration?: number): TagGenerator; insert(point: CodePoint, code: string): TOwner; insert(point: CodePoint, code: string, duration: number): ThreadGenerator; remove(range: CodeRange): TOwner; remove(range: CodeRange, duration: number): ThreadGenerator; replace(range: CodeRange, code: string): TOwner; replace(range: CodeRange, code: string, duration: number): ThreadGenerator; private replaceTween; private editTween; private appendTween; private prependTween; parse(value: PossibleCodeScope): CodeScope; toSignal(): CodeSignal; } declare function codeSignal(): PropertyDecorator; declare const DefaultHighlightStyle: HighlightStyle; /** * Performs a patience diff on two arrays of strings, returning an object * containing the lines that were deleted, inserted, and potentially moved * lines. The plus parameter can result in a significant performance hit due * to additional Longest Common Substring searches. * * @param aLines - The original array of strings * @param bLines - The new array of strings * @param plus - Whether to return the moved lines * * Adapted from Jonathan "jonTrent" Trent's patience-diff algorithm. * Types and tests added by Hunter "hhenrichsen" Henrichsen. * * {@link https://github.com/jonTrent/PatienceDiff} */ declare function patienceDiff(aLines: string[], bLines: string[]): { lines: { line: string; aIndex: number; bIndex: number; }[]; lineCountDeleted: number; lineCountInserted: number; }; /** * Utility function for debugging patienceDiff. * * @internal */ declare function printDiff(diff: ReturnType): void; /** * Transform the fragments to isolate the given range into its own fragment. * * @remarks * This function will try to preserve the original fragments, resolving them * only if they overlap with the range. * * @param range - The range to extract. * @param fragments - The fragments to transform. * * @returns A tuple containing the transformed fragments and the index of the * isolated fragment within. */ declare function extractRange(range: CodeRange, fragments: CodeTag[]): [CodeTag[], number]; interface LezerCache { tree: Tree; code: string; colorLookup: Map; } declare class LezerHighlighter implements CodeHighlighter { private readonly parser; private readonly style; private static classRegex; private readonly classLookup; constructor(parser: Parser, style?: HighlightStyle); initialize(): boolean; prepare(code: string): LezerCache | null; highlight(index: number, cache: LezerCache | null): HighlightResult; tokenize(code: string): string[]; private getNodeId; } declare class Scene2D extends GeneratorScene implements Inspectable { private view; private registeredNodes; private readonly nodeCounters; private assetHash; constructor(description: FullSceneDescription>); getView(): View2D; next(): Promise; draw(context: CanvasRenderingContext2D): Promise; reset(previousScene?: Scene): Promise; inspectPosition(x: number, y: number): InspectedElement | null; getNodeByPosition(x: number, y: number): Node | null; validateInspection(element: InspectedElement | null): InspectedElement | null; inspectAttributes(element: InspectedElement): InspectedAttributes | null; drawOverlay(element: InspectedElement, matrix: DOMMatrix, context: CanvasRenderingContext2D): void; transformMousePosition(x: number, y: number): Vector2 | null; registerNode(node: Node, key?: string): [string, () => void]; getNode(key: any): Node | null; getDetachedNodes(): Generator; getMediaAssets(): Array; /** * Seek all registered Media nodes (Video and Audio) to the current playback time. * Passes draw time; nodes with clipStart convert it to clip-relative time. * When waitForSeek is true, waits for each media seek to complete so the next draw shows the correct frame/sample. */ private syncAllMediaToCurrentTime; stopAllMedia(): void; adjustVolume(volumeScale: number): void; protected recreateView(): void; } declare function makeScene2D(name: string, runner: ThreadGeneratorFactory): DescriptionOf; declare function useScene2D(): Scene2D; declare function canvasStyleParser(style: PossibleCanvasStyle): Color | Gradient | Pattern | null; declare function resolveCanvasStyle(style: CanvasStyle, context: CanvasRenderingContext2D): string | CanvasGradient | CanvasPattern; declare function drawRoundRect(context: CanvasRenderingContext2D | Path2D, rect: BBox, radius: Spacing, smoothCorners: boolean, cornerSharpness: number): void; declare function adjustRectRadius(radius: number, horizontal: number, vertical: number, rect: BBox): number; declare function drawRect(context: CanvasRenderingContext2D | Path2D, rect: BBox): void; declare function fillRect(context: CanvasRenderingContext2D, rect: BBox): void; declare function strokeRect(context: CanvasRenderingContext2D, rect: BBox): void; declare function drawPolygon(path: CanvasRenderingContext2D | Path2D, rect: BBox, sides: number): void; declare function drawImage(context: CanvasRenderingContext2D, image: CanvasImageSource, destination: BBox): void; declare function drawImage(context: CanvasRenderingContext2D, image: CanvasImageSource, source: BBox, destination: BBox): void; declare function moveTo(context: CanvasRenderingContext2D | Path2D, position: Vector2): void; declare function lineTo(context: CanvasRenderingContext2D | Path2D, position: Vector2): void; declare function arcTo(context: CanvasRenderingContext2D | Path2D, through: Vector2, position: Vector2, radius: number): void; declare function drawLine(context: CanvasRenderingContext2D | Path2D, points: Vector2[]): void; declare function drawPivot(context: CanvasRenderingContext2D | Path2D, offset: Vector2, radius?: number): void; declare function arc(context: CanvasRenderingContext2D | Path2D, center: Vector2, radius: number, startAngle?: number, endAngle?: number, counterclockwise?: boolean): void; declare function bezierCurveTo(context: CanvasRenderingContext2D | Path2D, controlPoint1: Vector2, controlPoint2: Vector2, to: Vector2): void; declare function quadraticCurveTo(context: CanvasRenderingContext2D | Path2D, controlPoint: Vector2, to: Vector2): void; /** * Create a predicate that checks if the given object is an instance of the * given class. * * @param klass - The class to check against. */ declare function is(klass: new (...args: any[]) => T): (object: any) => object is T; export { Audio, Bezier, type BezierOverlayInfo, CODE, CanvasStyle, Circle, type CircleProps, CircleSegment, Code, CodeCursor, type CodeDiffer, type CodeFragment, type CodeFragmentDrawingInfo, type CodeHighlighter, type CodePoint, type CodeProps, type CodeRange, type CodeScope, type CodeSelection, type CodeSignal, CodeSignalContext, type CodeSignalHelpers, type CodeTag, type CodeTokenizer, ComponentChildren, CubicBezier, type CubicBezierProps, CubicBezierSegment, Curve, CurvePoint, CurveProfile, CurveProps, DefaultHighlightStyle, DesiredLength, type DrawHooks, type DrawTokenHook, Gradient, Grid, type GridProps, type HighlightResult, Icon, type IconProps, Img, type ImgProps, type Initializer, Knot, type KnotAuto, type KnotAutoHandles, type KnotAutoSignal, type KnotInfo, type KnotProps, Latex, type LatexProps, LezerHighlighter, Line, type LineProps, LineSegment, Media, type MediaProps, Node, NodeProps, Path, type PathProps, Pattern, Polygon, type PolygonProps, Polynomial, Polynomial2D, PossibleCanvasStyle, type PossibleCodeFragment, type PossibleCodeScope, type PossibleCodeSelection, type PossibleKnotAuto, QuadBezier, type QuadBezierProps, QuadBezierSegment, type RawCodeFragment, Ray, type RayProps, Rect, RectProps, Rive, type RiveProps, SVG, type SVGDocument, type SVGDocumentData, type SVGProps, type SVGShape, type SVGShapeData, Scene2D, Segment, Shape, ShapeProps, Spline, type SplineProps, Txt, type TxtProps, Video, type VideoProps, View2D, addInitializer, adjustRectRadius, arc, arcTo, bezierCurveTo, canvasStyleParser, codeSignal, colorSignal, compound, computed, consolidateCodeRanges, defaultDiffer, defaultStyle, defaultTokenize, drawImage, drawLine, drawPivot, drawPolygon, drawRect, drawRoundRect, extractRange, fillRect, findAllCodeRanges, getBezierSplineProfile, getCircleProfile, getPointAtDistance, getPolylineProfile, getRectProfile, initialize, insert, inverseCodeRange, is, isCodeRange, isCodeScope, isPointInCodeRange, isPointInCodeSelection, lineTo, lines, makeScene2D, metricsToFragment, moveTo, parseCodeFragment, parseCodeScope, parseCodeSelection, patienceDiff, pointToPoint, printDiff, quadraticCurveTo, remove, replace, resolveCanvasStyle, resolveCodeTag, resolveScope, strokeRect, useScene2D, word };