Skip to main content

Code

class Code extends Shape

A node for displaying and animating code.

Press play to preview the animation
import ...

export default makeScene2D(function* (view) {
const code = createRef<Code>();

view.add(
<Code
ref={code}
offset={-1}
position={view.size().scale(-0.5).add(60)}
fontFamily={'JetBrains Mono, monospace'}
fontSize={36}
code={`\
function hello() {
console.log('Hello');
}`}
/>,
);

yield* code()
.code(
`\
function hello() {
console.warn('Hello World');
}`,
1,
)
.wait(0.5)
.back(1)
.wait(0.5);
});

Constructors

constructor

public override new Codeprops: CodeProps: Code

Parameters

Overwrites Shape.constructor

Properties

absolutePosition

A helper signal for operating on the position in world space.

Retrieving the position using this signal returns the position in world space. Similarly, setting the position using this signal transforms the new value to local space.

If the new value is a function, the position of this node will be continuously updated to always match the position returned by the function. This can be useful to "pin" the node in a specific place or to make it follow another node's position.

Unlike position, this signal is not compound - it doesn't contain separate signals for the x and y components.

Inherited from Shape.absolutePosition

absoluteRotation

readonly public absoluteRotation: SimpleSignalnumberCode

A helper signal for operating on the rotation in world space.

Retrieving the rotation using this signal returns the rotation in world space. Similarly, setting the rotation using this signal transforms the new value to local space.

If the new value is a function, the rotation of this node will be continuously updated to always match the rotation returned by the function.

Inherited from Shape.absoluteRotation

absoluteScale

A helper signal for operating on the scale in world space.

Retrieving the scale using this signal returns the scale in world space. Similarly, setting the scale using this signal transforms the new value to local space.

If the new value is a function, the scale of this node will be continuously updated to always match the position returned by the function.

Unlike scale, this signal is not compound - it doesn't contain separate signals for the x and y components.

Inherited from Shape.absoluteScale

alignContent

Inherited from Shape.alignContent

alignItems

Inherited from Shape.alignItems

alignSelf

Inherited from Shape.alignSelf

antialiased

readonly public antialiased: SimpleSignalbooleanCode
Inherited from Shape.antialiased

basis

Inherited from Shape.basis

bottom

The position of the bottom edge of this node.

When set, this shortcut property will modify the node's position so that the bottom edge ends up in the given place.

When retrieved, it will return the position of the bottom edge in the parent space.

Inherited from Shape.bottom

bottomLeft

The position of the bottom left corner of this node.

When set, this shortcut property will modify the node's position so that the bottom left corner ends up in the given place.

When retrieved, it will return the position of the bottom left corner in the parent space.

Inherited from Shape.bottomLeft

bottomRight

The position of the bottom right corner of this node.

When set, this shortcut property will modify the node's position so that the bottom right corner ends up in the given place.

When retrieved, it will return the position of the bottom right corner in the parent space.

Inherited from Shape.bottomRight

cache

readonly public cache: SimpleSignalbooleanCode
Inherited from Shape.cache

cachePadding

Controls the padding of the cached canvas used by this node.

By default, the size of the cache is determined based on the bounding box of the node and its children. That includes effects such as stroke or shadow. This property can be used to expand the cache area further. Usually used to account for custom effects created by shaders.

Inherited from Shape.cachePadding

children

Inherited from Shape.children

clip

readonly public clip: SimpleSignalbooleanCode
Inherited from Shape.clip

code

readonly public code: CodeSignalCode

The code to display.


composite

readonly public composite: SimpleSignalbooleanCode
Inherited from Shape.composite

compositeOperation

readonly public compositeOperation: SimpleSignalGlobalCompositeOperationCode
Inherited from Shape.compositeOperation

creationStack

readonly public creationStack?: string
Inherited from Shape.creationStack

direction

Inherited from Shape.direction

drawHooks

Experimental
This is an experimental feature. The behavior and API may change drastically between minor releases.

Custom drawing logic for the code.

Check out DrawHooks for available render hooks.

Examples


element

Inherited from Shape.element

fill

readonly public fill: CanvasStyleSignalCode
Inherited from Shape.fill

filters

readonly public filters: FiltersSignalCode
Inherited from Shape.filters

fontFamily

readonly public fontFamily: SimpleSignalstringCode
Inherited from Shape.fontFamily

fontSize

readonly public fontSize: SimpleSignalnumberCode
Inherited from Shape.fontSize

fontStyle

readonly public fontStyle: SimpleSignalstringCode
Inherited from Shape.fontStyle

fontWeight

readonly public fontWeight: SimpleSignalnumberCode
Inherited from Shape.fontWeight

gap

readonly public gap: Vector2LengthSignalCode
Inherited from Shape.gap

grow

readonly public grow: SimpleSignalnumberCode
Inherited from Shape.grow

highlighter

readonly public highlighter: SimpleSignalnullCodeHighlighterunknownCode

The code highlighter to use for this code node.

Defaults to a shared LezerHighlighter.


isClass

public isClass: boolean
Inherited from Shape.isClass

justifyContent

Inherited from Shape.justifyContent

key

readonly public key: string
Inherited from Shape.key

layout

Inherited from Shape.layout

left

readonly public left: SimpleVector2SignalCode

The position of the left edge of this node.

When set, this shortcut property will modify the node's position so that the left edge ends up in the given place.

When retrieved, it will return the position of the left edge in the parent space.

Inherited from Shape.left

letterSpacing

readonly public letterSpacing: SimpleSignalnumberCode
Inherited from Shape.letterSpacing

lineCap

readonly public lineCap: SimpleSignalCanvasLineCapCode
Inherited from Shape.lineCap

lineDash

readonly public lineDash: SimpleSignalnumber[]Code
Inherited from Shape.lineDash

lineDashOffset

readonly public lineDashOffset: SimpleSignalnumberCode
Inherited from Shape.lineDashOffset

lineHeight

Inherited from Shape.lineHeight

lineJoin

readonly public lineJoin: SimpleSignalCanvasLineJoinCode
Inherited from Shape.lineJoin

lineWidth

readonly public lineWidth: SimpleSignalnumberCode
Inherited from Shape.lineWidth

margin

readonly public margin: SpacingSignalCode
Inherited from Shape.margin

maxHeight

Inherited from Shape.maxHeight

maxWidth

Inherited from Shape.maxWidth

middle

The position of the center of this node.

When set, this shortcut property will modify the node's position so that the center ends up in the given place.

If the offset has not been changed, this will be the same as the position.

When retrieved, it will return the position of the center in the parent space.

Inherited from Shape.middle

minHeight

Inherited from Shape.minHeight

minWidth

Inherited from Shape.minWidth

offset

Represents the offset of this node's origin.

By default, the origin of a node is located at its center. The origin serves as the pivot point when rotating and scaling a node, but it doesn't affect the placement of its children.

The value is relative to the size of this node. A value of 1 means as far to the right/bottom as possible. Here are a few examples of offsets:

  • [-1, -1] - top left corner
  • [1, -1] - top right corner
  • [0, 1] - bottom edge
  • [-1, 1] - bottom left corner
Inherited from Shape.offset

oldSelection

public oldSelection: nullCodeSelection = null

opacity

readonly public opacity: SimpleSignalnumberCode

Represents the opacity of this node in the range 0-1.

The value is clamped to the range 0-1.

Inherited from Shape.opacity

padding

readonly public padding: SpacingSignalCode
Inherited from Shape.padding

parent

readonly public parent: SimpleSignalnullNodevoid = ...
Inherited from Shape.parent

position

Represents the position of this node in local space of its parent.

Examples

Inherited from Shape.position

properties

readonly public properties: RecordstringPropertyMetadataany = ...
Inherited from Shape.properties

ratio

readonly public ratio: SimpleSignalnullnumberCode
Inherited from Shape.ratio

The position of the right edge of this node.

When set, this shortcut property will modify the node's position so that the right edge ends up in the given place.

When retrieved, it will return the position of the right edge in the parent space.

Inherited from Shape.right

rotation

readonly public rotation: SimpleSignalnumberCode

Represents the rotation (in degrees) of this node relative to its parent.

Inherited from Shape.rotation

scale

Represents the scale of this node in local space of its parent.

Examples

Inherited from Shape.scale

selection

The currently selected code range.

Either a single CodeRange or an array of them describing which parts of the code should be visually emphasized.

You can use word and lines to quickly create ranges.

Examples


selectionProgress

public selectionProgress: SimpleSignalnullnumbervoid = ...

shaders

readonly public shaders: SignalPossibleShaderConfigShaderConfig[]CodeSignalContextPossibleShaderConfigShaderConfig[]Code
Experimental
This is an experimental feature. The behavior and API may change drastically between minor releases.
Inherited from Shape.shaders

shadowBlur

readonly public shadowBlur: SimpleSignalnumberCode
Inherited from Shape.shadowBlur

shadowColor

readonly public shadowColor: ColorSignalCode
Inherited from Shape.shadowColor

shadowOffset

Inherited from Shape.shadowOffset

shrink

readonly public shrink: SimpleSignalnumberCode
Inherited from Shape.shrink

size

readonly public size: Vector2LengthSignalCode

Represents the size of this node.

A size is a two-dimensional vector, where x represents the width, and y represents the height.

The value of both x and y is of type Length which is either:

  • number - the desired length in pixels
  • ${number}% - a string with the desired length in percents, for example '50%'
  • null - an automatic length

When retrieving the size, all units are converted to pixels, using the current state of the layout. For example, retrieving the width set to '50%', while the parent has a width of 200px will result in the number 100 being returned.

When the node is not part of the layout, setting its size using percents refers to the size of the entire scene.

Examples

Inherited from Shape.size

skew

Represents the skew of this node in local space of its parent.

Examples

Inherited from Shape.skew

stroke

readonly public stroke: CanvasStyleSignalCode
Inherited from Shape.stroke

strokeFirst

readonly public strokeFirst: SimpleSignalbooleanCode
Inherited from Shape.strokeFirst

styles

Inherited from Shape.styles

textAlign

readonly public textAlign: SimpleSignalCanvasTextAlignCode
Inherited from Shape.textAlign

textDirection

readonly public textDirection: SimpleSignalCanvasDirectionCode
Inherited from Shape.textDirection

textWrap

Inherited from Shape.textWrap

top

readonly public top: SimpleVector2SignalCode

The position of the top edge of this node.

When set, this shortcut property will modify the node's position so that the top edge ends up in the given place.

When retrieved, it will return the position of the top edge in the parent space.

Inherited from Shape.top

topLeft

The position of the top left corner of this node.

When set, this shortcut property will modify the node's position so that the top left corner ends up in the given place.

When retrieved, it will return the position of the top left corner in the parent space.

Inherited from Shape.topLeft

topRight

The position of the top right corner of this node.

When set, this shortcut property will modify the node's position so that the top right corner ends up in the given place.

When retrieved, it will return the position of the top right corner in the parent space.

Inherited from Shape.topRight

wrap

Inherited from Shape.wrap

zIndex

readonly public zIndex: SimpleSignalnumberCode
Inherited from Shape.zIndex

defaultHighlighter

static public defaultHighlighter: nullCodeHighlighterunknown = null

Accessors

columnGap

public get columnGap(): SignalLengthnumberthisSignalContextLengthnumberthis
Inherited from Shape.columnGap

height

public get height(): SignalLengthnumberthisSignalContextLengthnumberthis
Inherited from Shape.height

rowGap

public get rowGap(): SignalLengthnumberthisSignalContextLengthnumberthis
Inherited from Shape.rowGap

width

public get width(): SignalLengthnumberthisSignalContextLengthnumberthis
Inherited from Shape.width

x

public get x(): SimpleSignalnumberthis
Inherited from Shape.x

y

public get y(): SimpleSignalnumberthis
Inherited from Shape.y

Methods

[iterator]

public [iterator](): Generatorkey: stringmeta: PropertyMetadataanysignal: SimpleSignalanyvoidvoidunknown
Inherited from Shape.[iterator]

absoluteOpacity

public absoluteOpacity(): number
Inherited from Shape.absoluteOpacity

add

Add the given node(s) as the children of this node.

The nodes will be appended at the end of the children list.

Examples

Parameters

Inherited from Shape.add

anchorPosition

public anchorPosition(): Vector2
Inherited from Shape.anchorPosition

applyState

public applyStatestate: NodeState: void

Apply the given state to the node, setting all matching signal values to the provided values.

Parameters

Inherited from Shape.applyState

cacheBBox

public cacheBBox(): BBox

Get a bounding box for the contents rendered by this node as well as its children.

Inherited from Shape.cacheBBox

cardinalPoint

Get the cardinal point corresponding to the given origin.

Parameters

Inherited from Shape.cardinalPoint

childAs

public childAsT extends NodeT = Nodeindex: number: nullT

Get the nth children cast to the specified type.

Type Parameters

Parameters

  • index: number

    The index of the child to retrieve.

Inherited from Shape.childAs

childrenAs

public childrenAsT extends NodeT = Node(): T[]

Get the children array cast to the specified type.

Type Parameters

Inherited from Shape.childrenAs

clone

public clonecustomProps: NodeState = {}: Code

Create a copy of this node.

Parameters

Inherited from Shape.clone

compositeToLocal

public compositeToLocal(): DOMMatrix
Inherited from Shape.compositeToLocal

compositeToWorld

public compositeToWorld(): DOMMatrix

A matrix mapping composite space to world space.

Certain effects such as blur and shadows ignore the current transformation. This matrix can be used to transform their parameters so that the effect appears relative to the closest composite root.

Inherited from Shape.compositeToWorld

computedPosition

public computedPosition(): Vector2
Inherited from Shape.computedPosition

createSignal

Create a child code signal.

Parameters


dispose

public dispose(): void

Prepare this node to be disposed of.

This method is called automatically when a scene is refreshed. It will be called even if the node is not currently attached to the tree.

The goal of this method is to clean any external references to allow the node to be garbage collected.

Inherited from Shape.dispose

drawOverlay

Draw an overlay for this node.

The overlay for the currently inspected node is displayed on top of the canvas.

The provided context is in screen space. The local-to-screen matrix can be used to transform all shapes that need to be displayed. This approach allows to keep the line widths and gizmo sizes consistent, no matter how zoomed-in the view is.

Parameters

Inherited from Shape.drawOverlay

findAll

public findAllT extends NodeTpredicate: node: any => node is T: T[]
public findAllT extends NodeT = Nodepredicate: node: any => boolean: T[]

Find all descendants of this node that match the given predicate.

Type Parameters

Parameters

  • predicate: node: any => node is T

    A function that returns true if the node matches.

Inherited from Shape.findAll

findAllRanges

public findAllRangespattern: stringRegExp: CodeRange[]

Find all code ranges that match the given pattern.

Parameters

  • pattern: stringRegExp

    Either a string or a regular expression to match.


findAncestor

public findAncestorT extends NodeTpredicate: node: Node => node is T: nullT
public findAncestorT extends NodeT = Nodepredicate: node: Node => boolean: nullT

Find the closest ancestor of this node that matches the given predicate.

Type Parameters

Parameters

Inherited from Shape.findAncestor

findFirst

public findFirstT extends NodeTpredicate: node: Node => node is T: nullT
public findFirstT extends NodeT = Nodepredicate: node: Node => boolean: nullT

Find the first descendant of this node that matches the given predicate.

Type Parameters

Parameters

Inherited from Shape.findFirst

findFirstRange

public findFirstRangepattern: stringRegExp: CodeRange

Find the first code range that matches the given pattern.

Parameters

  • pattern: stringRegExp

    Either a string or a regular expression to match.


findLast

public findLastT extends NodeTpredicate: node: Node => node is T: nullT
public findLastT extends NodeT = Nodepredicate: node: Node => boolean: nullT

Find the last descendant of this node that matches the given predicate.

Type Parameters

Parameters

Inherited from Shape.findLast

findLastRange

public findLastRangepattern: stringRegExp: CodeRange

Find the last code range that matches the given pattern.

Parameters

  • pattern: stringRegExp

    Either a string or a regular expression to match.


getOriginDelta

public getOriginDeltaorigin: Origin: Vector2

Parameters

Inherited from Shape.getOriginDelta

getPointBBox

public getPointBBoxpoint: CodePoint: BBox

Return the bounding box of the given point (character) in the code.

The returned bound box is in local space of the Code node.

Parameters


getSelectionBBox

public getSelectionBBoxselection: PossibleCodeSelection: BBox[]

Return bounding boxes of all characters in the selection.

The returned bounding boxes are in local space of the Code node. Each line of code has a separate bounding box.

Parameters


getState

public getState(): NodeState

Return a snapshot of the node's current signal values.

This method will calculate the values of any reactive properties of the node at the time the method is called.

Inherited from Shape.getState

highlighterCache

public highlighterCache(): nullafter: unknown = ...before: unknown = ...

hit

public hitposition: Vector2: nullNode

Try to find a node intersecting the given position.

Parameters

Inherited from Shape.hit

insert

public insertnode: ComponentChildrenindex: number = 0: Code

Insert the given node(s) at the specified index in the children list.

Examples

Parameters

Inherited from Shape.insert

instantiate

public instantiateprops: NodeProps = {}: Code

Create an instance of this node's class.

Parameters

Inherited from Shape.instantiate

isLayoutRoot

public isLayoutRoot(): boolean
Inherited from Shape.isLayoutRoot

layoutEnabled

public layoutEnabled(): boolean

Get the resolved layout mode of this node.

When the mode is null, its value will be inherited from the parent.

Use layout to get the raw mode set for this node (without inheritance).

Inherited from Shape.layoutEnabled

localToParent

public localToParent(): DOMMatrix

Get the local-to-parent matrix for this node.

This matrix transforms vectors from local space of this node to local space of this node's parent.

Inherited from Shape.localToParent

localToWorld

public localToWorld(): DOMMatrix

Get the local-to-world matrix for this node.

This matrix transforms vectors from local space of this node to world space.

Examples

Inherited from Shape.localToWorld

lockSize

public lockSize(): void
Inherited from Shape.lockSize

move

public moveby: number = 1: Code

Rearrange this node in relation to its siblings.

Children are rendered starting from the beginning of the children list. We can change the rendering order by rearranging said list.

A positive by arguments move the node up (it will be rendered on top of the elements it has passed). Negative values move it down.

Parameters

  • by: number = 1

    Number of places by which the node should be moved.

Inherited from Shape.move

moveAbove

public moveAbovenode: NodedirectlyAbove: boolean = false: Code

Move the node above the provided node in the parent's layout.

The node will be moved above the provided node and from then on will be rendered on top of it. By default, if the node is already positioned higher than the sibling node, it will not get moved.

Parameters

  • node: Node

    The sibling node below which to move.

  • directlyAbove: boolean = false

    Whether the node should be positioned directly above the sibling. When true, will move the node even if it is already positioned above the sibling.

Inherited from Shape.moveAbove

moveBelow

public moveBelownode: NodedirectlyBelow: boolean = false: Code

Move the node below the provided node in the parent's layout.

The node will be moved below the provided node and from then on will be rendered below it. By default, if the node is already positioned lower than the sibling node, it will not get moved.

Parameters

  • node: Node

    The sibling node below which to move.

  • directlyBelow: boolean = false

    Whether the node should be positioned directly below the sibling. When true, will move the node even if it is already positioned below the sibling.

Inherited from Shape.moveBelow

moveDown

public moveDown(): Code

Move the node down in relation to its siblings.

The node will exchange places with the sibling right below it (if any) and from then on will be rendered under it.

Inherited from Shape.moveDown

moveOffset

public moveOffsetoffset: Vector2: void

Update the offset of this node and adjust the position to keep it in the same place.

Parameters

Inherited from Shape.moveOffset

moveTo

public moveToindex: number: Code

Move the node to the provided position relative to its siblings.

If the node is getting moved to a lower position, it will be placed below the sibling that's currently at the provided index (if any). If the node is getting moved to a higher position, it will be placed above the sibling that's currently at the provided index (if any).

Parameters

  • index: number

    The index to move the node to.

Inherited from Shape.moveTo

moveToBottom

public moveToBottom(): Code

Move the node to the bottom in relation to its siblings.

The node will be placed at the beginning of the children list and from then on will be rendered below all of its siblings.

Inherited from Shape.moveToBottom

moveToTop

public moveToTop(): Code

Move the node to the top in relation to its siblings.

The node will be placed at the end of the children list and from then on will be rendered on top of all of its siblings.

Inherited from Shape.moveToTop

moveUp

public moveUp(): Code

Move the node up in relation to its siblings.

The node will exchange places with the sibling right above it (if any) and from then on will be rendered on top of it.

Inherited from Shape.moveUp

parentAs

public parentAsT extends NodeT = Node(): nullT

Get the parent cast to the specified type.

Type Parameters

Inherited from Shape.parentAs

parentToWorld

public parentToWorld(): DOMMatrix

Get the parent-to-world matrix for this node.

This matrix transforms vectors from local space of this node's parent to world space.

Inherited from Shape.parentToWorld

parsed

public parsed(): string

Get the currently displayed code as a string.


peekChildren

public peekChildren(): readonly Node[]

Get the current children of this node.

Unlike children, this method does not have any side effects. It does not register the children signal as a dependency, and it does not spawn any children. It can be used to safely retrieve the current state of the scene graph for debugging purposes.

Inherited from Shape.peekChildren

reactiveClone

public reactiveClonecustomProps: NodeState = {}: Code

Create a reactive copy of this node.

A reactive copy has all its properties dynamically updated to match the source node.

Parameters

Inherited from Shape.reactiveClone

releaseSize

public releaseSize(): void
Inherited from Shape.releaseSize

remove

public remove(): Code

Remove this node from the tree.

Inherited from Shape.remove

removeChildren

public removeChildren(): Code

Remove all children of this node.

Inherited from Shape.removeChildren

render

public rendercontext: CanvasRenderingContext2D: void

Render this node onto the given canvas.

Parameters

Inherited from Shape.render

reparent

public reparentnewParent: Node: Code

Change the parent of this node while keeping the absolute transform.

After performing this operation, the node will stay in the same place visually, but its parent will be changed.

Parameters

Inherited from Shape.reparent

restore

public restore(): void

Restore the node to its last saved state.

This method can be used together with the save method to restore a node to a previously saved state. Restoring a node to a previous state removes that state from the state stack.

Examples

Inherited from Shape.restore

ripple

public rippleduration: number = 1: GeneratorvoidThreadGeneratorPromiseanyPromisableanyvoidany

Parameters

Inherited from Shape.ripple

save

public save(): void

Push a snapshot of the node's current state onto the node's state stack.

This method can be used together with the restore method to save a node's current state and later restore it. It is possible to store more than one state by calling save method multiple times.

Inherited from Shape.save

snapshotClone

public snapshotClonecustomProps: NodeState = {}: Code

Create a copy of this node.

Unlike clone, a snapshot clone calculates any reactive properties at the moment of cloning and passes the raw values to the copy.

Parameters

Inherited from Shape.snapshotClone

toPromise

public toPromise(): PromiseCode

Wait for any asynchronous resources that this node or its children have.

Certain resources like images are always loaded asynchronously. Awaiting this method makes sure that all such resources are done loading before continuing the animation.

Inherited from Shape.toPromise

view

public view(): View2D
Inherited from Shape.view

worldToLocal

public worldToLocal(): DOMMatrix

Get the world-to-local matrix for this node.

This matrix transforms vectors from world space to local space of this node.

Examples

Inherited from Shape.worldToLocal

worldToParent

public worldToParent(): DOMMatrix

Get the world-to-parent matrix for this node.

This matrix transforms vectors from world space to local space of this node's parent.

Inherited from Shape.worldToParent

createSignal

Create a standalone code signal.

Parameters