Editor

See source code
Table of contents

Extends EventEmitter<TLEventMap>.

class Editor extends EventEmitter<TLEventMap> {}

Constructor

Constructs a new instance of the Editor class

Parameters

NameDescription

{ store, user, shapeUtils, bindingUtils, tools, getContainer, cameraOptions, initialState, autoFocus, inferDarkMode, options: _options, textOptions: _textOptions, getShapeVisibility, fontAssetUrls }


Properties

bindingUtils

A map of shape utility classes (TLShapeUtils) by shape type.

bindingUtils: {
  readonly [K in string]?: BindingUtil<TLBinding>;
};

contextId

readonly
readonly contextId: string;

disposables

readonly

A set of functions to call when the editor is disposed.

readonly disposables: Set<() => void>;

edgeScrollManager

A manager for moving the camera when the mouse is at the edge of the screen.

edgeScrollManager: EdgeScrollManager;

fonts

readonly

A utility for managing the set of fonts that should be rendered in the document.

readonly fonts: FontManager;

getContainer

The current HTML element containing the editor.

getContainer: () => HTMLElement;

Example

const container = editor.getContainer();

history

readonly

A manager for the editor's history.

protected readonly history: HistoryManager<TLRecord>;

id

readonly
readonly id: string;

inputs

readonly

A manager for the editor's input state.

readonly inputs: InputsManager;

isDisposed

Whether the editor is disposed.

isDisposed: boolean;

menus: {
  addOpenMenu: (id: string) => void;
  clearOpenMenus: () => void;
  deleteOpenMenu: (id: string) => void;
  getOpenMenus: () => string[];
  hasAnyOpenMenus: () => boolean;
  hasOpenMenus: () => boolean;
  isMenuOpen: (id: string) => boolean;
};

options

readonly
readonly options: TldrawOptions;

root

readonly

The root state of the statechart.

readonly root: StateNode;

scribbles

readonly

A manager for the editor's scribbles.

readonly scribbles: ScribbleManager;

shapeUtils

A map of shape utility classes (TLShapeUtils) by shape type.

shapeUtils: {
  readonly [K in string]?: ShapeUtil<TLShape>;
};

sideEffects

readonly

A manager for side effects and correct state enforcement. See StoreSideEffects for details.

readonly sideEffects: StoreSideEffects<TLRecord>;

snaps

readonly

A manager for the editor's snapping feature.

readonly snaps: SnapManager;

store

readonly

The editor's store

readonly store: TLStore;

styleProps

styleProps: {
  [key: string]: Map<StyleProp<any>, string>;
};

textMeasure

readonly

A helper for measuring text.

readonly textMeasure: TextManager;

timers

readonly

A manager for the any asynchronous events and making sure they're cleaned up upon disposal.

readonly timers: {
  dispose: () => void;
  requestAnimationFrame: (callback: FrameRequestCallback) => number;
  setInterval: (
    handler: TimerHandler,
    timeout?: number | undefined,
    ...args: any[]
  ) => number;
  setTimeout: (
    handler: TimerHandler,
    timeout?: number | undefined,
    ...args: any[]
  ) => number;
};

user

readonly

A manager for the user and their preferences.

readonly user: UserPreferencesManager;

Methods



alignShapes( )

Align shape positions.

alignShapes(
  shapes: TLShape[] | TLShapeId[],
  operation:
    | "bottom"
    | "center-horizontal"
    | "center-vertical"
    | "left"
    | "right"
    | "top",
): this;

Example

editor.alignShapes([box1, box2], "left");
editor.alignShapes(editor.getSelectedShapeIds(), "left");

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to align.

operation

  | "bottom"
  | "center-horizontal"
  | "center-vertical"
  | "left"
  | "right"
  | "top";

The align operation to apply.

Returns

this;

animateShape( )

Animate a shape.

animateShape(
  partial: null | TLShapePartial | undefined,
  opts?: TLCameraMoveOptions,
): this;

Example

editor.animateShape({ id: "box1", type: "box", x: 100, y: 100 });
editor.animateShape(
  { id: "box1", type: "box", x: 100, y: 100 },
  { animation: { duration: 100, ease: (t) => t * t } },
);

Parameters

NameDescription

partial

null | TLShapePartial | undefined;

The shape partial to update.

opts

The animation's options.

Returns

this;

animateShapes( )

Animate shapes.

animateShapes(
  partials: (null | TLShapePartial | undefined)[],
  opts?: TLCameraMoveOptions,
): this;

Example

editor.animateShapes([{ id: "box1", type: "box", x: 100, y: 100 }]);
editor.animateShapes([{ id: "box1", type: "box", x: 100, y: 100 }], {
  animation: { duration: 100, ease: (t) => t * t },
});

Parameters

NameDescription

partials

(null | TLShapePartial | undefined)[];

The shape partials to update.

opts

The animation's options.

Returns

this;

bail( )

Undo to the closest mark, discarding the changes so they cannot be redone.

bail(): this;

Example

editor.bail();

bailToMark( )

Undo to the given mark, discarding the changes so they cannot be redone.

bailToMark(id: string): this;

Example

const beginDrag = editor.markHistoryStoppingPoint();
// ... some changes
editor.bailToMark(beginDrag);

Parameters

NameDescription

id

string;

Returns

this;

blur( )

Switches off the editor's focused mode.

This makes the editor ignore keyboard events and some pointer events (move, wheel).

blur({ blurContainer }?: { blurContainer?: boolean | undefined }): this;

Example

editor.blur();

By default this also dispatches a 'blur' event to the container element. To prevent this, pass blurContainer: false.

editor.blur({ blurContainer: false });

Parameters

NameDescription

{ blurContainer }

{
  blurContainer?: boolean | undefined;
};

Returns

this;

bringForward( )

Bring shapes forward in the page's object list.

bringForward(
  shapes: TLShape[] | TLShapeId[],
  opts?: {
    considerAllShapes?: boolean;
  },
): this;

Example

editor.bringForward(["id1", "id2"]);
editor.bringForward(box1, box2);

By default, the operation will only consider overlapping shapes. To consider all shapes, pass { considerAllShapes: true } in the options.

editor.bringForward(["id1", "id2"], { considerAllShapes: true });

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to move.

opts

{
  considerAllShapes?: boolean;
};

The options for the forward operation.

Returns

this;

bringToFront( )

Bring shapes to the front of the page's object list.

bringToFront(shapes: TLShape[] | TLShapeId[]): this;

Example

editor.bringToFront(["id1", "id2"]);
editor.bringToFront([box1, box2]);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to move.

Returns

this;

canBindShapes( )

canBindShapes({
  fromShape,
  toShape,
  binding,
}: {
  binding:
    | {
        type: TLBinding["type"];
      }
    | TLBinding
    | TLBinding["type"];
  fromShape:
    | {
        type: TLShape["type"];
      }
    | TLShape
    | TLShape["type"];
  toShape:
    | {
        type: TLShape["type"];
      }
    | TLShape
    | TLShape["type"];
}): boolean;

Parameters

NameDescription

{ fromShape, toShape, binding }

{
  binding:
    | {
        type: TLBinding["type"];
      }
    | TLBinding
    | TLBinding["type"];
  fromShape:
    | {
        type: TLShape["type"];
      }
    | TLShape
    | TLShape["type"];
  toShape:
    | {
        type: TLShape["type"];
      }
    | TLShape
    | TLShape["type"];
};

Returns

boolean;

cancel( )

Dispatch a cancel event.

cancel(): this;

Example

editor.cancel();

cancelDoubleClick( )

Prevent a double click event from firing the next time the user clicks

cancelDoubleClick(): void;

canCreateShape( )

Get whether the provided shape can be created.

canCreateShape(
  shape: OptionalKeys<TLShapePartial<TLShape>, "id"> | TLShape["id"],
): boolean;

Parameters

NameDescription

shape

  | OptionalKeys<TLShapePartial<TLShape>, "id">
  | TLShape["id"];

The shape or shape IDs to check.

Returns

boolean;

canCreateShapes( )

Get whether the provided shapes can be created.

canCreateShapes(
  shapes: (OptionalKeys<TLShapePartial<TLShape>, "id"> | TLShape["id"])[],
): boolean;

Parameters

NameDescription

shapes

(
  | OptionalKeys<TLShapePartial<TLShape>, "id">
  | TLShape["id"]
)[];

The shapes or shape IDs to create.

Returns

boolean;

canCropShape( )

Whether the shape can be cropped.

canCropShape<T extends TLShape | TLShapeId>(shape: null | T): shape is T;

Parameters

NameDescription

shape

null | T;

The shape (or shape id) to check if it can be cropped.

Returns

shape is T;

true if the shape can be cropped, false otherwise.


canEditShape( )

Whether the shape can be edited.

canEditShape<T extends TLShape | TLShapeId>(
  shape: null | T,
  info?: TLEditStartInfo,
): shape is T;

Parameters

NameDescription

shape

null | T;

The shape (or shape id) to check if it can be edited.

info

The info about the edit start.

Returns

shape is T;

true if the shape can be edited, false otherwise.


canRedo( )

Whether the editor can redo.

canRedo(): boolean;

canUndo( )

Whether the editor can undo.

canUndo(): boolean;

centerOnPoint( )

Center the camera on a point (in the current page space).

centerOnPoint(point: VecLike, opts?: TLCameraMoveOptions): this;

Example

editor.centerOnPoint({ x: 100, y: 100 });
editor.centerOnPoint({ x: 100, y: 100 }, { animation: { duration: 200 } });

Parameters

NameDescription

point

VecLike;

The point in the current page space to center on.

opts

The camera move options.

Returns

this;

clearHistory( )

clearHistory(): this;

complete( )

Dispatch a complete event.

complete(): this;

Example

editor.complete();

createAssets( )

Create one or more assets.

createAssets(assets: TLAsset[]): this;

Example

editor.createAssets([...myAssets]);

Parameters

NameDescription

assets

TLAsset[];

The assets to create.

Returns

this;

createBinding( )

Create a single binding from a partial. You can omit the ID and most props of a binding, but the type, toId, and fromId must all be provided.

createBinding<B extends TLBinding = TLBinding>(
  partial: TLBindingCreate<B>,
): this;

Parameters

NameDescription

partial

Returns

this;

createBindings( )

Create bindings from a list of partial bindings. You can omit the ID and most props of a binding, but the type, toId, and fromId must all be provided.

createBindings<B extends TLBinding = TLBinding>(
  partials: TLBindingCreate<B>[],
): this;

Parameters

NameDescription

partials

TLBindingCreate<B>[];

Returns

this;

Turns the given URL into a deep link by adding a query parameter.

e.g. https://my-app.com/my-document?d=100.100.200.200.xyz123

If no URL is provided, it will use the current window.location.href.

createDeepLink(opts?: {
  param?: string;
  to?: TLDeepLink;
  url?: string | URL;
}): URL;

Example

// create a deep link to the current page + viewport
navigator.clipboard.writeText(editor.createDeepLink());

You can link to a particular set of shapes by providing a to parameter.

// create a deep link to the set of currently selected shapes
navigator.clipboard.writeText(
  editor.createDeepLink({
    to: { type: "selection", shapeIds: editor.getSelectedShapeIds() },
  }),
);

The default query param is 'd'. You can override this by providing a param parameter.

// Use `x` as the param name instead
editor.createDeepLink({ param: "x" });

Parameters

NameDescription

opts

{
  param?: string;
  to?: TLDeepLink;
  url?: string | URL;
};

Options for adding the state to the URL.

Returns

URL;

the updated URL


createPage( )

Create a page whilst ensuring that the page name is unique.

createPage(page: Partial<TLPage>): this;

Example

editor.createPage(myPage);
editor.createPage({ name: "Page 2" });

Parameters

NameDescription

page

Partial<TLPage>;

The page (or page partial) to create.

Returns

this;

createShape( )

Create a single shape.

createShape<TShape extends TLShape>(
  shape: TLCreateShapePartial<TShape>,
): this;

Example

editor.createShape(myShape);
editor.createShape({
  id: "box1",
  type: "text",
  props: { richText: toRichText("ok") },
});

Parameters

NameDescription

shape

The shape (or shape partial) to create.

Returns

this;

createShapes( )

Create shapes.

createShapes<TShape extends TLShape = TLShape>(
  shapes: TLCreateShapePartial<TShape>[],
): this;

Example

editor.createShapes([myShape]);
editor.createShapes([
  { id: "box1", type: "text", props: { richText: toRichText("ok") } },
]);

Parameters

NameDescription

shapes

TLCreateShapePartial<TShape>[];

The shapes (or shape partials) to create.

Returns

this;

createTemporaryAssetPreview( )

Register a temporary preview of an asset. This is useful for showing a ghost image of something that is being uploaded. Retrieve the placeholder with Editor.getTemporaryAssetPreview. Placeholders last for 3 minutes by default, but this can be configured using

createTemporaryAssetPreview(
  assetId: TLAssetId,
  file: File,
): string | undefined;

Example

editor.createTemporaryAssetPreview(assetId, file);

Parameters

NameDescription

assetId

The asset's id.

file

File;

The raw file.

Returns

string | undefined;

deleteAssets( )

Delete one or more assets.

deleteAssets(assets: TLAsset[] | TLAssetId[]): this;

Example

editor.deleteAssets(["asset1", "asset2"]);

Parameters

NameDescription

assets

TLAsset[] | TLAssetId[];

The assets (or asset ids) to delete.

Returns

this;

deleteBinding( )

Delete a binding by its ID. If the binding doesn't exist, it's ignored.

deleteBinding(
  binding: TLBinding | TLBindingId,
  opts?: Parameters<this["deleteBindings"]>[1],
): this;

Parameters

NameDescription

binding

opts

Parameters<this["deleteBindings"]>[1];

Returns

this;

deleteBindings( )

Delete several bindings by their IDs. If a binding ID doesn't exist, it's ignored.

deleteBindings(
  bindings: (TLBinding | TLBindingId)[],
  {
    isolateShapes,
  }?: {
    isolateShapes?: boolean | undefined;
  },
): this;

Parameters

NameDescription

bindings

{ isolateShapes }

{
  isolateShapes?: boolean | undefined;
};

Returns

this;

deletePage( )

Delete a page.

deletePage(page: TLPage | TLPageId): this;

Example

editor.deletePage("page1");

Parameters

NameDescription

page

The page (or the page id) to delete.

Returns

this;

deleteShape( )

Delete a shape.

deleteShape(id: TLShapeId): this;

Example

editor.deleteShape(shape.id);

Parameters

NameDescription

id

The id of the shape to delete.

Returns

this;

deleteShapes( )

Delete shapes.

deleteShapes(ids: TLShapeId[]): this;

Example

editor.deleteShapes(["box1", "box2"]);

Parameters

NameDescription

ids

TLShapeId[];

The ids of the shapes to delete.

Returns

this;

deselect( )

Remove a shape from the existing set of selected shapes.

deselect(...shapes: TLShape[] | TLShapeId[]): this;

Example

editor.deselect(shape.id);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

Returns

this;

dispatch( )

Dispatch an event to the editor.

dispatch(info: TLEventInfo): this;

Example

editor.dispatch(myPointerEvent);

Parameters

NameDescription

info

The event info.

Returns

this;

dispose( )

Dispose the editor.

dispose(): void;

distributeShapes( )

Distribute shape positions.

distributeShapes(
  shapes: TLShape[] | TLShapeId[],
  operation: "horizontal" | "vertical",
): this;

Example

editor.distributeShapes([box1, box2], "horizontal");
editor.distributeShapes(editor.getSelectedShapeIds(), "horizontal");

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to distribute.

operation

"horizontal" | "vertical";

Whether to distribute shapes horizontally or vertically.

Returns

this;

duplicatePage( )

Duplicate a page.

duplicatePage(page: TLPage | TLPageId, createId?: TLPageId): this;

Parameters

NameDescription

page

The page (or the page id) to duplicate. Defaults to the current page.

createId

The id of the new page. Defaults to a new id.

Returns

this;

duplicateShapes( )

Duplicate shapes.

duplicateShapes(shapes: TLShape[] | TLShapeId[], offset?: VecLike): this;

Example

editor.duplicateShapes(["box1", "box2"], { x: 8, y: 8 });
editor.duplicateShapes(editor.getSelectedShapes(), { x: 8, y: 8 });

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to duplicate.

offset

VecLike;

The offset (in pixels) to apply to the duplicated shapes.

Returns

this;

findCommonAncestor( )

Get the common ancestor of two or more shapes that matches a predicate.

findCommonAncestor(
  shapes: TLShape[] | TLShapeId[],
  predicate?: (shape: TLShape) => boolean,
): TLShapeId | undefined;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to check.

predicate

(shape: TLShape) => boolean;

The predicate to match.

Returns

TLShapeId | undefined;

findShapeAncestor( )

Find the first ancestor matching the given predicate

findShapeAncestor(
  shape: TLShape | TLShapeId,
  predicate: (parent: TLShape) => boolean,
): TLShape | undefined;

Example

const ancestor = editor.findShapeAncestor(myShape);
const ancestor = editor.findShapeAncestor(myShape.id);
const ancestor = editor.findShapeAncestor(
  myShape.id,
  (shape) => shape.type === "frame",
);

Parameters

NameDescription

shape

The shape to check the ancestors for.

predicate

(parent: TLShape) => boolean;

The predicate to match.

Returns

TLShape | undefined;

flipShapes( )

Flip shape positions.

flipShapes(
  shapes: TLShape[] | TLShapeId[],
  operation: "horizontal" | "vertical",
): this;

Example

editor.flipShapes([box1, box2], "horizontal", 32);
editor.flipShapes(editor.getSelectedShapeIds(), "horizontal", 32);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The ids of the shapes to flip.

operation

"horizontal" | "vertical";

Whether to flip horizontally or vertically.

Returns

this;

focus( )

Puts the editor into focused mode.

This makes the editor eligible to receive keyboard events and some pointer events (move, wheel).

focus({ focusContainer }?: { focusContainer?: boolean | undefined }): this;

Example

editor.focus();

By default this also dispatches a 'focus' event to the container element. To prevent this, pass focusContainer: false.

editor.focus({ focusContainer: false });

Parameters

NameDescription

{ focusContainer }

{
  focusContainer?: boolean | undefined;
};

Returns

this;

getAncestorPageId( )

Get the id of the containing page for a given shape.

getAncestorPageId(shape?: TLShape | TLShapeId): TLPageId | undefined;

Parameters

NameDescription

shape

The shape to get the page id for.

Returns

TLPageId | undefined;

The id of the page that contains the shape, or undefined if the shape is undefined.


getAsset( )

Get an asset by its id.

getAsset<T extends TLAsset>(asset: T | T["id"]): T | undefined;

Example

editor.getAsset("asset1");

Parameters

NameDescription

asset

T | T["id"];

The asset (or asset id) to get.

Returns

T | undefined;

getAssetForExternalContent( )

Get an asset for an external asset content type.

getAssetForExternalContent(
  info: TLExternalAsset,
): Promise<TLAsset | undefined>;

Example

const asset = await editor.getAssetForExternalContent({
  type: "file",
  file: myFile,
});
const asset = await editor.getAssetForExternalContent({
  type: "url",
  url: myUrl,
});

Parameters

NameDescription

info

Info about the external content.

Returns

Promise<TLAsset | undefined>;

The asset.


getAssets( )

Get all assets in the editor.

getAssets(): (
  | import("@tldraw/tlschema").TLBookmarkAsset
  | TLImageAsset
  | TLVideoAsset
)[];

getAttributionDisplayName( )

Resolve a display name for a user ID. Asks the TLUserStore first (the app's source of truth), falling back to the user: record in the store.

getAttributionDisplayName(userId: null | string): null | string;

Parameters

NameDescription

userId

null | string;

Returns

null | string;

getAttributionUser( )

Resolve a user record by ID. Asks the TLUserStore first (the app's source of truth), falling back to the user: record in the store.

getAttributionUser(userId: null | string): null | TLUser;

Parameters

NameDescription

userId

null | string;

Returns

null | TLUser;

getAttributionUserId( )

Get the current user's ID for attribution purposes. Also ensures a user: record exists in the store for the current user. Returns null when the user store has no current user.

getAttributionUserId(): null | string;

getBaseZoom( )

Get the camera's base level for calculating actual zoom levels based on the zoom steps.

getBaseZoom(): number;

Example

editor.getBaseZoom();

getBinding( )

Get a binding from the store by its ID if it exists.

getBinding(id: TLBindingId): TLBinding | undefined;

Parameters

NameDescription

id

Returns

TLBinding | undefined;

getBindingsFromShape( )

Get all bindings of a certain type from a particular shape. These are the bindings whose fromId matched the shape's ID.

getBindingsFromShape<K extends TLBinding["type"]>(
  shape: TLShape | TLShapeId,
  type: K,
): Extract<
  TLBinding,
  {
    type: K;
  }
>[];

Parameters

NameDescription

shape

type

K;

Returns

Extract<
  TLBinding,
  {
    type: K;
  }
>[];

getBindingsInvolvingShape( )

Get all bindings involving a particular shape. This includes bindings where the shape is the fromId or toId. If a type is provided, only bindings of that type are returned.

getBindingsInvolvingShape<K extends TLBinding["type"]>(
  shape: TLShape | TLShapeId,
  type: K,
): Extract<
  TLBinding,
  {
    type: K;
  }
>[];

Parameters

NameDescription

shape

type

K;

Returns

Extract<
  TLBinding,
  {
    type: K;
  }
>[];

getBindingsToShape( )

Get all bindings of a certain type to a particular shape. These are the bindings whose toId matches the shape's ID.

getBindingsToShape<K extends TLBinding["type"]>(
  shape: TLShape | TLShapeId,
  type: K,
): Extract<
  TLBinding,
  {
    type: K;
  }
>[];

Parameters

NameDescription

shape

type

K;

Returns

Extract<
  TLBinding,
  {
    type: K;
  }
>[];

getBindingUtil( )

Get a binding util from a binding itself.

getBindingUtil<K extends TLBinding["type"]>(
  type: K,
): BindingUtil<
  Extract<
    TLBinding,
    {
      type: K;
    }
  >
>;

Example

const util = editor.getBindingUtil(myArrowBinding);
const util = editor.getBindingUtil("arrow");
const util = editor.getBindingUtil<TLArrowBinding>(myArrowBinding);
const util = editor.getBindingUtil(TLArrowBinding)("arrow");

Parameters

NameDescription

type

K;

Returns

BindingUtil<
  Extract<
    TLBinding,
    {
      type: K;
    }
  >
>;

getCamera( )

The current camera.

getCamera(): TLCamera;

getCameraOptions( )

Get the current camera options.

getCameraOptions(): TLCameraOptions;

Example

editor.getCameraOptions();

getCameraState( )

Whether the camera is moving or idle.

getCameraState(): "idle" | "moving";

Example

editor.getCameraState();

getCanRedo( )

getCanRedo(): boolean;

getCanUndo( )

getCanUndo(): boolean;

getCollaborators( )

Returns a list of presence records for all peer collaborators. This will return the latest presence record for each connected user.

getCollaborators(): TLInstancePresence[];

getCollaboratorsOnCurrentPage( )

Returns a list of presence records for all peer collaborators on the current page. This will return the latest presence record for each connected user.

getCollaboratorsOnCurrentPage(): TLInstancePresence[];

getContentFromCurrentPage( )

Get content that can be exported for the given shape ids.

getContentFromCurrentPage(
  shapes: TLShape[] | TLShapeId[],
): TLContent | undefined;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to get content for.

Returns

TLContent | undefined;

The exported content.


getCroppingShapeId( )

The current cropping shape's id.

getCroppingShapeId(): null | TLShapeId;

getCulledShapes( )

Get culled shapes (those that should not render), taking into account which shapes are selected or editing.

getCulledShapes(): Set<TLShapeId>;

getCurrentPage( )

The current page.

getCurrentPage(): TLPage;

Example

editor.getCurrentPage();

getCurrentPageBounds( )

The bounds of the current page (the common bounds of all of the shapes on the page).

getCurrentPageBounds(): Box | undefined;

getCurrentPageId( )

The current page id.

getCurrentPageId(): TLPageId;

Example

editor.getCurrentPageId();

getCurrentPageRenderingShapesSorted( )

An array containing all of the rendering shapes in the current page, sorted in z-index order (accounting for nested shapes): e.g. A, B, BA, BB, C.

getCurrentPageRenderingShapesSorted(): TLShape[];

getCurrentPageShapeIds( )

An array of all of the shapes on the current page.

getCurrentPageShapeIds(): Set<TLShapeId>;

Example

editor.getCurrentPageIds();

getCurrentPageShapes( )

An array containing all of the shapes in the current page.

getCurrentPageShapes(): TLShape[];

getCurrentPageShapesInReadingOrder( )

Generates a reading order for shapes based on rows grouping. Tries to keep a natural reading order (left-to-right, top-to-bottom).

getCurrentPageShapesInReadingOrder(): TLShape[];

getCurrentPageShapesSorted( )

An array containing all of the shapes in the current page, sorted in z-index order (accounting for nested shapes): e.g. A, B, BA, BB, C.

getCurrentPageShapesSorted(): TLShape[];

getCurrentPageState( )

The current page state.

getCurrentPageState(): TLInstancePageState;

getCurrentTool( )

The current selected tool.

getCurrentTool(): StateNode;

getCurrentToolId( )

The id of the current selected tool.

getCurrentToolId(): string;

getDebouncedZoomLevel( )

Get the debounced zoom level. When the camera is moving, this returns the zoom level from when the camera started moving rather than the current zoom level. This can be used to avoid expensive re-renders during camera movements.

This behavior is controlled by the useDebouncedZoom option. When useDebouncedZoom is false, this method always returns the current zoom level.

getDebouncedZoomLevel(): number;

getDocumentSettings( )

The global document settings that apply to all users.

getDocumentSettings(): TLDocument;

getDraggingOverShape( )

Get the shape that some shapes should be dropped on at a given point.

getDraggingOverShape(
  point: Vec,
  droppingShapes: TLShape[],
): TLShape | undefined;

Parameters

NameDescription

point

Vec;

The point to find the parent for.

droppingShapes

TLShape[];

The shapes that are being dropped.

Returns

TLShape | undefined;

The shape to drop on.


getEditingShape( )

The current editing shape.

getEditingShape(): TLShape | undefined;

getEditingShapeId( )

The current editing shape's id.

getEditingShapeId(): null | TLShapeId;

getEfficientZoomLevel( )

Get the efficient zoom level. This returns the current zoom level if there are less than a certain number of shapes on the page, otherwise it returns the debounced zoom level. This can be used to avoid expensive re-renders during camera movements.

getEfficientZoomLevel(): number;

Example

editor.getEfficientZoomLevel();

getErasingShapeIds( )

The editor's current erasing ids.

getErasingShapeIds(): TLShapeId[];

getErasingShapes( )

The editor's current erasing shapes.

getErasingShapes(): NonNullable<TLShape | undefined>[];

getFocusedGroup( )

The current focused group.

getFocusedGroup(): TLShape | undefined;

getFocusedGroupId( )

The current focused group id.

getFocusedGroupId(): TLPageId | TLShapeId;

getHighestIndexForParent( )

Get the index above the highest child of a given parent.

getHighestIndexForParent(parent: TLPage | TLParentId | TLShape): IndexKey;

Parameters

NameDescription

parent

The parent (or the id) of the parent.

Returns

IndexKey;

The index.


getHintingShape( )

The editor's current hinting shapes.

getHintingShape(): NonNullable<TLShape | undefined>[];

getHintingShapeIds( )

The editor's current hinting shape ids.

getHintingShapeIds(): TLShapeId[];

getHoveredShape( )

The current hovered shape.

getHoveredShape(): TLShape | undefined;

getHoveredShapeId( )

The current hovered shape id.

getHoveredShapeId(): null | TLShapeId;

getInitialMetaForShape( )

Get the initial meta value for a shape.

getInitialMetaForShape(_shape: TLShape): JsonObject;

Example

editor.getInitialMetaForShape = (shape) => {
  if (shape.type === "note") {
    return { createdBy: myCurrentUser.id };
  }
};

Parameters

NameDescription

_shape

TLShape;

Returns

JsonObject;

getInitialZoom( )

Get the camera's initial or reset zoom level.

getInitialZoom(): number;

Example

editor.getInitialZoom();

getInstanceState( )

The current instance's state.

getInstanceState(): TLInstance;

getIsFocused( )

getIsFocused(): boolean;

getIsReadonly( )

getIsReadonly(): boolean;

getNearestAdjacentShape( )

Find the nearest adjacent shape in a specific direction.

getNearestAdjacentShape(
  shapes: TLShape[],
  currentShapeId: TLShapeId,
  direction: "down" | "left" | "right" | "up",
): TLShapeId;

Parameters

NameDescription

shapes

TLShape[];

currentShapeId

direction

"down" | "left" | "right" | "up";

Returns


getNotVisibleShapes( )

Get shapes that are outside of the viewport.

getNotVisibleShapes(): Set<TLShapeId>;

getOnlySelectedShape( )

The editor's only selected shape.

getOnlySelectedShape(): null | TLShape;

getOnlySelectedShapeId( )

The id of the editor's only selected shape.

getOnlySelectedShapeId(): null | TLShapeId;

getOutermostSelectableShape( )

Get the shape that should be selected when you click on a given shape, assuming there is nothing already selected. It will not return anything higher than or including the current focus layer.

getOutermostSelectableShape(
  shape: TLShape | TLShapeId,
  filter?: (shape: TLShape) => boolean,
): TLShape;

Parameters

NameDescription

shape

The shape to get the outermost selectable shape for.

filter

(shape: TLShape) => boolean;

A function to filter the selectable shapes.

Returns

TLShape;

The outermost selectable shape.


getPage( )

Get a page.

getPage(page: TLPage | TLPageId): TLPage | undefined;

Example

editor.getPage(myPage.id);
editor.getPage(myPage);

Parameters

NameDescription

page

The page (or the page id) to get.

Returns

TLPage | undefined;

getPages( )

Info about the project's current pages.

getPages(): TLPage[];

Example

editor.getPages();

getPageShapeIds( )

Get the ids of shapes on a page.

getPageShapeIds(page: TLPage | TLPageId): Set<TLShapeId>;

Example

const idsOnPage1 = editor.getPageShapeIds("page1");
const idsOnPage2 = editor.getPageShapeIds(myPage2);

Parameters

NameDescription

page

The page (or the page id) to get the shape ids for.

Returns

Set<TLShapeId>;

getPageStates( )

Page states.

getPageStates(): TLInstancePageState[];

getPath( )

The editor's current path of active states.

getPath(): string;

Example

editor.getPath(); // "select.idle"

getPointInParentSpace( )

Convert a delta in the current page space to a point in the local space of a shape's parent.

getPointInParentSpace(shape: TLShape | TLShapeId, point: VecLike): Vec;

Example

editor.getPointInParentSpace(myShape.id, { x: 100, y: 100 });

Parameters

NameDescription

shape

The shape to get the point in the local space of.

point

VecLike;

The page point to get in the local space of the shape.

Returns

Vec;

getPointInShapeSpace( )

Convert a point in the current page space to a point in the local space of a shape. For example, if a shape's page point were { x: 100, y: 100 }, a page point at { x: 110, y: 110 } would be at { x: 10, y: 10 } in the shape's local space.

getPointInShapeSpace(shape: TLShape | TLShapeId, point: VecLike): Vec;

Example

editor.getPointInShapeSpace(myShape, { x: 100, y: 100 });

Parameters

NameDescription

shape

The shape to get the point in the local space of.

point

VecLike;

The page point to get in the local space of the shape.

Returns

Vec;

getRenderingShapes( )

Get the shapes that should be displayed in the current viewport.

getRenderingShapes(): TLRenderingShape[];

Example

editor.getRenderingShapes();

getResizeScaleFactor( )

Get the scale factor used when creating or resizing shapes in dynamic size mode.

getResizeScaleFactor(): number;

getRichTextEditor( )

The current editing shape's text editor.

getRichTextEditor(): null | TiptapEditor;

getSelectedShapeAtPoint( )

Get the top-most selected shape at the given point, ignoring groups.

getSelectedShapeAtPoint(point: VecLike): TLShape | undefined;

Parameters

NameDescription

point

VecLike;

The point to check.

Returns

TLShape | undefined;

The top-most selected shape at the given point, or undefined if there is no shape at the point.


getSelectedShapeIds( )

The current selected ids.

getSelectedShapeIds(): TLShapeId[];

getSelectedShapes( )

An array containing all of the currently selected shapes.

getSelectedShapes(): TLShape[];

getSelectionPageBounds( )

The current page bounds of all the selected shapes. If the selection is rotated, then these bounds are the axis-aligned box that the rotated bounds would fit inside of.

getSelectionPageBounds(): Box | null;

getSelectionRotatedPageBounds( )

The bounds of the selection bounding box in the current page space.

getSelectionRotatedPageBounds(): Box | undefined;

getSelectionRotatedScreenBounds( )

The bounds of the selection bounding box in the current page space.

getSelectionRotatedScreenBounds(): Box | undefined;

getSelectionRotation( )

The rotation of the selection bounding box in the current page space.

getSelectionRotation(): number;

getSelectionScreenBounds( )

The bounds of the selection bounding box in the current page space.

getSelectionScreenBounds(): Box | undefined;

getShape( )

Get a shape by its id.

getShape<T extends TLShape = TLShape>(
  shape: TLParentId | TLShape,
): T | undefined;

Example

editor.getShape("box1");

Parameters

NameDescription

shape

The shape (or the id of the shape) to get.

Returns

T | undefined;

getShapeAncestors( )

Get the ancestors of a shape.

getShapeAncestors(shape: TLShape | TLShapeId, acc?: TLShape[]): TLShape[];

Example

const ancestors = editor.getShapeAncestors(myShape);
const ancestors = editor.getShapeAncestors(myShapeId);

Parameters

NameDescription

shape

The shape (or shape id) to get the ancestors for.

acc

TLShape[];

The accumulator.

Returns

TLShape[];

getShapeAndDescendantIds( )

Get the shape ids of all descendants of the given shapes (including the shapes themselves). IDs are returned in z-index order.

getShapeAndDescendantIds(ids: TLShapeId[]): Set<TLShapeId>;

Parameters

NameDescription

ids

TLShapeId[];

The ids of the shapes to get descendants of.

Returns

Set<TLShapeId>;

The descendant ids.


getShapeAtPoint( )

Get the shape at the current point.

getShapeAtPoint(
  point: VecLike,
  opts?: TLGetShapeAtPointOptions,
): TLShape | undefined;

Parameters

NameDescription

point

VecLike;

The point to check.

opts

Options for the check: hitInside to check if the point is inside the shape, margin to check if the point is within a margin of the shape, hitFrameInside to check if the point is inside the frame, and filter to filter the shapes to check.

Returns

TLShape | undefined;

The shape at the given point, or undefined if there is no shape at the point.


getShapeClipPath( )

Get the clip path for a shape.

getShapeClipPath(shape: TLShape | TLShapeId): string | undefined;

Example

const clipPath = editor.getShapeClipPath(shape);
const clipPath = editor.getShapeClipPath(shape.id);

Parameters

NameDescription

shape

The shape (or shape id) to get the clip path for.

Returns

string | undefined;

The clip path or undefined.


getShapeGeometry( )

Get the geometry of a shape in shape-space.

getShapeGeometry<T extends Geometry2d>(
  shape: TLShape | TLShapeId,
  opts?: TLGeometryOpts,
): T;

Example

editor.getShapeGeometry(myShape);
editor.getShapeGeometry(myShapeId);
editor.getShapeGeometry(myShapeId, { context: "arrow" });

Parameters

NameDescription

shape

The shape (or shape id) to get the geometry for.

opts

Additional options about the request for geometry. Passed to ShapeUtil.getGeometry.

Returns

T;

getShapeHandles( )

Get the handles (if any) for a shape.

getShapeHandles<T extends TLShape>(
  shape: T | T["id"],
): TLHandle[] | undefined;

Example

editor.getShapeHandles(myShape);
editor.getShapeHandles(myShapeId);

Parameters

NameDescription

shape

T | T["id"];

The shape (or shape id) to get the handles for.

Returns

TLHandle[] | undefined;

getShapeIdsInsideBounds( )

Get shape IDs within the given bounds.

Note: Uses shape page bounds only. Frames with labels outside their bounds may not be included even if the label is within the search bounds.

Note: Results are unordered. If you need z-order, combine with sorted shapes:

const candidates = editor.getShapeIdsInsideBounds(bounds);
const sorted = editor
  .getCurrentPageShapesSorted()
  .filter((s) => candidates.has(s.id));
getShapeIdsInsideBounds(bounds: Box): Set<TLShapeId>;

Parameters

NameDescription

bounds

Box;

The bounds to search within.

Returns

Set<TLShapeId>;

Unordered set of shape IDs within the given bounds.


getShapeLocalTransform( )

Get the local transform for a shape as a matrix model. This transform reflects both its translation (x, y) from from either its parent's top left corner, if the shape's parent is another shape, or else from the 0,0 of the page, if the shape's parent is the page; and the shape's rotation.

getShapeLocalTransform(shape: TLShape | TLShapeId): Mat;

Example

editor.getShapeLocalTransform(myShape);

Parameters

NameDescription

shape

The shape to get the local transform for.

Returns

Mat;

getShapeMask( )

Get the mask (in the current page space) for a shape.

getShapeMask(shape: TLShape | TLShapeId): undefined | VecLike[];

Example

const pageMask = editor.getShapeMask(shape.id);

Parameters

NameDescription

shape

The shape (or the shape id) of the shape to get the mask for.

Returns

undefined | VecLike[];

The mask for the shape.


getShapeMaskedPageBounds( )

Get the bounds of a shape in the current page space, incorporating any masks. For example, if the shape were the child of a frame and was half way out of the frame, the bounds would be the half of the shape that was in the frame.

getShapeMaskedPageBounds(shape: TLShape | TLShapeId): Box | undefined;

Example

editor.getShapeMaskedPageBounds(myShape);
editor.getShapeMaskedPageBounds(myShapeId);

Parameters

NameDescription

shape

The shape to get the masked bounds for.

Returns

Box | undefined;

getShapePageBounds( )

Get the bounds of a shape in the current page space.

getShapePageBounds(shape: TLShape | TLShapeId): Box | undefined;

Example

editor.getShapePageBounds(myShape);
editor.getShapePageBounds(myShapeId);

Parameters

NameDescription

shape

The shape (or shape id) to get the bounds for.

Returns

Box | undefined;

getShapePageTransform( )

Get the transform of a shape in the current page space.

getShapePageTransform(shape: TLShape | TLShapeId): Mat;

Example

editor.getShapePageTransform(myShape);
editor.getShapePageTransform(myShapeId);

Parameters

NameDescription

shape

The shape (or shape id) to get the page transform for.

Returns

Mat;

getShapeParent( )

Get the parent shape for a given shape. Returns undefined if the shape is the direct child of the page.

getShapeParent(shape?: TLShape | TLShapeId): TLShape | undefined;

Example

editor.getShapeParent(myShape);

Parameters

NameDescription

shape

Returns

TLShape | undefined;

getShapeParentTransform( )

Get the local transform of a shape's parent as a matrix model.

getShapeParentTransform(shape: TLShape | TLShapeId): Mat;

Example

editor.getShapeParentTransform(myShape);

Parameters

NameDescription

shape

The shape (or shape id) to get the parent transform for.

Returns

Mat;

getShapesAtPoint( )

Get the shapes, if any, at a given page point.

getShapesAtPoint(
  point: VecLike,
  opts?: {
    hitInside?: boolean | undefined;
    margin?: number | undefined;
  },
): TLShape[];

Example

editor.getShapesAtPoint({ x: 100, y: 100 });
editor.getShapesAtPoint({ x: 100, y: 100 }, { hitInside: true, margin: 8 });

Parameters

NameDescription

point

VecLike;

The page point to test.

opts

{
  hitInside?: boolean | undefined;
  margin?: number | undefined;
};

The options for the hit point testing.

Returns

TLShape[];

An array of shapes at the given point, sorted in reverse order of their absolute z-index (top-most shape first).


getShapesPageBounds( )

Get the page bounds of all the provided shapes.

getShapesPageBounds(shapeIds: TLShapeId[]): Box | null;

Parameters

NameDescription

shapeIds

TLShapeId[];

Returns

Box | null;

getShapeStyleIfExists( )

getShapeStyleIfExists<T>(shape: TLShape, style: StyleProp<T>): T | undefined;

Parameters

NameDescription

shape

TLShape;

style

StyleProp<T>;

Returns

T | undefined;

getShapeUtil( )

Get a shape util from a shape itself.

getShapeUtil<K extends TLShape["type"]>(
  type: K,
): ShapeUtil<
  Extract<
    TLShape,
    {
      type: K;
    }
  >
>;

Example

const util = editor.getShapeUtil(myArrowShape);
const util = editor.getShapeUtil("arrow");
const util = editor.getShapeUtil<TLArrowShape>(myArrowShape);
const util = editor.getShapeUtil(TLArrowShape)("arrow");

Parameters

NameDescription

type

K;

Returns

ShapeUtil<
  Extract<
    TLShape,
    {
      type: K;
    }
  >
>;

getSharedOpacity( )

Get the currently selected shared opacity. If any shapes are selected, this returns the shared opacity of the selected shapes. Otherwise, this returns the chosen opacity for the next shape.

getSharedOpacity(): SharedStyle<number>;

getSharedStyles( )

A map of all the current styles either in the current selection, or that are relevant to the current tool.

getSharedStyles(): ReadonlySharedStyleMap;

Example

const color = editor.getSharedStyles().get(DefaultColorStyle);
if (color && color.type === "shared") {
  print("All selected shapes have the same color:", color.value);
}

getSnapshot( )

getSnapshot(): TLEditorSnapshot;

getSortedChildIdsForParent( )

Get an array of all the children of a shape.

getSortedChildIdsForParent(
  parent: TLPage | TLParentId | TLShape,
): TLShapeId[];

Example

editor.getSortedChildIdsForParent("frame1");

Parameters

NameDescription

parent

The parent (or the id) of the parent shape.

Returns

TLShapeId[];

getStateDescendant( )

Get a descendant by its path.

getStateDescendant<T extends StateNode>(path: string): T | undefined;

Example

editor.getStateDescendant("select");
editor.getStateDescendant("select.brushing");

Parameters

NameDescription

path

string;

The descendant's path of state ids, separated by periods.

Returns

T | undefined;

getStyleForNextShape( )

Get the style for the next shape.

getStyleForNextShape<T>(style: StyleProp<T>): T;

Example

const color = editor.getStyleForNextShape(DefaultColorStyle);

Parameters

NameDescription

style

StyleProp<T>;

The style to get.

Returns

T;

getSvgElement( )

Get an exported SVG element of the given shapes.

getSvgElement(
  shapes: TLShape[] | TLShapeId[],
  opts?: TLSvgExportOptions,
): Promise<
  | {
      height: number;
      svg: SVGSVGElement;
      trimPadding: number;
      width: number;
    }
  | undefined
>;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to export.

opts

Options for the export.

Returns

Promise<
  | {
      height: number;
      svg: SVGSVGElement;
      trimPadding: number;
      width: number;
    }
  | undefined
>;

The SVG element.


getSvgString( )

Get an exported SVG string of the given shapes.

getSvgString(
  shapes: TLShape[] | TLShapeId[],
  opts?: TLSvgExportOptions,
): Promise<
  | {
      height: number;
      svg: string;
      trimPadding: number;
      width: number;
    }
  | undefined
>;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to export.

opts

Options for the export.

Returns

Promise<
  | {
      height: number;
      svg: string;
      trimPadding: number;
      width: number;
    }
  | undefined
>;

The SVG element.


getTemporaryAssetPreview( )

Get temporary preview of an asset. This is useful for showing a ghost image of something that is being uploaded.

getTemporaryAssetPreview(assetId: TLAssetId): string | undefined;

Example

editor.getTemporaryAssetPreview("someId");

Parameters

NameDescription

assetId

The asset's id.

Returns

string | undefined;

getTextOptions( )

Get the current text options.

getTextOptions(): TLTextOptions;

Example

editor.getTextOptions();

getViewportPageBounds( )

The current viewport in the current page space.

getViewportPageBounds(): Box;

getViewportScreenBounds( )

The bounds of the editor's viewport in screen space.

getViewportScreenBounds(): Box;

getViewportScreenCenter( )

The center of the editor's viewport in screen space.

getViewportScreenCenter(): Vec;

getZoomLevel( )

The current camera zoom level.

getZoomLevel(): number;

groupShapes( )

Create a group containing the provided shapes.

groupShapes(
  shapes: TLShape[],
  opts?: Partial<{
    groupId: TLShapeId;
    select: boolean;
  }>,
): this;

Example

editor.groupShapes([myShape, myOtherShape]);
editor.groupShapes([myShape, myOtherShape], {
  groupId: myGroupId,
  select: false,
});

Parameters

NameDescription

shapes

TLShape[];

The shapes (or shape ids) to group. Defaults to the selected shapes.

opts

Partial<{
  groupId: TLShapeId;
  select: boolean;
}>;

An options object.

Returns

this;

hasAncestor( )

Returns true if the the given shape has the given ancestor.

hasAncestor(
  shape: TLShape | TLShapeId | undefined,
  ancestorId: TLShapeId,
): boolean;

Parameters

NameDescription

shape

TLShape | TLShapeId | undefined;

The shape.

ancestorId

The id of the ancestor.

Returns

boolean;

hasExternalAssetHandler( )

hasExternalAssetHandler(type: TLExternalAsset["type"]): boolean;

Parameters

NameDescription

type

TLExternalAsset["type"];

Returns

boolean;

hasShapeUtil( )

Returns true if the editor has a shape util for the given shape / shape type.

hasShapeUtil(shape: TLShape | TLShapePartial<TLShape>): boolean;

Parameters

NameDescription

shape

A shape, shape partial, or shape type.

Returns

boolean;

interrupt( )

Dispatch an interrupt event.

interrupt(): this;

Example

editor.interrupt();

isAncestorSelected( )

Determine whether or not any of a shape's ancestors are selected.

isAncestorSelected(shape: TLShape | TLShapeId): boolean;

Parameters

NameDescription

shape

The shape (or shape id) of the shape to check.

Returns

boolean;

isIn( )

Get whether a certain tool (or other state node) is currently active.

isIn(path: string): boolean;

Example

editor.isIn("select");
editor.isIn("select.brushing");

Parameters

NameDescription

path

string;

The path of active states, separated by periods.

Returns

boolean;

isInAny( )

Get whether the state node is in any of the given active paths.

isInAny(...paths: string[]): boolean;

Example

state.isInAny("select", "erase");
state.isInAny("select.brushing", "erase.idle");

Parameters

NameDescription

paths

string[];

Returns

boolean;

isPointInShape( )

Test whether a point (in the current page space) will will a shape. This method takes into account masks, such as when a shape is the child of a frame and is partially clipped by the frame.

isPointInShape(
  shape: TLShape | TLShapeId,
  point: VecLike,
  opts?: {
    hitInside?: boolean | undefined;
    margin?: number | undefined;
  },
): boolean;

Example

editor.isPointInShape({ x: 100, y: 100 }, myShape);

Parameters

NameDescription

shape

The shape to test against.

point

VecLike;

The page point to test (in the current page space).

opts

{
  hitInside?: boolean | undefined;
  margin?: number | undefined;
};

The options for the hit point testing.

Returns

boolean;

isShapeHidden( )

isShapeHidden(shapeOrId: TLShape | TLShapeId): boolean;

Parameters

NameDescription

shapeOrId

Returns

boolean;

isShapeInPage( )

Get whether the given shape is the descendant of the given page.

isShapeInPage(shape: TLShape | TLShapeId, pageId?: TLPageId): boolean;

Example

editor.isShapeInPage(myShape);
editor.isShapeInPage(myShape, "page1");

Parameters

NameDescription

shape

The shape to check.

pageId

The id of the page to check against. Defaults to the current page.

Returns

boolean;

isShapeOfType( )

Get whether a shape matches the type of a TLShapeUtil.

isShapeOfType<K extends TLShape["type"]>(
  shape: TLShape,
  type: K,
): shape is Extract<
  TLShape,
  {
    type: K;
  }
>;

Example

const isArrowShape = isShapeOfType(someShape, "arrow");

Parameters

NameDescription

shape

TLShape;

the shape to test

type

K;

Returns

shape is Extract<
  TLShape,
  {
    type: K;
  }
>;

isShapeOrAncestorLocked( )

Check whether a shape or its parent is locked.

isShapeOrAncestorLocked(shape?: TLShape | TLShapeId): boolean;

Parameters

NameDescription

shape

The shape (or shape id) to check.

Returns

boolean;

loadSnapshot( )

Loads a snapshot into the editor.

loadSnapshot(
  snapshot: Partial<TLEditorSnapshot> | TLStoreSnapshot,
  opts?: TLLoadSnapshotOptions,
): this;

Parameters

NameDescription

snapshot

The snapshot to load.

opts

The options for loading the snapshot.

Returns

this;

markEventAsHandled( )

In tldraw, events are sometimes handled by multiple components. For example, the shapes might have events, but the canvas handles events too. The way that the canvas handles events can interfere with the with the shapes event handlers - for example, it calls .preventDefault() on pointerDown, which also prevents click events from firing on the shapes.

You can use .stopPropagation() to prevent the event from propagating to the rest of the DOM, but that can impact non-tldraw event handlers set up elsewhere. By using markEventAsHandled, you'll stop other parts of tldraw from handling the event without impacting other, non-tldraw event handlers. See also Editor.wasEventAlreadyHandled.

markEventAsHandled(
  e:
    | {
        nativeEvent: Event;
      }
    | Event,
): void;

Parameters

NameDescription

e

  | {
      nativeEvent: Event;
    }
  | Event;

Returns

void;

markHistoryStoppingPoint( )

Create a new "mark", or stopping point, in the undo redo history. Creating a mark will clear any redos. You typically want to do this just before a user interaction begins or is handled.

markHistoryStoppingPoint(name?: string): string;

Example

editor.markHistoryStoppingPoint();
editor.flipShapes(editor.getSelectedShapes());
const beginRotateMark = editor.markHistoryStoppingPoint();
// if the use cancels the rotation, you can bail back to this mark
editor.bailToMark(beginRotateMark);

Parameters

NameDescription

name

string;

The name of the mark, useful for debugging the undo/redo stacks

Returns

string;

a unique id for the mark that can be used with squashToMark or bailToMark.


moveShapesToPage( )

Move shapes to page.

moveShapesToPage(shapes: TLShape[] | TLShapeId[], pageId: TLPageId): this;

Example

editor.moveShapesToPage(["box1", "box2"], "page1");

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) of the shapes to move.

pageId

The id of the page where the shapes will be moved.

Returns

this;

Handles navigating to the content specified by the query param in the given URL.

Use Editor.createDeepLink to create a URL with a deep link query param.

If no URL is provided, it will look for the param in the current window.location.href.

navigateToDeepLink(
  opts?:
    | {
        param?: string;
        url?: string | URL;
      }
    | TLDeepLink,
): Editor;

Example

editor.navigateToDeepLink();

The default parameter name is 'd'. You can override this by providing the param option.

// disable page parameter and change viewport parameter to 'c'
editor.navigateToDeepLink({
  param: "x",
  url: "https://my-app.com/my-document?x=200.12.454.23.xyz123",
});

Parameters

NameDescription

opts

  | {
      param?: string;
      url?: string | URL;
    }
  | TLDeepLink;

Options for loading the state from the URL.

Returns

Editor;

nudgeShapes( )

Move shapes by a delta.

nudgeShapes(shapes: TLShape[] | TLShapeId[], offset: VecLike): this;

Example

editor.nudgeShapes(["box1", "box2"], { x: 8, y: 8 });

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to move.

offset

VecLike;

The offset to apply to the shapes.

Returns

this;

packShapes( )

Pack shapes into a grid centered on their current position. Based on potpack (https://github.com/mapbox/potpack).

packShapes(shapes: TLShape[] | TLShapeId[], _gap?: number): this;

Example

editor.packShapes([box1, box2]);
editor.packShapes(editor.getSelectedShapeIds(), 32);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to pack.

_gap

number;

Returns

this;

pageToScreen( )

Convert a point in the current page space to a point in current screen space.

pageToScreen(point: VecLike): Vec;

Example

editor.pageToScreen({ x: 100, y: 100 });

Parameters

NameDescription

point

VecLike;

The point in page space.

Returns

Vec;

pageToViewport( )

Convert a point in the current page space to a point in current viewport space.

pageToViewport(point: VecLike): Vec;

Example

editor.pageToViewport({ x: 100, y: 100 });

Parameters

NameDescription

point

VecLike;

The point in page space.

Returns

Vec;

popFocusedGroupId( )

Exit the current focused group, moving up to the next parent group if there is one.

popFocusedGroupId(): this;

putContentOntoCurrentPage( )

Place content into the editor.

putContentOntoCurrentPage(
  content: TLContent,
  opts?: {
    point?: VecLike;
    preserveIds?: boolean;
    preservePosition?: boolean;
    select?: boolean;
  },
): this;

Parameters

NameDescription

content

The content.

opts

{
  point?: VecLike;
  preserveIds?: boolean;
  preservePosition?: boolean;
  select?: boolean;
};

Options for placing the content.

Returns

this;

putExternalContent( )

Handle external content, such as files, urls, embeds, or plain text which has been put into the app, for example by pasting external text or dropping external images onto canvas.

putExternalContent<E>(
  info: TLExternalContent<E>,
  opts?: {
    force?: boolean | undefined;
  },
): Promise<void>;

Parameters

NameDescription

info

Info about the external content.

opts

{
  force?: boolean | undefined;
};

Options for handling external content, including force flag to bypass readonly checks.

Returns

Promise<void>;

redo( )

Redo to the next mark.

redo(): this;

Example

editor.redo();

registerDeepLinkListener( )

Register a listener for changes to a deep link for the current document.

You'll typically want to use this indirectly via the TldrawEditorBaseProps.deepLinks prop on the <Tldraw /> component.

By default this will update window.location in place, but you can provide a custom callback to handle state changes on your own.

registerDeepLinkListener(opts?: TLDeepLinkOptions): () => void;

Example

editor.registerDeepLinkListener({
  onChange(url) {
    window.history.replaceState({}, document.title, url.toString());
  },
});

You can also provide a custom URL to update, in which case you must also provide onChange.

editor.registerDeepLinkListener({
  getUrl: () => `https://my-app.com/my-document`,
  onChange(url) {
    setShareUrl(url.toString());
  },
});

By default this will update with a debounce interval of 500ms, but you can provide a custom interval.

editor.registerDeepLinkListener({ debounceMs: 1000 });

The default parameter name is d. You can override this by providing a param option.

editor.registerDeepLinkListener({ param: "x" });

Parameters

NameDescription

opts

Options for setting up the listener.

Returns

() => void;

a function that will stop the listener.


registerExternalAssetHandler( )

Register an external asset handler. This handler will be called when the editor needs to create an asset for some external content, like an image/video file or a bookmark URL. For example, the 'file' type handler will be called when a user drops an image onto the canvas.

The handler should extract any relevant metadata for the asset, upload it to blob storage using Editor.uploadAsset if needed, and return the asset with the metadata & uploaded URL.

registerExternalAssetHandler<T extends TLExternalAsset["type"]>(
  type: T,
  handler:
    | ((
        info: TLExternalAsset & {
          type: T;
        },
      ) => Promise<TLAsset>)
    | null,
): this;

Example

editor.registerExternalAssetHandler("file", myHandler);

Parameters

NameDescription

type

T;

The type of external content.

handler

  | ((
      info: TLExternalAsset & {
        type: T;
      },
    ) => Promise<TLAsset>)
  | null;

The handler to use for this content type.

Returns

this;

registerExternalContentHandler( )

Register an external content handler. This handler will be called when the editor receives external content of the provided type. For example, the 'image' type handler will be called when a user drops an image onto the canvas.

registerExternalContentHandler<T extends TLExternalContent<E>["type"], E>(
  type: T,
  handler:
    | ((
        info: T extends TLExternalContent<E>["type"]
          ? Extract<
              TLExternalContent<E>,
              {
                type: T;
              }
            >
          : TLExternalContent<E>,
      ) => void)
    | null,
): this;

Example

editor.registerExternalContentHandler("text", myHandler);
editor.registerExternalContentHandler<"embed", MyEmbedType>("embed", myHandler);

Parameters

NameDescription

type

T;

The type of external content.

handler

  | ((
      info: T extends TLExternalContent<E>["type"]
        ? Extract<
            TLExternalContent<E>,
            {
              type: T;
            }
          >
        : TLExternalContent<E>,
    ) => void)
  | null;

The handler to use for this content type.

Returns

this;

removeTool( )

Remove a tool. Useful if you need to remove a tool from the state chart on demand, after the editor has already been initialized.

removeTool(Tool: TLStateNodeConstructor, parent?: StateNode): void;

Parameters

NameDescription

Tool

The tool to delete.

parent

The parent state node to remove the tool from.

Returns

void;

renamePage( )

Rename a page.

renamePage(page: TLPage | TLPageId, name: string): this;

Example

editor.renamePage("page1", "My Page");

Parameters

NameDescription

page

The page (or the page id) to rename.

name

string;

The new name.

Returns

this;

reparentShapes( )

Reparent shapes to a new parent. This operation preserves the shape's current page positions / rotations.

reparentShapes(
  shapes: TLShape[] | TLShapeId[],
  parentId: TLParentId,
  insertIndex?: IndexKey,
): this;

Example

editor.reparentShapes([box1, box2], "frame1");
editor.reparentShapes([box1.id, box2.id], "frame1");
editor.reparentShapes([box1.id, box2.id], "frame1", 4);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) of the shapes to reparent.

parentId

The id of the new parent shape.

insertIndex

IndexKey;

The index to insert the children.

Returns

this;

replaceExternalContent( )

Handle replacing external content.

replaceExternalContent<E>(
  info: TLExternalContent<E>,
  opts?: {
    force?: boolean | undefined;
  },
): Promise<void>;

Parameters

NameDescription

info

Info about the external content.

opts

{
  force?: boolean | undefined;
};

Options for handling external content, including force flag to bypass readonly checks.

Returns

Promise<void>;

resetZoom( )

Set the zoom back to 100%.

resetZoom(point?: Vec, opts?: TLCameraMoveOptions): this;

Example

editor.resetZoom();
editor.resetZoom(editor.getViewportScreenCenter(), {
  animation: { duration: 200 },
});
editor.resetZoom(editor.getViewportScreenCenter(), {
  animation: { duration: 200 },
});

Parameters

NameDescription

point

Vec;

The screen point to zoom out on. Defaults to the viewport screen center.

opts

The camera move options.

Returns

this;

resizeShape( )

Resize a shape.

resizeShape(
  shape: TLShape | TLShapeId,
  scale: VecLike,
  opts?: TLResizeShapeOptions,
): this;

Parameters

NameDescription

shape

The shape (or the shape id of the shape) to resize.

scale

VecLike;

The scale factor to apply to the shape.

opts

Additional options.

Returns

this;

resizeToBounds( )

Resize and reposition a set of shapes so that their combined page bounds matches the given target bounds.

resizeToBounds(shapes: TLShape[] | TLShapeId[], bounds: BoxLike): this;

Example

editor.resizeToBounds([box1, box2], { x: 0, y: 0, w: 500, h: 500 });
editor.resizeToBounds(editor.getSelectedShapeIds(), new Box(0, 0, 500, 500));

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to resize.

bounds

BoxLike;

The target bounding box.

Returns

this;

resolveAssetsInContent( )

resolveAssetsInContent(
  content: TLContent | undefined,
): Promise<TLContent | undefined>;

Parameters

NameDescription

content

TLContent | undefined;

Returns

Promise<TLContent | undefined>;

resolveAssetUrl( )

resolveAssetUrl(
  assetId: null | TLAssetId,
  context: {
    dpr?: number;
    screenScale?: number;
    shouldResolveToOriginal?: boolean;
  },
): Promise<null | string>;

Parameters

NameDescription

assetId

null | TLAssetId;

context

{
  dpr?: number;
  screenScale?: number;
  shouldResolveToOriginal?: boolean;
};

Returns

Promise<null | string>;

rotateShapesBy( )

Rotate shapes by a delta in radians.

rotateShapesBy(
  shapes: TLShape[] | TLShapeId[],
  delta: number,
  opts?: {
    center?: VecLike;
  },
): this;

Example

editor.rotateShapesBy(editor.getSelectedShapeIds(), Math.PI);
editor.rotateShapesBy(editor.getSelectedShapeIds(), Math.PI / 2);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) of the shapes to move.

delta

number;

The delta in radians to apply to the selection rotation.

opts

{
  center?: VecLike;
};

The options for the rotation.

Returns

this;

run( )

Run a function in a transaction with optional options for context. You can use the options to change the way that history is treated or allow changes to locked shapes.

run(fn: () => void, opts?: TLEditorRunOptions): this;

Example

// updating with
editor.run(
  () => {
    editor.updateShape({ ...myShape, x: 100 });
  },
  { history: "ignore" },
);

// forcing changes / deletions for locked shapes
editor.toggleLock([myShape]);
editor.run(
  () => {
    editor.updateShape({ ...myShape, x: 100 });
    editor.deleteShape(myShape);
  },
  { ignoreShapeLock: true },
);

Parameters

NameDescription

fn

() => void;

The callback function to run.

opts

The options for the batch.

Returns

this;

screenToPage( )

Convert a point in screen space to a point in the current page space.

screenToPage(point: VecLike): Vec;

Example

editor.screenToPage({ x: 100, y: 100 });

Parameters

NameDescription

point

VecLike;

The point in screen space.

Returns

Vec;

select( )

Select one or more shapes.

select(...shapes: TLShape[] | TLShapeId[]): this;

Example

editor.select("id1");
editor.select("id1", "id2");

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shape (or the shape ids) to select.

Returns

this;

selectAdjacentShape( )

Select the next shape in the reading order or in cardinal order.

selectAdjacentShape(direction: TLAdjacentDirection): void;

Example

editor.selectAdjacentShape("next");

Parameters

NameDescription

direction

Returns

void;

selectAll( )

Select all shapes. If the user has selected shapes that share a parent, select all shapes within that parent. If the user has not selected any shapes, or if the shapes shapes are only on select all shapes on the current page.

selectAll(): this;

Example

editor.selectAll();

selectFirstChildShape( )

selectFirstChildShape(): void;

selectNone( )

Clear the selection.

selectNone(): this;

Example

editor.selectNone();

selectParentShape( )

selectParentShape(): void;

sendBackward( )

Send shapes backward in the page's object list.

sendBackward(
  shapes: TLShape[] | TLShapeId[],
  opts?: {
    considerAllShapes?: boolean;
  },
): this;

Example

editor.sendBackward(["id1", "id2"]);
editor.sendBackward([box1, box2]);

By default, the operation will only consider overlapping shapes. To consider all shapes, pass { considerAllShapes: true } in the options.

editor.sendBackward(["id1", "id2"], { considerAllShapes: true });

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to move.

opts

{
  considerAllShapes?: boolean;
};

The options for the backward operation.

Returns

this;

sendToBack( )

Send shapes to the back of the page's object list.

sendToBack(shapes: TLShape[] | TLShapeId[]): this;

Example

editor.sendToBack(["id1", "id2"]);
editor.sendToBack(box1, box2);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to move.

Returns

this;

setCamera( )

Set the current camera.

setCamera(point: VecLike, opts?: TLCameraMoveOptions): this;

Example

editor.setCamera({ x: 0, y: 0 });
editor.setCamera({ x: 0, y: 0, z: 1.5 });
editor.setCamera(
  { x: 0, y: 0, z: 1.5 },
  { animation: { duration: 1000, easing: (t) => t * t } },
);

Parameters

NameDescription

point

VecLike;

The new camera position.

opts

The camera move options.

Returns

this;

setCameraOptions( )

Set the camera options. Changing the options won't immediately change the camera itself, so you may want to call setCamera after changing the options.

setCameraOptions(opts: Partial<TLCameraOptions>): this;

Example

editor.setCameraOptions(myCameraOptions);
editor.setCamera(editor.getCamera());

Parameters

NameDescription

opts

Partial<TLCameraOptions>;

The camera options to set.

Returns

this;

setCroppingShape( )

Set the current cropping shape.

setCroppingShape(shape: null | TLShape | TLShapeId): this;

Example

editor.setCroppingShape(myShape);
editor.setCroppingShape(myShape.id);

Parameters

NameDescription

shape

null | TLShape | TLShapeId;

The shape (or shape id) to set as cropping.

Returns

this;

setCurrentPage( )

Set the current page.

setCurrentPage(page: TLPage | TLPageId): this;

Example

editor.setCurrentPage("page1");
editor.setCurrentPage(myPage1);

Parameters

NameDescription

page

The page (or the page id) to set as the current page.

Returns

this;

setCurrentTool( )

Set the selected tool.

setCurrentTool(id: string, info?: {}): this;

Example

editor.setCurrentTool("hand");
editor.setCurrentTool("hand", { date: Date.now() });

Parameters

NameDescription

id

string;

The id of the tool to select.

info

{};

Arbitrary data to pass along into the transition.

Returns

this;

setCursor( )

Set the cursor.

setCursor(cursor: Partial<TLCursor>): this;

Parameters

NameDescription

cursor

Partial<TLCursor>;

The cursor to set.

Returns

this;

setEditingShape( )

Set the current editing shape.

setEditingShape(shape: null | TLShape | TLShapeId): this;

Example

editor.setEditingShape(myShape);
editor.setEditingShape(myShape.id);

Parameters

NameDescription

shape

null | TLShape | TLShapeId;

The shape (or shape id) to set as editing.

Returns

this;

setErasingShapes( )

Set the editor's current erasing shapes.

setErasingShapes(shapes: TLShape[] | TLShapeId[]): this;

Example

editor.setErasingShapes([myShape]);
editor.setErasingShapes([myShape.id]);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to set as hinting.

Returns

this;

setFocusedGroup( )

Set the current focused group shape.

setFocusedGroup(shape: null | TLGroupShape | TLShapeId): this;

Parameters

NameDescription

shape

null | TLGroupShape | TLShapeId;

The group shape id (or group shape's id) to set as the focused group shape.

Returns

this;

setHintingShapes( )

Set the editor's current hinting shapes.

setHintingShapes(shapes: TLShape[] | TLShapeId[]): this;

Example

editor.setHintingShapes([myShape]);
editor.setHintingShapes([myShape.id]);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to set as hinting.

Returns

this;

setHoveredShape( )

Set the editor's current hovered shape.

setHoveredShape(shape: null | TLShape | TLShapeId): this;

Example

editor.setHoveredShape(myShape);
editor.setHoveredShape(myShape.id);

Parameters

NameDescription

shape

null | TLShape | TLShapeId;

The shape (or shape id) to set as hovered.

Returns

this;

setOpacityForNextShapes( )

Set the opacity for the next shapes. This will effect subsequently created shapes.

setOpacityForNextShapes(
  opacity: number,
  historyOptions?: TLHistoryBatchOptions,
): this;

Example

editor.setOpacityForNextShapes(0.5);

Parameters

NameDescription

opacity

number;

The opacity to set. Must be a number between 0 and 1 inclusive.

historyOptions

The history options for the change.

Returns

this;

setOpacityForSelectedShapes( )

Set the current opacity. This will effect any selected shapes.

setOpacityForSelectedShapes(opacity: number): this;

Example

editor.setOpacityForSelectedShapes(0.5);

Parameters

NameDescription

opacity

number;

The opacity to set. Must be a number between 0 and 1 inclusive.

Returns

this;

setRichTextEditor( )

Set the current editing shape's rich text editor.

setRichTextEditor(textEditor: null | TiptapEditor): this;

Example

editor.setRichTextEditor(richTextEditorView);

Parameters

NameDescription

textEditor

null | TiptapEditor;

The text editor to set as the current editing shape's text editor.

Returns

this;

setSelectedShapes( )

Select one or more shapes.

setSelectedShapes(shapes: TLShape[] | TLShapeId[]): this;

Example

editor.setSelectedShapes(["id1"]);
editor.setSelectedShapes(["id1", "id2"]);

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shape (or shape ids) to select.

Returns

this;

setStyleForNextShapes( )

Set the value of a StyleProp for the next shapes. This change will be applied to subsequently created shapes.

setStyleForNextShapes<T>(
  style: StyleProp<T>,
  value: T,
  historyOptions?: TLHistoryBatchOptions,
): this;

Example

editor.setStyleForNextShapes(DefaultColorStyle, "red");
editor.setStyleForNextShapes(DefaultColorStyle, "red", { ephemeral: true });

Parameters

NameDescription

style

StyleProp<T>;

The style to set.

value

T;

The value to set.

historyOptions

The history options for the change.

Returns

this;

setStyleForSelectedShapes( )

Set the value of a StyleProp. This change will be applied to the currently selected shapes.

setStyleForSelectedShapes<S extends StyleProp<any>>(
  style: S,
  value: StylePropValue<S>,
): this;

Example

editor.setStyleForSelectedShapes(DefaultColorStyle, "red");

Parameters

NameDescription

style

S;

The style to set.

value

The value to set.

Returns

this;

setTool( )

Set a tool. Useful if you need to add a tool to the state chart on demand, after the editor has already been initialized.

setTool(Tool: TLStateNodeConstructor, parent?: StateNode): void;

Parameters

NameDescription

Tool

The tool to set.

parent

The parent state node to set the tool on.

Returns

void;

slideCamera( )

Slide the camera in a certain direction.

slideCamera(opts?: {
  direction: VecLike;
  force?: boolean | undefined;
  friction?: number | undefined;
  speed: number;
  speedThreshold?: number | undefined;
}): this;

Example

editor.slideCamera({ speed: 1, direction: { x: 1, y: 0 }, friction: 0.1 });

Parameters

NameDescription

opts

{
  direction: VecLike;
  force?: boolean | undefined;
  friction?: number | undefined;
  speed: number;
  speedThreshold?: number | undefined;
};

Options for the slide

Returns

this;

squashToMark( )

Coalesces all changes since the given mark into a single change, removing any intermediate marks.

This is useful if you need to 'compress' the recent history to simplify the undo/redo experience of a complex interaction.

squashToMark(markId: string): this;

Example

const bumpShapesMark = editor.markHistoryStoppingPoint();
// ... some changes
editor.squashToMark(bumpShapesMark);

Parameters

NameDescription

markId

string;

The mark id to squash to.

Returns

this;

stackShapes( )

Stack shape.

stackShapes(
  shapes: TLShape[] | TLShapeId[],
  operation: "horizontal" | "vertical",
  gap?: number,
): this;

Example

editor.stackShapes([box1, box2], "horizontal");
editor.stackShapes(editor.getSelectedShapeIds(), "horizontal");

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to stack.

operation

"horizontal" | "vertical";

Whether to stack horizontally or vertically.

gap

number;

The gap to leave between shapes. By default, uses the editor's adjacentShapeMargin option.

Returns

this;

startFollowingUser( )

Start viewport-following a user.

startFollowingUser(userId: string): this;

Example

editor.startFollowingUser(myUserId);

Parameters

NameDescription

userId

string;

The id of the user to follow.

Returns

this;

stopCameraAnimation( )

Stop the current camera animation, if any.

stopCameraAnimation(): this;

Example

editor.stopCameraAnimation();

stopFollowingUser( )

Stop viewport-following a user.

stopFollowingUser(): this;

Example

editor.stopFollowingUser();

stretchShapes( )

Stretch shape sizes and positions to fill their common bounding box.

stretchShapes(
  shapes: TLShape[] | TLShapeId[],
  operation: "horizontal" | "vertical",
): this;

Example

editor.stretchShapes([box1, box2], "horizontal");
editor.stretchShapes(editor.getSelectedShapeIds(), "horizontal");

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to stretch.

operation

"horizontal" | "vertical";

Whether to stretch shapes horizontally or vertically.

Returns

this;

toggleLock( )

Toggle the lock state of one or more shapes. If there is a mix of locked and unlocked shapes, all shapes will be locked.

toggleLock(shapes: TLShape[] | TLShapeId[]): this;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to toggle.

Returns

this;

toImage( )

Get an exported image of the given shapes.

toImage(
  shapes: TLShape[] | TLShapeId[],
  opts?: TLImageExportOptions,
): Promise<{
  blob: Blob;
  height: number;
  width: number;
}>;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to export.

opts

Options for the export.

Returns

Promise<{
  blob: Blob;
  height: number;
  width: number;
}>;

A blob of the image.


toImageDataUrl( )

Get an exported image of the given shapes as a data URL.

toImageDataUrl(
  shapes: TLShape[] | TLShapeId[],
  opts?: TLImageExportOptions,
): Promise<{
  height: number;
  url: string;
  width: number;
}>;

Parameters

NameDescription

shapes

TLShape[] | TLShapeId[];

The shapes (or shape ids) to export.

opts

Options for the export.

Returns

Promise<{
  height: number;
  url: string;
  width: number;
}>;

A data URL of the image.


undo( )

Undo to the last mark.

undo(): this;

Example

editor.undo();

ungroupShapes( )

Ungroup some shapes.

ungroupShapes(
  ids: TLShapeId[],
  opts?: Partial<{
    select: boolean;
  }>,
): this;

Example

editor.ungroupShapes([myGroup, myOtherGroup]);
editor.ungroupShapes([myGroup], { select: false });

Parameters

NameDescription

ids

TLShapeId[];

opts

Partial<{
  select: boolean;
}>;

An options object.

Returns

this;

updateAssets( )

Update one or more assets.

updateAssets(assets: TLAssetPartial[]): this;

Example

editor.updateAssets([{ id: "asset1", name: "New name" }]);

Parameters

NameDescription

assets

The assets to update.

Returns

this;

updateBinding( )

Update a binding from a partial binding. Each partial must include an ID, which will be used to match the binding to it's existing record. If there is no existing record, that binding is skipped. The changes from the partial are merged into the existing record.

updateBinding<B extends TLBinding = TLBinding>(
  partial: TLBindingUpdate<B>,
): this;

Parameters

NameDescription

partial

Returns

this;

updateBindings( )

Update bindings from a list of partial bindings. Each partial must include an ID, which will be used to match the binding to it's existing record. If there is no existing record, that binding is skipped. The changes from the partial are merged into the existing record.

updateBindings(partials: (null | TLBindingUpdate | undefined)[]): this;

Parameters

NameDescription

partials

(null | TLBindingUpdate | undefined)[];

Returns

this;

updateCurrentPageState( )

Update this instance's page state.

updateCurrentPageState(
  partial: Partial<
    Omit<
      TLInstancePageState,
      "editingShapeId" | "focusedGroupId" | "pageId" | "selectedShapeIds"
    >
  >,
): this;

Example

editor.updateCurrentPageState({ id: "page1", editingShapeId: "shape:123" });

Parameters

NameDescription

partial

Partial<
  Omit<
    TLInstancePageState,
    | "editingShapeId"
    | "focusedGroupId"
    | "pageId"
    | "selectedShapeIds"
  >
>;

The partial of the page state object containing the changes.

Returns

this;

updateDocumentSettings( )

Update the global document settings that apply to all users.

updateDocumentSettings(settings: Partial<TLDocument>): this;

Parameters

NameDescription

settings

Partial<TLDocument>;

Returns

this;

updateInstanceState( )

Update the instance's state.

updateInstanceState(
  partial: Partial<Omit<TLInstance, "currentPageId">>,
  historyOptions?: TLHistoryBatchOptions,
): this;

Parameters

NameDescription

partial

Partial<Omit<TLInstance, "currentPageId">>;

A partial object to update the instance state with.

historyOptions

History batch options.

Returns

this;

updatePage( )

Update a page.

updatePage(partial: RequiredKeys<Partial<TLPage>, "id">): this;

Example

editor.updatePage({ id: "page2", name: "Page 2" });

Parameters

NameDescription

partial

RequiredKeys<Partial<TLPage>, "id">;

The partial of the shape to update.

Returns

this;

updatePointer( )

Dispatch a pointer move event in the current position of the pointer. This is useful when external circumstances have changed (e.g. the camera moved or a shape was moved) and you want the current interaction to respond to that change.

updatePointer(options?: TLUpdatePointerOptions): this;

Example

editor.updatePointer();

Parameters

NameDescription

options

The options for updating the pointer.

Returns

this;

The editor instance.


updateShape( )

Update a shape using a partial of the shape.

updateShape<T extends TLShape = TLShape>(
  partial: null | TLShapePartial<T> | undefined,
): this;

Example

editor.updateShape({ id: "box1", type: "geo", props: { w: 100, h: 100 } });

Parameters

NameDescription

partial

null | TLShapePartial<T> | undefined;

The shape partial to update.

Returns

this;

updateShapes( )

Update shapes using partials of each shape.

updateShapes<T extends TLShape>(
  partials: (null | TLShapePartial<T> | undefined)[],
): this;

Example

editor.updateShapes([{ id: "box1", type: "geo", props: { w: 100, h: 100 } }]);

Parameters

NameDescription

partials

(null | TLShapePartial<T> | undefined)[];

The shape partials to update.

Returns

this;

updateViewportScreenBounds( )

Update the viewport. The viewport will measure the size and screen position of its container element. This should be done whenever the container's position on the screen changes.

updateViewportScreenBounds(
  screenBounds: Box | HTMLElement,
  center?: boolean,
): this;

Example

editor.updateViewportScreenBounds(new Box(0, 0, 1280, 1024));
editor.updateViewportScreenBounds(new Box(0, 0, 1280, 1024), true);

Parameters

NameDescription

screenBounds

Box | HTMLElement;

The new screen bounds of the viewport.

center

boolean;

Whether to preserve the viewport page center as the viewport changes.

Returns

this;

uploadAsset( )

Upload an asset to the store's asset service, returning a URL that can be used to resolve the asset.

uploadAsset(
  asset: TLAsset,
  file: File,
  abortSignal?: AbortSignal,
): Promise<{
  meta?: JsonObject;
  src: string;
}>;

Parameters

NameDescription

asset

TLAsset;

file

File;

abortSignal

AbortSignal;

Returns

Promise<{
  meta?: JsonObject;
  src: string;
}>;

visitDescendants( )

Run a visitor function for all descendants of a shape.

visitDescendants(
  parent: TLPage | TLParentId | TLShape,
  visitor: (id: TLShapeId) => false | void,
): this;

Example

editor.visitDescendants("frame1", myCallback);

Parameters

NameDescription

parent

The parent (or the id) of the parent shape.

visitor

(id: TLShapeId) => false | void;

The visitor function.

Returns

this;

wasEventAlreadyHandled( )

Checks if an event has already been handled. See Editor.markEventAsHandled.

wasEventAlreadyHandled(
  e:
    | {
        nativeEvent: Event;
      }
    | Event,
): boolean;

Parameters

NameDescription

e

  | {
      nativeEvent: Event;
    }
  | Event;

Returns

boolean;

zoomIn( )

Zoom the camera in.

zoomIn(point?: Vec, opts?: TLCameraMoveOptions): this;

Example

editor.zoomIn();
editor.zoomIn(editor.getViewportScreenCenter(), {
  animation: { duration: 200 },
});
editor.zoomIn(editor.inputs.getCurrentScreenPoint(), {
  animation: { duration: 200 },
});

Parameters

NameDescription

point

Vec;

The screen point to zoom in on. Defaults to the screen center

opts

The camera move options.

Returns

this;

zoomOut( )

Zoom the camera out.

zoomOut(point?: Vec, opts?: TLCameraMoveOptions): this;

Example

editor.zoomOut();
editor.zoomOut(editor.getViewportScreenCenter(), {
  animation: { duration: 120 },
});
editor.zoomOut(editor.inputs.getCurrentScreenPoint(), {
  animation: { duration: 120 },
});

Parameters

NameDescription

point

Vec;

The point to zoom out on. Defaults to the viewport screen center.

opts

The camera move options.

Returns

this;

zoomToBounds( )

Zoom the camera to fit a bounding box (in the current page space).

zoomToBounds(
  bounds: BoxLike,
  opts?: {
    inset?: number;
    targetZoom?: number;
  } & TLCameraMoveOptions,
): this;

Example

editor.zoomToBounds(myBounds);
editor.zoomToBounds(myBounds, { animation: { duration: 200 } });
editor.zoomToBounds(myBounds, {
  animation: { duration: 200 },
  inset: 0,
  targetZoom: 1,
});

Parameters

NameDescription

bounds

BoxLike;

The bounding box.

opts

{
  inset?: number;
  targetZoom?: number;
} & TLCameraMoveOptions;

The camera move options, target zoom, or custom inset amount.

Returns

this;

zoomToFit( )

Zoom the camera to fit the current page's content in the viewport.

zoomToFit(opts?: TLCameraMoveOptions): this;

Example

editor.zoomToFit();
editor.zoomToFit({ animation: { duration: 200 } });

Parameters

NameDescription

opts

The camera move options.

Returns

this;

zoomToSelection( )

Zoom the camera to fit the current selection in the viewport.

zoomToSelection(opts?: TLCameraMoveOptions): this;

Example

editor.zoomToSelection();
editor.zoomToSelection({ animation: { duration: 200 } });

Parameters

NameDescription

opts

The camera move options.

Returns

this;

zoomToSelectionIfOffscreen( )

Zoom the camera to the current selection if offscreen.

zoomToSelectionIfOffscreen(
  padding?: number,
  opts?: {
    inset?: number;
    targetZoom?: number;
  } & TLCameraMoveOptions,
): void;

Parameters

NameDescription

padding

number;

opts

{
  inset?: number;
  targetZoom?: number;
} & TLCameraMoveOptions;

Returns

void;

zoomToUser( )

Animate the camera to a user's cursor position. This also briefly show the user's cursor if it's not currently visible.

zoomToUser(userId: string, opts?: TLCameraMoveOptions): this;

Example

editor.zoomToUser(myUserId);
editor.zoomToUser(myUserId, { animation: { duration: 200 } });

Parameters

NameDescription

userId

string;

The id of the user to animate to.

opts

The camera move options.

Returns

this;

Prev
EdgeScrollManager
Next
EditorAtom