Skip to content

Instantly share code, notes, and snippets.

@buwilliams
Created June 15, 2025 13:47
Show Gist options
  • Select an option

  • Save buwilliams/31d5f4f7849753e7b299a76e6667daaf to your computer and use it in GitHub Desktop.

Select an option

Save buwilliams/31d5f4f7849753e7b299a76e6667daaf to your computer and use it in GitHub Desktop.
tldraw reference documentation meant for coding agents

tldraw SDK Complete Reference Documentation

Compact reference with class names, types, method signatures and one-liner explanations.

@tldraw/editor - Core editor functionality and API:

Editor - Main class for controlling the tldraw canvas:

store: TLStore - The editor's data store containing all records
inputs: InputState - Current input state including mouse position and keyboard state
user: UserPreferencesManager - User preferences manager for settings
history: HistoryManager<TLRecord> - History manager for undo/redo operations
snaps: SnapManager - Snap manager for shape alignment and snapping
shapeUtils: Record<string, ShapeUtil> - Map of shape utility classes by type
bindingUtils: Record<string, BindingUtil> - Map of binding utility classes by type
sideEffects: StoreSideEffects<TLRecord> - Side effects manager for state enforcement

createShape<T>(shape: OptionalKeys<TLShapePartial<T>, 'id'>): this - Create single shape with optional id
createShapes<T>(shapes: OptionalKeys<TLShapePartial<T>, 'id'>[]): this - Create multiple shapes at once
updateShape<T>(partial: TLShapePartial<T>): this - Update single shape using partial data
updateShapes<T>(partials: TLShapePartial<T>[]): this - Update multiple shapes at once
deleteShape(id: TLShapeId): this - Delete single shape by id
deleteShapes(ids: TLShapeId[]): this - Delete multiple shapes by ids
getShape<T>(shape: TLParentId | TLShape): T | undefined - Get shape by id or shape object
getCurrentPageShapes(): TLShape[] - Get all shapes on current page
getCurrentPageShapesSorted(): TLShape[] - Get shapes sorted by z-index
getSelectedShapes(): TLShape[] - Get currently selected shapes
getSelectedShapeIds(): TLShapeId[] - Get ids of selected shapes

select(...ids: TLShapeId[]): this - Select one or more shapes by id
selectAll(): this - Select all shapes on current page
selectNone(): this - Clear current selection
setSelectedShapes(ids: TLShapeId[]): this - Set selection to specific shape ids
deselect(...shapes: TLShape[] | TLShapeId[]): this - Remove shapes from selection

setCamera(point: VecLike, opts?: TLCameraMoveOptions): this - Set camera position with animation
getCamera(): TLCamera - Get current camera state
zoomIn(point?: Vec, opts?: TLCameraMoveOptions): this - Zoom in centered on point
zoomOut(point?: Vec, opts?: TLCameraMoveOptions): this - Zoom out centered on point
zoomToFit(opts?: TLCameraMoveOptions): this - Zoom to fit all content
zoomToSelection(opts?: TLCameraMoveOptions): this - Zoom to fit current selection
resetZoom(point?: Vec, opts?: TLCameraMoveOptions): this - Reset zoom to 100%
centerOnPoint(point: VecLike, opts?: TLCameraMoveOptions): this - Center camera on point

undo(): this - Undo last operation
redo(): this - Redo last undone operation
mark(markId?: string): this - Create history mark for grouping operations
bailToMark(id: string): this - Undo to mark, discarding changes
squashToMark(markId: string): this - Coalesce changes since mark into single operation
clearHistory(): this - Clear all history

setCurrentTool(id: string, info?: {}): this - Set the active tool
getCurrentTool(): StateNode - Get current active tool state node
getCurrentToolId(): string - Get current tool id
isIn(path: string): boolean - Check if editor is in specific state path
isInAny(...paths: string[]): boolean - Check if in any given state paths
getPath(): string - Get current state path

createAssets(assets: TLAsset[]): this - Create one or more assets
deleteAssets(assets: TLAsset[] | TLAssetId[]): this - Delete one or more assets
updateAssets(assets: TLAssetPartial[]): this - Update one or more assets
getAsset<T>(asset: T | T['id']): T | undefined - Get asset by id
getAssets(): TLAsset[] - Get all assets
uploadAsset(asset: TLAsset, file: File): Promise<{src: string}> - Upload asset file

getSvgElement(shapes: TLShape[], opts?: TLSvgExportOptions): Promise<{svg: SVGSVGElement}> - Export as SVG element
getSvgString(shapes: TLShape[], opts?: TLSvgExportOptions): Promise<{svg: string}> - Export as SVG string
toImage(shapes: TLShape[], opts?: TLImageExportOptions): Promise<{blob: Blob}> - Export as image blob

ShapeUtil - Base class for defining custom shape behavior:

static type: string - Unique identifier for shape type
static props: RecordProps<Shape> - Validation schema for shape properties

getDefaultProps(): Shape['props'] - Return default properties for new shapes
getGeometry(shape: Shape): Geometry2d - Return geometry for hit testing and bounds
component(shape: Shape): JSX.Element - Return React component to render shape
indicator(shape: Shape): JSX.Element - Return selection indicator component
canEdit?(): boolean - Whether shape can be edited in place
canResize?(): boolean - Whether shape can be resized
canBind?(): boolean - Whether other shapes can bind to this shape
onResize?(shape: Shape, info: TLResizeInfo<Shape>): TLShapePartial<Shape> - Handle resize operations
onClick?(shape: Shape): TLShapePartial<Shape> - Handle click events
onDoubleClick?(shape: Shape): TLShapePartial<Shape> - Handle double-click events
toSvg?(shape: Shape, ctx: SvgExportContext): ReactElement - Custom SVG export

BindingUtil - Base class for defining custom binding behavior:

static type: string - Unique identifier for binding type
getDefaultProps(): Binding['props'] - Return default properties for new bindings

StateNode - Base class for tool state nodes:

id: string - Unique identifier for the state
parent?: StateNode - Parent state node
children?: Record<string, StateNode> - Child state nodes
onEnter?(info: any): void - Called when entering this state
onExit?(info: any): void - Called when exiting this state
onPointerDown?(info: TLPointerEventInfo): void - Handle pointer down events
onPointerUp?(info: TLPointerEventInfo): void - Handle pointer up events
onPointerMove?(info: TLPointerEventInfo): void - Handle pointer move events

@tldraw/state - Reactive state management using signals:

atom(name: string, initialValue: Value, options?: AtomOptions): Atom - Create mutable reactive value

Atom - Mutable signal that can be updated directly:

value: Value - Current value (reactive property)
get(): Value - Get current value
set(value: Value, diff?: Diff): void - Set new value with optional diff
update(updater: (current: Value) => Value): void - Update value using function

computed(name: string, compute: () => Value, options?: ComputedOptions): Computed - Create derived reactive value

Computed - Read-only signal computed from other signals:

value: Value - Current computed value (reactive)
get(): Value - Get current value

Signal - Base class for all reactive values:

name: string - Signal name for debugging
lastChangedEpoch: number - Epoch when value last changed
value: Value - Current signal value
get(): Value - Get current value
getDiffSince(epoch: number): Diff[] | RESET_VALUE - Get diffs since specific epoch

react(name: string, fn: () => void, scheduleEffect?: (cb: () => void) => void): () => void - Create reactive effect

transact(fn: () => void): void - Batch multiple signal updates into single transaction

isSignal(value: any): value is Signal - Check if value is a signal

isAtom(value: any): value is Atom - Check if value is an atom

whyAmIRunning(): void - Debug helper for understanding why computed/effect runs

getComputedInstance(obj: T, propertyName: keyof T): Computed - Get computed instance from @computed property

@tldraw/state-react - React bindings for state management:

useValue(name: string, fn: () => T, deps: any[]): T - Hook to track signal value in React component

track

(Component: (props: P) => JSX.Element): (props: P) => JSX.Element - HOC for automatic signal tracking

useComputed(name: string, compute: () => T, deps: any[]): Computed - Create computed signal inside React component

@tldraw/store - Data persistence and synchronization infrastructure:

Store - Core data store for managing records:

get<K>(id: K): RecordFromId<K> | undefined - Get record by id
put(records: R[], phaseOverride?: 'initialize'): void - Add records to store
update<T>(id: T['id'], updater: (record: T) => T): void - Update record using function
remove(ids: IdOf<R>[]): void - Remove records by ids
clear(): void - Remove all records
listen(onHistory: StoreListener<R>, filters?: StoreListenerFilters): () => void - Listen to store changes
getSnapshot(scope?: 'all' | RecordScope): StoreSnapshot<R> - Get store snapshot
loadSnapshot(snapshot: StoreSnapshot<R>): void - Load snapshot into store
serialize(scope?: 'all' | RecordScope): SerializedStore<R> - Serialize store to JSON
mergeRemoteChanges(fn: () => void): void - Apply changes marked as 'remote' source
createComputedCache<Result>(name: string, derive: (record: Record) => Result): ComputedCache<Result> - Create computed cache
createCache<Result>(create: (id, recordSignal) => Signal<Result>): {get: (id) => Result} - Create custom cache

StoreSideEffects - Manager for side effects and state enforcement:

registerBeforeCreateHandler<T>(typeName: T, handler: StoreBeforeCreateHandler<T>): () => void - Register pre-creation handler
registerAfterCreateHandler<T>(typeName: T, handler: StoreAfterCreateHandler<T>): () => void - Register post-creation handler
registerBeforeChangeHandler<T>(typeName: T, handler: StoreBeforeChangeHandler<T>): () => void - Register pre-change handler
registerAfterChangeHandler<T>(typeName: T, handler: StoreAfterChangeHandler<T>): () => void - Register post-change handler
registerBeforeDeleteHandler<T>(typeName: T, handler: StoreBeforeDeleteHandler<T>): () => void - Register pre-deletion handler
registerAfterDeleteHandler<T>(typeName: T, handler: StoreAfterDeleteHandler<T>): () => void - Register post-deletion handler

BaseRecord<TypeName, Id> - Base interface for all store records:

id: Id - Unique record identifier
typeName: TypeName - Type name for the record

StoreSchema - Schema definition for store structure:

static create<R>(types: RecordTypes, options?: StoreSchemaOptions): StoreSchema<R> - Create store schema from record types

@tldraw/sync - Real-time collaboration client:

useSync(options: {uri: string, assets?: TLAssetStore, schema?: StoreSchema}): TLStoreWithStatus - Connect to sync server for real-time collaboration

useSyncDemo(options: {roomId: string}): TLStoreWithStatus - Connect to demo server for prototyping

TLAssetStore - Interface for handling asset uploads and resolution:

upload(file: File, asset: TLAsset): Promise<{src: string; meta?: JsonObject}> - Upload asset file and return URL
resolve(asset: TLAsset): string | Promise<string> - Resolve asset to URL

@tldraw/sync-core - Server-side collaboration infrastructure:

TLSocketRoom - Server-side room for managing collaborative sessions:

constructor(options: {schema: StoreSchema, onDataChange?, onClientConnect?, onClientDisconnect?}) - Create new socket room
handleMessage(client: WebSocket, message: any): void - Handle incoming WebSocket message
getSnapshot(): TLStoreSnapshot - Get current room state snapshot
loadSnapshot(snapshot: TLStoreSnapshot): void - Load snapshot into room
sendMessage(client: WebSocket, message: any): void - Send message to specific client
broadcastMessage(message: any, except?: WebSocket): void - Broadcast message to all clients

tldraw - Main UI package providing complete tldraw experience:

Tldraw(props: TldrawProps): JSX.Element - Primary component for embedding tldraw

TldrawProps - Props for Tldraw component:

store?: TLStore | TLStoreWithStatus - Custom store instance
persistenceKey?: string - Key for local storage persistence
sessionId?: string - Session identifier
snapshot?: TLEditorSnapshot | TLStoreSnapshot - Initial snapshot to load
assetUrls?: TLAssetUrls - Custom asset URLs
shapeUtils?: readonly TLAnyShapeUtilConstructor[] - Custom shape utilities
bindingUtils?: readonly TLAnyBindingUtilConstructor[] - Custom binding utilities
tools?: readonly TLStateNodeConstructor[] - Custom tools
onMount?: (editor: Editor) => void - Callback when editor mounts
children?: ReactNode - Child components

TldrawEditor(props: TldrawEditorProps): JSX.Element - Lower-level editor component without UI

TldrawUi(props: TldrawUiProps): JSX.Element - UI components for tldraw

createShapeId(id?: string): TLShapeId - Create typed shape id

createAssetId(id?: string): TLAssetId - Create typed asset id

createPageId(id?: string): TLPageId - Create typed page id

toRichText(text: string): RichText - Convert string to rich text format

getSnapshot(store: TLStore): {document: DocumentSnapshot; session: SessionSnapshot} - Get editor snapshot

loadSnapshot(store: TLStore, snapshot: {document, session}): void - Load snapshot into store

@tldraw/tlschema - Schema definitions and types for tldraw data structures:

TLBaseShape<Type, Props> - Base interface for all shapes:

id: TLShapeId - Unique shape identifier
type: Type - Shape type string
x: number - X position on canvas
y: number - Y position on canvas
rotation: number - Rotation in radians
index: IndexKey - Z-index for layering
parentId: TLParentId - Parent shape or page id
isLocked: boolean - Whether shape is locked
opacity: TLOpacityType - Shape opacity (0-1)
props: Props - Shape-specific properties
meta: JsonObject - Custom metadata

TLShape - Union of all built-in shape types:

TLArrowShape | TLBookmarkShape | TLDrawShape | TLEmbedShape | TLFrameShape | TLGeoShape | TLGroupShape | TLHighlightShape | TLImageShape | TLLineShape | TLNoteShape | TLTextShape | TLVideoShape

TLGeoShape - Geometric shape (rectangle, circle, etc.):

props: TLGeoShapeProps - Geometric shape properties

TLGeoShapeProps - Properties for geometric shapes:

geo: 'rectangle' | 'ellipse' | 'triangle' | etc. - Geometric shape type
w: number - Width
h: number - Height
fill: 'none' | 'semi' | 'solid' | 'pattern' - Fill style
color: TLDefaultColorStyle - Shape color
dash: 'draw' | 'dashed' | 'dotted' | 'solid' - Line style
size: 's' | 'm' | 'l' | 'xl' - Size variant
text: string - Text content

TLTextShape - Text shape:

props: TLTextShapeProps - Text shape properties

TLTextShapeProps - Properties for text shapes:

color: TLDefaultColorStyle - Text color
size: 's' | 'm' | 'l' | 'xl' - Font size
font: 'draw' | 'sans' | 'serif' | 'mono' - Font family
textAlign: 'start' | 'middle' | 'end' - Text alignment
w: number - Width
richText: RichText - Rich text content
autoSize: boolean - Whether to auto-size
scale: number - Scale factor

TLImageShape - Image shape:

props: TLImageShapeProps - Image shape properties

TLImageShapeProps - Properties for image shapes:

w: number - Width
h: number - Height
assetId: TLAssetId - Reference to image asset
playing: boolean - Whether video/gif is playing
url: string - Image URL
crop: {topLeft: VecModel; bottomRight: VecModel} | null - Crop bounds

TLAsset - Union of all asset types:

TLImageAsset | TLVideoAsset | TLBookmarkAsset

TLImageAsset - Image asset:

id: TLAssetId - Unique asset identifier
type: 'image' - Asset type
props: TLImageAssetProps - Image asset properties

TLImageAssetProps - Properties for image assets:

name: string - Asset name
src: string - Asset URL
w: number - Width in pixels
h: number - Height in pixels
mimeType: string - MIME type
isAnimated: boolean - Whether image is animated

TLVideoAsset - Video asset:

id: TLAssetId - Unique asset identifier
type: 'video' - Asset type
props: TLVideoAssetProps - Video asset properties

TLPage - Page record:

id: TLPageId - Unique page identifier
name: string - Page name
index: IndexKey - Page order
meta: JsonObject - Custom metadata

TLDocument - Document settings:

id: RecordId<TLDocument> - Document identifier
gridSize: number - Grid size in pixels
name: string - Document name
meta: JsonObject - Custom metadata

TLInstance - Editor instance state:

id: TLInstanceId - Instance identifier
currentPageId: TLPageId - Current active page
followingUserId: string | null - User being followed
opacityForNextShape: number - Default opacity for new shapes
stylesForNextShape: Record<string, unknown> - Default styles for new shapes
brush: Box | null - Current selection brush
cursor: TLCursor - Current cursor state
isFocusMode: boolean - Whether in focus mode
exportBackground: boolean - Whether to export background
isDebugMode: boolean - Whether debug mode is enabled
isToolLocked: boolean - Whether tool is locked
screenBounds: Box - Screen bounds
isPenMode: boolean - Whether in pen mode
isGridMode: boolean - Whether grid is visible
canMoveCamera: boolean - Whether camera can be moved
isFocused: boolean - Whether editor is focused
isReadonly: boolean - Whether editor is readonly
meta: JsonObject - Custom metadata

TLArrowBinding - Arrow binding to shapes:

id: TLBindingId - Unique binding identifier
type: 'arrow' - Binding type
fromId: TLShapeId - Source shape id
toId: TLShapeId - Target shape id
props: TLArrowBindingProps - Arrow binding properties

TLArrowBindingProps - Properties for arrow bindings:

terminal: 'start' | 'end' - Which end of arrow
normalizedAnchor: VecModel - Anchor point (0-1 normalized)
isExact: boolean - Whether arrow enters shape
isPrecise: boolean - Whether to bind to exact anchor

createTLSchema(opts: {shapes?, bindings?}): StoreSchema - Create custom tldraw schema

defaultShapeSchemas: Record<string, SchemaShapeInfo> - Built-in shape schemas

defaultBindingSchemas: Record<string, SchemaBindingInfo> - Built-in binding schemas

ID Types - Branded ID types for type safety:

TLShapeId: RecordId<TLShape> - Shape identifier
TLAssetId: RecordId<TLAsset> - Asset identifier
TLPageId: RecordId<TLPage> - Page identifier
TLInstanceId: RecordId<TLInstance> - Instance identifier
TLBindingId: RecordId<TLBinding> - Binding identifier
TLParentId: TLPageId | TLShapeId - Parent identifier (page or shape)

@tldraw/validate - Runtime validation utilities:

T - Collection of built-in validators:

T.string: Validator<string> - Validates string values
T.number: Validator<number> - Validates number values
T.boolean: Validator<boolean> - Validates boolean values
T.null: Validator<null> - Validates null values
T.undefined: Validator<undefined> - Validates undefined values
T.unknown: Validator<unknown> - Accepts any value
T.array<T>(itemValidator: Validator<T>): Validator<T[]> - Validates arrays with item validation
T.set<T>(itemValidator: Validator<T>): Validator<Set<T>> - Validates sets with item validation
T.dict<T>(valueValidator: Validator<T>): Validator<Record<string, T>> - Validates objects with value validation
T.object<T>(schema: {[K in keyof T]: Validator<T[K]>}): Validator<T> - Validates objects with property schema
T.union<T>(key: string, variants: Record<string, Validator<T>>): Validator<T> - Validates discriminated unions
T.literal<T>(value: T): Validator<T> - Validates exact literal value
T.optional<T>(validator: Validator<T>): Validator<T | undefined> - Makes validator optional
T.nullable<T>(validator: Validator<T>): Validator<T | null> - Makes validator nullable

Validator - Base validator interface:

check(value: unknown): value is T - Type guard function
validate(value: unknown): T - Validates and returns value or throws
validateUnsafe(value: unknown): {success: true; value: T} | {success: false; error: string} - Safe validation with result object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment