# tldraw SDK Examples -------- # Tldraw component Category: Getting started Keywords: basic, getting started, intro, simple, quick start, hello world, installation, first app, tldraw component The simplest way to use the `Tldraw` component. The `Tldraw` component renders the full tldraw editor as a regular React component. Put it anywhere in your React tree; it fills whatever container it's given, so the container needs a size. Here `.tldraw__editor` makes it fill the page. Import `tldraw/tldraw.css` alongside the component. Without it, the editor's UI has no styling. By default the editor does not persist between refreshes or sync between tabs. To keep your work after a refresh, see the [persistence key example](https://tldraw.dev/examples/persistence-key). ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function BasicExample() { return (
) } ``` -------- # Editor options Category: Configuration Keywords: options, configuration, pages, animation, camera Override editor options like the maximum number of pages and animation duration. The `options` prop on `Tldraw` takes a `Partial` and overrides tldraw's defaults; anything you leave out keeps its default value. Options are read once when the editor is created, so define the object outside the component (or memoize it) rather than creating a new one on every render. This example limits documents to 3 pages and sets `animationMediumMs` to 5 seconds. Try opening the page menu and adding pages: the "create page" button disables after the third. Then zoom in or out from the zoom menu and watch the (very) slow animation. ## App.tsx ```tsx import { Tldraw, TldrawOptions } from 'tldraw' import 'tldraw/tldraw.css' const options: Partial = { maxPages: 3, animationMediumMs: 5000, } export default function CustomOptionsExample() { return (
) } ``` -------- # Shape options Category: Configuration Keywords: configure, shapeutil, shape options, noteshapeoptions, frameshapeoptions, builtin shapes, customization Change the behavior of built-in shapes with `ShapeUtil.configure`. Several built-in shape utils expose an `options` object. `ShapeUtil.configure(options)` returns a subclass of the util with those options overridden, and passing that subclass in the `shapeUtils` prop replaces the default one. You can find a shape's options in the `options` property of its util, for example [`NoteShapeOptions`](https://tldraw.dev/reference/tldraw/NoteShapeOptions) and [`FrameShapeOptions`](https://tldraw.dev/reference/tldraw/FrameShapeOptions). Here notes get `resizeMode: 'scale'` so they can be resized by dragging a handle, and frames get `showColors: true` so the color style applies to them. Try creating a note (N) and dragging a corner handle, or a frame (F) and changing its color in the style panel. ## App.tsx ```tsx import { FrameShapeUtil, NoteShapeUtil, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' const shapeUtils = [ FrameShapeUtil.configure({ showColors: true }), NoteShapeUtil.configure({ resizeMode: 'scale' }), ] export default function ConfigureShapeUtilExample() { return (
) } ``` -------- # Camera options Category: Configuration Keywords: camera, cameraoptions, zoom constraints, pan constraints, camera bounds, zoom speed, pan speed, viewport, isfixed Configure the camera's constraints, zoom steps, and wheel behavior, and change them live. The `Tldraw` component takes its initial camera configuration from `options={{ camera: { ... } }}`, a `TLCameraOptions` object. It controls whether the camera is locked, what the mouse wheel does, pan and zoom speed, the zoom steps, and (optionally) constraints that keep the camera inside a bounded area with a chosen fit behavior, padding, and origin. The control panel in this example changes the options at runtime with `editor.setCameraOptions()` so you can see the effect of each setting. The dashed rectangle on the canvas is the constraint bounds; the dotted rectangle in front of the canvas is the padding. Try switching bounds between "A4 page" and "landscape", then change behavior from `contain` to `inside` or `outside` and pan around. "Reset camera" re-fits the camera to the current constraints; "Reset camera options" restores the defaults. ## App.tsx ```tsx import { useEffect } from 'react' import { BoxModel, TLCameraOptions, Tldraw, Vec, clamp, track, useEditor, useLocalStorageState, } from 'tldraw' import 'tldraw/tldraw.css' const CAMERA_OPTIONS: TLCameraOptions = { isLocked: false, wheelBehavior: 'pan', panSpeed: 1, zoomSpeed: 1, zoomSteps: [0.1, 0.25, 0.5, 1, 2, 4, 8], constraints: { initialZoom: 'fit-max', baseZoom: 'fit-max', bounds: { x: 0, y: 0, w: 1600, h: 900, }, behavior: { x: 'contain', y: 'contain' }, padding: { x: 100, y: 100 }, origin: { x: 0.5, y: 0.5 }, }, } const BOUNDS_SIZES: Record = { a4: { x: 0, y: 0, w: 1050, h: 1485 }, landscape: { x: 0, y: 0, w: 1600, h: 900 }, portrait: { x: 0, y: 0, w: 900, h: 1600 }, square: { x: 0, y: 0, w: 900, h: 900 }, } export default function CameraOptionsExample() { return (
) } const PaddingDisplay = track(() => { const editor = useEditor() const cameraOptions = editor.getCameraOptions() if (!cameraOptions.constraints) return null const { constraints: { padding: { x: px, y: py }, }, } = cameraOptions return (
) }) const BoundsDisplay = track(() => { const editor = useEditor() const cameraOptions = editor.getCameraOptions() if (!cameraOptions.constraints) return null const { constraints: { bounds: { x, y, w, h }, }, } = cameraOptions const d = Vec.ToAngle({ x: w, y: h }) * (180 / Math.PI) const colB = '#00000002' const colA = '#0000001F' return ( <>
{/* grey and white stripes */}
) }) // [1] const components = { OnTheCanvas: BoundsDisplay, InFrontOfTheCanvas: PaddingDisplay, } const CameraOptionsControlPanel = track(() => { const editor = useEditor() // [2] const [cameraOptions, setCameraOptions] = useLocalStorageState('camera ex1', CAMERA_OPTIONS) // [3] useEffect(() => { editor.run(() => { editor.setCameraOptions(cameraOptions) editor.setCamera(editor.getCamera(), { immediate: true, }) }) }, [editor, cameraOptions]) const { constraints } = cameraOptions const updateOptions = ( options: Partial< Omit & { constraints: Partial } > ) => { const { constraints } = options const cameraOptions = editor.getCameraOptions() setCameraOptions({ ...cameraOptions, ...options, constraints: constraints === undefined ? cameraOptions.constraints : { ...(cameraOptions.constraints! ?? CAMERA_OPTIONS.constraints), ...constraints, }, }) } return (
{ const val = clamp(Number(e.target.value), 0, 2) updateOptions({ panSpeed: val }) }} /> { const val = clamp(Number(e.target.value), 0, 2) updateOptions({ zoomSpeed: val }) }} /> { try { const val = e.target.value.split(', ').map((v) => Number(v)) if (val.every((v) => typeof v === 'number' && Number.isFinite(v))) { updateOptions({ zoomSteps: val }) } } catch { // ignore } }} /> {constraints ? ( <> { const val = clamp(Number(e.target.value), 0, 1) updateOptions({ constraints: { origin: { ...constraints.origin, x: val, }, }, }) }} /> { const val = clamp(Number(e.target.value), 0, 1) updateOptions({ constraints: { ...constraints, origin: { ...constraints.origin, y: val, }, }, }) }} /> { const val = clamp(Number(e.target.value), 0) updateOptions({ constraints: { ...constraints, padding: { ...constraints.padding, x: val, }, }, }) }} /> { const val = clamp(Number(e.target.value), 0) updateOptions({ constraints: { padding: { ...constraints.padding, y: val, }, }, }) }} /> ) : null}
) }) /* [1] These two components are only there to visualize the configuration: BoundsDisplay draws the constraint bounds in page space (OnTheCanvas), and PaddingDisplay draws the padding inset in screen space (InFrontOfTheCanvas). Neither is needed to make constraints work. [2] The panel's options are kept in local storage so they survive a refresh, and so the panel, not the initial `options.camera`, is the source of truth once it has mounted. [3] `editor.setCameraOptions()` updates the options at runtime and re-applies the constraints to the current camera. We follow it with `setCamera(getCamera(), { immediate: true })` so the camera snaps to its new constrained position instead of animating there. Wrapping both in `editor.run()` keeps them in one transaction. */ ``` -------- # Asset options Category: Configuration Keywords: assets, images, videos, upload, acceptedimagetypes, acceptedvideotypes, maxassetsize, maximagesize, maximagedimension Restrict which images and videos can be added to the canvas. The `Tldraw` component has props that control which assets it accepts when files are dropped, pasted, or uploaded: - `acceptedImageMimeTypes` and `acceptedVideoMimeTypes` filter by file type. Here only JPEGs are allowed and videos are turned off entirely. - `maxAssetSize` caps the file size in bytes (1 MB here). - `maxImageDimension` limits an image's width or height in pixels; larger images are scaled down on import. `Infinity` disables the limit. Try dropping a PNG or a video onto the canvas: it is rejected with a toast. A JPEG under 1 MB is accepted. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function AssetPropsExample() { return (
) } ``` -------- # Custom text outline Category: Configuration Keywords: text, outline, showTextOutline, configure, TextShapeUtil, ArrowShapeUtil, GeoShapeUtil, label, performance, styling Disable the text outline on text, arrow, and geo shape labels. By default tldraw draws a halo in the canvas background color around text labels so they stay legible when they overlap other shapes. Each shape util that renders text (`TextShapeUtil`, `ArrowShapeUtil`, `GeoShapeUtil`) has a `showTextOutline` option; this example sets it to `false` on all three with `ShapeUtil.configure`. The canvas starts with three overlapping text shapes and a labeled arrow so you can see the difference. Try changing `showTextOutline` back to `true` for one of the utils and compare. You might turn outlines off for a different visual style, or for performance: the outline is drawn with a text shadow, which can be expensive on some browsers (tldraw already skips it on Safari). ## App.tsx ```tsx import { ArrowShapeUtil, GeoShapeUtil, TextShapeUtil, Tldraw, toRichText } from 'tldraw' import 'tldraw/tldraw.css' // [1] const shapeUtils = [ ArrowShapeUtil.configure({ showTextOutline: false }), TextShapeUtil.configure({ showTextOutline: false }), GeoShapeUtil.configure({ showTextOutline: false }), ] export default function CustomTextOutlineExample() { return (
{ if (editor.getCurrentPageShapeIds().size > 0) return // [2] const message = toRichText('very good whiteboard') editor.createShapes([ { type: 'text', x: 100, y: 100, props: { richText: message } }, { type: 'text', x: 110, y: 110, props: { richText: message } }, { type: 'text', x: 120, y: 120, props: { richText: message } }, { type: 'arrow', x: 0, y: 0, props: { richText: toRichText('hello world'), start: { x: 0, y: 0 }, end: { x: 200, y: 200 }, }, }, ]) }} />
) } /* [1] Text outlines are an option on each shape util that renders text labels, so each one has to be configured separately. Passing the configured utils in `shapeUtils` replaces the defaults. [2] Overlapping text shapes and an arrow with a label. With outlines on, each label would get a halo in the background color that separates it from the text behind it; here they run together. */ ``` -------- # Display options Category: Configuration Keywords: display, values, override, configure, colors, fonts, customize Override the colors, fonts, and stroke widths a shape renders with, without changing its props. Built-in shape utils compute a set of display values (stroke color, fill color, label font, stroke width, and so on) from a shape's style props each time the shape renders. The `getCustomDisplayValues` option lets you override any of them: return a partial object and it is merged over the defaults. This example configures `GeoShapeUtil` so that locked shapes are filled red, ellipses use a monospace label, and every geo shape has a 10px stroke. Try locking the rectangle (select it, then use the context menu) to see the fill change, or change the size style and notice that the stroke width stays the same. Because display values are computed at render time, they don't touch the document: unlocking the shape or opening the file elsewhere shows the normal styles. ## App.tsx ```tsx import { GeoShapeUtil, Tldraw, toRichText, type GeoShapeUtilDisplayValues } from 'tldraw' import 'tldraw/tldraw.css' // [1] const shapeUtils = [ GeoShapeUtil.configure({ getCustomDisplayValues(editor, shape): Partial { const values: Partial = {} // [2] if (shape.isLocked) { const colors = editor.getCurrentTheme().colors[editor.getColorMode()] values.fillColor = colors.red.solid } if (shape.props.geo === 'ellipse') { values.labelFontFamily = 'monospace' } values.strokeWidth = 10 return values }, }), ] export default function DisplayOptionsExample() { return (
{ editor.createShapes([ { type: 'geo', x: 100, y: 100, props: { w: 200, h: 100, geo: 'rectangle', fill: 'solid', richText: toRichText('Rectangle'), }, }, { type: 'geo', x: 400, y: 100, props: { w: 200, h: 200, geo: 'ellipse', richText: toRichText('Ellipse'), }, }, ]) editor.zoomToFit({ animation: { duration: 0 } }) editor.zoomOut() }} />
) } /* [1] `getCustomDisplayValues` runs every time a geo shape renders, after the default display values have been computed from the shape's style props. Whatever it returns is merged on top, so you only need to return the values you want to change. Passing the configured util in `shapeUtils` replaces the default GeoShapeUtil. [2] Display values can depend on anything about the shape, not just its props. Locked shapes get a red fill; ellipses get a monospace label; every geo shape gets a 10px stroke regardless of its size style. */ ``` -------- # Edge scrolling Category: Configuration Keywords: scroll, edge, auto-scroll, drag, edge scroll manager, options, camera Configure how the camera auto-scrolls when dragging near the viewport edge. Edge scrolling automatically pans the camera when you drag a shape or selection brush close to the edge of the viewport. This example provides sliders for the four options that control it, passed through the `Tldraw` component's `options` prop: - `edgeScrollSpeed`: base scroll speed in pixels per tick (default 25) - `edgeScrollDelay`: how long the pointer must linger near the edge before scrolling starts (default 200ms) - `edgeScrollEaseDuration`: how long the scroll takes to accelerate to full speed (default 200ms) - `edgeScrollDistance`: the width of the edge zone that triggers scrolling (default 8px) Drag one of the shapes toward a window edge to feel the current settings, then adjust the sliders and try again. The sliders commit on release because editor options are read when the editor is created: changing the `options` prop recreates the editor instance. ## App.tsx ```tsx import { useState } from 'react' import { Editor, TLGeoShape, Tldraw, toRichText } from 'tldraw' import 'tldraw/tldraw.css' import './edge-scrolling.css' // There's a guide at the bottom of this file! // [1] interface EdgeScrollValues { edgeScrollSpeed: number edgeScrollDelay: number edgeScrollEaseDuration: number edgeScrollDistance: number } const DEFAULTS: EdgeScrollValues = { edgeScrollSpeed: 25, edgeScrollDelay: 200, edgeScrollEaseDuration: 200, edgeScrollDistance: 8, } const CONTROLS = [ { key: 'edgeScrollSpeed', label: 'Speed (px per tick)', min: 0, max: 100, step: 5 }, { key: 'edgeScrollDelay', label: 'Delay (ms)', min: 0, max: 1000, step: 50 }, { key: 'edgeScrollEaseDuration', label: 'Ease duration (ms)', min: 0, max: 1000, step: 50 }, { key: 'edgeScrollDistance', label: 'Edge zone size (px)', min: 0, max: 240, step: 8 }, ] as const // [2] function ControlsPanel({ values, onCommit, }: { values: EdgeScrollValues onCommit(next: EdgeScrollValues): void }) { const [pending, setPending] = useState(values) return (
Edge scrolling options
{CONTROLS.map((control) => { // read the slider's value from the DOM at commit time so the commit // can't lag behind the last change event const commit = (input: HTMLInputElement) => onCommit({ ...pending, [control.key]: Number(input.value) }) return ( ) })}
) } function createDemoShapes(editor: Editor) { // changing the options prop recreates the editor but keeps the store, so // only create the demo shapes on the first mount if (editor.getCurrentPageShapeIds().size > 0) return editor.createShape({ type: 'text', x: 120, y: 80, props: { richText: toRichText('Drag a shape toward the edge of the window to edge scroll'), }, }) const colors = ['blue', 'orange', 'green'] as const colors.forEach((color, i) => { editor.createShape({ type: 'geo', x: 150 + i * 220, y: 200, props: { w: 140, h: 140, fill: 'solid', color }, }) }) } export default function EdgeScrollingExample() { const [values, setValues] = useState(DEFAULTS) return (
{/* [3] */}
) } /* [1] Edge scrolling is configured through four editor options: - edgeScrollSpeed: the base scroll speed in pixels per tick (default 25). The speed also scales with how close the pointer is to the edge, and is reduced on small screens. - edgeScrollDelay: how long (ms) the pointer must stay near the edge before scrolling starts (default 200). Raising it prevents accidental scrolls. - edgeScrollEaseDuration: how long (ms) the scroll takes to accelerate from zero to full speed once it starts (default 200). - edgeScrollDistance: the width in pixels of the edge zone that triggers scrolling (default 8). Pointer positions outside the window scroll at full speed. Try a large zone (200+): since you grab a shape near its middle, scrolling then kicks in as soon as the shape itself touches the window edge, rather than waiting for the pointer to get there. [2] The sliders commit when you release them rather than while you drag. That's because editor options are read once when the editor instance is created: changing the options prop tears down and recreates the editor, so we don't want to do it dozens of times per second mid-drag. Commits fire on pointer release, key release (so keyboard adjustment works too), and blur — re-committing an unchanged value is harmless, since the Tldraw component shallow-compares its options. [3] Options are passed via the Tldraw component's options prop. Any option from TldrawOptions can be overridden this way; unspecified options keep their defaults. */ ``` ## edge-scrolling.css ```css /* This panel lives outside the tldraw container, so the theme variables aren't inherited here — each use provides a fallback value. */ .edge-scrolling__panel { position: absolute; bottom: 80px; left: 8px; z-index: var(--tl-layer-panels, 300); display: flex; flex-direction: column; gap: 8px; width: 240px; padding: 12px; border-radius: 8px; background: var(--tl-color-panel, #fcfcfc); box-shadow: var(--tl-shadow-2, 0 1px 3px rgba(0, 0, 0, 0.2)); } .edge-scrolling__title { font-size: 12px; font-weight: 600; color: var(--tl-color-text-1, #2e2e2e); } .edge-scrolling__row { display: flex; flex-direction: column; gap: 2px; font-size: 11px; color: var(--tl-color-text-1, #2e2e2e); } .edge-scrolling__reset { margin-top: 4px; padding: 4px 8px; border: 1px solid var(--tl-color-muted-1, rgba(0, 0, 0, 0.1)); border-radius: 6px; background: var(--tl-color-panel, #fcfcfc); font-size: 11px; cursor: pointer; } .edge-scrolling__reset:hover { background: var(--tl-color-muted-2, rgba(0, 0, 0, 0.043)); } ``` -------- # Persistence key Category: Configuration Keywords: persistence, local storage, save state, persistencekey, indexeddb, session storage, auto save Save the document in the browser and sync it between tabs with `persistenceKey`. Pass a `persistenceKey` to the `Tldraw` component and it stores the document in IndexedDB under that key, restores it on the next load, and keeps other tabs with the same key in sync via a broadcast channel. Draw something, refresh the page, and it's still there. Open this page in a second tab and changes appear in both. Different keys are independent documents, so use a key per document (for example a document id) rather than one per app. If you need to persist somewhere other than the browser, see the sync and snapshot examples instead. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function PersistenceKeyExample() { return (
) } ``` -------- # Read-only Category: Configuration Keywords: readonly, read-only mode, isreadonly, view only, disable editing, presentation mode, locked editor Put the editor in read-only mode so the document can be viewed but not changed. Read-only mode is an instance state flag: `editor.updateInstanceState({ isReadonly: true })`. This example sets it in `onMount`. When it's on, editing tools disappear from the toolbar (only select, hand, and laser pointer remain), editing commands like delete and paste are ignored, and shapes can't be moved or resized. You can still pan, zoom, select, and use the laser pointer. Because it's instance state rather than document state, it can be toggled at runtime, for example when a user's permissions change. Read it back with `editor.getIsReadonly()`. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function ReadOnlyExample() { return (
{ editor.updateInstanceState({ isReadonly: true }) }} />
) } ``` -------- # Reduced motion preferences Category: Configuration Keywords: accessibility, a11y, reduced motion, animation, prefers-reduced-motion, useprefersreducedmotion, animationspeed, user preferences, custom shape, css animation, vestibular Respect the user's reduced motion preference in a custom shape with `usePrefersReducedMotion`. `usePrefersReducedMotion()` returns `true` when the user has turned on tldraw's "reduce motion" preference (`animationSpeed: 0` in user preferences) or, if no tldraw preference is set, when the operating system reports `prefers-reduced-motion: reduce`. Use it inside a shape's React component to swap animations for static alternatives. The pulse shapes here animate normally and fall back to a still gray circle when reduced motion is preferred. The "Toggle" button in the top panel flips the tldraw preference with `editor.user.updateUserPreferences({ animationSpeed })`, so you can watch every shape switch at once. The same setting is available to users under Preferences > Accessibility > Reduce motion in the main menu. Reduced motion matters for users with vestibular disorders and motion sensitivity, and honoring it is cheap once the check is in one place. ## App.tsx ```tsx import { Geometry2d, HTMLContainer, RecordProps, Rectangle2d, ShapeUtil, T, TLComponents, TLShape, Tldraw, TldrawUiButton, useEditor, usePrefersReducedMotion, } from 'tldraw' import 'tldraw/tldraw.css' import './reduced-motion.css' const PULSE_SHAPE_TYPE = 'pulse-shape' // [1] declare module 'tldraw' { export interface TLGlobalShapePropsMap { [PULSE_SHAPE_TYPE]: { w: number; h: number } } } type PulseShape = TLShape // [2] function PulseShapeComponent() { const prefersReducedMotion = usePrefersReducedMotion() return (
{prefersReducedMotion ? 'Static mode' : 'Animated mode'}
) } // [3] export class PulseShapeUtil extends ShapeUtil { static override type = PULSE_SHAPE_TYPE static override props: RecordProps = { w: T.number, h: T.number, } getDefaultProps(): PulseShape['props'] { return { w: 200, h: 200 } } getGeometry(shape: PulseShape): Geometry2d { return new Rectangle2d({ width: shape.props.w, height: shape.props.h, isFilled: true, }) } component() { return } getIndicatorPath(shape: PulseShape) { const path = new Path2D() path.rect(0, 0, shape.props.w, shape.props.h) return path } } // [4] function MotionToggle() { const editor = useEditor() const prefersReducedMotion = usePrefersReducedMotion() const toggleMotion = () => { const currentSpeed = editor.user.getAnimationSpeed() editor.user.updateUserPreferences({ animationSpeed: currentSpeed === 0 ? 1 : 0, }) } return (
Motion: {prefersReducedMotion ? 'Reduced' : 'Normal'} Toggle
) } const components: TLComponents = { TopPanel: MotionToggle, } const shapeUtils = [PulseShapeUtil] export default function ReducedMotionExample() { return (
{ editor.createShape({ type: PULSE_SHAPE_TYPE, x: 200, y: 200 }) editor.createShape({ type: PULSE_SHAPE_TYPE, x: 450, y: 200 }) editor.createShape({ type: PULSE_SHAPE_TYPE, x: 325, y: 450 }) }} />
) } /* [1] Registering the props in TLGlobalShapePropsMap is what makes `editor.createShape({ type })` type-check and gives `TLShape<'pulse-shape'>` its props type. [2] `usePrefersReducedMotion()` returns true when the user's tldraw preference has `animationSpeed` set to 0, or (if no preference is set) when the OS reports `prefers-reduced-motion: reduce`. It is a hook, so the shape's rendering lives in a React component that `component()` returns; the component re-renders when the preference changes and swaps the CSS class from the pulsing indicator to the static one. [3] The util itself is minimal: geometry, indicator, and the component above. [4] The toggle flips the tldraw preference with `editor.user.updateUserPreferences()`. Setting `animationSpeed: 0` is what tldraw's own "reduce motion" preference does, so the hook and every shape using it respond the same way they would to the built-in setting. */ ``` ## reduced-motion.css ```css .pulse-shape { display: flex; align-items: center; justify-content: center; pointer-events: all; background-color: var(--tl-color-low); border: 1px solid var(--tl-color-low-border); border-radius: var(--tl-radius-3); } .pulse-shape__content { text-align: center; } .pulse-shape__label { font-size: 14px; color: var(--tl-color-text-1); } .pulse-indicator, .pulse-indicator--static { width: 40px; height: 40px; border-radius: 50%; margin: 0 auto 16px; } .pulse-indicator { background-color: var(--tl-color-primary); animation: pulse 2s ease-in-out infinite; } .pulse-indicator--static { background-color: var(--tl-color-text-3); } @keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.2); opacity: 0.7; } } .motion-toggle { display: flex; gap: 8px; align-items: center; padding: 0 8px; pointer-events: all; } .motion-toggle__label { font-size: 14px; } ``` -------- # Custom embeds Category: Configuration Keywords: embed, iframe, CustomEmbedDefinition, DEFAULT_EMBED_DEFINITIONS, toEmbedUrl, fromEmbedUrl, jsfiddle, url parsing Add a custom embed provider and remove some of the built-in ones. tldraw recognizes URLs from many services out of the box and turns them into embed shapes. This example configures `EmbedShapeUtil` with its own list of `embedDefinitions`: two of the defaults (tldraw and YouTube) plus a new `CustomEmbedDefinition` for JSFiddle. A definition pairs `hostnames` with `toEmbedUrl` and `fromEmbedUrl` functions that convert between the page URL and the iframe URL. Custom definitions also need an `icon`, which shows in the embed dialog. Try clicking "Insert embed" in the top panel: only tldraw, YouTube, and JSFiddle are listed. Pasting a JSFiddle URL like `https://jsfiddle.net/user/abc123/1/embedded/` onto the canvas also creates an embed. For sandbox permissions and other per-definition options, see the embed permissions example. ## App.tsx ```tsx import { CustomEmbedDefinition, DEFAULT_EMBED_DEFINITIONS, DefaultEmbedDefinitionType, EmbedShapeUtil, TLComponents, Tldraw, TldrawUiButton, TldrawUiButtonLabel, useActions, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const defaultEmbedTypesToKeep: DefaultEmbedDefinitionType[] = ['tldraw', 'youtube'] const defaultEmbedsToKeep = DEFAULT_EMBED_DEFINITIONS.filter((embed) => defaultEmbedTypesToKeep.includes(embed.type) ) // [2] const customEmbed: CustomEmbedDefinition = { type: 'jsfiddle', title: 'JSFiddle', hostnames: ['jsfiddle.net'], minWidth: 300, minHeight: 300, width: 720, height: 500, doesResize: true, toEmbedUrl: (url) => { const urlObj = new URL(url) const matches = urlObj.pathname.match(/\/([^/]+)\/([^/]+)\/(\d+)\/embedded/) if (matches) { return `https://jsfiddle.net/${matches[1]}/${matches[2]}/embedded/` } return }, fromEmbedUrl: (url) => { const urlObj = new URL(url) const matches = urlObj.pathname.match(/\/([^/]+)\/([^/]+)\/(\d+)\/embedded/) if (matches) { return `https://jsfiddle.net/${matches[1]}/${matches[2]}/` } return }, icon: 'https://jsfiddle.net/img/favicon.png', } // [3] const shapeUtils = [ EmbedShapeUtil.configure({ embedDefinitions: [...defaultEmbedsToKeep, customEmbed] }), ] // [4] function InsertEmbedButton() { const actions = useActions() return (
actions['insert-embed'].onSelect('helper-buttons')} > Insert embed
) } const components: TLComponents = { TopPanel: InsertEmbedButton, } export default function CustomEmbedExample() { return (
) } /* [1] tldraw ships embed definitions for several popular apps in `DEFAULT_EMBED_DEFINITIONS`. Here we keep only the 'tldraw' and 'youtube' ones; the rest will no longer be offered in the embed dialog or recognized when a URL is pasted. [2] A custom definition for JSFiddle. `hostnames` decides which pasted URLs this definition handles, `toEmbedUrl` turns a page URL into the iframe URL (returning undefined rejects the URL), and `fromEmbedUrl` maps back for copying the link out. Custom definitions must include an `icon`, which the embed dialog shows next to the title. [3] `EmbedShapeUtil.configure({ embedDefinitions })` replaces the whole list, so include any defaults you want to keep alongside the custom one. [4] An "Insert embed" button in the top panel, so the dialog is one click away. It triggers the built-in `insert-embed` action via `useActions`, the same one the main menu uses. */ ``` -------- # Environment detection Category: Configuration Keywords: tlenv, tlenvreactive, platform detection, browser, iscoarsepointer, touch, mobile, adaptive ui, usevalue Detect the platform, browser, and pointer type with `tlenv` and `tlenvReactive`. tldraw exports two objects that describe the environment it's running in: - `tlenv` is a plain object of flags that don't change during a session: `isDarwin`, `isIos`, `isAndroid`, `isSafari`, `isFirefox`, `isChromeForIos`, and so on. Read it directly, for example to show Cmd instead of Ctrl in shortcut hints on macOS. - `tlenvReactive` is an atom holding values that can change while the app is open, most importantly `isCoarsePointer`. Read it with `useValue` (or inside a `track`ed component) so your UI updates when it changes. The panel at the top shows what each one reports for your device, and a button that grows to a 48px touch target when the pointer is coarse. On a touchscreen laptop, tap the screen and then move the trackpad to watch the pointer type and button size switch. ## App.tsx ```tsx import { Tldraw, TldrawUiButton, TldrawUiIcon, tlenv, tlenvReactive, useValue } from 'tldraw' import 'tldraw/tldraw.css' import './environment-detection.css' function EnvironmentInfo() { // [1] const isCoarsePointer = useValue('coarse pointer', () => tlenvReactive.get().isCoarsePointer, []) // [2] const buttonSize = isCoarsePointer ? '48px' : '32px' return (
{/* [3] */}
Platform (tlenv): {tlenv.isIos && 'iOS'} {tlenv.isDarwin && !tlenv.isIos && 'macOS'} {tlenv.isAndroid && 'Android'} {!tlenv.isDarwin && !tlenv.isIos && !tlenv.isAndroid && 'Other'}
Browser: {tlenv.isSafari && 'Safari'} {tlenv.isFirefox && 'Firefox'} {tlenv.isChromeForIos && 'Chrome for iOS'} {!tlenv.isSafari && !tlenv.isFirefox && !tlenv.isChromeForIos && 'Other'}
Modifier key: {tlenv.isDarwin ? '⌘ Cmd' : 'Ctrl'}
Pointer type (tlenvReactive): {isCoarsePointer ? 'Touch' : 'Mouse'}
alert(`Button size: ${buttonSize}`)} >
) } const components = { TopPanel: EnvironmentInfo, } export default function EnvironmentDetectionExample() { return (
) } /* [1] `tlenvReactive` is an atom, so read it inside `useValue` to re-render when it changes. On a touchscreen laptop `isCoarsePointer` flips as the user switches between touching the screen and using the trackpad. `tlenv` is a plain object whose values are fixed at load time, so it can be read directly during render. [2] Touch needs bigger targets than a mouse: 48px for a coarse pointer, 32px for a fine one. [3] `isIos` is checked before `isDarwin` because iPadOS reports itself as a Mac, so both are true on an iPad. */ ``` ## environment-detection.css ```css .environment-info { display: flex; flex-direction: column; gap: 8px; margin: 8px; padding: 12px; } ``` -------- # Embed permissions Category: Configuration Keywords: embed, iframe, sandbox, permissions, aspect ratio, interactive, youtube, security Configure embed sandbox permissions, aspect ratio locking, and visual options. Embedded iframes in tldraw are sandboxed with deliberately conservative defaults (`embedShapePermissionDefaults`). This example configures `EmbedShapeUtil` with two embed definitions that override those defaults in opposite directions: - A **YouTube** definition that grants `allow-presentation` (so the fullscreen button works), locks the aspect ratio to 16:9 with `isAspectRatioLocked`, sets a `backgroundColor` for the loading state, and disables `canEditWhileLocked`. - A **read-only website** definition (showing Wikipedia's whiteboard article) that turns off scripts, forms, popups, and same-origin access entirely. This is the pattern for embedding untrusted pages as inert previews. It uses `overrideOutlineRadius` to round the shape outline, and works here because Wikipedia renders its content without JavaScript; a script-dependent site would show an empty frame in this mode. The example also shows the embed interactivity rule: an embed's iframe ignores pointer events until you double-click the shape to enter its editing state, which is why embeds can be dragged and resized without the iframe capturing the pointer. For adding a new embed provider from scratch, see the custom embed example. ## App.tsx ```tsx import { CustomEmbedDefinition, DEFAULT_EMBED_DEFINITIONS, Editor, EmbedShapeUtil, TLEmbedDefinition, TLEmbedShape, Tldraw, toRichText, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const youtube = DEFAULT_EMBED_DEFINITIONS.find((def) => def.type === 'youtube')! // [1] const presentationYoutube: TLEmbedDefinition = { ...youtube, isAspectRatioLocked: true, backgroundColor: '#000000', canEditWhileLocked: false, overridePermissions: { 'allow-presentation': true, }, } // [2] const readOnlyWebsite: CustomEmbedDefinition = { type: 'website', title: 'Website (read-only)', hostnames: ['wikipedia.org', '*.wikipedia.org'], width: 680, height: 1000, doesResize: true, overrideOutlineRadius: 12, backgroundColor: '#f8f9fa', overridePermissions: { 'allow-scripts': false, 'allow-forms': false, 'allow-popups': false, 'allow-same-origin': false, }, toEmbedUrl: (url) => url, fromEmbedUrl: (url) => url, icon: 'https://en.wikipedia.org/static/favicon/wikipedia.ico', } // [3] const shapeUtils = [ EmbedShapeUtil.configure({ embedDefinitions: [presentationYoutube, readOnlyWebsite] }), ] // [4] function handleMount(editor: Editor) { editor.createShape({ type: 'text', x: 100, y: 40, props: { richText: toRichText( 'Embeds are inert until you double-click them (editing state). Try resizing each one, too.' ), }, }) editor.createShape({ type: 'text', x: 100, y: 100, props: { richText: toRichText('YouTube: aspect ratio locked, fullscreen allowed'), size: 's', }, }) editor.createShape({ type: 'embed', x: 100, y: 140, props: { // "tldraw sync — multiplayer whiteboards in React" from the tldraw channel url: 'https://www.youtube.com/watch?v=COw7Wm9HS-g', w: 640, h: 360, }, }) editor.createShape({ type: 'text', x: 820, y: 100, props: { richText: toRichText('Read-only website: scripts, forms, and popups disabled'), size: 's', }, }) editor.createShape({ type: 'embed', x: 820, y: 140, props: { // what else would a whiteboard embed? url: 'https://en.wikipedia.org/wiki/Whiteboard', w: 680, h: 1000, }, }) editor.zoomToFit() } export default function EmbedPermissionsExample() { return (
) } /* Embedded iframes are sandboxed. The defaults (embedShapePermissionDefaults in the tldraw package) are deliberately conservative — scripts, same-origin, forms, and popups allowed; modals, popups-to-escape-sandbox, top navigation, and presentation disabled. Each definition can override individual permissions. The custom embed example covers adding a provider in the first place. [1] A customized YouTube definition: - overridePermissions grants 'allow-presentation' so the player's fullscreen button works (a permission that's off by default because a malicious embed could "present" itself pretending to be the host app). - isAspectRatioLocked keeps the player 16:9 when resized — try a corner handle. - backgroundColor fills the shape behind the iframe while it loads. - canEditWhileLocked: false means a locked shape can't enter its interactive editing state. [2] A definition pointing the other way: an intentionally locked-down website embed, here showing Wikipedia's article on whiteboards. Everything risky is off — no scripts, no forms, no popups, no same-origin access — the pattern to use for embedding untrusted pages as inert, read-only previews. Note that the page still renders because Wikipedia is server-rendered: with allow-scripts off, a site that needs JavaScript to paint would show an empty frame, so pick embeds for this mode accordingly. overrideOutlineRadius rounds the shape's outline to match providers whose embeds have their own border radius (Spotify is the in-tree example). [3] Definitions are passed to EmbedShapeUtil with configure(), replacing the default list. Adding a definition with an icon (CustomEmbedDefinition) also puts it in the insert-embed dialog. [4] Embed shapes are created like any shape: the util matches the url against each definition's hostnames to pick the right definition. Note the interactivity rule: an embed's iframe ignores pointer events until you double-click the shape to start editing it (editor.getEditingShapeId() controls this) — that's why you can drag embeds around without the iframe swallowing your clicks. */ ``` -------- # Deep links Category: Configuration Keywords: deep links, url, navigation, viewport, search params, createdeeplink, navigatetodeeplink, routing Keep the camera position in the URL so links open at the same view. Deep links are URLs that point to a specific part of a document: a viewport, a page, or a set of shapes. Try it here: create a shape, then pan or zoom. The `d` search param in the URL updates as you go, and opening that URL in a new tab returns to the same view. ## The `deepLinks` option The simplest way to use deep links is the `deepLinks` key of the `Tldraw` component's `options` prop. It keeps `window.location` in sync with a search param that tldraw can navigate to, e.g. `https://my-app.com/document-name?d=v1234.-234.3.21`. Setting `deepLinks: true` enables the default behavior: 1. When the editor initializes, before the initial render, it checks `window.location` for a search param called `d`. If found, it parses the value as a deep link and navigates there. 2. 500 milliseconds after each camera or page change, it updates `window.location` with the latest `d` param. You can customize this behavior by passing an options object instead: ```tsx ``` For full options see the [`TLDeepLinkOptions`](/reference/editor/TLDeepLinkOptions) API reference. ## Handling deep links manually The same functionality is exposed as methods and utilities, which gives you more control if, for example, you prefer not to use search params in the URL. ### Creating a deep link You can create an isolated deep link string using the [`createDeepLinkString`](/reference/editor/createDeepLinkString) helper which takes a [`TLDeepLink`](/reference/editor/TLDeepLink) descriptor object. ```tsx createDeepLinkString({ type: 'page', pageId: 'page:abc123' }) // => 'pabc123' createDeepLinkString({ type: 'shapes', shapeIds: ['shape:foo', 'shape:bar'] }) // => 'sfoo.bar' createDeepLinkString({ type: 'viewport', pageId: 'page:abc123', bounds: { x: 0, y: 0, w: 1024, h: 768, }, }) // => 'v0.0.1024.768.abc123' ``` If you do prefer to put this in a URL as a query param, you can use the [`Editor.createDeepLink`](/reference/editor/Editor#createDeepLink) method. ```tsx editor.createDeepLink({ to: { type: 'page', pageId: 'page:abc123' } }) // => 'https://my-app.com/document-name?d=pabc123' ``` ### Handling a deep link You can parse a deep link string with [`parseDeepLinkString`](/reference/editor/parseDeepLinkString) which returns a [`TLDeepLink`](/reference/editor/TLDeepLink) descriptor object. You can then call [`Editor.navigateToDeepLink`](/reference/editor/Editor#navigateToDeepLink) with this descriptor to navigate to the part of the document described by the deep link. `Editor#navigateToDeepLink` also can take a plain URL if the deep link is encoded as a query param. ```tsx editor.navigateToDeepLink(parseDeepLinkString('pabc123')) // or pass in a url editor.navigateToDeepLink({ url: 'https://my-app.com/document-name?d=pabc123' }) // or call without options to use the current `window.location` editor.navigateToDeepLink() ``` ### Listening for deep link changes You can listen for deep link changes with the [`Editor.registerDeepLinkListener`](/reference/editor/Editor#registerDeepLinkListener) method, which takes the same options as the `deepLinks` option. ```tsx useEffect(() => { const unlisten = editor.registerDeepLinkListener({ param: 'page', getTarget(editor) { return { type: 'page', pageId: editor.getCurrentPageId() } }, onChange(url) { console.log('the new search params are', url.searchParams) }, debounceMs: 100, }) return () => { unlisten() } }, [editor]) ``` ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function DeepLinksExample() { return (
) } ``` -------- # Frame colors Category: Configuration Keywords: frame, colors, configure, frameshapeutil, showcolors, shapeutils Give frames a colored fill and heading with the `showColors` option. By default frames are white with a plain heading and ignore the color style. `FrameShapeUtil.configure({ showColors: true })` makes frames use the selected color for a tinted fill and a colored heading, and adds the color picker to the style panel when a frame is selected. Create a frame (F), then pick a color in the style panel to see it applied. ## App.tsx ```tsx import { FrameShapeUtil, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' const shapeUtils = [FrameShapeUtil.configure({ showColors: true })] export default function FrameColorsExample() { return (
) } ``` -------- # Note resizing Category: Configuration Keywords: note shape, resize, sticky note, resizemode, scale, configure, shapeutil configuration, note scaling Let users resize sticky notes with `NoteShapeUtil`'s `resizeMode` option. Notes have a fixed size by default and can't be resized. `NoteShapeUtil.configure({ resizeMode: 'scale' })` makes them scale as a whole when a resize handle is dragged: the note, its text, and its padding all grow together, so the note keeps its proportions rather than reflowing. Create a note (N) and drag a corner handle to try it. `resizeMode: 'none'` is the default behavior. ## App.tsx ```tsx import { NoteShapeUtil, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' const shapeUtils = [NoteShapeUtil.configure({ resizeMode: 'scale' })] export default function ResizeNoteExample() { return (
) } ``` -------- # Precise exact arrows Category: Configuration Keywords: arrow, configure, isprecise, isexact, arrow behavior, arrowshapeutil, arrow tool, alt key Make precise arrows always bind exactly, using `ArrowShapeUtil.configure`. An arrow bound to a shape is either imprecise (it points at the shape's center) or precise (it points at a specific spot inside the shape). A precise arrow can also be exact: instead of stopping at the shape's edge, it continues into the shape all the way to the bound point. By default an arrow becomes precise when you hover slowly over a target, and becomes exact when you also hold Alt. The `shouldBeExact` option on `ArrowShapeUtil` receives the editor and whether the current binding is precise, and returns whether it should also be exact. This example returns `isPrecise`, so every precise arrow is exact and Alt is no longer needed. Try it: draw an arrow into a shape and pause before releasing. The arrow tip lands inside the shape instead of stopping at its edge. ## App.tsx ```tsx import { ArrowShapeUtil, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' const shapeUtils = [ ArrowShapeUtil.configure({ shouldBeExact: (editor, isPrecise) => isPrecise, }), ] export default function ArrowsPreciseExactExample() { return (
) } ``` -------- # Disable pages Category: Configuration Keywords: maxpages, single page, options, page selector, configuration Hide the page menu and page management UI with `maxPages: 1`. Set the `maxPages` editor option to `1` to remove the page menu from the top-left panel and the "move to page" item from the context menu. This is what most single-canvas apps want. The document itself still contains one page record, so shapes and the store work exactly as before. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function DisablePagesExample() { return (
) } ``` -------- # Minimal Category: Configuration Keywords: tldraweditor, minimal, bare bones, custom ui, no ui, headless, shapeutils, tools, statenodeonly Use `TldrawEditor` on its own with one custom shape and one custom tool, and no UI. `TldrawEditor` is the editor without tldraw's default shapes, tools, or UI. You provide everything: here that's a single box shape (`MiniBoxShapeUtil`) and a small select tool (`MiniSelectTool`) built as a `StateNode` with idle, pointing, and dragging child states. Double-click the canvas to create a box, double-click a box to delete it, click or shift-click to select, and drag to move. `MicroSelectTool.ts` in the same folder shows an even smaller select tool with no child states; it isn't used by the example but is a good starting point for reading. For a fuller custom shape and tool, see the custom config example. For the pieces the `Tldraw` component adds on top of `TldrawEditor`, see the sublibraries example. ## App.tsx ```tsx import { TldrawEditor, createShapeId } from 'tldraw' import 'tldraw/tldraw.css' import { MiniBoxShapeUtil } from './MiniBoxShape' import { MiniSelectTool } from './MiniSelectTool' // There's a guide at the bottom of this file! // [1] const tools = [MiniSelectTool] const shapeUtils = [MiniBoxShapeUtil] function Instructions() { return (

Double click to create or delete shapes.

Click or shift+click to select shapes.

Click and drag to move shapes.

) } const components = { OnTheCanvas: Instructions, } // [2] export default function OnlyEditorExample() { return (
{ editor .selectAll() .deleteShapes(editor.getSelectedShapeIds()) .createShapes([{ id: createShapeId(), type: 'box', x: 100, y: 100 }]) }} />
) } /* [1] TldrawEditor has no built-in shapes or tools, so we supply our own: a box shape util (MiniBoxShape.tsx) and a select tool (MiniSelectTool.ts). MicroSelectTool.ts is an even smaller select tool without child states; it isn't wired up here but is worth reading first. The custom config example covers writing shapes and tools in more depth. [2] `initialState` names the tool the editor starts in; it must match a tool's `static id`. There is no UI here, so the instructions are rendered through the `OnTheCanvas` component slot instead. */ ``` ## MicroSelectTool.ts ```ts import { StateNode, TLClickEventInfo, TLPointerEventInfo, createShapeId } from 'tldraw' // There's a guide at the bottom of this file! // [1] export class MicroSelectTool extends StateNode { static override id = 'select' // [2] override onPointerDown(info: TLPointerEventInfo) { const { editor } = this switch (info.target) { case 'canvas': { const hitShape = editor.getShapeAtPoint(editor.inputs.getCurrentPagePoint()) if (hitShape) { this.onPointerDown({ ...info, shape: hitShape, target: 'shape', }) return } editor.selectNone() break } case 'shape': { editor.select(info.shape.id) break } } } // [3] override onDoubleClick(info: TLClickEventInfo) { const { editor } = this if (info.phase !== 'up') return switch (info.target) { case 'canvas': { const hitShape = editor.getShapeAtPoint(editor.inputs.getCurrentPagePoint()) if (hitShape) { this.onDoubleClick({ ...info, shape: hitShape, target: 'shape', }) return } const currentPagePoint = editor.inputs.getCurrentPagePoint() editor.createShapes([ { id: createShapeId(), type: 'box', x: currentPagePoint.x - 50, y: currentPagePoint.y - 50, props: { w: 100, h: 100, }, }, ]) break } case 'shape': { editor.deleteShapes([info.shape.id]) break } } } } /* The smallest possible "select" tool: a single StateNode with no child states. It isn't used by the example; MiniSelectTool.ts is the version that's wired up. [1] A tool is a StateNode with a static `id`. If this tool were registered in place of MiniSelectTool, the example's `initialState="select"` would start the editor in it. With no children, event handlers go directly on the tool. [2] Pointer events arrive with a `target` of 'canvas' or 'shape'. Custom shapes rendered with `pointerEvents: 'all'` report themselves as the target, but hits on the canvas can still land on a shape (for example when the pointer is inside a hollow shape), so we re-check with `getShapeAtPoint` and re-dispatch as a 'shape' event. [3] Double-click fires once per phase ('down', 'up', 'settle-down', 'settle-up'); we only act on 'up' so the shape is created or deleted once. */ ``` ## MiniBoxShape.tsx ```tsx import { BaseBoxShapeUtil, HTMLContainer, TLShape } from 'tldraw' // There's a guide at the bottom of this file! const BOX_TYPE = 'box' // [1] declare module 'tldraw' { export interface TLGlobalShapePropsMap { [BOX_TYPE]: { w: number; h: number; color: string } } } // [2] export type MiniBoxShape = TLShape // [3] export class MiniBoxShapeUtil extends BaseBoxShapeUtil { static override type = BOX_TYPE override getDefaultProps(): MiniBoxShape['props'] { return { w: 100, h: 100, color: '#efefef' } } // [a] component(shape: MiniBoxShape) { return (
) } // [b] getIndicatorPath(shape: MiniBoxShape) { const path = new Path2D() path.rect(0, 0, shape.props.w, shape.props.h) return path } } /* [1] Registering the props in TLGlobalShapePropsMap is what makes `editor.createShapes({ type: 'box' })` type-check and gives `TLShape<'box'>` its props type. [2] The shape's record type, derived from the registration above. [3] BaseBoxShapeUtil supplies rectangular geometry and resize behavior for any shape with `w` and `h` props, so this util only needs to say what the box looks like. [a] HTMLContainer positions the shape's DOM on the canvas. `pointerEvents: 'all'` is what lets the select tool receive events with this shape as the target. [b] The indicator is the outline drawn when the shape is selected or hovered, as a Path2D in shape space. */ ``` ## MiniSelectTool.ts ```ts import { StateNode, TLClickEventInfo, TLPointerEventInfo, TLShape, createShapeId } from 'tldraw' // There's a guide at the bottom of this file! // [1] export class MiniSelectTool extends StateNode { static override id = 'select' static override children() { return [IdleState, PointingState, DraggingState] } static override initial = 'idle' } // [2] class IdleState extends StateNode { static override id = 'idle' // [a] override onPointerDown(info: TLPointerEventInfo) { const { editor } = this switch (info.target) { case 'canvas': { const hitShape = editor.getShapeAtPoint(editor.inputs.getCurrentPagePoint()) if (hitShape) { this.onPointerDown({ ...info, shape: hitShape, target: 'shape', }) return } editor.selectNone() break } case 'shape': { if (editor.inputs.getShiftKey()) { editor.select(...editor.getSelectedShapeIds(), info.shape.id) } else { if (!editor.getSelectedShapeIds().includes(info.shape.id)) { editor.select(info.shape.id) } this.parent.transition('pointing', info) } break } } } // [b] override onDoubleClick(info: TLClickEventInfo) { const { editor } = this if (info.phase !== 'up') return switch (info.target) { case 'canvas': { const hitShape = editor.getShapeAtPoint(editor.inputs.getCurrentPagePoint()) if (hitShape) { this.onDoubleClick({ ...info, shape: hitShape, target: 'shape', }) return } const currentPagePoint = editor.inputs.getCurrentPagePoint() editor.createShapes([ { id: createShapeId(), type: 'box', x: currentPagePoint.x - 50, y: currentPagePoint.y - 50, props: { w: 100, h: 100, }, }, ]) break } case 'shape': { editor.deleteShapes([info.shape.id]) break } } } } // [3] class PointingState extends StateNode { static override id = 'pointing' // [a] override onPointerUp(info: TLPointerEventInfo) { this.parent.transition('idle', info) } // [b] override onPointerMove() { if (this.editor.inputs.getIsDragging()) { this.parent.transition('dragging', { shapes: [...this.editor.getSelectedShapes()] }) } } } // [4] class DraggingState extends StateNode { static override id = 'dragging' private initialDraggingShapes: TLShape[] = [] // [a] override onEnter(info: { shapes: TLShape[] }) { this.initialDraggingShapes = info.shapes } override onPointerUp(info: TLPointerEventInfo) { this.parent.transition('idle', info) } // [b] override onPointerMove() { const { initialDraggingShapes } = this const originPagePoint = this.editor.inputs.getOriginPagePoint() const currentPagePoint = this.editor.inputs.getCurrentPagePoint() this.editor.updateShapes( initialDraggingShapes.map((shape) => { return { ...shape, x: shape.x + (currentPagePoint.x - originPagePoint.x), y: shape.y + (currentPagePoint.y - originPagePoint.y), } }) ) } } /* Tools are nodes in the editor's state chart (https://tldraw.dev/docs/tools). This tool has three child states, idle [2], pointing [3], and dragging [4]; exactly one is active at a time, and events go to the active child. A child calls `this.parent.transition(id, info)` to hand control to a sibling; the sibling's `onEnter` receives `info`, which is how data moves between states. [1] The tool itself only declares its id, its children, and which child starts active. [2] Idle is where the tool waits for input. [a] Pointer events arrive with a `target` of 'canvas' or 'shape'. A hit on the canvas can still land on a shape (for example inside a hollow shape), so we re-check with `getShapeAtPoint` and re-dispatch as a 'shape' event. Pointing a shape selects it (or adds it with shift) and moves to pointing so a drag can begin. [b] Double-click fires once per phase ('down', 'up', 'settle-down', 'settle-up'); we only act on 'up' so the shape is created or deleted once. [3] Pointing exists to tell a click from a drag. [a] Pointer up without moving far enough: back to idle. [b] `editor.inputs.getIsDragging()` becomes true once the pointer has moved past the drag threshold. We then move to dragging and hand it the shapes to move. [4] Dragging moves the selected shapes. [a] The shapes captured on enter keep their original positions, so each move can be computed from the pointer's total offset since the drag started rather than accumulated deltas. [b] `getOriginPagePoint()` is where the pointer went down; the difference to `getCurrentPagePoint()` is applied to each shape's starting position with `editor.updateShapes()`. */ ``` -------- # Sublibraries Category: Configuration Keywords: tldraweditor, tldrawui, sublibraries, modular, architecture, defaultshapeutils, defaulttools, components Assemble the `Tldraw` component yourself from `TldrawEditor`, `TldrawUi`, and the default shapes and tools. The `Tldraw` component is a convenience wrapper. Underneath it is `TldrawEditor` (the canvas and editor, with no shapes, tools, or UI of its own), `TldrawUi` (the default menus, toolbar, and panels), and a set of defaults: `defaultShapeUtils`, `defaultBindingUtils`, `defaultTools`, `defaultShapeTools`, and so on. This example builds the same editor from those pieces. It behaves like the plain `Tldraw` component, but every part is now visible and replaceable: drop a shape util from the list, pass a different tool set, or leave out `TldrawUi` and supply your own interface. The only-editor example goes further and uses `TldrawEditor` with a single custom shape and tool. ## App.tsx ```tsx import { useEffect } from 'react' import { ContextMenu, DEFAULT_SUPPORTED_IMAGE_TYPES, DEFAULT_SUPPORT_VIDEO_TYPES, DefaultContextMenuContent, TldrawEditor, TldrawUi, defaultAddFontsFromNode, defaultAssetUtils, defaultBindingUtils, defaultEditorAssetUrls, defaultOverlayUtils, defaultShapeTools, defaultShapeUtils, defaultTools, registerDefaultExternalContentHandlers, registerDefaultSideEffects, tipTapDefaultExtensions, useEditor, useToasts, useTranslation, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const allDefaultTools = [...defaultTools, ...defaultShapeTools] const defaultOptions = { text: { tipTapConfig: { extensions: tipTapDefaultExtensions, }, addFontsFromNode: defaultAddFontsFromNode, }, } // [1] export default function ExplodedExample() { return (
) } function InsideEditorAndUiContext() { const editor = useEditor() const toasts = useToasts() const msg = useTranslation() // [2] useEffect(() => { registerDefaultExternalContentHandlers(editor, { maxImageDimension: 5000, maxAssetSize: 10 * 1024 * 1024, // 10mb acceptedImageMimeTypes: DEFAULT_SUPPORTED_IMAGE_TYPES, acceptedVideoMimeTypes: DEFAULT_SUPPORT_VIDEO_TYPES, toasts, msg, }) const cleanupSideEffects = registerDefaultSideEffects(editor) return () => { cleanupSideEffects() } }, [editor, msg, toasts]) return ( ) } /* The `Tldraw` component is a thin wrapper that wires these pieces together. Assembling them yourself lets you swap or omit any of them. [1] `TldrawEditor` is the UI-free editor. Everything the `Tldraw` component normally supplies is passed in explicitly here: the default shape utils, binding utils, asset utils, overlay utils, tools, asset URLs, and the rich text options. Swap any of these for your own; the custom config example shows how to write shapes and tools. `TldrawUi` renders the default UI around it, and the context menu is mounted as a child so it can wrap the canvas. [2] Two more things the `Tldraw` component does on mount that `TldrawEditor` does not: register the default external content handlers (dropped and pasted files, URLs, embeds, SVG text) and the default store side effects (for example, resolving an embed's aspect ratio when it is created). Both need the toasts and translation contexts from `TldrawUi`, which is why this component is rendered inside it. */ ``` -------- # Controlling the canvas Category: Editor API Keywords: editor api, createshapes, updateshape, rotateshapesby, zoomtofit, select, useeditor, onmount, setstyle, context Create, update, rotate, and select shapes and move the camera with the editor API. The `Editor` instance is the entry point for everything you can do programmatically in tldraw. This example gets the editor two ways, from the `onMount` callback and from the `useEditor` hook inside a child component, then walks through a short timeline of API calls: `createShapes`, `updateShape`, `rotateShapesBy`, `zoomToFit`, `select`, and finally `setStyleForSelectedShapes` and `setStyleForNextShapes` to cycle the shape's color. Watch the canvas after it loads: each step runs one second after the last so you can see what every call does. ## App.tsx ```tsx import { useEffect } from 'react' import { createShapeId, DefaultColorStyle, Editor, TLGeoShape, Tldraw, toRichText, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const STEP_MS = 1000 const TIMELINE_MS = STEP_MS * 5 // [1] export default function APIExample() { const handleMount = (editor: Editor) => { const id = createShapeId('hello') // Run each API call on its own beat so a viewer can see what each one does. // richText is set at creation time; adding a first label later would trigger // the geo shape's auto-sizing and swallow the height update in step 2. const steps: (() => void)[] = [ // 1. Create the shape () => { editor.createShapes([ { id, type: 'geo', x: 128 + Math.random() * 500, y: 128 + Math.random() * 500, props: { geo: 'rectangle', w: 120, h: 100, dash: 'draw', color: 'blue', size: 'm', richText: toRichText('hello world!'), }, }, ]) }, // 2. Triple the shape's height () => { const shape = editor.getShape(id)! editor.updateShape({ id, type: 'geo', props: { h: shape.props.h * 3 }, }) }, // 3. Rotate the shape around its center () => editor.rotateShapesBy([id], Math.PI / 8), // 4. Zoom the camera to fit the shape () => editor.zoomToFit(), // 5. Select the shape () => editor.select(id), ] const timeouts = steps.map((step, i) => setTimeout(step, i * STEP_MS)) return () => { timeouts.forEach(clearTimeout) } } return (
) } // [2] const InsideOfEditorContext = () => { const editor = useEditor() useEffect(() => { let i = 0 let interval: ReturnType | undefined // Wait for the onMount timeline to finish so the color cycle doesn't // interrupt the staged setup. const start = setTimeout(() => { interval = setInterval(() => { const selection = [...editor.getSelectedShapeIds()] editor.selectAll() editor.setStyleForSelectedShapes(DefaultColorStyle, i % 2 ? 'blue' : 'light-blue') editor.setStyleForNextShapes(DefaultColorStyle, i % 2 ? 'blue' : 'light-blue') editor.setSelectedShapes(selection) i++ }, STEP_MS) }, TIMELINE_MS) return () => { clearTimeout(start) if (interval) clearInterval(interval) } }, [editor]) return null } /* Introduction: This example shows how to use the tldraw editor instance to make changes to the canvas. The editor is tldraw's "god object": you can use it to do just about everything that's possible in tldraw. Internally, the canvas component and all shapes, tools, and UI components use this instance to send events, observe changes, and perform actions. There are two main ways to get hold of the editor: [1] The Tldraw component passes its editor instance to the onMount callback prop. We schedule each API call on its own beat so a viewer can see the effect of every step: creating the shape, updating its height, rotating it, zooming the camera, and selecting it. The cleanup function returned from onMount cancels any pending steps if the editor unmounts first. [2] Any component rendered as a child of Tldraw can read the editor from React context with the useEditor hook. Once the timeline above finishes, this child component takes over and demonstrates two more API calls, setStyleForSelectedShapes and setStyleForNextShapes, by cycling the shape's color. */ ``` -------- # Save and load snapshots Category: Editor API Keywords: snapshot, save, load, getsnapshot, loadsnapshot, persistence, export, import, document, session, localstorage Save the editor's contents with `getSnapshot()` and restore them with `loadSnapshot()`. `getSnapshot(editor.store)` returns a `{ document, session }` object: `document` holds the pages, shapes, and assets, and `session` holds per-user state like the current page, camera, and selection. `loadSnapshot(editor.store, snapshot)` restores either or both. The editor here starts from a bundled snapshot passed to the `snapshot` prop. Draw something, click "Save snapshot", change the canvas, then click "Load snapshot" to restore it from localStorage. ## App.tsx ```tsx import { useEffect, useState } from 'react' import { getSnapshot, loadSnapshot, TLComponents, Tldraw, TldrawUiButton, TLEditorSnapshot, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' import _jsonSnapshot from './snapshot.json' import './snapshots.css' // There's a guide at the bottom of this file! const jsonSnapshot = _jsonSnapshot as any as TLEditorSnapshot function SnapshotToolbar() { const editor = useEditor() const [showCheckMark, setShowCheckMark] = useState(false) const save = () => { // [1] const { document, session } = getSnapshot(editor.store) localStorage.setItem('snapshot', JSON.stringify({ document, session })) setShowCheckMark(true) } const load = () => { const snapshot = localStorage.getItem('snapshot') if (!snapshot) return // [2] loadSnapshot(editor.store, JSON.parse(snapshot)) } useEffect(() => { if (!showCheckMark) return const timeout = setTimeout(() => setShowCheckMark(false), 1000) return () => clearTimeout(timeout) }, [showCheckMark]) return (
Saved Save snapshot Load snapshot
) } const components: TLComponents = { SharePanel: SnapshotToolbar, } export default function SnapshotExample() { return (
{/* [3] */}
) } /* [1] `getSnapshot(editor.store)` returns `{ document, session }`. `document` is the content: pages, shapes, assets, and so on. `session` is per-user editor state such as the current page, camera, and selection. In a multi-user app you'd usually store these separately so each user keeps their own session. Here we store both together in localStorage. [2] `loadSnapshot(editor.store, snapshot)` restores it. You can pass just `{ document }` and load `{ session }` later on its own, or skip the session entirely. [3] Passing a snapshot to the `snapshot` prop loads it into the store when the editor is created, so the editor starts with content. */ ``` ## snapshots.css ```css .snapshot-toolbar { display: flex; align-items: center; gap: 4px; margin: 8px; padding: 4px; pointer-events: all; } .snapshot-saved { padding: 0 8px; font-size: 12px; transition: transform 0.2s ease, opacity 0.2s ease; transform: scale(0.5); opacity: 0; } .snapshot-saved[data-visible='true'] { transform: scale(1); opacity: 1; } ``` -------- # Coordinate system transformations Category: Editor API Keywords: coordinates, screenToPage, pageToScreen, pageToViewport, getViewportScreenBounds, getViewportPageBounds, viewport, transformation, screen space, page space, dom positioning, overlay, camera Convert between screen, page, and viewport coordinates and position DOM elements over shapes. The editor uses three coordinate systems: - **Screen space**: browser pixels, as reported by DOM events - **Viewport space**: pixels relative to the editor container, used to position DOM elements over the canvas - **Page space**: the infinite canvas that shapes live in `editor.screenToPage(point)`, `editor.pageToScreen(point)`, and `editor.pageToViewport(point)` convert between them, and `editor.getViewportScreenBounds()` and `editor.getViewportPageBounds()` describe the visible area in screen and page space. Move the mouse to see the pointer position in all three systems, then pan and zoom to see how screen coordinates stay put while page coordinates change. Draw and select a shape to see a DOM label positioned above it with `pageToViewport`. ## App.tsx ```tsx import { Tldraw, TLEditorComponents, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' import './coordinate-system.css' // There's a guide at the bottom of this file! // [1] function CoordinateDebugPanel() { const editor = useEditor() // [2] const mouse = useValue( 'mouse', () => { const page = editor.inputs.getCurrentPagePoint() return { page, screen: editor.pageToScreen(page), viewport: editor.pageToViewport(page), } }, [editor] ) // [3] const viewportScreenBounds = useValue('screen bounds', () => editor.getViewportScreenBounds(), [ editor, ]) const viewportPageBounds = useValue('page bounds', () => editor.getViewportPageBounds(), [editor]) return (

Coordinate systems

Mouse position

Screen: ({mouse.screen.x.toFixed(0)}, {mouse.screen.y.toFixed(0)})
Page: ({mouse.page.x.toFixed(0)}, {mouse.page.y.toFixed(0)})
Viewport: ({mouse.viewport.x.toFixed(0)}, {mouse.viewport.y.toFixed(0)})

Viewport bounds

Screen: ({viewportScreenBounds.x.toFixed(0)}, {viewportScreenBounds.y.toFixed(0)},{' '} {viewportScreenBounds.w.toFixed(0)}×{viewportScreenBounds.h.toFixed(0)})
Page: ({viewportPageBounds.x.toFixed(0)}, {viewportPageBounds.y.toFixed(0)},{' '} {viewportPageBounds.w.toFixed(0)}×{viewportPageBounds.h.toFixed(0)})
) } // [4] function SelectedShapeOverlay() { const editor = useEditor() const overlay = useValue( 'selected shape overlay', () => { const selectedShapeId = editor.getOnlySelectedShapeId() if (!selectedShapeId) return null const pageBounds = editor.getShapePageBounds(selectedShapeId) if (!pageBounds) return null // [5] const topLeft = editor.pageToViewport(pageBounds.point) return { pageBounds, topLeft } }, [editor] ) if (!overlay) return null return (
Page: ({overlay.pageBounds.x.toFixed(0)}, {overlay.pageBounds.y.toFixed(0)})
) } // [6] const components: TLEditorComponents = { InFrontOfTheCanvas: () => ( <> ), } export default function CoordinateSystemExample() { return (
) } /* The editor works with three coordinate systems: - Screen space: browser pixels, as reported by DOM events (`clientX`, `clientY`). - Viewport space: pixels relative to the top-left of the editor's container. This is what you use to position DOM elements inside the editor. - Page space: the infinite canvas that shapes live in. Panning and zooming change how page space maps to the other two. `screenToPage`, `pageToScreen`, and `pageToViewport` convert between them. [1] A panel that prints the pointer position in each system, plus the viewport bounds. It's rendered in the `InFrontOfTheCanvas` slot so it sits over the canvas but doesn't move with it. [2] `editor.inputs.getCurrentPagePoint()` is a reactive signal that updates on every pointer move, so reading it inside `useValue` keeps the readout live. We convert it back to the other two spaces with `pageToScreen` and `pageToViewport`. Going the other way, `screenToPage` turns a DOM event's `clientX`/`clientY` into a page point. [3] `getViewportScreenBounds()` is the editor container's rectangle in screen space, so it only changes when the container moves or resizes. `getViewportPageBounds()` is the region of the page currently visible, so it changes whenever you pan or zoom. [4] A label positioned above the selected shape. `getOnlySelectedShapeId()` returns null unless exactly one shape is selected. [5] Elements inside `InFrontOfTheCanvas` are positioned relative to the editor container, so we use `pageToViewport`, not `pageToScreen`. `pageToScreen` includes the container's offset from the browser origin, which would push the label off target whenever the editor isn't at (0, 0), for example next to a sidebar. [6] Define `components` outside the React component so the slot component identity is stable across renders. */ ``` ## coordinate-system.css ```css .coordinate-debug-panel { position: absolute; top: 64px; left: 16px; width: 280px; background: white; border: 1px solid #ccc; padding: 12px; font-family: system-ui, sans-serif; font-size: 12px; z-index: 10000; user-select: none; } .coordinate-debug-panel h3 { margin: 0 0 8px 0; font-size: 13px; font-weight: 600; } .coordinate-debug-panel h4 { margin: 8px 0 4px 0; font-size: 11px; font-weight: 600; color: #666; } .coordinate-section { margin-bottom: 8px; } .coordinate-row { display: flex; justify-content: space-between; padding: 2px 0; } .coordinate-label { color: #666; } .coordinate-value { font-family: monospace; font-size: 11px; } .shape-overlay { position: absolute; pointer-events: none; z-index: 10000; background: #333; color: white; padding: 4px 8px; font-size: 11px; font-family: monospace; white-space: nowrap; } ``` -------- # Create an arrow Category: Editor API Keywords: arrow, createShape, createBindings, binding, connection, normalizedAnchor, isPrecise, isExact, terminal, programmatic creation Create an arrow bound to two shapes with `createShape` and `createBindings`. Arrows attach to shapes through arrow bindings, one per terminal. This example creates two geo shapes, then creates an arrow shape and two `arrow` binding records connecting its `start` and `end` terminals to them. The `normalizedAnchor`, `isPrecise`, and `isExact` binding props control where on each shape the arrow attaches. Try dragging either shape: the arrow stays connected because the bindings, not the arrow's own props, define where its terminals go. ## App.tsx ```tsx import { createShapeId, Editor, TLArrowBinding, Tldraw, TLShapeId, Vec, VecLike } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! export default function CreateArrowExample() { return (
{ if (editor.getCurrentPageShapeIds().size > 0) return const shapeAId = createShapeId() const shapeBId = createShapeId() editor.createShapes([ { id: shapeAId, type: 'geo', x: 100, y: 100 }, { id: shapeBId, type: 'geo', x: 400, y: 400 }, ]) createArrowBetweenShapes(editor, shapeAId, shapeBId) }} />
) } type TerminalOptions = Partial> function createArrowBetweenShapes( editor: Editor, startShapeId: TLShapeId, endShapeId: TLShapeId, options: { start?: TerminalOptions; end?: TerminalOptions } = {} ) { // [1] const { normalizedAnchor: startNormalizedAnchor = { x: 0.5, y: 0.5 }, isExact: startIsExact = false, isPrecise: startIsPrecise = false, } = options.start ?? {} const { normalizedAnchor: endNormalizedAnchor = { x: 0.5, y: 0.5 }, isExact: endIsExact = false, isPrecise: endIsPrecise = false, } = options.end ?? {} // [2] const startTerminalPagePosition = getAnchorInPageSpace( editor, startShapeId, startNormalizedAnchor ) const endTerminalPagePosition = getAnchorInPageSpace(editor, endShapeId, endNormalizedAnchor) // [3] const arrowPagePoint = Vec.Min(startTerminalPagePosition, endTerminalPagePosition) const arrowId = createShapeId() editor.run(() => { editor.markHistoryStoppingPoint('creating_arrow') editor.createShape({ id: arrowId, type: 'arrow', x: arrowPagePoint.x, y: arrowPagePoint.y, props: { // [4] start: Vec.Sub(startTerminalPagePosition, arrowPagePoint).toJson(), end: Vec.Sub(endTerminalPagePosition, arrowPagePoint).toJson(), }, }) // [5] editor.createBindings([ { fromId: arrowId, toId: startShapeId, type: 'arrow', props: { terminal: 'start', normalizedAnchor: startNormalizedAnchor, isExact: startIsExact, isPrecise: startIsPrecise, }, }, { fromId: arrowId, toId: endShapeId, type: 'arrow', props: { terminal: 'end', normalizedAnchor: endNormalizedAnchor, isExact: endIsExact, isPrecise: endIsPrecise, }, }, ]) }) } function getAnchorInPageSpace(editor: Editor, shapeId: TLShapeId, normalizedAnchor: VecLike) { const { point, size } = editor.getShapeGeometry(shapeId).bounds const localPoint = Vec.Add(point, Vec.MulV(normalizedAnchor, size)) return editor.getShapePageTransform(shapeId).applyToPoint(localPoint) } /* An arrow connects to other shapes through arrow bindings: one binding record per terminal (`start` and `end`) that points from the arrow to the shape it's attached to. Once the bindings exist, the editor keeps the arrow's terminals attached as either shape moves. [1] Of the binding props, `normalizedAnchor` is the point inside the bound shape that the terminal targets, in the shape's own bounds: (0, 0) is the top left, (1, 1) the bottom right. It's only used when `isPrecise` is true; otherwise the arrow aims at the shape's center. By default the arrow stops at the outside of the shape's geometry; set `isExact` to true to make it end exactly on the anchor point instead. [2] To place the arrow sensibly we compute where each anchor is on the page. The anchor is defined in the shape's local bounds, so we take the geometry bounds, scale the normalized anchor by their size, and push the result through the shape's page transform so rotation and parent groups are handled. [3] The arrow shape's `x`/`y` are in its parent's space, which here is the page. We put the arrow's origin at the top-left corner of the box spanning both terminals. [4] An arrow's `start` and `end` props are relative to the arrow's own position. When a terminal is bound, the editor recomputes it from the binding, so these values mostly matter for the unbound case, but setting them keeps the arrow's transform sensible. [5] Create the shape and the bindings inside one `editor.run` so they land in a single history entry. Bindings are created with `createBindings`, not by setting props on the arrow. */ ``` -------- # Custom clipping shape Category: Editor API Keywords: clipping, clip path, mask, getClipPath, shouldClipChild, polygon, children, parent-child, circular Clip child shapes to a circle with `getClipPath` and `shouldClipChild`. Any `ShapeUtil` can clip its children by implementing `getClipPath`, which returns a polygon in the shape's local coordinates. The editor transforms it to page space, intersects it with any ancestor clip paths, and applies it to every child. Implement `shouldClipChild` to leave some children unclipped (frames use this to skip arrows). The example defines a circle shape that clips its children to a polygon approximation of the circle. Try dragging shapes into and out of the circle, resizing it, or clicking with the "Circle clip" tool (shortcut `c`) to place new circles. The "Disable clipping" button flips a shared atom that `shouldClipChild` reads, turning clipping off for every circle at once. ## App.tsx ```tsx import { createShapeId, DefaultToolbar, DefaultToolbarContent, TLComponents, Tldraw, TldrawUiButton, TldrawUiMenuItem, TLGeoShapeProps, TLTextShapeProps, TLUiOverrides, toRichText, useEditor, useIsToolSelected, useTools, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import { CircleClipShapeTool } from './CircleClipShapeTool' import { CircleClipShapeUtil, isClippingEnabled$ } from './CircleClipShapeUtil' import './CustomClipping.css' // There's a guide at the bottom of this file! // [1] const shapeUtils = [CircleClipShapeUtil] const tools = [CircleClipShapeTool] // [2] const customUiOverrides: TLUiOverrides = { tools(editor, tools) { tools['circle-clip'] = { id: 'circle-clip', label: 'Circle clip', icon: 'color', kbd: 'c', onSelect() { editor.setCurrentTool('circle-clip') }, } return tools }, } // [3] function ToggleClippingButton() { const editor = useEditor() const clippingEnabled = useValue(isClippingEnabled$) return (
isClippingEnabled$.update((prev) => !prev)} onPointerDown={editor.markEventAsHandled} onPointerUp={editor.markEventAsHandled} > {clippingEnabled ? '✂️ Disable clipping' : '○ Enable clipping'}
) } // [4] function CustomToolbar() { const tools = useTools() const isCircleClipSelected = useIsToolSelected(tools['circle-clip']) return ( ) } // [5] const components: TLComponents = { Toolbar: CustomToolbar, InFrontOfTheCanvas: ToggleClippingButton, } // [6] export default function CustomClippingExample() { return (
{ editor.setCurrentTool('select') const clipShapeId = createShapeId() editor.createShape({ id: clipShapeId, type: 'circle-clip', x: 200, y: 200, props: { w: 300, h: 300, }, }) editor.createShape({ type: 'text', x: 0, y: 100, parentId: clipShapeId, props: { size: 'l', textAlign: 'middle', richText: toRichText('This text is clipped to the circle! ✂️'), } satisfies Partial, }) editor.createShape({ type: 'geo', x: 100, y: 290, parentId: clipShapeId, props: { geo: 'rectangle', w: 200, h: 100, fill: 'solid', color: 'blue', richText: toRichText('Oops you found me!'), } satisfies Partial, }) editor.zoomToFit() }} />
) } /* Any shape can clip its children by implementing `getClipPath` (the polygon, in local space) and optionally `shouldClipChild` (which children it applies to). See CircleClipShapeUtil.tsx for the shape itself; this file wires it into the editor and UI. [1] Define the shape util and tool arrays outside the component so they keep the same identity across renders. A new array on each render would make the editor think its shape utils changed. [2] Register the tool with the UI so it has a label, icon, and keyboard shortcut. This is what `useTools()` returns in the toolbar below. [3] The toggle flips a module-level atom that every circle's `shouldClipChild` reads, so one click changes clipping for all circles. `markEventAsHandled` on pointer down/up stops the canvas from treating the click as the start of a selection. [4] Add the tool to the default toolbar. `useIsToolSelected` highlights it while it's active. [5] Override the toolbar and add the toggle button in the `InFrontOfTheCanvas` slot. [6] On mount, create a circle with a text shape and a rectangle as children. Both are partly outside the circle so the clipping is visible right away. */ ``` ## CircleClipShapeTool.tsx ```tsx import { StateNode, TLPointerEventInfo } from 'tldraw' export class CircleClipShapeTool extends StateNode { static override id = 'circle-clip' override onEnter() { this.editor.setCursor({ type: 'cross', rotation: 0 }) } override onPointerDown(info: TLPointerEventInfo) { if (info.target !== 'canvas') return const { x, y } = this.editor.inputs.getCurrentPagePoint() this.editor.createShape({ type: 'circle-clip', x: x - 100, y: y - 100, props: { w: 200, h: 200 }, }) } } ``` ## CircleClipShapeUtil.tsx ```tsx import { BaseBoxShapeUtil, Circle2d, Geometry2d, PI2, RecordProps, SVGContainer, T, TLResizeInfo, TLShape, Vec, atom, clamp, resizeBox, toDomPrecision, } from 'tldraw' const CIRCLE_CLIP_TYPE = 'circle-clip' declare module 'tldraw' { export interface TLGlobalShapePropsMap { [CIRCLE_CLIP_TYPE]: { w: number h: number } } } export type CircleClipShape = TLShape export const isClippingEnabled$ = atom('isClippingEnabled', true) const STROKE_WIDTH = 3 // There's a guide at the bottom of this file! export class CircleClipShapeUtil extends BaseBoxShapeUtil { static override type = CIRCLE_CLIP_TYPE static override props: RecordProps = { w: T.number, h: T.number, } override canBind() { return false } // [1] override canReceiveNewChildrenOfType(shape: CircleClipShape) { return !shape.isLocked } override providesBackgroundForChildren(): boolean { return true } override getDefaultProps(): CircleClipShape['props'] { return { w: 200, h: 200, } } override getGeometry(shape: CircleClipShape): Geometry2d { const radius = Math.min(shape.props.w, shape.props.h) / 2 return new Circle2d({ radius, x: shape.props.w / 2 - radius, y: shape.props.h / 2 - radius, isFilled: true, }) } // [2] override getClipPath(shape: CircleClipShape): Vec[] | undefined { const centerX = shape.props.w / 2 const centerY = shape.props.h / 2 const outerRadius = Math.min(shape.props.w, shape.props.h) / 2 // Inset by half the stroke so children clip to the stroke's inner edge, not its center line. const clipRadius = outerRadius - STROKE_WIDTH / 2 // Roughly one vertex every 8px of circumference. const segments = clamp(Math.round((PI2 * clipRadius) / 8), 3, 360) const points: Vec[] = [] for (let i = 0; i < segments; i++) { const angle = (i / segments) * Math.PI * 2 const x = centerX + Math.cos(angle) * clipRadius const y = centerY + Math.sin(angle) * clipRadius points.push(new Vec(x, y)) } return points } // [3] override shouldClipChild(_child: TLShape): boolean { return isClippingEnabled$.get() } // [4] override component(shape: CircleClipShape) { const radius = Math.min(shape.props.w, shape.props.h) / 2 const centerX = shape.props.w / 2 const centerY = shape.props.h / 2 const clippingEnabled = isClippingEnabled$.get() return ( {clippingEnabled ? '✂️' : '○'} ) } override getIndicatorPath(shape: CircleClipShape) { const radius = Math.min(shape.props.w, shape.props.h) / 2 const centerX = shape.props.w / 2 const centerY = shape.props.h / 2 const path = new Path2D() path.arc(centerX, centerY, radius, 0, Math.PI * 2) return path } override onResize(shape: CircleClipShape, info: TLResizeInfo) { return resizeBox(shape, info) } } /* [1] Allow shapes to be dropped into the circle. Dragging a shape over the circle reparents it, at which point the clip path applies. `providesBackgroundForChildren` makes children's backgrounds render above this shape rather than behind it. [2] `getClipPath` returns a polygon in the shape's local space. The editor transforms it to page space and intersects it with any ancestor clip paths, so a circle needs to be approximated with enough vertices to look smooth at the sizes it's used at. [3] `shouldClipChild` is only called when `getClipPath` returns a polygon, and lets you exclude some children (for example arrows, which frames don't clip). Here it reads a module-level atom so a single toggle turns clipping on and off for every circle at once. [4] `component` reads the same atom. Shape components are rendered inside a reactive tracking scope, so the circle restyles itself when the atom changes without any explicit subscription. */ ``` ## CustomClipping.css ```css .CustomClipping-toggle { position: absolute; top: 64px; left: 12px; pointer-events: all; z-index: 1000; } ``` -------- # Zoom to bounds Category: Editor API Keywords: zoom, zoomToBounds, camera, bounds, Box, inset, animation, viewport, programmatic zoom Move the camera to fit a page-space box in the viewport with `editor.zoomToBounds()`. `zoomToBounds(bounds, opts)` fits a `Box` (or any `{ x, y, w, h }`) into the viewport. Two boxes are drawn on the canvas, and the buttons zoom to each one or to `Box.Common` of both. The camera keeps the viewport's aspect ratio, so the visible area may be larger than the box you pass. `inset` adds screen-space padding around the box (defaults to `options.zoomToFitPadding`), and `animation` animates the move instead of jumping. ## App.tsx ```tsx import { Box, createShapeId, Editor, TLComponents, Tldraw, TldrawUiButton, useEditor } from 'tldraw' import 'tldraw/tldraw.css' import './zoom-to-bounds.css' // There's a guide at the bottom of this file! const zoomBox1 = new Box(50, 100, 900, 720) const zoomBox2 = new Box(1000, 500, 500, 400) function ZoomControls() { const editor = useEditor() return (
{/* [1] */} editor.zoomToBounds(zoomBox1, { inset: 72 })}> Zoom to violet box editor.zoomToBounds(zoomBox2, { inset: 72, animation: { duration: 200 } })} > Zoom to blue box editor.zoomToBounds(Box.Common([zoomBox1, zoomBox2]), { inset: 200, animation: { duration: 200 }, }) } > Zoom to both boxes
) } const components: TLComponents = { TopPanel: ZoomControls, } function handleMount(editor: Editor) { editor.createShapes([ { id: createShapeId(), type: 'geo', x: zoomBox1.x, y: zoomBox1.y, isLocked: true, props: { w: zoomBox1.w, h: zoomBox1.h, color: 'violet' }, }, { id: createShapeId(), type: 'geo', x: zoomBox2.x, y: zoomBox2.y, isLocked: true, props: { w: zoomBox2.w, h: zoomBox2.h, color: 'blue' }, }, ]) } export default function ZoomToBoundsExample() { return (
) } /* [1] `zoomToBounds` fits the given page-space box into the viewport. The camera keeps the viewport's aspect ratio, so the visible area is usually larger than the box you pass on one axis. `inset` is screen-space padding around the box; when omitted the editor uses `options.zoomToFitPadding` (capped relative to the viewport width). Pass `animation` to animate the move; without it the camera jumps. */ ``` ## zoom-to-bounds.css ```css .control-panel { display: flex; flex-direction: row; flex-wrap: wrap; margin: 8px; } ``` -------- # Arrow labels Category: Editor API Keywords: arrow, label, richText, toRichText, labelPosition, labelColor, font, annotation, text, bend, curved Create arrows with text labels and control their position, color, and font. Arrow labels live in the arrow shape's `richText` prop; pass `toRichText('...')` when creating the shape. The example lays out a grid of arrows showing `labelPosition` (a fraction from 0 at the start to 1 at the end), `labelColor` (independent of the arrow's `color`), each `font` option, and a label on a curved arrow made with `bend`. Try selecting an arrow and dragging its label along the arrow, or double-click a label to edit the text. ## App.tsx ```tsx import { createShapeId, Tldraw, toRichText } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! export default function ArrowLabelsExample() { return (
{ if (editor.getCurrentPageShapeIds().size > 0) return // [1] editor.createShapes([ { id: createShapeId(), type: 'arrow', x: 100, y: 100, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Default label'), labelPosition: 0.5, }, }, // [2] { id: createShapeId(), type: 'arrow', x: 100, y: 200, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Start'), labelPosition: 0.2, color: 'blue', labelColor: 'red', }, }, { id: createShapeId(), type: 'arrow', x: 100, y: 300, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Middle'), labelPosition: 0.5, color: 'blue', labelColor: 'violet', }, }, { id: createShapeId(), type: 'arrow', x: 100, y: 400, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('End'), labelPosition: 0.8, color: 'blue', labelColor: 'green', }, }, // [3] { id: createShapeId(), type: 'arrow', x: 550, y: 100, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Draw font'), font: 'draw', }, }, { id: createShapeId(), type: 'arrow', x: 550, y: 200, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Sans font'), font: 'sans', }, }, { id: createShapeId(), type: 'arrow', x: 550, y: 300, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Serif font'), font: 'serif', }, }, { id: createShapeId(), type: 'arrow', x: 550, y: 400, props: { start: { x: 0, y: 0 }, end: { x: 300, y: 0 }, richText: toRichText('Mono font'), font: 'mono', }, }, // [4] { id: createShapeId(), type: 'arrow', x: 300, y: 475, props: { start: { x: 0, y: 0 }, end: { x: 400, y: 150 }, bend: 50, richText: toRichText('Curved arrow'), labelPosition: 0.5, font: 'sans', color: 'violet', size: 'm', }, }, ]) editor.zoomToFit({ animation: { duration: 0 } }) }} />
) } /* Arrow labels are stored in the arrow's `richText` prop. Use the `toRichText()` helper to turn a plain string into that format. [1] The simplest labeled arrow. `labelPosition` is a fraction along the arrow from 0 (start) to 1 (end); 0.5 is the default and centers the label. [2] `labelColor` sets the text color independently of the arrow's `color`, which is useful for contrast when the arrow itself is a light color. [3] `font` picks the label typeface: 'draw' (hand-drawn), 'sans', 'serif', or 'mono'. The `size` prop, shared with the stroke width, controls the label's font size. [4] `bend` curves the arrow, and the label is positioned along the curve rather than the chord. */ ``` -------- # Create a video shape Category: Editor API Keywords: video, asset, assetrecordtype, createassets, local, static, mp4, videoshape Create a video shape from a locally hosted video by creating a video asset and a shape that references it. Video shapes reference a `TLVideoAsset` record that holds the source URL and natural dimensions. This example creates the asset with `editor.createAssets`, then creates a `video` shape whose `assetId` points at it. The same pattern is used for images in the local-images example. ## App.tsx ```tsx import { AssetRecordType, Editor, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' const videoWidth = 640 const videoHeight = 360 // Video shapes work like image shapes: the shape references an asset record that holds // the source URL and natural size, so create the asset first. See the local-images example. function handleMount(editor: Editor) { const assetId = AssetRecordType.createId() editor.createAssets([ { id: assetId, type: 'video', typeName: 'asset', props: { name: 'fluid.mp4', src: '/fluid.mp4', w: videoWidth, h: videoHeight, mimeType: 'video/mp4', isAnimated: true, }, meta: {}, }, ]) const { x, y } = editor.getViewportPageBounds().center editor.createShape({ type: 'video', x: x - videoWidth / 2, y: y - videoHeight / 2, props: { assetId, w: videoWidth, h: videoHeight, }, }) } export default function LocalVideosExample() { return (
) } ``` -------- # Create an image shape Category: Editor API Keywords: image, asset, assetrecordtype, createassets, local, static, png, jpg, imageshape Create an image shape from a locally hosted image by creating an asset record and a shape that references it. Image shapes don't store image data themselves. Each one references an asset record that holds the source URL and natural dimensions. This example creates the asset with `editor.createAssets` using `AssetRecordType.createId()` for its id, then creates an image shape with `editor.createShape` whose `assetId` points at it. The image is served from the app's `public` folder. To let users upload their own images, see the hosted-images example. ## App.tsx ```tsx import { AssetRecordType, Editor, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const imageWidth = 1200 const imageHeight = 675 function handleMount(editor: Editor) { // [1] const assetId = AssetRecordType.createId() editor.createAssets([ { id: assetId, type: 'image', typeName: 'asset', props: { name: 'tldraw.png', src: '/tldraw.png', // You could also use a data URL here w: imageWidth, h: imageHeight, mimeType: 'image/png', isAnimated: false, }, meta: {}, }, ]) // [2] const { x, y } = editor.getViewportPageBounds().center editor.createShape({ type: 'image', x: x - imageWidth / 2, y: y - imageHeight / 2, props: { assetId, w: imageWidth, h: imageHeight, }, }) } export default function LocalImagesExample() { return (
) } /* An image shape doesn't hold its own pixels. It points at an asset record via `assetId`, and the asset holds the source URL and the image's natural size. So to show an image you create the asset first [1] and then the shape [2]. Here the image is served from this app's `public` folder. Your framework may serve static files differently, or you might use a data URL. To let users upload their own images, see the hosted-images example. [1] Create the asset record. `AssetRecordType.createId()` gives us an id we can reference from the shape. [2] Create the image shape, linked to the asset by `assetId`, and center it in the current viewport. The shape starts at the image's natural size, but the user can resize it later without touching the asset. That separation is one reason assets and shapes are different records: many shapes can share one asset. */ ``` -------- # Custom overlay Category: Editor API Keywords: overlay, overlayutil, canvas, render, 2d, cursor Draw a pointer-following ring on the canvas overlay layer with a custom `OverlayUtil`. Overlays are the canvas-drawn UI above shapes: selection handles, the brush rectangle, snap indicators, collaborator brushes and scribbles. They render into a Canvas 2D context in page space rather than the React tree, which keeps them cheap during fast interactions. To add one, subclass `OverlayUtil` and implement `isActive()`, `getOverlays()`, and `render()`, then pass it to `` alongside `defaultOverlayUtils`. This example adds a pink ring that follows the pointer. Move the mouse and zoom in and out: the ring stays the same size on screen because `render()` scales by the zoom level. ## App.tsx ```tsx import { Tldraw, defaultOverlayUtils } from 'tldraw' import 'tldraw/tldraw.css' import { PointerRingOverlayUtil } from './PointerRingOverlayUtil' // There's a guide at the bottom of this file! // [1] const overlayUtils = [...defaultOverlayUtils, PointerRingOverlayUtil] export default function CustomOverlayExample() { return (
{/* [2] */}
) } /* Overlays are ephemeral UI drawn on top of the canvas — selection handles, the brush rectangle, snap indicators, and so on. They render into a Canvas 2D context, not the React tree, so they're cheap even during fast interactions. To add your own, subclass `OverlayUtil` and implement three methods: - `isActive()` — whether the overlay should render right now. Checked reactively. - `getOverlays()` — one or more overlay instances derived from editor state. - `render(ctx, overlays)` — draw into a page-space canvas context. See `PointerRingOverlayUtil.ts` for a minimal implementation that draws a ring following the cursor. `getOverlays()` reads the reactive `editor.inputs.getCurrentPagePoint()`, so the ring redraws automatically as the pointer moves. Because the context is in page space, `render()` divides the ring's radius and line width by the zoom level to keep them a constant size on screen. [1] Register your overlay util alongside `defaultOverlayUtils` so the built-in overlays (selection, brush, scribble, snap, handles, collaborator brushes and scribbles) stay intact. Passing an array without them removes those overlays. `options.zIndex` controls paint order; higher paints on top. [2] Pass the array to the `overlayUtils` prop on ``. Each util is constructed once when the editor mounts, so define the array at module level. */ ``` ## PointerRingOverlayUtil.ts ```ts import { OverlayUtil, TLOverlay } from 'tldraw' interface TLPointerRingOverlay extends TLOverlay { props: { x: number y: number } } export class PointerRingOverlayUtil extends OverlayUtil { static override type = 'pointer-ring' override options = { zIndex: 50 } override isActive(): boolean { return true } override getOverlays(): TLPointerRingOverlay[] { const { x, y } = this.editor.inputs.getCurrentPagePoint() return [{ id: 'pointer-ring', type: 'pointer-ring', props: { x, y } }] } override render(ctx: CanvasRenderingContext2D, overlays: TLPointerRingOverlay[]): void { const overlay = overlays[0] if (!overlay) return const { x, y } = overlay.props const zoom = this.editor.getZoomLevel() const radius = 24 / zoom ctx.lineWidth = 2 / zoom ctx.strokeStyle = 'hotpink' ctx.beginPath() ctx.arc(x, y, radius, 0, Math.PI * 2) ctx.stroke() } } ``` -------- # Dynamic tools with setTool and removeTool Category: Editor API Keywords: settool, removetool, dynamic tools, runtime, conditional, permissions, feature flags, toolbar Add and remove a tool from the editor and toolbar at runtime with `setTool` and `removeTool`. Tools are normally passed to `` once via the `tools` prop. `editor.setTool(Tool)` and `editor.removeTool(Tool)` let you add and remove tools from the state chart after the editor has mounted, which is useful for permission checks, feature flags, or plugin-style features. The example adds a heart-stamp tool that isn't installed initially. Click "Add heart tool" to install it (it appears in the toolbar and can be selected with `y`), stamp a few hearts, then click "Remove heart tool" to take it away again. Notice that the toolbar entry is driven by a small atom rather than React state, so the `components` object stays stable. ## App.tsx ```tsx import { atom, DefaultToolbar, DefaultToolbarContent, StateNode, TLComponents, TLTextShape, TLUiAssetUrlOverrides, TLUiOverrides, Tldraw, TldrawUiButton, TldrawUiMenuItem, toRichText, useEditor, useIsToolSelected, useTools, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './dynamic-tools.css' // There's a guide at the bottom of this file! const OFFSET = 12 // [1] class HeartTool extends StateNode { static override id = 'heart' override onEnter() { this.editor.setCursor({ type: 'cross', rotation: 0 }) } override onPointerDown() { const currentPagePoint = this.editor.inputs.getCurrentPagePoint() this.editor.createShape({ type: 'text', x: currentPagePoint.x - OFFSET, y: currentPagePoint.y - OFFSET, props: { richText: toRichText('❤️') }, }) } } // [2] const isHeartToolEnabled$ = atom('isHeartToolEnabled', false) // [3] const uiOverrides: TLUiOverrides = { tools(editor, tools) { tools.heart = { id: 'heart', icon: 'heart-icon', label: 'Heart', kbd: 'y', onSelect: () => { // [4] if (!isHeartToolEnabled$.get()) return editor.setCurrentTool('heart') }, } return tools }, } const customAssetUrls: TLUiAssetUrlOverrides = { icons: { 'heart-icon': '/heart-icon.svg', }, } // [5] const components: TLComponents = { Toolbar: (props) => { const tools = useTools() const isHeartSelected = useIsToolSelected(tools['heart']) const isHeartToolEnabled = useValue(isHeartToolEnabled$) return ( {isHeartToolEnabled && ( )} ) }, InFrontOfTheCanvas: () => { const editor = useEditor() const isHeartToolEnabled = useValue(isHeartToolEnabled$) const toggleHeartTool = () => { if (isHeartToolEnabled) { // [6] if (editor.getCurrentToolId() === 'heart') { editor.setCurrentTool('select') } editor.removeTool(HeartTool) } else { // [7] editor.setTool(HeartTool) } isHeartToolEnabled$.set(!isHeartToolEnabled) } return (
{isHeartToolEnabled ? '💔 Remove heart tool' : '💖 Add heart tool'}
) }, } export default function DynamicToolsExample() { return (
{ isHeartToolEnabled$.set(false) }} />
) } /* `editor.setTool` and `editor.removeTool` add and remove tools from the editor's state chart after it has been created. Use them when a tool's availability depends on runtime conditions such as permissions or feature flags. [1] A minimal tool that stamps a heart at the pointer. It is deliberately not passed to `` via the `tools` prop; it is added later with `setTool`. [2] Whether the tool is currently installed. Keeping this in an atom lets the toolbar and the toggle button share it without lifting state into the example component, which would force the `components` object to be recreated on every change. [3] Register the tool with the UI so the toolbar knows its label, icon, and shortcut. This entry can exist even while the tool is absent from the state chart; the toolbar below decides whether to show it. The shortcut is `y` because `r` already belongs to the rectangle tool. [4] Keyboard shortcuts are registered from the `tools` override whether or not the toolbar shows the item, so pressing `y` while the tool is uninstalled would call `setCurrentTool` on a state that doesn't exist and throw. Guard on the atom instead. [5] The toolbar reads the atom with `useValue` and only renders the heart item while the tool exists. The toggle button lives in `InFrontOfTheCanvas` and gets the editor from `useEditor`. [6] Removing a tool does not exit it if it's active, so switch to select first. `removeTool` is a no-op if the tool isn't in the state chart. [7] `setTool` constructs the tool and attaches it to the root state. It throws if a tool with the same id already exists, so don't call it twice without removing first. [8] A fresh editor starts without the tool, so reset the flag in case the example remounts. */ ``` ## dynamic-tools.css ```css .toggle-button-container { position: absolute; top: 16px; left: 50%; transform: translateX(-50%); display: flex; flex-direction: column; align-items: center; gap: 8px; pointer-events: auto; } ``` -------- # Focus the editor Category: Editor API Keywords: focus, blur, autofocus, keyboard shortcuts, multiple editors, scrolling, instance state Control the editor's focus with `focus()`, `blur()`, and `autoFocus` to gate keyboard shortcuts and scroll capture. The editor's focus decides whether its keyboard shortcuts respond and whether wheel events pan the canvas. It is related to, but not the same as, the browser's notion of focus (the document's [active element](https://developer.mozilla.org/en-US/docs/Web/API/Document/activeElement)). The browser's focus can't be relied on for this: iframes aren't descendants of their parents, and many menus are portalled elsewhere in the document, so checking whether the active element is inside the `Tldraw` element isn't reliable. That leaves focus management to you, especially with more than one editor on a page. This example mounts the editor with `autoFocus={false}` and drives focus with `editor.focus()` and `editor.blur()` from a checkbox that stays in sync via `editor.getIsFocused()`. Try typing in the text input while the editor is focused (shortcuts shouldn't fire), and toggle the checkbox to see scrolling switch between the page and the canvas. ## App.tsx ```tsx import { useState } from 'react' import { Editor, Tldraw, useValue } from 'tldraw' import 'tldraw/tldraw.css' import './editor-focus.css' // There's a guide at the bottom of this file! export default function EditorFocusExample() { const [editor, setEditor] = useState(null) // [1] const isFocused = useValue('isFocused', () => editor?.getIsFocused() ?? false, [editor]) return (

You should be able to type in this text input without triggering editor shortcuts, even when the editor is focused.

Controlled focus

{ // [2] if (e.target.checked) { editor?.focus() } else { editor?.blur() } }} />

The checkbox focuses and blurs the editor. Clicking on the canvas also focuses it, which is why the checkbox follows the editor's own focus state.

When the editor is focused, its keyboard shortcuts work and scrolling over it moves the canvas. When it is not, shortcuts are ignored and the page scrolls instead.

{/* [3] */}
) } /* [1] `editor.getIsFocused()` is reactive, so reading it through `useValue` keeps the checkbox in sync whether focus changed through the checkbox or by clicking the canvas. [2] `editor.focus()` and `editor.blur()` set the editor's focus state and, by default, also focus or blur the container element. Pass `{ focusContainer: false }` / `{ blurContainer: false }` to change only the editor's state. [3] `autoFocus={false}` stops the editor from grabbing focus when it mounts, which matters when the canvas is one of several things on a page (or one of several editors). */ ``` ## editor-focus.css ```css .editor-focus-example { padding: 32px; min-height: 120vh; } .editor-focus-example__controls { display: flex; gap: 4px; } .editor-focus-example__editor { width: 800px; max-width: 100%; height: 500px; } /* The editor adds this class to its container while it has focus. */ .tl-container__focused { outline: 1px solid var(--tl-color-primary); } ``` -------- # Lock camera zoom Category: Editor API Keywords: camera, zoom, lock, setcameraoptions, zoomsteps, getzoomlevel, getcameraoptions, viewport, fixed zoom Lock the camera at its current zoom level by collapsing `zoomSteps` to a single value. The camera's `zoomSteps` option defines the zoom levels the camera can move between; the smallest and largest steps also bound the zoom range. Setting `zoomSteps` to a single value equal to the current zoom (`editor.setCameraOptions({ zoomSteps: [editor.getZoomLevel()] })`) means every zoom gesture, shortcut, and menu action has nowhere to go, so the zoom stays fixed while panning still works. Restoring `DEFAULT_CAMERA_OPTIONS.zoomSteps` unlocks it. Press Shift+K to lock the camera at its current zoom, then try scrolling, pinching, or using the zoom menu. Press Shift+K again to unlock. ## App.tsx ```tsx import { DEFAULT_CAMERA_OPTIONS, Tldraw, TLUiOverrides } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const overrides: TLUiOverrides = { actions(editor, actions) { actions.lockCameraZoom = { id: 'lock-camera-zoom', kbd: 'shift+k', onSelect() { // [1] const isLocked = editor.getCameraOptions().zoomSteps.length === 1 editor.setCameraOptions({ zoomSteps: isLocked ? DEFAULT_CAMERA_OPTIONS.zoomSteps : [editor.getZoomLevel()], }) }, } return actions }, } export default function LockCameraZoomExample() { return (
) } /* [1] The camera can only zoom to values in `zoomSteps` (or between the smallest and largest of them). With a single step equal to the current zoom, every zoom gesture, shortcut, and menu action is a no-op, so the zoom is effectively locked. Restoring the default steps unlocks it. We use `zoomSteps.length === 1` as the "is locked" flag so the same shortcut toggles both ways. */ ``` -------- # Search text on the canvas Category: Editor API Keywords: search, text search, find text, keyboard shortcut, helpers, helperButtons, filter shapes, overrides, actions, gettext Search the text of every shape on the current page and zoom to a result. Each shape util exposes its text through `getText(shape)`, so the search filters `editor.getCurrentPageShapes()` by that value. Results are listed in the `HelperButtons` UI slot, and clicking one selects the shape and calls `zoomToSelection` to animate the camera to it. A UI action override binds Cmd+F / Ctrl+F to open the panel. Add some text or shapes with labels, press Cmd+F or Ctrl+F, and start typing. Press Escape to close. ## App.tsx ```tsx import { TLComponents, TLUiOverrides, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' import { showSearch, TextSearchPanel } from './TextSearchPanel' import './text-search.css' // There's a guide at the bottom of this file! // [1] const components: TLComponents = { HelperButtons: TextSearchPanel, } // [2] const overrides: TLUiOverrides = { actions(_editor, actions) { return { ...actions, 'text-search': { id: 'text-search', label: 'Search', kbd: 'cmd+f,ctrl+f', onSelect() { showSearch.set(true) }, }, } }, } export default function TextSearchExample() { return (
) } /* [1] The search panel renders in the `HelperButtons` slot, which sits at the top left of the canvas under the menu panel. See TextSearchPanel.tsx for the search itself. [2] Registering an action with `kbd: 'cmd+f,ctrl+f'` takes over the browser's find shortcut while the editor is focused. The action just flips a shared `atom`; the panel reads that atom with `track` so it shows and hides reactively. */ ``` ## TextSearchPanel.tsx ```tsx import { useEffect, useRef, useState } from 'react' import { atom, EASINGS, Editor, TLShape, TldrawUiButton, track, useEditor } from 'tldraw' export const showSearch = atom('showSearch', false) interface SearchResult { text: string shape: TLShape } // [1] function getShapesWithText(editor: Editor, text: string): SearchResult[] { if (!text) return [] const query = text.toLowerCase() const results: SearchResult[] = [] for (const shape of editor.getCurrentPageShapes()) { const shapeText = editor.getShapeUtil(shape).getText(shape) if (shapeText?.toLowerCase().includes(query)) { results.push({ text: shapeText, shape }) } } return results.sort((a, b) => a.text.localeCompare(b.text)) } function moveToShape(editor: Editor, shape: TLShape) { editor.setSelectedShapes([shape.id]) editor.zoomToSelection({ animation: { duration: 500, easing: EASINGS.easeInOutCubic }, }) } function handleKeyDown(e: React.KeyboardEvent) { if (e.key === 'Escape') { showSearch.set(false) } } export const TextSearchPanel = track(() => { const editor = useEditor() const [searchText, setSearchText] = useState('') const inputRef = useRef(null) const isVisible = showSearch.get() useEffect(() => { if (isVisible) { setSearchText('') inputRef.current?.focus() } }, [isVisible]) if (!isVisible) return null // [2] const results = getShapesWithText(editor, searchText) return (
setSearchText(e.target.value)} /> {results.map((result) => ( moveToShape(editor, result.shape)} > {result.text} ))}
) }) /* [1] Every shape util can report its text through `getText(shape)`. It returns `undefined` for shapes with no text, so this works across geo, text, note, arrow, and any custom shape that implements it. [2] The component is wrapped in `track`, so calling `getShapesWithText` during render subscribes it to the page's shapes. Results update live as text on the canvas changes, not just when the query changes. */ ``` ## text-search.css ```css .text-search-panel { display: flex; flex-direction: column; gap: 4px; max-height: calc(100% - 110px); margin: 50px 0px; padding: 4px; background-color: var(--tl-color-low); pointer-events: all; border-top-right-radius: var(--tl-radius-4); border-bottom-right-radius: var(--tl-radius-4); overflow: auto; border-right: 2px solid var(--tl-color-background); border-bottom: 2px solid var(--tl-color-background); border-top: 2px solid var(--tl-color-background); } .text-search-panel-button { border-radius: var(--tl-radius-4); outline-offset: -1px; } .text-search-input { border-radius: var(--tl-radius-2); margin: 4px; } ``` -------- # Shape animation Category: Editor API Keywords: animate, animation, shape, easing, transition, movement, rotation, opacity Animate a shape's position, rotation, and opacity with `animateShape()` and `animateShapes()`. `editor.animateShape(partial, { animation })` interpolates a shape's `x`, `y`, `rotation`, and `opacity` from their current values to those in the partial over the given `duration`, using an easing function from `EASINGS` (or any `(t) => number`). `animateShapes()` does the same for many shapes at once. Shape props are also interpolated when the shape util implements `getInterpolatedProps`. Select one shape and try the position, rotation, fade, and combined buttons, or use "Animate multiple shapes" to scatter everything on the page. ## App.tsx ```tsx import { createShapeId, EASINGS, TLComponents, Tldraw, TldrawUiButton, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './shape-animation.css' // There's a guide at the bottom of this file! function AnimationControls() { const editor = useEditor() // [1] const animatePosition = () => { const shape = editor.getOnlySelectedShape() if (!shape) return editor.animateShape( { ...shape, x: shape.x + 200, y: shape.y + 100 }, { animation: { duration: 800, easing: EASINGS.easeInOutCubic } } ) } const animateRotation = () => { const shape = editor.getOnlySelectedShape() if (!shape) return editor.animateShape( { ...shape, rotation: shape.rotation + Math.PI * 2 }, { animation: { duration: 1000, easing: EASINGS.easeInOutCubic } } ) } const animateFade = () => { const shape = editor.getOnlySelectedShape() if (!shape) return editor.animateShape( { ...shape, opacity: shape.opacity > 0.5 ? 0.2 : 1 }, { animation: { duration: 600, easing: EASINGS.easeInOutQuad } } ) } const animateAll = () => { const shape = editor.getOnlySelectedShape() if (!shape) return editor.animateShape( { ...shape, x: shape.x + 150, y: shape.y - 100, rotation: shape.rotation + Math.PI, opacity: 0.3, }, { animation: { duration: 1200, easing: EASINGS.easeInOutCubic } } ) } // [2] const animateMultiple = () => { const updates = editor.getCurrentPageShapes().map((shape) => ({ ...shape, x: shape.x + (Math.random() - 0.5) * 200, y: shape.y + (Math.random() - 0.5) * 200, rotation: shape.rotation + (Math.random() - 0.5) * Math.PI, })) editor.animateShapes(updates, { animation: { duration: 1000, easing: EASINGS.easeOutCubic } }) } const hasOneSelected = useValue( 'has one selected', () => editor.getSelectedShapeIds().length === 1, [editor] ) return (
Animate position Animate rotation Fade in/out Animate all Animate multiple shapes
) } const components: TLComponents = { TopPanel: AnimationControls, } export default function ShapeAnimationExample() { return (
{ const id = createShapeId() editor.createShapes([ { id, type: 'geo', x: 200, y: 200, props: { w: 100, h: 100, color: 'blue', }, }, { id: createShapeId(), type: 'geo', x: 400, y: 300, props: { w: 80, h: 80, color: 'red', geo: 'ellipse', }, }, { id: createShapeId(), type: 'geo', x: 600, y: 200, props: { w: 120, h: 90, color: 'green', geo: 'triangle', }, }, ]) editor.select(id) }} />
) } /* [1] `animateShape()` takes a shape partial (here the whole shape spread with new values) plus animation options, and interpolates `x`, `y`, `rotation`, and `opacity` from the shape's current values to the targets over `duration`. `easing` accepts any function from `EASINGS`, or your own `(t) => number`. Props are interpolated too when the shape util implements `getInterpolatedProps`. [2] `animateShapes()` does the same for many partials at once, sharing one duration and easing. Starting a new animation on a shape that's already animating cancels the earlier one for that shape. */ ``` ## shape-animation.css ```css .animation-controls { display: flex; flex-wrap: wrap; margin: 8px; } ``` -------- # Z-order Category: Editor API Keywords: z-order, index, stacking, layers, reorder, sendToBack, bringToFront, sendBackward, bringForward Reorder shapes with `sendToBack`, `sendBackward`, `bringForward`, and `bringToFront`. This example shows how to use the four z-order methods to control shape stacking: - `editor.sendToBack(ids)` — move shapes to the very bottom - `editor.bringToFront(ids)` — move shapes to the very top - `editor.sendBackward(ids)` — move shapes one step down (by default, only past overlapping shapes) - `editor.bringForward(ids)` — move shapes one step up (by default, only past overlapping shapes) Select one or more shapes and use the buttons to see the stacking order change. When multiple shapes are selected, their relative order is preserved. For `sendBackward` and `bringForward`, pass `{ considerAllShapes: true }` to move past non-overlapping shapes too. ## App.tsx ```tsx import { createShapeId, Editor, TLComponents, Tldraw, TldrawUiButton, useEditor } from 'tldraw' import 'tldraw/tldraw.css' import './z-order.css' // There's a guide at the bottom of this file! const COLORS = ['red', 'blue', 'green', 'orange'] as const const SHAPE_SIZE = 150 const OVERLAP = 110 function ZOrderControls() { const editor = useEditor() return (
{/* [1] */} editor.sendToBack(editor.getSelectedShapeIds())}> Send to back editor.sendBackward(editor.getSelectedShapeIds())} > Send backward editor.bringForward(editor.getSelectedShapeIds())} > Bring forward editor.bringToFront(editor.getSelectedShapeIds())} > Bring to front
) } const components: TLComponents = { TopPanel: ZOrderControls, } function handleMount(editor: Editor) { if (editor.getCurrentPageShapeIds().size > 0) return editor.createShapes( COLORS.map((color, i) => ({ id: createShapeId(), type: 'geo' as const, x: 200 + i * (SHAPE_SIZE - OVERLAP), y: 200 + i * (SHAPE_SIZE - OVERLAP), props: { w: SHAPE_SIZE, h: SHAPE_SIZE, color, fill: 'solid' as const, }, })) ) editor.zoomToFit({ animation: { duration: 0 } }) } export default function ZOrderExample() { return (
) } /* [1] `sendToBack` and `bringToFront` move shapes to the very bottom or top of their parent. `sendBackward` and `bringForward` shift them one step, and by default only past shapes they overlap, which is what you want from a UI button: moving past a shape on the other side of the page would look like nothing happened. Pass `{ considerAllShapes: true }` to move exactly one position in the z-order regardless. When several shapes are selected, their relative order is preserved, so they move as a block. */ ``` ## z-order.css ```css .z-order-controls { display: flex; flex-direction: row; flex-wrap: wrap; margin: 8px; } ``` -------- # Align and distribute shapes Category: Editor API Keywords: align, distribute, alignshapes, distributeshapes, layout, position, arrange, horizontal, vertical Align and distribute selected shapes with `alignShapes` and `distributeShapes`. The editor exposes the same alignment and distribution operations that the built-in context menu uses. `editor.alignShapes(ids, operation)` accepts `left`, `center-horizontal`, `right`, `top`, `center-vertical`, `bottom`, or `center`, and `editor.distributeShapes(ids, operation)` accepts `horizontal` or `vertical`. The example creates five shapes and selects them. Try clicking the buttons in the top panel, then use "Reset positions" to put the shapes back. Align operations need at least two selected shapes, and distribute operations need at least three, so change the selection to see the buttons become no-ops. ## App.tsx ```tsx import { createShapeId, TLComponents, Tldraw, TldrawUiButton, useEditor } from 'tldraw' import 'tldraw/tldraw.css' import './align-and-distribute-shapes.css' // There's a guide at the bottom of this file! // [1] const ALIGN_OPERATIONS = [ { operation: 'left', label: 'Align left' }, { operation: 'center-horizontal', label: 'Align center H' }, { operation: 'right', label: 'Align right' }, { operation: 'top', label: 'Align top' }, { operation: 'center-vertical', label: 'Align center V' }, { operation: 'bottom', label: 'Align bottom' }, { operation: 'center', label: 'Align center' }, ] as const const DISTRIBUTE_OPERATIONS = [ { operation: 'horizontal', label: 'Distribute horizontal' }, { operation: 'vertical', label: 'Distribute vertical' }, ] as const // Original positions of the demo shapes, captured on mount so "Reset positions" can restore them. const originalPositions = new Map() function ControlPanel() { const editor = useEditor() return (
{ALIGN_OPERATIONS.map(({ operation, label }) => ( { // [2] const selectedIds = editor.getSelectedShapeIds() if (selectedIds.length > 1) { editor.alignShapes(selectedIds, operation) } }} > {label} ))} {DISTRIBUTE_OPERATIONS.map(({ operation, label }) => ( { // [3] const selectedIds = editor.getSelectedShapeIds() if (selectedIds.length > 2) { editor.distributeShapes(selectedIds, operation) } }} > {label} ))} { // [4] editor.updateShapes( editor.getCurrentPageShapes().flatMap((shape) => { const originalPos = originalPositions.get(shape.id) return originalPos ? [{ ...shape, ...originalPos }] : [] }) ) }} > Reset positions
) } // [5] const components: TLComponents = { TopPanel: ControlPanel, } export default function AlignAndDistributeShapesExample() { return (
{ const shapes = [ { id: createShapeId(), type: 'geo' as const, x: 100, y: 100, props: { w: 100, h: 100, color: 'blue' as const }, }, { id: createShapeId(), type: 'geo' as const, x: 300, y: 200, props: { w: 120, h: 80, color: 'red' as const }, }, { id: createShapeId(), type: 'geo' as const, x: 500, y: 150, props: { w: 80, h: 120, color: 'green' as const }, }, { id: createShapeId(), type: 'geo' as const, x: 150, y: 400, props: { w: 100, h: 100, color: 'violet' as const }, }, { id: createShapeId(), type: 'geo' as const, x: 400, y: 450, props: { w: 90, h: 90, color: 'orange' as const }, }, ] originalPositions.clear() for (const shape of shapes) { originalPositions.set(shape.id, { x: shape.x, y: shape.y }) } editor.createShapes(shapes) editor.selectAll() }} components={components} />
) } /* [1] The operation names accepted by `editor.alignShapes` and `editor.distributeShapes`. Listing them in a typed array lets us render one button per operation. [2] `alignShapes` moves the selected shapes so their edges (or centers) line up. It needs at least two shapes; with fewer there is nothing to align to. [3] `distributeShapes` keeps the outermost two shapes where they are and spaces the ones in between evenly, so it needs at least three shapes to do anything. [4] `updateShapes` applies all the position changes in one call, so a single undo restores every shape. [5] Define `components` at module level so the `TopPanel` component identity is stable across renders. Defining it inline would remount the panel every time the parent re-renders. */ ``` ## align-and-distribute-shapes.css ```css .control-panel { display: flex; flex-direction: row; flex-wrap: wrap; margin: 8px; } ``` -------- # Conditional culling Category: Editor API Keywords: culling, canCull, viewport, performance, glow, shadow, overflow, custom shape Keep shapes with overflow effects rendered off-screen by overriding `canCull()`. Culling is an optimization that hides shapes with `display: none` once their bounds leave the viewport. Shapes with visuals that extend beyond their bounds, like glows or drop shadows, pop in and out at the viewport edge when they're culled. Override `canCull()` on your `ShapeUtil` to opt individual shapes out. In this example both shapes have the same glow, and each has a checkbox that toggles a `preventCulling` prop read by `canCull()`. Try panning the canvas horizontally: the shape with "Prevent culling" checked stays visible as it slides off-screen, while the other disappears abruptly once its bounds leave the viewport. ## App.tsx ```tsx import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLShape, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' import './conditional-culling.css' // There's a guide at the bottom of this file! const GLOW_SHAPE_TYPE = 'glow-shape' declare module 'tldraw' { export interface TLGlobalShapePropsMap { [GLOW_SHAPE_TYPE]: { w: number; h: number; preventCulling: boolean } } } type GlowShape = TLShape class GlowShapeUtil extends BaseBoxShapeUtil { static override type = GLOW_SHAPE_TYPE static override props: RecordProps = { w: T.number, h: T.number, preventCulling: T.boolean, } getDefaultProps(): GlowShape['props'] { return { w: 150, h: 100, preventCulling: false, } } // [1] override canCull(shape: GlowShape) { return !shape.props.preventCulling } // [2] component(shape: GlowShape) { return ( ) } getIndicatorPath(shape: GlowShape) { const path = new Path2D() path.rect(0, 0, shape.props.w, shape.props.h) return path } } const shapeUtils = [GlowShapeUtil] export default function ConditionalCullingExample() { return (
{ // [3] editor.createShape({ type: GLOW_SHAPE_TYPE, x: 200, y: 100, props: { preventCulling: true }, }) editor.createShape({ type: GLOW_SHAPE_TYPE, x: 200, y: 350, props: { preventCulling: false }, }) }} />
) } /* Culling hides a shape (`display: none`) once its bounds leave the viewport. Shapes whose visuals extend past their bounds (glows, drop shadows, other overflow) pop in and out at the viewport edge when that happens. Returning false from `canCull()` keeps the shape visible off-screen. [1] `canCull()` is called per shape, so the decision can depend on the shape's own props (or any other state). Here a checkbox on the shape flips it. [2] Both shapes render the same glow; only the checkbox differs. Stopping pointer-down propagation lets the checkbox receive the click instead of the select tool starting a drag. [3] Two shapes stacked vertically so you can pan sideways and watch both leave the viewport at once. The one with "Prevent culling" checked keeps its glow visible past the edge; the other vanishes as soon as its bounds are off-screen. Culled shapes skip layout and paint, so only opt out of culling for shapes that genuinely need it. */ ``` ## conditional-culling.css ```css .glow-shape { width: 100%; height: 100%; background-color: #2f80ed; border-radius: 8px; display: flex; align-items: center; justify-content: center; box-shadow: 0 0 80px 50px rgba(47, 128, 237, 0.8); pointer-events: all; } .glow-shape label { display: flex; align-items: center; gap: 8px; color: white; font-weight: bold; font-size: 13px; cursor: pointer; } .glow-shape input { width: 16px; height: 16px; cursor: pointer; } ``` -------- # Dimensions HUD Category: Editor API Keywords: overlay, overlayutil, hud, dimensions, resize, bounds, gesture Show a live width × height pill next to the selection with a custom `OverlayUtil`. A non-interactive HUD that reads the editor's selection state and draws a dimensions label on the canvas overlay layer. Because overlays render in page space, the label follows pan and zoom without any `pageToScreen` plumbing; screen-sized values like padding and font size are divided by the zoom level instead. Select a shape and resize or rotate it: the label sticks to the edge closest to the bottom of the page and flips so it's never upside down. Select several shapes to see it fall back to the selection bounds. ## App.tsx ```tsx import { Tldraw, defaultOverlayUtils } from 'tldraw' import 'tldraw/tldraw.css' import { DimensionsHudOverlayUtil } from './DimensionsHudOverlayUtil' // There's a guide at the bottom of this file! // [1] const overlayUtils = [...defaultOverlayUtils, DimensionsHudOverlayUtil] export default function DimensionsHudExample() { return (
{/* [2] */}
) } /* This example adds a non-interactive dimensions label that follows the current selection. The label is implemented as a custom `OverlayUtil`, so it renders in the editor's canvas overlay layer rather than in the React tree. `DimensionsHudOverlayUtil.ts` does three things: - `isActive()` subscribes to the current selection and skips work when nothing is selected. - `getOverlays()` derives the label's page-space position, dimensions, and rotation from the selected shape or selection bounds. - `render()` draws the pill with Canvas 2D APIs. [1] Register the custom overlay util after `defaultOverlayUtils` so the built-in overlays remain enabled. The util's `options.zIndex` controls where it appears relative to the selection handles and other canvas overlays. [2] Pass the overlay util array to the `overlayUtils` prop on ``. Utils are constructed once on mount, so define the array at module level. */ ``` ## DimensionsHudOverlayUtil.ts ```ts import { Box, OverlayUtil, type TLOverlay, Vec } from 'tldraw' interface TLDimensionsHudOverlay extends TLOverlay { props: { x: number y: number w: number h: number rotation: number } } const LABEL_PADDING = 20 const PI2 = Math.PI * 2 type LabelEdge = 'top' | 'right' | 'bottom' | 'left' // [1] function getLabelEdge(rotation: number): LabelEdge { const quarterTurn = Math.round(rotation / (Math.PI / 2)) const normalizedQuarterTurn = ((quarterTurn % 4) + 4) % 4 switch (normalizedQuarterTurn) { case 0: return 'bottom' case 1: return 'right' case 2: return 'top' default: return 'left' } } // [2] function getReadableRotation(rotation: number): number { const normalizedRotation = ((rotation + Math.PI) % PI2) - Math.PI return Math.abs(normalizedRotation) > Math.PI / 2 ? rotation + Math.PI : rotation } // [3] function getLabelPointForEdge(edge: LabelEdge, bounds: Box, padding: number): Vec { switch (edge) { case 'bottom': return new Vec(bounds.midX, bounds.maxY + padding) case 'right': return new Vec(bounds.maxX + padding, bounds.midY) case 'top': return new Vec(bounds.midX, bounds.minY - padding) case 'left': return new Vec(bounds.minX - padding, bounds.midY) } } export class DimensionsHudOverlayUtil extends OverlayUtil { static override type = 'dimensions-hud' override options = { zIndex: 950 } override isActive(): boolean { return this.editor.getSelectedShapeIds().length > 0 } override getOverlays(): TLDimensionsHudOverlay[] { const selectedShapeIds = this.editor.getSelectedShapeIds() if (selectedShapeIds.length === 0) return [] // [4] if (selectedShapeIds.length > 1) { const bounds = this.editor.getSelectionPageBounds() if (!bounds) return [] const zoom = this.editor.getZoomLevel() return [ { id: 'dimensions-hud', type: 'dimensions-hud', props: { x: bounds.midX, y: bounds.maxY + LABEL_PADDING / zoom, w: Math.round(bounds.width), h: Math.round(bounds.height), rotation: 0, }, }, ] } const shape = this.editor.getShape(selectedShapeIds[0]) if (!shape) return [] // [5] const bounds = this.editor.getShapeGeometry(shape).bounds const transform = this.editor.getShapePageTransform(shape) const zoom = this.editor.getZoomLevel() const rotation = transform.rotation() // [6] const padding = LABEL_PADDING / zoom const labelEdge = getLabelEdge(rotation) const localLabelPoint = getLabelPointForEdge(labelEdge, bounds, padding) const labelPoint = transform.applyToPoint(localLabelPoint) const labelRotation = labelEdge === 'left' || labelEdge === 'right' ? rotation + Math.PI / 2 : rotation const readableLabelRotation = getReadableRotation(labelRotation) return [ { id: 'dimensions-hud', type: 'dimensions-hud', props: { x: labelPoint.x, y: labelPoint.y, w: Math.round(bounds.width), h: Math.round(bounds.height), rotation: readableLabelRotation, }, }, ] } override render(ctx: CanvasRenderingContext2D, overlays: TLDimensionsHudOverlay[]): void { const overlay = overlays[0] if (!overlay) return const colors = this.editor.getCurrentTheme().colors[this.editor.getColorMode()] const { x, y, w, h, rotation } = overlay.props const zoom = this.editor.getZoomLevel() ctx.save() // [7] ctx.textAlign = 'center' ctx.textBaseline = 'middle' ctx.font = `${10 / zoom}px sans-serif` const dimensionsLabel = `${w} × ${h}` const metrics = ctx.measureText(dimensionsLabel) const textHeight = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent const textWidth = metrics.width const pillPaddingX = 5 / zoom const pillWidth = textWidth + pillPaddingX * 2 const pillHeight = textHeight * 2 ctx.translate(x, y) ctx.rotate(rotation) ctx.fillStyle = colors.selectionStroke ctx.beginPath() ctx.roundRect(-pillWidth / 2, -pillHeight / 2, pillWidth, pillHeight, pillHeight / 3.5) ctx.fill() ctx.fillStyle = colors.selectedContrast ctx.fillText(dimensionsLabel, 0, 0) ctx.restore() } } /* [1] Pick the side of the selected shape that is closest to the bottom of the page. This keeps the label near the user's expected resize readout position even when the shape is rotated. [2] Flip the label by half a turn when it would otherwise be upside down. [3] Calculate the label point in the shape's local coordinate space. The shape's page transform converts it to page space later. [4] Multiple selections do not have a single rotation, so the label uses the selection's page bounds and stays horizontal. [5] Use shape geometry bounds for the width and height. These are local bounds, so they represent the unrotated dimensions the user is editing. [6] Overlay drawing happens in page space. Divide fixed screen-space values by the zoom level so padding, text, and the pill size look consistent while zooming. [7] Save and restore the canvas context around all drawing state because overlay utils share the same Canvas 2D context. */ ``` -------- # Lasso select tool Category: Editor API Keywords: lasso, selection, freehand, overlays, custom tool, state machine, atom, statenode, getstrokepoints, getsvgpathfromstrokepoints, overlayutil Select shapes by drawing a freehand lasso around them with a custom tool and a canvas overlay. The tool is a `StateNode` with an `idle` child and a `lassoing` child. While lassoing, the tool stores the pointer's page-space points in an `atom`, so anything that reads them re-renders as they change. A custom `OverlayUtil` reads that atom, smooths the points with `getStrokePoints`, converts them to an SVG path with `getSvgPathFromStrokePoints`, and draws the result onto the canvas overlay with `Path2D`. On pointer up, the tool selects every shape whose page-space vertices are all inside the lasso polygon (`pointInPolygon`) and whose outline does not cross the lasso (`polygonsIntersect`), then switches back to the select tool. Press `W` or pick the lasso from the toolbar, then drag a loop around some shapes. Only shapes fully enclosed by the loop are selected. ## App.tsx ```tsx import { DefaultKeyboardShortcutsDialog, DefaultKeyboardShortcutsDialogContent, DefaultToolbar, DefaultToolbarContent, TLComponents, Tldraw, TldrawUiMenuItem, TLUiOverrides, useIsToolSelected, useTools, } from 'tldraw' import { LassoOverlayUtil } from './LassoOverlayUtil' import { LassoSelectTool } from './LassoSelectTool' // There's a guide at the bottom of this file! //[1] const uiOverrides: TLUiOverrides = { tools(editor, tools) { tools['lasso-select'] = { id: 'lasso-select', icon: 'color', label: 'Lasso select', kbd: 'w', //w for wrangle 🤠 onSelect: () => { editor.setCurrentTool('lasso-select') }, } return tools }, } //[2] const components: TLComponents = { Toolbar: (props) => { const tools = useTools() const isLassoSelected = useIsToolSelected(tools['lasso-select']) return ( ) }, KeyboardShortcutsDialog: (props) => { const tools = useTools() return ( ) }, } //[3] const overlayUtils = [LassoOverlayUtil] export default function LassoSelectToolExample() { return (
) } /* The tool itself lives in LassoSelectTool.ts and the overlay in LassoOverlayUtil.ts. For a simpler selection tool, see the `MiniSelectTool` and `MicroSelectTool` in the only-editor example. [1] The UI override registers the tool with the UI so it has an icon, label, and keyboard shortcut. See the add-tool-to-toolbar example for more on this. [2] The `components` override adds the tool to the toolbar and the keyboard shortcuts dialog. These are defined at module level so `` doesn't see a new object on every render. [3] `LassoOverlayUtil` draws the lasso onto the canvas overlay. It reads the tool's `points` atom, smooths the points with `getStrokePoints`, converts them to an SVG path, and paints it with a `Path2D`. */ ``` ## LassoOverlayUtil.ts ```ts import { getStrokePoints, getSvgPathFromStrokePoints, OverlayUtil, TLOverlay } from 'tldraw' import { LassoingState } from './LassoSelectTool' interface TLLassoOverlay extends TLOverlay { props: { svgPath: string } } export class LassoOverlayUtil extends OverlayUtil { static override type = 'lasso' override isActive(): boolean { return this.editor.isIn('lasso-select.lassoing') } override getOverlays(): TLLassoOverlay[] { const lassoing = this.editor.getStateDescendant('lasso-select.lassoing') const points = lassoing?.points.get() ?? [] if (points.length === 0) return [] const smoothedPoints = getStrokePoints(points) const svgPath = getSvgPathFromStrokePoints(smoothedPoints, true) if (!svgPath) return [] return [ { id: 'lasso', type: 'lasso', props: { svgPath }, }, ] } override render(ctx: CanvasRenderingContext2D, overlays: TLLassoOverlay[]): void { const overlay = overlays[0] if (!overlay) return const zoom = this.editor.getZoomLevel() const colors = this.editor.getCurrentTheme().colors[this.editor.getColorMode()] const path = new Path2D(overlay.props.svgPath) ctx.globalAlpha = 0.5 ctx.fillStyle = colors.selectionFill ctx.fill(path) ctx.globalAlpha = 1 ctx.lineWidth = 2 / zoom ctx.strokeStyle = colors.selectionStroke ctx.stroke(path) } } ``` ## LassoSelectTool.ts ```ts import { atom, pointInPolygon, polygonsIntersect, StateNode, TLPointerEventInfo, TLShape, VecModel, } from 'tldraw' // There's a guide at the bottom of this file! export class LassoSelectTool extends StateNode { static override id = 'lasso-select' static override children() { return [IdleState, LassoingState] } static override initial = 'idle' } export class IdleState extends StateNode { static override id = 'idle' override onPointerDown(info: TLPointerEventInfo) { const { editor } = this editor.selectNone() this.parent.transition('lassoing', info) } } //[1] export class LassoingState extends StateNode { static override id = 'lassoing' info = {} as TLPointerEventInfo markId = null as null | string //[a] points = atom('lasso points', []) override onEnter(info: TLPointerEventInfo) { this.points.set([]) this.markId = null this.info = info this.startLasso() } private startLasso() { this.markId = this.editor.markHistoryStoppingPoint('lasso start') } //[b] override onPointerMove(): void { this.addPointToLasso() } private addPointToLasso() { const { inputs } = this.editor const { x, y, z } = inputs.getCurrentPagePoint().toFixed() const newPoint = { x, y, z } this.points.set([...this.points.get(), newPoint]) } //[c] private getShapesInLasso() { const { editor } = this const shapes = editor.getCurrentPageRenderingShapesSorted() const lassoPoints = this.points.get() const shapesInLasso = shapes.filter((shape) => { return this.doesLassoFullyContainShape(lassoPoints, shape) }) return shapesInLasso } private doesLassoFullyContainShape(lassoPoints: VecModel[], shape: TLShape): boolean { const { editor } = this const geometry = editor.getShapeGeometry(shape) const pageTransform = editor.getShapePageTransform(shape) const shapeVertices = pageTransform.applyToPoints(geometry.vertices) const allVerticesInside = shapeVertices.every((vertex) => { return pointInPolygon(vertex, lassoPoints) }) if (!allVerticesInside) { return false } // All vertices can be inside the lasso while an edge still crosses it, e.g. a // wide shape inside a concave lasso. Reject those too. if (geometry.isClosed) { if (polygonsIntersect(shapeVertices, lassoPoints)) { return false } } return true } override onPointerUp(): void { this.complete() } override onComplete() { this.complete() } //[d] complete() { const { editor } = this const shapesInLasso = this.getShapesInLasso() editor.setSelectedShapes(shapesInLasso) editor.setCurrentTool('select') } } /* For a general guide on building tools with child states, see the `MiniSelectTool` in the only-editor example. [1] `LassoingState` is active from pointer down until pointer up. [a] `points` is an `atom` rather than a plain array so that `LassoOverlayUtil`, which reads it while rendering the canvas overlay, re-renders whenever a point is added. [b] Each pointer move appends the current page-space pointer position to `points`. [c] A shape counts as inside the lasso when every one of its page-space vertices is inside the lasso polygon and none of its edges cross the lasso outline. [d] On pointer up (or when the editor completes the interaction some other way, e.g. a menu opens or the page changes), select the enclosed shapes and hand back to the select tool. If you wanted to take the lasso further, you could: - live update the selection as the user moves the mouse, similar to how the default select and brush select tools work - use modifier keys to add or subtract from the selection instead of just setting the selection - properly handle what happens when we select a shape that's grouped with other shapes (do we select the shape within the group or move up a level and select the entire group? what about layers?) - extend the default selection tool to allow for lasso selection when a hotkey is pressed, similar to the brush select tool - add a little bit of leeway to the lasso selection logic to allow for shapes that are mostly, but not fully, enclosed in the lasso to be selected */ ``` -------- # Locked shapes Category: Editor API Keywords: lock, unlock, locked, islocked, ignoreshapelock, selectlockedshapes, template, background, togglelock, editor.run, programmatic, read-only Lock shapes against user editing, move them from code with `ignoreShapeLock`, and let users select them with the `selectLockedShapes` option. The blue shapes are locked on mount with `editor.toggleLock`. Users can't drag, resize, edit, or delete them, and left-clicking one does nothing (right-click still selects it). - **Scatter / Reset** wrap `editor.updateShapes` in `editor.run(fn, { ignoreShapeLock: true })`, which lifts the lock guard for the callback so code can move shapes the user can't. - **Allow selecting locked shapes** toggles the `selectLockedShapes` editor option, which lets locked shapes be picked by left-click, brush, and scribble selection. It only affects selection; the lock guards on moving, resizing, editing, and deleting still apply. Editor options are fixed for the editor's lifetime, so flipping the toggle passes a new `options` object to `` and the editor is recreated (the store, and so the shapes, are kept). ## App.tsx ```tsx import { useMemo } from 'react' import { atom, createShapeId, Editor, Tldraw, TldrawUiButton, TLComponents, TLShapeId, toRichText, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './locked-shapes.css' // There's a guide at the bottom of this file! const TEMPLATE_IDS: TLShapeId[] = [ createShapeId('t1'), createShapeId('t2'), createShapeId('t3'), createShapeId('t4'), ] const HOME_POSITIONS = [ { x: 100, y: 100 }, { x: 250, y: 100 }, { x: 100, y: 250 }, { x: 250, y: 250 }, ] // [1] const selectLockedShapes$ = atom('selectLockedShapes', false) function ControlPanel() { const editor = useEditor() const selectLockedShapes = useValue(selectLockedShapes$) // [2] const moveTemplates = (positions: { x: number; y: number }[]) => { editor.run( () => { editor.updateShapes(TEMPLATE_IDS.map((id, i) => ({ id, type: 'geo', ...positions[i] }))) }, { ignoreShapeLock: true } ) } const handleScatter = () => { moveTemplates( TEMPLATE_IDS.map(() => ({ x: 50 + Math.random() * 300, y: 50 + Math.random() * 300 })) ) } return (
Scatter moveTemplates(HOME_POSITIONS)}> Reset
) } const components: TLComponents = { TopPanel: ControlPanel, } // [3] function handleMount(editor: Editor) { if (!editor.getShape(TEMPLATE_IDS[0])) { const props = { geo: 'rectangle' as const, w: 130, h: 130, dash: 'dashed' as const, color: 'light-blue' as const, fill: 'semi' as const, richText: toRichText('Locked'), } editor.createShapes( TEMPLATE_IDS.map((id, i) => ({ id, type: 'geo', ...HOME_POSITIONS[i], props })) ) editor.toggleLock(TEMPLATE_IDS) } editor.zoomToFit({ animation: { duration: 0 } }) } export default function LockedShapesExample() { const selectLockedShapes = useValue(selectLockedShapes$) const options = useMemo(() => ({ selectLockedShapes }), [selectLockedShapes]) return (
) } /* Locked shapes can't be moved, resized, edited, or deleted by the user. This example shows two ways the editor lets you work around that: - `editor.run(fn, { ignoreShapeLock: true })` lifts the lock guard for the duration of the callback, so code can move shapes the user can't drag. - The `selectLockedShapes` editor option lets locked shapes be selected by left-click, brush, and scribble selection. Only selection changes; the lock guards still apply to everything else. Try it: left-click a blue shape and nothing happens (right-click still selects it). Turn on "Allow selecting locked shapes" and left-click or brush across one; it selects, but the handles won't move it. Scatter and Reset move the shapes regardless of the toggle. [1] The toggle lives in a module-level `atom` so both the control panel (inside the editor) and the example component (outside it) can read it with `useValue`. Editor options are read-only once the editor is created, so the example passes a new `options` object to ``, which recreates the editor with the new setting. The store is preserved, so the shapes and camera survive the swap. [2] Both buttons wrap `updateShapes` in `editor.run` with `ignoreShapeLock: true`. Without it, updates to locked shapes are silently dropped. [3] On mount, create a 2x2 grid of shapes and lock them with `toggleLock`. `onMount` runs again whenever the editor is recreated, so it checks whether the shapes already exist first. */ ``` ## locked-shapes.css ```css .locked-shapes-panel { display: flex; gap: 8px; align-items: center; padding: 4px 8px; } .locked-shapes-panel label { display: flex; align-items: center; gap: 6px; font-size: 13px; cursor: pointer; user-select: none; } ``` -------- # Reactive inputs Category: Editor API Keywords: inputs manager, pointer tracking, mouse position, velocity, usevalue, reactive state, screen point, page point, origin point, pointer events, modifier keys Track pointer positions, velocity, and modifier keys reactively with `editor.inputs` and `useValue`. `editor.inputs` exposes the current, previous, and origin pointer positions in both screen and page space, the pointer velocity, and the state of the modifier keys. Each getter (`getCurrentPagePoint()`, `getPointerVelocity()`, `getShiftKey()`, and so on) reads a reactive atom, so wrapping a call in `useValue` subscribes the component and re-renders it whenever the value changes. Move the pointer around the canvas and hold modifier keys to watch the panel update. Origin points only change on pointer down. ## App.tsx ```tsx import { TLComponents, Tldraw, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' import './reactive-inputs.css' // There's a guide at the bottom of this file! const components: TLComponents = { TopPanel: ReactiveInputsPanel, } export default function ReactiveInputsExample() { return (
) } function formatNum(n: number, decimals: number): string { const s = n.toFixed(decimals) return n >= 0 ? ` ${s}` : s } function ReactiveInputsPanel() { const editor = useEditor() // [1] const currentScreenPoint = useValue( 'current screen point', () => editor.inputs.getCurrentScreenPoint(), [editor] ) const currentPagePoint = useValue( 'current page point', () => editor.inputs.getCurrentPagePoint(), [editor] ) const previousScreenPoint = useValue( 'previous screen point', () => editor.inputs.getPreviousScreenPoint(), [editor] ) const previousPagePoint = useValue( 'previous page point', () => editor.inputs.getPreviousPagePoint(), [editor] ) const originScreenPoint = useValue( 'origin screen point', () => editor.inputs.getOriginScreenPoint(), [editor] ) const originPagePoint = useValue('origin page point', () => editor.inputs.getOriginPagePoint(), [ editor, ]) const pointerVelocity = useValue('pointer velocity', () => editor.inputs.getPointerVelocity(), [ editor, ]) // [2] const shiftKey = useValue('shift key', () => editor.inputs.getShiftKey(), [editor]) const ctrlKey = useValue('ctrl key', () => editor.inputs.getCtrlKey(), [editor]) const altKey = useValue('alt key', () => editor.inputs.getAltKey(), [editor]) const metaKey = useValue('meta key', () => editor.inputs.getMetaKey(), [editor]) const accelKey = useValue('accel key', () => editor.inputs.getAccelKey(), [editor]) return (
{/* [3] */}
Screen point
{formatNum(currentScreenPoint.x, 0)}, {formatNum(currentScreenPoint.y, 0)}
Page point
{formatNum(currentPagePoint.x, 0)}, {formatNum(currentPagePoint.y, 0)}
Prev screen
{formatNum(previousScreenPoint.x, 0)}, {formatNum(previousScreenPoint.y, 0)}
Prev page
{formatNum(previousPagePoint.x, 0)}, {formatNum(previousPagePoint.y, 0)}
Origin screen
{formatNum(originScreenPoint.x, 0)}, {formatNum(originScreenPoint.y, 0)}
Origin page
{formatNum(originPagePoint.x, 0)}, {formatNum(originPagePoint.y, 0)}
{/* [4] */}
Velocity
{formatNum(pointerVelocity.x, 2)}, {formatNum(pointerVelocity.y, 2)} px/ms
Modifiers
Shift Ctrl Alt Meta Accel
) } /* [1] `editor.inputs` exposes pointer state through getters (`getCurrentPagePoint()`, `getOriginScreenPoint()`, and so on) that read reactive atoms. Reading them inside `useValue` subscribes the component, so it re-renders whenever the pointer moves. Reading them outside a reactive context still works but won't update the UI. [2] Modifier keys are reactive too. `getAccelKey()` is the platform accelerator (Cmd on Mac, Ctrl elsewhere), which is what you want for cross-platform shortcuts. [3] Screen points are relative to the editor's container. Page points are in canvas coordinates, so they account for the camera's pan and zoom. Origin points are where the last pointer down happened. [4] Pointer velocity is updated by the tick manager, in pixels per millisecond. It's useful for detecting flicks or driving physics-style interactions. */ ``` ## reactive-inputs.css ```css /* tlui-menu provides the native panel background, radius, and shadow. */ .reactive-inputs-panel { margin: 8px; padding: var(--tl-space-2); pointer-events: all; } .reactive-inputs-content { display: flex; flex-wrap: wrap; gap: var(--tl-space-2); align-items: center; } .input-group { display: flex; align-items: baseline; gap: var(--tl-space-1); padding: var(--tl-space-1) var(--tl-space-3); background: var(--tl-color-muted-2); border-radius: var(--tl-radius-2); } .input-label { font-size: 12px; color: var(--tl-color-text); white-space: nowrap; } .input-value { font-size: 10px; color: var(--tl-color-text); white-space: nowrap; font-variant-numeric: tabular-nums; min-width: 80px; } .input-hint { font-size: 11px; color: var(--tl-color-text-3); } .modifier-keys { display: flex; flex-wrap: wrap; gap: var(--tl-space-1); } .modifier-key { display: inline-block; padding: var(--tl-space-1) var(--tl-space-2); font-size: 11px; background: var(--tl-color-muted-1); color: var(--tl-color-text-3); border-radius: var(--tl-radius-1); } .modifier-key[data-active='true'] { background: var(--tl-color-selected); color: var(--tl-color-selected-contrast); } ``` -------- # Replace a built-in overlay Category: Editor API Keywords: overlay, overlayutil, brush, selection, custom, render Replace the built-in selection brush by subclassing `BrushOverlayUtil` and overriding its `render` method. Every canvas overlay (the selection brush, scribble, snap indicators, shape handles) is an `OverlayUtil` subclass you can replace. This example extends the built-in `BrushOverlayUtil` and overrides `render` to draw a dashed purple rectangle instead of the default. Because the subclass inherits the `brush` type, passing it in `overlayUtils` replaces the default brush; `` merges custom utils over the defaults by type. Drag-select on the canvas to see it. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' import { DashedBrushOverlayUtil } from './DashedBrushOverlayUtil' // There's a guide at the bottom of this file! // [1] const overlayUtils = [DashedBrushOverlayUtil] export default function ReplaceBrushOverlayExample() { return (
) } /* The canvas overlays (brush, scribble, snap indicators, selection handles, and so on) are all `OverlayUtil` subclasses. To replace one, subclass the built-in util and override the methods you want to change. `DashedBrushOverlayUtil.ts` extends `BrushOverlayUtil` and overrides `render` to draw a dashed purple rectangle. `getOverlays`, `isActive`, and the static `type` are inherited, so it activates exactly when the built-in brush would. Try drag-selecting a region on the canvas. [1] `` merges the overlay utils you pass with the defaults, and a custom util whose static `type` matches a default replaces it. Since our subclass inherits `type = 'brush'`, passing it alone is enough to swap out the built-in brush. `shapeUtils` and `bindingUtils` merge by static `type` the same way; `tools` merge by static `id`. */ ``` ## DashedBrushOverlayUtil.ts ```ts import { BrushOverlayUtil, TLBrushOverlay } from 'tldraw' export class DashedBrushOverlayUtil extends BrushOverlayUtil { override render(ctx: CanvasRenderingContext2D, overlays: TLBrushOverlay[]): void { const overlay = overlays[0] if (!overlay) return const { x, y, w, h } = overlay.props const zoom = this.editor.getZoomLevel() ctx.fillStyle = 'rgba(147, 51, 234, 0.08)' ctx.fillRect(x, y, w, h) ctx.save() ctx.lineWidth = 2 / zoom ctx.setLineDash([8 / zoom, 4 / zoom]) ctx.strokeStyle = 'rgb(147, 51, 234)' ctx.strokeRect(x, y, w, h) ctx.restore() } } ``` -------- # Toggle focus mode Category: Editor API Keywords: focus mode, isfocusmode, updateinstancestate, distraction free, hide ui, onmount Enable focus mode on mount with `updateInstanceState`. Focus mode hides the default UI so only the canvas is visible. It's a flag on the editor's instance state, so `editor.updateInstanceState({ isFocusMode: true })` turns it on and the UI responds. Users can toggle it themselves with `Cmd/Ctrl+.` or the exit button that focus mode leaves in the corner. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function FocusModeExample() { return (
{ // [1] editor.updateInstanceState({ isFocusMode: true }) }} />
) } /* [1] Focus mode is a flag on the editor's instance state. `updateInstanceState` sets it; the default UI reads it and hides everything except a small exit button. When a `persistenceKey` is used, this flag is preserved as a user preference, so setting it in `onMount` forces it on regardless. */ ``` -------- # Hovered overlay Category: Editor API Keywords: overlay, overlaymanager, hover, hit test, selection, handle, reactive Read the canvas overlay under the pointer with `editor.overlays.getHoveredOverlay()`. The `OverlayManager` on `editor.overlays` tracks every active canvas overlay (selection handles, resize corners, rotation handles, shape handles) and which one is under the pointer. `getHoveredOverlay()` is reactive, so this example reads it with `useValue` and prints its type and id in the top panel. Select a shape, then hover its handles to see the readout update. `getOverlayAtPoint(point)` does the same hit test for an arbitrary page point. ## App.tsx ```tsx import { TLComponents, Tldraw, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' import './hovered-overlay.css' // There's a guide at the bottom of this file! // [1] function HoveredOverlayReadout() { const editor = useEditor() const hovered = useValue('hoveredOverlay', () => editor.overlays.getHoveredOverlay(), [editor]) return (
{hovered ? ( <>
type {hovered.type}
id {hovered.id}
) : (
Select a shape, then hover its handles
)}
) } // [2] const components: TLComponents = { TopPanel: HoveredOverlayReadout, } export default function HoveredOverlayExample() { return (
) } /* The editor exposes an `OverlayManager` on `editor.overlays` that tracks every active canvas overlay — selection handles, resize corners, rotation handles, shape handles, and so on. It gives you reactive access to the overlay the user is hovering and hit-testing at an arbitrary page point. Key methods on `editor.overlays`: - `getHoveredOverlay()` — the `TLOverlay` currently under the pointer, or null. Reactive: updates as the pointer moves. - `getOverlayAtPoint(point, margin?)` — hit test any page-space point against all interactive overlays. Returns the topmost match, or null. - `getCurrentOverlays()` — every active overlay in paint order. - `getOverlayGeometry(overlay)` — cached hit-test geometry for an overlay. [1] Read `editor.overlays.getHoveredOverlay()` inside `useValue` so the component re-renders whenever the hovered overlay changes. Select a shape to produce handles, then hover one to see its type (for example `selection_foreground` or `shape_handle`) and its id. [2] Mount the readout into the `TopPanel` component slot. */ ``` ## hovered-overlay.css ```css .hovered-overlay-readout { background: var(--color-panel); border: 1px solid var(--color-divider); border-radius: 8px; padding: 8px 12px; margin: 8px; font-size: 12px; color: var(--color-text); pointer-events: none; display: flex; flex-direction: column; gap: 4px; min-width: 220px; } .hovered-overlay-readout > div { display: flex; gap: 8px; align-items: baseline; } .hovered-overlay-readout span { color: var(--color-text-3); font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; width: 36px; } .hovered-overlay-readout code { font-family: var(--tl-font-mono, monospace); font-size: 12px; } .hovered-overlay-readout__empty { color: var(--color-text-3); font-style: italic; } ``` -------- # Interaction end callback Category: Editor API Keywords: callback, interaction, drag, resize, rotate, tool, oninteractionend, translating, setcurrenttool, programmatic Run custom logic when a programmatically started drag ends with `onInteractionEnd`. When a tool starts one of the select tool's interactions itself, for example `editor.setCurrentTool('select.translating', info)`, the `onInteractionEnd` field in `info` controls what happens when the interaction finishes. Pass a tool id string to report that tool as the current one while the drag runs (and return to it if tool lock is on), or a function to run arbitrary code. This example's tool creates a square on click and immediately starts translating it. Click and drag anywhere: when you release, the callback changes the fill to a pattern and returns to the tool so the next click creates another square. ## App.tsx ```tsx import { createShapeId, StateNode, TLPointerEventInfo, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] class QuickShapeTool extends StateNode { static override id = 'quick-shape' override onEnter() { this.editor.setCursor({ type: 'cross', rotation: 0 }) } override onPointerDown(info: TLPointerEventInfo) { const currentPagePoint = this.editor.inputs.getCurrentPagePoint() const shapeId = createShapeId() this.editor.createShape({ id: shapeId, type: 'geo', x: currentPagePoint.x - 50, y: currentPagePoint.y - 50, props: { w: 100, h: 100, fill: 'solid' }, }) this.editor.setSelectedShapes([shapeId]) // [2] this.editor.setCurrentTool('select.translating', { ...info, target: 'shape', shape: this.editor.getShape(shapeId), isCreating: true, // [3] onInteractionEnd: () => { this.editor.updateShape({ id: shapeId, type: 'geo', props: { fill: 'pattern' }, }) this.editor.setCurrentTool('quick-shape') }, }) } } const tools = [QuickShapeTool] export default function InteractionEndExample() { return (
) } /* [1] A tool that creates a shape on pointer down and immediately hands off to the select tool's translating state, so the shape follows the pointer until it's released. [2] `select.translating` is normally entered from `select.pointing_shape`. Entering it directly needs the same info: the pointer event, the target shape, and `isCreating`, which tells the state that the shape was just created so it won't Alt-clone it and will treat the drag as part of creation. [3] `onInteractionEnd` runs when the drag finishes. Passing a string such as 'quick-shape' mainly masks the current tool id, so the UI keeps showing that tool during the drag; it only switches back to it on completion when tool lock is on. Passing a function lets you do more first. Here we swap the fill to a pattern and then return to this tool so the next click creates another shape. */ ``` -------- # Performance hooks Category: Editor API Keywords: performance, fps, frame, interaction, camera, resize, translate, perf, monitoring, devtools Subscribe to `editor.performance` events to show frame time stats for interactions and camera moves. `editor.performance.on(event, fn)` subscribes to performance events and returns an unsubscribe function. This example listens for `interaction-end`, which fires when a translate, resize, rotate, or draw finishes, and `camera-end`, which fires once panning or zooming settles. Both include frame time stats (average, p95, p99, fps) plus context like shape counts and zoom level, which the panel renders. It also creates a `PerformanceApiAdapter`, which mirrors the same events into the browser's Performance API as `tldraw:*` marks and measures so they show up in a DevTools performance recording. Drag a shape, or pan and zoom the canvas, and watch the panel update. ## App.tsx ```tsx import { useEffect, useState } from 'react' import { Editor, PerformanceApiAdapter, TLCameraEndPerfEvent, TLComponents, TLInteractionEndPerfEvent, TLPerfFrameTimeStats, Tldraw, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' import './performance-hooks.css' // There's a guide at the bottom of this file! function FrameTimeStats({ event }: { event: TLPerfFrameTimeStats }) { return (
Frame times
Duration {event.duration.toFixed(0)}ms
FPS {event.fps.toFixed(1)}
Frames {event.frameCount}
Avg {event.avgFrameTime.toFixed(1)}ms
p95 {event.p95FrameTime.toFixed(1)}ms
) } type LastEvent = | { kind: 'interaction'; event: TLInteractionEndPerfEvent } | { kind: 'camera'; event: TLCameraEndPerfEvent } // [1] function PerfPanel() { const editor = useEditor() const [last, setLast] = useState(null) useEffect(() => { // [2] const unsubs = [ editor.performance.on('interaction-end', (event) => { setLast({ kind: 'interaction', event }) }), editor.performance.on('camera-end', (event) => { setLast({ kind: 'camera', event }) }), ] // [3] const adapter = new PerformanceApiAdapter(editor.performance) return () => { unsubs.forEach((unsub) => unsub()) adapter.dispose() } }, [editor]) return (
{last ? ( <>
{last.kind === 'interaction' ? `Interaction: ${last.event.name}` : `Camera: ${last.event.type}`}
{last.kind === 'interaction' ? (
Context
{Object.entries(last.event.selectedShapeTypes).map(([type, count]) => (
{type} {count}
))}
All shapes {last.event.shapeCount}
Zoom {(last.event.zoomLevel * 100).toFixed(0)}%
) : (
Visible shapes {last.event.visibleShapeCount}
Culled shapes {last.event.culledShapeCount}
Zoom {(last.event.zoomLevel * 100).toFixed(0)}%
)} ) : (
Drag a shape or pan the canvas to see performance stats
)}
) } const components: TLComponents = { InFrontOfTheCanvas: PerfPanel, } function handleMount(editor: Editor) { editor.createShapes([ { type: 'geo', x: 100, y: 100, props: { w: 200, h: 200, fill: 'solid' } }, { type: 'geo', x: 400, y: 100, props: { w: 150, h: 150, geo: 'ellipse', fill: 'solid' } }, { type: 'geo', x: 200, y: 350, props: { w: 250, h: 100, geo: 'diamond', fill: 'solid' } }, ]) } export default function PerformanceHooksExample() { return (
) } /* [1] The panel lives in the `InFrontOfTheCanvas` slot so it can use `useEditor`. It shows only the most recent event; each new one replaces the last. [2] `editor.performance.on('interaction-end', fn)` fires when any interaction completes (translate, resize, rotate, draw, and so on). `camera-end` fires once panning or zooming has settled. Both carry frame time stats (avg, p95, p99, fps) plus context such as shape counts and zoom level. `on` returns an unsubscribe function, which the effect cleanup calls. [3] `PerformanceApiAdapter` mirrors the same events into the browser's Performance API with `performance.mark()` and `performance.measure()`. Record in the DevTools performance tab while interacting and you'll see measures like `tldraw:interaction:translating` in the timings lane. It's optional; dispose it when you're done. */ ``` ## performance-hooks.css ```css .perf-panel { position: absolute; bottom: 64px; right: 8px; display: flex; flex-direction: column; gap: 12px; padding: 8px 12px; font-size: 12px; min-width: 200px; background-color: var(--tl-color-panel); border-radius: var(--tl-radius-3); box-shadow: var(--tl-shadow-2); pointer-events: none; z-index: var(--tl-layer-panels); } .perf-section { display: flex; flex-direction: column; gap: 3px; } .perf-section-title { font-size: 12px; margin-bottom: 2px; } .perf-row { display: flex; justify-content: space-between; gap: 12px; } .perf-label { opacity: 0.6; } .perf-value { font-family: var(--tl-font-mono); font-size: 11px; } .perf-hint { opacity: 0.5; } ``` -------- # Selection bounds Category: Editor API Keywords: selection, bounds, rotation, geometry, getselectionpagebounds, getselectionrotatedpagebounds, getselectionrotation Visualize the difference between `getSelectionPageBounds()` and `getSelectionRotatedPageBounds()` for the current selection. `getSelectionPageBounds()` returns the smallest upright rectangle around the selection; `getSelectionRotatedPageBounds()` returns a box aligned to the selection's shared rotation, which is what the visible selection handles use. This example draws both over the canvas with an `InFrontOfTheCanvas` component that converts page bounds to viewport pixels using `pageToViewport()` and the zoom level. Select the single rotated shape, the group with a shared rotation, and the two ungrouped shapes with different rotations to see when the two boxes differ and when the rotated box falls back to axis-aligned. ## App.tsx ```tsx import { Editor, TLComponents, Tldraw, createShapeId, toRichText, track, useEditor } from 'tldraw' import 'tldraw/tldraw.css' import './selection-bounds.css' // There's a guide at the bottom of this file! const DEMO_IDS = { blue: createShapeId('selection-bounds-blue'), greenA: createShapeId('selection-bounds-green-a'), greenB: createShapeId('selection-bounds-green-b'), greenGroup: createShapeId('selection-bounds-green-group'), purple: createShapeId('selection-bounds-purple'), red: createShapeId('selection-bounds-red'), hint: createShapeId('selection-bounds-hint'), } as const const ALL_DEMO_IDS = Object.values(DEMO_IDS) const SAME_ROTATION = Math.PI / 6 const DEMO_SHAPES: Parameters[0] = [ { id: DEMO_IDS.blue, type: 'geo' as const, x: 120, y: 250, rotation: SAME_ROTATION, props: { geo: 'rectangle' as const, w: 180, h: 110, color: 'blue' as const, fill: 'semi' as const, dash: 'draw' as const, }, }, { id: DEMO_IDS.greenA, type: 'geo' as const, x: 430, y: 205, props: { geo: 'rectangle' as const, w: 140, h: 80, color: 'green' as const, fill: 'semi' as const, dash: 'solid' as const, }, }, { id: DEMO_IDS.greenB, type: 'geo' as const, x: 610, y: 245, props: { geo: 'rectangle' as const, w: 120, h: 70, color: 'green' as const, fill: 'semi' as const, dash: 'solid' as const, }, }, { id: DEMO_IDS.purple, type: 'geo' as const, x: 880, y: 205, rotation: Math.PI / 8, props: { geo: 'rectangle' as const, w: 130, h: 80, color: 'violet' as const, fill: 'semi' as const, dash: 'solid' as const, }, }, { id: DEMO_IDS.red, type: 'geo' as const, x: 1040, y: 260, rotation: -Math.PI / 10, props: { geo: 'rectangle' as const, w: 130, h: 80, color: 'red' as const, fill: 'semi' as const, dash: 'solid' as const, }, }, ] function seedDemoContent(editor: Editor) { const existingDemoShapeIds = ALL_DEMO_IDS.filter((id) => editor.getShape(id)) if (existingDemoShapeIds.length) { editor.deleteShapes(existingDemoShapeIds) } editor.createShapes([ ...DEMO_SHAPES, { id: DEMO_IDS.hint, type: 'text' as const, x: 880, y: 340, props: { richText: toRichText('⬆ Select both boxes,\nthen rotate them!'), color: 'grey' as const, size: 's' as const, autoSize: true, }, }, ]) editor.groupShapes([DEMO_IDS.greenA, DEMO_IDS.greenB], { groupId: DEMO_IDS.greenGroup, select: false, }) editor.updateShapes([{ id: DEMO_IDS.greenGroup, type: 'group', rotation: SAME_ROTATION }]) editor.select(DEMO_IDS.blue) editor.zoomToFit({ animation: { duration: 0 } }) } const SelectionBoundsOverlay = track(() => { const editor = useEditor() const axisAlignedBounds = editor.getSelectionPageBounds() // [1] const rotatedBounds = editor.getSelectionRotatedPageBounds() // [2] if (!axisAlignedBounds || !rotatedBounds) return null // [3] const zoom = editor.getZoomLevel() const rotation = editor.getSelectionRotation() const axisAlignedViewportPoint = editor.pageToViewport(axisAlignedBounds.point) const rotatedViewportPoint = editor.pageToViewport(rotatedBounds.point) return ( <>
) }) function BoundsKey() { return (
getSelectionPageBounds — smallest upright rectangle
getSelectionRotatedPageBounds — aligned to selection rotation
) } const components: TLComponents = { InFrontOfTheCanvas: SelectionBoundsOverlay, TopPanel: BoundsKey, } export default function SelectionBoundsExample() { return (
{ if (ALL_DEMO_IDS.every((id) => editor.getShape(id))) { return } seedDemoContent(editor) }} />
) } /* The editor keeps two kinds of bounds for the current selection. [1] `getSelectionPageBounds()` is the axis-aligned bounding box (blue dashed). It has zero rotation and is the smallest upright rectangle containing every selected shape. It's used for hit testing and culling, not for the visible selection UI. [2] `getSelectionRotatedPageBounds()` is the rotated selection box (amber solid). When the selected shapes share one rotation, this box follows it, which is why the resize handles on two equally rotated shapes line up with the shapes' own axes. When rotations differ there's no sensible shared angle, so it falls back to the axis-aligned box. [3] Both boxes are in page space. `pageToViewport()` converts their origins to viewport pixels, and the sizes are scaled by the zoom level, so plain HTML elements can be laid over the canvas. The component is wrapped in `track` so it re-renders whenever the selection or camera changes. Try selecting each demo: 1. The blue shape: a single rotated shape, where the two boxes differ. 2. The green group: two shapes with a shared rotation, so the rotated box still follows their angle. 3. The purple and red pair: two ungrouped shapes with different rotations, so the rotated box collapses to the axis-aligned one. Rotate one of them on its own to see how the axis-aligned box changes while the rotated box stays aligned to the page. */ ``` ## selection-bounds.css ```css .selection-bounds-box { position: absolute; top: 0; left: 0; pointer-events: none; transform-origin: top left; } .selection-bounds-box--axis { border: 2px dashed rgba(45, 116, 255, 0.95); background: rgba(45, 116, 255, 0.08); z-index: 9998; } .selection-bounds-box--rotated { border: 2px solid rgba(237, 137, 54, 0.95); background: rgba(237, 137, 54, 0.12); z-index: 9999; } .selection-bounds-key { display: flex; flex-direction: column; gap: 4px; padding: 8px 12px; font-size: 12px; font-family: monospace; pointer-events: none; } .selection-bounds-key-item { display: flex; align-items: center; gap: 6px; } .selection-bounds-key-swatch { width: 16px; height: 10px; border-radius: 2px; } .selection-bounds-key-swatch--axis { border: 2px dashed rgba(45, 116, 255, 0.95); background: rgba(45, 116, 255, 0.08); } .selection-bounds-key-swatch--rotated { border: 2px solid rgba(237, 137, 54, 0.95); background: rgba(237, 137, 54, 0.12); } ``` -------- # Easter egg styles Category: Editor API Keywords: easter egg, white, color, fill, lined-fill, label, scale, hidden styles, keyboard shortcuts Set style values that are hidden or hard to find in the default style panel. Several style values are valid on shapes but are not prominent in the default UI. Some have keyboard shortcuts; all can be set through the shape's props: - **White** color (`Alt+T`), which the color picker leaves out - **Fill** (`Alt+F`), a solid fill in the shape's full color, and **lined fill** (`Alt+Shift+F`), a slightly lighter solid variant, both in the fill picker's overflow dropdown - **Label color**, a separate color for a shape's label text, with no picker at all - **Scale**, a multiplier for stroke width and text size that the "Dynamic size" preference sets automatically The example creates one shape for each. Try selecting a shape and pressing the shortcuts to see the styles change. ## App.tsx ```tsx import { Tldraw, toRichText } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! export default function EasterEggStylesExample() { return (
{ editor.createShapes([ // [1] { type: 'geo', x: 0, y: 0, props: { geo: 'rectangle', w: 250, h: 250, color: 'blue', fill: 'fill', richText: toRichText('Fill\n(Alt+F)'), }, }, { type: 'geo', x: 300, y: 0, props: { geo: 'rectangle', w: 250, h: 250, color: 'blue', fill: 'lined-fill', richText: toRichText('Lined fill\n(Alt+Shift+F)'), }, }, // [2] { type: 'geo', x: 600, y: 0, props: { geo: 'rectangle', w: 250, h: 250, color: 'white', fill: 'fill', richText: toRichText('White\n(Alt+T)'), }, }, // [3] { type: 'geo', x: 900, y: 0, props: { geo: 'rectangle', w: 250, h: 250, color: 'blue', richText: toRichText('Label color'), labelColor: 'red', }, }, // [4] { type: 'geo', x: 1200, y: 0, props: { geo: 'rectangle', w: 250, h: 250, color: 'blue', scale: 2.5, richText: toRichText('Scale'), }, }, ]) editor.zoomToFit() }} />
) } /* Some style values are valid on shapes but are hidden or hard to find in the default style panel. They can still be set programmatically or, for some, with a keyboard shortcut. [1] `fill: 'fill'` (Alt+F) is a solid fill in the shape's full color rather than the tinted 'solid' fill; `fill: 'lined-fill'` (Alt+Shift+F) is a slightly lighter solid variant. Both are tucked away in the fill picker's overflow dropdown. [2] `color: 'white'` (Alt+T) is a white color option not shown in the color picker. [3] `labelColor` sets the label text color independently of the shape's `color`. The default style panel has no picker for it, so it can only be set programmatically. [4] `scale` multiplies the shape's stroke width and text size without changing `w`/`h`. The "Dynamic size" preference sets it automatically based on zoom when creating shapes; here it's set directly. */ ``` -------- # Add a tool to the toolbar Category: UI & theming Keywords: custom tool, toolbar, icon, asset urls, keyboard shortcuts dialog, defaulttoolbar, tldrawuimenuitem, useistoolselected, usetools, components Add a custom tool to the toolbar with its own icon and keyboard shortcut. To make a custom tool appear on tldraw's toolbar you need four things: register the tool item in the UI's tools context with the `tools` override, override the `Toolbar` component to render a `TldrawUiMenuItem` for it, override the `KeyboardShortcutsDialog` so its shortcut appears in the dialog, and pass an `assetUrls` entry for the tool's icon. The sticker tool is selected on load. Click on the canvas to drop a heart, or press `S` to switch back to it after using another tool. For more information on how to implement custom tools, check out the custom tool example. ## App.tsx ```tsx import { DefaultKeyboardShortcutsDialog, DefaultKeyboardShortcutsDialogContent, DefaultToolbar, DefaultToolbarContent, TLComponents, TLUiAssetUrlOverrides, TLUiOverrides, Tldraw, TldrawUiMenuItem, useIsToolSelected, useTools, } from 'tldraw' import 'tldraw/tldraw.css' import { StickerTool } from './sticker-tool-util' // There's a guide at the bottom of this file! // [1] const uiOverrides: TLUiOverrides = { tools(editor, tools) { tools.sticker = { id: 'sticker', icon: 'heart-icon', label: 'Sticker', kbd: 's', onSelect: () => { editor.setCurrentTool('sticker') }, } return tools }, } // [2] const components: TLComponents = { Toolbar: (props) => { const tools = useTools() const isStickerSelected = useIsToolSelected(tools['sticker']) return ( ) }, // [3] KeyboardShortcutsDialog: (props) => { const tools = useTools() return ( {/* Ideally, we'd interleave this into the tools group */} ) }, } // [4] export const customAssetUrls: TLUiAssetUrlOverrides = { icons: { 'heart-icon': '/heart-icon.svg', }, } // [5] const customTools = [StickerTool] export default function ToolInToolbarExample() { return (
) } /* Introduction: You can make an icon for your custom tool appear on tldraw's toolbar. To do this you need to add the tool to the UI's tools context, override the toolbar component, optionally add the tool to the keyboard shortcuts dialog, and pass in an asset URL for its icon. For more information on how to implement custom tools, check out the custom tool example. [1] The `tools` override adds a tool item to the UI's tools context. The item describes how the tool appears in menus (icon, label, keyboard shortcut) and what happens when it's selected. This is separate from the `StateNode` class that implements the tool's behavior; the UI needs both. [2] Override the `Toolbar` component so we can place our tool in it. `DefaultToolbar` provides the toolbar chrome and `DefaultToolbarContent` renders the built-in tools, so we render our own `TldrawUiMenuItem` before it. `useIsToolSelected` lets the button show as active when the sticker tool is the current tool. [3] The keyboard shortcuts dialog doesn't know about custom tools, so we override it and append our tool after `DefaultKeyboardShortcutsDialogContent`. This makes the tool's shortcut show up in the dialog. [4] The tool item references an icon named `heart-icon`, so we tell the UI where to find that icon via the `assetUrls` prop. Any icon name that isn't a built-in tldraw icon needs an entry here. [5] Define the tools array outside the component so it's a stable reference. We pass the tools, overrides, components, and asset URLs to the `Tldraw` component, and set `initialState="sticker"` so the tool is selected on load. */ ``` ## sticker-tool-util.tsx ```tsx import { StateNode, toRichText } from 'tldraw' // Check out the custom tool example for a more detailed explanation of the tool class. const OFFSET = 12 export class StickerTool extends StateNode { static override id = 'sticker' override onEnter() { this.editor.setCursor({ type: 'cross', rotation: 0 }) } override onPointerDown() { const currentPagePoint = this.editor.inputs.getCurrentPagePoint() this.editor.createShape({ type: 'text', x: currentPagePoint.x - OFFSET, y: currentPagePoint.y - OFFSET, props: { richText: toRichText('❤️') }, }) } } ``` -------- # Remove a tool from the toolbar Category: UI & theming Keywords: hide tool, remove tool, overrides, customization, toolbar customization, disable tool, tool visibility Remove the text tool from the toolbar and keyboard shortcuts with a `tools` override. The `tools` override in `TLUiOverrides` receives the map of UI tool items and returns the one the UI should use. Deleting an entry removes that tool from the toolbar, its keyboard shortcut, and the keyboard shortcuts dialog. The tool is still registered with the editor, so it can be activated programmatically with `editor.setCurrentTool`. Here we remove the text tool; try pressing `T` and note that nothing happens. ## App.tsx ```tsx import { TLUiOverrides, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // [1] const overrides: TLUiOverrides = { tools(_editor, tools) { delete tools.text return tools }, } export default function RemoveToolExample() { return (
) } /* [1] The `tools` override receives the map of UI tool items and returns the map the UI should use. Deleting an entry removes the tool from the toolbar, its keyboard shortcut, and the keyboard shortcuts dialog. The tool itself is still registered with the editor, so `editor.setCurrentTool('text')` still works. Define the overrides object outside the component (or memoize it) so the UI doesn't rebuild on every render. */ ``` -------- # Change default colors Category: UI & theming Keywords: colors, colours, theme, palette, style panel, defaultcolorstyle, color values, theming, customization Change the values in tldraw's default color palette with `editor.updateTheme()`. Get the current theme with `editor.getTheme()`, change the color values you want, and pass the result to `editor.updateTheme()`. Here the "black" color renders as aqua in light mode. Try drawing something with the default color to see the change. To add or remove colors, or to register additional named themes, see the custom theme and multiple themes examples. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! export default function ChangingDefaultColorsExample() { return (
{/* [1] */} { const theme = editor.getTheme('default')! editor.updateTheme({ ...theme, colors: { ...theme.colors, light: { ...theme.colors.light, black: { ...theme.colors.light.black, solid: 'aqua' }, }, }, }) }} />
) } /* [1] Use `editor.updateTheme()` to change a theme's color palette. Get the current theme with `editor.getTheme()`, copy it with the values you want changed, and pass it back. Here we make the "black" color's solid value aqua in light mode. Changing values this way keeps the set of color names the same, so existing shapes (and other users in a multiplayer session) keep working. To add or remove colors, or register additional named themes, see the custom theme and multiple themes examples. */ ``` -------- # Change default styles Category: UI & theming Keywords: styles, default style, style props, size, color, dash, fill, setdefaultvalue Change the default value of a style prop with `setDefaultValue`. Every style prop has a built-in default value: new shapes use `m` for size, `black` for color, and so on. Call `setDefaultValue` on the style prop to change it. In this example the size style defaults to `s`, so newly created shapes are small. Call `setDefaultValue` at module level, before any editor is created, so the change applies everywhere the style is used. ## App.tsx ```tsx import { DefaultSizeStyle, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // Call this at module level, before any editor is created, so every editor // (and every new shape) picks up the new default. DefaultSizeStyle.setDefaultValue('s') export default function ChangingDefaultStyleExample() { return (
) } ``` -------- # Changing menus Category: UI & theming Keywords: menu, toolbar, context menu, main menu, page menu, ActionsMenu, DebugMenu, HelpMenu, StylePanel, QuickActions, ZoomMenu, components, TldrawUiMenuItem Add items to every one of tldraw's menus, including the toolbar, main menu, context menu, and page menu. Use the `components` prop to override tldraw's default menus. You can provide a React component of your own, import the default component and add to it, or return `null` to hide it completely. Each default menu comes as a pair, for example `DefaultMainMenu` and `DefaultMainMenuContent`, so you can wrap the default content with your own items. This example customizes every menu in tldraw: - Toolbar - Main menu - Context menu - Page menu - Actions menu - Debug menu - Help menu - Keyboard shortcuts dialog - Navigation panel - Quick actions panel - Style panel - Zoom menu The custom additions are highlighted in thistle so they're easy to spot. ## App.tsx ```tsx import { DefaultActionsMenu, DefaultActionsMenuContent, DefaultColorStyle, DefaultContextMenu, DefaultContextMenuContent, DefaultDebugMenu, DefaultDebugMenuContent, DefaultHelpMenu, DefaultHelpMenuContent, DefaultKeyboardShortcutsDialog, DefaultKeyboardShortcutsDialogContent, DefaultMainMenu, DefaultMainMenuContent, DefaultPageMenu, DefaultQuickActions, DefaultQuickActionsContent, DefaultStylePanel, DefaultStylePanelContent, DefaultToolbar, DefaultToolbarContent, DefaultZoomMenu, DefaultZoomMenuContent, TLComponents, Tldraw, TldrawUiButton, TldrawUiButtonLabel, TldrawUiMenuGroup, TldrawUiMenuItem, TldrawUiToolbar, TLUiContextMenuProps, TLUiKeyboardShortcutsDialogProps, TLUiStylePanelProps, useEditor, useIsToolSelected, useTldrawUiComponents, useTools, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] function CustomActionsMenu() { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } // [2] function CustomContextMenu(props: TLUiContextMenuProps) { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } // [3] function CustomDebugMenu() { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } // [4] function CustomHelpMenu() { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } // [5] function CustomKeyboardShortcutsDialog(props: TLUiKeyboardShortcutsDialogProps) { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } // [6] function CustomMainMenu() { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } // [7] function CustomNavigationPanel() { const { ZoomMenu } = useTldrawUiComponents() return (
here you are {ZoomMenu && }
) } // [8] function CustomPageMenu() { return (
) } // [9] function CustomQuickActions() { return (
window.alert('code')} />
) } // [10] function CustomStylePanel(props: TLUiStylePanelProps) { const editor = useEditor() return (
{ editor.setStyleForSelectedShapes(DefaultColorStyle, 'red') }} > Red
{ editor.setStyleForSelectedShapes(DefaultColorStyle, 'green') }} > Green
) } // [11] function CustomToolbar() { const editor = useEditor() const tools = useTools() const isRhombusSelected = useIsToolSelected(tools['rhombus-2']) return ( { editor.selectAll().deleteShapes(editor.getSelectedShapeIds()) }} title="Delete all" > 🧨 ) } // [12] function CustomZoomMenu() { return (
{ window.open('https://x.com/tldraw', '_blank') }} />
) } const components: TLComponents = { ActionsMenu: CustomActionsMenu, ContextMenu: CustomContextMenu, DebugMenu: CustomDebugMenu, HelpMenu: CustomHelpMenu, KeyboardShortcutsDialog: CustomKeyboardShortcutsDialog, MainMenu: CustomMainMenu, NavigationPanel: CustomNavigationPanel, PageMenu: CustomPageMenu, QuickActions: CustomQuickActions, StylePanel: CustomStylePanel, Toolbar: CustomToolbar, ZoomMenu: CustomZoomMenu, } export default function CustomMenusExample() { return (
) } /* You can use the `components` prop to override tldraw's default menus. You can provide a React component of your own, import our default component and add to it, or return null to hide it completely. This example does this with every menu in tldraw. The thistle-colored areas mark the custom additions. [1] The actions menu is a dropdown found in the top-left of the tldraw component, or just above the toolbar on smaller screens. It contains actions related to editing shapes such as grouping, rotating, or changing shape order. [2] Create some shapes, select them, and right click the selection to see the custom context menu. [3] The debug menu contains helpful menu items for debugging the tldraw component. To show it, turn on debug mode in the preferences. [4] The help menu contains menu items to change the language of the application and to open the keyboard shortcuts dialog. [5] The keyboard shortcuts dialog is a modal that lists all the keyboard shortcuts available in tldraw. You can open it via the help menu. [6] The main menu contains the Edit, Shape, and Preferences submenus, among others. To open it, click the hamburger icon in the top left corner of the tldraw component. [7] The navigation panel is in the bottom left of the tldraw component at larger breakpoints. It normally contains the zoom menu and a minimap. Replacing it drops the zoom menu too, so this one renders `ZoomMenu` from `useTldrawUiComponents` to keep [12] reachable. The zoom menu's trigger is a toolbar button, so it has to sit inside a `TldrawUiToolbar`. [8] The page menu contains options for creating and editing pages. To open it, click the page name in the top left of the tldraw component. [9] The quick actions menu appears next to the main menu, or above the toolbar on smaller screens. [10] The style panel appears on the right side of the tldraw component. It contains options to change the style of shapes, such as color, stroke width, and opacity. [11] The toolbar contains the tools used to create and select shapes. Here we add the left-leaning rhombus geo shape at the front and a "delete all" button at the end. There is no `tool.rhombus-2` translation key, so the item reuses the style panel's `geo-style.rhombus-2` label. [12] The zoom menu is in the bottom left of the tldraw component. The button that opens it is labeled with a percentage indicating the editor's current zoom level. */ ``` -------- # Format rich text on multiple shapes Category: UI & theming Keywords: rich text, formatting, batch edit, multiple shapes, style panel, bold, marks, programmatic formatting, tlrichtext, document traversal Add a style panel button that bolds (or unbolds) all the text in every selected shape at once. Rich text in tldraw is a TipTap (ProseMirror) JSON document stored in `shape.props.richText`. Each text node can carry a `marks` array, and bold is represented as `{ type: 'bold' }`. This example walks that document with three small helpers, `makeAllTextBold`, `removeBoldFromAllText`, and `isAllTextBold`, and writes the result back with `editor.updateShapes`. The button lives in a custom `StylePanel` that wraps `DefaultStylePanel`. It reads the selection with `useValue`, so it enables itself whenever any selected shape has rich text and shows as active when every text node is already bold. Try selecting a mix of text, geo, and note shapes and toggling the button. For the same idea built on ProseMirror's `Node` API (bold, italic, and highlight, including shapes nested inside frames and groups), see the [text mass style updates](https://tldraw.dev/examples/text-mass-style-updates) example. ## App.tsx ```tsx import { DefaultStylePanel, DefaultStylePanelContent, ExtractShapeByProps, TLComponents, TLRichText, TLShape, TLUiStylePanelProps, Tldraw, TldrawUiButton, TldrawUiButtonIcon, TldrawUiButtonLabel, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' type ShapeWithRichText = ExtractShapeByProps<{ richText: TLRichText }> function isShapeWithRichText(shape: TLShape | null | undefined): shape is ShapeWithRichText { return !!(shape && 'richText' in shape.props) } // [1] function makeAllTextBold(richText: TLRichText): TLRichText { if (!richText || !richText.content) { return richText } const processNode = (node: any): any => { if (node.type === 'text') { const hasBold = node.marks?.some((mark: any) => mark.type === 'bold') if (hasBold) { return node } return { ...node, marks: [...(node.marks || []), { type: 'bold' }], } } if (node.content && Array.isArray(node.content)) { return { ...node, content: node.content.map(processNode), } } return node } return { ...richText, content: richText.content.map(processNode), } } function isAllTextBold(richText: TLRichText): boolean { if (!richText || !richText.content) { return false } const checkNode = (node: any): boolean => { if (node.type === 'text') { return node.marks?.some((mark: any) => mark.type === 'bold') ?? false } if (node.content && Array.isArray(node.content)) { return node.content.every(checkNode) } // Leaf nodes without text (hard breaks, etc.) have nothing to bold return true } return richText.content.every(checkNode) } function removeBoldFromAllText(richText: TLRichText): TLRichText { if (!richText || !richText.content) { return richText } const processNode = (node: any): any => { if (node.type === 'text') { const marks = node.marks?.filter((mark: any) => mark.type !== 'bold') || [] return { ...node, marks: marks.length > 0 ? marks : undefined, } } if (node.content && Array.isArray(node.content)) { return { ...node, content: node.content.map(processNode), } } return node } return { ...richText, content: richText.content.map(processNode), } } // [2] function CustomStylePanel(props: TLUiStylePanelProps) { const editor = useEditor() const shapesWithRichText = useValue( 'shapes with rich text', () => editor.getSelectedShapes().filter(isShapeWithRichText), [editor] ) const hasRichTextSelection = shapesWithRichText.length > 0 const allBold = hasRichTextSelection && shapesWithRichText.every((shape) => isAllTextBold(shape.props.richText)) const handleToggleBold = () => { if (!hasRichTextSelection) return // [3] editor.run(() => { editor.markHistoryStoppingPoint('toggle bold') editor.updateShapes( shapesWithRichText.map((shape) => ({ id: shape.id, type: shape.type, props: { richText: allBold ? removeBoldFromAllText(shape.props.richText) : makeAllTextBold(shape.props.richText), }, })) ) }) } return (
Bold all text
) } const components: TLComponents = { StylePanel: CustomStylePanel, } export default function RichTextFormatOnMultipleShapesExample() { return (
) } /* This example adds a "Bold all text" toggle to the style panel that applies to every selected shape with rich text at once. Rich text in tldraw is a TipTap (ProseMirror) JSON document; each text node can carry a `marks` array such as `[{ type: 'bold' }]`. Here we walk that JSON directly. For a version that uses ProseMirror's Node API instead, see the "Text mass style updates" example. [1] The helpers recursively map over the document, adding or removing the bold mark on text nodes and leaving the structure untouched. `isAllTextBold` is the inverse check that decides whether the button should add or remove bold. [2] `ExtractShapeByProps<{ richText: TLRichText }>` narrows to any shape whose props include rich text (text, geo, note, arrow), so the panel works across shape types. Reading the selection inside `useValue` keeps the button state in sync as the selection or the shapes' text changes. [3] `editor.updateShapes` applies all the changes in one go, and the history stopping point makes the whole toggle a single undo step. Shapes are never mutated directly; we always pass a new `richText` object through the editor. */ ``` -------- # Custom theme Category: UI & theming Keywords: theme, brand, custom, colors, fonts, dark mode, light mode, palette, updatetheme Add custom colors and fonts to the theme, remove built-in ones, and adjust theme values at runtime. Pass a `themes` prop to `` to replace the default theme. This example adds a "pink" color and two custom fonts (a bundled pixel font and a remote Google Font), removes the "light-\*" colors and the serif font, and adds translations so the style panel shows readable names. Custom color and font names are declared to TypeScript via module augmentation of `TLThemeDefaultColors`, `TLThemeFonts`, and `TLRemovedDefaultThemeColors`. The sliders in the bottom right change the theme's `fontSize`, `lineHeight`, and `strokeWidth` at runtime with `editor.updateTheme()`. Draw some shapes and drag the stroke width slider to see them update. To register additional named themes and switch between them, see the multiple themes example. ## App.tsx ```tsx import { useCallback, useEffect, useRef, useState } from 'react' import { DEFAULT_THEME, Editor, TLDefaultColor, TLTheme, TLThemeFont, TLThemes, TLUiOverrides, Tldraw, TldrawUiButton, TldrawUiButtonLabel, toRichText, } from 'tldraw' import 'tldraw/tldraw.css' import silkscreenBoldUrl from './custom-font/Silkscreen-Bold.ttf' import silkscreenRegularUrl from './custom-font/Silkscreen-Regular.ttf' import './custom-theme.css' // [1] declare module '@tldraw/tlschema' { interface TLThemeDefaultColors { pink: TLDefaultColor } interface TLThemeFonts { pixel: TLThemeFont cursive: TLThemeFont } // [2] interface TLRemovedDefaultThemeColors { 'light-violet': true 'light-blue': true 'light-green': true 'light-red': true } } // Helper to create a full color entry from a base solid color function makeColor(solid: string, semi: string, pattern: string): TLDefaultColor { return { solid, semi, pattern, fill: solid, linedFill: semi, frameHeadingStroke: solid, frameHeadingFill: semi, frameStroke: solid, frameFill: semi, frameText: solid, noteFill: semi, noteText: solid, highlightSrgb: solid, highlightP3: solid, } } // [3] const pinkLight = makeColor('#e91e8c', '#fce4f2', '#f06baf') const pinkDark = makeColor('#f06baf', '#3d1a2e', '#e91e8c') // [4] const pixelFont: TLThemeFont = { fontFamily: "'Silkscreen', sans-serif", icon:
Aa
, faces: [ { family: 'Silkscreen', src: { url: silkscreenRegularUrl }, weight: 'normal', style: 'normal', }, { family: 'Silkscreen', src: { url: silkscreenBoldUrl }, weight: 'bold', style: 'normal', }, ], } // Custom font — use a Google Font loaded via full URLs. These versioned // gstatic URLs expire when Google revs the font; refresh them from // https://fonts.googleapis.com/css2?family=Comic+Neue:wght@400;700 if they 404. const cursiveFont: TLThemeFont = { fontFamily: "'Comic Neue', cursive", icon:
Aa
, faces: [ { family: 'Comic Neue', src: { url: 'https://fonts.gstatic.com/s/comicneue/v9/4UaHrEJDsxBrF37olUeD96rp57F2IwM.woff2', format: 'woff2', }, weight: 'normal', style: 'normal', }, { family: 'Comic Neue', src: { url: 'https://fonts.gstatic.com/s/comicneue/v9/4UaErEJDsxBrF37olUeD_xHM8pxULilENlY.woff2', format: 'woff2', }, weight: 'bold', style: 'normal', }, ], } // [5] const { serif: _serif, ...keptFonts } = DEFAULT_THEME.fonts const customFonts = { ...keptFonts, pixel: pixelFont, cursive: cursiveFont } as TLTheme['fonts'] // [6] function colorsWithoutLightVariants(base: Record, pink: TLDefaultColor) { const { 'light-violet': _lv, 'light-blue': _lb, 'light-green': _lg, 'light-red': _lr, ...kept } = base return { ...kept, pink } as TLTheme['colors']['light'] } // [7] const uiOverrides: TLUiOverrides = { translations: { en: { 'color-style.pink': 'Pink', 'font-style.pixel': 'Pixel', 'font-style.cursive': 'Cursive', }, }, } // [8] const DEFAULTS = { fontSize: 16, lineHeight: 1.35, strokeWidth: 2, } // [9] const themes: Partial = { default: { id: 'default', fontSize: DEFAULTS.fontSize, lineHeight: DEFAULTS.lineHeight, strokeWidth: DEFAULTS.strokeWidth, fonts: customFonts, colors: { light: colorsWithoutLightVariants(DEFAULT_THEME.colors.light, pinkLight), dark: colorsWithoutLightVariants(DEFAULT_THEME.colors.dark, pinkDark), }, }, } export default function CustomThemeExample() { const [fontSize, setFontSize] = useState(DEFAULTS.fontSize) const [lineHeight, setLineHeight] = useState(DEFAULTS.lineHeight) const [strokeWidth, setStrokeWidth] = useState(DEFAULTS.strokeWidth) const editorRef = useRef(null) // Apply slider values to the theme programmatically. Rather than passing // a new `themes` object whenever a value changes (which would recreate the // store and reload the canvas from persistence), we update the existing // "default" theme in place via `editor.updateTheme()`. Spreading the current // theme preserves the custom colors and fonts while overriding the adjusted // values. Shapes re-render reactively without the board flashing. useEffect(() => { const editor = editorRef.current if (!editor) return editor.updateTheme({ ...editor.getTheme('default')!, fontSize, lineHeight, strokeWidth }) }, [fontSize, lineHeight, strokeWidth]) return (
{ editorRef.current = editor if (editor.getCurrentPageShapeIds().size > 0) return editor.createShape({ type: 'geo', x: 100, y: 100, props: { w: 200, h: 200, color: 'red' }, }) editor.createShape({ type: 'geo', x: 350, y: 100, props: { w: 200, h: 200, color: 'blue', geo: 'ellipse', richText: toRichText('Hello'), }, }) // [10] editor.createShape({ type: 'geo', x: 600, y: 100, props: { w: 200, h: 200, color: 'pink', geo: 'diamond' }, }) editor.createShape({ type: 'text', x: 100, y: 350, props: { richText: toRichText('Theme text'), size: 'l' }, }) // [11] editor.createShape({ type: 'text', x: 350, y: 350, props: { richText: toRichText('Pixel font!'), size: 'l', font: 'pixel' }, }) editor.createShape({ type: 'text', x: 600, y: 350, props: { richText: toRichText('Cursive font!'), size: 'l', font: 'cursive' }, }) editor.createShape({ type: 'note', x: 100, y: 500, props: { color: 'black', richText: toRichText('A sticky note'), }, }) }} >
) } // [12] function ThemeControls({ fontSize, onFontSizeChange, lineHeight, onLineHeightChange, strokeWidth, onStrokeWidthChange, }: { fontSize: number onFontSizeChange(v: number): void lineHeight: number onLineHeightChange(v: number): void strokeWidth: number onStrokeWidthChange(v: number): void }) { return (
e.stopPropagation()}> { onFontSizeChange(DEFAULTS.fontSize) onLineHeightChange(DEFAULTS.lineHeight) onStrokeWidthChange(DEFAULTS.strokeWidth) }} > Reset to defaults
) } function ThemeSlider({ label, value, onChange, min, max, step, defaultValue, }: { label: string value: number onChange(v: number): void min: number max: number step: number defaultValue: number }) { const [localValue, setLocalValue] = useState(value) const isDragging = useRef(false) // sync from parent when not actively dragging if (!isDragging.current && localValue !== value) { setLocalValue(value) } const isDefault = localValue === defaultValue const handleInput = useCallback((e: React.ChangeEvent) => { isDragging.current = true setLocalValue(Number(e.target.value)) }, []) const handleCommit = useCallback(() => { if (!isDragging.current) return isDragging.current = false onChange(localValue) }, [onChange, localValue]) return (
{label} {localValue % 1 === 0 ? localValue : localValue.toFixed(2)}
) } /* [1] Extend the `TLThemeDefaultColors` and `TLThemeFonts` interfaces via module augmentation so TypeScript knows about the custom "pink" color and the "pixel" and "cursive" fonts. Because `themes` is passed to ``, the names are registered with the style enums automatically at store creation. [2] Extend `TLRemovedDefaultThemeColors` to remove built-in colors from the type. This is the type-level half of removing the "light-*" variants; [6] removes them from the theme values. [3] Define color entries for light and dark variants. Each theme needs a full `TLDefaultColor` entry for the custom color in both palettes. [4] A custom font has a `fontFamily` CSS string and, for fonts that need loading, a `faces` array of `TLFontFace` entries pointing at the font files (here bundled locally via import; the cursive font below uses remote URLs). System fonts like Arial or Georgia can omit `faces`. The `icon` field is the React element the style panel uses as the button for this font; here "Aa" rendered in the font itself. [5] Remove a built-in font: destructure "serif" out of the default font palette and spread the rest. The serif option disappears from the style panel and the two custom fonts take its place. [6] Remove built-in colors: destructure the "light-*" variants out of the default palette. They won't appear in the style panel, and "pink" is added in their place. [7] Translation overrides provide human-readable names for custom style values. Without these, the tooltip for "pink" would show the raw key "color-style.pink". [8] Default values for the adjustable theme properties. These match `DEFAULT_THEME`. [9] The `themes` prop is a stable object passed once to ``. It registers the custom color and fonts at store creation and seeds the starting values. Slider adjustments are applied at runtime with `editor.updateTheme()` rather than by passing a new `themes` prop, because a new object would recreate the store and reload the canvas from persistence. `updateTheme` updates the active theme reactively, so shapes re-render immediately. Which palette (light or dark) is used follows the user's color scheme preference. [10] Create a shape using the custom "pink" color. Because the theme declares the color, it passes validation. [11] Create shapes using the custom "pixel" and "cursive" fonts. They show up in the style panel alongside the remaining built-in fonts (draw, sans, mono). [12] A panel with sliders for `fontSize`, `lineHeight`, and `strokeWidth`. Try drawing some shapes with different sizes and then moving the stroke width slider to see how theme values affect shape rendering. */ ``` ## custom-theme.css ```css .custom-theme-toolbar { pointer-events: all; display: flex; flex-direction: column; gap: 16px; padding: 8px; bottom: 56px; right: 8px; width: 200px; position: absolute; height: fit-content; } .custom-theme-slider { display: flex; flex-direction: column; gap: 4px; } .custom-theme-slider__header { display: flex; justify-content: space-between; align-items: baseline; } .custom-theme-slider__label { white-space: nowrap; } .custom-theme-slider__value { font-variant-numeric: tabular-nums; min-width: 36px; text-align: right; } .custom-theme-slider__value[data-default='true'] { opacity: 0.5; } .custom-theme-slider input[type='range'] { width: 100%; margin: 0; accent-color: var(--color-selected); } ``` -------- # Multiple themes Category: UI & theming Keywords: theme, themes, brand, custom, module augmentation, TLThemes, switch, setcurrenttheme Register several named themes and switch between them at runtime. Themes are keyed by id in the `TLThemes` interface. Augment that interface with your theme ids so `editor.setCurrentTheme()` is type-checked, build each theme by cloning `DEFAULT_THEME` and overriding the colors you care about, and pass them to `` through the `themes` prop. Switch at runtime with `editor.setCurrentTheme(id)`; `editor.getCurrentThemeId()` is reactive. Try clicking the theme buttons at the top left. The blue rectangle and violet note recolor because those palette entries differ between the themes. ## App.tsx ```tsx import { DEFAULT_THEME, Editor, TLTheme, TLThemeId, TLThemes, Tldraw, TldrawUiButton, TldrawUiButtonLabel, structuredClone, toRichText, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './multiple-themes.css' // There's a guide at the bottom of this file! // [1] declare module '@tldraw/tlschema' { interface TLThemes { ocean: TLTheme sunset: TLTheme } } // [2] const OCEAN_THEME: TLTheme = structuredClone(DEFAULT_THEME) OCEAN_THEME.id = 'ocean' OCEAN_THEME.colors.light.blue.solid = '#2b7ab5' OCEAN_THEME.colors.light.violet.solid = '#6a5acd' OCEAN_THEME.colors.light.violet.noteFill = '#b8a9e8' OCEAN_THEME.colors.light.violet.noteText = '#000000' OCEAN_THEME.colors.dark.blue.solid = '#3a9bd5' OCEAN_THEME.colors.dark.violet.solid = '#7b6bd4' OCEAN_THEME.colors.dark.violet.noteFill = '#3a2d6e' OCEAN_THEME.colors.dark.violet.noteText = '#f2f2f2' const SUNSET_THEME: TLTheme = structuredClone(DEFAULT_THEME) SUNSET_THEME.id = 'sunset' SUNSET_THEME.colors.light.blue.solid = '#e07038' SUNSET_THEME.colors.light.violet.solid = '#9b4dca' SUNSET_THEME.colors.light.violet.noteFill = '#dab0f0' SUNSET_THEME.colors.light.violet.noteText = '#000000' SUNSET_THEME.colors.dark.blue.solid = '#f0884a' SUNSET_THEME.colors.dark.violet.solid = '#b060d8' SUNSET_THEME.colors.dark.violet.noteFill = '#5c2870' SUNSET_THEME.colors.dark.violet.noteText = '#f2f2f2' // [3] const themes: Partial = { ocean: OCEAN_THEME, sunset: SUNSET_THEME, } function createInitialShapes(editor: Editor) { if (editor.getCurrentPageShapeIds().size > 0) return editor.createShapes([ { type: 'geo', x: 100, y: 100, props: { w: 200, h: 200, color: 'blue', richText: toRichText('Try switching themes') }, }, { type: 'note', x: 350, y: 100, props: { color: 'violet', richText: toRichText('Colors change per theme') }, }, ]) } export default function MultipleThemesExample() { return (
{/* [4] */}
) } // [5] const THEME_LABELS: Record = { default: 'Default', ocean: 'Ocean', sunset: 'Sunset', } function ThemeSwitcher() { const editor = useEditor() const currentThemeId = useValue('themeId', () => editor.getCurrentThemeId(), [editor]) return (
{(Object.keys(THEME_LABELS) as TLThemeId[]).map((id) => ( editor.setCurrentTheme(id)} > {THEME_LABELS[id]} ))}
) } /* [1] Extend the `TLThemes` interface to register custom theme IDs. This gives you type-safe theme names throughout the API — `editor.setCurrentTheme('ocean')` will autocomplete, and passing an unregistered name will be a type error. [2] Define theme objects by cloning `DEFAULT_THEME` and overriding just the colors you want to change. Each theme contains both `light` and `dark` color palettes. [3] Collect the themes in a `Partial`. The `default` theme is always registered, so only the additional themes need to be listed. Keep this object at module level: it's a prop of ``, and a new object each render would re-register the themes. [4] `` registers the `themes` at mount time and keeps them updated if the prop changes. You can also register or update themes later with `editor.updateTheme()`. [5] `editor.setCurrentTheme(id)` switches theme at runtime and `editor.getCurrentThemeId()` is reactive, so reading it in `useValue` keeps the active button highlighted. */ ``` ## multiple-themes.css ```css .theme-switcher { position: absolute; top: 60px; left: 12px; display: flex; gap: 4px; padding: 4px; pointer-events: all; } ``` -------- # Hide UI components Category: UI & theming Keywords: hide ui, components override, minimal ui, headless, remove ui, TLUiComponents, null components Hide any built-in UI component by setting its slot to `null`. Every part of the default UI is a slot in `TLUiComponents`. Passing `null` for a slot removes it. This example sets every slot to `null` so you can see the full list; in practice you'd only null out the pieces you want gone. Hiding `Toasts`, `Dialogs`, or `A11y` also disables the features that render through them. To remove the whole UI at once, use the `hideUi` prop instead. ## App.tsx ```tsx import { TLUiComponents, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // [1] const components: Required = { ContextMenu: null, ActionsMenu: null, HelpMenu: null, ZoomMenu: null, MainMenu: null, Minimap: null, StylePanel: null, PageMenu: null, NavigationPanel: null, Toolbar: null, KeyboardShortcutsDialog: null, QuickActions: null, HelperButtons: null, DebugPanel: null, DebugMenu: null, SharePanel: null, MenuPanel: null, TopPanel: null, CursorChatBubble: null, RichTextToolbar: null, ImageToolbar: null, VideoToolbar: null, Dialogs: null, Toasts: null, A11y: null, FollowingIndicator: null, PeopleMenu: null, PeopleMenuAvatar: null, PeopleMenuItem: null, PeopleMenuFacePile: null, UserPresenceEditor: null, } export default function UiComponentsHiddenExample() { return (
) } /* [1] Setting a slot to `null` removes that part of the UI. Set only the slots you want to hide; the `Required<>` type is here so this example lists every slot, which is handy as a reference. Hiding `Toasts`, `Dialogs`, or `A11y` also disables the features that render through them (toast notifications, dialogs like the keyboard shortcuts panel, and screen reader announcements). To hide everything at once, use the `hideUi` prop instead. */ ``` -------- # Menu system hover Category: UI & theming Keywords: menu, hover, dropdown, programmatic, control, editor.menus, addopenmenu, deleteopenmenu, usemenuisopen Open and close a dropdown menu from hover events using `editor.menus`. tldraw keeps track of open menus in `editor.menus`, keyed by id. The UI's dropdown primitives read that state, so you can open or close a menu from anywhere by writing to it: - `editor.menus.addOpenMenu(id)` opens a menu - `editor.menus.deleteOpenMenu(id)` closes it - `useMenuIsOpen(id)` subscribes to a menu's open state Try hovering the green-labeled zone to open the dropdown and the red-labeled zone to close it. Clicking the trigger button still works as usual. This is handy for hover-driven toolbars or for closing menus in response to events elsewhere in your app. ## App.tsx ```tsx import { Tldraw, TldrawUiButton, TldrawUiButtonLabel, TldrawUiDropdownMenuContent, TldrawUiDropdownMenuItem, TldrawUiDropdownMenuRoot, TldrawUiDropdownMenuTrigger, useEditor, useMenuIsOpen, } from 'tldraw' import 'tldraw/tldraw.css' import './menu-system-hover.css' // There's a guide at the bottom of this file! // [1] function HoverControlledMenu() { const editor = useEditor() const [isOpen] = useMenuIsOpen('hover-menu') return (
{/* [2] */}
editor.menus.addOpenMenu('hover-menu')} > Hover to open menu
{/* [3] */}
editor.menus.deleteOpenMenu('hover-menu')} > Hover to close menu
{/* [4] */} Menu {isOpen ? '(open)' : '(closed)'} Menu item 1 Menu item 2 Menu item 3
) } export default function MenuSystemHoverExample() { return (
) } /* tldraw tracks which menus are open in `editor.menus`, keyed by menu id. The dropdown primitives read and write that state, so anything else that writes it can open or close a menu too. Here two hover zones do exactly that. [1] `useMenuIsOpen(id)` returns `[isOpen, setIsOpen]` for a menu id and re-renders when the state changes. [2] `editor.menus.addOpenMenu('hover-menu')` marks the menu as open. The dropdown with the matching `id` responds by opening. [3] `editor.menus.deleteOpenMenu('hover-menu')` marks it closed again. [4] `TldrawUiDropdownMenuRoot` takes the same `id`, which is what links it to [2] and [3]. Clicking the trigger still toggles the menu the normal way. */ ``` ## menu-system-hover.css ```css .hover-menu-container { position: absolute; top: 100px; left: 0; display: flex; flex-direction: column; gap: var(--tl-space-3); padding: var(--tl-space-3); z-index: var(--tl-layer-panels); } .hover-zone { padding: var(--tl-space-3) var(--tl-space-5); border-radius: var(--tl-radius-2); font-size: 13px; font-weight: 500; cursor: default; user-select: none; transition: opacity 0.15s ease; background-color: var(--tl-color-low); pointer-events: auto; } .hover-zone:hover { opacity: 0.8; } .hover-zone-open { color: var(--tl-color-success); } .hover-zone-close { color: var(--tl-color-danger); } ``` -------- # Screen reader accessibility Category: UI & theming Keywords: accessibility, a11y, screen reader, aria, getariadescriptor, gettext, usea11y, announcements, aria live region, polite, assertive, wcag Make custom shapes describe themselves to screen readers, and announce messages from your own UI. When a shape is selected, tldraw announces it through an ARIA live region. The text comes from the shape util: `getAriaDescriptor()` first, falling back to `getText()`, followed by the shape type and its position in reading order. The card shape here overrides both methods, and a `translations` override gives the custom type a readable name (`tool.note-card`) for that announcement. The top panel shows the other half: `useA11y()` returns an `announce()` function you can call from any component inside ``. Use `priority: 'polite'` for confirmations and status updates that can wait, and `priority: 'assertive'` for errors that should interrupt. Try selecting a card with a screen reader running, then press the buttons. ## App.tsx ```tsx import { useState } from 'react' import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLComponents, Tldraw, TldrawUiButton, TLShape, TLUiOverrides, useA11y, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' import './screen-reader-accessibility.css' const CARD_SHAPE_TYPE = 'note-card' declare module 'tldraw' { export interface TLGlobalShapePropsMap { [CARD_SHAPE_TYPE]: { w: number; h: number; title: string; description: string } } } type CardShape = TLShape export class CardShapeUtil extends BaseBoxShapeUtil { static override type = CARD_SHAPE_TYPE static override props: RecordProps = { w: T.number, h: T.number, title: T.string, description: T.string, } getDefaultProps(): CardShape['props'] { return { w: 300, h: 180, title: 'Untitled', description: '', } } // [1] override getAriaDescriptor(shape: CardShape): string | undefined { const { title, description } = shape.props if (description) { return `${title} - ${description}` } return title } // [2] override getText(shape: CardShape): string | undefined { return `${shape.props.title}\n${shape.props.description}` } component(shape: CardShape) { const { title, description } = shape.props return (
{title}
{description &&
{description}
}
) } getIndicatorPath(shape: CardShape) { const path = new Path2D() path.rect(0, 0, shape.props.w, shape.props.h) return path } } const customShapes = [CardShapeUtil] // [3] const overrides: TLUiOverrides = { translations: { en: { [`tool.${CARD_SHAPE_TYPE}`]: 'Note card' }, }, } function CustomAnnouncementPanel() { const editor = useEditor() // [4] const a11y = useA11y() const [isEnabled, setIsEnabled] = useState(false) // [5] const handleActionConfirmation = () => { const selectedShapes = editor.getSelectedShapes() if (selectedShapes.length > 0) { a11y.announce({ msg: `Action completed for ${selectedShapes.length} shape${selectedShapes.length === 1 ? '' : 's'}`, priority: 'polite', }) } else { a11y.announce({ msg: 'No shapes selected', priority: 'polite', }) } } // [6] const handleValidation = () => { const selectedShapes = editor.getSelectedShapes() if (selectedShapes.length === 0) { a11y.announce({ msg: 'Validation failed: No shapes selected', priority: 'assertive', }) } else { const hasText = selectedShapes.some((shape) => { const util = editor.getShapeUtil(shape) return util.getText(shape) }) if (!hasText) { a11y.announce({ msg: 'Validation failed: Selected shapes must contain text', priority: 'assertive', }) } else { a11y.announce({ msg: 'Validation passed', priority: 'polite', }) } } } // [7] const handleToggle = () => { const newState = !isEnabled setIsEnabled(newState) a11y.announce({ msg: `Feature ${newState ? 'enabled' : 'disabled'}`, priority: 'polite', }) } return (
Perform action Validate selection {isEnabled ? 'Disable' : 'Enable'} feature
) } const components: TLComponents = { TopPanel: CustomAnnouncementPanel, } export default function ScreenReaderAccessibilityExample() { return (
{ // [8] editor.createShape({ type: CARD_SHAPE_TYPE, x: 100, y: 100, props: { title: 'Meeting Notes', description: 'Discussed Q4 planning and team goals', }, }) editor.createShape({ type: CARD_SHAPE_TYPE, x: 450, y: 100, props: { title: 'Project Ideas', description: 'Brainstorming session for new features', }, }) editor.createShape({ type: CARD_SHAPE_TYPE, x: 100, y: 320, props: { title: 'Action Items', description: 'Follow up with design team by Friday', }, }) }} />
) } /* This example shows two sides of screen reader support: making a custom shape describe itself when selected, and announcing your own messages from custom UI. [1] `getAriaDescriptor()` returns the text announced when the shape is selected. It's the place for an alt-text-style description that may differ from what's visibly rendered. If it returns nothing, the announcer falls back to `getText()`. [2] `getText()` returns the shape's visible text. The editor uses it for text extraction and search, and the announcer uses it as the fallback described in [1]. Returning it here also lets the "Validate selection" button below check whether the selected shapes have any text at all. [3] The selection announcement ends with the shape's type, looked up as `tool.` in the UI translations. Without an override a custom shape is announced by its raw key ("tool.note-card"), so we add a translation for it. [4] `useA11y()` returns the accessibility context. It must be called from a component rendered inside ``, such as this `TopPanel` component. [5] Polite announcements queue behind whatever the screen reader is currently saying. Use them for confirmations and status updates. [6] Assertive announcements interrupt the current speech. Reserve them for messages the user must hear now, like validation errors. [7] Announce state changes when the visible change alone (here, the button label flipping) wouldn't be noticed by a screen reader user. [8] Create three sample cards. Select one to hear the `getAriaDescriptor()` text, followed by the shape type and its index in reading order ("1 of 3"). The announcements render into an off-screen ARIA live region owned by the default `A11y` component, so nothing visible changes. */ ``` ## screen-reader-accessibility.css ```css .announcement-panel { display: flex; flex-direction: row; flex-wrap: wrap; margin: 8px; } .card-shape { padding: var(--tl-space-5); background-color: white; border: 1px solid var(--tl-color-low-border); border-radius: var(--tl-radius-3); display: flex; flex-direction: column; gap: var(--tl-space-3); } ``` -------- # Things on the canvas Category: UI & theming Keywords: canvas overlay, OnTheCanvas, InFrontOfTheCanvas, components, custom component, camera, page coordinates, pageToViewport, usevalue Render React components on the canvas that either scale with the camera or float in front of it. Two component slots live inside the canvas. `OnTheCanvas` components are positioned in page space and behave like shapes: they scale with the zoom and move when you pan. `InFrontOfTheCanvas` components render in screen space, so they follow the page but stay the same size. This example puts two counters on the canvas and a label in front of it that follows the current selection using `editor.getSelectionRotatedPageBounds()` and `editor.pageToViewport()`. Try zooming: the counters grow and shrink, the label doesn't. Both slots are set through the `components` prop. ## App.tsx ```tsx import { useState } from 'react' import { Tldraw, TLEditorComponents, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' import './things-on-the-canvas.css' // There's a guide at the bottom of this file! // [1] function MyComponent() { const [state, setState] = useState(0) const editor = useEditor() return ( <>

The count is {state}!

These components are on the canvas. They will scale with camera zoom like shapes.

The count is {state}!

Create and select a shape to see the in front of the canvas component

) } // [2] function MyComponentInFront() { const editor = useEditor() const position = useValue( 'selection position', () => { const bounds = editor.getSelectionRotatedPageBounds() if (!bounds) return null return editor.pageToViewport(bounds.point) }, [editor] ) if (!position) return null return (

This won’t scale with zoom.

) } // [3] const components: TLEditorComponents = { OnTheCanvas: MyComponent, InFrontOfTheCanvas: MyComponentInFront, } export default function OnTheCanvasExample() { return (
) } /* This example shows the two component slots that live inside the canvas: `OnTheCanvas` and `InFrontOfTheCanvas`. `OnTheCanvas` components behave like shapes: they scale with the zoom and move when the page is panned. `InFrontOfTheCanvas` components render in screen space, so they move with the page but don't scale. For a component that ignores the camera entirely, put it in a UI slot such as `TopPanel` or `SharePanel` instead (see the "UI zones" example). [1] Our `OnTheCanvas` component. Its `top`/`left` are page coordinates. We call `editor.markEventAsHandled` on pointer down so clicks on the card don't also reach the canvas and start a selection or brush. [2] Our `InFrontOfTheCanvas` component. We want it to sit next to the selection, so we read the selection bounds inside `useValue`; the component re-renders whenever the selection or the camera changes. `editor.pageToViewport` converts the page-space point into viewport (screen) coordinates. [3] Define the components object once at module level, so `` doesn't see a new object on every render. */ ``` ## things-on-the-canvas.css ```css .on-the-canvas-card { position: absolute; width: 200px; padding: 12px; border-radius: 8px; user-select: unset; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 8px rgba(0, 0, 0, 0.1); } .in-front-of-the-canvas-card { position: absolute; border-radius: 8px; padding: 0 10px; background: #efefef; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1), 0 4px 8px rgba(0, 0, 0, 0.1); } ``` -------- # Toasts and dialogs Category: UI & theming Keywords: toasts, dialogs, useToasts, useDialogs, addToast, addDialog, notifications, modals, TldrawUiDialog Show toasts and dialogs from your own UI with the `useToasts` and `useDialogs` hooks. `useToasts()` returns `addToast`, `removeToast`, and `clearToasts`; `useDialogs()` returns `addDialog`, `removeDialog`, and `clearDialogs`. Both hooks work in any component rendered inside ``. This example puts a row of launcher buttons in the `SharePanel` slot. `addDialog` takes a component that receives an `onClose` prop. Build the content from tldraw's dialog primitives (`TldrawUiDialogHeader`, `TldrawUiDialogBody`, `TldrawUiDialogFooter`) to match the default UI, or render anything you want. The example also shows a dialog containing a select menu, and a dialog that opens a second one on top of itself. Try opening the select and clicking outside it: the select closes but the dialog stays. ## App.tsx ```tsx import { Select as _Select } from 'radix-ui' import { useState } from 'react' import { TLComponents, Tldraw, TldrawUiButton, TldrawUiButtonLabel, TldrawUiDialogBody, TldrawUiDialogCloseButton, TldrawUiDialogFooter, TldrawUiDialogHeader, TldrawUiDialogTitle, TLUiDialogProps, useContainer, useDialogs, useToasts, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file // [1] function MyDialog({ onClose }: TLUiDialogProps) { return ( <> Title

This dialog body holds a few sentences of text so you can see how longer content behaves. Regular prose wraps onto multiple lines within the dialog width.

Long unbroken strings, like https://example.com/a/really/long/url/that/cannot/wrap/onto/the/next/line, also break instead of overflowing or being clipped.

Cancel Continue ) } // [2] function MySimpleDialog({ onClose }: TLUiDialogProps) { return (

Title

Description...

) } // [3] function MyDialogWithSelect({ onClose }: TLUiDialogProps) { const container = useContainer() const [value, setValue] = useState('a') return ( <> Dialog with a select

A select opened inside a modal is its own dismissable layer.

<_Select.Root value={value} onValueChange={setValue}> <_Select.Trigger data-testid="dialog-select.trigger" style={{ display: 'flex', alignItems: 'center', gap: 8 }} > <_Select.Value /> <_Select.Icon>▾ <_Select.Portal container={container}> <_Select.Content data-testid="dialog-select.content" position="popper" sideOffset={4} style={{ backgroundColor: 'var(--tl-color-panel)', boxShadow: 'var(--tl-shadow-3)', borderRadius: 'var(--tl-radius-2)', padding: 4, zIndex: 'var(--tl-layer-canvas-overlays)', }} > <_Select.Viewport> {['a', 'b', 'c'].map((v) => ( <_Select.Item key={v} value={v} data-testid={`dialog-select.item-${v}`} style={{ padding: '4px 8px', cursor: 'pointer' }} > <_Select.ItemText>Option {v} ))}
Done ) } // [4] function MyNestedDialog({ onClose }: TLUiDialogProps) { const { addDialog } = useDialogs() return (

Parent dialog

Opens another dialog on top of itself.

) } function MyConfirmDialog({ onClose }: TLUiDialogProps) { return (

Nested dialog

) } // [5] function CustomSharePanel() { const { addToast } = useToasts() const { addDialog } = useDialogs() return (
) } // [6] function StackedDialogLauncher() { const { addDialog } = useDialogs() return ( ) } const components: TLComponents = { SharePanel: CustomSharePanel, InFrontOfTheCanvas: StackedDialogLauncher, } export default function ToastsDialogsExample() { return (
) } /* The `useToasts` and `useDialogs` hooks return functions to add, remove, and clear toasts and dialogs from anywhere inside ``. [1] A dialog built from tldraw's dialog primitives (`TldrawUiDialogHeader`, `TldrawUiDialogBody`, `TldrawUiDialogFooter`, and so on), so it matches the rest of the UI. `onClose` is passed to your component by the dialog system; call it from your own buttons to close the dialog. The `onClose` you pass to `addDialog` is separate: it runs after the dialog closes, however it was dismissed (here we show a toast from it). [2] ...or render anything you like. The dialog system only supplies the modal wrapper and the `onClose` callback. [3] Dialogs can contain their own popups, like this Radix select. Because tldraw's dialog is a Radix dismissable layer, clicking outside an open select closes just the select and leaves the dialog open; a second outside click closes the dialog. Portal the select into `useContainer()` so it inherits tldraw's CSS variables. [4] Dialogs stack. A dialog can call `addDialog` to open another on top of itself, and each one, including the topmost, keeps its own controls interactive. [5] The launcher buttons live in the `SharePanel` slot, top right of the UI. [6] The stacked-dialog launcher is rendered in `InFrontOfTheCanvas` instead, because the share panel overflows off-screen on narrow mobile layouts and the e2e test for stacked dialogs needs to reach it with a tap. */ ``` -------- # UI primitives Category: UI & theming Keywords: button, dropdown, select, input, slider, popover, icon, tooltip, menu, ui Tour the UI primitives tldraw exports for building panels, menus, and dialogs that match its look. Everything in tldraw's default UI is built from a small set of exported primitives, and you can use the same ones in your own components. This example renders them all in an `OnTheCanvas` panel so you can zoom in and inspect them: - `TldrawUiButton` with `TldrawUiButtonLabel` and `TldrawUiButtonIcon`, in its normal, primary, danger, icon, and menu types - `TldrawUiDropdownMenu*` for menus with groups, checkbox items, and submenus - `TldrawUiSelect*` for a select control, with and without item icons - `TldrawUiInput` and `TldrawUiSlider` - `TldrawUiPopover*` for floating content - `TldrawUiIcon` for every icon in `iconTypes` - `TldrawUiTooltip` and `TldrawUiKbd` The primitives read tldraw's UI context and CSS variables, so they must be rendered inside `` (in a `components` slot or as children) and they follow the editor's light or dark mode automatically. ## App.tsx ```tsx import { useState } from 'react' import { iconTypes, Tldraw, TldrawUiButton, TldrawUiButtonIcon, TldrawUiButtonLabel, TldrawUiDropdownMenuCheckboxItem, TldrawUiDropdownMenuContent, TldrawUiDropdownMenuGroup, TldrawUiDropdownMenuItem, TldrawUiDropdownMenuRoot, TldrawUiDropdownMenuSub, TldrawUiDropdownMenuSubContent, TldrawUiDropdownMenuSubTrigger, TldrawUiDropdownMenuTrigger, TldrawUiIcon, TldrawUiInput, TldrawUiKbd, TldrawUiPopover, TldrawUiPopoverContent, TldrawUiPopoverTrigger, TldrawUiSelect, TldrawUiSelectContent, TldrawUiSelectItem, TldrawUiSelectTrigger, TldrawUiSelectValue, TldrawUiSlider, TldrawUiTooltip, TLEditorComponents, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' import './ui-primitives.css' // [1] function UiShowcase() { const editor = useEditor() const [checkboxValue, setCheckboxValue] = useState(false) const [inputValue, setInputValue] = useState('') const [sliderValue, setSliderValue] = useState(50) const [selectValue, setSelectValue] = useState('medium') return (

UI primitives

{/* Buttons */}

Buttons

{}}> Normal {}}> Primary {}}> Danger Disabled
With icon
{/* Dropdown Menu */}

Dropdown menu

Open menu Cut ⌘X Copy ⌘C Paste ⌘V setCheckboxValue(!checkboxValue)} > Checkbox item Option A Option B
{/* Select */}

Select

{selectValue} {selectValue} {selectValue}
{/* Input */}

Input

{/* Slider */}

Slider

{sliderValue}%
{/* Popover */}

Popover

Open popover

This is popover content!

It can contain any elements.

{/* Icons */}

Icons ({iconTypes.length})

{iconTypes.map((icon) => (
))}
{/* Tooltip */}

Tooltip

Hover me
{/* Keyboard shortcuts */}

Keyboard shortcuts

⌘ ⇧ ⌥ ⌃ ⌘S ⌘⇧Z
) } // [2] const components: TLEditorComponents = { OnTheCanvas: UiShowcase, } export default function UiPrimitivesExample() { return (
) } /* [1] A tour of the UI primitives exported from tldraw: buttons, dropdown menus, selects, inputs, sliders, popovers, icons, tooltips, and keyboard shortcut badges. They all read tldraw's CSS variables, so anything you build with them matches the rest of the UI (including dark mode). The showcase calls `editor.markEventAsHandled` on pointer down so clicks on the controls don't also reach the canvas. [2] The showcase is rendered in the `OnTheCanvas` slot, so it scales with the camera. That's deliberate: zoom in to inspect the components at different sizes. The primitives need the UI context that `` provides, so they must be rendered inside it (a `components` slot, or as children). */ ``` ## ui-primitives.css ```css .ui-showcase { position: absolute; top: 32px; left: 32px; pointer-events: all; background: var(--tl-color-panel); border-radius: var(--tl-radius-3); padding: 16px; width: 380px; box-shadow: var(--tl-shadow-2); user-select: none; } .ui-showcase h2 { margin: 0 0 16px 0; font-size: 16px; font-weight: 600; } .ui-showcase h3 { margin: 0 0 8px 0; font-size: 12px; font-weight: 500; color: var(--tl-color-text-1); text-transform: uppercase; letter-spacing: 0.5px; } .ui-showcase section { margin-bottom: 20px; } .ui-showcase section:last-child { margin-bottom: 0; } .ui-row { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .ui-row-wide { width: 100%; } .ui-value { font-size: 12px; color: var(--tl-color-text-1); min-width: 40px; } .ui-popover-content { padding: 12px 16px; font-size: 13px; } .ui-popover-content p { margin: 0 0 8px 0; } .ui-popover-content p:last-child { margin-bottom: 0; } .ui-icon-grid { display: grid; grid-template-columns: repeat(auto-fill, 24px); gap: 4px; } .ui-icon-cell { display: flex; align-items: center; justify-content: center; width: 24px; height: 24px; border-radius: 4px; } .ui-icon-cell:hover { background: var(--tl-color-muted-2); } ``` -------- # UI zones Category: UI & theming Keywords: zones, TopPanel, SharePanel, ui zones, custom panels, components override, top zone, share zone Fill the empty `TopPanel` and `SharePanel` slots with your own components. The default UI leaves two slots empty for you: `TopPanel` in the top center of the screen and `SharePanel` in the top right, above the style panel. Set either one through the `components` prop to render your own React component there. tldraw.com uses them for the document title and the share button. ## App.tsx ```tsx import { TLComponents, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] function CustomTopPanel() { return (

Top panel

) } // [2] function CustomSharePanel() { return (

Share panel

) } const components: TLComponents = { SharePanel: CustomSharePanel, TopPanel: CustomTopPanel, } export default function ZonesExample() { return (
) } /* The default UI leaves two slots empty for you to fill: `TopPanel` in the top center of the screen, and `SharePanel` in the top right, above the style panel. Both are set through the `components` prop like any other slot. [1] Rendered in the top center. tldraw.com uses this slot for the document title. [2] Rendered in the top right. tldraw.com uses this slot for the share button and collaborator avatars. */ ``` -------- # Hide the entire UI Category: UI & theming Keywords: hideui, bare editor, minimal, custom ui, headless Hide all of tldraw's default UI with the `hideUi` prop. Passing `hideUi` to `` removes the toolbar, menus, and panels while keeping the canvas, default shapes, tools, and keyboard shortcuts. The editor is fully functional; you just need to provide your own controls, typically by rendering components inside `` that call `useEditor()`. Keyboard shortcuts still work here, so try pressing `d` for the draw tool or `r` for a rectangle. See the custom UI example for building your own controls. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function HideUiExample() { return (
) } /* `hideUi` removes all of tldraw's default UI but keeps the editor, its tools, and its keyboard shortcuts. Build your own controls on top with `useEditor()`; see the custom UI example for a starting point. */ ``` -------- # Replace the entire UI Category: UI & theming Keywords: hideui, custom ui, keyboard shortcuts, setcurrenttool, track, useeditor, toolbar, buttons Hide tldraw's UI with `hideUi` and build your own toolbar and shortcuts on top of the editor. Pass `hideUi` to the `Tldraw` component to hide the default UI, then render your own components as children so they can reach the editor through `useEditor`. This example adds a minimal toolbar with select, pencil, and eraser buttons, plus keyboard shortcuts for switching tools and deleting shapes. The toolbar is wrapped in `track()` so the active button follows `editor.getCurrentToolId()`. `hideUi` doesn't remove the context menu; see the exploded example for how to omit it. ## App.tsx ```tsx import { useEffect } from 'react' import { Tldraw, track, useEditor } from 'tldraw' import 'tldraw/tldraw.css' import './custom-ui.css' // There's a guide at the bottom of this file! // [1] export default function CustomUiExample() { return (
) } // [2] const CustomUi = track(() => { const editor = useEditor() useEffect(() => { const handleKeyUp = (e: KeyboardEvent) => { if (editor.getEditingShapeId() !== null) return const target = e.target as HTMLElement | null if (target?.isContentEditable) return if (target?.tagName === 'INPUT' || target?.tagName === 'TEXTAREA') return switch (e.key) { case 'Delete': case 'Backspace': { editor.deleteShapes(editor.getSelectedShapeIds()) break } case 'v': { editor.setCurrentTool('select') break } case 'e': { editor.setCurrentTool('eraser') break } case 'x': case 'p': case 'b': case 'd': { editor.setCurrentTool('draw') break } } } window.addEventListener('keyup', handleKeyUp) return () => { window.removeEventListener('keyup', handleKeyUp) } }, [editor]) return (
) }) /* [1] We render the `Tldraw` component with the `hideUi` prop, which hides the default toolbar, style panel, menus, and so on. Our custom UI is rendered as a child of `Tldraw`, which gives it access to the editor instance via React context. The context menu isn't hidden by `hideUi`. If you want to hide it too, render the parts that make up the `Tldraw` component separately and omit the context menu; see the exploded example. [2] The component is wrapped in `track()` so it re-renders when the signals it reads change; here `editor.getCurrentToolId()` drives which button is active. See the signals example for more: https://tldraw.dev/examples/signals We get the editor via `useEditor` and add a window `keyup` listener for our own shortcuts. The listener skips key presses while a shape is being edited or when an input has focus, so typing text doesn't switch tools. */ ``` ## custom-ui.css ```css .custom-layout { position: absolute; inset: 0px; z-index: 300; pointer-events: none; } .custom-toolbar { position: absolute; top: 0px; left: 0px; width: 100%; display: flex; align-items: center; justify-content: center; padding: 8px; gap: 8px; } .custom-button { pointer-events: all; padding: 4px 12px; background: white; border: 1px solid black; border-radius: 64px; } .custom-button[data-isactive='true'] { background-color: black; color: white; } ``` -------- # Contextual style panel Category: UI & theming Keywords: style panel, contextual toolbar, infrontofthecanvas, selection, floating ui, styles Replace the built-in style panel with style controls of your own. The style panel is a component slot like any other. Switch off the built-in one and you can build your own style controls and put them wherever your app needs them. This example moves them onto the canvas. The controls appear in a toolbar that floats above the selected shapes, within reach of what you're editing, instead of docked in the top right corner. The toolbar shows only the styles that belong to what you've selected, so it's two controls wide for a highlighter and eight for an arrow. Nothing here checks the shape type: a shape supports a style when its props schema says so, and `editor.getSharedStyles()` returns the styles every selected shape has in common. Select a line and a text shape together and you're left with color and size. The same rule covers custom shapes. Declare `color: DefaultColorStyle` in your shape's props and the color picker appears with no extra wiring. The toolbar leaves out the opacity slider, which is the one control in the docked panel that isn't a style prop. ## App.tsx ```tsx import { useState } from 'react' import { ArrowShapeArrowheadEndStyle, ArrowShapeArrowheadStartStyle, ArrowShapeKindStyle, Box, defaultGeoTypeDefinitions, DefaultColorStyle, DefaultDashStyle, DefaultFillStyle, DefaultFontStyle, DefaultHorizontalAlignStyle, DefaultSizeStyle, DefaultTextAlignStyle, DefaultVerticalAlignStyle, Editor, GeoShapeGeoStyle, GeoShapeUtil, getColorStyleItems, getColorValue, getFontStyleItems, LineShapeSplineStyle, SharedStyle, StyleProp, StyleValuesForUi, tlmenus, TLComponents, TLDefaultColorStyle, Tldraw, TldrawUiButtonIcon, TldrawUiContextualToolbar, TldrawUiPopover, TldrawUiPopoverContent, TldrawUiPopoverTrigger, TldrawUiToolbar, TldrawUiToolbarButton, TLUiIconType, track, useEditor, useTranslation, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const FILL_ITEMS = [ { value: 'none', icon: 'fill-none' }, { value: 'semi', icon: 'fill-semi' }, { value: 'solid', icon: 'fill-solid' }, { value: 'pattern', icon: 'fill-pattern' }, { value: 'lined-fill', icon: 'fill-lined-fill' }, { value: 'fill', icon: 'fill-fill' }, ] as const const DASH_ITEMS = [ { value: 'draw', icon: 'dash-draw' }, { value: 'dashed', icon: 'dash-dashed' }, { value: 'dotted', icon: 'dash-dotted' }, { value: 'solid', icon: 'dash-solid' }, ] as const const SIZE_ITEMS = [ { value: 's', icon: 'size-small' }, { value: 'm', icon: 'size-medium' }, { value: 'l', icon: 'size-large' }, { value: 'xl', icon: 'size-extra-large' }, ] as const const ARROW_KIND_ITEMS = [ { value: 'arc', icon: 'arrow-arc' }, { value: 'elbow', icon: 'arrow-elbow' }, ] as const const ARROWHEAD_ITEMS = [ { value: 'none', icon: 'arrowhead-none' }, { value: 'arrow', icon: 'arrowhead-arrow' }, { value: 'triangle', icon: 'arrowhead-triangle' }, { value: 'square', icon: 'arrowhead-square' }, { value: 'dot', icon: 'arrowhead-dot' }, { value: 'diamond', icon: 'arrowhead-diamond' }, { value: 'inverted', icon: 'arrowhead-triangle-inverted' }, { value: 'bar', icon: 'arrowhead-bar' }, ] as const const SPLINE_ITEMS = [ { value: 'line', icon: 'spline-line' }, { value: 'cubic', icon: 'spline-cubic' }, ] as const const TEXT_ALIGN_ITEMS = [ { value: 'start', icon: 'text-align-left' }, { value: 'middle', icon: 'text-align-center' }, { value: 'end', icon: 'text-align-right' }, ] as const const LABEL_ALIGN_ITEMS = [ { value: 'start', icon: 'horizontal-align-start' }, { value: 'middle', icon: 'horizontal-align-middle' }, { value: 'end', icon: 'horizontal-align-end' }, ] as const const VERTICAL_ALIGN_ITEMS = [ { value: 'start', icon: 'vertical-align-start' }, { value: 'middle', icon: 'vertical-align-middle' }, { value: 'end', icon: 'vertical-align-end' }, ] as const // [2] function getGeoStyleItems(editor: Editor): StyleValuesForUi { const { customGeoTypes } = editor.getShapeUtil('geo').options const merged = { ...defaultGeoTypeDefinitions, ...customGeoTypes } return Object.entries(merged).map(([value, definition]) => ({ value, icon: definition.icon })) } interface StylePickerProps { uiType: string style: StyleProp value: SharedStyle items: StyleValuesForUi /** Defaults to `style-panel.`. Pass this when the two don't line up. */ labelKey?: string getItemColor?(value: T): string } // [3] function StylePicker({ uiType, style, value, items, labelKey, getItemColor, }: StylePickerProps) { const editor = useEditor() const msg = useTranslation() const [isOpen, setIsOpen] = useState(false) // [4] const popoverId = `contextual style ${style.id}` const label = msg(labelKey ?? `style-panel.${uiType}`) const icon = value.type === 'mixed' ? 'mixed' : (items.find((item) => item.value === value.value)?.icon ?? items[0]?.icon) // [5] const handleSelect = (next: T) => { editor.markHistoryStoppingPoint('contextual style panel') editor.run(() => { editor.setStyleForSelectedShapes(style, next) editor.setStyleForNextShapes(style, next) }) // [6] tlmenus.deleteOpenMenu(popoverId, editor.contextId) setIsOpen(false) } return ( 4 ? 'grid' : 'horizontal'} label={label} > {items.map((item) => ( handleSelect(item.value)} > ))} ) } // [7] const ContextualStylePanel = track(() => { const editor = useEditor() const msg = useTranslation() // [8] const styles = editor.getSharedStyles() if (!editor.isIn('select.idle') || editor.getSelectedShapeIds().length === 0) return null const color = styles.get(DefaultColorStyle) const fill = styles.get(DefaultFillStyle) const dash = styles.get(DefaultDashStyle) const size = styles.get(DefaultSizeStyle) const font = styles.get(DefaultFontStyle) const geo = styles.get(GeoShapeGeoStyle) const arrowKind = styles.get(ArrowShapeKindStyle) const arrowheadStart = styles.get(ArrowShapeArrowheadStartStyle) const arrowheadEnd = styles.get(ArrowShapeArrowheadEndStyle) const spline = styles.get(LineShapeSplineStyle) const textAlign = styles.get(DefaultTextAlignStyle) const labelAlign = styles.get(DefaultHorizontalAlignStyle) const verticalAlign = styles.get(DefaultVerticalAlignStyle) const theme = editor.getCurrentTheme() const colors = theme.colors[editor.getColorMode()] // [9] const getSelectionBounds = () => { const bounds = editor.getSelectionRotatedScreenBounds() if (!bounds) return undefined return new Box(bounds.x, bounds.y, bounds.width, 0) } return ( {color && ( getColorValue(colors, value as TLDefaultColorStyle, 'solid')} /> )} {fill && ( )} {dash && ( )} {size && ( )} {font && ( )} {geo && ( )} {arrowKind && ( )} {arrowheadStart && ( )} {arrowheadEnd && ( )} {spline && ( )} {textAlign && ( )} {labelAlign && ( )} {verticalAlign && ( )} ) }) // [10] const components: TLComponents = { StylePanel: null, InFrontOfTheCanvas: ContextualStylePanel, } export default function ContextualStylePanelExample() { return (
) } /* The style panel is a component slot like any other. Switch off the built-in one and you can build your own style controls and put them wherever your app needs them. This example moves them onto the canvas, into a toolbar that floats above the selected shapes. It shows only the styles that selection supports, so it's short for a highlighter and long for an arrow. [1] Each picker needs a list of the style values it offers and an icon for each one. The SDK keeps its own lists private, so we spell ours out here. These match what the docked panel offers, which is narrower than what the schema allows. There's no icon for the `pipe` arrowhead or for `dash: none`, and the `*-legacy` label alignments only turn up in migrated documents, so none of them are worth a button. See [4] for what the trigger shows when a shape holds one of these values anyway. [2] Three of the lists are built at render time instead. `getColorStyleItems` and `getFontStyleItems` read the current theme, and `getGeoStyleItems` merges the built-in geo types with any registered through `GeoShapeUtil.configure()`. Custom colors, fonts and geo types need no extra work here. [3] One component covers every style. The trigger shows the current value and opens a popover below the toolbar, which keeps the rest of the controls visible while you pick. `uiType` is the name the SDK uses for a style in its translation files, so it gives us the button labels for free: "Color" and "Light blue" rather than `color` and `light-blue`. Four styles name their panel section differently from their values, and `labelKey` covers those. Only color passes `getItemColor`. Icons are drawn in `currentColor`, so setting `color` on a button turns it into a swatch. [4] Two details on the trigger. The popover id comes from `style.id` rather than `uiType`, because text align and label align share a `uiType` and would otherwise fight over one id. And when the current value has no button of its own, we fall back to the first item's icon so the trigger never renders blank. The docked panel's dropdowns do the same. [5] `setStyleForSelectedShapes` restyles the current selection and `setStyleForNextShapes` carries the value to the next shape you draw. The docked panel sets both too. Marking a stopping point first means one undo reverts the whole change. [6] A popover registers itself with the editor's menu system, and `MenuClickCapture` responds by covering the canvas with a layer that swallows the next click. Our toolbar sits on the canvas, underneath that layer, so it goes dead while a menu is open. Closing the popover as soon as a value is picked keeps the toolbar clickable. [7] `track` re-renders this component whenever the reactive editor state it reads changes. That's what makes the toolbar follow the selection. [8] A shape supports a style when its props schema declares it as a `StyleProp`, so the editor works out which controls apply without us naming a single shape type. `editor.getSharedStyles()` returns the styles that every selected shape supports, and we render a picker only when its style is there. Select a line and you get color, dash, size and spline. Select a text shape and you get color, size, font and alignment. Select the two together and only color and size survive. Custom shapes need no special handling: declare `color: DefaultColorStyle` in the props and the color picker appears. The reverse holds too. A frame declares `color` as a plain validator rather than a `StyleProp`, which is how it stays out of the style panel, so selecting one here gives you no toolbar at all. A style's value is `shared` when all the selected shapes agree on it and `mixed` when they don't. The pickers use this to decide which item to highlight. [9] `getSelectionBounds` tells the toolbar where to position itself. We collapse the bounds to zero height so the toolbar sits just above the top edge of the selection. [10] Setting `StylePanel` to null removes the docked panel on both desktop and mobile. `InFrontOfTheCanvas` renders our toolbar on top of the shapes but behind the rest of the UI. */ ``` -------- # Contextual toolbar Category: UI & theming Keywords: contextual toolbar, infrontofthecanvas, selection, ui overlay, custom ui, toolbar, selected shapes Show a toolbar above the selected shapes using the `TldrawUiContextualToolbar` primitive. The toolbar is rendered in the `InFrontOfTheCanvas` slot, so it appears above the canvas but below the rest of the UI. It positions itself using the bounds returned from `getSelectionBounds`, and reads the shared size style of the selection with `editor.getSharedStyles()`. Select shapes of different types and change their size from the toolbar; this works just like changing the size from the style panel on the right. ## App.tsx ```tsx import { Box, DefaultSizeStyle, Tldraw, TldrawUiButtonIcon, TldrawUiContextualToolbar, TldrawUiToolbarButton, TLEditorComponents, TLEditorSnapshot, track, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' import _jsonSnapshot from './snapshot.json' // There's a guide at the bottom of this file! const jsonSnapshot = _jsonSnapshot as any as TLEditorSnapshot const SIZES = [ { value: 's', icon: 'size-small' }, { value: 'm', icon: 'size-medium' }, { value: 'l', icon: 'size-large' }, { value: 'xl', icon: 'size-extra-large' }, ] as const // [1] const ContextualToolbarComponent = track(() => { const editor = useEditor() const showToolbar = editor.isIn('select.idle') // [2] const size = editor.getSharedStyles().get(DefaultSizeStyle) if (!size || !showToolbar) return null const currentSize = size.type === 'shared' ? size.value : undefined // [3] const getSelectionBounds = () => { const fullBounds = editor.getSelectionRotatedScreenBounds() if (!fullBounds) return undefined return new Box(fullBounds.x, fullBounds.y, fullBounds.width, 0) } return ( {SIZES.map(({ value, icon }) => { return ( editor.setStyleForSelectedShapes(DefaultSizeStyle, value)} > ) })} ) }) const components: TLEditorComponents = { InFrontOfTheCanvas: ContextualToolbarComponent, } export default function ContextualToolbar() { return (
) } /* `TldrawUiContextualToolbar` is rendered in the `InFrontOfTheCanvas` slot, so it sits on top of the shapes but behind the rest of the UI. [1] The component is wrapped in `track()` so it re-renders when the selection, camera, or tool state changes. We only show the toolbar while the select tool is idle, so it disappears while shapes are being dragged, resized, or rotated. [2] Different shapes support different style properties. `getSharedStyles()` returns the styles supported by every selected shape; if none of them support `DefaultSizeStyle` we don't show the toolbar at all. If all the shapes have the same size, the entry's type is `shared` and we highlight that size. If they differ, the type is `mixed` and nothing is highlighted. [3] `getSelectionBounds` tells the toolbar where to position itself. Here we use the selection's rotated screen bounds with a height of zero so the toolbar sits along the top edge; you can use any other logic you like. */ ``` -------- # Custom canvas components Category: UI & theming Keywords: components, Background, Canvas, Grid, Cursor, ShapeIndicator, OnTheCanvas, InFrontOfTheCanvas, custom ui, override Replace tldraw's on-canvas components, such as the background, with your own. tldraw's on-canvas UI is built from replaceable React components: the background, grid, cursors, shape indicators, and more. Pass your own via the `components` prop, or pass `null` to hide one. This example replaces the `Background` component with a light blue div. See `TLEditorComponents` for the full list of slots. ## App.tsx ```tsx import { Tldraw, TLEditorComponents } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const components: TLEditorComponents = { Background: () => { return
}, } export default function CustomComponentsExample() { return (
) } /* The `components` prop replaces the background, grid, cursors, shape indicators, and more. See `TLEditorComponents` for the full list. [1] Define the components object outside the React component so it's a stable reference. Here we replace the `Background` component with a plain div in a light blue color. Passing `null` for a component hides it entirely. */ ``` -------- # Custom grid Category: UI & theming Keywords: grid, canvas, 2d context, Grid component, getViewportPageBounds, devicePixelRatio, camera, custom rendering Draw a custom grid on the canvas with a 2d canvas context. Override the `Grid` component via the `components` prop to draw your own grid. The component receives the camera position, zoom, and grid size, and this example uses them to draw minor and major grid lines into a 2d canvas at the device's pixel ratio. Grid mode is turned on in `onMount` so the grid is visible immediately. Try zooming and panning; the grid redraws to match the camera and switches color in dark mode. ## App.tsx ```tsx import { useLayoutEffect, useRef } from 'react' import { TLComponents, Tldraw, approximately, useColorMode, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const components: TLComponents = { // [1] Grid: ({ size, ...camera }) => { const editor = useEditor() // [2] const screenBounds = useValue('screenBounds', () => editor.getViewportScreenBounds(), [editor]) const devicePixelRatio = useValue('dpr', () => editor.getInstanceState().devicePixelRatio, [ editor, ]) const isDarkMode = useColorMode() === 'dark' const canvas = useRef(null) useLayoutEffect(() => { if (!canvas.current) return // [3] const canvasW = screenBounds.w * devicePixelRatio const canvasH = screenBounds.h * devicePixelRatio canvas.current.width = canvasW canvas.current.height = canvasH const ctx = canvas.current?.getContext('2d') if (!ctx) return ctx.clearRect(0, 0, canvasW, canvasH) // [4] const pageViewportBounds = editor.getViewportPageBounds() const startPageX = Math.ceil(pageViewportBounds.minX / size) * size const startPageY = Math.ceil(pageViewportBounds.minY / size) * size const endPageX = Math.floor(pageViewportBounds.maxX / size) * size const endPageY = Math.floor(pageViewportBounds.maxY / size) * size const numRows = Math.round((endPageY - startPageY) / size) const numCols = Math.round((endPageX - startPageX) / size) ctx.strokeStyle = isDarkMode ? '#555' : '#BBB' // [5] for (let row = 0; row <= numRows; row++) { const pageY = startPageY + row * size // convert the page-space Y offset into our canvas' coordinate space const canvasY = (pageY + camera.y) * camera.z * devicePixelRatio const isMajorLine = approximately(pageY % (size * 10), 0) drawLine(ctx, 0, canvasY, canvasW, canvasY, isMajorLine ? 3 : 1) } for (let col = 0; col <= numCols; col++) { const pageX = startPageX + col * size // convert the page-space X offset into our canvas' coordinate space const canvasX = (pageX + camera.x) * camera.z * devicePixelRatio const isMajorLine = approximately(pageX % (size * 10), 0) drawLine(ctx, canvasX, 0, canvasX, canvasH, isMajorLine ? 3 : 1) } }, [screenBounds, camera, size, devicePixelRatio, editor, isDarkMode]) // [6] return }, } export default function CustomGridExample() { return (
{ e.updateInstanceState({ isGridMode: true }) }} />
) } function drawLine( ctx: CanvasRenderingContext2D, x1: number, y1: number, x2: number, y2: number, width: number ) { ctx.beginPath() ctx.moveTo(x1, y1) ctx.lineTo(x2, y2) ctx.lineWidth = width ctx.stroke() } /* [1] To add a custom grid, override the `Grid` component. It receives the camera position and zoom along with the grid size in page space, and re-renders whenever the camera moves. [2] Besides the camera, the grid also needs to redraw when the screen bounds change, when the device pixel ratio changes, or when the color mode changes. `useValue` and `useColorMode` subscribe to those values so the component re-renders when they change. [3] To avoid pixelation we render at the device's actual resolution, so the canvas size is scaled by the device pixel ratio. [4] Calculate the first and last grid lines visible in the viewport, in page space, so we only draw the lines that are actually on screen. [5] Convert each page-space line position into canvas pixels using the camera and device pixel ratio. Major lines are drawn every 10 grid units. [6] The `tl-grid` class is important for correct positioning and pointer-event handling. */ ``` -------- # Drag and drop tray Category: UI & theming Keywords: drag, drop, tray, shapes, InFrontOfTheCanvas, useAtom, useQuickReactor, screenToPage Drag items from a custom tray onto the canvas to create shapes. The tray is a custom `InFrontOfTheCanvas` component that renders over the canvas. Each item tracks its own pointer events through a small state machine (`idle`, `pointing_item`, `dragging`) held in a `useAtom`. A drag only starts after the pointer moves more than 10px, so clicking an item does nothing. On drop, `editor.screenToPage()` converts the pointer position to page space and `editor.createShape()` places the shape there. `useQuickReactor` positions the drag preview by writing to the DOM directly, avoiding a React render per pointer move. Try dragging an emoji from the tray on the left onto the canvas. Press Escape mid-drag to cancel. ## App.tsx ```tsx import { useMemo, useRef } from 'react' import { Box, TLEditorComponents, Tldraw, Vec, useAtom, useEditor, useQuickReactor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './drag-and-drop-tray.css' import { TRAY_ITEMS, TrayItem } from './trayitems' // There's a guide at the bottom of this file! // [1] type DragState = | { name: 'idle' } | { name: 'pointing_item' item: TrayItem startPosition: Vec } | { name: 'dragging' item: TrayItem currentPosition: Vec } // [2] const DragAndDropTray = () => { const rTrayContainer = useRef(null) const rDraggingImage = useRef(null) const editor = useEditor() // [3] const dragState = useAtom('dragState', () => ({ name: 'idle', })) // [4] const { handlePointerUp, handlePointerDown } = useMemo(() => { let target: HTMLDivElement | null = null function handlePointerMove(e: PointerEvent) { const current = dragState.get() const screenPoint = new Vec(e.clientX, e.clientY) switch (current.name) { case 'idle': { break } case 'pointing_item': { const dist = Vec.Dist(screenPoint, current.startPosition) if (dist > 10) { // [a] dragState.set({ name: 'dragging', item: current.item, currentPosition: screenPoint, }) } break } case 'dragging': { // [b] dragState.set({ ...current, currentPosition: screenPoint, }) break } } } function handlePointerUp(e: React.PointerEvent) { const current = dragState.get() target = e.currentTarget as HTMLDivElement target.releasePointerCapture(e.pointerId) switch (current.name) { case 'idle': { break } case 'pointing_item': { dragState.set({ name: 'idle', }) break } case 'dragging': { // [c] const screenPoint = new Vec(e.clientX, e.clientY) const pagePoint = editor.screenToPage(screenPoint) editor.markHistoryStoppingPoint('create shape from tray') editor.createShape({ ...current.item.shapeBase, x: pagePoint.x - 50, // center on cursor at 100x100 y: pagePoint.y - 50, }) dragState.set({ name: 'idle', }) break } } removeEventListeners() } function handlePointerDown(e: React.PointerEvent) { e.preventDefault() target = e.currentTarget as HTMLDivElement target.setPointerCapture(e.pointerId) const itemIndex = target.dataset.drag_item_index! const item = TRAY_ITEMS[+itemIndex] if (!item) return const startPosition = new Vec(e.clientX, e.clientY) // [d] dragState.set({ name: 'pointing_item', item, startPosition, }) target.addEventListener('pointermove', handlePointerMove) document.addEventListener('keydown', handleKeyDown) } function handleKeyDown(e: KeyboardEvent) { const current = dragState.get() if (e.key === 'Escape' && current.name === 'dragging') { removeEventListeners() } } function removeEventListeners() { if (target) { target.removeEventListener('pointermove', handlePointerMove) document.removeEventListener('keydown', handleKeyDown) } dragState.set({ name: 'idle', }) } return { handlePointerDown, handlePointerUp, } }, [dragState, editor]) const state = useValue('dragState', () => dragState.get(), [dragState]) // [5] useQuickReactor( 'drag-image-style', () => { const current = dragState.get() const imageRef = rDraggingImage.current const trayContainerRef = rTrayContainer.current if (!imageRef || !trayContainerRef) return switch (current.name) { case 'idle': case 'pointing_item': { imageRef.style.display = 'none' break } case 'dragging': { const trayContainerRect = trayContainerRef.getBoundingClientRect() const box = new Box( trayContainerRect.x, trayContainerRect.y, trayContainerRect.width, trayContainerRect.height ) const viewportScreenBounds = editor.getViewportScreenBounds() const isInside = Box.ContainsPoint(box, current.currentPosition) if (isInside) { imageRef.style.display = 'none' } else { imageRef.style.position = 'absolute' imageRef.style.pointerEvents = 'none' imageRef.style.left = '0px' imageRef.style.top = '0px' imageRef.style.transform = `translate(${current.currentPosition.x - viewportScreenBounds.x - 25}px, ${current.currentPosition.y - viewportScreenBounds.y - 25}px)` imageRef.style.width = '50px' imageRef.style.height = '50px' imageRef.style.fontSize = '40px' imageRef.style.display = 'flex' imageRef.style.alignItems = 'center' } } } }, [dragState] ) return ( <> {/* [6] */}
{TRAY_ITEMS.map((item, index) => (
{item.emoji}
))}
{/* [7] */}
{state.name === 'dragging' && state.item.emoji}
) } // [8] const components: TLEditorComponents = { InFrontOfTheCanvas: DragAndDropTray, } export default function DragAndDropTrayExample() { return (
) } /* This example builds a tray of items that can be dragged onto the canvas to create shapes. The tray is a custom `InFrontOfTheCanvas` component, so it renders over the canvas but inside tldraw's UI layer, and it drives the interaction with its own small state machine. [1] `DragState` is a discriminated union: `idle`, `pointing_item` (pointer is down but hasn't moved far enough to count as a drag), and `dragging`. Modelling it this way means each handler only has to deal with the transitions that are valid from its current state. [2] `rTrayContainer` is used for bounds checking (we hide the preview while the pointer is still over the tray) and `rDraggingImage` is the preview element that follows the cursor. [3] `useAtom` gives us a reactive atom that both the memoized event handlers and the `useQuickReactor` below can read without being recreated when the state changes. [4] The handlers are created once in `useMemo` and read the atom directly, so they don't go stale. [a] We only enter `dragging` after the pointer moves more than 10px, so a plain click on a tray item doesn't accidentally create a shape. [b] While dragging we just track the pointer position; the preview is positioned in [5]. [c] On pointer up while dragging, convert the screen point to page space with `editor.screenToPage()` and create the shape there. `markHistoryStoppingPoint` makes each drop its own undo step. [d] On pointer down we capture the pointer on the item element, so we keep receiving move/up events even when the pointer leaves it. The item index comes from a `data-` attribute so one handler serves every item. [5] `useQuickReactor` runs synchronously whenever `dragState` changes and writes styles to the preview element directly. Positioning via the DOM rather than React state avoids a React render on every pointer move. The offset by `getViewportScreenBounds()` converts the client coordinates to coordinates relative to the editor container, which is what an `InFrontOfTheCanvas` component is positioned against. [6] Each tray item gets the shared pointer handlers and a `data-drag_item_index` attribute that [4d] reads back. [7] The preview element only has content while dragging; [5] handles showing and hiding it. [8] `components` is defined at module level so `` doesn't see a new object on every render, which would remount the UI. */ ``` ## drag-and-drop-tray.css ```css .drag-tray { position: absolute; left: 10px; top: 50px; background: var(--tl-color-panel); border-radius: 9px; box-shadow: var(--tl-shadow-1); z-index: 1000; pointer-events: all; overflow: hidden; } .drag-tray-items { display: flex; flex-direction: column; gap: 4px; } .drag-tray-item { display: flex; align-items: center; justify-content: center; gap: 12px; width: 40px; height: 40px; border-radius: 8px; cursor: grab; transition: all 0.2s ease; user-select: none; font-size: 18px; } ``` ## trayitems.ts ```ts import { TLShape, toRichText } from 'tldraw' // Distributes over the shape union so `props` is typed against the matching shape's props. export type TrayItem = T extends T ? { id: string emoji: string label: string shapeBase: { type: T['type'] props: Partial } } : never export const TRAY_ITEMS: TrayItem[] = [ { id: 'snowman', emoji: '⛄', label: 'Snowman', shapeBase: { type: 'geo', props: { richText: toRichText('⛄'), size: 'm', }, }, }, { id: 'ice-cream', emoji: '🍦', label: 'Ice Cream', shapeBase: { type: 'geo', props: { richText: toRichText('🍦'), size: 'm', }, }, }, { id: 'smiley', emoji: '😊', label: 'Smiley', shapeBase: { type: 'geo', props: { richText: toRichText('😊'), size: 'm', }, }, }, { id: 'star', emoji: '⭐', label: 'Star', shapeBase: { type: 'geo', props: { richText: toRichText('⭐'), size: 'm', }, }, }, { id: 'heart', emoji: '❤️', label: 'Heart', shapeBase: { type: 'geo', props: { richText: toRichText('❤️'), size: 'm', }, }, }, ] ``` -------- # Error boundary Category: UI & theming Keywords: error handling, shapeerrorfallback, error boundary, components, crash recovery, fallback ui Customize the fallback shown when a shape throws while rendering. Every shape renders inside its own error boundary, so a shape that throws doesn't crash the editor. Instead tldraw renders the `ShapeErrorFallback` component in its place. Override it through the `components` prop to show your own message; it receives the thrown `error` as a prop. This example registers a shape whose `component()` always throws and creates one on mount so you can see the custom fallback immediately. ## App.tsx ```tsx import { TLComponents, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' import { ErrorShapeUtil } from './ErrorShape' // There's a guide at the bottom of this file! // [1] const shapeUtils = [ErrorShapeUtil] // [2] const components: TLComponents = { ShapeErrorFallback: ({ error }) =>
Shape error! {String(error)}
, } export default function ErrorBoundaryExample() { return (
{ // [3] editor.createShape({ type: 'error' }) }} />
) } /* Each shape renders inside its own error boundary, so a shape that throws shows a fallback instead of taking down the editor. This example customizes that fallback. [1] A custom shape whose `component()` always throws. See ErrorShape.ts. [2] `ShapeErrorFallback` receives the thrown `error`. Like `shapeUtils`, `components` is defined at module level so `` doesn't see a new object every render. [3] Create the error shape on mount so the fallback is visible straight away. */ ``` ## ErrorShape.ts ```ts import { BaseBoxShapeUtil, TLShape } from 'tldraw' const ERROR_TYPE = 'error' declare module 'tldraw' { export interface TLGlobalShapePropsMap { [ERROR_TYPE]: { w: number; h: number } } } export type ErrorShape = TLShape export class ErrorShapeUtil extends BaseBoxShapeUtil { static override type = ERROR_TYPE getDefaultProps() { return { w: 100, h: 100 } } component() { throw new Error('Error!') } // Indicators are drawn on a shared canvas overlay with no error boundary, so // throwing here would break every overlay. Return nothing instead. getIndicatorPath() { return undefined } } ``` -------- # Selection UI Category: UI & theming Keywords: selection, ui overlay, infrontofthecanvas, custom controls, duplicate, handles, usevalue, getselectionrotatedscreenbounds Add duplicate-in-direction buttons around the selection using the `InFrontOfTheCanvas` slot. The `InFrontOfTheCanvas` component renders in screen space above the canvas, so anything you put there stays a fixed size while the camera moves. This example reads `editor.getSelectionRotatedScreenBounds()` and `editor.getSelectionRotation()` inside `useValue` to position four buttons around the selection, rotated to match it. Each button calls `editor.duplicateShapes` with an offset computed from the selection's rotated bounds. Try selecting a shape, rotating it, and clicking the arrows. ## App.tsx ```tsx import { TLComponents, Tldraw, Vec, intersectLineSegmentPolygon, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] function SelectionUi() { const editor = useEditor() // [2] const info = useValue( 'selection bounds', () => { const screenBounds = editor.getViewportScreenBounds() const rotation = editor.getSelectionRotation() const rotatedScreenBounds = editor.getSelectionRotatedScreenBounds() if (!rotatedScreenBounds) return return { x: rotatedScreenBounds.x - screenBounds.x, y: rotatedScreenBounds.y - screenBounds.y, width: rotatedScreenBounds.width, height: rotatedScreenBounds.height, rotation, } }, [editor] ) if (!info) return null return (
) } // [3] function DuplicateInDirectionButton({ x, y, rotation, }: { x: number y: number rotation: number }) { const editor = useEditor() return ( ) } const components: TLComponents = { InFrontOfTheCanvas: SelectionUi, } export default function SelectionUiExample() { return (
) } /* This example adds four "duplicate in this direction" buttons around the current selection, rendered in the InFrontOfTheCanvas slot. [1] InFrontOfTheCanvas renders in screen space above the canvas, so it doesn't scale with the camera. That makes it the right place for controls that should stay a fixed size while following the selection. The slot's wrapper has `pointer-events: none` and already marks pointer events as handled, so we only need to opt our container back in with `pointerEvents: 'all'`. [2] `getSelectionRotatedScreenBounds` gives the selection's bounds in screen space, already rotated to match the selection. Those coordinates are relative to the whole window, so we subtract the viewport's screen position to get coordinates relative to the tldraw component. Reading everything inside `useValue` keeps the buttons glued to the selection as it moves, rotates, or the camera pans. [3] Each button's `rotation` sets both its CSS rotation and the direction the copies are offset in, zeroed to the right. [4] To offset the copies by exactly one selection-width plus padding in the chosen direction, we cast a ray from the selection's center and find where it exits the padded, rotated selection bounds. Doubling that distance lands the duplicates just past the original in that direction. */ ``` -------- # Text mass style updates Category: UI & theming Keywords: text, contextual, mass, style, bold, italic, highlight, styles Toggle bold, italic, or highlight on all the text in the selected shapes, including text nested in frames. Rich text in tldraw is a TipTap (ProseMirror) JSON document. This example parses it with ProseMirror's `Node.fromJSON` (using a schema built from `tipTapDefaultExtensions`), adds or removes a mark on every text node, and writes the result back with `editor.updateShape`. Container shapes such as frames and groups are handled by recursing into `editor.getSortedChildIdsForParent`. The buttons live in a custom `StylePanel` that wraps `DefaultStylePanel`. They only appear when the selection (expanded with `editor.getShapeAndDescendantIds`) contains at least one shape with rich text, and each shows as active when every text node already carries its mark. Try selecting a frame full of text and pressing "Bold all". For a lighter version that walks the JSON directly, see the [format rich text on multiple shapes](https://tldraw.dev/examples/rich-text-on-multiple-shapes) example. ## App.tsx ```tsx import { Fragment, Node, Schema } from '@tiptap/pm/model' import { DefaultStylePanel, DefaultStylePanelContent, Editor, ExtractShapeByProps, getSchema, JSONContent, tipTapDefaultExtensions, TLComponents, Tldraw, TldrawUiButton, TldrawUiButtonIcon, TldrawUiButtonLabel, TLRichText, TLShape, TLShapeId, TLUiStylePanelProps, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! const schema = getSchema(tipTapDefaultExtensions) type Style = 'bold' | 'italic' | 'highlight' const STYLES: { style: Style; icon: string; label: string }[] = [ { style: 'bold', icon: 'bold', label: 'Bold' }, { style: 'italic', icon: 'italic', label: 'Italic' }, { style: 'highlight', icon: 'highlight', label: 'Highlight' }, ] type RichTextShape = ExtractShapeByProps<{ richText: TLRichText }> function isRichTextShape(shape: TLShape): shape is RichTextShape { return 'richText' in shape.props } function isUniformlyMarked(doc: Node, markName: string): boolean { let hasText = false let allMarked = true doc.descendants((node) => { if (node.isText) { hasText = true if (!node.marks.some((m) => m.type.name === markName)) { allMarked = false } } }) return hasText && allMarked } // [1] function setMark(doc: Node, schema: Schema, markName: string, active: boolean): Node { const markType = schema.marks[markName] return mapTextNodes(doc, schema, (node) => { if (active) { return node.mark(markType.create().addToSet(node.marks)) } else { return node.mark(node.marks.filter((m) => m.type !== markType)) } }) } function mapTextNodes(node: Node, schema: Schema, fn: (textNode: Node) => Node): Node { if (node.isText) return fn(node) if (node.content.size === 0) return node const children: Node[] = [] node.content.forEach((child) => { children.push(mapTextNodes(child, schema, fn)) }) return node.copy(Fragment.from(children)) } // [2] function setMarkOnShape(editor: Editor, id: TLShapeId, style: Style, active: boolean) { const shape = editor.getShape(id) if (!shape) return if (isRichTextShape(shape)) { const richText = shape.props.richText const doc = Node.fromJSON(schema, richText as JSONContent) const updated = setMark(doc, schema, style, active) editor.updateShape({ id, type: shape.type, props: { richText: updated.toJSON() }, }) } else { editor .getSortedChildIdsForParent(id) .forEach((childId) => setMarkOnShape(editor, childId, style, active)) } } function isUniformlyStyled(editor: Editor, shapeId: TLShapeId, style: Style) { const shape = editor.getShape(shapeId) if (!shape || !isRichTextShape(shape)) return false const doc = Node.fromJSON(schema, shape.props.richText as JSONContent) return isUniformlyMarked(doc, style) } // [3] function CustomStylePanel(props: TLUiStylePanelProps) { const editor = useEditor() const selectedShapeIds = useValue('selected shape ids', () => editor.getSelectedShapeIds(), [ editor, ]) const allTextShapeIds = useValue( 'text shape ids', () => { const allIds = editor.getShapeAndDescendantIds(selectedShapeIds) return [...allIds].filter((id) => { const shape = editor.getShape(id) return !!shape && isRichTextShape(shape) }) }, [editor, selectedShapeIds] ) const hasTextShapes = allTextShapeIds.length > 0 return ( {hasTextShapes && (
{STYLES.map(({ style, icon, label }) => ( ))}
)}
) } // [4] function StyleButton({ style, icon, label, textShapeIds, }: { style: Style icon: string label: string textShapeIds: TLShapeId[] }) { const editor = useEditor() const isActive = useValue( `all ${style}`, () => textShapeIds.every((id) => isUniformlyStyled(editor, id, style)), [editor, textShapeIds, style] ) return ( { editor.run(() => { editor.markHistoryStoppingPoint(`toggle ${style}`) editor.getSelectedShapeIds().forEach((id) => { setMarkOnShape(editor, id, style, !isActive) }) }) }} title={`${label} all text in selected shapes`} > {label} all ) } const components: TLComponents = { StylePanel: CustomStylePanel, } export default function TextMassStyleUpdatesExample() { return (
) } /* This example adds bold, italic, and highlight buttons to the style panel that toggle the mark on all text in the selected shapes at once, including text shapes nested inside selected frames and groups. Rich text is a TipTap (ProseMirror) JSON document; rather than walk the JSON by hand we parse it into a ProseMirror `Node` and use its mark API. For a hand-rolled JSON version, see the "Format rich text on multiple shapes" example. [1] `setMark` and `mapTextNodes` rebuild a ProseMirror document with each text node's marks changed. ProseMirror nodes are immutable, so we return a new tree rather than mutating in place. [2] `setMarkOnShape` parses `shape.props.richText` with `Node.fromJSON`, using the schema built from tldraw's default TipTap extensions, and writes the result back with `toJSON()`. It handles both shapes with rich text (by rewriting the document) and container shapes like frames and groups (by recursing into their children via `getSortedChildIdsForParent`). The add/remove decision is made once per click: if every text node in every selected shape already has the mark, remove it everywhere; otherwise add it everywhere. [3] The custom `StylePanel` wraps `DefaultStylePanel` and adds a section above the default content. `getShapeAndDescendantIds` expands the selection to include nested shapes so the buttons appear when a frame containing text is selected. [4] Each button reads its active state inside `useValue`, so it stays in sync as the selection or the shapes' text changes. Reactivity here comes from `editor.getShape` being read inside the computation. */ ``` -------- # Add connected shape Category: UI & theming Keywords: plus button, quick connect, infrontofthecanvas, selection, arrow, bindings, duplicate, node, diagram, flowchart Show plus buttons around a selected shape that create a new connected shape, like in Figma. When a single shape is selected, four plus buttons appear on the edges of its selection bounds. Clicking one duplicates the shape in that direction and connects the two shapes with a bound arrow, then selects the new shape so you can keep extending the diagram. The buttons are rendered in the `InFrontOfTheCanvas` component slot and positioned by converting the shape's page bounds to viewport coordinates with `pageToViewport`. The connection is made by creating an arrow shape and binding both of its terminals with `createBindings`. ## App.tsx ```tsx import { DefaultColorStyle, Editor, TLComponents, Tldraw, TLShape, createShapeId, track, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' import './add-connected-shape.css' // There's a guide at the bottom of this file! // [1] const DIRECTIONS = [ { name: 'up', dx: 0, dy: -1 }, { name: 'right', dx: 1, dy: 0 }, { name: 'down', dx: 0, dy: 1 }, { name: 'left', dx: -1, dy: 0 }, ] as const type Direction = (typeof DIRECTIONS)[number] const GAP = 80 const BUTTON_OFFSET = 24 // [2] function addConnectedShape(editor: Editor, shape: TLShape, direction: Direction) { const bounds = editor.getShapePageBounds(shape.id) if (!bounds) return editor.run(() => { editor.markHistoryStoppingPoint('add connected shape') // [3] editor.duplicateShapes([shape.id], { x: direction.dx * (bounds.width + GAP), y: direction.dy * (bounds.height + GAP), }) // If duplication did nothing (e.g. a locked shape), the original is // still the only selected shape — don't connect it to itself. const newShape = editor.getOnlySelectedShape() if (!newShape || newShape.id === shape.id) return // [4] const color = editor.getShapeStyleIfExists(shape, DefaultColorStyle) const arrowId = createShapeId() editor.createShape({ id: arrowId, type: 'arrow', x: bounds.center.x, y: bounds.center.y, props: color ? { color } : {}, }) editor.createBindings([ { fromId: arrowId, toId: shape.id, type: 'arrow', props: { terminal: 'start', normalizedAnchor: { x: 0.5, y: 0.5 }, isExact: false, isPrecise: false, }, }, { fromId: arrowId, toId: newShape.id, type: 'arrow', props: { terminal: 'end', normalizedAnchor: { x: 0.5, y: 0.5 }, isExact: false, isPrecise: false, }, }, ]) }) } // [5] const AddConnectedShapeButtons = track(() => { const editor = useEditor() if (!editor.isIn('select.idle')) return null const shape = editor.getOnlySelectedShape() if (!shape || editor.isShapeOfType(shape, 'arrow')) return null const bounds = editor.getShapePageBounds(shape.id) if (!bounds) return null return ( <> {DIRECTIONS.map((direction) => { // [6] const edgeMidpoint = editor.pageToViewport({ x: bounds.center.x + direction.dx * (bounds.width / 2), y: bounds.center.y + direction.dy * (bounds.height / 2), }) return ( ) })} ) }) const components: TLComponents = { InFrontOfTheCanvas: AddConnectedShapeButtons, } export default function AddConnectedShapeExample() { return (
{ if (editor.getCurrentPageShapeIds().size > 0) return const id = createShapeId() const { x, y } = editor.getViewportPageBounds().center editor.createShape({ id, type: 'geo', x: x - 80, y: y - 50, props: { w: 160, h: 100, fill: 'semi', color: 'light-blue' }, }) editor.select(id) }} />
) } /* This example shows how to add "plus" buttons around a selected shape that create a new connected shape in that direction, similar to quick-connect affordances in tools like Figma and FigJam. [1] Each button corresponds to a direction. The dx/dy unit vector is used both to position the button on the selection edge and to place the new shape. [2] When a button is clicked, we create the new shape and connect it with an arrow inside a single `editor.run()` transaction. `markHistoryStoppingPoint` makes the whole operation undoable in one step. [3] `duplicateShapes` clones the selected shape (keeping its type, size, and styles) at a page-space offset in the chosen direction, and selects the copy — so the user can keep tapping a plus button to grow the diagram. [4] `getShapeStyleIfExists` reads a style from a shape, returning `undefined` when that shape type doesn't support the style — so the arrow's color is copied from the source shape when it has one. Without this, `createShape` would fill the color from the editor's "next shape" styles — whatever color was last active in the style panel — which usually won't match the shapes it connects. To connect the two shapes we create an arrow shape and bind each terminal to a shape with `createBindings`. With `isPrecise: false` the arrow targets the center of each shape and gracefully stops at the shape's outline, so it always leaves from the correct edge no matter where the shapes move. [5] The buttons are rendered in the `InFrontOfTheCanvas` component slot: above the canvas, below the rest of the UI. The component is wrapped in `track()` so it re-renders when the selection, camera, or state chart changes. We only show the buttons when exactly one non-arrow shape is selected and the select tool is idle, so they disappear while translating, resizing, or pointing. [6] The shape's page bounds are converted to viewport (screen) coordinates with `pageToViewport`, and each button is pushed a fixed number of screen pixels away from the edge so the buttons stay the same size at any zoom level. This example uses the shape's axis-aligned page bounds, so the buttons stay upright even when the shape is rotated. */ ``` ## add-connected-shape.css ```css .add-connected-button { position: absolute; top: -14px; left: -14px; width: 28px; height: 28px; border: none; border-radius: 50%; background: var(--tl-color-selection-stroke); color: var(--tl-color-selected-contrast); font-size: 18px; line-height: 1; cursor: pointer; pointer-events: all; display: flex; align-items: center; justify-content: center; box-shadow: var(--tl-shadow-1); opacity: 0.8; } .add-connected-button:hover { opacity: 1; } ``` -------- # Color picker Category: UI & theming Keywords: color, picker, theme, palette, custom, fonts, updatetheme, meta Add custom colors and fonts to the theme palette at runtime. A toolbar in the top-left adds new entries to the editor's color palette via a native color picker, and to the font palette via a curated Google Fonts dropdown. Each new entry shows up immediately in the style panel and applies to any selected shape. All possible custom slots (`custom-1..20`, `gf-1..10`) are declared up front via module augmentation and registered through a stable `themes` prop, so persisted shapes always pass validation. The actual colors and fonts are pushed into the live theme with `editor.updateTheme()`. The palette itself is stored on the document's `meta`, so it persists, syncs across tabs, and takes part in undo/redo together with the shapes that use it. Try adding a color, applying it to a shape, then pressing undo. ## App.tsx ```tsx import { useEffect, useMemo, useRef, useState } from 'react' import 'tldraw/tldraw.css' import './color-picker.css' import { DEFAULT_THEME, DefaultColorStyle, DefaultFontStyle, Editor, JsonObject, TLDOCUMENT_ID, TLDefaultColor, TLShape, TLShapePartial, TLTheme, TLThemeFont, TLThemes, TLUiOverrides, Tldraw, useValue, } from 'tldraw' // Pre-declare slot names for custom colors and fonts. The runtime only // fills the slots the user has actually added, but TypeScript needs concrete // keys to compute `TLDefaultColorStyle` / `TLDefaultFontStyle`. const MAX_CUSTOM_COLORS = 20 const MAX_CUSTOM_FONTS = 10 const PERSISTENCE_KEY = 'color-picker-example' type CustomColorKey = | 'custom-1' | 'custom-2' | 'custom-3' | 'custom-4' | 'custom-5' | 'custom-6' | 'custom-7' | 'custom-8' | 'custom-9' | 'custom-10' | 'custom-11' | 'custom-12' | 'custom-13' | 'custom-14' | 'custom-15' | 'custom-16' | 'custom-17' | 'custom-18' | 'custom-19' | 'custom-20' type CustomFontKey = | 'gf-1' | 'gf-2' | 'gf-3' | 'gf-4' | 'gf-5' | 'gf-6' | 'gf-7' | 'gf-8' | 'gf-9' | 'gf-10' declare module '@tldraw/tlschema' { interface TLThemeDefaultColors { 'custom-1': TLDefaultColor 'custom-2': TLDefaultColor 'custom-3': TLDefaultColor 'custom-4': TLDefaultColor 'custom-5': TLDefaultColor 'custom-6': TLDefaultColor 'custom-7': TLDefaultColor 'custom-8': TLDefaultColor 'custom-9': TLDefaultColor 'custom-10': TLDefaultColor 'custom-11': TLDefaultColor 'custom-12': TLDefaultColor 'custom-13': TLDefaultColor 'custom-14': TLDefaultColor 'custom-15': TLDefaultColor 'custom-16': TLDefaultColor 'custom-17': TLDefaultColor 'custom-18': TLDefaultColor 'custom-19': TLDefaultColor 'custom-20': TLDefaultColor } interface TLThemeFonts { 'gf-1': TLThemeFont 'gf-2': TLThemeFont 'gf-3': TLThemeFont 'gf-4': TLThemeFont 'gf-5': TLThemeFont 'gf-6': TLThemeFont 'gf-7': TLThemeFont 'gf-8': TLThemeFont 'gf-9': TLThemeFont 'gf-10': TLThemeFont } } interface GoogleFont { name: string family: string } const GOOGLE_FONTS: GoogleFont[] = [ { name: 'Roboto', family: "'Roboto', sans-serif" }, { name: 'Lato', family: "'Lato', sans-serif" }, { name: 'Open Sans', family: "'Open Sans', sans-serif" }, { name: 'Montserrat', family: "'Montserrat', sans-serif" }, { name: 'Raleway', family: "'Raleway', sans-serif" }, { name: 'Oswald', family: "'Oswald', sans-serif" }, { name: 'Playfair Display', family: "'Playfair Display', serif" }, { name: 'Merriweather', family: "'Merriweather', serif" }, { name: 'Pacifico', family: "'Pacifico', cursive" }, { name: 'Caveat', family: "'Caveat', cursive" }, { name: 'Permanent Marker', family: "'Permanent Marker', cursive" }, { name: 'Bebas Neue', family: "'Bebas Neue', sans-serif" }, ] // Fan a single hex onto every role in TLDefaultColor. The theme renderer // reads different roles for different contexts (outline vs fill vs note // background); we use the picked hex for all of them plus a translucent // variant for the semi fills. function makeColor(solid: string): TLDefaultColor { const translucent = solid + '33' return { solid, semi: translucent, pattern: solid, fill: solid, linedFill: translucent, frameHeadingStroke: solid, frameHeadingFill: translucent, frameStroke: solid, frameFill: translucent, frameText: solid, noteFill: translucent, noteText: solid, highlightSrgb: solid, highlightP3: solid, } } function makeFontEntry(family: string): TLThemeFont { return { fontFamily: family, icon:
Aa
, } } const customColorTranslations: Record = {} for (let i = 1; i <= MAX_CUSTOM_COLORS; i++) { customColorTranslations[`color-style.custom-${i}`] = `Custom ${i}` } const customFontTranslations: Record = {} for (let i = 1; i <= MAX_CUSTOM_FONTS; i++) { customFontTranslations[`font-style.gf-${i}`] = `Google font ${i}` } const uiOverrides: TLUiOverrides = { translations: { en: { ...customColorTranslations, ...customFontTranslations }, }, } // Inject one loading every curated Google Font family, so dropdown // previews render in the right typeface and canvas text picks up the family // once it's registered in the theme. let googleFontsLoaded = false function ensureGoogleFontsLoaded() { if (googleFontsLoaded) return googleFontsLoaded = true const families = GOOGLE_FONTS.map((f) => `family=${f.name.replace(/ /g, '+')}`).join('&') const link = document.createElement('link') link.rel = 'stylesheet' link.href = `https://fonts.googleapis.com/css2?${families}&display=swap` document.head.appendChild(link) } // The palette (which hex/family each `custom-*` / `gf-*` slot maps to) lives // on the tldraw document's `meta`. Shapes only persist the slot *key* (`custom-2`, // `gf-1`); this is where the slot's actual value is kept. Storing it in the // document — instead of a separate React/localStorage copy — means the editor // persists it (via `persistenceKey`), syncs it across tabs, and includes it in // undo/redo for free, always atomically with the shapes that reference it. There // is therefore nothing to hand-reconcile: no cross-tab listener, no load-time // recovery, no save-failure handling. const PALETTE_META_KEY = 'colorPickerPalette' interface Palette { hexes: string[] fonts: GoogleFont[] } function isGoogleFont(v: unknown): v is GoogleFont { return ( typeof v === 'object' && v !== null && typeof (v as GoogleFont).family === 'string' && typeof (v as GoogleFont).name === 'string' ) } // `meta` is free-form JSON, so normalise whatever we read into a known shape. // This also guards against a corrupt or hand-edited document. function parsePalette(raw: unknown): Palette { const obj = (raw ?? {}) as { hexes?: unknown; fonts?: unknown } return { hexes: Array.isArray(obj.hexes) ? obj.hexes.filter((h): h is string => typeof h === 'string').slice(0, MAX_CUSTOM_COLORS) : [], fonts: Array.isArray(obj.fonts) ? obj.fonts.filter(isGoogleFont).slice(0, MAX_CUSTOM_FONTS) : [], } } function readRawPalette(editor: Editor): unknown { return editor.getDocumentSettings().meta[PALETTE_META_KEY] } // Write the palette into the document `meta`. Call this inside `editor.run` so it // batches into one undo step with any shape repair that goes with it. function writePalette(editor: Editor, palette: Palette) { editor.store.update(TLDOCUMENT_ID, (doc) => ({ ...doc, meta: { ...doc.meta, [PALETTE_META_KEY]: palette as unknown as JsonObject }, })) } const isCustomColor = (v: unknown): v is string => typeof v === 'string' && /^custom-\d+$/.test(v) const isCustomFont = (v: unknown): v is string => typeof v === 'string' && /^gf-\d+$/.test(v) const DEFAULT_COLOR = DefaultColorStyle.defaultValue const DEFAULT_FONT = DefaultFontStyle.defaultValue // When the palette is cleared, the slots leave the *live* theme, so every // shape and the per-tab "next shape" style that still names a `custom-*` / `gf-*` // slot is remapped back to a built-in value (`black` / `draw`). The enum keeps // every slot registered (see `buildCompleteTheme`), so this isn't needed to keep // records valid — it just stops those shapes from rendering with an empty slot. // Run inside the same `editor.run` as the palette write so the two move together // through undo/redo. function repairShapesUsingCustomStyles(editor: Editor) { const updates: TLShapePartial[] = [] for (const record of editor.store.allRecords()) { if (record.typeName !== 'shape') continue const shape = record as TLShape const props = shape.props as Record const next: Record = {} if (isCustomColor(props.color)) next.color = DEFAULT_COLOR if (isCustomColor(props.labelColor)) next.labelColor = DEFAULT_COLOR if (isCustomFont(props.font)) next.font = DEFAULT_FONT if (Object.keys(next).length > 0) { updates.push({ id: shape.id, type: shape.type, props: next } as TLShapePartial) } } if (updates.length > 0) editor.updateShapes(updates) // `stylesForNextShape` lives on the per-tab `instance` record; reset any entry // that points at a slot we're removing so the next created shape doesn't // re-apply it. const stylesForNextShape = editor.getInstanceState().stylesForNextShape const fixed: Record = {} for (const [id, value] of Object.entries(stylesForNextShape)) { if (isCustomColor(value)) fixed[id] = DEFAULT_COLOR else if (isCustomFont(value)) fixed[id] = DEFAULT_FONT } if (Object.keys(fixed).length > 0) { editor.updateInstanceState({ stylesForNextShape: { ...stylesForNextShape, ...fixed } }) } } export default function ColorPickerExample() { const [editor, setEditor] = useState(null) // Register *every* possible slot up front (with placeholder values). Passed // as the stable `themes` prop, this makes `createTLStore` register the full // style enum before the persisted document is validated on load, so shapes // referencing any slot pass validation even before the palette is read. The // visible colors/fonts are pushed separately via `editor.updateTheme` below. const [initialThemes] = useState>(() => ({ default: buildCompleteTheme() })) // Read the palette straight from the document `meta`, reactively. Because // the store drives local edits, undo/redo, and cross-tab sync alike, this one // read covers all three with no extra plumbing. `useValue` returns the stored // reference (stable until the document record changes, so unrelated edits like // moving a shape don't churn it); `useMemo` normalises it. const rawPalette = useValue('palette', () => (editor ? readRawPalette(editor) : undefined), [ editor, ]) const palette = useMemo(() => parsePalette(rawPalette), [rawPalette]) // Push the palette's actual colors/fonts into the live theme. The style // panel and canvas read this, so only slots the palette contains are shown; the // complete prop's placeholder slots stay hidden. Runs on load, on every palette // change, and on undo/redo (all surface through `palette` above). useEffect(() => { if (!editor) return editor.updateTheme(buildTheme(palette.hexes, palette.fonts)) if (palette.fonts.length > 0) ensureGoogleFontsLoaded() }, [editor, palette]) const addColor = (hex: string) => { if (!editor || palette.hexes.length >= MAX_CUSTOM_COLORS) return const hexes = [...palette.hexes, hex] editor.run(() => { writePalette(editor, { hexes, fonts: palette.fonts }) // Put the new color into the live theme before applying it, so a // selected shape repaints with it immediately. The enum already knows the // slot (complete `themes` prop), so the style set never trips validation. editor.updateTheme(buildTheme(hexes, palette.fonts)) if (editor.getSelectedShapeIds().length > 0) { const key = `custom-${hexes.length}` as CustomColorKey editor.setStyleForSelectedShapes(DefaultColorStyle, key) } }) } const addFont = (font: GoogleFont) => { if (!editor || palette.fonts.length >= MAX_CUSTOM_FONTS) return if (palette.fonts.some((f) => f.family === font.family)) return const fonts = [...palette.fonts, font] ensureGoogleFontsLoaded() editor.run(() => { writePalette(editor, { hexes: palette.hexes, fonts }) editor.updateTheme(buildTheme(palette.hexes, fonts)) if (editor.getSelectedShapeIds().length > 0) { // DefaultFontStyle's static type is the four built-ins; the runtime // enum (complete `themes` prop) knows this slot. const key = `gf-${fonts.length}` as CustomFontKey editor.setStyleForSelectedShapes(DefaultFontStyle, key as 'draw') } }) } // Remove every custom color and font. We clear the palette and remap every // shape / next-shape style off the custom slots in a single `editor.run`, so // it's one undo step and the palette can never drift from the shapes that // reference it — undo restores both together, redo clears both together. const clearCustomStyles = () => { if (!editor) return editor.run(() => { repairShapesUsingCustomStyles(editor) writePalette(editor, { hexes: [], fonts: [] }) }) } const hasCustomStyles = palette.hexes.length > 0 || palette.fonts.length > 0 return (
setEditor(editor)} >
e.stopPropagation()}> = MAX_CUSTOM_COLORS} /> f.family)} addFont={addFont} isFull={palette.fonts.length >= MAX_CUSTOM_FONTS} /> {hasCustomStyles && ( )}
) } function buildTheme(hexes: string[], fonts: GoogleFont[]): TLTheme { const lightColors = { ...DEFAULT_THEME.colors.light } as TLTheme['colors']['light'] const darkColors = { ...DEFAULT_THEME.colors.dark } as TLTheme['colors']['dark'] for (let i = 0; i < hexes.length; i++) { const key = `custom-${i + 1}` as CustomColorKey const entry = makeColor(hexes[i]) lightColors[key] = entry darkColors[key] = entry } const themeFonts = { ...DEFAULT_THEME.fonts } as TLTheme['fonts'] for (let i = 0; i < fonts.length; i++) { const key = `gf-${i + 1}` as CustomFontKey themeFonts[key] = makeFontEntry(fonts[i].family) } return { ...DEFAULT_THEME, id: 'default', colors: { light: lightColors, dark: darkColors }, fonts: themeFonts, } } // A stable theme that registers *every* possible custom slot (`custom-1..N`, // `gf-1..N`). It's passed as the `themes` prop, which `createTLStore` registers // into the style enum *before* the persisted document is validated on load, and // which the editor re-registers on every render. Registering the full set means: // - persisted or cross-tab shapes can never reference a slot the enum doesn't // know, so they always pass validation (no load crash, no per-render drop); // - the enum is never narrowed, so adding/removing palette entries can't // invalidate existing shapes. // The placeholder values here are never shown: the style panel and canvas read // the *live* theme, which we set with `editor.updateTheme(buildTheme(...))` to // contain only the slots actually in the palette. function buildCompleteTheme(): TLTheme { const hexes = Array.from({ length: MAX_CUSTOM_COLORS }, () => '#000000') const fonts: GoogleFont[] = Array.from({ length: MAX_CUSTOM_FONTS }, (_, i) => ({ name: `placeholder-${i + 1}`, family: 'sans-serif', })) return buildTheme(hexes, fonts) } // Color add flow — the native picker opens immediately on "+ Add color". // The picker fires onChange continuously while dragging, so we stage a preview // and only commit on the explicit Add button. function AddColorButton({ addColor, isFull }: { addColor(hex: string): void; isFull: boolean }) { const [isStaging, setIsStaging] = useState(false) const [staged, setStaged] = useState(() => randomHex()) const inputRef = useRef(null) const open = () => { setStaged(randomHex()) setIsStaging(true) inputRef.current?.click() } const reopen = () => inputRef.current?.click() const commit = () => { addColor(staged) setIsStaging(false) } const cancel = () => setIsStaging(false) return (
setStaged(e.target.value)} className="color-picker-add-color__input" aria-hidden tabIndex={-1} /> {isStaging ? (
) : ( )}
) } // Font add flow — dropdown of curated Google Fonts. Selection is atomic // (one click = one commit), so no staging needed. Already-added fonts are // shown but disabled. function AddFontButton({ addedFamilies, addFont, isFull, }: { addedFamilies: string[] addFont(font: GoogleFont): void isFull: boolean }) { const [isOpen, setIsOpen] = useState(false) const containerRef = useRef(null) const open = () => { ensureGoogleFontsLoaded() setIsOpen(true) } const close = () => setIsOpen(false) useEffect(() => { if (!isOpen) return const handler = (e: MouseEvent) => { if (!containerRef.current?.contains(e.target as Node)) close() } document.addEventListener('mousedown', handler) return () => document.removeEventListener('mousedown', handler) }, [isOpen]) return (
{isOpen && (
{GOOGLE_FONTS.map((font) => { const alreadyAdded = addedFamilies.includes(font.family) return ( ) })}
)}
) } function randomHex(): string { const hue = Math.floor(Math.random() * 360) return hslToHex(hue, 70, 55) } function hslToHex(h: number, s: number, l: number): string { const sNorm = s / 100 const lNorm = l / 100 const k = (n: number) => (n + h / 30) % 12 const a = sNorm * Math.min(lNorm, 1 - lNorm) const f = (n: number) => Math.round(255 * (lNorm - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1))))) const toHex = (v: number) => v.toString(16).padStart(2, '0') return `#${toHex(f(0))}${toHex(f(8))}${toHex(f(4))}` } ``` ## color-picker.css ```css .color-picker-toolbar { position: absolute; top: 56px; left: 8px; display: flex; gap: 8px; pointer-events: all; z-index: 300; } .color-picker-button { padding: 6px 10px; font-size: 12px; font-weight: 500; border: 1px solid var(--tl-color-divider); border-radius: 8px; background: var(--tl-color-panel); color: var(--tl-color-text); cursor: pointer; box-shadow: var(--tl-shadow-1); line-height: 1; } .color-picker-button:hover:not(:disabled) { background: var(--tl-color-muted-2); } .color-picker-button:disabled { opacity: 0.5; cursor: not-allowed; } .color-picker-button--primary { background: var(--tl-color-selected); color: var(--tl-color-selected-contrast); border-color: var(--tl-color-selected); } .color-picker-button--primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--tl-color-selected); } .color-picker-button--icon { padding: 4px 8px; font-size: 14px; } .color-picker-add-color { position: relative; } .color-picker-add-color__input { position: absolute; inset: 0; opacity: 0; pointer-events: none; } .color-picker-add-color__staging { display: flex; align-items: center; gap: 6px; padding: 4px; background: var(--tl-color-panel); border: 1px solid var(--tl-color-divider); border-radius: 10px; box-shadow: var(--tl-shadow-1); } .color-picker-add-color__swatch { width: 28px; height: 28px; padding: 0; border: 1px solid var(--tl-color-divider); border-radius: 6px; cursor: pointer; } .color-picker-add-color__hex { font-family: var(--tl-font-mono, monospace); font-size: 11px; color: var(--tl-color-text); min-width: 64px; } .color-picker-add-font { position: relative; } .color-picker-font-dropdown { position: absolute; top: calc(100% + 4px); left: 0; min-width: 200px; max-height: 320px; overflow-y: auto; background: var(--tl-color-panel); border: 1px solid var(--tl-color-divider); border-radius: 10px; box-shadow: var(--tl-shadow-2); padding: 4px; display: flex; flex-direction: column; } .color-picker-font-dropdown__item { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 10px; font-size: 14px; background: transparent; border: none; border-radius: 6px; color: var(--tl-color-text); cursor: pointer; text-align: left; } .color-picker-font-dropdown__item:hover:not(:disabled) { background: var(--tl-color-muted-2); } .color-picker-font-dropdown__item:disabled { opacity: 0.5; cursor: not-allowed; } .color-picker-font-dropdown__added { font-size: 10px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--tl-color-text-3); } ``` -------- # Custom actions Category: UI & theming Keywords: actions, overrides, keyboard shortcuts, kbd, custom actions, useactions, helpers, addtoast, tluiactionitem Add a custom action and change an existing action's keyboard shortcut using the `overrides` prop. The `actions` override receives tldraw's default actions and returns the set to use. Here we add a `my-action` action that shows a toast when you press `S`, and change the delete action's shortcut to `Shift + X`. Try pressing `S` on the canvas to see the toast, then select a shape and press `Shift + X` to delete it. For more information on keyboard shortcuts see the [keyboard shortcuts example](https://tldraw.dev/examples/keyboard-shortcuts). ## App.tsx ```tsx import { Tldraw, TLUiActionItem, TLUiActionsContextType, TLUiOverrides } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const overrides: TLUiOverrides = { actions(_editor, actions, helpers) { const myCustomAction: TLUiActionItem = { id: 'my-action', label: 'My action', icon: 'circle', // [2] kbd: 's', onSelect(source) { // [3] helpers.addToast({ title: `My action was selected from ${source}!` }) }, } // [4] const newActions: TLUiActionsContextType = { ...actions, 'my-action': myCustomAction, delete: { ...actions['delete'], kbd: 'shift+x', }, } return newActions }, } export default function ActionOverridesExample() { return (
) } /* Tldraw's actions can be fired via keyboard shortcuts, or from anywhere in the user interface via the `useActions` hook. This example shows how to override tldraw's actions object via the Tldraw component's `overrides` prop. To learn more about surfacing actions in a customized menu, see the custom menus example. [1] Define the overrides outside of the component (or memoize them) so the object is stable across renders. The `actions` override receives the editor, the default actions, and a set of UI helpers, and returns the actions object to use. [2] Keyboard shortcuts use the same syntax as tldraw's built-in actions, e.g. `'s'` or `'shift+x'`. For more information on keyboard shortcuts see the keyboard shortcuts example. [3] UI helpers like `addToast`, `removeToast`, and `addDialog` are available on the helpers object. [4] Return a new object with the new action added. You can also modify existing actions, as shown here by changing the delete action's shortcut. */ ``` -------- # Custom error capture Category: UI & theming Keywords: error, ErrorFallback, error boundary, crash handling, getErrorAnnotations, sentry, debugging, error tracking Customize the error screen that appears when the editor crashes and read the annotations tldraw attaches to errors. When a critical error occurs in the editor, tldraw displays an error screen with options to refresh or reset. Override the `ErrorFallback` component in the `components` prop to replace it with your own. tldraw annotates errors with extra information about the editor's state at the time of the error, such as the active tool and the selected shapes. Read it with `getErrorAnnotations(error)` and forward it to your error tracking service (like Sentry). This example shows the annotations on screen instead. Click "Throw an error" to trigger a crash and see the custom fallback. A separate component, `ShapeErrorFallback`, handles errors in individual shapes; see the error boundary example for that. `ErrorFallback` handles editor-level errors that affect the entire application. ## App.tsx ```tsx import { getErrorAnnotations, Tldraw, TLEditorComponents, useEditor } from 'tldraw' import 'tldraw/tldraw.css' import './custom-error-capture.css' // There's a guide at the bottom of this file! // [1] const components: TLEditorComponents = { // [2] ErrorFallback: ({ error }) => { // [3] const annotations = error instanceof Error ? getErrorAnnotations(error) : null return (

Something went wrong

{error instanceof Error ? error.message : String(error)}
{/* [4] */} {annotations && (
{JSON.stringify(annotations, null, 2)}
)}
) }, // [5] InFrontOfTheCanvas: () => { const editor = useEditor() return ( ) }, } export default function CustomErrorCaptureExample() { return (
{/* [7] */}
) } /* [1] Define your component overrides outside of the React component so that they're static. If you must define them inside the component, wrap them in `useMemo` so they aren't recreated on every render. [2] `ErrorFallback` is displayed when a critical error occurs in the editor that would otherwise crash the entire application. This is different from `ShapeErrorFallback`, which handles errors in individual shapes. The component receives the error, so you can match it to your app's design and offer recovery options. [3] `getErrorAnnotations` retrieves the debugging information tldraw attaches to errors: tags (key-value pairs for categorization) and extras (additional context data such as the current tool or the selected shapes). This is what you'd forward to an error reporting service like Sentry. [4] Here we show the annotations on screen so you can see what's captured. In production you'd send them to your error tracking service instead of displaying them to users. [5] For this example, we've added a button in the `InFrontOfTheCanvas` slot that intentionally triggers an error so you can see the custom `ErrorFallback` in action. In a real application the fallback only appears when genuine errors occur. [6] Creating a shape with an unknown type throws inside the editor, which is enough to trip the error boundary. The `@ts-expect-error` is there because TypeScript rightly rejects the bad type. [7] Pass the components to the `Tldraw` component via the `components` prop. */ ``` ## custom-error-capture.css ```css .custom-error__button { position: absolute; top: 100px; left: 100px; pointer-events: all; } .custom-error { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 8px; align-items: center; justify-content: center; background: #f5f5f5; } .custom-error__annotations { margin: 8px 0; padding: 8px; background: white; border: 1px solid #ccc; border-radius: 4px; font-size: 12px; max-width: 600px; max-height: 300px; overflow-y: auto; text-align: left; } ``` -------- # Custom indicators Category: UI & theming Keywords: indicators, shape indicator, overlay, overlayutils, shapeindicatoroverlayutil, getrenderingshapes Change when shape indicators are shown by replacing the shape indicator overlay util. Shape indicators are the outlines drawn around a shape when you hover or select it. They're rendered by `ShapeIndicatorOverlayUtil`. Subclass it, override `getOverlays()` to return the ids you want outlined, and pass it in the `overlayUtils` prop. Because it shares the built-in util's `type`, it replaces the default rather than adding a second layer. This example outlines every rendered shape all of the time. Try adding shapes or zooming out; each visible shape, including the group's children, keeps its outline. ## App.tsx ```tsx import { createShapeId, ShapeIndicatorOverlayUtil, TLShapeIndicatorOverlay, Tldraw, toRichText, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] class AllShapesIndicatorOverlayUtil extends ShapeIndicatorOverlayUtil { override getOverlays(): TLShapeIndicatorOverlay[] { const ids = this.editor.getRenderingShapes().map((s) => s.id) if (ids.length === 0) return [] return [ { id: 'shape_indicator', type: 'shape_indicator', props: { idsToDisplay: ids, hintingShapeIds: [] }, }, ] } } // [2] const overlayUtils = [AllShapesIndicatorOverlayUtil] export default function IndicatorsLogicExample() { return (
{ if (editor.getCurrentPageShapeIds().size === 0) { const bottomLeftA = createShapeId() const bottomLeftB = createShapeId() editor.createShapes([ { type: 'geo', x: 100, y: 100 }, { type: 'geo', x: 500, y: 150, props: { geo: 'ellipse' } }, { id: bottomLeftA, type: 'geo', x: 100, y: 500 }, { id: bottomLeftB, type: 'geo', x: 250, y: 400 }, { type: 'text', x: 500, y: 500, props: { richText: toRichText('Hello, world!') } }, ]) editor.groupShapes([bottomLeftA, bottomLeftB]) editor.setSelectedShapes([]) } }} />
) } /* Shape indicators are the outlines drawn around hovered and selected shapes. They're painted by `ShapeIndicatorOverlayUtil`, an overlay util, so changing when they appear means replacing that util. [1] Subclass `ShapeIndicatorOverlayUtil` and override `getOverlays()`. The default only lists selected, hovered, and hinted shapes; here we list every shape currently being rendered, so all of them get an outline all of the time. Filter the ids to indicate only some shapes. `render()` is inherited, so the outlines still look like the built-in ones. [2] Pass the util via `overlayUtils`. It has the same `static type` (`'shape_indicator'`) as the built-in util, so it replaces it instead of running alongside it. Defining the array at module level keeps `` from seeing a new array on every render. */ ``` -------- # Custom keyboard shortcuts Category: UI & theming Keywords: shortcuts, hotkeys, keybindings, kbd, overrides, actions, tools, customize Change tldraw's default keyboard shortcuts for tools and actions. Shortcuts are the `kbd` field on tool and action definitions. Use the `actions` and `tools` functions of `TLUiOverrides` to return copies with different `kbd` strings, then pass the overrides to ``. The keyboard shortcuts dialog reads the same field, so it updates automatically. Try it: - Press `x` to toggle the grid - Press `p` to select the draw tool - Press `cmd+1` (or `ctrl+1`) to copy the selection as a PNG For adding shortcuts to custom tools, see the custom config example. ## App.tsx ```tsx import { TLUiOverrides, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const overrides: TLUiOverrides = { // [a] actions(_editor, actions) { return { ...actions, 'toggle-grid': { ...actions['toggle-grid'], kbd: 'x' }, 'copy-as-png': { ...actions['copy-as-png'], kbd: 'cmd+1,ctrl+1' }, } }, // [b] tools(_editor, tools) { return { ...tools, draw: { ...tools.draw, kbd: 'p' } } }, } export default function KeyboardShortcutsExample() { return (
{/* [2] */}
) } /* Keyboard shortcuts belong to either tools (draw, eraser, ...) or actions (undo, group, toggle grid, ...). Both are described by objects with a `kbd` string, so changing a shortcut is a matter of returning a copy of the object with a different `kbd`. The `kbd` syntax is a comma-separated list of key combos, e.g. `'x'`, `'shift+x'`, `'cmd+1,ctrl+1'` (the second combo covers Windows and Linux). The keyboard shortcuts dialog reads the same `kbd` strings, so it stays in sync with your overrides. [1] `overrides` is a `TLUiOverrides` object. Each function receives the defaults and returns the replacements. It's defined at module level so `` doesn't see a new object on every render. [a] `toggle-grid` moves from cmd+' to `x`, and `copy-as-png` moves from cmd+shift+c to cmd+1. The override replaces the default shortcut rather than adding to it. [b] The draw tool moves from `d` to `p`. [2] Pass the overrides to ``. Open the keyboard shortcuts dialog from the help menu to see the new bindings. For shortcuts on custom tools, see the custom config example. */ ``` -------- # Escape shape focus trap Category: UI & theming Keywords: tab, keyboard navigation, accessibility, a11y, shape toolbar, focus, contextual toolbar, keyboard Tab from a selected shape into a custom contextual toolbar instead of cycling to the next shape. By default tldraw traps the Tab key while shapes are selected and uses it to move between shapes. This example intercepts that with a capture-phase `keydown` listener registered in `onMount`, so it runs before tldraw's own handler and can call `stopImmediatePropagation()`. - Tab with a shape selected and focus on the canvas moves focus to the first toolbar button. - Tab and Shift+Tab inside the toolbar cycle between its buttons. - Tab on the last button (or Shift+Tab on the first) returns focus to the canvas and restores shape navigation. - Escape inside the toolbar also returns focus to the canvas. Try it: click a shape, then press Tab to focus the toolbar. Use Tab and Shift+Tab to move between buttons, and Escape to return to the canvas. ## App.tsx ```tsx import { useCallback } from 'react' import { Box, Tldraw, TldrawUiButtonIcon, TldrawUiContextualToolbar, TldrawUiToolbarButton, TLEditorComponents, track, useEditor, } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const ShapeToolbar = track(() => { const editor = useEditor() const showToolbar = editor.isIn('select.idle') && editor.getOnlySelectedShapeId() // [2] const handleReturn = useCallback(() => { editor.getContainer().focus() }, [editor]) if (!showToolbar) return null // [3] const getSelectionBounds = () => { const fullBounds = editor.getSelectionRotatedScreenBounds() if (!fullBounds) return undefined return new Box(fullBounds.x, fullBounds.y, fullBounds.width, 0) } return ( { editor.duplicateShapes(editor.getSelectedShapes()) handleReturn() }} > { editor.deleteShapes(editor.getSelectedShapeIds()) handleReturn() }} > ) }) const components: TLEditorComponents = { InFrontOfTheCanvas: ShapeToolbar, } export default function EscapeShapeFocusTrapExample() { return (
{ editor.createShape({ type: 'geo', x: 400, y: 200 }) // [4] const container = editor.getContainer() const getToolbar = () => container.querySelector('.tlui-contextual-toolbar') // [5] function enableFocusRing() { container.classList.remove('tl-container__no-focus-ring') } function handleKeyDown(e: KeyboardEvent) { const toolbarEl = getToolbar() const isInToolbar = toolbarEl?.contains(document.activeElement) // [6] if (e.key === 'Tab' && !isInToolbar) { const hasSelected = editor.getOnlySelectedShapeId() !== null const isOnCanvas = document.activeElement === container || document.activeElement?.classList.contains('tl-container') if (hasSelected && isOnCanvas && !e.shiftKey) { e.preventDefault() e.stopImmediatePropagation() const btn = toolbarEl?.querySelector('button') if (btn) { btn.focus() enableFocusRing() } } return } // [7] if (e.key === 'Tab' && isInToolbar && toolbarEl) { const buttons = Array.from(toolbarEl.querySelectorAll('button')) const currentIndex = buttons.indexOf(document.activeElement as HTMLElement) if (currentIndex === -1) return e.preventDefault() e.stopImmediatePropagation() if (e.shiftKey) { if (currentIndex === 0) { container.focus() } else { buttons[currentIndex - 1].focus() } } else { if (currentIndex === buttons.length - 1) { container.focus() } else { buttons[currentIndex + 1].focus() } } enableFocusRing() return } // [8] if (e.key === 'Escape' && isInToolbar) { e.preventDefault() e.stopImmediatePropagation() container.focus() } } // [9] container.addEventListener('keydown', handleKeyDown, { capture: true }) return () => container.removeEventListener('keydown', handleKeyDown, { capture: true }) }} />
) } /* [1] A contextual toolbar that appears above the selected shape. `track()` re-renders it whenever the editor state it reads (the tool state and the selection) changes. [2] Moving focus back to the container hands Tab back to tldraw's built-in shape navigation. [3] Position the toolbar on the top edge of the selection, the same pattern used in the contextual toolbar example. [4] The keyboard interception is registered in `onMount` so its cleanup runs when the editor unmounts. [5] Because we call `stopImmediatePropagation()` in [6] and [7], the editor's `FocusManager` (which listens on `document.body`) never sees the Tab key and so never removes `tl-container__no-focus-ring`. Removing it ourselves keeps the focus outline visible on the toolbar buttons. [6] Tab with focus on the canvas and one shape selected: focus the first toolbar button instead of letting tldraw cycle to the next shape. [7] Tab inside the toolbar cycles between its buttons. Tab on the last button or Shift+Tab on the first returns focus to the canvas, so focus can't leak into unrelated UI. [8] Escape inside the toolbar returns focus to the canvas. [9] The listener is registered with `capture: true` so it runs before tldraw's own bubble-phase handler in `useDocumentEvents`, which is what makes `stopImmediatePropagation()` effective. */ ``` -------- # Overlay theme colors Category: UI & theming Keywords: theme, overlay, brush, selection, snap, laser, color Restyle the brush, selection, snap lines, and laser with theme colors. Canvas overlays read their colors from the active theme. Overriding `brushFill`, `brushStroke`, `selectionFill`, `selectionStroke`, `selectedContrast`, `snap`, and `laser` on the theme restyles every built-in overlay in one place — no subclassing needed. This example swaps all of them for a magenta palette. ## App.tsx ```tsx import { DEFAULT_THEME, TLTheme, TLThemes, Tldraw, structuredClone } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const OVERLAY_COLORS_LIGHT = { brushFill: 'rgba(236, 72, 153, 0.15)', brushStroke: 'rgba(236, 72, 153, 0.6)', selectionFill: 'rgba(236, 72, 153, 0.05)', selectionStroke: 'rgb(236, 72, 153)', selectedContrast: '#ffffff', snap: 'rgb(236, 72, 153)', laser: 'rgb(236, 72, 153)', } const OVERLAY_COLORS_DARK = { brushFill: 'rgba(236, 72, 153, 0.2)', brushStroke: 'rgba(236, 72, 153, 0.6)', selectionFill: 'rgba(236, 72, 153, 0.1)', selectionStroke: 'rgb(236, 72, 153)', selectedContrast: '#ffffff', snap: 'rgb(236, 72, 153)', laser: 'rgb(236, 72, 153)', } // [2] const magentaTheme: TLTheme = structuredClone(DEFAULT_THEME) Object.assign(magentaTheme.colors.light, OVERLAY_COLORS_LIGHT) Object.assign(magentaTheme.colors.dark, OVERLAY_COLORS_DARK) const themes: Partial = { default: magentaTheme } export default function OverlayThemeColorsExample() { return (
{/* [3] */}
) } /* Canvas overlays read their colors from the active theme. This lets you restyle the brush, selection outline, snap indicators, laser pointer, and handle contrast color in one place — no need to subclass every built-in overlay util. The overlay-related keys on `TLThemeColors` are: - `brushFill`, `brushStroke` — the drag-select rectangle. - `selectionFill`, `selectionStroke` — the selection bounding box. - `selectedContrast` — handle fill color against the selection stroke. - `snap` — snap indicator lines. - `laser` — laser pointer trail color. Try drag-selecting (brush), selecting a shape (selection + handles), drawing with the laser tool, or moving a shape next to another (snap lines). [1] Define the overlay-related color overrides. `TLThemeColors` contains many more keys — shape palette colors (`red`, `blue`, …), text, background, cursor — that we want to leave alone. [2] Clone `DEFAULT_THEME` and merge only the overlay overrides into the `light` and `dark` palettes. The shape palette and UI chrome stay as-is. [3] Pass the modified theme under the `default` key. `` registers it at mount time — no module augmentation needed because we're updating the already-registered `default` theme rather than adding a new named theme. */ ``` -------- # Selection color condition Category: UI & theming Keywords: selection, color, conditional styling, css variables, react, getselectedshapes, isshapeoftype, css class Turn the selection red whenever every selected shape is a rectangle. Selection colors are part of the editor's theme (`selectionStroke` and `selectionFill` in `TLTheme`), so changing them means swapping the theme rather than overriding CSS variables. This example clones `DEFAULT_THEME` into a red variant, then uses `react` inside `onMount` to watch `editor.getSelectedShapes()` and call `editor.updateTheme` with either variant depending on the selection. Try selecting the two rectangles (red), then add the ellipse to the selection (back to blue). ## App.tsx ```tsx import { DEFAULT_THEME, TLTheme, Tldraw, react, structuredClone } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! // [1] const RECTANGLE_SELECTION_THEME: TLTheme = structuredClone(DEFAULT_THEME) RECTANGLE_SELECTION_THEME.colors.light.selectionStroke = '#cc0000' RECTANGLE_SELECTION_THEME.colors.light.selectionFill = 'rgba(255, 68, 68, 0.24)' RECTANGLE_SELECTION_THEME.colors.dark.selectionStroke = '#ff4444' RECTANGLE_SELECTION_THEME.colors.dark.selectionFill = 'rgba(255, 68, 68, 0.32)' export default function SelectionColorConditionExample() { return (
{ // [2] const stopListening = react('update selection theme', () => { const selectedShapes = editor.getSelectedShapes() // [3] const allAreRectangles = selectedShapes.length > 0 && selectedShapes.every( (shape) => editor.isShapeOfType(shape, 'geo') && shape.props.geo === 'rectangle' ) // [4] editor.updateTheme({ ...(allAreRectangles ? RECTANGLE_SELECTION_THEME : DEFAULT_THEME), id: 'default', }) }) // [5] editor .createShapes([ { type: 'geo', x: 0, y: 0 }, { type: 'geo', x: 120, y: 0 }, ]) .selectAll() .zoomToSelection() .createShape({ type: 'geo', x: 60, y: 120, props: { geo: 'ellipse' } }) return stopListening }} />
) } /* This example changes the selection color based on which shapes are selected: red when every selected shape is a rectangle, the default blue otherwise. [1] Selection colors live on the theme (`selectionStroke` and `selectionFill`), not in CSS variables, because the selection overlays are drawn to canvas. We clone DEFAULT_THEME and override those two colors for both light and dark modes. [2] `react` runs the callback once, then again whenever any signal it read changes. Here it reads the selection, so it re-runs on every selection change. It returns a disposer, which we return from onMount so it's cleaned up when the editor unmounts. [3] Change this condition to check for any shape type or combination. [4] `editor.updateTheme` replaces the theme registered under the given id. Both variants keep the id 'default', so this swaps the current theme in place and leaves the module-level DEFAULT_THEME object untouched. [5] Some shapes to test with. The two rectangles are selected on load. */ ``` -------- # Stroke size picker Category: UI & theming Keywords: stroke, size, picker, pen, draw, style panel, styleprop, custom styles Give the draw tool twelve stroke sizes instead of four. The draw tool's built-in size style has only four values (s, m, l, xl). This example gives draw shapes a numeric stroke size style defined with `StyleProp.define`, wires it into the draw shape's stroke width with `DrawShapeUtil.configure`, and composes a custom style panel that swaps the built-in size picker for a twelve-option preset picker. The picker only appears when the draw tool is active or draw shapes are selected; every other shape keeps the default size picker. To use a custom style with a custom shape instead, check the [custom shape with custom styles example](https://tldraw.dev/examples/shape-with-custom-styles). ## App.tsx ```tsx import { DefaultStylePanel, DrawShapeUtil, StyleProp, StylePanelArrowKindPicker, StylePanelArrowheadPicker, StylePanelColorPicker, StylePanelDashPicker, StylePanelFillPicker, StylePanelFontPicker, StylePanelGeoShapePicker, StylePanelLabelAlignPicker, StylePanelOpacityPicker, StylePanelSection, StylePanelSizePicker, StylePanelSplinePicker, StylePanelTextAlignPicker, T, TLComponents, TLUiStylePanelProps, Tldraw, drawShapeProps, useStylePanelContext, } from 'tldraw' import 'tldraw/tldraw.css' import './stroke-size-picker.css' // [1] const strokeSizeStyle = StyleProp.define('example:strokeSize', { defaultValue: 4, type: T.number, }) // [2] declare module '@tldraw/tlschema' { interface TLDrawShapeProps { strokeSize: number } } // [3] class CustomDrawShapeUtil extends DrawShapeUtil.configure({ getCustomDisplayValues(_editor, shape) { return { strokeWidth: shape.props.strokeSize } }, }) { static override props = { ...drawShapeProps, strokeSize: strokeSizeStyle } override getDefaultProps() { return { ...super.getDefaultProps(), strokeSize: strokeSizeStyle.defaultValue } } } const shapeUtils = [CustomDrawShapeUtil] const STROKE_SIZE_PRESETS = [1, 2, 3, 4, 6, 8, 10, 12, 16, 20, 26, 32] // [4] function StrokeSizePicker() { const { styles, onValueChange, onHistoryMark } = useStylePanelContext() const strokeSize = styles.get(strokeSizeStyle) // [5] if (strokeSize === undefined) return const value = strokeSize.type === 'mixed' ? null : strokeSize.value return (
{STROKE_SIZE_PRESETS.map((size) => ( ))}
) } // [6] function CustomStylePanel(props: TLUiStylePanelProps) { return ( ) } const components: TLComponents = { StylePanel: CustomStylePanel, } export default function StrokeSizePickerExample() { return (
{ editor.setCurrentTool('draw') }} />
) } /* This example replaces the draw tool's four stroke sizes (s, m, l, xl) with a custom numeric stroke size style, controlled from the style panel by a twelve-option preset picker. [1] We define a numeric style prop for the stroke size. Because it's a style (rather than a plain shape prop), the editor remembers the most recent value for the next shape you draw, shows it in the style panel whenever it's relevant, and reports a "mixed" value when a multi-shape selection disagrees. [2] We extend the draw shape's props interface via declaration merging, so `shape.props.strokeSize` is fully typed everywhere in this file. [3] We customize the default draw shape in two steps. `DrawShapeUtil.configure` overrides `getCustomDisplayValues`, which the draw shape resolves its stroke width through, so rendering, hit testing, and image exports all use our custom size. The subclass then adds the style to the shape's props and default props, which registers it with the editor's styles system and the store's validator. Passing the util to `Tldraw` via the `shapeUtils` prop replaces the built-in draw shape util, so the default draw tool picks it up automatically. [4] The picker reads the current value from `useStylePanelContext`. Its `onValueChange` helper applies the style to any selected shapes and remembers it for the next shapes, exactly like the built-in pickers. [5] The style map only contains the stroke size style when it's relevant: when the draw tool is active, or when the selection includes draw shapes. Everywhere else (geo shapes, arrows, text, and so on) we fall back to the default four-value size picker, since those shapes still use the built-in size style. [6] We compose the style panel from the same building blocks as the default panel, swapping the size picker slot for our stroke size picker. See `DefaultStylePanelContent` for the full list of available sections. Make sure to forward the panel's props to `DefaultStylePanel`: the editor passes `isMobile` when it renders the panel inside the mobile toolbar popover. */ ``` ## stroke-size-picker.css ```css .stroke-size-picker { display: grid; grid-template-columns: repeat(6, 1fr); } .stroke-size-picker__preset { all: unset; display: flex; align-items: center; justify-content: center; height: 32px; border-radius: var(--tl-radius-2); cursor: pointer; } .stroke-size-picker__preset:hover { background: var(--tl-color-muted-2); } .stroke-size-picker__preset[data-active='true'] { background: var(--tl-color-hint); } .stroke-size-picker__dot { border-radius: 50%; background: var(--tl-color-text-1); } ``` -------- # Dark mode Category: UI & theming Keywords: dark mode, theme, system preferences, color scheme, colorscheme Start the editor in dark mode with the `colorScheme` prop. Pass `colorScheme="dark"` to `` to render in dark mode. The prop accepts `'light'` (the default), `'dark'`, or `'system'`, which follows the operating system's preference. The prop only sets the default. If the user has a `colorScheme` set in their preferences (for example via `editor.user.updateUserPreferences`), that preference wins. To let users switch at runtime, see the toggle dark mode example. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function DarkModeExample() { return (
) } /* The `colorScheme` prop sets the editor's default color scheme: 'light' (the default), 'dark', or 'system' to follow the OS preference. A user preference set via `editor.user.updateUserPreferences({ colorScheme })` takes priority over this prop, so a persisted user preference from another example may override it. See the dark-mode-toggle example for switching at runtime. */ ``` -------- # Force mobile layout Category: UI & theming Keywords: mobile, responsive, breakpoint, forcemobile, layout, ui layout Force the UI to use the mobile layout regardless of screen size. The `forceMobile` prop pins tldraw's UI to the mobile breakpoint, so the toolbar and menus render in their compact mobile arrangement even in a wide window. Without it, the layout is chosen from the width of the editor's container. Try resizing the window: the layout stays in mobile mode. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function ForceMobileExample() { return (
) } /* The `forceMobile` prop pins the UI to the mobile breakpoint regardless of the container's width. Useful for previewing the mobile layout on desktop, or when the editor is embedded in a narrow panel where the desktop layout wouldn't fit. */ ``` -------- # Toggle dark mode Category: UI & theming Keywords: theme, dark mode, light mode, colorscheme, user preferences, updateuserpreferences, getisdarkmode, setcolormode Toggle between light and dark mode by updating the user's `colorScheme` preference. The user's `colorScheme` preference is the source of truth for the editor's color mode. This example adds a button to the `TopPanel` slot that reads the current mode with `editor.user.getIsDarkMode()` and flips it with `editor.user.updateUserPreferences({ colorScheme })`. `editor.setColorMode()` is a shorthand for the same update. Try clicking the button at the top of the page. Because user preferences are persisted to local storage, the setting is remembered across reloads. To set a default without a toggle, see the dark mode example. ## App.tsx ```tsx import { TLComponents, Tldraw, TldrawUiButton, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! function DarkModeButton() { const editor = useEditor() // [1] const isDark = useValue('isDark', () => editor.user.getIsDarkMode(), [editor]) return (
editor.user.updateUserPreferences({ colorScheme: isDark ? 'light' : 'dark' }) } > {isDark ? 'Switch to light mode' : 'Switch to dark mode'}
) } const components: TLComponents = { TopPanel: DarkModeButton, } export default function DarkModeToggleExample() { return (
) } /* [1] `editor.user.getIsDarkMode()` resolves the user's `colorScheme` preference (including 'system') to a boolean. Reading it inside `useValue` keeps the button label in sync when the preference changes from anywhere, e.g. the toggle in the main menu. [2] `editor.setColorMode('dark')` is a shorthand for the same preference update. */ ``` -------- # Inspector panel Category: UI & theming Keywords: inspector, properties, props, selection, panel, debug, usevalue, bindings, shared styles, getselectedshapes, getbindingsinvolvingshape, editorprovider Show the properties, shared styles, and bindings of the current selection in a side panel. The panel is a plain React component rendered next to `` rather than inside it. The editor instance is captured from `onMount` and passed to `EditorProvider`, which makes `useEditor()` and `useValue()` work outside the canvas. With one shape selected it lists the shape's record fields and `props`, plus any bindings from `editor.getBindingsInvolvingShape()`. With several selected it shows `editor.getSharedStyles()`, marking styles that differ across the selection as mixed. Try selecting a shape, then drawing an arrow to it and selecting the arrow to see its binding. Select several shapes with different colors to see mixed styles. ## App.tsx ```tsx import { useState } from 'react' import { Editor, EditorProvider, SharedStyle, StyleProp, TLBinding, TLShapeId, Tldraw, useColorMode, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './inspector-panel.css' // There's a guide at the bottom of this file! function InspectorPanel() { const editor = useEditor() // [1] const selectedShapes = useValue('selected shapes', () => editor.getSelectedShapes(), [editor]) const sharedStyles = useValue('shared styles', () => editor.getSharedStyles(), [editor]) const bindings = useValue( 'bindings', () => { const only = editor.getOnlySelectedShape() return only ? editor.getBindingsInvolvingShape(only.id) : [] }, [editor] ) if (selectedShapes.length === 0) { return (

Inspector

No shape selected

) } if (selectedShapes.length > 1) { return (

Inspector

{sharedStyles.size > 0 && (

Shared styles

{Array.from(sharedStyles.entries()).map(([styleProp, sharedStyle]) => ( ))}
)}

{selectedShapes.length} shapes selected

) } const [selectedShape] = selectedShapes const { props, ...rest } = selectedShape return (

Inspector

{Object.entries(rest).map(([key, value]) => ( ))}
{Object.keys(props).length > 0 && (

Shape props

{Object.entries(props).map(([key, value]) => ( ))}
)} {bindings.length > 0 && (

Bindings ({bindings.length})

{bindings.map((binding) => ( ))}
)}
) } // [2] function SharedStyleRow({ styleProp, sharedStyle, }: { styleProp: StyleProp sharedStyle: SharedStyle }) { const isMixed = sharedStyle.type === 'mixed' return (
{styleProp.id.replace('tldraw:', '')}: {isMixed ? '(mixed)' : formatValue(sharedStyle.value)}
) } function formatValue(val: unknown): string { if (val === null || val === undefined) return String(val) if (typeof val === 'string') return `"${val}"` if (Array.isArray(val)) return `Array(${val.length})` if (typeof val === 'object') return `Object(${Object.keys(val).length} keys)` return String(val) } function PropertyRow({ name, value }: { name: string; value: unknown }) { const [isExpanded, setIsExpanded] = useState(false) const isObject = value !== null && typeof value === 'object' if (!isObject) { return (
{name}: {formatValue(value)}
) } return (
{name}: {formatValue(value)}
{isExpanded && (
{JSON.stringify(value, null, 2)}
)}
) } // [3] function BindingRow({ binding, selectedShapeId, }: { binding: TLBinding selectedShapeId: TLShapeId }) { const editor = useEditor() const isFrom = binding.fromId === selectedShapeId const otherShapeId = isFrom ? binding.toId : binding.fromId const otherShape = useValue('other shape', () => editor.getShape(otherShapeId), [ editor, otherShapeId, ]) return (
{binding.type} ({isFrom ? 'from' : 'to'})
{otherShape && } {Object.keys(binding.props).length > 0 && }
) } // [4] function InspectorPanelWrapper() { const colorMode = useColorMode() return (
) } // [5] export default function InspectorPanelExample() { const [editor, setEditor] = useState(null) return (
{editor && ( )}
) } /* [1] Everything the panel shows is read inside `useValue`, so the panel re-renders whenever the selection or the selected shapes' records change. `getSharedStyles()` and `getBindingsInvolvingShape()` are the same APIs the style panel and arrow bindings use. [2] `getSharedStyles()` returns a map from `StyleProp` to a `SharedStyle`: either `{ type: 'shared', value }` when every selected shape agrees, or `{ type: 'mixed' }`. [3] Bindings are directional records with `fromId` and `toId`. For an arrow bound to a shape, the arrow is `from` and the shape is `to`. [4] Components rendered outside `` don't inherit its theme class, so we apply `tl-theme__dark` / `tl-theme__light` ourselves based on `useColorMode()`. [5] The panel lives outside ``, so it can't call `useEditor()` on its own. We grab the editor from `onMount` and wrap the panel in `EditorProvider` to make the editor hooks work there. */ ``` ## inspector-panel.css ```css .example-container { display: flex; height: 100vh; width: 100%; } .canvas-container { flex: 1; height: 100vh; } /* Theme variables */ .tl-theme__light .inspector-panel { --inspector-bg: white; --inspector-border: #ccc; --inspector-text: inherit; --inspector-heading: #666; --inspector-muted: #666; --inspector-value: #333; --inspector-btn-bg: #e0e0e0; --inspector-btn-border: #ccc; --inspector-btn-text: inherit; --inspector-btn-hover: #d0d0d0; --inspector-btn-active: #c0c0c0; --inspector-json-bg: #f8f8f8; --inspector-json-border: #e0e0e0; --inspector-json-text: #444; --inspector-binding-bg: #f9f9f9; --inspector-binding-border: #007acc; --inspector-binding-type: #007acc; --inspector-binding-dir-bg: #e0e0e0; --inspector-binding-dir-text: #666; } .tl-theme__dark .inspector-panel { --inspector-bg: #2a2a2a; --inspector-border: #555; --inspector-text: #e0e0e0; --inspector-heading: #aaa; --inspector-muted: #aaa; --inspector-value: #ddd; --inspector-btn-bg: #555; --inspector-btn-border: #666; --inspector-btn-text: #e0e0e0; --inspector-btn-hover: #666; --inspector-btn-active: #777; --inspector-json-bg: #1e1e1e; --inspector-json-border: #555; --inspector-json-text: #ddd; --inspector-binding-bg: #333; --inspector-binding-border: #4da6ff; --inspector-binding-type: #4da6ff; --inspector-binding-dir-bg: #555; --inspector-binding-dir-text: #ccc; } .inspector-panel { width: 300px; background: var(--inspector-bg); border-left: 1px solid var(--inspector-border); color: var(--inspector-text); padding: 16px; font-family: monospace; font-size: 12px; overflow-y: auto; } .inspector-panel h3 { margin: 0 0 16px 0; font-size: 14px; font-weight: bold; } .inspector-panel h4 { margin: 16px 0 8px 0; font-size: 12px; font-weight: bold; color: var(--inspector-heading); text-transform: uppercase; } .inspector-panel h4:first-child { margin-top: 0; } .inspector-panel p { margin: 0; color: var(--inspector-muted); font-style: italic; } .inspector-section { margin-bottom: 16px; } .inspector-section:last-child { margin-bottom: 0; } .property-row { margin-bottom: 4px; line-height: 1.4; } .property-row-header { display: flex; align-items: center; } .property-name { flex: 0 0 1; font-weight: bold; margin-right: 8px; } .property-value { flex: 1; word-break: break-all; color: var(--inspector-value); } /* Shared style indicators */ .shared-style { color: #0066cc; } .mixed-style { color: #ff6600; font-style: italic; } .toggle-button { background: var(--inspector-btn-bg); border: 1px solid var(--inspector-btn-border); color: var(--inspector-btn-text); border-radius: 2px; width: 18px; height: 18px; font-size: 12px; font-weight: bold; cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 0; line-height: 1; margin-right: 8px; } .toggle-button:hover { background: var(--inspector-btn-hover); } .toggle-button:active { background: var(--inspector-btn-active); } .property-json { margin-top: 4px; margin-left: 8px; background: var(--inspector-json-bg); border: 1px solid var(--inspector-json-border); border-radius: 4px; padding: 8px; overflow-x: auto; } .property-json pre { margin: 0; font-size: 11px; line-height: 1.3; color: var(--inspector-json-text); white-space: pre-wrap; word-break: break-word; } /* Binding-specific styles */ .binding-row { margin-bottom: 12px; padding: 8px; background: var(--inspector-binding-bg); border-radius: 4px; border-left: 3px solid var(--inspector-binding-border); } .binding-header { display: flex; align-items: center; margin-bottom: 4px; gap: 8px; } .binding-type { font-weight: bold; color: var(--inspector-binding-type); text-transform: uppercase; font-size: 11px; } .binding-direction { font-size: 10px; color: var(--inspector-binding-dir-text); background: var(--inspector-binding-dir-bg); padding: 2px 6px; border-radius: 2px; } .binding-props { margin-top: 4px; } .binding-prop { margin-left: 8px; } .binding-row:last-child { margin-bottom: 0; } ``` -------- # Layer panel Category: UI & theming Keywords: layers, panel, tree view, hierarchy, visibility, show, hide, getsortedchildidsforparent, getshapevisibility, meta, infrontofthecanvas Build a minimal layers panel that lists, selects, renames, and hides shapes. The panel is an `InFrontOfTheCanvas` component that walks the page with `editor.getSortedChildIdsForParent()`, recursing into groups and frames to build a tree. Each row reads its shape reactively with `useValue`, so the list stays in sync as you draw. Visibility is stored on `shape.meta` and enforced through the `getShapeVisibility` prop: `meta.hidden` hides a shape and its children, and `meta.force_show` lets a child stay visible inside a hidden parent. Try clicking a row to select the shape (shift-click to add to the selection), double-clicking a name to rename it, and clicking the eye icon to hide it. Double-click the eye on a child of a hidden group to force it visible. ## App.tsx ```tsx import { TLComponents, TLEditorSnapshot, Tldraw, useEditor, useValue } from 'tldraw' import 'tldraw/tldraw.css' import { ShapeList } from './ShapeList' import './layer-panel.css' import snapshot from './snapshot.json' // There's a guide at the bottom of this file! const components: TLComponents = { // [1] InFrontOfTheCanvas: () => { const editor = useEditor() const shapeIds = useValue( 'shapeIds', () => editor.getSortedChildIdsForParent(editor.getCurrentPageId()), [editor] ) return (
Shapes
) }, } export default function LayerPanelExample() { return (
s.meta.force_show ? 'visible' : s.meta.hidden ? 'hidden' : 'inherit' } // Initial content so the panel has something to show. snapshot={snapshot as unknown as TLEditorSnapshot} />
) } /* [1] The panel is an `InFrontOfTheCanvas` component. It reads the current page's top-level shape ids with `getSortedChildIdsForParent(pageId)` inside `useValue`, so it re-renders when shapes are added, removed, or reordered. [2] `ShapeList` (see ShapeList.tsx) recurses into groups and frames using the same `getSortedChildIdsForParent` call with a shape id as the parent. [3] `getShapeVisibility` decides whether a shape is hidden. The panel stores its choice in `shape.meta`: `hidden` hides a shape (and, via 'inherit', its children); `force_show` lets a child stay visible even when its parent is hidden. */ ``` ## ShapeList.tsx ```tsx import capitalize from 'lodash/capitalize' import { useRef, useState } from 'react' import { Editor, TLShapeId, useEditor, useValue } from 'tldraw' import { VisibilityOff, VisibilityOn } from '../../../icons/icons' const selectedBg = '#E8F4FE' const childSelectedBg = '#F3F9FE' const childBg = '#00000006' function ShapeItem({ shapeId, depth, parentIsSelected, parentIsHidden, }: { shapeId: TLShapeId depth: number parentIsSelected?: boolean parentIsHidden?: boolean }) { const editor = useEditor() const shape = useValue('shape', () => editor.getShape(shapeId), [editor]) const children = useValue('children', () => editor.getSortedChildIdsForParent(shapeId), [editor]) const isHidden = useValue('isHidden', () => editor.isShapeHidden(shapeId), [editor]) const isSelected = useValue('isSelected', () => editor.getSelectedShapeIds().includes(shapeId), [ editor, ]) const shapeName = useValue('shapeName', () => getShapeName(editor, shapeId), [editor]) const [isEditingName, setIsEditingName] = useState(false) const timeSinceLastVisibilityToggle = useRef(Date.now()) if (!shape) return null return ( <>
{ setIsEditingName(true) }} onPointerDown={() => { if (editor.inputs.getCtrlKey() || editor.inputs.getShiftKey()) { if (isSelected) { editor.deselect(shape) } else { editor.select(...editor.getSelectedShapes(), shape) } } else { editor.select(shape) } }} style={{ paddingLeft: 10 + depth * 20, opacity: isHidden ? 0.5 : 1, background: isSelected ? selectedBg : parentIsSelected ? childSelectedBg : depth > 0 ? childBg : undefined, }} > {isEditingName ? ( setIsEditingName(false)} onChange={(ev) => { if (shape.type === 'frame') { editor.updateShape({ ...shape, props: { name: ev.target.value } }) } else { editor.updateShape({ ...shape, meta: { name: ev.target.value } }) } }} onKeyDown={(ev) => { if (ev.key === 'Enter' || ev.key === 'Escape') { ev.currentTarget.blur() } }} /> ) : (
{shapeName}
)}
{!!children?.length && ( )} ) } export function ShapeList({ shapeIds, depth, parentIsSelected, parentIsHidden, }: { shapeIds: TLShapeId[] depth: number parentIsSelected?: boolean parentIsHidden?: boolean }) { if (!shapeIds.length) return null return (
{shapeIds.map((shapeId) => ( ))}
) } function getShapeName(editor: Editor, shapeId: TLShapeId) { const shape = editor.getShape(shapeId) if (!shape) return 'Unknown shape' return ( (shape.meta.name as string) || editor.getShapeUtil(shape).getText(shape) || capitalize(shape.type + ' shape') ) } ``` ## layer-panel.css ```css .layer-panel { position: absolute; left: 0; top: 42px; width: 200px; height: calc(100% - 42px); background: white; display: flex; flex-direction: column; pointer-events: all; } .shape-tree { display: flex; flex-direction: column; } .shape-item { display: flex; align-items: center; justify-content: space-between; padding: 6px 10px; } .shape-visibility-toggle { padding: 3px 6px; border-radius: 3px; outline: none; border: none; background: none; flex-shrink: 0; } .shape-visibility-toggle:hover { cursor: pointer; background-color: #0000000b; } .layer-panel-title { padding: 10px; font-size: smaller; font-weight: bolder; } .shape-name-input { border: none; background: none; width: 0; flex-grow: 1; padding: 0; } .shape-name { overflow: hidden; text-overflow: ellipsis; text-wrap: nowrap; } ``` -------- # Page panel Category: UI & theming Keywords: pages, page menu, sidebar, thumbnails, previews, external ui, page list Replace the page menu with a custom sidebar with live thumbnails of every page. This example shows how to build a custom page panel in your own DOM, outside the canvas. The panel uses `editor.getPages()` inside `useValue` to re-render whenever pages change. It manages pages with `editor.setCurrentPage`, `editor.createPage`, `editor.renamePage`, and `editor.deletePage`. Double-click a page to rename it. The canvas only renders the current page, so the thumbnails are exported images: `editor.getPageShapeIds(pageId)` and `editor.getSvgString` both work for any page, not just the current one. Thumbnails regenerate on a debounced store listener as you draw. ## App.tsx ```tsx import { useEffect, useState } from 'react' import { Editor, EditorProvider, PageRecordType, TLComponents, TLPage, TLPageId, Tldraw, useEditor, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './page-panel.css' // There's a guide at the bottom of this file! // [1] const components: TLComponents = { PageMenu: null, } export default function PagePanelExample() { const [editor, setEditor] = useState(null) return (
{/* [2] */} {editor && ( )}
) } function PagePanel() { const editor = useEditor() // [3] const pages = useValue('pages', () => editor.getPages(), [editor]) const currentPageId = useValue('current page id', () => editor.getCurrentPageId(), [editor]) // [4] function handleCreatePage() { const newPageId = PageRecordType.createId() editor.run(() => { editor.markHistoryStoppingPoint('creating page') editor.createPage({ id: newPageId, name: `Page ${pages.length + 1}` }) editor.setCurrentPage(newPageId) }) } function handleRenamePage(page: TLPage) { const name = window.prompt('Rename page', page.name) if (name && name !== page.name) { editor.markHistoryStoppingPoint('renaming page') editor.renamePage(page.id, name) } } function handleDeletePage(page: TLPage) { editor.markHistoryStoppingPoint('deleting page') editor.deletePage(page.id) } return (
{pages.map((page, index) => (
editor.setCurrentPage(page.id)} onDoubleClick={() => handleRenamePage(page)} >
{index + 1} {page.name} {pages.length > 1 && ( )}
))}
) } function PageThumbnail({ pageId }: { pageId: TLPageId }) { const editor = useEditor() const [src, setSrc] = useState(null) useEffect(() => { let isCancelled = false let timeout: ReturnType | undefined // [5] async function generateThumbnail() { const shapeIds = editor.getPageShapeIds(pageId) if (shapeIds.size === 0) { if (!isCancelled) setSrc(null) return } const result = await editor.getSvgString([...shapeIds], { background: false, padding: 16, }) if (isCancelled || !result) return setSrc(`data:image/svg+xml;charset=utf-8,${encodeURIComponent(result.svg)}`) } generateThumbnail() // [6] const removeListener = editor.store.listen( () => { if (editor.getCurrentPageId() !== pageId) return clearTimeout(timeout) timeout = setTimeout(generateThumbnail, 300) }, { scope: 'document', source: 'user' } ) return () => { isCancelled = true clearTimeout(timeout) removeListener() } }, [editor, pageId]) return (
{src ? : Empty}
) } /* This example shows how to replace the built-in page menu with a custom page panel in your own DOM, outside the canvas, with live thumbnail previews of every page. The canvas only renders the shapes of the current page, so we export the other pages as images to show their previews. [1] Hide the built-in page menu by overriding the `PageMenu` component with null. [2] Use the `onMount` prop to grab the editor instance and store it in React state. Wrapping external components in `EditorProvider` lets them use `useEditor` and `useValue` even though they're rendered outside ``. [3] `editor.getPages()` is a computed (reactive) value backed by a store query for all page records, sorted by index. Reading it inside `useValue` means this component re-renders automatically whenever pages are created, deleted, renamed, or reordered. [4] Create the page with an explicit id so we can navigate to it right away. `editor.run` batches the two changes, and `markHistoryStoppingPoint` makes the whole thing a single undo step. Note that `editor.deletePage` automatically switches to another page if you delete the current one. [5] The canvas never renders pages other than the current one, so we export them as images instead. `editor.getPageShapeIds(pageId)` returns the shape ids on any page (not just the current one), and `editor.getSvgString` can export shapes from any page. We turn the SVG string into a data URL for a plain tag. [6] Regenerate the thumbnail when the document changes, debounced so we don't re-export on every pointer move. Local edits can only affect the current page, so each thumbnail skips changes made while another page is active. In a multiplayer app you'd also listen to remote changes (source: 'all') and check which page the changed shapes belong to. */ ``` ## page-panel.css ```css .page-panel-layout { display: flex; width: 100%; height: 100vh; } .page-panel-canvas { position: relative; flex: 1; height: 100%; } .page-panel { width: 168px; flex-shrink: 0; display: flex; flex-direction: column; background: #f9fafb; border-right: 1px solid #e3e3e3; } .page-panel-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; padding: 8px; } .page-panel-item { border: 1px solid #e3e3e3; border-radius: 6px; background: white; padding: 4px; cursor: pointer; } .page-panel-item[data-iscurrent='true'] { border-color: #2f80ed; outline: 1px solid #2f80ed; } .page-panel-thumbnail { aspect-ratio: 4 / 3; display: flex; align-items: center; justify-content: center; background: white; border-radius: 4px; overflow: hidden; } .page-panel-thumbnail img { max-width: 100%; max-height: 100%; } .page-panel-thumbnail-empty { color: #b0b0b0; font-size: 11px; } .page-panel-item-footer { display: flex; align-items: center; gap: 4px; padding: 4px 2px 2px 2px; font-size: 12px; } .page-panel-item-index { color: #999; } .page-panel-item-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .page-panel-item-delete { border: none; background: none; color: #999; font-size: 14px; line-height: 1; padding: 0 2px; cursor: pointer; visibility: hidden; } .page-panel-item:hover .page-panel-item-delete { visibility: visible; } .page-panel-item-delete:hover { color: #d32f2f; } .page-panel-add { margin: 8px; padding: 6px; border: 1px solid #e3e3e3; border-radius: 6px; background: white; font-size: 12px; cursor: pointer; } .page-panel-add:hover { background: #f0f0f0; } ``` -------- # Floaty window Category: UI & theming Keywords: camera, setcamera, window position, screenx, screeny, tick event Pin the canvas to the desktop so the browser window appears to float over it. On every editor `tick`, the example reads `window.screenX` and `window.screenY` and, if the window has moved, calls `editor.setCamera()` with the negative offset. The canvas stays put on screen while the window slides over it, an illusion that was [popular on social media](https://x.com/steveruizok/status/1727436505440981099) for a while. Try dragging the browser window around the screen (it won't work while the window is maximized). ## App.tsx ```tsx import { useEffect } from 'react' import { Tldraw, useEditor } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this file! export default function FloatyExample() { return (
) } // [1] function FloatyWindow() { const editor = useEditor() useEffect(() => { let x = window.screenX let y = window.screenY // [2] function updateCamera() { if (window.screenX === x && window.screenY === y) return x = window.screenX y = window.screenY editor.setCamera({ x: -x, y: -y }) } // [3] editor.on('tick', updateCamera) return () => { editor.off('tick', updateCamera) } }, [editor]) return null } /* Moving the browser window across the screen pans the camera by the same amount, so the canvas looks like it's pinned to the desktop while the window slides over it. This was [popular on social media](https://x.com/steveruizok/status/1727436505440981099) for a while. [1] Any component rendered as a child of `` can call `useEditor()`, so this hook component runs its effect once the editor exists and renders nothing. [2] `window.screenX` / `screenY` are the window's position on the screen. When they change, the camera is set to the negative of that offset so page space stays fixed relative to the screen. Camera coordinates are page-space, so this is exact at zoom 1. [3] There's no DOM event for the window moving, so we poll on the editor's `tick` event and unsubscribe in the effect cleanup. */ ``` -------- # Custom translations and overrides Category: UI & theming Keywords: translation, i18n, localization, language, useTranslation, overrides, multilingual, custom text, brand voice, plural, ICU Override tldraw's translation strings and read them in your own components with `useTranslation`. Apps often need to customize UI text to match their brand voice or terminology. The `translations` override on the `overrides` prop maps a language code to translation keys and strings; you can replace existing keys (here "Duplicate" becomes "Make a copy" and "Delete" becomes "Remove") or add new ones, in as many languages as you like. The `useTranslation` hook returns a `msg` function that looks up a key in the current language, so custom components render the same strings as tldraw's built-in menus. Right click a shape to see the overrides in the context menu, or switch the language to Spanish from the language submenu in the main menu. Strings are ICU messages, so the selection count here is one string that reads correctly for any number rather than a choice made in code. Each language gets its own plural categories, which is the part code can't do on its behalf: Arabic has six of them, Polish four. ## App.tsx ```tsx import { TLComponents, TLUiOverrides, Tldraw, TldrawUiButton, useEditor, useTranslation, useValue, } from 'tldraw' import 'tldraw/tldraw.css' import './custom-language-translations.css' // There's a guide at the bottom of this file! // [1] function CustomToolbar() { const editor = useEditor() const msg = useTranslation() const selectedCount = useValue('selected count', () => editor.getSelectedShapeIds().length, [ editor, ]) return (
{/* [2] */} {msg('example.selected', { count: selectedCount })} editor.duplicateShapes(editor.getSelectedShapeIds())} > {/* [3] */} {msg('action.duplicate')} editor.deleteShapes(editor.getSelectedShapeIds())} > {msg('action.delete')}
) } // [4] const overrides: TLUiOverrides = { translations: { en: { 'action.duplicate': 'Make a copy', 'action.delete': 'Remove', 'example.selected': '{count, plural, =0 {Nothing selected} one {# shape selected} other {# shapes selected}}', }, es: { 'action.duplicate': 'Hacer una copia', 'action.delete': 'Eliminar', 'example.selected': '{count, plural, =0 {Nada seleccionado} one {# forma seleccionada} other {# formas seleccionadas}}', }, }, } // [5] const components: TLComponents = { TopPanel: CustomToolbar, } export default function CustomLanguageTranslationExample() { return (
{/* [6] */}
) } /* This example shows how to customize tldraw's translation strings and use them in your own components. This is useful when you need to match your app's brand voice or terminology. [1] The `useTranslation` hook returns a function (conventionally named `msg`) that looks up a translated string by key in the user's current language. [2] Messages are ICU MessageFormat, so one string covers every count. Pass the values it needs as a second argument. The plural categories are the locale's own, which is why this can't be done by picking between two strings in code: Arabic has six categories, Polish four, Russian three. [3] `action.duplicate` and `action.delete` are keys tldraw already uses in its own menus. Because we override them below, both our toolbar and tldraw's built-in menus show the custom text. [4] The `translations` override maps a language code (like `en` or `es`) to an object of translation keys and strings. You can override existing keys or add new ones for your own UI, like `example.selected` here. Languages you don't override fall back to tldraw's defaults. [5] Define the components object outside the React component so it's a stable reference. The custom toolbar is placed in the `TopPanel` slot. [6] Pass both the overrides and the components to the `Tldraw` component. The custom translations also show up in tldraw's own menus. Try creating a shape and right clicking it to see "Make a copy" and "Remove" in the context menu, or switch the language to Spanish from the main menu's language submenu to see the `es` overrides — including the count, which agrees with itself in both languages. */ ``` ## custom-language-translations.css ```css .custom-language-toolbar { pointer-events: all; display: flex; margin: 8px; } .custom-language-count { align-self: center; padding: 0 8px; font-size: 12px; color: var(--tl-color-text-1); white-space: nowrap; } ``` -------- # Custom renderer Category: UI & theming Keywords: renderer, canvas, Background component, Canvas component, custom rendering, 2d context, alternative rendering Draw shapes with your own 2d canvas renderer instead of tldraw's DOM rendering. The `Background` component is replaced with a component that reads `editor.getRenderingShapes()` on every animation frame and draws draw and geo shapes to a 2d canvas, using `getColorValue` to look up theme colors. tldraw's regular shapes layer is hidden with CSS, while selection, handles, and the rest of the UI keep working. This is a sketch of the approach rather than a complete renderer: it handles draw and geo shapes and draws a bounding box for everything else. Try drawing a few shapes and moving them around. ## App.tsx ```tsx import { TLComponents, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' import { CustomRenderer } from './CustomRenderer' import './custom-renderer.css' // There's a guide at the bottom of this file! // [1] const components: TLComponents = { Background: CustomRenderer, } export default function CustomRendererExample() { return ( // [2]
) } /* The shapes are drawn to a 2d canvas from the editor's shape data instead of being rendered by React. [1] We replace the `Background` component with our custom renderer (see `CustomRenderer.tsx`). It reads the rendering shapes from the editor on every animation frame and draws them itself. Even though the DOM shapes are hidden, tldraw still does the work of figuring out which shapes to render. In a real app you might set the `Canvas` component to null and render everything yourself. [2] The `.custom-renderer` class hides tldraw's regular shapes layer via CSS (see `custom-renderer.css`) so only our canvas rendering is visible. Selection, handles, and the rest of the UI still work as normal. */ ``` ## CustomRenderer.tsx ```tsx import { useLayoutEffect, useRef } from 'react' import { getColorValue, getPointsFromDrawSegment, useEditor } from 'tldraw' export function CustomRenderer() { const editor = useEditor() const rCanvas = useRef(null) useLayoutEffect(() => { const canvas = rCanvas.current if (!canvas) return canvas.style.width = '100%' canvas.style.height = '100%' const rect = canvas.getBoundingClientRect() canvas.width = rect.width canvas.height = rect.height const ctx = canvas.getContext('2d')! let raf = -1 function render() { if (!canvas) return ctx.resetTransform() ctx.clearRect(0, 0, canvas.width, canvas.height) const camera = editor.getCamera() ctx.scale(camera.z, camera.z) ctx.translate(camera.x, camera.y) const renderingShapes = editor.getRenderingShapes() const theme = editor.getCurrentTheme() const colors = theme.colors[editor.getColorMode()] const currentPageId = editor.getCurrentPageId() for (const { shape, opacity } of renderingShapes) { const maskedPageBounds = editor.getShapeMaskedPageBounds(shape) if (!maskedPageBounds) continue ctx.save() if (shape.parentId !== currentPageId) { ctx.beginPath() ctx.rect( maskedPageBounds.minX, maskedPageBounds.minY, maskedPageBounds.width, maskedPageBounds.height ) ctx.clip() } ctx.beginPath() ctx.globalAlpha = opacity const transform = editor.getShapePageTransform(shape.id) ctx.transform(transform.a, transform.b, transform.c, transform.d, transform.e, transform.f) if (editor.isShapeOfType(shape, 'draw')) { // Draw a freehand shape for (const segment of shape.props.segments) { const points = getPointsFromDrawSegment(segment, shape.props.scaleX, shape.props.scaleY) ctx.moveTo(points[0].x, points[0].y) if (segment.type === 'straight') { ctx.lineTo(points[1].x, points[1].y) } else { for (const point of points.slice(1)) { ctx.lineTo(point.x, point.y) } } } ctx.strokeStyle = getColorValue(colors, shape.props.color, 'solid') ctx.lineWidth = 4 ctx.stroke() if (shape.props.fill !== 'none' && shape.props.isClosed) { ctx.fillStyle = getColorValue(colors, shape.props.color, 'semi') ctx.fill() } } else if (editor.isShapeOfType(shape, 'geo')) { // Draw a geo shape const bounds = editor.getShapeGeometry(shape).bounds ctx.strokeStyle = getColorValue(colors, shape.props.color, 'solid') ctx.lineWidth = 2 ctx.strokeRect(bounds.minX, bounds.minY, bounds.width, bounds.height) } else { // Draw any other kind of shape const bounds = editor.getShapeGeometry(shape).bounds ctx.strokeStyle = 'black' ctx.lineWidth = 2 ctx.strokeRect(bounds.minX, bounds.minY, bounds.width, bounds.height) } ctx.restore() } raf = requestAnimationFrame(render) } render() return () => { cancelAnimationFrame(raf) } }, [editor]) return } ``` ## custom-renderer.css ```css /* Hide tldraw's DOM shape layer; the custom renderer draws the shapes instead. */ .custom-renderer .tl-shapes { display: none; } ``` -------- # Toolbar groups Category: UI & theming Keywords: toolbar, toolbar groups, TldrawUiMenuGroup, DefaultToolbar, customize toolbar, toolbar items, toolbar layout, orientation Split the toolbar into labelled groups with dividers between them. Pass children to `DefaultToolbar` to replace its default items. Wrap related items in `TldrawUiMenuGroup` to draw a divider between groups; the built-in `*ToolbarItem` components (`SelectToolbarItem`, `DrawToolbarItem`, `RectangleToolbarItem`, and so on) give you the standard tools. Any menu item works in the toolbar too. Here the first group is a plain `TldrawUiMenuItem` that toggles the toolbar between horizontal and vertical, so you can see how groups lay out in both orientations. ## App.tsx ```tsx import { useMemo, useState } from 'react' import { ArrowDownToolbarItem, ArrowLeftToolbarItem, ArrowRightToolbarItem, ArrowUpToolbarItem, CloudToolbarItem, DefaultToolbar, DiamondToolbarItem, DrawToolbarItem, EllipseToolbarItem, EraserToolbarItem, HandToolbarItem, HexagonToolbarItem, HighlightToolbarItem, LaserToolbarItem, OvalToolbarItem, RectangleToolbarItem, RhombusToolbarItem, SelectToolbarItem, StarToolbarItem, TLComponents, Tldraw, TldrawUiMenuGroup, TldrawUiMenuItem, TriangleToolbarItem, } from 'tldraw' import 'tldraw/tldraw.css' export default function ToolbarGroupsExample() { const [orientation, setOrientation] = useState<'horizontal' | 'vertical'>('horizontal') // [1] const components = useMemo((): TLComponents => { return { Toolbar: () => ( {/* [2] */} setOrientation(orientation === 'horizontal' ? 'vertical' : 'horizontal') } label="Toggle orientation" icon={🔄} /> ), } }, [orientation]) return (
) } /* [1] The toolbar component closes over `orientation`, so we rebuild the components object with `useMemo` when it changes. Everything else in the toolbar comes from the built-in `*ToolbarItem` components, which read the tools from context. [2] `TldrawUiMenuGroup` draws a divider between groups of items. Any menu item works inside the toolbar, not just tool items; here the first group is a plain `TldrawUiMenuItem` that flips the toolbar's orientation. Try it: the groups stack vertically and the overflow menu moves with them. */ ``` -------- # Vertical toolbar Category: UI & theming Keywords: vertical toolbar, toolbar orientation, DefaultToolbar, components override, layout Move the toolbar from the bottom of the screen to a vertical strip on the left. `DefaultToolbar` takes an `orientation` prop. Override the `Toolbar` slot with a component that renders `` and the toolbar, its groups, and its overflow menu all switch to a vertical layout. To also change which tools appear, pass children to `DefaultToolbar` (see the [toolbar groups](https://tldraw.dev/examples/toolbar-groups) example). ## App.tsx ```tsx import { DefaultToolbar, TLComponents, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' const components: TLComponents = { Toolbar: () => , } export default function VerticalToolbarExample() { return (
) } ``` -------- # Inset editor Category: Page layout Keywords: inline, embedded, non-fullscreen, layout, container, positioning, inset, wrapper Place the `Tldraw` component in a container that doesn't fill the screen. The `Tldraw` component fills its container, and that container can be anywhere in your layout. Here it's an absolutely positioned box inset 100px from every edge of the page. Pointer events, keyboard shortcuts, camera, and UI all work the same as in a full-screen editor because the editor measures its own container rather than the window. For examples with several fixed-size editors on one page, see [Inset editor (fixed sizes)](https://tldraw.dev/examples/inline). ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function InsetExample() { return (
) } ``` -------- # Inset editor (fixed sizes) Category: Page layout Keywords: inline, embedded, fixed size, width, height, responsive, multiple editors See how the default UI adapts when the `Tldraw` component is given a fixed width and height. The `Tldraw` component fills whatever container it's placed in. This example renders the same document (via a shared `persistenceKey`) in five containers of different fixed sizes, so you can see how the default toolbar, menus, and panels rearrange themselves as the available space shrinks. For guidance on focus handling and UI trimming when embedding several editors in a page, see the [Inset editor (common practices)](https://tldraw.dev/examples/inline-behavior) example. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function InlineExample() { return ( <> ) } function InlineEditor({ width, height }: { width: number; height: number }) { const title = `${width} x ${height}` return (

{title}

) } ``` -------- # Inset editor (common practices) Category: Page layout Keywords: inline, embedded, focus, blur, multiple editors, autofocus, hand tool, edge scrolling, edgescrollspeed, maxpages, context Embed several `Tldraw` blocks in a page so that only one is focused at a time, with a stripped-down UI. When tldraw is one block among many in a larger document, the defaults for a full-page editor get in the way: every editor grabs keyboard shortcuts, the select tool makes it easy to accidentally move things while scrolling past, and the full UI is too much for a small space. This example shows the adjustments we recommend: - Track the focused editor in a React context, and call `editor.focus()` / `editor.blur()` (with `focusContainer` / `blurContainer` off) so only one editor handles keyboard input at a time. - Default to the hand tool on mount and whenever focus is lost, and clear the selection on blur. - Hide the UI of unfocused editors with `hideUi`. - Set `edgeScrollSpeed: 0` so the canvas doesn't scroll when the pointer nears the edge of a small block, and `maxPages: 0` to remove the pages menu. - Remove the help menu, navigation panel, and main menu via `components`. Try clicking into one block, then another, then somewhere on the page outside all of them. ## App.tsx ```tsx import { createContext, useContext, useState } from 'react' import { Editor, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this page! // [1] const focusedEditorContext = createContext( {} as { focusedEditor: Editor | null setFocusedEditor(editor: Editor | null): void } ) // [2] function blurEditor(editor: Editor) { editor.blur({ blurContainer: false }) editor.selectNone() editor.setCurrentTool('hand') } export default function InlineBehaviorExample() { const [focusedEditor, setFocusedEditor] = useState(null) return (
{ if (!focusedEditor) return blurEditor(focusedEditor) setFocusedEditor(null) }} >
) } function InlineBlock({ persistenceKey }: { persistenceKey: string }) { const { focusedEditor, setFocusedEditor } = useContext(focusedEditorContext) const [editor, setEditor] = useState() return (
{ if (!editor) return if (focusedEditor && focusedEditor !== editor) { blurEditor(focusedEditor) } editor.focus({ focusContainer: false }) setFocusedEditor(editor) }} onPointerDown={(e) => e.stopPropagation()} > { setEditor(editor) editor.setCurrentTool('hand') }} />
) } /* [1] A context tracking which editor is focused. Only the focused editor handles keyboard shortcuts, so several editors on one page don't fight over them. See also the 'Multiple editors' and 'Focus the editor' examples. [2] Called on any editor that loses focus. `blurContainer: false` stops the editor's DOM container from being blurred (we manage focus at the block level), and we reset the user's tool state so nothing is left selected or half-drawn. [3] Clicking anywhere on the page outside an editor blurs the focused one. [4] Clicking into a block focuses its editor and blurs whichever was focused before. Stopping pointer-down propagation keeps [3] from immediately blurring it again. [5] Unfocused editors hide their UI. [6] `maxPages: 0` removes the pages menu. `edgeScrollSpeed: 0` disables edge scrolling, which is too easily triggered when the canvas is small. [7] Drop UI components that don't earn their space in a small block. [8] Default to the hand tool on mount so scrolling past a block doesn't accidentally move shapes, and keep a reference to the editor for the focus handlers. */ ``` -------- # Inset canvas Category: Page layout Keywords: canvas position, inset, css, custom layout, canvas offset Move the `.tl-canvas` element so it no longer fills the `Tldraw` container. Normally the canvas fills the whole `Tldraw` container and the UI floats over it. This example uses CSS to shrink and center the `.tl-canvas` element to the middle 50% of the container, leaving the UI where it was. Pointer positions, hit testing, and the camera still line up correctly because the editor measures the canvas element itself, not its container. This is an unusual layout; the point of the example is to show that if you need to reposition the canvas within the editor's chrome, you can do it with CSS alone. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' import './inset-canvas.css' export default function InsetCanvasExample() { return (
) } ``` ## inset-canvas.css ```css .tldraw__editor-with-inset-canvas .tl-canvas { position: absolute; inset: 25%; width: 50%; height: 50%; } ``` -------- # Scrollable container Category: Page layout Keywords: scrollable, container, layout, autofocus, focus, mousewheel, viewport, nested Use the editor inside a page that scrolls, and see how focus decides who gets the wheel events. The `Tldraw` component works inside a scrollable page. The one thing to be aware of is the mouse wheel: while the editor is focused it consumes wheel events to pan and zoom the canvas, and the page doesn't scroll. When it's blurred, wheel events pass through and the page scrolls as normal. Here the editor is centered in a container larger than the viewport, with `autoFocus` on. Try scrolling with the pointer over the canvas, then set `autoFocus={false}` and try again. ## App.tsx ```tsx import { Tldraw } from 'tldraw' import 'tldraw/tldraw.css' export default function ScrollExample() { return (
) } /* While the editor is focused it consumes wheel events to pan and zoom, so the page won't scroll when the pointer is over the canvas. Try turning off `autoFocus` to see the difference. */ ``` -------- # Multiple editors Category: Page layout Keywords: multiple editors, focus, autofocus, blur, context, shared document, persistencekey, sync Put several `Tldraw` components on one page and make sure only one is focused at a time. Each `Tldraw` component is its own editor with its own keyboard handling, so with several on a page you need to decide which one currently owns focus. This example turns off `autoFocus` on every editor and tracks the focused one in a React context. Wrapping each editor in a focusable `div` (`tabIndex={-1}`) with an `onFocus` handler lets us call `editor.focus()` on the newly focused editor and `editor.blur()` on the previous one. Clicking anywhere else on the page blurs whichever editor was focused. Editors B and C share a `persistenceKey`, so they show the same locally synchronized document. Try drawing in one and watching the other update. The long block of text below is there so you can check that scrolling the page and typing in the textarea don't get captured by an unfocused editor. ## App.tsx ```tsx import { createContext, useCallback, useContext, useState } from 'react' import { Editor, Tldraw } from 'tldraw' import 'tldraw/tldraw.css' // There's a guide at the bottom of this page! // [1] const focusedEditorContext = createContext( {} as { focusedEditor: Editor | null setFocusedEditor(editor: Editor | null): void } ) // [2] export default function MultipleExample() { const [focusedEditor, _setFocusedEditor] = useState(null) const setFocusedEditor = useCallback( (editor: Editor | null) => { if (focusedEditor !== editor) { if (focusedEditor) { focusedEditor.blur() } if (editor) { editor.focus() } _setFocusedEditor(editor) } }, [focusedEditor] ) const focusName = focusedEditor === (window as any).EDITOR_A ? 'A' : focusedEditor === (window as any).EDITOR_B ? 'B' : focusedEditor === (window as any).EDITOR_C ? 'C' : 'none' return (
setFocusedEditor(null)} >

Focusing: {focusName}