Editor
See source codeTable of contents
- bindingUtils
- contextId
- disposables
- edgeScrollManager
- fonts
- getContainer
- history
- id
- inputs
- isDisposed
- menus
- options
- root
- scribbles
- shapeUtils
- sideEffects
- snaps
- store
- styleProps
- textMeasure
- timers
- user
- Properties
- Methods
- _decayCameraStateTimeout
- _flushEventForTick
- _tickCameraState
- _updateCurrentPageState
- alignShapes
- animateShape
- animateShapes
- bail
- bailToMark
- blur
- bringForward
- bringToFront
- canBindShapes
- cancel
- cancelDoubleClick
- canCreateShape
- canCreateShapes
- centerOnPoint
- clearHistory
- complete
- createAssets
- createBinding
- createBindings
- createDeepLink
- createPage
- createShape
- createShapes
- createTemporaryAssetPreview
- deleteAssets
- deleteBinding
- deleteBindings
- deletePage
- deleteShape
- deleteShapes
- deselect
- dispatch
- dispose
- distributeShapes
- duplicatePage
- duplicateShapes
- findCommonAncestor
- findShapeAncestor
- flipShapes
- focus
- getAncestorPageId
- getAsset
- getAssetForExternalContent
- getAssets
- getBaseZoom
- getBinding
- getBindingsFromShape
- getBindingsInvolvingShape
- getBindingsToShape
- getBindingUtil
- getCamera
- getCameraOptions
- getCameraState
- getCanRedo
- getCanUndo
- getCollaborators
- getCollaboratorsOnCurrentPage
- getContentFromCurrentPage
- getCroppingShapeId
- getCulledShapes
- getCurrentPage
- getCurrentPageBounds
- getCurrentPageId
- getCurrentPageRenderingShapesSorted
- getCurrentPageShapeIds
- getCurrentPageShapes
- getCurrentPageShapesInReadingOrder
- getCurrentPageShapesSorted
- getCurrentPageState
- getCurrentTool
- getCurrentToolId
- getDocumentSettings
- getDraggingOverShape
- getEditingShape
- getEditingShapeId
- getErasingShapeIds
- getErasingShapes
- getFocusedGroup
- getFocusedGroupId
- getHighestIndexForParent
- getHintingShape
- getHintingShapeIds
- getHoveredShape
- getHoveredShapeId
- getInitialMetaForShape
- getInitialZoom
- getInstanceState
- getIsFocused
- getIsReadonly
- getNearestAdjacentShape
- getNotVisibleShapes
- getOnlySelectedShape
- getOnlySelectedShapeId
- getOutermostSelectableShape
- getPage
- getPages
- getPageShapeIds
- getPageStates
- getPath
- getPointInParentSpace
- getPointInShapeSpace
- getRenderingShapes
- getRichTextEditor
- getSelectedShapeAtPoint
- getSelectedShapeIds
- getSelectedShapes
- getSelectionPageBounds
- getSelectionRotatedPageBounds
- getSelectionRotatedScreenBounds
- getSelectionRotation
- getSelectionScreenBounds
- getShape
- getShapeAncestors
- getShapeAndDescendantIds
- getShapeAtPoint
- getShapeClipPath
- getShapeGeometry
- getShapeHandles
- getShapeLocalTransform
- getShapeMask
- getShapeMaskedPageBounds
- getShapePageBounds
- getShapePageTransform
- getShapeParent
- getShapeParentTransform
- getShapesAtPoint
- getShapesPageBounds
- getShapeStyleIfExists
- getShapeUtil
- getSharedOpacity
- getSharedStyles
- getSnapshot
- getSortedChildIdsForParent
- getStateDescendant
- getStyleForNextShape
- getSvgElement
- getSvgString
- getTemporaryAssetPreview
- getTextOptions
- getViewportPageBounds
- getViewportScreenBounds
- getViewportScreenCenter
- getZoomLevel
- groupShapes
- hasAncestor
- hasExternalAssetHandler
- hasShapeUtil
- interrupt
- isAncestorSelected
- isIn
- isInAny
- isPointInShape
- isShapeHidden
- isShapeInPage
- isShapeOfType
- isShapeOrAncestorLocked
- loadSnapshot
- markEventAsHandled
- markHistoryStoppingPoint
- moveShapesToPage
- navigateToDeepLink
- nudgeShapes
- packShapes
- pageToScreen
- pageToViewport
- popFocusedGroupId
- putContentOntoCurrentPage
- putExternalContent
- redo
- registerDeepLinkListener
- registerExternalAssetHandler
- registerExternalContentHandler
- renamePage
- reparentShapes
- replaceExternalContent
- resetZoom
- resizeShape
- resolveAssetsInContent
- resolveAssetUrl
- rotateShapesBy
- run
- screenToPage
- select
- selectAdjacentShape
- selectAll
- selectFirstChildShape
- selectNone
- selectParentShape
- sendBackward
- sendToBack
- setCamera
- setCameraOptions
- setCroppingShape
- setCurrentPage
- setCurrentTool
- setCursor
- setEditingShape
- setErasingShapes
- setFocusedGroup
- setHintingShapes
- setHoveredShape
- setOpacityForNextShapes
- setOpacityForSelectedShapes
- setRichTextEditor
- setSelectedShapes
- setStyleForNextShapes
- setStyleForSelectedShapes
- slideCamera
- squashToMark
- stackShapes
- startFollowingUser
- stopCameraAnimation
- stopFollowingUser
- stretchShapes
- toggleLock
- toImage
- toImageDataUrl
- undo
- ungroupShapes
- updateAssets
- updateBinding
- updateBindings
- updateCurrentPageState
- updateDocumentSettings
- updateInstanceState
- updatePage
- updatePointer
- updateShape
- updateShapes
- updateViewportScreenBounds
- uploadAsset
- visitDescendants
- wasEventAlreadyHandled
- zoomIn
- zoomOut
- zoomToBounds
- zoomToFit
- zoomToSelection
- zoomToSelectionIfOffscreen
- zoomToUser
Extends EventEmitter<TLEventMap>.
class Editor extends EventEmitter<TLEventMap> {}Constructor
Constructs a new instance of the Editor class
Parameters
| Name | Description |
|---|---|
|
Properties
bindingUtils
A map of shape utility classes (TLShapeUtils) by shape type.
bindingUtils: {
readonly [K in string]?: BindingUtil<TLUnknownBinding>
}contextId
readonly contextId: stringdisposables
A set of functions to call when the app is disposed.
readonly disposables: Set<() => void>edgeScrollManager
A manager for moving the camera when the mouse is at the edge of the screen.
edgeScrollManager: EdgeScrollManagerfonts
A utility for managing the set of fonts that should be rendered in the document.
readonly fonts: FontManagergetContainer
The current HTML element containing the editor.
getContainer: () => HTMLElementExample
const container = editor.getContainer()history
A manager for the app's history.
protected readonly history: HistoryManager<TLRecord>id
readonly id: stringinputs
The app's current input state.
inputs: {
buttons: Set<number>
keys: Set<string>
originScreenPoint: Vec
originPagePoint: Vec
currentScreenPoint: Vec
currentPagePoint: Vec
previousScreenPoint: Vec
previousPagePoint: Vec
pointerVelocity: Vec
altKey: boolean
ctrlKey: boolean
isPen: boolean
metaKey: boolean
shiftKey: boolean
isDragging: boolean
isEditing: boolean
isPanning: boolean
isPinching: boolean
isPointing: boolean
isSpacebarPanning: boolean
}isDisposed
Whether the editor is disposed.
isDisposed: booleanmenus
menus: {
addOpenMenu: (id: string) => void
clearOpenMenus: () => void
deleteOpenMenu: (id: string) => void
getOpenMenus: () => string[]
hasAnyOpenMenus: () => boolean
hasOpenMenus: () => boolean
isMenuOpen: (id: string) => boolean
}options
readonly options: TldrawOptionsroot
The root state of the statechart.
readonly root: StateNodescribbles
A manager for the editor's scribbles.
readonly scribbles: ScribbleManagershapeUtils
A map of shape utility classes (TLShapeUtils) by shape type.
shapeUtils: {
readonly [K in string]?: ShapeUtil<TLUnknownShape>
}sideEffects
A manager for side effects and correct state enforcement. See StoreSideEffects for details.
readonly sideEffects: StoreSideEffects<TLRecord>snaps
A manager for the app's snapping feature.
readonly snaps: SnapManagerstore
The editor's store
readonly store: TLStorestyleProps
styleProps: {
[key: string]: Map<StyleProp<any>, string>
}textMeasure
A helper for measuring text.
readonly textMeasure: TextManagertimers
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,
...args: any[]
) => number
setTimeout: (
handler: TimerHandler,
timeout?: number,
...args: any[]
) => number
}user
A manager for the user and their preferences.
readonly user: UserPreferencesManagerMethods
alignShapes( )
Align shape positions.
alignShapes(
shapes: TLShape[] | TLShapeId[],
operation:
| 'bottom'
| 'center-horizontal'
| 'center-vertical'
| 'left'
| 'right'
| 'top'
): thisExample
editor.alignShapes([box1, box2], 'left')
editor.alignShapes(editor.getSelectedShapeIds(), 'left')Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to align. |
| The align operation to apply. |
Returns
thisanimateShape( )
Animate a shape.
animateShape(
partial: null | TLShapePartial | undefined,
opts?: TLCameraMoveOptions
): thisExample
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
| Name | Description |
|---|---|
| The shape partial to update. |
| The animation's options. |
Returns
thisanimateShapes( )
Animate shapes.
animateShapes(
partials: (null | TLShapePartial | undefined)[],
opts?: TLCameraMoveOptions
): thisExample
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
| Name | Description |
|---|---|
| The shape partials to update. |
| The animation's options. |
Returns
thisbail( )
Undo to the closest mark, discarding the changes so they cannot be redone.
bail(): thisExample
editor.bail()bailToMark( )
Undo to the given mark, discarding the changes so they cannot be redone.
bailToMark(id: string): thisExample
const beginDrag = editor.markHistoryStoppingPoint()
// ... some changes
editor.bailToMark(beginDrag)Parameters
| Name | Description |
|---|---|
| |
Returns
thisblur( )
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 }): thisExample
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
| Name | Description |
|---|---|
| |
Returns
thisbringForward( )
Bring shapes forward in the page's object list.
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
| Name | Description |
|---|---|
| The shapes (or shape ids) to move. |
| The options for the forward operation. |
Returns
thisbringToFront( )
Bring shapes to the front of the page's object list.
Example
editor.bringToFront(['id1', 'id2'])
editor.bringToFront([box1, box2])Parameters
Returns
thiscanBindShapes( )
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']
}): booleanParameters
| Name | Description |
|---|---|
|
Returns
booleancancel( )
Dispatch a cancel event.
cancel(): thisExample
editor.cancel()cancelDoubleClick( )
Prevent a double click event from firing the next time the user clicks
cancelDoubleClick(): voidcanCreateShape( )
Get whether the provided shape can be created.
canCreateShape<T extends TLUnknownShape>(
shape: OptionalKeys<TLShapePartial<T>, 'id'> | T['id']
): booleanParameters
| Name | Description |
|---|---|
| The shape or shape IDs to check. |
Returns
booleancanCreateShapes( )
Get whether the provided shapes can be created.
canCreateShapes<T extends TLUnknownShape>(
shapes: (OptionalKeys<TLShapePartial<T>, 'id'> | T['id'])[]
): booleanParameters
| Name | Description |
|---|---|
| The shapes or shape IDs to create. |
Returns
booleancenterOnPoint( )
Center the camera on a point (in the current page space).
centerOnPoint(point: VecLike, opts?: TLCameraMoveOptions): thisExample
editor.centerOnPoint({ x: 100, y: 100 })
editor.centerOnPoint({ x: 100, y: 100 }, { animation: { duration: 200 } })Parameters
| Name | Description |
|---|---|
| The point in the current page space to center on. |
| The camera move options. |
Returns
thisclearHistory( )
clearHistory(): thiscomplete( )
Dispatch a complete event.
complete(): thisExample
editor.complete()createAssets( )
Create one or more assets.
createAssets(assets: TLAsset[]): thisExample
editor.createAssets([...myAssets])Parameters
| Name | Description |
|---|---|
| The assets to create. |
Returns
thiscreateBinding( )
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>
): thisParameters
| Name | Description |
|---|---|
|
Returns
thiscreateBindings( )
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>[]
): thisParameters
| Name | Description |
|---|---|
| |
Returns
thiscreateDeepLink( )
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
}): URLExample
// 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
| Name | Description |
|---|---|
| Options for adding the state to the URL. |
Returns
URLthe updated URL
createPage( )
Create a page whilst ensuring that the page name is unique.
createPage(page: Partial<TLPage>): thisExample
editor.createPage(myPage)
editor.createPage({ name: 'Page 2' })Parameters
| Name | Description |
|---|---|
| The page (or page partial) to create. |
Returns
thiscreateShape( )
Create a single shape.
createShape<T extends TLUnknownShape>(
shape: OptionalKeys<TLShapePartial<T>, 'id'>
): thisExample
editor.createShape(myShape)
editor.createShape({
id: 'box1',
type: 'text',
props: { richText: toRichText('ok') },
})Parameters
| Name | Description |
|---|---|
| The shape (or shape partial) to create. |
Returns
thiscreateShapes( )
Create shapes.
createShapes<T extends TLUnknownShape>(
shapes: OptionalKeys<TLShapePartial<T>, 'id'>[]
): thisExample
editor.createShapes([myShape])
editor.createShapes([
{ id: 'box1', type: 'text', props: { richText: toRichText('ok') } },
])Parameters
| Name | Description |
|---|---|
| The shapes (or shape partials) to create. |
Returns
thiscreateTemporaryAssetPreview( )
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 | undefinedExample
editor.createTemporaryAssetPreview(assetId, file)Parameters
| Name | Description |
|---|---|
| The asset's id. |
| The raw file. |
Returns
string | undefineddeleteAssets( )
Delete one or more assets.
Example
editor.deleteAssets(['asset1', 'asset2'])Parameters
Returns
thisdeleteBinding( )
Delete a binding by its ID. If the binding doesn't exist, it's ignored.
deleteBinding(
binding: TLBinding | TLBindingId,
opts?: Parameters<this['deleteBindings']>[1]
): thisParameters
| Name | Description |
|---|---|
| |
| |
Returns
thisdeleteBindings( )
Delete several bindings by their IDs. If a binding ID doesn't exist, it's ignored.
deleteBindings(
bindings: (TLBinding | TLBindingId)[],
{
isolateShapes,
}?: {
isolateShapes?: boolean | undefined
}
): thisParameters
| Name | Description |
|---|---|
| |
| |
Returns
thisdeletePage( )
Delete a page.
Example
editor.deletePage('page1')Parameters
Returns
thisdeleteShape( )
Delete a shape.
deleteShape(id: TLShapeId): thisExample
editor.deleteShape(shape.id)Parameters
| Name | Description |
|---|---|
| The id of the shape to delete. |
Returns
thisdeleteShapes( )
Delete shapes.
deleteShapes(ids: TLShapeId[]): thisExample
editor.deleteShapes(['box1', 'box2'])Parameters
| Name | Description |
|---|---|
| The ids of the shapes to delete. |
Returns
thisdeselect( )
Remove a shape from the existing set of selected shapes.
Example
editor.deselect(shape.id)Parameters
Returns
thisdispatch( )
Dispatch an event to the editor.
dispatch(info: TLEventInfo): thisExample
editor.dispatch(myPointerEvent)Parameters
| Name | Description |
|---|---|
| The event info. |
Returns
thisdispose( )
Dispose the editor.
dispose(): voiddistributeShapes( )
Distribute shape positions.
Example
editor.distributeShapes([box1, box2], 'horizontal')
editor.distributeShapes(editor.getSelectedShapeIds(), 'horizontal')Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to distribute. |
| Whether to distribute shapes horizontally or vertically. |
Returns
thisduplicatePage( )
Duplicate a page.
Parameters
| Name | Description |
|---|---|
| The page (or the page id) to duplicate. Defaults to the current page. |
| The id of the new page. Defaults to a new id. |
Returns
thisduplicateShapes( )
Duplicate shapes.
Example
editor.duplicateShapes(['box1', 'box2'], { x: 8, y: 8 })
editor.duplicateShapes(editor.getSelectedShapes(), { x: 8, y: 8 })Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to duplicate. |
| The offset (in pixels) to apply to the duplicated shapes. |
Returns
thisfindCommonAncestor( )
Get the common ancestor of two or more shapes that matches a predicate.
findCommonAncestor(
shapes: TLShape[] | TLShapeId[],
predicate?: (shape: TLShape) => boolean
): TLShapeId | undefinedParameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to check. |
| The predicate to match. |
Returns
TLShapeId | undefinedfindShapeAncestor( )
Find the first ancestor matching the given predicate
findShapeAncestor(
shape: TLShape | TLShapeId,
predicate: (parent: TLShape) => boolean
): TLShape | undefinedExample
const ancestor = editor.findShapeAncestor(myShape)
const ancestor = editor.findShapeAncestor(myShape.id)
const ancestor = editor.findShapeAncestor(
myShape.id,
(shape) => shape.type === 'frame'
)Parameters
| Name | Description |
|---|---|
| The shape to check the ancestors for. |
| The predicate to match. |
Returns
TLShape | undefinedflipShapes( )
Flip shape positions.
Example
editor.flipShapes([box1, box2], 'horizontal', 32)
editor.flipShapes(editor.getSelectedShapeIds(), 'horizontal', 32)Parameters
| Name | Description |
|---|---|
| The ids of the shapes to flip. |
| Whether to flip horizontally or vertically. |
Returns
thisfocus( )
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 }): thisExample
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
| Name | Description |
|---|---|
| |
Returns
thisgetAncestorPageId( )
Get the id of the containing page for a given shape.
Parameters
Returns
TLPageId | undefinedThe 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 | undefinedExample
editor.getAsset('asset1')Parameters
| Name | Description |
|---|---|
| The asset (or asset id) to get. |
Returns
T | undefinedgetAssetForExternalContent( )
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
| Name | Description |
|---|---|
| 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
)[]getBaseZoom( )
Get the camera's base level for calculating actual zoom levels based on the zoom steps.
getBaseZoom(): numberExample
editor.getBaseZoom()getBinding( )
Get a binding from the store by its ID if it exists.
getBinding(id: TLBindingId): TLBinding | undefinedParameters
| Name | Description |
|---|---|
|
Returns
TLBinding | undefinedgetBindingsFromShape( )
Get all bindings of a certain type from a particular shape. These are the bindings whose
fromId matched the shape's ID.
getBindingsFromShape<Binding extends TLUnknownBinding = TLBinding>(
shape: TLShape | TLShapeId,
type: Binding['type']
): Binding[]Parameters
Returns
Binding[]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<Binding extends TLUnknownBinding = TLBinding>(
shape: TLShape | TLShapeId,
type?: Binding['type']
): Binding[]Parameters
Returns
Binding[]getBindingsToShape( )
Get all bindings of a certain type to a particular shape. These are the bindings whose
toId matches the shape's ID.
getBindingsToShape<Binding extends TLUnknownBinding = TLBinding>(
shape: TLShape | TLShapeId,
type: Binding['type']
): Binding[]Parameters
Returns
Binding[]getBindingUtil( )
Get a binding util from a binding itself.
getBindingUtil<S extends TLUnknownBinding>(
binding:
| {
type: S['type']
}
| S
): BindingUtil<S>Example
const util = editor.getBindingUtil(myArrowBinding)
const util = editor.getBindingUtil('arrow')
const util = editor.getBindingUtil<TLArrowBinding>(myArrowBinding)
const util = editor.getBindingUtil(TLArrowBinding)('arrow')Parameters
| Name | Description |
|---|---|
| A binding, binding partial, or binding type. |
Returns
BindingUtil<S>getCamera( )
The current camera.
getCamera(): TLCameragetCameraOptions( )
Get the current camera options.
getCameraOptions(): TLCameraOptionsExample
editor.getCameraOptions()getCameraState( )
Whether the camera is moving or idle.
getCameraState(): 'idle' | 'moving'Example
editor.getCameraState()getCanRedo( )
Whether the app can redo.
getCanRedo(): booleangetCanUndo( )
Whether the app can undo.
getCanUndo(): booleangetCollaborators( )
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.
Parameters
Returns
TLContent | undefinedThe exported content.
getCroppingShapeId( )
The current cropping shape's id.
getCroppingShapeId(): null | TLShapeIdgetCulledShapes( )
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(): TLPageExample
editor.getCurrentPage()getCurrentPageBounds( )
The bounds of the current page (the common bounds of all of the shapes on the page).
getCurrentPageBounds(): Box | undefinedgetCurrentPageId( )
The current page id.
getCurrentPageId(): TLPageIdExample
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(): TLInstancePageStategetCurrentTool( )
The current selected tool.
getCurrentTool(): StateNodegetCurrentToolId( )
The id of the current selected tool.
getCurrentToolId(): stringgetDocumentSettings( )
The global document settings that apply to all users.
getDocumentSettings(): TLDocumentgetDraggingOverShape( )
Get the shape that some shapes should be dropped on at a given point.
Parameters
| Name | Description |
|---|---|
| The point to find the parent for. |
| The shapes that are being dropped. |
Returns
TLShape | undefinedThe shape to drop on.
getEditingShape( )
The current editing shape.
getEditingShape(): TLShape | undefinedgetEditingShapeId( )
The current editing shape's id.
getEditingShapeId(): null | TLShapeIdgetErasingShapeIds( )
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 | undefinedgetFocusedGroupId( )
The current focused group id.
getHighestIndexForParent( )
Get the index above the highest child of a given parent.
getHighestIndexForParent(parent: TLPage | TLParentId | TLShape): IndexKeyParameters
| Name | Description |
|---|---|
| The parent (or the id) of the parent. |
Returns
IndexKeyThe 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 | undefinedgetHoveredShapeId( )
The current hovered shape id.
getHoveredShapeId(): null | TLShapeIdgetInitialMetaForShape( )
Get the initial meta value for a shape.
getInitialMetaForShape(_shape: TLShape): JsonObjectExample
editor.getInitialMetaForShape = (shape) => {
if (shape.type === 'note') {
return { createdBy: myCurrentUser.id }
}
}Parameters
| Name | Description |
|---|---|
|
Returns
JsonObjectgetInitialZoom( )
Get the camera's initial or reset zoom level.
getInitialZoom(): numberExample
editor.getInitialZoom()getInstanceState( )
The current instance's state.
getInstanceState(): TLInstancegetIsFocused( )
getIsFocused(): booleangetIsReadonly( )
getIsReadonly(): booleangetNearestAdjacentShape( )
Find the nearest adjacent shape in a specific direction.
getNearestAdjacentShape(
shapes: TLShape[],
currentShapeId: TLShapeId,
direction: 'down' | 'left' | 'right' | 'up'
): TLShapeIdParameters
Returns
getNotVisibleShapes( )
Get shapes that are outside of the viewport.
getNotVisibleShapes(): Set<TLShapeId>getOnlySelectedShape( )
The app's only selected shape.
getOnlySelectedShape(): null | TLShapegetOnlySelectedShapeId( )
The id of the app's only selected shape.
getOnlySelectedShapeId(): null | TLShapeIdgetOutermostSelectableShape( )
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
): TLShapeParameters
| Name | Description |
|---|---|
| The shape to get the outermost selectable shape for. |
| A function to filter the selectable shapes. |
Returns
The outermost selectable shape.
getPage( )
Get a page.
Example
editor.getPage(myPage.id)
editor.getPage(myPage)Parameters
Returns
TLPage | undefinedgetPages( )
Info about the project's current pages.
getPages(): TLPage[]Example
editor.getPages()getPageShapeIds( )
Get the ids of shapes on a page.
Example
const idsOnPage1 = editor.getPageShapeIds('page1')
const idsOnPage2 = editor.getPageShapeIds(myPage2)Parameters
Returns
Set<TLShapeId>getPageStates( )
Page states.
getPageStates(): TLInstancePageState[]getPath( )
The editor's current path of active states.
getPath(): stringExample
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.
Example
editor.getPointInParentSpace(myShape.id, { x: 100, y: 100 })Parameters
| Name | Description |
|---|---|
| The shape to get the point in the local space of. |
| The page point to get in the local space of the shape. |
Returns
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.
Example
editor.getPointInShapeSpace(myShape, { x: 100, y: 100 })Parameters
| Name | Description |
|---|---|
| The shape to get the point in the local space of. |
| The page point to get in the local space of the shape. |
Returns
getRenderingShapes( )
Get the shapes that should be displayed in the current viewport.
getRenderingShapes(): TLRenderingShape[]Example
editor.getRenderingShapes()getRichTextEditor( )
The current editing shape's text editor.
getRichTextEditor(): null | TiptapEditorgetSelectedShapeAtPoint( )
Get the top-most selected shape at the given point, ignoring groups.
Parameters
| Name | Description |
|---|---|
| The point to check. |
Returns
TLShape | undefinedThe 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 | nullgetSelectionRotatedPageBounds( )
The bounds of the selection bounding box in the current page space.
getSelectionRotatedPageBounds(): Box | undefinedgetSelectionRotatedScreenBounds( )
The bounds of the selection bounding box in the current page space.
getSelectionRotatedScreenBounds(): Box | undefinedgetSelectionRotation( )
The rotation of the selection bounding box in the current page space.
getSelectionRotation(): numbergetSelectionScreenBounds( )
The bounds of the selection bounding box in the current page space.
getSelectionScreenBounds(): Box | undefinedgetShape( )
Get a shape by its id.
getShape<T extends TLShape = TLShape>(
shape: TLParentId | TLShape
): T | undefinedExample
editor.getShape('box1')Parameters
| Name | Description |
|---|---|
| The shape (or the id of the shape) to get. |
Returns
T | undefinedgetShapeAncestors( )
Get the ancestors of a shape.
Example
const ancestors = editor.getShapeAncestors(myShape)
const ancestors = editor.getShapeAncestors(myShapeId)Parameters
| Name | Description |
|---|---|
| The shape (or shape id) to get the ancestors for. |
| 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.
Parameters
| Name | Description |
|---|---|
| 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 | undefinedParameters
| Name | Description |
|---|---|
| The point to check. |
| Options for the check: |
Returns
TLShape | undefinedThe shape at the given point, or undefined if there is no shape at the point.
getShapeClipPath( )
Get the clip path for a shape.
Example
const clipPath = editor.getShapeClipPath(shape)
const clipPath = editor.getShapeClipPath(shape.id)Parameters
Returns
string | undefinedThe clip path or undefined.
getShapeGeometry( )
Get the geometry of a shape in shape-space.
getShapeGeometry<T extends Geometry2d>(
shape: TLShape | TLShapeId,
opts?: TLGeometryOpts
): TExample
editor.getShapeGeometry(myShape)
editor.getShapeGeometry(myShapeId)
editor.getShapeGeometry(myShapeId, { context: 'arrow' })Parameters
| Name | Description |
|---|---|
| The shape (or shape id) to get the geometry for. |
| Additional options about the request for geometry. Passed to ShapeUtil.getGeometry. |
Returns
TgetShapeHandles( )
Get the handles (if any) for a shape.
Example
editor.getShapeHandles(myShape)
editor.getShapeHandles(myShapeId)Parameters
| Name | Description |
|---|---|
| The shape (or shape id) to get the handles for. |
Returns
TLHandle[] | undefinedgetShapeLocalTransform( )
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.
Example
editor.getShapeLocalTransform(myShape)Parameters
Returns
getShapeMask( )
Get the mask (in the current page space) for a shape.
Example
const pageMask = editor.getShapeMask(shape.id)Parameters
| Name | Description |
|---|---|
| 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.
Example
editor.getShapeMaskedPageBounds(myShape)
editor.getShapeMaskedPageBounds(myShapeId)Parameters
Returns
Box | undefinedgetShapePageBounds( )
Get the bounds of a shape in the current page space.
Example
editor.getShapePageBounds(myShape)
editor.getShapePageBounds(myShapeId)Parameters
Returns
Box | undefinedgetShapePageTransform( )
Get the transform of a shape in the current page space.
Example
editor.getShapePageTransform(myShape)
editor.getShapePageTransform(myShapeId)Parameters
Returns
getShapeParent( )
Get the parent shape for a given shape. Returns undefined if the shape is the direct child of the page.
Example
editor.getShapeParent(myShape)Parameters
Returns
TLShape | undefinedgetShapeParentTransform( )
Get the local transform of a shape's parent as a matrix model.
Example
editor.getShapeParentTransform(myShape)Parameters
Returns
getShapesAtPoint( )
Get the shapes, if any, at a given page point.
Example
editor.getShapesAtPoint({ x: 100, y: 100 })
editor.getShapesAtPoint({ x: 100, y: 100 }, { hitInside: true, margin: 8 })Parameters
| Name | Description |
|---|---|
| The page point to test. |
| 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.
Parameters
| Name | Description |
|---|---|
|
Returns
Box | nullgetShapeStyleIfExists( )
Parameters
Returns
T | undefinedgetShapeUtil( )
Get a shape util from a shape itself.
getShapeUtil<S extends TLUnknownShape>(
shape: S | TLShapePartial<S>
): ShapeUtil<S>Example
const util = editor.getShapeUtil(myArrowShape)
const util = editor.getShapeUtil('arrow')
const util = editor.getShapeUtil<TLArrowShape>(myArrowShape)
const util = editor.getShapeUtil(TLArrowShape)('arrow')Parameters
| Name | Description |
|---|---|
| A shape, shape partial, or shape type. |
Returns
ShapeUtil<S>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(): ReadonlySharedStyleMapExample
const color = editor.getSharedStyles().get(DefaultColorStyle)
if (color && color.type === 'shared') {
print('All selected shapes have the same color:', color.value)
}getSnapshot( )
getSnapshot(): TLEditorSnapshotgetSortedChildIdsForParent( )
Get an array of all the children of a shape.
getSortedChildIdsForParent(parent: TLPage | TLParentId | TLShape): TLShapeId[]Example
editor.getSortedChildIdsForParent('frame1')Parameters
| Name | Description |
|---|---|
| The parent (or the id) of the parent shape. |
Returns
getStateDescendant( )
Get a descendant by its path.
getStateDescendant<T extends StateNode>(path: string): T | undefinedExample
editor.getStateDescendant('select')
editor.getStateDescendant('select.brushing')Parameters
| Name | Description |
|---|---|
| The descendant's path of state ids, separated by periods. |
Returns
T | undefinedgetStyleForNextShape( )
Get the style for the next shape.
getStyleForNextShape<T>(style: StyleProp<T>): TExample
const color = editor.getStyleForNextShape(DefaultColorStyle)Parameters
| Name | Description |
|---|---|
| The style to get. |
Returns
TgetSvgElement( )
Get an exported SVG element of the given shapes.
getSvgElement(
shapes: TLShape[] | TLShapeId[],
opts?: TLSvgExportOptions
): Promise<
| {
height: number
svg: SVGSVGElement
width: number
}
| undefined
>Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to export. |
| Options for the export. |
Returns
Promise<
| {
height: number
svg: SVGSVGElement
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
width: number
}
| undefined
>Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to export. |
| Options for the export. |
Returns
Promise<
| {
height: number
svg: string
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 | undefinedExample
editor.getTemporaryAssetPreview('someId')Parameters
| Name | Description |
|---|---|
| The asset's id. |
Returns
string | undefinedgetTextOptions( )
Get the current text options.
getTextOptions(): TLTextOptionsExample
editor.getTextOptions()getViewportPageBounds( )
The current viewport in the current page space.
getViewportPageBounds(): BoxgetViewportScreenBounds( )
The bounds of the editor's viewport in screen space.
getViewportScreenBounds(): BoxgetViewportScreenCenter( )
The center of the editor's viewport in screen space.
getViewportScreenCenter(): VecgetZoomLevel( )
The current camera zoom level.
getZoomLevel(): numbergroupShapes( )
Create a group containing the provided shapes.
Example
editor.groupShapes([myShape, myOtherShape])
editor.groupShapes([myShape, myOtherShape], {
groupId: myGroupId,
select: false,
})Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to group. Defaults to the selected shapes. |
| An options object. |
Returns
thishasAncestor( )
Returns true if the the given shape has the given ancestor.
Parameters
| Name | Description |
|---|---|
| The shape. |
| The id of the ancestor. |
Returns
booleanhasExternalAssetHandler( )
hasExternalAssetHandler(type: TLExternalAsset['type']): booleanParameters
| Name | Description |
|---|---|
| |
Returns
booleanhasShapeUtil( )
Returns true if the editor has a shape util for the given shape / shape type.
hasShapeUtil<S extends TLUnknownShape>(shape: S | TLShapePartial<S>): booleanParameters
| Name | Description |
|---|---|
| A shape, shape partial, or shape type. |
Returns
booleaninterrupt( )
Dispatch an interrupt event.
interrupt(): thisExample
editor.interrupt()isAncestorSelected( )
Determine whether or not any of a shape's ancestors are selected.
Parameters
Returns
booleanisIn( )
Get whether a certain tool (or other state node) is currently active.
isIn(path: string): booleanExample
editor.isIn('select')
editor.isIn('select.brushing')Parameters
| Name | Description |
|---|---|
| The path of active states, separated by periods. |
Returns
booleanisInAny( )
Get whether the state node is in any of the given active paths.
isInAny(...paths: string[]): booleanExample
state.isInAny('select', 'erase')
state.isInAny('select.brushing', 'erase.idle')Parameters
| Name | Description |
|---|---|
| |
Returns
booleanisPointInShape( )
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
margin?: number
}
): booleanExample
editor.isPointInShape({ x: 100, y: 100 }, myShape)Parameters
| Name | Description |
|---|---|
| The shape to test against. |
| The page point to test (in the current page space). |
| The options for the hit point testing. |
Returns
booleanisShapeHidden( )
Parameters
Returns
booleanisShapeInPage( )
Get whether the given shape is the descendant of the given page.
Example
editor.isShapeInPage(myShape)
editor.isShapeInPage(myShape, 'page1')Parameters
| Name | Description |
|---|---|
| The shape to check. |
| The id of the page to check against. Defaults to the current page. |
Returns
booleanisShapeOfType( )
Get whether a shape matches the type of a TLShapeUtil.
isShapeOfType<T extends TLUnknownShape>(
shape: TLUnknownShape,
type: T['type']
): shape is TExample
const isArrowShape = isShapeOfType<TLArrowShape>(someShape, 'arrow')Parameters
| Name | Description |
|---|---|
| the shape to test |
| |
Returns
shape is TisShapeOrAncestorLocked( )
Check whether a shape or its parent is locked.
Parameters
Returns
booleanloadSnapshot( )
Loads a snapshot into the editor.
loadSnapshot(
snapshot: Partial<TLEditorSnapshot> | TLStoreSnapshot,
opts?: TLLoadSnapshotOptions
): thisParameters
| Name | Description |
|---|---|
| The snapshot to load. |
| The options for loading the snapshot. |
Returns
thismarkEventAsHandled( )
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
): voidParameters
| Name | Description |
|---|---|
| |
Returns
voidmarkHistoryStoppingPoint( )
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): stringExample
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
| Name | Description |
|---|---|
| The name of the mark, useful for debugging the undo/redo stacks |
Returns
stringa unique id for the mark that can be used with squashToMark or bailToMark.
moveShapesToPage( )
Move shapes to page.
Example
editor.moveShapesToPage(['box1', 'box2'], 'page1')Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) of the shapes to move. |
| The id of the page where the shapes will be moved. |
Returns
thisnavigateToDeepLink( )
Handles navigating to the content specified by the query param in the given URL.
Use 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
): EditorExample
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
| Name | Description |
|---|---|
| Options for loading the state from the URL. |
Returns
nudgeShapes( )
Move shapes by a delta.
Example
editor.nudgeShapes(['box1', 'box2'], { x: 8, y: 8 })Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to move. |
| The offset to apply to the shapes. |
Returns
thispackShapes( )
Pack shapes into a grid centered on their current position. Based on potpack (https://github.com/mapbox/potpack).
Example
editor.packShapes([box1, box2])
editor.packShapes(editor.getSelectedShapeIds(), 32)Parameters
Returns
thispageToScreen( )
Convert a point in the current page space to a point in current screen space.
Example
editor.pageToScreen({ x: 100, y: 100 })Parameters
| Name | Description |
|---|---|
| The point in page space. |
Returns
pageToViewport( )
Convert a point in the current page space to a point in current viewport space.
Example
editor.pageToViewport({ x: 100, y: 100 })Parameters
| Name | Description |
|---|---|
| The point in page space. |
Returns
popFocusedGroupId( )
Exit the current focused group, moving up to the next parent group if there is one.
popFocusedGroupId(): thisputContentOntoCurrentPage( )
Place content into the editor.
putContentOntoCurrentPage(
content: TLContent,
opts?: {
point?: VecLike
preserveIds?: boolean
preservePosition?: boolean
select?: boolean
}
): thisParameters
| Name | Description |
|---|---|
| The content. |
| Options for placing the content. |
Returns
thisputExternalContent( )
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
}
): Promise<void>Parameters
| Name | Description |
|---|---|
| Info about the external content. |
| Options for handling external content, including force flag to bypass readonly checks. |
Returns
Promise<void>redo( )
Redo to the next mark.
redo(): thisExample
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): () => voidExample
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
| Name | Description |
|---|---|
| Options for setting up the listener. |
Returns
() => voida 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
): thisExample
editor.registerExternalAssetHandler('file', myHandler)Parameters
| Name | Description |
|---|---|
| The type of external content. |
| The handler to use for this content type. |
Returns
thisregisterExternalContentHandler( )
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
): thisExample
editor.registerExternalContentHandler('text', myHandler)editor.registerExternalContentHandler<'embed', MyEmbedType>('embed', myHandler)Parameters
| Name | Description |
|---|---|
| The type of external content. |
| The handler to use for this content type. |
Returns
thisrenamePage( )
Rename a page.
Example
editor.renamePage('page1', 'My Page')Parameters
Returns
thisreparentShapes( )
Reparent shapes to a new parent. This operation preserves the shape's current page positions / rotations.
reparentShapes(
shapes: TLShape[] | TLShapeId[],
parentId: TLParentId,
insertIndex?: IndexKey
): thisExample
editor.reparentShapes([box1, box2], 'frame1')
editor.reparentShapes([box1.id, box2.id], 'frame1')
editor.reparentShapes([box1.id, box2.id], 'frame1', 4)Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) of the shapes to reparent. |
| The id of the new parent shape. |
| The index to insert the children. |
Returns
thisreplaceExternalContent( )
Handle replacing external content.
replaceExternalContent<E>(
info: TLExternalContent<E>,
opts?: {
force?: boolean
}
): Promise<void>Parameters
| Name | Description |
|---|---|
| Info about the external content. |
| 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): thisExample
editor.resetZoom()
editor.resetZoom(editor.getViewportScreenCenter(), {
animation: { duration: 200 },
})
editor.resetZoom(editor.getViewportScreenCenter(), {
animation: { duration: 200 },
})Parameters
| Name | Description |
|---|---|
| The screen point to zoom out on. Defaults to the viewport screen center. |
| The camera move options. |
Returns
thisresizeShape( )
Resize a shape.
resizeShape(
shape: TLShape | TLShapeId,
scale: VecLike,
opts?: TLResizeShapeOptions
): thisParameters
| Name | Description |
|---|---|
| The shape (or the shape id of the shape) to resize. |
| The scale factor to apply to the shape. |
| Additional options. |
Returns
thisresolveAssetsInContent( )
Parameters
| Name | Description |
|---|---|
| |
Returns
Promise<TLContent | undefined>resolveAssetUrl( )
resolveAssetUrl(
assetId: null | TLAssetId,
context: {
dpr?: number
screenScale?: number
shouldResolveToOriginal?: boolean
}
): Promise<null | string>Parameters
| Name | Description |
|---|---|
| |
| |
Returns
Promise<null | string>rotateShapesBy( )
Rotate shapes by a delta in radians.
Example
editor.rotateShapesBy(editor.getSelectedShapeIds(), Math.PI)
editor.rotateShapesBy(editor.getSelectedShapeIds(), Math.PI / 2)Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) of the shapes to move. |
| The delta in radians to apply to the selection rotation. |
| The options for the rotation. |
Returns
thisrun( )
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): thisExample
// 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
| Name | Description |
|---|---|
| The callback function to run. |
| The options for the batch. |
Returns
thisscreenToPage( )
Convert a point in screen space to a point in the current page space.
Example
editor.screenToPage({ x: 100, y: 100 })Parameters
| Name | Description |
|---|---|
| The point in screen space. |
Returns
select( )
Select one or more shapes.
Example
editor.select('id1')
editor.select('id1', 'id2')Parameters
Returns
thisselectAdjacentShape( )
Select the next shape in the reading order or in cardinal order.
selectAdjacentShape(direction: TLAdjacentDirection): voidExample
editor.selectAdjacentShape('next')Parameters
| Name | Description |
|---|---|
|
Returns
voidselectAll( )
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(): thisExample
editor.selectAll()selectFirstChildShape( )
selectFirstChildShape(): voidselectNone( )
Clear the selection.
selectNone(): thisExample
editor.selectNone()selectParentShape( )
selectParentShape(): voidsendBackward( )
Send shapes backward in the page's object list.
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
| Name | Description |
|---|---|
| The shapes (or shape ids) to move. |
| The options for the backward operation. |
Returns
thissendToBack( )
Send shapes to the back of the page's object list.
Example
editor.sendToBack(['id1', 'id2'])
editor.sendToBack(box1, box2)Parameters
Returns
thissetCamera( )
Set the current camera.
setCamera(point: VecLike, opts?: TLCameraMoveOptions): thisExample
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
| Name | Description |
|---|---|
| The new camera position. |
| The camera move options. |
Returns
thissetCameraOptions( )
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>): thisExample
editor.setCameraOptions(myCameraOptions)
editor.setCamera(editor.getCamera())Parameters
| Name | Description |
|---|---|
| The camera options to set. |
Returns
thissetCroppingShape( )
Set the current cropping shape.
Example
editor.setCroppingShape(myShape)
editor.setCroppingShape(myShape.id)Parameters
Returns
thissetCurrentPage( )
Set the current page.
Example
editor.setCurrentPage('page1')
editor.setCurrentPage(myPage1)Parameters
Returns
thissetCurrentTool( )
Set the selected tool.
setCurrentTool(id: string, info?: {}): thisExample
editor.setCurrentTool('hand')
editor.setCurrentTool('hand', { date: Date.now() })Parameters
| Name | Description |
|---|---|
| The id of the tool to select. |
| Arbitrary data to pass along into the transition. |
Returns
thissetCursor( )
Set the cursor.
setCursor(cursor: Partial<TLCursor>): thisParameters
| Name | Description |
|---|---|
| The cursor to set. |
Returns
thissetEditingShape( )
Set the current editing shape.
Example
editor.setEditingShape(myShape)
editor.setEditingShape(myShape.id)Parameters
Returns
thissetErasingShapes( )
Set the editor's current erasing shapes.
Example
editor.setErasingShapes([myShape])
editor.setErasingShapes([myShape.id])Parameters
Returns
thissetFocusedGroup( )
Set the current focused group shape.
setFocusedGroup(shape: null | TLGroupShape | TLShapeId): thisParameters
| Name | Description |
|---|---|
| The group shape id (or group shape's id) to set as the focused group shape. |
Returns
thissetHintingShapes( )
Set the editor's current hinting shapes.
Example
editor.setHintingShapes([myShape])
editor.setHintingShapes([myShape.id])Parameters
Returns
thissetHoveredShape( )
Set the editor's current hovered shape.
Example
editor.setHoveredShape(myShape)
editor.setHoveredShape(myShape.id)Parameters
Returns
thissetOpacityForNextShapes( )
Set the opacity for the next shapes. This will effect subsequently created shapes.
setOpacityForNextShapes(
opacity: number,
historyOptions?: TLHistoryBatchOptions
): thisExample
editor.setOpacityForNextShapes(0.5)Parameters
| Name | Description |
|---|---|
| The opacity to set. Must be a number between 0 and 1 inclusive. |
| The history options for the change. |
Returns
thissetOpacityForSelectedShapes( )
Set the current opacity. This will effect any selected shapes.
setOpacityForSelectedShapes(opacity: number): thisExample
editor.setOpacityForSelectedShapes(0.5)Parameters
| Name | Description |
|---|---|
| The opacity to set. Must be a number between 0 and 1 inclusive. |
Returns
thissetRichTextEditor( )
Set the current editing shape's rich text editor.
setRichTextEditor(textEditor: null | TiptapEditor): thisExample
editor.setRichTextEditor(richTextEditorView)Parameters
| Name | Description |
|---|---|
| The text editor to set as the current editing shape's text editor. |
Returns
thissetSelectedShapes( )
Select one or more shapes.
Example
editor.setSelectedShapes(['id1'])
editor.setSelectedShapes(['id1', 'id2'])Parameters
Returns
thissetStyleForNextShapes( )
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
): thisExample
editor.setStyleForNextShapes(DefaultColorStyle, 'red')
editor.setStyleForNextShapes(DefaultColorStyle, 'red', { ephemeral: true })Parameters
| Name | Description |
|---|---|
| The style to set. |
| The value to set. |
| The history options for the change. |
Returns
thissetStyleForSelectedShapes( )
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>
): thisExample
editor.setStyleForSelectedShapes(DefaultColorStyle, 'red')Parameters
| Name | Description |
|---|---|
| The style to set. |
| The value to set. |
Returns
thisslideCamera( )
Slide the camera in a certain direction.
slideCamera(opts?: {
direction: VecLike
force?: boolean
friction?: number
speed: number
speedThreshold?: number
}): thisExample
editor.slideCamera({ speed: 1, direction: { x: 1, y: 0 }, friction: 0.1 })Parameters
| Name | Description |
|---|---|
| Options for the slide |
Returns
thissquashToMark( )
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): thisExample
const bumpShapesMark = editor.markHistoryStoppingPoint()
// ... some changes
editor.squashToMark(bumpShapesMark)Parameters
| Name | Description |
|---|---|
| The mark id to squash to. |
Returns
thisstackShapes( )
Stack shape.
stackShapes(
shapes: TLShape[] | TLShapeId[],
operation: 'horizontal' | 'vertical',
gap?: number
): thisExample
editor.stackShapes([box1, box2], 'horizontal')
editor.stackShapes(editor.getSelectedShapeIds(), 'horizontal')Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to stack. |
| Whether to stack horizontally or vertically. |
| The gap to leave between shapes. By default, uses the editor's |
Returns
thisstartFollowingUser( )
Start viewport-following a user.
startFollowingUser(userId: string): thisExample
editor.startFollowingUser(myUserId)Parameters
| Name | Description |
|---|---|
| The id of the user to follow. |
Returns
thisstopCameraAnimation( )
Stop the current camera animation, if any.
stopCameraAnimation(): thisExample
editor.stopCameraAnimation()stopFollowingUser( )
Stop viewport-following a user.
stopFollowingUser(): thisExample
editor.stopFollowingUser()stretchShapes( )
Stretch shape sizes and positions to fill their common bounding box.
Example
editor.stretchShapes([box1, box2], 'horizontal')
editor.stretchShapes(editor.getSelectedShapeIds(), 'horizontal')Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to stretch. |
| Whether to stretch shapes horizontally or vertically. |
Returns
thistoggleLock( )
Toggle the lock state of one or more shapes. If there is a mix of locked and unlocked shapes, all shapes will be locked.
Parameters
Returns
thistoImage( )
Get an exported image of the given shapes.
toImage(
shapes: TLShape[] | TLShapeId[],
opts?: TLImageExportOptions
): Promise<{
blob: Blob
height: number
width: number
}>Parameters
| Name | Description |
|---|---|
| The shapes (or shape ids) to export. |
| 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
| Name | Description |
|---|---|
| The shapes (or shape ids) to export. |
| 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(): thisExample
editor.undo()ungroupShapes( )
Ungroup some shapes.
ungroupShapes(
ids: TLShapeId[],
opts?: Partial<{
select: boolean
}>
): thisExample
editor.ungroupShapes([myGroup, myOtherGroup])
editor.ungroupShapes([myGroup], { select: false })Parameters
| Name | Description |
|---|---|
| |
| An options object. |
Returns
thisupdateAssets( )
Update one or more assets.
updateAssets(assets: TLAssetPartial[]): thisExample
editor.updateAssets([{ id: 'asset1', name: 'New name' }])Parameters
| Name | Description |
|---|---|
| The assets to update. |
Returns
thisupdateBinding( )
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>
): thisParameters
| Name | Description |
|---|---|
|
Returns
thisupdateBindings( )
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)[]): thisParameters
| Name | Description |
|---|---|
| |
Returns
thisupdateCurrentPageState( )
Update this instance's page state.
updateCurrentPageState(
partial: Partial<
Omit<
TLInstancePageState,
'editingShapeId' | 'focusedGroupId' | 'pageId' | 'selectedShapeIds'
>
>
): thisExample
editor.updateCurrentPageState({ id: 'page1', editingShapeId: 'shape:123' })Parameters
| Name | Description |
|---|---|
| The partial of the page state object containing the changes. |
Returns
thisupdateDocumentSettings( )
Update the global document settings that apply to all users.
updateDocumentSettings(settings: Partial<TLDocument>): thisParameters
| Name | Description |
|---|---|
| |
Returns
thisupdateInstanceState( )
Update the instance's state.
updateInstanceState(
partial: Partial<Omit<TLInstance, 'currentPageId'>>,
historyOptions?: TLHistoryBatchOptions
): thisParameters
| Name | Description |
|---|---|
| A partial object to update the instance state with. |
| History batch options. |
Returns
thisupdatePage( )
Update a page.
updatePage(partial: RequiredKeys<Partial<TLPage>, 'id'>): thisExample
editor.updatePage({ id: 'page2', name: 'Page 2' })Parameters
| Name | Description |
|---|---|
| The partial of the shape to update. |
Returns
thisupdatePointer( )
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): thisExample
editor.updatePointer()Parameters
| Name | Description |
|---|---|
| The options for updating the pointer. |
Returns
thisThe editor instance.
updateShape( )
Update a shape using a partial of the shape.
updateShape<T extends TLUnknownShape>(
partial: null | TLShapePartial<T> | undefined
): thisExample
editor.updateShape({ id: 'box1', type: 'geo', props: { w: 100, h: 100 } })Parameters
| Name | Description |
|---|---|
| The shape partial to update. |
Returns
thisupdateShapes( )
Update shapes using partials of each shape.
updateShapes<T extends TLUnknownShape>(
partials: (null | TLShapePartial<T> | undefined)[]
): thisExample
editor.updateShapes([{ id: 'box1', type: 'geo', props: { w: 100, h: 100 } }])Parameters
| Name | Description |
|---|---|
| The shape partials to update. |
Returns
thisupdateViewportScreenBounds( )
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
): thisExample
editor.updateViewportScreenBounds(new Box(0, 0, 1280, 1024))
editor.updateViewportScreenBounds(new Box(0, 0, 1280, 1024), true)Parameters
| Name | Description |
|---|---|
| The new screen bounds of the viewport. |
| Whether to preserve the viewport page center as the viewport changes. |
Returns
thisuploadAsset( )
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
| Name | Description |
|---|---|
| |
| |
| |
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
): thisExample
editor.visitDescendants('frame1', myCallback)Parameters
| Name | Description |
|---|---|
| The parent (or the id) of the parent shape. |
| The visitor function. |
Returns
thiswasEventAlreadyHandled( )
Checks if an event has already been handled. See Editor.markEventAsHandled.
wasEventAlreadyHandled(
e:
| {
nativeEvent: Event
}
| Event
): booleanParameters
| Name | Description |
|---|---|
| |
Returns
booleanzoomIn( )
Zoom the camera in.
zoomIn(point?: Vec, opts?: TLCameraMoveOptions): thisExample
editor.zoomIn()
editor.zoomIn(editor.getViewportScreenCenter(), {
animation: { duration: 200 },
})
editor.zoomIn(editor.inputs.currentScreenPoint, {
animation: { duration: 200 },
})Parameters
| Name | Description |
|---|---|
| The screen point to zoom in on. Defaults to the screen center |
| The camera move options. |
Returns
thiszoomOut( )
Zoom the camera out.
zoomOut(point?: Vec, opts?: TLCameraMoveOptions): thisExample
editor.zoomOut()
editor.zoomOut(editor.getViewportScreenCenter(), {
animation: { duration: 120 },
})
editor.zoomOut(editor.inputs.currentScreenPoint, {
animation: { duration: 120 },
})Parameters
| Name | Description |
|---|---|
| The point to zoom out on. Defaults to the viewport screen center. |
| The camera move options. |
Returns
thiszoomToBounds( )
Zoom the camera to fit a bounding box (in the current page space).
zoomToBounds(
bounds: BoxLike,
opts?: {
inset?: number
targetZoom?: number
} & TLCameraMoveOptions
): thisExample
editor.zoomToBounds(myBounds)
editor.zoomToBounds(myBounds, { animation: { duration: 200 } })
editor.zoomToBounds(myBounds, {
animation: { duration: 200 },
inset: 0,
targetZoom: 1,
})Parameters
| Name | Description |
|---|---|
| The bounding box. |
| The camera move options, target zoom, or custom inset amount. |
Returns
thiszoomToFit( )
Zoom the camera to fit the current page's content in the viewport.
zoomToFit(opts?: TLCameraMoveOptions): thisExample
editor.zoomToFit()
editor.zoomToFit({ animation: { duration: 200 } })Parameters
| Name | Description |
|---|---|
| The camera move options. |
Returns
thiszoomToSelection( )
Zoom the camera to fit the current selection in the viewport.
zoomToSelection(opts?: TLCameraMoveOptions): thisExample
editor.zoomToSelection()
editor.zoomToSelection({ animation: { duration: 200 } })Parameters
| Name | Description |
|---|---|
| The camera move options. |
Returns
thiszoomToSelectionIfOffscreen( )
Zoom the camera to the current selection if offscreen.
zoomToSelectionIfOffscreen(
padding?: number,
opts?: {
inset?: number
targetZoom?: number
} & TLCameraMoveOptions
): voidParameters
| Name | Description |
|---|---|
| |
| |
Returns
voidzoomToUser( )
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): thisExample
editor.zoomToUser(myUserId)
editor.zoomToUser(myUserId, { animation: { duration: 200 } })Parameters
| Name | Description |
|---|---|
| The id of the user to animate to. |
| The camera move options. |
Returns
this