# 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 (
)
})
/*
[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 (
)
}
/*
[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 (
)
}
/*
[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 (
)
}
```
--------
# 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 (
)
}
/*
[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 (
)
}
/*
[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 (
)
}
/*
[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 (
)
}
/*
[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 (
)
}
/*
[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 (
)
}
/*
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 (
)
}
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 (
)
}
/*
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
)
}
/*
[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 (
)
}
/*
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 (
)
},
}
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.
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 (
)
}
/*
[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
)
}
/*
[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 (
)
}
/*
[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 (
)
}
/*
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 (
)
}
/*
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 (
)
}
/*
[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]
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 (
)
}
/*
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 (
)
}
/*
[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 (
)
}
/*
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 (
)
}
/*
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]
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 (
)
}
/*
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 (
)
}
/*
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 (
)
}
/*
[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 (
{(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
)
}
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 (
{
// [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 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.
)
}
/*
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 {}}>
DangerDisabled
With icon
{/* Dropdown Menu */}
Dropdown menu
Open menuCut⌘XCopy⌘CPaste⌘V setCheckboxValue(!checkboxValue)}
>
Checkbox itemOption AOption B
)
}
/*
[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 (
)
}
/*
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 (
)
}
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] */}
)
}
/*
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 (
)
}
/*
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 && (
)
}
/*
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 (
)
}
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 (
)
}
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 (
)
}
/*
[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 (
)
}
/*
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 (
)
}
/*
[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 (
)
}
/*
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 (
)
}
/*
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'}
)
}
/*
[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 (
)
}
/*
[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 (
<>
)
}
/*
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 (
)
}
// [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)
}}
>
)
}
/*
[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}
These two editors share the same persistence key so they will share a (locally)
synchronized document.
setFocusedEditor((window as any).EDITOR_C)}
style={{ height: 600 }}
>
{
;(window as any).EDITOR_C = editor
}}
/>
)
}
// [5]
function ABunchOfText() {
return (
White Board
Chapter 1: The First Strokes
The fluorescent lights flickered overhead as John sat hunched over his desk, his fingers
tapping rhythmically on the keyboard. He was a software developer, and tonight, he had a
peculiar mission. A mission that would take him deep into the labyrinthine world of web
development. John had stumbled upon a new whiteboard library called “tldraw”, a seemingly
simple tool that promised to revolutionize collaborative drawing on the web. Little did he
know that this discovery would set off a chain of events that would challenge his skills,
test his perseverance, and blur the line between reality and imagination.
With a newfound sense of excitement, John began integrating “tldraw” into his latest
project. As lines of code danced across his screen, he imagined the possibilities that lay
ahead. The potential to create virtual spaces where ideas could be shared, concepts could be
visualized, and teams could collaborate seamlessly from different corners of the world. It
was a dream that seemed within reach, a vision of a future where creativity and technology
merged into a harmonious symphony.
As the night wore on, John’s mind became consumed with the whiteboard library. He couldn’t
help but marvel at its elegance and simplicity. With each stroke of his keyboard, he felt a
surge of inspiration, a connection to something greater than himself. It was as if the lines
of code he was writing were transforming into a digital canvas, waiting to be filled with
the strokes of imagination. In that moment, John realized that he was not just building a
tool, but breathing life into a new form of expression. The whiteboard was no longer just a
blank slate; it had become a portal to a world where ideas could flourish and dreams could
take shape.
Little did John know, this integration of “tldraw” was only the beginning. It would lead him
down a path filled with unforeseen challenges, where he would confront his own limitations
and question the very nature of creation. The journey ahead would test his resolve, pushing
him to the edge of his sanity. And as he embarked on this perilous adventure, he could not
shake the feeling that the whiteboard held secrets far beyond his understanding. Secrets
that would unfold before his eyes, one stroke at a time.
)
}
/*
With several editors on one page, only one should own keyboard focus at a time. Every
editor here has `autoFocus={false}`, and we manage focus ourselves with a context.
The editors are also stashed on `window` (`EDITOR_A`, `EDITOR_B`, `EDITOR_C`) so the
e2e tests can reach them; a real app would keep them in state or refs.
[1]
A context holding the focused editor and a setter.
[2]
The setter blurs the previously focused editor and focuses the new one before
updating state, so exactly one editor has `isFocused` at any time.
[3]
Each editor is wrapped in a focusable div (`tabIndex={-1}`). When it receives DOM
focus, we mark its editor as the focused one. Editor A focuses itself on mount.
[4]
Editors B and C share a persistence key, so they display the same locally
synchronized document.
[5]
A long story that doesn't go anywhere, but it's a good way to test that scrolling
the page doesn't get captured by an unfocused editor.
*/
```
--------
# External dialog
Category: Page layout
Keywords: dialog, modal, css, styling, custom styles, embed, insert
Open dialogs over the whole page instead of inside the `Tldraw` container.
The tldraw UI renders its dialogs (insert embed, edit link, keyboard shortcuts) inside the `Tldraw` component, positioned absolutely within it. When the editor is a small inset in a larger page, that can leave dialogs cramped or clipped.
This example overrides the `.tlui-dialog__overlay` and `.tlui-dialog__positioner` styles to use `position: fixed`, so dialogs are positioned relative to the browser window instead. Try it: open the "Insert embed" dialog from the menu, or press `Cmd + I` / `Ctrl + I`, and the dialog will center over the whole page rather than the 600 × 400 editor.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
// [1]
import './external-dialog.css'
export default function ExternalDialog() {
return (
)
}
/*
[1]
By default the dialog overlay and positioner are `position: absolute` and fill the
`Tldraw` container. Switching them to `position: fixed` makes them fill the browser
window instead, so a dialog can be centered over the whole page even when the editor
is a small inset. See external-dialog.css.
*/
```
## external-dialog.css
```css
.tlui-dialog__overlay,
.tlui-dialog__positioner {
position: fixed;
}
```
--------
# External UI (using context)
Category: Page layout
Keywords: custom ui, toolbar, buttons, context, createcontext, usecontext, onmount, getcurrenttoolid, setcurrenttool, getstylefornextshape, setstylefornextshapes
Control the editor from a toolbar rendered outside the `Tldraw` component, sharing the editor through React context.
UI that lives outside the `Tldraw` component can't use `useEditor()`. This example captures the editor in `onMount`, stores it in state, and then provides it through a React context so any descendant component (here, an `ExternalToolbar` rendered below the canvas) can read it with `useContext`.
The provider only renders once the editor exists, so consumers never have to handle a `null` editor. Compare with the [External UI (using state)](https://tldraw.dev/examples/external-ui) example, which keeps the editor in local state and uses it in the same component.
## App.tsx
```tsx
import { createContext, useContext, useState } from 'react'
import { Editor, GeoShapeGeoStyle, Tldraw, useValue } from 'tldraw'
import 'tldraw/tldraw.css'
import './external-ui.css'
// There's a guide at the bottom of this file!
// [1]
const editorContext = createContext({} as { editor: Editor })
export default function ExternalUiContextExample() {
const [editor, setEditor] = useState(null)
return (
)
}
/*
[1]
A React context for the editor. Components outside `Tldraw` can't use `useEditor()`,
so we provide our own.
[2]
Use the `onMount` prop to get the editor instance and store it in state.
[3]
Only render the provider (and its descendants) once the editor exists, so consumers
never see a null editor.
[4]
Any descendant of the provider can read the editor from context. `useValue` keeps
the active button in sync with the current tool.
[5]
The geo tool creates whichever geo shape is set in `GeoShapeGeoStyle`, so set the
style first, then switch tools. `editor.run` batches the two updates together.
*/
```
## external-ui.css
```css
.external-toolbar {
display: flex;
align-items: center;
justify-content: center;
padding: 8px;
gap: 8px;
}
.external-button {
pointer-events: all;
padding: 4px 12px;
background: white;
border: 1px solid black;
border-radius: 16px;
}
.external-button[data-isactive='true'] {
background-color: black;
color: white;
}
```
--------
# External UI (using state)
Category: Page layout
Keywords: custom ui, toolbar, buttons, state, usestate, onmount, getcurrenttoolid, setcurrenttool, getstylefornextshape, setstylefornextshapes, usevalue
Control the editor from a toolbar rendered outside the `Tldraw` component, holding the editor in React state.
UI that lives outside the `Tldraw` component can't use `useEditor()`, so it needs some other way to reach the editor instance. The simplest option is to capture it in `onMount` and store it in state in the same component that renders ``.
Here the default toolbar is hidden (`components={{ Toolbar: null }}`) and replaced with three buttons rendered below the canvas. `useValue` keeps the active button in sync with `editor.getCurrentToolId()`, and the buttons call `editor.setCurrentTool()`. Because the editor is `null` until it mounts, the callbacks guard against that.
Try clicking "Oval" and drawing on the canvas. The oval button sets `GeoShapeGeoStyle` before switching to the geo tool, since the geo tool creates whichever geo shape is currently selected in the style.
For a version that distributes the editor through React context, so any descendant component can use it, see the [External UI (using context)](https://tldraw.dev/examples/external-ui-context) example.
## App.tsx
```tsx
import { useState } from 'react'
import { Editor, GeoShapeGeoStyle, Tldraw, useValue } from 'tldraw'
import 'tldraw/tldraw.css'
import './external-ui.css'
// There's a guide at the bottom of this file!
export default function ExternalUiExample() {
// [1]
const [editor, setEditor] = useState(null)
const currentToolId = useValue('current tool id', () => editor?.getCurrentToolId(), [editor])
return (
)
}
/*
[1]
Components outside `Tldraw` can't use `useEditor()`, so we hold the editor in React
state instead. It's null until the editor mounts.
[2]
Use the `onMount` prop to get the editor instance and store it in state.
[3]
Read from the editor with `useValue` (so the active button updates when the tool
changes) and call its methods to control it. The callbacks guard against the editor
not being mounted yet.
[4]
The geo tool creates whichever geo shape is set in `GeoShapeGeoStyle` (oval,
rectangle, etc), so set the style first, then switch tools. `editor.run` batches the
two updates together.
*/
```
## external-ui.css
```css
.external-toolbar {
display: flex;
align-items: center;
justify-content: center;
padding: 8px;
gap: 8px;
}
.external-button {
pointer-events: all;
padding: 4px 12px;
background: white;
border: 1px solid black;
border-radius: 16px;
}
.external-button[data-isactive='true'] {
background-color: black;
color: white;
}
```
--------
# Snapshot image component
Category: Page layout
Keywords: tldrawimage, snapshot, display snapshot, read only, getsnapshot, store snapshot, tlstoresnapshot, format, svg, png
Render a store snapshot as a static SVG or PNG image with the `TldrawImage` component.
`TldrawImage` takes a `TLStoreSnapshot` and renders it as an image, with no editor, canvas, or UI. It's a lightweight way to show a read-only preview of a document. Props like `pageId`, `bounds`, `background`, `darkMode`, `padding`, `scale`, and `format` control what gets rendered and how.
This example toggles between an editable `Tldraw` and a `TldrawImage` of the same document. Try editing the drawing, panning or zooming, switching to dark mode, then pressing "Save drawing": the image is regenerated with the editor's current page, viewport bounds, and theme. Use the format dropdown to switch between SVG and PNG output.
## App.tsx
```tsx
import { useState } from 'react'
import {
Box,
Editor,
StoreSnapshot,
TLPageId,
TLRecord,
TLStoreSnapshot,
Tldraw,
TldrawImage,
getSnapshot,
} from 'tldraw'
import 'tldraw/tldraw.css'
import initialSnapshot from './snapshot.json'
// There's a guide at the bottom of this file!
export default function TldrawImageExample() {
const [editor, setEditor] = useState()
const [snapshot, setSnapshot] = useState>(
initialSnapshot as TLStoreSnapshot
)
const [currentPageId, setCurrentPageId] = useState()
const [showBackground, setShowBackground] = useState(true)
const [isDarkMode, setIsDarkMode] = useState(false)
const [viewportPageBounds, setViewportPageBounds] = useState(new Box(0, 0, 600, 400))
const [isEditing, setIsEditing] = useState(false)
const [format, setFormat] = useState<'svg' | 'png'>('svg')
return (
)
}
/*
[1]
Pass a `TLStoreSnapshot` to the `snapshot` prop. When the user saves, we grab a fresh
one from the editor with `getSnapshot(editor.store).document`.
[2]
`pageId` picks which page to render. It defaults to the first page, which is why we
capture the editor's current page when leaving edit mode.
[3]
The remaining props control appearance: `background` and `darkMode` match what the
user was looking at, `bounds` renders just the region that was in the viewport, and
`format` chooses between SVG and PNG output.
*/
```
--------
# Signals
Category: Events & effects
Keywords: signals, reactive, track, usevalue, usereactor, state management, side effects, computed, atom
Keep React components and side effects in sync with editor state using `track`, `useValue`, and `useReactor`.
tldraw's editor state is made of signals: every `editor.get...()` call reads one. This example shows
the three main ways to react to them from a component. `track` wraps a component so it re-renders
when any signal it read during render changes. `useValue` subscribes to just the return value of a
function. `useReactor` runs a side effect (here, updating the document title with the shape count)
whenever the signals it reads change.
Try switching tools, zooming, and adding shapes: the panel above the style panel and the browser
tab title both update. The file includes two versions of the panel, one using `track` and one using
`useValue`, that behave the same way.
## App.tsx
```tsx
import { TLComponents, Tldraw, track, useEditor, useReactor, useValue } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
// [1]
const InfoPanel = track(function InfoPanel() {
const editor = useEditor()
const tool = editor.getCurrentToolId()
const zoom = editor.getZoomLevel().toFixed(2)
// [2]
useReactor(
'change title',
() => {
const shapes = editor.getCurrentPageShapes()
document.title = `shapes: ${shapes.length}`
},
[editor]
)
return (
)
}
/*
tldraw's editor state is built on signals. Any `editor.get...()` call reads a signal, and there
are two ways to make a React component follow those reads.
[1]
`track` wraps a component so that every signal read during render is recorded, and the component
re-renders when any of them change. Here that's the current tool and the zoom level. This panel
is placed in the `SharePanel` slot, above the style panel.
[2]
`useReactor` runs a side effect (rather than a render) whenever the signals it reads change,
throttled to once per animation frame. Here it keeps the document title in sync with the shape
count. `useQuickReactor` is the same but runs synchronously on every change. Both take a deps
array like `useEffect`; the effect is re-created when the deps change.
[3]
`useValue` is the more targeted alternative: pass a name, a function that reads signals, and a
deps array, and the component re-renders only when the function's *return value* changes. This
version of the panel behaves identically to [1]. Prefer `useValue` when you want to pick a few
values out of a component that shouldn't otherwise track everything it touches; `track` is
convenient when the whole component is about editor state.
*/
```
--------
# Canvas events
Category: Events & effects
Keywords: events, pointer events, mouse events, click, keyboard events, canvas events, event listeners, tleventinfo, editor.on
Log the pointer, keyboard, and other input events the editor dispatches to its tools.
The editor is an event emitter. Subscribing to `editor.on('event', handler)` gives you every
`TLEventInfo` the editor processes: pointer, keyboard, wheel, pinch, click, and tick events. This
example keeps the most recent event of each type and shows them on the right-hand side.
Try moving your cursor, dragging, and holding modifier keys, and watch the panel update. These are
input events, not document changes: to see shapes being created or deleted, look at the store events
example, and for high-level UI actions like tool selection, see the UI events example.
## App.tsx
```tsx
import { useCallback, useState } from 'react'
import { TLEventInfo, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import './canvas-events.css'
// There's a guide at the bottom of this file!
type TimedEvent = TLEventInfo & { lastUpdated: number }
export default function CanvasEventsExample() {
const [events, setEvents] = useState>({})
// [1]
const handleEvent = useCallback((data: TLEventInfo) => {
setEvents((prevEvents) => ({
...prevEvents,
[data.type]: {
...data,
lastUpdated: Date.now(),
},
}))
}, [])
const eventsArray = Object.values(events).sort((a, b) => a.lastUpdated - b.lastUpdated)
return (
)
}
/*
Canvas events are the low-level input events the editor dispatches to its tools: pointer,
keyboard, wheel, pinch, tick and so on. They don't cover document changes like creating or
deleting shapes; for those, see the store events example. For higher-level UI actions like
"zoom in" or "select tool", see the UI events example.
[1]
Pointer moves and ticks fire many times a second, so logging every event would be unreadable.
Instead we keep the latest event of each type, keyed by `type`, and show them ordered by when
they last fired.
[2]
`Editor` is an event emitter. Subscribing to `'event'` gives you every `TLEventInfo` the editor
handles, after its own processing. `onMount` can return a cleanup function, which is the right
place to unsubscribe.
*/
```
## canvas-events.css
```css
.canvas-events {
display: flex;
}
.canvas-events__editor {
width: 50%;
height: 100vh;
}
.canvas-events__log {
width: 50%;
height: 100vh;
padding: 8px;
background: #eee;
border-left: solid 2px #333;
font-family: monospace;
font-size: 12px;
display: flex;
flex-direction: column-reverse;
overflow: auto;
white-space: pre-wrap;
}
```
--------
# Store events
Category: Events & effects
Keywords: store, events, listen, changes, transactions, added, updated, removed, tleventmaphandler, subscribe
Listen to store changes and log shape creates, updates, deletes, and page switches.
`editor.store.listen` calls your handler once per transaction with a `HistoryEntry` describing the
records that were added, updated, and removed. This example subscribes from `onMount`, filters to
changes made by the local user, and turns the entries it cares about into readable lines in the
panel on the right.
Try creating and deleting shapes, changing their styles, or switching pages. Store events cover
document changes, not input: for pointer and keyboard events see the canvas events example, and for
high-level UI actions see the UI events example. To react to changes with side effects rather than
just observe them, see the side effects examples.
## App.tsx
```tsx
import { useCallback, useState } from 'react'
import { isEqual, TLEventMapHandler, TLShape, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import './store-events.css'
// There's a guide at the bottom of this file!
export default function StoreEventsExample() {
const [storeEvents, setStoreEvents] = useState([])
// [1]
const handleChangeEvent = useCallback>((change) => {
const messages: string[] = []
for (const record of Object.values(change.changes.added)) {
if (record.typeName === 'shape') {
messages.push(`created shape (${record.type})`)
}
}
for (const [from, to] of Object.values(change.changes.updated)) {
if (from.typeName === 'instance' && to.typeName === 'instance') {
if (from.currentPageId !== to.currentPageId) {
messages.push(`changed page (${from.currentPageId}, ${to.currentPageId})`)
}
} else if (from.typeName === 'shape' && to.typeName === 'shape') {
messages.push(`updated shape (${describeShapeDiff(from, to)})`)
}
}
for (const record of Object.values(change.changes.removed)) {
if (record.typeName === 'shape') {
messages.push(`deleted shape (${record.type})`)
}
}
if (messages.length) {
setStoreEvents((events) => [...events, ...messages])
}
}, [])
return (
)
}
// [3]
function describeShapeDiff(from: TLShape, to: TLShape) {
const changed: string[] = []
for (const key of Object.keys(to) as (keyof TLShape)[]) {
if (key === 'props') {
for (const propKey of Object.keys(to.props)) {
const a = (from.props as Record)[propKey]
const b = (to.props as Record)[propKey]
if (!isEqual(a, b)) changed.push(`props.${propKey}: ${JSON.stringify(b)}`)
}
} else if (!isEqual(from[key], to[key])) {
changed.push(`${key}: ${JSON.stringify(to[key])}`)
}
}
return changed.join(', ')
}
/*
Store events tell you what changed in the document: shapes created, updated, or deleted, pages
switched, and so on. They don't include input like pointer and keyboard events; for those, see
the canvas events example.
[1]
The listener receives a `HistoryEntry` for every transaction. Its `changes` is a `RecordsDiff`
with `added`, `updated`, and `removed` maps keyed by record id, and `updated` entries are
`[from, to]` pairs. Records of all types come through here (shapes, pages, the instance record,
camera, and so on), so we check `typeName` and turn the ones we care about into readable lines.
[2]
`editor.store.listen` returns an unsubscribe function, and `onMount` can return a cleanup
function, so returning one from the other is all the wiring needed. The filters restrict this
listener to changes made by the local user (`source: 'user'`, as opposed to `'remote'` changes
arriving from other clients) across all record scopes. Use `scope: 'document'` if you only care
about persisted document content and not things like the camera or selection.
[3]
Compare the two versions of an updated shape and list the top-level and `props` fields that
changed. Nested values like `richText` need a deep comparison, so this uses `isEqual`, which
tldraw re-exports from lodash.
*/
```
## store-events.css
```css
.store-events {
display: flex;
}
.store-events__editor {
width: 60%;
height: 100vh;
}
.store-events__log {
width: 40%;
height: 100vh;
padding: 8px;
background: #eee;
border-left: solid 2px #333;
font-family: monospace;
font-size: 12px;
display: flex;
flex-direction: column-reverse;
overflow: auto;
}
```
--------
# UI events
Category: Events & effects
Keywords: ui events, onUiEvent, TLUiEventHandler, event logging, keyboard shortcuts, actions, tools, debugging, analytics
Listen to the actions the default UI performs and see which editor API each one calls.
The `onUiEvent` prop of `` is called for every action the default UI performs, whether it
came from a menu, the toolbar, or a keyboard shortcut. Each event has a name (see `TLUiEventMap`) and
data that includes a `source`. This example logs them on the right-hand side, alongside the editor
API call the UI made for that event, which makes it a useful way to learn the SDK.
Try selecting tools, changing styles, aligning shapes, or using undo/redo. UI events fire only for
UI interactions; calling `editor.alignShapes()` yourself won't trigger one. For pointer and keyboard
input see the canvas events example, and for document changes see the store events example.
## App.tsx
```tsx
import { useCallback, useState } from 'react'
import { TLUiEventHandler, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { getCodeSnippet } from './codeSnippets'
import './ui-events.css'
// There's a guide at the bottom of this file!
export default function UiEventsExample() {
const [uiEvents, setUiEvents] = useState([])
// [1]
const handleUiEvent = useCallback((name, data) => {
const codeSnippet = getCodeSnippet(name, data)
setUiEvents((events) => [
...events,
`event: ${name} ${JSON.stringify(data)}${codeSnippet ? `\ncode: ${codeSnippet}` : ''}`,
])
}, [])
return (
)
}
/*
UI events are the high-level actions the default UI performs: selecting a tool, grouping
shapes, zooming, toggling grid mode, and so on. They fire whichever way the action was
triggered (menu, toolbar, or keyboard shortcut) and each comes with a `source` telling you
which. They don't fire when you call the same editor methods yourself. For the full list, see
the `TLUiEventMap` type; for `source` values, see `TLUiEventSource`.
[1]
The handler receives the event name and its data. This example also shows the editor API call
that the default UI made for the event (see `codeSnippets.ts`), which is a handy way to learn
which method does what.
[2]
Pass the handler to the `onUiEvent` prop of ``. Since it's called for every UI action,
this is a good hook for analytics.
To listen to input events or document changes instead, see the canvas events and store events
examples.
*/
```
## codeSnippets.ts
```ts
// Maps UI event names to the editor API call that the default UI makes for them. This is only
// for display: the events are already handled by the time `onUiEvent` fires. Not every event
// has a one-line equivalent; those return an empty string. See `TLUiEventMap` for the full list.
const STYLE_PROPS: Record = {
'tldraw:color': 'DefaultColorStyle',
'tldraw:labelColor': 'DefaultLabelColorStyle',
'tldraw:dash': 'DefaultDashStyle',
'tldraw:fill': 'DefaultFillStyle',
'tldraw:font': 'DefaultFontStyle',
'tldraw:horizontalAlign': 'DefaultHorizontalAlignStyle',
'tldraw:verticalAlign': 'DefaultVerticalAlignStyle',
'tldraw:textAlign': 'DefaultTextAlignStyle',
'tldraw:size': 'DefaultSizeStyle',
'tldraw:geo': 'GeoShapeGeoStyle',
'tldraw:arrowKind': 'ArrowShapeKindStyle',
'tldraw:arrowheadStart': 'ArrowShapeArrowheadStartStyle',
'tldraw:arrowheadEnd': 'ArrowShapeArrowheadEndStyle',
'tldraw:spline': 'LineShapeSplineStyle',
}
const REORDER_METHODS: Record = {
toFront: 'bringToFront',
forward: 'bringForward',
backward: 'sendBackward',
toBack: 'sendToBack',
}
const SELECTION_METHODS: Record = {
'group-shapes': 'groupShapes',
'ungroup-shapes': 'ungroupShapes',
'delete-shapes': 'deleteShapes',
'toggle-lock': 'toggleLock',
'distribute-shapes': 'distributeShapes',
'align-shapes': 'alignShapes',
'stretch-shapes': 'stretchShapes',
'flip-shapes': 'flipShapes',
'stack-shapes': 'stackShapes',
}
const USER_PREF_TOGGLES: Record = {
'toggle-snap-mode': 'isSnapMode',
'toggle-wrap-mode': 'isWrapMode',
'toggle-dynamic-size-mode': 'isDynamicSizeMode',
'toggle-paste-at-cursor': 'isPasteAtCursorMode',
'toggle-keyboard-shortcuts': 'areKeyboardShortcutsEnabled',
'toggle-invert-zoom': 'isZoomDirectionInverted',
'toggle-reduce-motion': 'animationSpeed',
'toggle-edge-scrolling': 'edgeScrollSpeed',
}
const INSTANCE_STATE_TOGGLES: Record = {
'toggle-transparent': 'exportBackground',
'toggle-tool-lock': 'isToolLocked',
'toggle-focus-mode': 'isFocusMode',
'toggle-grid-mode': 'isGridMode',
'toggle-debug-mode': 'isDebugMode',
}
const ZOOM_METHODS: Record = {
'zoom-in': 'zoomIn',
'zoom-out': 'zoomOut',
'reset-zoom': 'resetZoom',
'zoom-to-fit': 'zoomToFit',
'zoom-to-selection': 'zoomToSelection',
}
export function getCodeSnippet(name: string, data: any): string {
switch (name) {
case 'set-style':
if (data.id === 'opacity') {
return `editor.setOpacityForSelectedShapes(${data.value}); editor.setOpacityForNextShapes(${data.value})`
}
return `editor.setStyleForSelectedShapes(${STYLE_PROPS[data.id] ?? '?'}, '${data.value}'); editor.setStyleForNextShapes(${STYLE_PROPS[data.id] ?? '?'}, '${data.value}')`
case 'select-tool':
if (data.id === 'media') return 'insertMedia()'
if (data.id.startsWith('geo-')) {
const geo = data.id.replace('geo-', '')
return `editor.setStyleForNextShapes(GeoShapeGeoStyle, '${geo}'); editor.setCurrentTool('geo')`
}
return `editor.setCurrentTool('${data.id}')`
case 'rotate-ccw':
case 'rotate-cw':
return 'editor.rotateShapesBy(editor.getSelectedShapeIds(), )'
case 'reorder-shapes':
return `editor.${REORDER_METHODS[data.operation] ?? '?'}(editor.getSelectedShapeIds())`
case 'stack-shapes':
return `editor.stackShapes(editor.getSelectedShapeIds(), '${data.operation}', editor.options.adjacentShapeMargin)`
case 'pack-shapes':
return `editor.packShapes(editor.getSelectedShapeIds(), editor.options.adjacentShapeMargin)`
case 'duplicate-shapes':
return `editor.duplicateShapes(editor.getSelectedShapeIds(), { x: , y: })`
case 'select-all-shapes':
return `editor.selectAll()`
case 'select-none-shapes':
return `editor.selectNone()`
case 'export-as':
return `exportAs(editor, editor.getSelectedShapeIds(), { format: '${data.format}' })`
case 'copy-as':
return `copyAs(editor, editor.getSelectedShapeIds(), { format: '${data.format}' })`
case 'undo':
case 'redo':
return `editor.${name}()`
case 'cut':
case 'copy':
return `const { ${name} } = useMenuClipboardEvents(); ${name}()`
case 'paste':
return `const { paste } = useMenuClipboardEvents(); navigator.clipboard.read().then(paste)`
case 'print':
return 'printSelectionOrPages()'
case 'stop-following':
return `editor.stopFollowingUser()`
case 'exit-pen-mode':
return `editor.updateInstanceState({ isPenMode: false })`
case 'remove-frame':
return `removeFrame(editor, editor.getSelectedShapeIds())`
case 'fit-frame-to-content':
return `fitFrameToContent(editor, editor.getOnlySelectedShape().id)`
case 'unlock-all':
return `editor.updateShapes(editor.getCurrentPageShapes().filter((s) => s.isLocked).map((s) => ({ id: s.id, type: s.type, isLocked: false })))`
case 'color-scheme':
return `editor.user.updateUserPreferences({ colorScheme: '${data.value}' })`
}
if (name in SELECTION_METHODS) {
const operation = data.operation !== undefined ? `, '${data.operation}'` : ''
return `editor.${SELECTION_METHODS[name]}(editor.getSelectedShapeIds()${operation})`
}
if (name in ZOOM_METHODS) {
const point =
name === 'zoom-in' || name === 'zoom-out' || name === 'reset-zoom' ? 'undefined, ' : ''
return `editor.${ZOOM_METHODS[name]}(${point}{ animation: { duration: editor.options.animationMediumMs } })`
}
if (name in USER_PREF_TOGGLES) {
return `editor.user.updateUserPreferences({ ${USER_PREF_TOGGLES[name]}: })`
}
if (name in INSTANCE_STATE_TOGGLES) {
const key = INSTANCE_STATE_TOGGLES[name]
return `editor.updateInstanceState({ ${key}: !editor.getInstanceState().${key} })`
}
return ''
}
```
## ui-events.css
```css
.ui-events {
display: flex;
}
.ui-events__editor {
width: 60%;
height: 100vh;
}
.ui-events__log {
width: 40%;
height: 100vh;
padding: 8px;
background: #eee;
border-left: solid 2px #333;
font-family: monospace;
font-size: 12px;
overflow: auto;
}
.ui-events__log pre {
border-bottom: 1px solid #000;
margin-bottom: 0;
padding-bottom: 12px;
white-space: pre-wrap;
}
```
--------
# Block events
Category: Events & effects
Keywords: event, block, pointer-events, overlay, infrontofthecanvas, user-select
Overlay UI on the canvas that captures pointer events instead of passing them through.
The `InFrontOfTheCanvas` component slot renders a full-size layer over the canvas with
`pointer-events: none`, so anything you put there is click-through by default. To make part of it
interactive, set `pointer-events: all` on that element. The slot sits above the canvas and marks
pointer events that start inside it as handled, so tldraw won't select, draw, or pan in response.
Try clicking and dragging inside the box, then outside it. The box also sets `user-select: text` on
its paragraph, since tldraw turns text selection off inside its container by default.
## App.tsx
```tsx
import { TLComponents, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import './event-blocker.css'
// There's a guide at the bottom of this file!
function WelcomeScreen() {
return (
// [1]
{/* [2] */}
{/* [3] */}
Notice that if you click on this box or start a drag from in here, you will not be
interacting with the canvas. However, you can still interact with the canvas by clicking
anywhere else!
)
}
/*
[1]
The `InFrontOfTheCanvas` slot is a full-size layer over the canvas that starts with
`pointer-events: none`, so anything rendered here is click-through by default. This
backdrop just centers the panel; pointer events pass straight through it to the canvas.
[2]
Setting `pointer-events: all` on the panel opts it back in. The slot sits above the canvas
and marks pointer events that start inside it as handled (see `editor.markEventAsHandled`),
so tldraw ignores them: clicking or dragging here won't select, draw, or pan. You don't need
to call `stopPropagation` yourself.
[3]
tldraw disables text selection everywhere inside its container so that dragging on the
canvas doesn't highlight text. If you want the user to be able to select text in your
overlay, set `user-select: text` on it.
*/
```
## event-blocker.css
```css
.event-blocker__backdrop {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
}
.event-blocker__panel {
pointer-events: all;
width: 400px;
padding: 32px;
border-radius: 20px;
box-shadow: 2px 2px 12px rgba(0, 0, 0, 0.2);
background-color: white;
}
.event-blocker__panel p {
user-select: text;
}
```
--------
# Prevent instance changes
Category: Events & effects
Keywords: instance state, prevent change, registerbeforechangehandler, side effects, grid mode, isgridmode, validation, state protection
Reject changes to the instance record that would turn grid mode off.
Side effects aren't just for shapes: you can register handlers for any record type in the store.
This example registers a `registerBeforeChangeHandler` for the `instance` record and returns the
previous record whenever the incoming change has `isGridMode: false`, which cancels the change.
Try toggling the grid from the main menu or with the keyboard shortcut: it stays on. Rejecting a
change this way is silent, so if the change came from a user action you may want to
explain why nothing happened. To reject only some fields of a change while keeping the rest, return
a merged record instead of `prev`.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
export default function PreventInstanceChangeExample() {
return (
{
editor.updateInstanceState({ isGridMode: true })
// Returning `prev` rejects the change no matter where it came from: menu, shortcut, or code.
editor.sideEffects.registerBeforeChangeHandler('instance', (prev, next) => {
if (!next.isGridMode) {
return prev
}
return next
})
}}
/>
)
}
```
--------
# Prevent shape changes
Category: Events & effects
Keywords: prevent transform, lock shape, registerbeforechangehandler, side effects, immutable shape, disable move, disable resize, disable rotate, shape protection
Reject changes to a shape's position, rotation, and size while still allowing style and text edits.
`editor.sideEffects.registerBeforeChangeHandler` sees every proposed shape change and returns the
record that will be written. This example compares `prev` and `next` for geo rectangles and returns
`prev` (cancelling the change) if `x`, `y`, `rotation`, `props.w`, or `props.h` would differ. Other
changes pass through untouched.
Try dragging, rotating, or resizing the rectangle: nothing happens. Now change its color or edit its
label: that works. This is a finer-grained alternative to `isLocked`, which would also stop the shape
being selected. A rejected change is silent, so consider giving the user some feedback if
this is a real permission rule.
## App.tsx
```tsx
import { Tldraw, toRichText } from 'tldraw'
import 'tldraw/tldraw.css'
export default function PreventShapeChangeExample() {
return (
{
editor.createShape({
type: 'geo',
x: 100,
y: 100,
props: {
w: 300,
h: 300,
richText: toRichText("style me but don't transform me"),
},
})
// Unlike locking the shape, rejecting transforms here leaves it selectable and editable.
editor.sideEffects.registerBeforeChangeHandler('shape', (prev, next) => {
if (
editor.isShapeOfType(prev, 'geo') &&
editor.isShapeOfType(next, 'geo') &&
next.props.geo === 'rectangle'
) {
if (
next.x !== prev.x ||
next.y !== prev.y ||
next.rotation !== prev.rotation ||
next.props.w !== prev.props.w ||
next.props.h !== prev.props.h
) {
return prev
}
}
return next
})
}}
/>
)
}
```
--------
# Prevent multi-shape selection
Category: Events & effects
Keywords: selection, single selection, prevent multi-select, instance page state, registerbeforechangehandler, selectedshapeids, selection control
Limit the selection to a single shape by rewriting selection changes in a before-change handler.
The current selection is stored on the `instance_page_state` record as `selectedShapeIds`. This
example registers a `registerBeforeChangeHandler` for that record and, whenever an incoming change
would select more than one shape, returns a copy with only the last id. Since every selection
method writes to the same record, one handler covers shift-click, brush selection, select all, and
`editor.select()` calls from your own code.
Try creating a few shapes and shift-clicking or dragging a selection box over them: only one ends up
selected. Rewriting the change instead of rejecting it (by returning `prev`) means the user's action
still does something sensible.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
export default function PreventMultiShapeSelectionExample() {
return (
{
// Rewriting to the last id (rather than rejecting) keeps brushing and select-all usable.
editor.sideEffects.registerBeforeChangeHandler('instance_page_state', (prev, next) => {
if (
prev.selectedShapeIds !== next.selectedShapeIds &&
next.selectedShapeIds.length > 1
) {
return {
...next,
selectedShapeIds: [next.selectedShapeIds[next.selectedShapeIds.length - 1]],
}
}
return next
})
}}
/>
)
}
```
--------
# Before create/update shape
Category: Events & effects
Keywords: side effects, registerbeforecreatehandler, registerbeforechangehandler, intercept, validation, lifecycle, hooks, shape creation
Intercept shapes before they're created or updated and keep them inside a circle.
`editor.sideEffects.registerBeforeCreateHandler` and `registerBeforeChangeHandler` run before a
record is written to the store. Whatever the handler returns is what gets written, so you can
adjust (or reject, by returning the previous record) a change instead of reacting to it afterwards.
In this example, both handlers run the same function that pulls a shape's origin back inside a
circle around the page origin.
Try drawing shapes and dragging them out past the circle: they stop at the edge. The camera is
locked on the circle so the constraint is easy to see. For the "after" side of this API, see the
after create/update shape example.
## App.tsx
```tsx
import { Box, Editor, SVGContainer, TLShape, Tldraw, Vec, isShapeId } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
const RADIUS = 500
// [1]
function constrainShapeToRadius(editor: Editor, shape: TLShape, radius: number) {
if (isShapeId(shape.parentId)) return shape
const shapePoint = Vec.From(shape)
const distanceFromCenter = shapePoint.len()
if (distanceFromCenter > radius) {
const newPoint = shapePoint.uni().mul(radius)
return {
...shape,
x: newPoint.x,
y: newPoint.y,
}
}
return shape
}
export default function BeforeCreateUpdateShapeExample() {
return (
)
}
/*
[1]
Returns a copy of the shape whose x/y origin is within `radius` of the page origin, or the
same shape if it's already inside (or if it's parented to another shape rather than the page,
since a child's x/y are relative to its parent, not the page). Note that this constrains the
shape's origin, not its whole bounds, so shapes can still poke out past the circle.
[2]
Before-create and before-change handlers run before the record is written to the store, and
whatever they return is what gets written. That lets us adjust a shape on its way in instead
of reacting after the fact. Registering the same function for both means the constraint holds
for newly drawn shapes as well as shapes being dragged, resized, or pasted.
[3]
Lock the camera on the constrained area so it's obvious what's happening. The camera lock
isn't part of the side effect; it's just for the demo.
*/
```
--------
# Before delete shape
Category: Events & effects
Keywords: side effects, registerbeforedeletehandler, intercept, prevent deletion, lifecycle, hooks, validation
Intercept shape deletions and cancel the ones you don't want to allow.
`editor.sideEffects.registerBeforeDeleteHandler` runs before a record is removed from the store.
Return `false` to cancel the deletion; return nothing to let it proceed. In this example, red shapes
can't be deleted but everything else can.
Try selecting each text shape and pressing delete. The red one stays put, whether you delete it
directly, select all and delete, or cut it. This only guards deletions: the user can still
recolor the shape and then delete it.
## App.tsx
```tsx
import { Editor, Tldraw, createShapeId, toRichText } from 'tldraw'
import 'tldraw/tldraw.css'
export default function BeforeDeleteShapeExample() {
return (
)
}
function createDemoShapes(editor: Editor) {
editor
.createShapes([
{
id: createShapeId(),
type: 'text',
props: {
richText: toRichText("Red shapes can't be deleted"),
color: 'red',
},
},
{
id: createShapeId(),
type: 'text',
y: 30,
props: {
richText: toRichText('but other shapes can'),
color: 'black',
},
},
])
.zoomToFit({ animation: { duration: 0 } })
}
```
--------
# Custom double-click behavior
Category: Events & effects
Keywords: double click, override, statenode, select tool, method replacement, handleDoubleClickOnCanvas, getStateDescendant, runtime, idle state, createTextOnCanvasDoubleClick
Replace what happens when the user double-clicks on empty canvas by patching the select tool's `Idle` state at runtime.
By default, double-clicking on empty canvas creates a text shape and starts editing it. That
behavior lives in the `handleDoubleClickOnCanvas` method of the select tool's `Idle` state. This
example uses `editor.getStateDescendant('select.idle')` from `onMount` to grab that state and
replace the method with one that shows an alert.
Try double-clicking on the canvas. Double-clicking an editable shape still edits it as usual, but
double-clicking a shape that can't be edited falls through to the same method, so it shows the
alert too.
**This example is hacky.** Patching a built-in state's method is a lightweight way to tweak one
behavior without writing a whole custom tool, but `handleDoubleClickOnCanvas` is not public API and
can be renamed or removed in any release. If you only want to disable the default, pass
`options={{ createTextOnCanvasDoubleClick: false }}` to `` instead. If you need different
behavior, write a custom select tool.
## App.tsx
```tsx
import { StateNode, TLClickEventInfo, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
// [1]
type IdleStateNode = StateNode & {
handleDoubleClickOnCanvas(info: TLClickEventInfo): void
}
export default function CustomDoubleClickBehaviorExample() {
return (
{
// [2]
const selectIdleState = editor.getStateDescendant('select.idle')
if (!selectIdleState) throw Error('SelectTool Idle state not found')
// [3]
selectIdleState.handleDoubleClickOnCanvas = function (_info: TLClickEventInfo) {
window.alert('double clicked on the canvas')
}
}}
/>
)
}
/*
The select tool's `Idle` state calls `handleDoubleClickOnCanvas` when the user double-clicks
on empty canvas (or on a shape that can't be edited). By default it creates a text shape and
starts editing it. Here we swap that method out at runtime for one that shows an alert.
[1]
The `Idle` class itself isn't exported from `tldraw`, and `handleDoubleClickOnCanvas` isn't
part of the public `StateNode` type, so we describe the shape we expect and cast to it.
[2]
`editor.getStateDescendant` walks the tool state tree by dotted path: `'select'` is the
select tool, `'select.idle'` is its idle child state. Because tools are singletons created
when the editor mounts, `onMount` is a safe place to patch them.
[3]
Assigning a `function` (rather than an arrow function) means `this` inside it is the state
node, the same as it would be for the original method. This replaces the default behavior
entirely; if you want to extend it instead, keep a reference to the original method and call
it from your replacement.
If all you want is to turn the default off, there's a simpler route: pass
`options={{ createTextOnCanvasDoubleClick: false }}` to ``.
*/
```
--------
# After create/update shape
Category: Events & effects
Keywords: side effects, registeraftercreatehandler, registerafterchangehandler, lifecycle, hooks, shape creation, shape update
Run a handler after shapes are created or updated to keep only one red shape on the page.
`editor.sideEffects.registerAfterCreateHandler` and `registerAfterChangeHandler` run after a
record has been written to the store. That makes them the right place to update _other_ records in
response to a change. Here, whenever a shape is created or changed and it turns out to be red, every
other red shape on the same page is turned black.
Try selecting one of the black words and setting its color to red in the style panel: the previously
red word turns black. Because after-change handlers also fire for the updates they cause, make sure
your handler is a no-op for records that already satisfy your rule, or it will loop.
## App.tsx
```tsx
import {
Editor,
TLShape,
TLShapeId,
TLShapePartial,
Tldraw,
createShapeId,
toRichText,
} from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
type ShapeWithColor = Extract
// [1]
function ensureOnlyOneRedShape(editor: Editor, shapeId: TLShapeId) {
const shape = editor.getShape(shapeId)!
if (!isRedShape(shape)) return
const pageId = editor.getAncestorPageId(shape.id)!
const otherRedShapesOnPage = Array.from(editor.getPageShapeIds(pageId))
.map((id) => editor.getShape(id)!)
.filter(
(otherShape): otherShape is ShapeWithColor =>
otherShape.id !== shape.id && isRedShape(otherShape)
)
editor.updateShapes(
otherRedShapesOnPage.map(
(shape) =>
({
id: shape.id,
type: shape.type,
props: { color: 'black' },
}) as TLShapePartial // [2]
)
)
}
function isRedShape(shape: TLShape) {
return 'color' in shape.props && shape.props.color === 'red'
}
export default function AfterCreateUpdateShapeExample() {
return (
)
}
function createDemoShapes(editor: Editor) {
editor
.createShapes(
'there can only be one red shape'.split(' ').map((word, i) => ({
id: createShapeId(),
type: 'text',
y: i * 30,
props: {
color: i === 5 ? 'red' : 'black',
richText: toRichText(word),
},
}))
)
.zoomToFit({ animation: { duration: 0 } })
}
/*
[1]
If the given shape is red, turn every other red shape on the same page black. Not every
shape type has a `color` prop (images and videos don't, for example), so we check for it
before reading it.
[2]
`ShapeWithColor` is a union of every shape type with a `color` prop, and TypeScript can't
narrow `{ type: shape.type, props: { color } }` back to one member of that union, so we assert
the partial. Each shape's `type` still comes from the shape itself, so the update is well formed.
[3]
Because `updateShapes` here triggers the after-change handler again for the shapes it turns
black, the check has to be a no-op for non-red shapes or it would loop forever.
*/
```
--------
# After delete shape
Category: Events & effects
Keywords: side effects, registerafterdeletehandler, lifecycle, hooks, shape deletion, frames, parent shapes
Run a handler after shapes are deleted to remove frames that have become empty.
`editor.sideEffects.registerAfterDeleteHandler` runs after a record has been removed from the
store, which makes it a good place to clean up anything that depended on that record. In this
example, deleting the last child of a frame deletes the frame too.
Try deleting the shapes inside the frame one by one. Once the last one goes, the frame disappears
with it. The handler also runs for the frame it just deleted, so nested frames cascade: emptying an
inner frame can empty and delete its outer frame too.
## App.tsx
```tsx
import { Editor, Tldraw, createShapeId, toRichText } from 'tldraw'
import 'tldraw/tldraw.css'
export default function AfterDeleteShapeExample() {
return (
)
}
function createDemoShapes(editor: Editor) {
const frameId = createShapeId()
editor.createShapes([
{
id: frameId,
type: 'frame',
props: { w: 400, h: 200 },
},
{
id: createShapeId(),
type: 'text',
parentId: frameId,
x: 50,
y: 40,
props: {
richText: toRichText('Frames will be deleted when their last child is.'),
w: 300,
autoSize: false,
},
},
...[50, 180, 310].map((x) => ({
id: createShapeId(),
type: 'geo' as const,
parentId: frameId,
x,
y: 120,
props: { w: 40, h: 40 },
})),
])
editor.zoomToFit({ animation: { duration: 0 } })
}
```
--------
# Permissions
Category: Events & effects
Keywords: constraints, bounds, side effects, permissions, clamping, registerbeforechangehandler, movement restriction, bounded region, shape geometry, svgcontainer
Keep a shape inside a bounding box by clamping its position in a before-change side effect.
`editor.sideEffects.registerBeforeChangeHandler` sees every proposed change to a shape before it's
written and can return a modified record instead. This example uses that to keep a rectangle inside
a dashed container: whenever the shape's new position would put any of it outside, its `x` and `y`
are clamped back in.
Try dragging the rectangle or nudging it with the arrow keys: it stops at the container edge every
time, because the constraint runs at the store level rather than in any one tool. Inside a
before-change handler the new shape isn't in the store yet, so the example computes geometry with `editor.getShapeUtil(shape).getGeometry(shape)`
rather than the cached `editor.getShapeGeometry`, which would return the old version. This example
only clamps position; resizing past the edge is handled in the permissions 2 example.
## App.tsx
```tsx
import { Box, clamp, Editor, SVGContainer, TLGeoShape, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
const CONTAINER_BOUNDS = new Box(100, 100, 400, 300)
// [1]
function constrainShapeToBounds(editor: Editor, shape: TLGeoShape): TLGeoShape {
const localBounds = editor.getShapeUtil(shape).getGeometry(shape).bounds
const pageBounds = new Box(
shape.x + localBounds.x,
shape.y + localBounds.y,
localBounds.w,
localBounds.h
)
if (CONTAINER_BOUNDS.contains(pageBounds)) return shape
// [2]
return {
...shape,
x: clamp(shape.x, CONTAINER_BOUNDS.x - localBounds.x, CONTAINER_BOUNDS.maxX - localBounds.maxX),
y: clamp(shape.y, CONTAINER_BOUNDS.y - localBounds.y, CONTAINER_BOUNDS.maxY - localBounds.maxY),
}
}
export default function PermissionsExample() {
return (
)
}
/*
[1]
Work out where the *proposed* shape would sit on the page. Inside a before-change handler the
new shape isn't in the store yet, so cached lookups like `editor.getShapeGeometry(shape)` or
`editor.getShapePageBounds(shape)` would describe the old version. Calling the shape util's
`getGeometry` directly computes from the record we were given.
[2]
Clamp the shape's origin so its bounds stay inside the container. Geometry bounds are in the
shape's local space (for a geo shape they start at 0,0), so we offset by them.
[3]
Before-change handlers run for every shape update, whether it came from dragging, the arrow
keys, alignment actions, or `editor.updateShapes` in your own code. Returning a modified record
is what gets written, so the constraint holds regardless of how the change was made. We only
apply it to geo shapes here.
[4]
Draw the container as a dashed rectangle in page coordinates so it's easy to see. It's purely
visual and takes no part in the constraint.
*/
```
--------
# Permissions 2
Category: Events & effects
Keywords: constraints, bounds, side effects, permissions, clamping, registerbeforechangehandler, movement restriction, bounded region, shape geometry, resize constraint
Keep a shape inside a bounding box when it's moved or resized, using a before-change side effect.
This is a follow-on to the permissions example. That one only clamps a shape's position; here the
`registerBeforeChangeHandler` side effect also clamps its size, so resizing past the container edge
shrinks the shape instead of letting it escape.
Try dragging the rectangle and pulling its resize handles past the dashed border. Because a
before-change handler sees the shape before it's written to the store, cached lookups like
`editor.getShapeGeometry` would return the shape's old size, so the example computes geometry from
the proposed record with `editor.getShapeUtil(shape).getGeometry(shape)`. The size clamp assumes an
unrotated rectangle; rotated shapes would need their page bounds clamped instead.
## App.tsx
```tsx
import { Box, clamp, Editor, SVGContainer, TLGeoShape, Tldraw, toRichText } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
const CONTAINER_BOUNDS = new Box(100, 100, 400, 300)
// [1]
function constrainShapeToBounds(editor: Editor, shape: TLGeoShape): TLGeoShape {
const localBounds = editor.getShapeUtil(shape).getGeometry(shape).bounds
const pageBounds = new Box(
shape.x + localBounds.x,
shape.y + localBounds.y,
localBounds.w,
localBounds.h
)
if (CONTAINER_BOUNDS.contains(pageBounds)) return shape
// [2]
const w = Math.min(shape.props.w, CONTAINER_BOUNDS.w)
const h = Math.min(shape.props.h, CONTAINER_BOUNDS.h)
return {
...shape,
x: clamp(shape.x, CONTAINER_BOUNDS.x, CONTAINER_BOUNDS.maxX - w),
y: clamp(shape.y, CONTAINER_BOUNDS.y, CONTAINER_BOUNDS.maxY - h),
props: { ...shape.props, w, h },
}
}
export default function PermissionsExample2() {
return (
)
}
/*
This builds on the permissions example, which only clamps position. Here a resize that would
push the shape past the container is clamped too.
[1]
Inside a before-change handler the new shape isn't in the store yet, so cached lookups like
`editor.getShapeGeometry(shape)` or `editor.getShapePageBounds(shape)` describe the *old*
version, which is exactly wrong when the change is a resize. Calling the shape util's
`getGeometry` directly computes bounds from the record we were given.
[2]
Clamp the size to the container first, then clamp the origin so the (possibly shrunk) shape
fits. This uses `props.w`/`props.h` directly, which is fine for an unrotated rectangle whose
geometry starts at its origin. A general solution would clamp the rotated page bounds instead.
[3]
Because the constraint runs at the store level, it applies however the change was made:
dragging, resize handles, arrow keys, alignment actions, or `editor.updateShapes` from your own
code. We only apply it to geo shapes here.
*/
```
--------
# Derived view
Category: Events & effects
Keywords: computed, incremental, derivation, performance, store history, diffsince, reactive, usevalue
Derive a set of draw shape ids from the store incrementally, using the store's change history instead of rescanning every shape.
A `computed` signal can look at what changed since it last ran, rather than recomputing from
scratch. This example builds a reactive set of draw shape ids: on the first run it scans every
shape, and after that it reads `store.history.getDiffSince(lastComputedEpoch)` and only adds or
removes ids for draw shapes that were created or deleted. If nothing relevant changed, it returns
the previous set so nothing downstream re-runs.
The counter at the top of the page reads the set's size with `useValue`. Try drawing a few strokes
and deleting them; moving or restyling shapes leaves the set untouched, so nothing downstream re-runs.
The same pattern works for any expensive derived view of the document.
## App.tsx
```tsx
import { useMemo } from 'react'
import {
computed,
Editor,
isShape,
isUninitialized,
RESET_VALUE,
TLComponents,
Tldraw,
TLShapeId,
useEditor,
useValue,
} from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
function DrawShapeCounter() {
const editor = useEditor()
// [1]
const drawShapeIds = useMemo(() => deriveDrawShapeIds(editor), [editor])
const count = useValue('draw shape count', () => drawShapeIds.get().size, [drawShapeIds])
return (
)
}
// [2]
export function deriveDrawShapeIds(editor: Editor) {
const { store } = editor
const shapeIds = store.query.ids('shape')
function fromScratch() {
return new Set([...shapeIds.get()].filter((id) => editor.getShape(id)!.type === 'draw'))
}
return computed>('drawShapeIds', (prevValue, lastComputedEpoch) => {
// [3]
if (isUninitialized(prevValue)) {
return fromScratch()
}
// [4]
const diff = store.history.getDiffSince(lastComputedEpoch)
if (diff === RESET_VALUE) {
return fromScratch()
}
// [5]
let nextValue: Set | undefined
for (const changes of diff) {
for (const record of Object.values(changes.added)) {
if (isShape(record) && record.type === 'draw') {
nextValue ??= new Set(prevValue)
nextValue.add(record.id)
}
}
for (const record of Object.values(changes.removed)) {
if (isShape(record) && record.type === 'draw') {
nextValue ??= new Set(prevValue)
nextValue.delete(record.id)
}
}
}
// [6]
return nextValue ?? prevValue
})
}
/*
Signals let you derive a value from the store and have it stay up to date. The naive way to
count draw shapes is to loop over every shape each time anything changes. That's fine for
small documents, but on large ones it's wasted work: most changes don't touch draw shapes at
all. This example builds a computed set of draw shape ids that updates itself incrementally
from the store's change history.
[1]
The derivation is created once per editor and read with `useValue`. Since `useValue` only
re-renders when the returned value changes, and we return the set's size, moving or restyling
shapes doesn't re-render this component at all.
[2]
`store.query.ids('shape')` is a reactive set of every shape id in the store. We only use it for
the from-scratch pass; the incremental path reads diffs instead.
[3]
The first time a `computed` runs, `prevValue` is a special uninitialized sentinel, so there's
nothing to diff against and we compute from scratch.
[4]
`store.history` is an atom whose value is a change counter and whose diffs are the record
changes between updates. `getDiffSince(lastComputedEpoch)` returns every change since our last
run, or `RESET_VALUE` if the history buffer no longer goes back that far (or the store was
reset), in which case we start over.
[5]
Walk the diffs and only allocate a new set if a draw shape was actually added or removed.
Updates to existing draw shapes don't change membership, so we skip `changes.updated`.
[6]
Returning `prevValue` when nothing changed means downstream signals (and `useValue`) see the
same reference and don't recompute. That's what makes the incremental approach cheap.
*/
```
--------
# Shape meta (on change)
Category: Events & effects
Keywords: meta, metadata, side effects, registerbeforechangehandler, getinitialmeta, onchange, tracking, audit, custom data
Stamp `updatedBy` and `updatedAt` metadata on shapes every time they change.
Every shape has a `meta` property for your own JSON data. This example keeps it up to date with a
`registerBeforeChangeHandler` side effect that rewrites `meta` on every user-initiated shape change,
and replaces `editor.getInitialMetaForShape` so new shapes start with the same fields. A panel at the
top shows the selected shape's meta.
Create a shape, select it, and move or restyle it: the timestamp updates with each change. The
handler ignores changes with `source: 'remote'`, so in a multiplayer document a peer's edits keep
their own author. For setting meta only at creation time, see the shape meta (on create) example.
## App.tsx
```tsx
import { TLComponents, TLShape, Tldraw, useEditor, useValue } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
// [1]
type ShapeWithMyMeta = TLShape & { meta: { updatedBy: string; updatedAt: number } }
function MetaUiHelper() {
const editor = useEditor()
// [2]
const onlySelectedShape = useValue(
'only selected shape',
() => editor.getOnlySelectedShape() as ShapeWithMyMeta | null,
[editor]
)
return (
{onlySelectedShape
? JSON.stringify(onlySelectedShape.meta, null, '\t')
: 'Select one shape to see its meta data.'}
)
}
/*
Every shape has a `meta` property for your own JSON data. tldraw stores and syncs it but never
reads it. This example stamps `updatedBy` and `updatedAt` on shapes as they change. See the
shapes docs for more on meta: https://tldraw.dev/docs/shapes#meta
[1]
A shape's `meta` is typed as `JsonObject`. To get useful types for your own fields, intersect
the shape type with the shape of your meta.
[2]
Reading `editor.getOnlySelectedShape()` inside `useValue` re-renders this panel whenever the
selection changes or the selected shape's record changes, which is what makes the meta update
live as you drag.
[3]
`getInitialMetaForShape` is called by `createShapes` for every new shape, and its result is
merged with any `meta` you passed. Replacing it here means new shapes start out with the same
fields the change handler maintains.
[4]
A before-change side effect can return a modified record to be written in place of `next`.
Filtering on `source === 'user'` skips changes that arrived from a remote peer, so in a
multiplayer document you don't overwrite the real author with the local user.
*/
```
--------
# Shape meta (on create)
Category: Events & effects
Keywords: meta, metadata, getinitialmeta, getinitialmetaforshape, oncreate, custom data, usevalue
Record who created each shape and when by replacing `editor.getInitialMetaForShape`.
Every shape has a `meta` property for your own JSON data. When `createShapes` creates a shape it
merges the result of `editor.getInitialMetaForShape(shape)` with whatever `meta` you passed. This
example replaces that method in `onMount` to stamp `createdBy` and `createdAt` on every new shape.
A panel at the top shows the selected shape's meta.
Create a shape and select it to see its meta. Since this only runs at creation, later edits leave
the values alone. To keep meta current as shapes change, see the shape meta (on change) example.
## App.tsx
```tsx
import { TLComponents, TLShape, Tldraw, useEditor, useValue } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
// [1]
type ShapeWithMyMeta = TLShape & { meta: { createdBy: string; createdAt: number } }
function MetaUiHelper() {
const editor = useEditor()
// [2]
const onlySelectedShape = useValue(
'only selected shape',
() => editor.getOnlySelectedShape() as ShapeWithMyMeta | null,
[editor]
)
return (
{onlySelectedShape
? JSON.stringify(onlySelectedShape.meta, null, '\t')
: 'Select one shape to see its meta data.'}
)
}
/*
Every shape has a `meta` property for your own JSON data. tldraw stores and syncs it but never
reads it. This example records who created each shape and when. See the shapes docs for more on
meta: https://tldraw.dev/docs/shapes#meta
[1]
A shape's `meta` is typed as `JsonObject`. To get useful types for your own fields, intersect
the shape type with the shape of your meta.
[2]
Reading `editor.getOnlySelectedShape()` inside `useValue` re-renders this panel whenever the
selection changes.
[3]
`getInitialMetaForShape` is called by `createShapes` for every new shape. Its result is merged
with any `meta` passed to `createShapes`, with the explicit meta winning. It's a plain method on
the editor, so the simplest way to customize it is to replace it in `onMount`. The shape is
passed in, so you can return different meta for different shape types.
*/
```
--------
# Unsaved changes
Category: Events & effects
Keywords: save, unsaved changes, document changes, store.listen, document scope, RecordsDiff, squashRecordDiffs, persistence, dirty state, getSnapshot
Track unsaved document changes as a squashed diff and enable a save button while there are any.
This example listens to the store with `editor.store.listen(handler, { scope: 'document' })`, so
only changes to persisted document records count, not the camera or selection. Each transaction's
diff is folded into a running `RecordsDiff` with `squashRecordDiffs`, so a shape that's created and
then deleted cancels out and repeated edits collapse into one. The save button in the top panel is
enabled while that diff is non-empty.
Try drawing something: the button lights up. Delete what you drew and it goes back to "No changes",
because the squashed diff is empty again. Clicking save hands the diff and a snapshot from
`editor.getSnapshot()` to a placeholder function and resets the diff.
## App.tsx
```tsx
import { useCallback, useEffect, useRef, useState } from 'react'
import {
RecordsDiff,
TLComponents,
TLEditorSnapshot,
TLEventMapHandler,
TLRecord,
Tldraw,
TldrawUiButton,
squashRecordDiffs,
useEditor,
} from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
function emptyDiff(): RecordsDiff {
return { added: {}, removed: {}, updated: {} }
}
function SaveButton() {
const editor = useEditor()
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
// [1]
const rUnsavedChanges = useRef>(emptyDiff())
useEffect(() => {
const handleDocumentChange: TLEventMapHandler<'change'> = (entry) => {
squashRecordDiffs([rUnsavedChanges.current, entry.changes], { mutateFirstDiff: true })
setHasUnsavedChanges(!isDiffEmpty(rUnsavedChanges.current))
}
// [2]
return editor.store.listen(handleDocumentChange, { scope: 'document' })
}, [editor])
// [3]
const handleSave = useCallback(() => {
saveChanges(rUnsavedChanges.current, editor.getSnapshot())
rUnsavedChanges.current = emptyDiff()
setHasUnsavedChanges(false)
}, [editor])
return (
)
}
function saveChanges(_diff: RecordsDiff, _snapshot: TLEditorSnapshot) {
// Send the diff or the snapshot to your server here.
}
function isDiffEmpty(diff: RecordsDiff) {
for (const key in diff.added) return false
for (const key in diff.removed) return false
for (const key in diff.updated) return false
return true
}
const components: TLComponents = {
TopPanel: SaveButton,
}
export default function UnsavedChangesExample() {
return (
)
}
/*
[1]
Rather than a boolean "dirty" flag, we accumulate every change since the last save into a
single `RecordsDiff`. `squashRecordDiffs` folds each new transaction into it, so a shape that
was created and then deleted cancels out, and a shape edited ten times shows up as one update
from its saved state to its current state. Because the squash mutates in place, this lives in
a ref rather than React state; the boolean state is only there to re-render the button.
[2]
`scope: 'document'` limits the listener to records that are part of the persisted document
(shapes, pages, assets, bindings, the document record). Session state like the camera,
selection, and current page still writes to the store but shouldn't count as unsaved work.
`store.listen` returns its unsubscribe function, so it doubles as the effect's cleanup.
[3]
When saving, you have two things to send: the accumulated diff (small, and exactly what
changed) or a full snapshot from `editor.getSnapshot()` (simpler to store and restore). Which
you use depends on your backend. Either way, reset the diff afterwards so it starts tracking
from the newly saved state.
*/
```
--------
# Custom shape
Category: Shapes & tools
Keywords: shapeutil, custom shape, getGeometry, component, indicator, HTMLContainer, Rectangle2d, getDefaultProps, props, validator
Define a minimal custom shape with a `ShapeUtil` and add it to the editor.
A custom shape needs a `ShapeUtil` subclass that declares its `type` and prop validators, returns default props, provides geometry for hit-testing, and renders a React component. Pass the util class to `` through the `shapeUtils` prop and the editor can create, select, resize, and persist the shape like any built-in one.
This example's shape is a rectangle with some text inside. It extends `ShapeUtil` directly so you can see `getGeometry` and `onResize` written out; extending `BaseBoxShapeUtil` would provide both for a `w`/`h` shape. The shape is created in `onMount`. To add a toolbar tool for creating it, see the custom shape and tool example.
## App.tsx
```tsx
import {
Geometry2d,
HTMLContainer,
RecordProps,
Rectangle2d,
ShapeUtil,
T,
TLResizeInfo,
TLShape,
Tldraw,
resizeBox,
} from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
const MY_CUSTOM_SHAPE_TYPE = 'my-custom-shape'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_CUSTOM_SHAPE_TYPE]: { w: number; h: number; text: string }
}
}
// [2]
type ICustomShape = TLShape
// [3]
export class MyShapeUtil extends ShapeUtil {
// [a]
static override type = MY_CUSTOM_SHAPE_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
text: T.string,
}
// [b]
getDefaultProps(): ICustomShape['props'] {
return {
w: 200,
h: 200,
text: "I'm a shape!",
}
}
// [c]
override canEdit(shape: ICustomShape) {
return false
}
override canResize(shape: ICustomShape) {
return true
}
override isAspectRatioLocked(shape: ICustomShape) {
return false
}
// [d]
getGeometry(shape: ICustomShape): Geometry2d {
return new Rectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
})
}
// [e]
override onResize(shape: ICustomShape, info: TLResizeInfo) {
return resizeBox(shape, info)
}
// [f]
component(shape: ICustomShape) {
return {shape.props.text}
}
// [g]
getIndicatorPath(shape: ICustomShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
// [4]
const customShape = [MyShapeUtil]
export default function CustomShapeExample() {
return (
)
}
/*
Introduction:
You can create custom shapes in tldraw by creating a shape util and passing it to the Tldraw component.
In this example, we'll create a custom shape that is a simple rectangle with some text inside of it.
[1]
First, we need to extend TLGlobalShapePropsMap to add our shape's props to the global type system.
This tells TypeScript about the shape's properties. For this shape, we define width (w), height (h),
and text as the shape's properties.
[2]
Define the shape type using TLShape with the shape's type as a type argument.
[3]
This is our shape util. In tldraw shape utils are classes that define how a shape behaves and renders.
We can extend the ShapeUtil class and provide the shape type as a generic. If we extended the
BaseBoxShapeUtil class instead, we wouldn't have to define methods such as `getGeometry` and `onResize`.
[a]
This is where we define our shape's props and type for the editor. It's important to use the same
string for the type as we did in [1]. We define the shape's props using tldraw's validator
library, which makes sure the store always has shape data we can trust.
[b]
This is a method that returns the default props for our shape.
[c]
Some handy methods for controlling different shape behaviour. These are the defaults, so you don't
have to define them; they're only shown here so you know they exist. Check out the editable shape
example to learn more about creating an editable shape.
[d]
The getGeometry method is what the editor uses for hit-testing, binding etc. We're using the
Rectangle2d class from tldraw's geometry library to create a rectangle shape. `isFilled: true`
means clicks inside the rectangle hit the shape, not just clicks on its outline. If we extended
the BaseBoxShapeUtil class, we wouldn't have to define this method.
[e]
We're using the resizeBox utility method to handle resizing our shape. If we extended the
BaseBoxShapeUtil class, we wouldn't have to define this method.
[f]
The component method defines how our shape renders. We're returning an HTMLContainer here, which
is a handy component that tldraw exports. It's essentially a div with some special css. There's a
lot of flexibility here, and you can use any React hooks you want and return any valid JSX.
[g]
The indicator is the blue outline around a selected shape. We're returning a Path2D for a rectangle
with the same width and height as the shape. The path is stroked onto the canvas overlay.
[4]
This is where we render the Tldraw component with our custom shape. We're passing in our custom shape
util as an array to the shapeUtils prop. We're also using the onMount callback to create a shape on
the canvas. If you want to learn how to add a tool for your shape, check out the custom config example.
If you want to learn how to programmatically control the canvas, check out the Editor API examples.
*/
```
--------
# Custom tool (sticker)
Category: Shapes & tools
Keywords: statenode, tool, pointer events, onpointerdown, onenter, cursor, createshape, state machine
A minimal custom tool that drops a heart emoji wherever you click.
Tools are nodes in tldraw's state chart and are responsible for handling user input. A custom tool extends `StateNode`, sets a static `id`, and overrides event handlers such as `onEnter` and `onPointerDown`. Pass the class to `` through the `tools` prop.
The sticker tool here sets a crosshair cursor when it becomes active and creates a text shape at `editor.inputs.getCurrentPagePoint()` on every pointer down. The example hides the UI and starts with the tool selected via `initialState`, so just click anywhere on the canvas. For a tool with child states and drag interactions, see the screenshot tool example; for adding a tool to the toolbar, see the custom shape and tool example.
## App.tsx
```tsx
import { StateNode, Tldraw, toRichText } from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
const OFFSET = 12
// [1]
class StickerTool extends StateNode {
static override id = 'sticker'
// [a]
override onEnter() {
this.editor.setCursor({ type: 'cross', rotation: 0 })
}
// [b]
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 customTools = [StickerTool]
export default function CustomToolExample() {
return (
)
}
/*
Introduction:
Tools are nodes in tldraw's state machine. They are responsible for handling user input.
You can create custom tools by extending the `StateNode` class and overriding its methods.
In this example we make a very simple sticker tool that adds a heart emoji to the canvas
when you click.
[1]
We extend the `StateNode` class to create a new tool called `StickerTool`. We set its id
to "sticker". We are not implementing any child states in this example, so we don't need
to set an initial state or define any children states. To see an example of a custom tool
with child states, check out the screenshot tool example.
[a] The onEnter method is called when the tool is activated. We use it to set the cursor
to a crosshair.
[b] The onPointerDown method is called when the user presses on the canvas. We create a
text shape at the pointer's page-space position, read from `editor.inputs`, offset so
the emoji is centered under the cursor.
[2]
We pass our custom tool to the Tldraw component using the `tools` prop. We also set the
initial state to our custom tool. We hide the ui and add some helpful text to the canvas
using the `onMount` prop. This is not necessary for the tool to work but it helps make the
example more visually clear.
*/
```
--------
# Custom tool (screenshot)
Category: Shapes & tools
Keywords: custom tool, statenode, screenshot, export, state machine, child states, brush selection, dragging state, overrides, toolbar, asset urls
A custom tool with child states that exports a dragged-out area of the canvas as a PNG.
Tools are `StateNode`s in tldraw's state chart, and this one has three child states: idle, pointing, and dragging. The dragging state keeps the box being drawn in an atom, which an `InFrontOfTheCanvas` component reads to draw the box over the canvas, and on pointer up it calls `exportAs` (or `copyAs` when ctrl is held) with `bounds` set to the box.
The example also shows the wiring a new tool needs: the `tools` prop, a `TLUiOverrides` entry so the UI knows the tool's label, icon, and shortcut, a custom icon via `assetUrls`, and a `Toolbar` override that adds the item.
Try selecting the screenshot tool (or press J) and dragging over some shapes. Hold shift for a 16:9 box, alt to center it on the start point, and ctrl to copy to the clipboard instead of downloading.
## App.tsx
```tsx
import {
Box,
DefaultToolbar,
DefaultToolbarContent,
TLComponents,
TLUiAssetUrlOverrides,
TLUiOverrides,
Tldraw,
TldrawUiMenuItem,
useEditor,
useIsToolSelected,
useTools,
useValue,
} from 'tldraw'
import 'tldraw/tldraw.css'
import { ScreenshotDragging } from './ScreenshotTool/childStates/Dragging'
import { ScreenshotTool } from './ScreenshotTool/ScreenshotTool'
// There's a guide at the bottom of this file!
// [1]
const customTools = [ScreenshotTool]
// [2]
const customUiOverrides: TLUiOverrides = {
tools: (editor, tools) => {
return {
...tools,
screenshot: {
id: 'screenshot',
label: 'Screenshot',
icon: 'tool-screenshot',
kbd: 'j',
onSelect() {
editor.setCurrentTool('screenshot')
},
},
}
},
}
function CustomToolbar() {
const tools = useTools()
const isScreenshotSelected = useIsToolSelected(tools['screenshot'])
return (
)
}
// [3]
const customAssetUrls: TLUiAssetUrlOverrides = {
icons: {
'tool-screenshot': '/tool-screenshot.svg',
},
}
// [4]
function ScreenshotBox() {
const editor = useEditor()
const screenshotBrush = useValue(
'screenshot brush',
() => {
if (editor.getPath() !== 'screenshot.dragging') return null
const draggingState = editor.getStateDescendant('screenshot.dragging')!
const box = draggingState.screenshotBox.get()
// The box is in page space, but this component sits in front of the canvas in
// viewport space, so convert it.
const zoomLevel = editor.getZoomLevel()
const { x, y } = editor.pageToViewport({ x: box.x, y: box.y })
return new Box(x, y, box.w * zoomLevel, box.h * zoomLevel)
},
[editor]
)
if (!screenshotBrush) return null
return (
)
}
const customComponents: TLComponents = {
InFrontOfTheCanvas: ScreenshotBox,
Toolbar: CustomToolbar,
}
// [5]
export default function ScreenshotToolExample() {
return (
)
}
/*
Introduction:
This example shows how to create a custom tool. In tldraw, tools are parts of the
tldraw state chart. While the most common use for tools is creating shapes, you can
use tools to create other types of interactions too! In this example, we create a
"screenshot tool" that lets the user draw a box on the canvas. When the user finishes
drawing their box, we'll export (or copy) a screenshot of that area.
[1]
Our custom tool is a class that extends `StateNode`. See the ScreenshotTool folder for the
tool itself. The array is defined outside of any React component and passed to the Tldraw
component's `tools` prop.
[2]
Register the tool with the UI by adding it to the `tools` object in a `TLUiOverrides`. This
gives the toolbar (and keyboard shortcuts) the tool's label, icon, shortcut, and what to do
when it's selected. The custom toolbar then places the item in front of the default content.
[3]
The toolbar item uses a custom icon, so we map its icon id to a url via `assetUrls.icons`.
[4]
While the tool's dragging state is active we draw the screenshot box in the
`InFrontOfTheCanvas` slot, which renders over the canvas but under menus and the toolbar. The
box lives in an atom on the dragging state node, so reading it inside `useValue` re-renders
this component as the user drags. `editor.getStateDescendant` finds that node by path.
[5]
All of the customizations are defined outside of the React component so they keep the same
identity across renders; new objects each render would make Tldraw re-register them.
*/
```
## ScreenshotTool.ts
```ts
import { StateNode } from 'tldraw'
import { ScreenshotDragging } from './childStates/Dragging'
import { ScreenshotIdle } from './childStates/Idle'
import { ScreenshotPointing } from './childStates/Pointing'
// There's a guide at the bottom of this file!
export class ScreenshotTool extends StateNode {
// [1]
static override id = 'screenshot'
static override initial = 'idle'
static override children() {
return [ScreenshotIdle, ScreenshotPointing, ScreenshotDragging]
}
// [2]
override onEnter() {
this.editor.setCursor({ type: 'cross', rotation: 0 })
}
override onExit() {
this.editor.setCursor({ type: 'default', rotation: 0 })
}
// [3]
override onInterrupt() {
this.complete()
}
override onCancel() {
this.complete()
}
private complete() {
this.parent.transition('select', {})
}
}
/*
[1]
The tool is a `StateNode` with the id "screenshot" and three child states: idle, pointing, and
dragging. `initial` names the child state to enter when the tool is selected.
[2]
Set a crosshair cursor while the tool is active and restore the default on exit.
[3]
Interrupt (e.g. a pinch gesture starts) and cancel (escape) both bail out to the select tool.
`this.parent` is the root state, whose children are the tools.
*/
```
## Dragging.ts
```ts
import { Box, StateNode, atom, copyAs, exportAs } from 'tldraw'
// There's a guide at the bottom of this file!
export class ScreenshotDragging extends StateNode {
static override id = 'dragging'
// [1]
screenshotBox = atom('screenshot brush', new Box())
// [2]
override onEnter() {
this.update()
}
override onPointerMove() {
this.update()
}
override onKeyDown() {
this.update()
}
override onKeyUp() {
this.update()
}
private update() {
const inputs = this.editor.inputs
const shiftKey = inputs.getShiftKey()
const altKey = inputs.getAltKey()
const originPagePoint = inputs.getOriginPagePoint()
const currentPagePoint = inputs.getCurrentPagePoint()
const box = Box.FromPoints([originPagePoint, currentPagePoint])
if (shiftKey) {
if (box.w > box.h * (16 / 9)) {
box.h = box.w * (9 / 16)
} else {
box.w = box.h * (16 / 9)
}
if (currentPagePoint.x < originPagePoint.x) {
box.x = originPagePoint.x - box.w
}
if (currentPagePoint.y < originPagePoint.y) {
box.y = originPagePoint.y - box.h
}
}
if (altKey) {
box.w *= 2
box.h *= 2
box.x = originPagePoint.x - box.w / 2
box.y = originPagePoint.y - box.h / 2
}
this.screenshotBox.set(box)
}
// [3]
override onPointerUp() {
const { editor } = this
const box = this.screenshotBox.get()
const shapes = editor.getCurrentPageShapes().filter((s) => {
const pageBounds = editor.getShapeMaskedPageBounds(s)
if (!pageBounds) return false
return box.includes(pageBounds)
})
if (shapes.length) {
if (editor.inputs.getCtrlKey()) {
copyAs(
editor,
shapes.map((s) => s.id),
{ format: 'png', bounds: box }
)
} else {
exportAs(
editor,
shapes.map((s) => s.id),
{
format: 'png',
name: 'Screenshot',
bounds: box,
}
)
}
}
this.editor.setCurrentTool('select')
}
// [4]
override onCancel() {
this.editor.setCurrentTool('select')
}
}
/*
[1]
The box the user is dragging out is stored in an atom so the UI can subscribe to it with
`useValue` (see the ScreenshotBox component in ScreenshotToolExample.tsx). A plain field
wouldn't trigger a re-render.
[2]
Recompute the box between the pointer-down origin and the current pointer on enter, on pointer
move, and on key down/up so the modifiers apply immediately: shift locks the box to 16:9 and
alt centers it on the origin at double size.
[3]
On pointer up, export every shape whose (masked) page bounds overlap the box as a PNG
cropped to the box, or copy it to the clipboard when ctrl is held. `exportAs` and `copyAs` are
the same helpers the export menu uses.
[4]
Cancel (escape) abandons the box and returns to the select tool.
*/
```
## Idle.ts
```ts
import { StateNode } from 'tldraw'
// There's a guide at the bottom of this file!
export class ScreenshotIdle extends StateNode {
static override id = 'idle'
// [1]
override onPointerDown() {
this.parent.transition('pointing')
}
}
/*
[1]
On pointer down, hand off to the sibling pointing state. `this.parent` is the screenshot tool.
*/
```
## Pointing.ts
```ts
import { StateNode } from 'tldraw'
// There's a guide at the bottom of this file!
export class ScreenshotPointing extends StateNode {
static override id = 'pointing'
// [1]
override onPointerMove() {
if (this.editor.inputs.getIsDragging()) {
this.parent.transition('dragging')
}
}
// [2]
override onPointerUp() {
this.complete()
}
override onCancel() {
this.complete()
}
private complete() {
this.parent.transition('idle')
}
}
/*
[1]
`inputs.getIsDragging()` becomes true once the pointer has moved past the drag distance
threshold since pointer down. Until then we stay here, so a plain click never starts a box.
[2]
A pointer up or cancel before the drag threshold is a click, not a screenshot, so go back to idle.
*/
```
--------
# Cubic bezier curve shape
Category: Shapes & tools
Keywords: bezier, curve, handles, control points, shapeutil, editing mode, statenode, getHandles, onHandleDrag, getHandleSnapGeometry, overlay
A cubic bezier curve shape with draggable control point handles.
`BezierCurveShapeUtil` stores four points (start, end, cp1, cp2), builds a `CubicBezier2d` geometry from them, and exposes each point as a handle through `getHandles`. `onHandleDrag` updates the props: dragging an endpoint carries its control point along, and cmd/ctrl + dragging an endpoint moves the control point instead. `getHandleSnapGeometry` lets control points snap onto the endpoints, which collapses that end of the curve into a sharp corner.
The example also keeps the curve in its editing state while you work on it. A custom `ShapeHandleOverlayUtil` shows handles during editing, and `CubicBezierShapeExample.tsx` wraps a few of the select tool's state node handlers so a handle drag returns to `select.editing_shape` rather than `select.idle`. **That part is hacky:** it patches select tool state nodes at runtime, which is not public API and can break between releases. Everything else in the example (the shape util, handles, snapping, overlay util) uses supported APIs.
Try dragging the handles, cmd/ctrl + clicking a control point to collapse it, and cmd/ctrl + dragging the curve itself to bend it.
## App.tsx
```tsx
import {
createShapeId,
Tldraw,
type Editor,
type StateNode,
type TLAnyOverlayUtilConstructor,
type TLAnyShapeUtilConstructor,
type TLHandle,
type TLOverlay,
type TLPointerEventInfo,
type TLShapeId,
} from 'tldraw'
import { BezierShapeHandleOverlayUtil } from './BezierShapeHandleOverlayUtil'
import { BezierCurveShapeUtil } from './CubicBezierShape'
import { SneakyUndoRedoWhileEditing } from './SneakyUndoRedoWhileEditing'
const customShapes: TLAnyShapeUtilConstructor[] = [BezierCurveShapeUtil]
type ShapeHandleOverlay = TLOverlay<{ shapeId: TLShapeId; handle: TLHandle }>
type PointingHandleState = StateNode & {
info?: TLPointerEventInfo & { target: 'handle' }
}
function getPointingHandleInfo(
state: PointingHandleState,
fallback?: TLPointerEventInfo
): (TLPointerEventInfo & { target: 'handle' }) | undefined {
if (state.info?.target === 'handle') return state.info
if (fallback?.target === 'handle') return fallback
return undefined
}
const customOverlays: TLAnyOverlayUtilConstructor[] = [BezierShapeHandleOverlayUtil]
function startEditingBezierShape(editor: Editor, id: TLShapeId) {
editor.setEditingShape(id)
editor.setCurrentTool('select.editing_shape')
}
function getBezierHandleOverlayAtPoint(editor: Editor): ShapeHandleOverlay | null {
const overlay = editor.overlays.getOverlayAtPoint(
editor.inputs.getCurrentPagePoint(),
editor.options.hitTestMargin / editor.getZoomLevel()
)
if (!overlay || overlay.type !== 'shape_handle') return null
const shapeHandleOverlay = overlay as ShapeHandleOverlay
const shape = editor.getShape(shapeHandleOverlay.props.shapeId)
if (!shape || !editor.isShapeOfType(shape, 'bezier-curve')) return null
return shapeHandleOverlay
}
function updateHoveredBezierHandle(editor: Editor) {
const editingShape = editor.getEditingShape()
if (!editingShape || !editor.isShapeOfType(editingShape, 'bezier-curve')) return false
const overlay = getBezierHandleOverlayAtPoint(editor)
const previousOverlayId = editor.overlays.getHoveredOverlayId()
if (overlay) {
editor.overlays.setHoveredOverlay(overlay.id)
editor.setHoveredShape(null)
const cursor = editor.overlays.getOverlayUtil(overlay).getCursor(overlay)
if (cursor) {
editor.setCursor({ type: cursor, rotation: editor.getSelectionRotation() })
}
return true
}
if (previousOverlayId) {
editor.setCursor({ type: 'default', rotation: 0 })
}
editor.overlays.setHoveredOverlay(null)
return false
}
export default function BezierCurveShapeExample() {
return (
{
editor.user.updateUserPreferences({ isSnapMode: true })
const viewportPageBounds = editor.getViewportPageBounds()
const centerX = viewportPageBounds.center.x
const centerY = viewportPageBounds.center.y
const id = createShapeId()
editor.createShape({
id,
type: 'bezier-curve',
x: centerX - 200,
y: centerY - 150,
})
// Select and edit the shape on appear
editor.select(id)
startEditingBezierShape(editor, id)
// [2]
const pointingHandleState =
editor.getStateDescendant('select.pointing_handle')
const editingShapeState = editor.getStateDescendant('select.editing_shape')
if (!pointingHandleState) {
throw new Error('SelectTool pointing_handle state not found')
}
if (!editingShapeState) {
throw new Error('SelectTool editing_shape state not found')
}
const originalHandlers = {
pointingHandle: {
onPointerMove: pointingHandleState.onPointerMove?.bind(pointingHandleState),
onPointerUp: pointingHandleState.onPointerUp?.bind(pointingHandleState),
},
editingShape: {
onPointerDown: editingShapeState.onPointerDown?.bind(editingShapeState),
onPointerMove: editingShapeState.onPointerMove?.bind(editingShapeState),
},
}
// clicking on start or end point should not go to select.idle
pointingHandleState.onPointerUp = (info: TLPointerEventInfo) => {
const handleInfo = getPointingHandleInfo(pointingHandleState, info)
if (!handleInfo) {
originalHandlers.pointingHandle.onPointerUp?.(info)
return
}
if (
handleInfo.accelKey &&
editor.isShapeOfType(handleInfo.shape, 'bezier-curve') &&
handleInfo.target === 'handle'
) {
switch (handleInfo.handle.id) {
case 'cp1': {
editor.updateShape({
id: handleInfo.shape.id,
type: 'bezier-curve',
props: {
cp1: {
x: handleInfo.shape.props.start.x,
y: handleInfo.shape.props.start.y,
},
},
})
startEditingBezierShape(editor, handleInfo.shape.id)
return
}
case 'cp2': {
editor.updateShape({
id: handleInfo.shape.id,
type: 'bezier-curve',
props: {
cp2: { x: handleInfo.shape.props.end.x, y: handleInfo.shape.props.end.y },
},
})
startEditingBezierShape(editor, handleInfo.shape.id)
return
}
}
}
if (
editor.isShapeOfType(handleInfo.shape, 'bezier-curve') &&
handleInfo.target === 'handle'
) {
startEditingBezierShape(editor, handleInfo.shape.id)
return
}
originalHandlers.pointingHandle.onPointerUp?.(info)
}
// return to editing state after dragging a handle
pointingHandleState.onPointerMove = (info: TLPointerEventInfo) => {
if (!editor.inputs.getIsDragging()) {
originalHandlers.pointingHandle.onPointerMove?.(info)
return
}
const handleInfo = getPointingHandleInfo(pointingHandleState, info)
if (!handleInfo) {
originalHandlers.pointingHandle.onPointerMove?.(info)
return
}
if (editor.isShapeOfType(handleInfo.shape, 'bezier-curve')) {
editor.updateInstanceState({ isToolLocked: true })
editor.setCurrentTool('select.dragging_handle', {
...handleInfo,
onInteractionEnd: () => {
startEditingBezierShape(editor, handleInfo.shape.id)
},
})
return
}
originalHandlers.pointingHandle.onPointerMove?.(info)
}
editingShapeState.onPointerDown = (info: TLPointerEventInfo) => {
const editingShape = editor.getEditingShape()
if (editingShape && editor.isShapeOfType(editingShape, 'bezier-curve')) {
const overlay = getBezierHandleOverlayAtPoint(editor)
if (overlay) {
editor.setCurrentTool('select.pointing_handle', {
...info,
target: 'handle',
shape: editingShape,
handle: overlay.props.handle,
})
return
}
}
originalHandlers.editingShape.onPointerDown?.(info)
}
// allow translating in editing state
editingShapeState.onPointerMove = (info: TLPointerEventInfo) => {
if (updateHoveredBezierHandle(editor) && !editor.inputs.getIsDragging()) return
if (editor.inputs.getIsDragging()) {
const editingShape = editor.getEditingShape()
if (editingShape && editor.isShapeOfType(editingShape, 'bezier-curve')) {
editor.updateInstanceState({ isToolLocked: true })
editor.setCurrentTool('select.translating', {
...info,
target: 'shape',
shape: editingShape,
onInteractionEnd: () => {
startEditingBezierShape(editor, editingShape.id)
},
})
return
}
}
originalHandlers.editingShape.onPointerMove?.(info)
}
}}
>
{/* [3] */}
)
}
/*
Introduction:
This example creates a cubic bezier curve shape with draggable handles. The shape itself lives
in CubicBezierShape.tsx; this file wires up the editor so the curve stays in its editing state
while its handles are dragged.
[1]
The default shape handle overlay only shows handles in select.idle and select.pointing_handle.
BezierShapeHandleOverlayUtil replaces it (same `type`, 'shape_handle') and also shows handles
for bezier curves while they're being edited or while a handle is being dragged, so the handles
don't disappear mid-interaction. Other shapes fall through to the default behaviour.
[2]
The select tool's child states normally return to select.idle after a handle drag, which would
end editing. Rather than fork the whole select tool, we grab the state nodes with
`getStateDescendant` and wrap their event handlers, delegating back to the originals for any
shape that isn't a bezier curve. The wrapped handlers add three interactions:
1. Cmd/ctrl + click on a cp1/cp2 handle collapses it onto its start/end point.
2. After dragging any handle, return to select.editing_shape instead of select.idle.
3. Dragging the curve itself while editing translates it, then returns to editing.
Patching state nodes like this is a workaround, not a supported API: it depends on the select
tool's internal state ids and event flow.
[3]
Undo/redo shortcuts are ignored while a shape is being edited, because for text shapes the text
editor owns them. SneakyUndoRedoWhileEditing listens for cmd/ctrl+z at the window level and
restores the editing shape afterwards. It's a hack, but a small one.
*/
```
## BezierShapeHandleOverlayUtil.ts
```ts
import { ShapeHandleOverlayUtil } from 'tldraw'
export class BezierShapeHandleOverlayUtil extends ShapeHandleOverlayUtil {
static override type = 'shape_handle'
override isActive(): boolean {
const editor = this.editor
const onlySelectedShape = editor.getOnlySelectedShape()
if (!onlySelectedShape || !editor.isShapeOfType(onlySelectedShape, 'bezier-curve')) {
return super.isActive()
}
if (editor.getIsReadonly() || editor.getInstanceState().isChangingStyle) return false
if (!editor.getShapeHandles(onlySelectedShape)) return false
if (editor.isInAny('select.pointing_handle', 'select.dragging_handle')) return true
return (
editor.getEditingShapeId() === onlySelectedShape.id && editor.isIn('select.editing_shape')
)
}
}
```
## CubicBezierShape.tsx
```tsx
import {
BoundsSnapGeometry,
CubicBezier2d,
Geometry2d,
getIndicesAbove,
HandleSnapGeometry,
HTMLContainer,
RecordProps,
ShapeUtil,
TLHandle,
TLHandleDragInfo,
TLResizeInfo,
TLShape,
Vec,
VecLike,
vecModelValidator,
ZERO_INDEX_KEY,
} from 'tldraw'
const BEZIER_CURVE_TYPE = 'bezier-curve'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[BEZIER_CURVE_TYPE]: { start: VecLike; cp1: VecLike; cp2: VecLike; end: VecLike }
}
}
// [2]
export type MyBezierCurveShape = TLShape
// [3]
export class BezierCurveShapeUtil extends ShapeUtil {
static override type = BEZIER_CURVE_TYPE
static override props: RecordProps = {
start: vecModelValidator,
cp1: vecModelValidator,
cp2: vecModelValidator,
end: vecModelValidator,
}
private isCtrlKeyOnTranslateStart = false
private didHitCurveOnTranslateStart = false
override getDefaultProps(): MyBezierCurveShape['props'] {
return {
start: { x: 0, y: 0 },
cp1: { x: 0, y: 140 },
cp2: { x: 350, y: 300 },
end: { x: 400, y: 110 },
}
}
override canEdit(): boolean {
return true
}
// [4]
getGeometry(shape: MyBezierCurveShape): Geometry2d {
return new CubicBezier2d({
start: new Vec(shape.props.start.x, shape.props.start.y),
cp1: new Vec(shape.props.cp1.x, shape.props.cp1.y),
cp2: new Vec(shape.props.cp2.x, shape.props.cp2.y),
end: new Vec(shape.props.end.x, shape.props.end.y),
})
}
override hideSelectionBoundsBg(shape: MyBezierCurveShape): boolean {
return this.editor.getEditingShapeId() === shape.id
}
override hideSelectionBoundsFg(shape: MyBezierCurveShape): boolean {
return this.editor.getEditingShapeId() === shape.id
}
override hideResizeHandles(shape: MyBezierCurveShape): boolean {
return this.editor.getEditingShapeId() === shape.id
}
override onResize(shape: MyBezierCurveShape, info: TLResizeInfo) {
const { scaleX, scaleY } = info
return {
props: {
start: { x: shape.props.start.x * scaleX, y: shape.props.start.y * scaleY },
cp1: { x: shape.props.cp1.x * scaleX, y: shape.props.cp1.y * scaleY },
cp2: { x: shape.props.cp2.x * scaleX, y: shape.props.cp2.y * scaleY },
end: { x: shape.props.end.x * scaleX, y: shape.props.end.y * scaleY },
},
}
}
override getBoundsSnapGeometry(shape: MyBezierCurveShape): BoundsSnapGeometry {
return {
points: [shape.props.start, shape.props.end],
}
}
override toSvg(shape: MyBezierCurveShape) {
const path = this.getGeometry(shape).getSvgPathData(true)
return
}
// [5]
override getHandles(shape: MyBezierCurveShape): TLHandle[] {
const indices = [ZERO_INDEX_KEY, ...getIndicesAbove(ZERO_INDEX_KEY, 3)]
let handles: TLHandle[] = [
{
id: 'start',
type: 'vertex',
x: shape.props.start.x,
y: shape.props.start.y,
index: indices[0],
snapType: 'align',
},
{
id: 'cp1',
type: 'vertex',
x: shape.props.cp1.x,
y: shape.props.cp1.y,
index: indices[1],
snapType: 'align',
snapReferenceHandleId: 'start',
},
{
id: 'cp2',
type: 'vertex',
x: shape.props.cp2.x,
y: shape.props.cp2.y,
index: indices[2],
snapType: 'align',
},
{
id: 'end',
type: 'vertex',
x: shape.props.end.x,
y: shape.props.end.y,
index: indices[3],
snapType: 'align',
},
]
if (Vec.Equals(shape.props.cp1, shape.props.start)) {
handles = handles.filter((handle) => handle.id !== 'cp1')
}
if (Vec.Equals(shape.props.cp2, shape.props.end)) {
handles = handles.filter((handle) => handle.id !== 'cp2')
}
return handles
}
// [6]
override getHandleSnapGeometry(shape: MyBezierCurveShape): HandleSnapGeometry {
return {
points: [shape.props.start, shape.props.end],
getSelfSnapPoints: (handle) => {
if (handle.id === 'cp1' || handle.id === 'cp2') {
return [shape.props.start, shape.props.end]
}
return handle.id === 'end' ? [shape.props.start] : [shape.props.end]
},
}
}
// [7]
override onHandleDrag(shape: MyBezierCurveShape, info: TLHandleDragInfo) {
const { handle } = info
const { id, x, y } = handle
let newProps: Partial = {}
// cmd/ctrl + drag on start or end moves that endpoint's control point instead
if (this.editor.inputs.getCtrlKey()) {
switch (id) {
case 'start': {
return {
...shape,
props: {
...shape.props,
cp1: { x, y },
},
}
}
case 'end': {
return {
...shape,
props: {
...shape.props,
cp2: { x, y },
},
}
}
}
}
switch (id) {
case 'start': {
const delta = Vec.Sub(handle, shape.props.start)
newProps = {
start: { x, y },
cp1: { x: shape.props.cp1.x + delta.x, y: shape.props.cp1.y + delta.y },
}
break
}
case 'end': {
const delta = Vec.Sub(handle, shape.props.end)
newProps = {
end: { x, y },
cp2: { x: shape.props.cp2.x + delta.x, y: shape.props.cp2.y + delta.y },
}
break
}
default: {
newProps = {
[id as 'cp1' | 'cp2']: { x, y },
}
break
}
}
return {
...shape,
props: {
...shape.props,
...newProps,
},
}
}
// [8]
override onTranslateStart(shape: MyBezierCurveShape) {
// sample the meta key once here so the curve doesn't start bending if the user presses
// cmd/ctrl partway through a plain translation
this.isCtrlKeyOnTranslateStart = this.editor.inputs.getCtrlKey()
// bend only when the drag started on the curve itself, not on the start or end handle
const handles = this.getHandles(shape)
const startAndEndHandles = handles.filter(
(handle) => handle.id === 'start' || handle.id === 'end'
)
if (!startAndEndHandles.length) return
const hitStartOrEndHandle = startAndEndHandles.some((handle) => {
const threshold = 8 / this.editor.getZoomLevel()
const pageTransform = this.editor.getShapePageTransform(shape)
const handleInPageSpace = pageTransform.applyToPoint(handle)
if (Vec.Dist(handleInPageSpace, this.editor.inputs.getCurrentPagePoint()) < threshold) {
return true
}
return false
})
const hitCurve = this.editor.isPointInShape(shape, this.editor.inputs.getCurrentPagePoint(), {
margin: 10 / this.editor.getZoomLevel(),
})
this.didHitCurveOnTranslateStart = hitCurve && !hitStartOrEndHandle
}
override onTranslate(initial: MyBezierCurveShape, current: MyBezierCurveShape) {
if (this.isCtrlKeyOnTranslateStart && this.didHitCurveOnTranslateStart) {
const delta = Vec.Sub(current, initial)
const offsetX = Math.round(delta.x)
const offsetY = Math.round(delta.y)
return {
...initial,
props: {
...initial.props,
cp1: { x: initial.props.cp1.x + offsetX, y: initial.props.cp1.y + offsetY },
cp2: { x: initial.props.cp2.x + offsetX, y: initial.props.cp2.y + offsetY },
},
}
}
return
}
// [9]
component(shape: MyBezierCurveShape) {
const path = this.getGeometry(shape).getSvgPathData(true)
const { start, end, cp1, cp2 } = shape.props
const zoomLevel = this.editor.getZoomLevel()
return (
)
}
getIndicatorPath(shape: MyBezierCurveShape) {
const path = this.getGeometry(shape).getSvgPathData(true)
return new Path2D(path)
}
private shouldShowControlLines(shape: MyBezierCurveShape) {
const selectedShape = this.editor.getOnlySelectedShape() === shape
if (!selectedShape) return false
return this.editor.isInAny(
'select.editing_shape',
'select.pointing_handle',
'select.dragging_handle'
)
}
}
/*
This is our custom cubic bezier curve shape. A cubic bezier curve is defined by four points: start,
end, and two control points (cp1, cp2).
[1]
Extend TLGlobalShapePropsMap to add our shape's props to the global type system: the four points
that define the curve.
[2]
Define the shape type using TLShape with the shape's type as a type argument.
[3]
BezierCurveShapeUtil extends ShapeUtil directly (rather than BaseBoxShapeUtil) because the shape has
no width and height props; its bounds come from the curve. `vecModelValidator` validates each point.
[4]
getGeometry returns a CubicBezier2d, which the editor uses for hit-testing, bounds, and snapping.
Because it isn't filled, clicking inside the curve's bounds but away from the line doesn't hit it.
[5]
Four handles: start, end, cp1, and cp2. A control point handle is hidden when it sits exactly on
its endpoint (a "collapsed" corner). `snapType: 'align'` lets a handle snap into alignment with the
snap points returned from [6].
[6]
getHandleSnapGeometry controls what handles snap to. `points` are what other shapes' handles snap
to; `getSelfSnapPoints` returns what this shape's own handles snap to. Control points snap to the
endpoints so you can collapse them by dragging, and endpoints snap to each other. The snap manager
handles zoom-independent thresholds and draws the snap indicators.
[7]
onHandleDrag returns the updated shape:
- Cmd/ctrl + drag on start/end moves that endpoint's control point (cp1 or cp2) instead.
- Dragging start/end also carries its control point along, so the curve keeps its shape.
- Dragging cp1/cp2 moves only that control point.
[8]
onTranslateStart and onTranslate implement "bending": cmd/ctrl + drag on the curve itself moves both
control points together instead of moving the shape. Whether to bend is decided once in
onTranslateStart, based on where the drag started and whether cmd/ctrl was down.
[9]
The component draws the curve, plus dashed lines from start→cp1 and end→cp2 while the shape is
being edited or a handle is being dragged. Stroke widths are divided by the zoom level so they stay
one screen pixel wide.
*/
```
## SneakyUndoRedoWhileEditing.tsx
```tsx
import { useEffect } from 'react'
import { useEditor } from 'tldraw'
export function SneakyUndoRedoWhileEditing() {
const editor = useEditor()
useEffect(() => {
function handleKeydown(e: KeyboardEvent) {
if (e.key === 'z' && (e.metaKey || e.ctrlKey)) {
const editingShape = editor.getEditingShape()
if (!editingShape) return
if (e.shiftKey) {
editor.redo()
editor.setEditingShape(editingShape)
} else {
editor.undo()
editor.setEditingShape(editingShape)
}
}
}
window.addEventListener('keydown', handleKeydown)
return () => {
window.removeEventListener('keydown', handleKeydown)
}
}, [editor])
return null
}
```
--------
# Custom shape and tool
Category: Shapes & tools
Keywords: shapeutils, tools, toolbar, custom tool, custom shape, icon, overrides, card, statenode, keyboard shortcut, migrations
Register a custom shape and a tool that creates it, with a toolbar button and keyboard shortcut.
The card shape is defined by `CardShapeUtil` (rendering, geometry, resizing, props validation, and migrations) and created by `CardShapeTool`, which extends `BaseBoxShapeTool` to get click-and-drag creation for free. Both are passed to `` through the `shapeUtils` and `tools` props.
The `ui-overrides.tsx` file adds the tool to the UI: the `tools` override registers it with an icon, label, and the `c` shortcut, and the custom `Toolbar` and `KeyboardShortcutsDialog` components place it alongside the defaults.
Select the card tool in the toolbar (the ⚫️ icon) or press `c`, then click or drag on the canvas to create a card. The card's button counts clicks to show that ordinary React state works inside a shape component.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { CardShapeTool } from './CardShape/CardShapeTool'
import { CardShapeUtil } from './CardShape/CardShapeUtil'
import { components, uiOverrides } from './ui-overrides'
// There's a guide at the bottom of this file!
// [1]
const customShapeUtils = [CardShapeUtil]
const customTools = [CardShapeTool]
// [2]
export default function CustomConfigExample() {
return (
)
}
/*
Introduction:
This example shows how to create a custom shape, and add your own icon for it to the toolbar.
Check out CardShapeUtil.tsx and CardShapeTool.tsx to see how we define the shape util and tool.
Check out ui-overrides.tsx for more info on how to add your icon to the toolbar.
[1]
We define arrays to hold the custom shape util and custom tool. It's important to do this outside of
any React component so that the arrays don't get redefined on every render.
[2]
Now we'll pass these arrays into the Tldraw component's props, along with our ui overrides.
*/
```
## ui-overrides.tsx
```tsx
import {
DefaultKeyboardShortcutsDialog,
DefaultKeyboardShortcutsDialogContent,
DefaultToolbar,
DefaultToolbarContent,
TLComponents,
TLUiOverrides,
TldrawUiMenuItem,
useIsToolSelected,
useTools,
} from 'tldraw'
export const uiOverrides: TLUiOverrides = {
tools(editor, tools) {
// Create a tool item in the ui's context.
tools.card = {
id: 'card',
icon: 'color',
label: 'Card',
kbd: 'c',
onSelect: () => {
editor.setCurrentTool('card')
},
}
return tools
},
}
export const components: TLComponents = {
Toolbar: (props) => {
const tools = useTools()
const isCardSelected = useIsToolSelected(tools['card'])
return (
)
},
KeyboardShortcutsDialog: (props) => {
const tools = useTools()
return (
)
},
}
/*
This file contains overrides for the Tldraw UI. These overrides are used to add your custom tools to
the toolbar and the keyboard shortcuts menu.
First we have to add our new tool to the tools object in the tools override. This is where we define
all the basic information about our new tool - its icon, label, keyboard shortcut, what happens when
we select it, etc.
Then, we replace the UI components for the toolbar and keyboard shortcut dialog with our own, which
add our new tool in front of the existing default content.
*/
```
## CardShapeTool.tsx
```tsx
import { BaseBoxShapeTool } from 'tldraw'
export class CardShapeTool extends BaseBoxShapeTool {
static override id = 'card'
static override initial = 'idle'
override shapeType = 'card' as const
}
/*
This file contains our custom tool. The tool is a StateNode with the `id` "card".
We get click-to-create and drag-to-create for free by extending BaseBoxShapeTool, but we
could handle events in our own way by overriding methods like onDoubleClick. For an example
of a tool with more custom functionality, check out the screenshot-tool example.
*/
```
## CardShapeUtil.tsx
```tsx
import { useState } from 'react'
import {
HTMLContainer,
Rectangle2d,
ShapeUtil,
TLDefaultColorStyle,
TLResizeInfo,
TLShape,
getColorValue,
resizeBox,
} from 'tldraw'
import { cardShapeMigrations } from './card-shape-migrations'
import { cardShapeProps } from './card-shape-props'
const CARD_TYPE = 'card'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[CARD_TYPE]: { w: number; h: number; color: TLDefaultColorStyle }
}
}
// A type for our custom card shape
export type ICardShape = TLShape
// There's a guide at the bottom of this file!
export class CardShapeUtil extends ShapeUtil {
static override type = CARD_TYPE
// [1]
static override props = cardShapeProps
// [2]
static override migrations = cardShapeMigrations
// [3]
override isAspectRatioLocked(shape: ICardShape) {
return false
}
override canResize(shape: ICardShape) {
return true
}
// [4]
getDefaultProps(): ICardShape['props'] {
return {
w: 300,
h: 300,
color: 'black',
}
}
// [5]
getGeometry(shape: ICardShape) {
return new Rectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
})
}
// [6]
component(shape: ICardShape) {
const { editor } = this
const bounds = editor.getShapeGeometry(shape).bounds
const theme = editor.getCurrentTheme()
const colors = theme.colors[editor.getColorMode()]
const { color } = shape.props
//[a]
// eslint-disable-next-line react-hooks/rules-of-hooks
const [count, setCount] = useState(0)
return (
Clicks: {count}
)
}
// [7]
getIndicatorPath(shape: ICardShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
// [8]
override onResize(shape: ICardShape, info: TLResizeInfo) {
return resizeBox(shape, info)
}
}
/*
A utility class for the card shape. This is where you define the shape's behavior,
how it renders (its component and indicator), and how it handles different events.
[1]
A validation schema for the shape's props (optional)
Check out card-shape-props.ts for more info.
[2]
Migrations for upgrading shapes (optional)
Check out card-shape-migrations.ts for more info.
[3]
Letting the editor know whether the shape's aspect ratio is locked and whether it
can be resized. These are the defaults, shown here so you know they exist.
[4]
The default props the shape will be rendered with when click-creating one.
[5]
We use this to calculate the shape's geometry for hit-testing, bindings and
doing other geometric calculations.
[6]
Render method — the React component that will be rendered for the shape. It takes the
shape as an argument. HTMLContainer is just a div that's being used to wrap our text
and button. The colors come from the editor's current theme so the card follows dark mode.
- [a] Check it out! We can do normal React stuff here like using useState.
- [b] You need to stop the pointer down event on buttons, otherwise the editor will
think you're trying to select or drag the shape.
[7]
getIndicatorPath — returns a Path2D used when hovering over the shape or when it's selected.
The path is stroked onto the canvas overlay.
[8]
Resize handler — called when the shape is resized. Sometimes you'll want to do some
custom logic here, but for our purposes, this is fine.
*/
```
## card-shape-migrations.ts
```ts
import { createShapePropsMigrationIds, createShapePropsMigrationSequence } from 'tldraw'
const versions = createShapePropsMigrationIds(
// this must match the shape type in the shape definition
'card',
{
AddColor: 1,
}
)
// Migrations for the custom card shape (optional but very helpful)
export const cardShapeMigrations = createShapePropsMigrationSequence({
sequence: [
{
id: versions.AddColor,
up(props) {
// it is safe to mutate the props object here
props.color = 'black'
},
down(props) {
delete props.color
},
},
],
})
```
## card-shape-props.ts
```ts
import { DefaultColorStyle, RecordProps, T } from 'tldraw'
import { ICardShape } from './CardShapeUtil'
// Validation for our custom card shape's props, using one of tldraw's default styles
export const cardShapeProps: RecordProps = {
w: T.number,
h: T.number,
color: DefaultColorStyle,
}
// To generate your own custom styles, check out the custom styles example.
```
--------
# Shape with onClick
Category: Shapes & tools
Keywords: onClick, custom shape, click handler, drag
Handle clicks on a custom shape with `ShapeUtil.onClick`.
Implement `onClick` on your shape util to react when the user clicks the shape. The select tool calls it on pointer up when the pointer didn't drag; return a shape partial and the editor applies it (and skips selecting the shape), or return nothing to fall through to normal selection.
Unlike a React `onClick` on a DOM element inside the shape component, `ShapeUtil.onClick` goes through the editor's event system, so clicking and dragging both work on selected and unselected shapes. Try clicking the shape to bump the counter, then dragging it.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { ClickableShapeUtil } from './ClickableShapeUtil'
// [1]
const customShapeUtils = [ClickableShapeUtil]
// [2]
export default function ShapeWithOnClickExample() {
return (
)
}
/*
[1]
We define the custom shape utils array outside of the component so it doesn't get recreated
on every render.
[2]
We pass our custom shape util to the Tldraw component and create an initial shape on mount
so there's something to interact with right away.
Try it:
- Click the shape to increment the counter
- Drag the shape to move it
- Both work whether or not the shape is selected
*/
```
## ClickableShapeUtil.tsx
```tsx
import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLShape, TLShapePartial } from 'tldraw'
// There's a guide at the bottom of this file!
const CLICKABLE_SHAPE_TYPE = 'clickable'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[CLICKABLE_SHAPE_TYPE]: { w: number; h: number; count: number }
}
}
type ClickableShape = TLShape
// [2]
export class ClickableShapeUtil extends BaseBoxShapeUtil {
static override type = CLICKABLE_SHAPE_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
count: T.number,
}
getDefaultProps(): ClickableShape['props'] {
return {
w: 200,
h: 100,
count: 0,
}
}
// [3]
override onClick(shape: ClickableShape): TLShapePartial | void {
return {
id: shape.id,
type: shape.type,
props: {
count: shape.props.count + 1,
},
}
}
// [4]
component(shape: ClickableShape) {
return (
Clicks: {shape.props.count}
)
}
// [5]
getIndicatorPath(shape: ClickableShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
/*
This example shows how to use ShapeUtil.onClick to handle clicks on a custom shape.
[1]
Extend TLGlobalShapePropsMap to register the shape's props. We include a `count` prop
that tracks how many times the shape has been clicked.
[2]
Our shape util class. We extend BaseBoxShapeUtil which provides getGeometry (a filled
rectangle from w/h), onResize, and snap geometry for free.
[3]
The onClick handler is the key part of the example. The select tool calls it on pointer
up when the user clicks the shape without dragging. If it returns a shape partial, the
editor applies it and skips selecting the shape; return nothing to fall through to the
normal selection behavior.
This is different from a React onClick on a DOM element inside the component: those
elements sit under the editor's pointer handling (HTMLContainer has pointer-events: none),
so a React handler would also need pointer-events: all and would fight with dragging.
ShapeUtil.onClick goes through the editor's event system, so click and drag coexist.
[4]
The component renders the click count. There are no React event handlers here; the click
handling is done entirely through ShapeUtil.onClick above.
[5]
getIndicatorPath returns a Path2D that tldraw strokes onto the canvas overlay as the
blue outline when the shape is selected.
*/
```
--------
# Shape with onDoubleClickEdge
Category: Shapes & tools
Keywords: onDoubleClickEdge, custom shape, resize, edge, double click
Toggle a custom shape between two sizes with `ShapeUtil.onDoubleClickEdge`.
Implement `onDoubleClickEdge` on your shape util to react when the user double-clicks one of the four edge resize handles (top, right, bottom, left) of a selected shape. Return a shape partial to update the shape, or nothing to fall through to the default double-click behavior. Corners have a matching `onDoubleClickCorner` handler.
Select the shape and double-click one of its edges: it toggles between 400×320 and 200×200.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { ResizableShapeUtil } from './ResizableShapeUtil'
// [1]
const customShapeUtils = [ResizableShapeUtil]
// [2]
export default function ShapeWithOnDoubleClickEdgeExample() {
return (
)
}
/*
[1]
We define the custom shape utils array outside of the component so it doesn't get
recreated on every render.
[2]
We pass our custom shape util to the Tldraw component and create an initial shape
on mount so there's something to interact with right away.
Try it:
- Select the shape, then double-click one of its edge resize handles
- The shape toggles between 400×320 and 200×200
*/
```
## ResizableShapeUtil.tsx
```tsx
import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLShape, TLShapePartial } from 'tldraw'
// There's a guide at the bottom of this file!
const RESIZABLE_SHAPE_TYPE = 'resizable'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[RESIZABLE_SHAPE_TYPE]: { w: number; h: number }
}
}
type ResizableShape = TLShape
export class ResizableShapeUtil extends BaseBoxShapeUtil {
static override type = RESIZABLE_SHAPE_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
}
getDefaultProps(): ResizableShape['props'] {
return {
w: 400,
h: 320,
}
}
// [2]
override onDoubleClickEdge(shape: ResizableShape): TLShapePartial | void {
const isAtSmallSize = shape.props.w === 200 && shape.props.h === 200
return {
id: shape.id,
type: shape.type,
props: isAtSmallSize ? { w: 400, h: 320 } : { w: 200, h: 200 },
}
}
component(shape: ResizableShape) {
return (
{shape.props.w} × {shape.props.h}
)
}
getIndicatorPath(shape: ResizableShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
/*
This example shows how to use ShapeUtil.onDoubleClickEdge to handle double-clicks
on a shape's resize edge.
[1]
Extend TLGlobalShapePropsMap to register the shape's props. We just need width
and height for this example.
[2]
The select tool calls onDoubleClickEdge when the user double-clicks one of the
selected shape's edge resize handles (top, right, bottom, left); corners go to
onDoubleClickCorner instead. We return a shape partial that toggles the shape
between two preset sizes. The editor marks a history stopping point and applies
the partial, so the toggle is a single undo step. Return nothing to fall through
to the default double-click behavior (starting to edit, if the shape allows it).
*/
```
--------
# Custom shape with custom styles
Category: Shapes & tools
Keywords: custom styles, styleprop, defineenum, style panel, defaultstylepanel, userelevantsstyles, setstyleforselectedshapes, shapeutil
Define your own style with `StyleProp.defineEnum` and expose it in the style panel.
Styles are shape props that the editor tracks across selections: the style panel shows the shared value of every selected shape, and new shapes pick up the most recently used value. This example defines a custom "rating" style, uses it as a prop on a custom shape, and adds a dropdown for it to the default style panel using `useRelevantStyles` and `editor.setStyleForSelectedShapes`.
Select the shapes and change the rating in the style panel. Try selecting both shapes at once to see the "mixed" state.
To use tldraw's existing styles with your shapes, check the [tldraw styles example](https://tldraw.dev/examples/shape-with-tldraw-styles).
## App.tsx
```tsx
import {
BaseBoxShapeUtil,
DefaultStylePanel,
DefaultStylePanelContent,
HTMLContainer,
StyleProp,
T,
TLComponents,
Tldraw,
TLShape,
useEditor,
useRelevantStyles,
} from 'tldraw'
import 'tldraw/tldraw.css'
const MY_SHAPE_WITH_CUSTOM_STYLES_TYPE = 'myshapewithcustomstyles'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_SHAPE_WITH_CUSTOM_STYLES_TYPE]: {
w: number
h: number
rating: MyRatingStyle
}
}
}
// There's a guide at the bottom of this file!
// [1]
const myRatingStyle = StyleProp.defineEnum('example:rating', {
defaultValue: 1,
values: [1, 2, 3, 4, 5],
})
// [2]
type MyRatingStyle = T.TypeOf
type IMyShape = TLShape
class MyShapeUtil extends BaseBoxShapeUtil {
static override type = MY_SHAPE_WITH_CUSTOM_STYLES_TYPE
// [3]
static override props = {
w: T.number,
h: T.number,
rating: myRatingStyle,
}
getDefaultProps(): IMyShape['props'] {
return {
w: 300,
h: 300,
rating: 4, // [4]
}
}
component(shape: IMyShape) {
// [5]
const stars = ['☆', '☆', '☆', '☆', '☆']
for (let i = 0; i < shape.props.rating; i++) {
stars[i] = '★'
}
return (
{stars}
)
}
getIndicatorPath(shape: IMyShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
// [6]
function CustomStylePanel() {
const editor = useEditor()
const styles = useRelevantStyles()
if (!styles) return null
const rating = styles.get(myRatingStyle)
return (
{rating !== undefined && (
)
}
/*
This file shows a custom shape that uses a custom style. For more on custom
shapes, see the custom shape example.
[1]
Our custom shape uses a new style called "rating". We create it with
StyleProp.defineEnum so that it has a fixed set of values and a default. The
id ('example:rating') must be unique across all styles in the editor.
[2]
Extract the type of the style's values so we can use it in the shape's props.
[3]
Pass the style as one of the shape's props. Any prop whose validator is a
StyleProp is treated as a style: the editor tracks it across selections and
shows it in the style panel.
[4]
Because this prop is a style, whatever value we put here in the default
props is overwritten when a shape is created: the editor uses its "style for
next shape" value instead, which is either the style's default value or the
value the user most recently set. This is special behavior just for styles.
[5]
Inside the component we read the style just like any other prop.
[6]
A custom style panel that renders the default style panel content plus a
dropdown for the rating style. useRelevantStyles returns the styles shared by
the selected shapes (or the current tool), and each entry is either a shared
value or 'mixed'. editor.setStyleForSelectedShapes writes the new value to
every selected shape, and editor.setStyleForNextShapes remembers it for shapes
created afterwards, which is what the default style panel does too. For more
on customizing the style panel, see the stroke size picker example.
[7]
Define shapeUtils and components outside the React component so they aren't
recreated on every render.
[8]
We create two shapes. The first does not specify a rating, so it gets the
editor's current value for the style, which is the style's default of 1 (not
the 4 in getDefaultProps, see [4]). The second specifies a rating of 5, so it
uses that value.
*/
```
--------
# Custom shape with tldraw styles
Category: Shapes & tools
Keywords: default styles, defaultsizestyle, defaultcolorstyle, style panel, getcurrenttheme, getcolorvalue, shapeutil
Use tldraw's built-in size and color styles as props on a custom shape.
The default style panel shows the styles shared by your selection or current tool. If all selected shapes have the same value for a style, that value is shown as selected; otherwise the panel shows it as "mixed". You get this for free on custom shapes by using tldraw's `StyleProp`s (here `DefaultSizeStyle` and `DefaultColorStyle`) as prop validators.
Select the shape and change the size and color in the style panel. The shape reads the color from the current theme with `editor.getCurrentTheme()` and `getColorValue`, so it also follows dark mode.
To create your own custom styles, check the [custom styles example](https://tldraw.dev/examples/shape-with-custom-styles).
## App.tsx
```tsx
import {
BaseBoxShapeUtil,
DefaultColorStyle,
DefaultSizeStyle,
getColorValue,
HTMLContainer,
T,
TLDefaultColorStyle,
TLDefaultSizeStyle,
Tldraw,
TLShape,
} from 'tldraw'
import 'tldraw/tldraw.css'
const MY_SHAPE_WITH_TLDRAW_STYLES_TYPE = 'myshapewithtldrawstyles' as const
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_SHAPE_WITH_TLDRAW_STYLES_TYPE]: {
w: number
h: number
size: TLDefaultSizeStyle
color: TLDefaultColorStyle
}
}
}
// There's a guide at the bottom of this file!
// [1]
const FONT_SIZES: Record = {
s: 1.125,
m: 1.5,
l: 2.25,
xl: 2.75,
}
type IMyShape = TLShape
class MyShapeUtil extends BaseBoxShapeUtil {
static override type = MY_SHAPE_WITH_TLDRAW_STYLES_TYPE
// [2]
static override props = {
w: T.number,
h: T.number,
size: DefaultSizeStyle,
color: DefaultColorStyle,
}
getDefaultProps(): IMyShape['props'] {
return {
w: 300,
h: 300,
size: 'm',
color: 'black',
}
}
// [3]
component(shape: IMyShape) {
const theme = this.editor.getCurrentTheme()
const colors = theme.colors[this.editor.getColorMode()]
return (
Select the shape and use the style panel to change the font size and color
)
}
/*
This file shows a custom shape that uses tldraw's default styles. For more on
custom shapes, see the custom shape example.
[1]
Style values are just strings like 's' or 'black'; it's up to the shape to
decide what they mean. Here we map each size to a multiplier of the theme's
base font size (theme.fontSize is 16px in the default theme), so text scales
with custom themes. Any mapping works; these happen to match tldraw's own text
shape.
[2]
For the shape's props, we use the DefaultSizeStyle and DefaultColorStyle
StyleProps for the size and color properties. Because the validators are
StyleProps, the editor treats these props as styles: the style panel shows
them for this shape, and new shapes pick up the most recently used values.
(You can use the useRelevantStyles hook to get the styles of the user's
selected shapes in your own UI.)
[3]
Inside the component we read the styles to change how the shape looks. We get
the color from the editor's current theme via editor.getCurrentTheme() and
getColorValue, which resolves the color name for the current light or dark
mode. Reading the theme here is reactive, so the shape re-renders when the
theme or color mode changes.
*/
```
--------
# Clickable custom shape
Category: Shapes & tools
Keywords: interaction, pointer events, stop propagation, click, input, button, checkbox, todo, html, custom shape, onclick
A todo shape with a checkbox and text input that handle their own pointer events.
By default the editor handles all pointer events on the canvas, so clicking a shape selects it and dragging moves it. To let part of a shape handle its own interactions, set `pointer-events: all` on the shape's `HTMLContainer` and call `stopPropagation()` on the events you want to keep from reaching the canvas.
Try clicking the checkbox to toggle the todo and typing in the input. Once a todo is checked, the input becomes read-only and lets pointer events through, so clicking it selects the shape as usual. See `my-interactive-shape-util.tsx` for the shape.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { myInteractiveShape } from './my-interactive-shape-util'
// There's a guide at the bottom of this file!
// [1]
const customShapeUtils = [myInteractiveShape]
export default function InteractiveShapeExample() {
return (
)
}
/*
[1]
The shape util array is defined outside the component so it keeps the same identity across
renders. See my-interactive-shape-util.tsx for the shape itself, which shows how to let a
shape handle its own pointer events (a checkbox and a text input) without the editor
selecting or dragging it.
*/
```
## my-interactive-shape-util.tsx
```tsx
import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLShape } from 'tldraw'
// There's a guide at the bottom of this file!
const MY_INTERACTIVE_SHAPE_TYPE = 'my-interactive-shape'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_INTERACTIVE_SHAPE_TYPE]: { w: number; h: number; checked: boolean; text: string }
}
}
export type IMyInteractiveShape = TLShape
export class myInteractiveShape extends BaseBoxShapeUtil {
static override type = MY_INTERACTIVE_SHAPE_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
checked: T.boolean,
text: T.string,
}
getDefaultProps(): IMyInteractiveShape['props'] {
return {
w: 230,
h: 230,
checked: false,
text: '',
}
}
// [1]
component(shape: IMyInteractiveShape) {
return (
this.editor.updateShape({
id: shape.id,
type: MY_INTERACTIVE_SHAPE_TYPE,
props: { checked: !shape.props.checked },
})
}
// [b] This is where we stop event propagation
onPointerDown={(e) => e.stopPropagation()}
onTouchStart={(e) => e.stopPropagation()}
onTouchEnd={(e) => e.stopPropagation()}
/>
this.editor.updateShape({
id: shape.id,
type: MY_INTERACTIVE_SHAPE_TYPE,
props: { text: e.currentTarget.value },
})
}
// [c]
onPointerDown={(e) => {
if (!shape.props.checked) {
e.stopPropagation()
}
}}
onTouchStart={(e) => {
if (!shape.props.checked) {
e.stopPropagation()
}
}}
onTouchEnd={(e) => {
if (!shape.props.checked) {
e.stopPropagation()
}
}}
/>
)
}
getIndicatorPath(shape: IMyInteractiveShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
/*
This is a custom shape, for a more in-depth look at how to create a custom shape,
see our custom shape example.
[1]
This is where we describe how our shape will render
[a] Shape containers have `pointer-events: none` by default so the canvas receives every
pointer event. Set it to `all` (or `auto`) to opt in to receiving events on the shape's HTML.
[b] Stop propagation so the editor doesn't select or start dragging the shape when the
checkbox is clicked. The canvas container forwards the events it receives on to the editor,
so stopping them here keeps them from reaching the canvas.
[c] While the todo is unchecked, the text input handles its own pointer events. Once it's
checked the input is read-only, so we let the events through to the canvas and the shape
selects and drags as usual.
*/
```
--------
# Custom handle snap reference
Category: Shapes & tools
Keywords: handles, snapping, snapReferenceHandleId, angle snapping, shift modifier, getHandles, control points, vertex, reference point
Choose which handle a shift-drag angle snap is measured from with `snapReferenceHandleId`.
When a user holds shift while dragging a handle, the select tool snaps the handle to 15 degree increments around a reference handle. By default that reference is the next vertex handle in index order. Setting `snapReferenceHandleId` on a handle returned from `getHandles` overrides the reference.
The Y-shaped connector here has a center junction and three arms. Each arm handle names `center` as its snap reference, so shift-dragging an arm rotates it around the junction in clean angles instead of around a neighbouring arm.
The shape is selected on load so its handles are visible. Try shift-dragging one of the arm endpoints, then compare with a plain drag.
## App.tsx
```tsx
import {
Edge2d,
Geometry2d,
Group2d,
HTMLContainer,
RecordProps,
ShapeUtil,
TLHandle,
TLHandleDragInfo,
TLShape,
Tldraw,
Vec,
VecLike,
ZERO_INDEX_KEY,
createShapeId,
getIndicesAbove,
vecModelValidator,
} from 'tldraw'
import 'tldraw/tldraw.css'
const Y_SHAPE_TYPE = 'y-shape'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[Y_SHAPE_TYPE]: {
center: VecLike
armTop: VecLike
armLeft: VecLike
armRight: VecLike
}
}
}
// [2]
type YShape = TLShape
// [3]
class YShapeUtil extends ShapeUtil {
static override type = Y_SHAPE_TYPE
static override props: RecordProps = {
center: vecModelValidator,
armTop: vecModelValidator,
armLeft: vecModelValidator,
armRight: vecModelValidator,
}
override getDefaultProps(): YShape['props'] {
return {
center: { x: 100, y: 100 },
armTop: { x: 100, y: 180 },
armLeft: { x: 30, y: 20 },
armRight: { x: 170, y: 20 },
}
}
override canEdit(): boolean {
return true
}
override hideSelectionBoundsBg(): boolean {
return true
}
override hideSelectionBoundsFg(): boolean {
return true
}
override hideResizeHandles(): boolean {
return true
}
override hideRotateHandle(): boolean {
return true
}
// [4]
getGeometry(shape: YShape): Geometry2d {
const { center, armTop, armLeft, armRight } = shape.props
const c = Vec.From(center)
const t = Vec.From(armTop)
const l = Vec.From(armLeft)
const r = Vec.From(armRight)
return new Group2d({
children: [
new Edge2d({ start: c, end: t }),
new Edge2d({ start: c, end: l }),
new Edge2d({ start: c, end: r }),
],
})
}
// [5]
override getHandles(shape: YShape): TLHandle[] {
const indices = [ZERO_INDEX_KEY, ...getIndicesAbove(ZERO_INDEX_KEY, 3)]
return [
{
id: 'center',
type: 'vertex',
x: shape.props.center.x,
y: shape.props.center.y,
index: indices[0],
},
{
id: 'armTop',
type: 'vertex',
x: shape.props.armTop.x,
y: shape.props.armTop.y,
index: indices[1],
// [6]
snapReferenceHandleId: 'center',
},
{
id: 'armLeft',
type: 'vertex',
x: shape.props.armLeft.x,
y: shape.props.armLeft.y,
index: indices[2],
snapReferenceHandleId: 'center',
},
{
id: 'armRight',
type: 'vertex',
x: shape.props.armRight.x,
y: shape.props.armRight.y,
index: indices[3],
snapReferenceHandleId: 'center',
},
]
}
override onHandleDrag(shape: YShape, info: TLHandleDragInfo) {
const { handle } = info
return {
...shape,
props: {
...shape.props,
[handle.id]: { x: handle.x, y: handle.y },
},
}
}
// [7]
component(shape: YShape) {
const { center, armTop, armLeft, armRight } = shape.props
return (
)
}
getIndicatorPath(shape: YShape) {
const { center, armTop, armLeft, armRight } = shape.props
const path = new Path2D()
path.moveTo(center.x, center.y)
path.lineTo(armTop.x, armTop.y)
path.moveTo(center.x, center.y)
path.lineTo(armLeft.x, armLeft.y)
path.moveTo(center.x, center.y)
path.lineTo(armRight.x, armRight.y)
return path
}
}
const customShapes = [YShapeUtil]
export default function CustomRelativeSnappingYShapeExample() {
return (
)
}
/*
The shape is a Y-shaped connector: three arms radiating from a center junction point.
When you hold shift while dragging a handle, the editor snaps the handle's angle to 15 degree
increments, measured from a reference handle. By default the reference is the next vertex handle
in index order, which for a shape like this would be a neighbouring arm rather than the junction.
`snapReferenceHandleId` lets each arm name the center as its reference instead.
[1]
Extend TLGlobalShapePropsMap to add our shape's props to the global type system: four points
representing the junction and the three arm endpoints.
[2]
Define the shape type using TLShape with the shape's type as a type argument.
[3]
The shape util, with `vecModelValidator` for each point. Selection bounds, resize handles, and
the rotate handle are hidden because the handles are the whole interface for this shape.
[4]
The geometry is a Group2d containing three Edge2d segments from the center to each arm, so
hit-testing follows the lines rather than the bounding box.
[5]
Four handles in index order: [center, armTop, armLeft, armRight]. `getIndicesAbove` generates
fractional index keys after ZERO_INDEX_KEY so the handles have a well-defined order.
[6]
Each arm sets `snapReferenceHandleId: 'center'`. Shift + drag any arm and its angle snaps
relative to the junction. Try removing the property from one arm and shift-dragging it: the
angle then snaps relative to whichever vertex handle comes next in index order.
[7]
The component draws the three arms as SVG lines.
*/
```
--------
# Custom shape with handles
Category: Shapes & tools
Keywords: handles, custom handles, gethandles, onhandledrag, interaction, geometry, tail, shapeutil, tool
A speech bubble shape whose tail is moved with a custom handle.
Handles let the user change a shape's geometry directly. This shape returns a single handle for its tail from `getHandles`, updates the tail in `onHandleDrag`, and uses `onBeforeUpdate` to keep the tail a sensible length and outside the bubble body no matter how the shape changes. The tail is stored as a fraction of the shape's size so it scales with drag-create and resize.
Pick the speech bubble tool from the toolbar (or press S), draw a bubble, then drag the tail handle around. Double-click to add text and watch the body grow to fit.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { SpeechBubbleTool } from './SpeechBubble/SpeechBubbleTool'
import { SpeechBubbleUtil } from './SpeechBubble/SpeechBubbleUtil'
import { components, customAssetUrls, uiOverrides } from './SpeechBubble/ui-overrides'
import './customhandles.css'
// There's a guide at the bottom of this file!
// [1]
const shapeUtils = [SpeechBubbleUtil]
const tools = [SpeechBubbleTool]
// [2]
export default function CustomShapeWithHandles() {
return (
)
}
/*
Use handles when you want user interaction to alter the geometry of a shape. Here a speech bubble
has a handle on the tail so the user can move it. Most of the interesting code is in
SpeechBubbleUtil.tsx and helpers.tsx.
[1]
The custom shape util and tool arrays are defined outside of any React component so they don't get
redefined on every render. See SpeechBubbleUtil.tsx and SpeechBubbleTool.tsx for the definitions.
[2]
We pass the shape util and tool into the Tldraw component's `shapeUtils` and `tools` props, plus the
UI overrides, components, and asset urls that add the tool to the toolbar with its own icon. See
ui-overrides.tsx for details.
*/
```
## customhandles.css
```css
/* Resize handles are normally on top, but we want the tail handle to win when they overlap */
.tl-user-handles {
z-index: 101;
}
/* The text label doesn't normally deal with text that goes sideways,
* so this accounts for that */
.tl-shape[data-shape-type='speech-bubble'] .tl-text-label {
justify-content: flex-start !important;
}
```
## SpeechBubbleTool.tsx
```tsx
import { BaseBoxShapeTool } from 'tldraw'
export class SpeechBubbleTool extends BaseBoxShapeTool {
static override id = 'speech-bubble'
override shapeType = 'speech-bubble' as const
}
/*
The speech bubble tool is a StateNode with the id "speech-bubble". Extending BaseBoxShapeTool gives
us click-to-create and drag-to-create of a `shapeType` shape for free. For a tool with more custom
behavior, see the screenshot tool example.
*/
```
## SpeechBubbleUtil.tsx
```tsx
import {
DefaultColorStyle,
DefaultFontStyle,
DefaultHorizontalAlignStyle,
DefaultSizeStyle,
DefaultVerticalAlignStyle,
Geometry2d,
PlainTextLabel,
Polygon2d,
RecordPropsType,
ShapeUtil,
T,
TLDefaultSizeStyle,
TLHandle,
TLHandleDragInfo,
TLResizeInfo,
TLShape,
Vec,
ZERO_INDEX_KEY,
getColorValue,
getFontFamily,
resizeBox,
structuredClone,
vecModelValidator,
} from 'tldraw'
import { getSpeechBubbleVertices, getTailIntersectionPoint } from './helpers'
const LABEL_FONT_SIZES: Record = {
s: 1.125,
m: 1.375,
l: 1.625,
xl: 2,
}
const TEXT_PROPS = {
fontWeight: 'normal',
fontVariant: 'normal',
fontStyle: 'normal',
padding: '0px',
}
const SPEECH_BUBBLE_TYPE = 'speech-bubble'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[SPEECH_BUBBLE_TYPE]: SpeechBubbleShapeProps
}
}
// Stroke width multipliers per size, applied to the theme's base stroke width
const STROKE_SIZES: Record = {
s: 1,
m: 1.75,
l: 2.5,
xl: 5,
}
// There's a guide at the bottom of this file!
export const speechBubbleShapeProps = {
w: T.number,
h: T.number,
size: DefaultSizeStyle,
color: DefaultColorStyle,
font: DefaultFontStyle,
align: DefaultHorizontalAlignStyle,
verticalAlign: DefaultVerticalAlignStyle,
growY: T.positiveNumber,
text: T.string,
tail: vecModelValidator,
}
export type SpeechBubbleShapeProps = RecordPropsType
// [2]
export type SpeechBubbleShape = TLShape
export class SpeechBubbleUtil extends ShapeUtil {
static override type = SPEECH_BUBBLE_TYPE
// [3]
static override props = speechBubbleShapeProps
override canEdit(shape: SpeechBubbleShape) {
return true
}
// [4]
getDefaultProps(): SpeechBubbleShapeProps {
return {
w: 200,
h: 130,
color: 'black',
size: 'm',
font: 'draw',
align: 'middle',
verticalAlign: 'start',
growY: 0,
text: '',
tail: { x: 0.5, y: 1.5 },
}
}
getHeight(shape: SpeechBubbleShape) {
return shape.props.h + shape.props.growY
}
getGeometry(shape: SpeechBubbleShape): Geometry2d {
const speechBubbleGeometry = getSpeechBubbleVertices(shape)
const body = new Polygon2d({
points: speechBubbleGeometry,
isFilled: true,
})
return body
}
// [5]
override getHandles(shape: SpeechBubbleShape): TLHandle[] {
const { tail, w } = shape.props
return [
{
id: 'tail',
type: 'vertex',
label: 'Move tail',
index: ZERO_INDEX_KEY,
// props.tail coordinates are normalized
// but here we need them in shape space
x: tail.x * w,
y: tail.y * this.getHeight(shape),
},
]
}
override onHandleDrag(shape: SpeechBubbleShape, { handle }: TLHandleDragInfo) {
return {
...shape,
props: {
tail: {
x: handle.x / shape.props.w,
y: handle.y / this.getHeight(shape),
},
},
}
}
override onBeforeCreate(next: SpeechBubbleShape) {
return this.getGrowY(next, next.props.growY)
}
// [6]
override onBeforeUpdate(prev: SpeechBubbleShape, shape: SpeechBubbleShape) {
const { w, tail } = shape.props
const fullHeight = this.getHeight(shape)
const { segmentsIntersection, insideShape } = getTailIntersectionPoint(shape)
const slantedLength = Math.hypot(w, fullHeight)
const MIN_DISTANCE = slantedLength / 5
const MAX_DISTANCE = slantedLength / 1.5
const tailInShapeSpace = new Vec(tail.x * w, tail.y * fullHeight)
const distanceToIntersection = tailInShapeSpace.dist(segmentsIntersection)
const center = new Vec(w / 2, fullHeight / 2)
const tailDirection = Vec.Sub(tailInShapeSpace, center).uni()
let newPoint = tailInShapeSpace
if (insideShape) {
newPoint = Vec.Add(segmentsIntersection, tailDirection.mul(MIN_DISTANCE))
} else {
if (distanceToIntersection <= MIN_DISTANCE) {
newPoint = Vec.Add(segmentsIntersection, tailDirection.mul(MIN_DISTANCE))
} else if (distanceToIntersection >= MAX_DISTANCE) {
newPoint = Vec.Add(segmentsIntersection, tailDirection.mul(MAX_DISTANCE))
}
}
const next = structuredClone(shape)
next.props.tail.x = newPoint.x / w
next.props.tail.y = newPoint.y / fullHeight
return this.getGrowY(next, prev.props.growY)
}
component(shape: SpeechBubbleShape) {
const {
id,
type,
props: { color, font, size, align, text },
} = shape
const vertices = getSpeechBubbleVertices(shape)
const pathData = 'M' + vertices[0] + 'L' + vertices.slice(1) + 'Z'
const isSelected = shape.id === this.editor.getOnlySelectedShapeId()
const theme = this.editor.getCurrentTheme()
const colors = theme.colors[this.editor.getColorMode()]
return (
<>
>
)
}
getIndicatorPath(shape: SpeechBubbleShape) {
const vertices = getSpeechBubbleVertices(shape)
const pathData = 'M' + vertices[0] + 'L' + vertices.slice(1) + 'Z'
return new Path2D(pathData)
}
override onResize(shape: SpeechBubbleShape, info: TLResizeInfo) {
return resizeBox(shape, info)
}
getGrowY(shape: SpeechBubbleShape, prevGrowY = 0) {
const PADDING = 17
const theme = this.editor.getCurrentTheme()
const nextTextSize = this.editor.textMeasure.measureText(shape.props.text, {
...TEXT_PROPS,
lineHeight: theme.lineHeight,
fontFamily: getFontFamily(theme, shape.props.font),
fontSize: theme.fontSize * LABEL_FONT_SIZES[shape.props.size],
maxWidth: shape.props.w - PADDING * 2,
})
const nextHeight = nextTextSize.h + PADDING * 2
let growY = 0
if (nextHeight > shape.props.h) {
growY = nextHeight - shape.props.h
} else {
if (prevGrowY) {
growY = 0
}
}
return {
...shape,
props: {
...shape.props,
growY,
},
}
}
}
/*
This file contains the speech bubble shape util. Most of the logic that makes the tail behave
lives in the onBeforeUpdate handler [6]: because the tail is driven by a handle, we constrain it
there so every way of changing the shape (dragging the handle, resizing, editing text) keeps the
tail in a sensible place.
[1]
Extend TLGlobalShapePropsMap to add our shape's props to the global type system. The tail is a
VecModel.
[2]
Define the shape type using TLShape with the shape's type as a type argument.
[3]
The shape's props with a validator for each key. Using tldraw's StyleProps (DefaultSizeStyle,
DefaultColorStyle, DefaultFontStyle, and the align styles) here is what makes those options show
up in the style panel for this shape; add 'dash' or 'fill' the same way if you want them.
[4]
Default props. The tail is stored as a fraction of the shape's width and height rather than in
pixels, so it scales correctly when the shape is drag-created or resized. The rest of the util
converts between the normalized tail and shape space as needed.
[5]
`getHandles` returns the handles to show when the shape is selected: just the tail here. Handle
positions are in shape space, so we scale the normalized tail up. `onHandleDrag` does the reverse
when the handle moves.
[6]
onBeforeUpdate runs on every change to the shape. We use it to keep the tail at a sensible
distance from the body: pushed outside if it was dragged inside, and clamped between a minimum
and maximum length. It also recomputes `growY` so the body grows to fit the text. See helpers.tsx
for the geometry.
*/
```
## helpers.tsx
```tsx
import { Vec, intersectLineSegmentLineSegment, invLerp, lerp, pointInPolygon } from 'tldraw'
import { SpeechBubbleShape } from './SpeechBubbleUtil'
export function getSpeechBubbleVertices(shape: SpeechBubbleShape): Vec[] {
const { w, tail } = shape.props
const fullHeight = shape.props.h + shape.props.growY
const tailInShapeSpace = new Vec(tail.x * w, tail.y * fullHeight)
const [tl, tr, br, bl] = [
new Vec(0, 0),
new Vec(w, 0),
new Vec(w, fullHeight),
new Vec(0, fullHeight),
]
const offsetH = w / 10
const offsetV = fullHeight / 10
const { adjustedIntersection, intersectionSegmentIndex } = getTailIntersectionPoint(shape)
let vertices: Vec[]
// Inject the tail segments into the geometry of the shape
switch (intersectionSegmentIndex) {
case 0:
// top
vertices = [
tl,
new Vec(adjustedIntersection.x - offsetH, adjustedIntersection.y),
new Vec(tailInShapeSpace.x, tailInShapeSpace.y),
new Vec(adjustedIntersection.x + offsetH, adjustedIntersection.y),
tr,
br,
bl,
]
break
case 1:
// right
vertices = [
tl,
tr,
new Vec(adjustedIntersection.x, adjustedIntersection.y - offsetV),
new Vec(tailInShapeSpace.x, tailInShapeSpace.y),
new Vec(adjustedIntersection.x, adjustedIntersection.y + offsetV),
br,
bl,
]
break
case 2:
// bottom
vertices = [
tl,
tr,
br,
new Vec(adjustedIntersection.x + offsetH, adjustedIntersection.y),
new Vec(tailInShapeSpace.x, tailInShapeSpace.y),
new Vec(adjustedIntersection.x - offsetH, adjustedIntersection.y),
bl,
]
break
case 3:
// left
vertices = [
tl,
tr,
br,
bl,
new Vec(adjustedIntersection.x, adjustedIntersection.y + offsetV),
new Vec(tailInShapeSpace.x, tailInShapeSpace.y),
new Vec(adjustedIntersection.x, adjustedIntersection.y - offsetV),
]
break
default:
throw Error("no intersection found, this shouldn't happen")
}
return vertices
}
export function getTailIntersectionPoint(shape: SpeechBubbleShape) {
const { w, tail } = shape.props
const fullHeight = shape.props.h + shape.props.growY
const tailInShapeSpace = new Vec(tail.x * w, tail.y * fullHeight)
const center = new Vec(w / 2, fullHeight / 2)
const corners = [new Vec(0, 0), new Vec(w, 0), new Vec(w, fullHeight), new Vec(0, fullHeight)]
const segments = [
[corners[0], corners[1]],
[corners[1], corners[2]],
[corners[2], corners[3]],
[corners[3], corners[0]],
]
let segmentsIntersection: Vec | null = null
let intersectionSegment: Vec[] | null = null
const insideShape = pointInPolygon(tailInShapeSpace, corners)
// We want to be sure we get an intersection, so if the point is
// inside the shape, push it away from the center by a big distance
const pointToCheck = insideShape
? Vec.Add(tailInShapeSpace, Vec.Sub(tailInShapeSpace, center).uni().mul(1000000))
: tailInShapeSpace
// Test each segment for an intersection
for (const segment of segments) {
segmentsIntersection = intersectLineSegmentLineSegment(
segment[0],
segment[1],
center,
pointToCheck
)
if (segmentsIntersection) {
intersectionSegment = segment
break
}
}
if (!(segmentsIntersection && intersectionSegment)) {
throw Error("no intersection found, this shouldn't happen")
}
const [start, end] = intersectionSegment
const intersectionSegmentIndex = segments.indexOf(intersectionSegment)
// a normalised vector from start to end, so this can work in any direction
const unit = Vec.Sub(end, start).uni()
// Where is the intersection relative to the start?
const totalDistance = Vec.Dist(start, end)
const distance = Vec.Dist(segmentsIntersection, start)
// make it stick to the middle
const middleRelative = mapRange(0, totalDistance, -1, 1, distance) // absolute -> -1 to 1
const squaredRelative = Math.abs(middleRelative) ** 2 * Math.sign(middleRelative) // square it and keep the sign
const squared = mapRange(-1, 1, 0, totalDistance, squaredRelative) // -1 to 1 -> absolute
const offset = (segments.indexOf(intersectionSegment) % 2 === 0 ? w / 10 : fullHeight / 10) * 3
const constrained = mapRange(0, totalDistance, offset, totalDistance - offset, distance)
// combine the two
const interpolated = lerp(constrained, squared, 0.5)
const adjustedIntersection = unit.mul(interpolated).add(start)
// We need the adjusted intersection to draw the tail, but the original intersection
// for the onBeforeUpdate handler
return {
segmentsIntersection,
adjustedIntersection,
intersectionSegmentIndex,
insideShape,
}
}
/**
* Maps a value from one range to another.
* e.g. mapRange(10, 20, 50, 100, 15) => 75
*/
function mapRange(a1: number, b1: number, a2: number, b2: number, s: number) {
return lerp(a2, b2, invLerp(a1, b1, s))
}
```
## ui-overrides.tsx
```tsx
import {
DefaultKeyboardShortcutsDialog,
DefaultKeyboardShortcutsDialogContent,
DefaultToolbar,
DefaultToolbarContent,
TLComponents,
TLUiAssetUrlOverrides,
TLUiOverrides,
TldrawUiMenuItem,
useIsToolSelected,
useTools,
} from 'tldraw'
// There's a guide at the bottom of this file!
// [1]
export const uiOverrides: TLUiOverrides = {
tools(editor, tools) {
tools.speech = {
id: 'speech-bubble',
icon: 'speech-bubble',
label: 'Speech bubble',
kbd: 's',
onSelect: () => {
editor.setCurrentTool('speech-bubble')
},
}
return tools
},
}
// [2]
export const customAssetUrls: TLUiAssetUrlOverrides = {
icons: {
'speech-bubble': '/speech-bubble.svg',
},
}
// [3]
export const components: TLComponents = {
Toolbar: (props) => {
const tools = useTools()
const isSpeechBubbleSelected = useIsToolSelected(tools['speech'])
return (
)
},
KeyboardShortcutsDialog: (props) => {
const tools = useTools()
return (
)
},
}
/*
This file adds the speech bubble tool to the toolbar and the keyboard shortcuts dialog.
[1]
The `tools` override registers the tool item with the UI: its icon, label, keyboard shortcut,
and what happens when it's selected.
[2]
The tool item uses a custom icon, so we provide its url through the Tldraw component's
`assetUrls` prop. The key must match the `icon` on the tool item.
[3]
We replace the toolbar and keyboard shortcuts dialog with versions that render our tool item
alongside the default content. Here it's added at the start; you can place it anywhere among
the default items instead.
*/
```
--------
# Custom tool with child states
Category: Shapes & tools
Keywords: custom tool, state machine, StateNode, child states, tool states, onPointerDown, onPointerMove, onEnter, transitions, pointing, dragging, idle
Split a custom tool into idle, pointing, and dragging child states to tell clicks from drags.
Tools are `StateNode`s in tldraw's state machine. Once a tool needs to distinguish a click from a drag, or a click on empty canvas from a click on a shape, giving it child states keeps each piece of behavior in the state that owns it: `Idle` decides what the user is doing, `Pointing` waits to see whether a drag starts, and `Dragging` updates the shape. `this.parent.transition()` moves between them and passes data to the next state's `onEnter`.
This builds on the [custom tool example](https://tldraw.dev/examples/custom-tool). Instructions for what to try are drawn on the canvas.
## App.tsx
```tsx
import {
StateNode,
TLClickEventInfo,
TLPointerEventInfo,
TLShape,
TLShapeId,
Tldraw,
createShapeId,
toRichText,
} from 'tldraw'
import 'tldraw/tldraw.css'
// There's a guide at the bottom of this file!
const OFFSET = -12
const EMOJIS = ['❤️', '🔥', '👍', '👎', '😭', '🤣']
// [1]
class StickerTool extends StateNode {
static override id = 'sticker'
static override initial = 'idle'
static override children() {
return [Idle, Pointing, Dragging]
}
}
// [2]
class Idle extends StateNode {
static override id = 'idle'
// [a]
override onEnter() {
this.editor.setCursor({ type: 'cross' })
}
// [b]
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
}
this.parent.transition('pointing', { shape: null })
break
}
case 'shape': {
if (editor.inputs.getShiftKey()) {
editor.updateShape({
id: info.shape.id,
type: 'text',
props: { richText: toRichText('👻 boo!') },
})
} else {
this.parent.transition('pointing', { shape: info.shape })
}
break
}
}
}
// [c]
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.createShape({
type: 'text',
x: currentPagePoint.x + OFFSET,
y: currentPagePoint.y + OFFSET,
props: { richText: toRichText('❤️') },
})
break
}
case 'shape': {
editor.deleteShapes([info.shape.id])
break
}
}
}
}
// [3]
class Pointing extends StateNode {
static override id = 'pointing'
private shape: TLShape | null = null
// [a]
override onEnter(info: { shape: TLShape | null }) {
this.shape = info.shape
}
// [b]
override onPointerUp() {
this.parent.transition('idle')
}
// [c]
override onPointerMove() {
if (this.editor.inputs.getIsDragging()) {
this.parent.transition('dragging', { shape: this.shape })
}
}
}
// [4]
class Dragging extends StateNode {
static override id = 'dragging'
private shapeId: TLShapeId | null = null
// [a]
override onEnter(info: { shape: TLShape | null }) {
if (info.shape) {
this.shapeId = info.shape.id
return
}
const currentPagePoint = this.editor.inputs.getCurrentPagePoint()
this.shapeId = createShapeId()
this.editor.createShape({
id: this.shapeId,
type: 'text',
x: currentPagePoint.x + OFFSET,
y: currentPagePoint.y + OFFSET,
props: { richText: toRichText('❤️') },
})
}
// [b]
override onPointerUp() {
this.parent.transition('idle')
}
// [c]
override onPointerMove() {
if (!this.shapeId) return
const originPagePoint = this.editor.inputs.getOriginPagePoint()
const currentPagePoint = this.editor.inputs.getCurrentPagePoint()
const distance = originPagePoint.dist(currentPagePoint)
this.editor.updateShape({
id: this.shapeId,
type: 'text',
props: {
richText: toRichText(EMOJIS[Math.floor(distance / 20) % EMOJIS.length]),
},
})
}
}
// [5]
const customTools = [StickerTool]
export default function ToolWithChildStatesExample() {
return (
{
editor.createShape({
type: 'text',
x: 50,
y: 50,
props: {
richText: toRichText(
'-Double click the canvas to add a sticker\n-Double click a sticker to delete it\n-Click and drag on a sticker to change it\n-Click and drag on the canvas to create a sticker\n-Shift click a sticker for a surprise!'
),
size: 's',
textAlign: 'start',
},
})
}}
/>
)
}
/*
Tools are nodes in tldraw's state machine and handle user input. A tool with a single state
quickly turns into a tangle of flags once it has to tell clicks apart from drags. Child states
solve that: each state handles the events that matter to it and transitions to the next. This
example expands on the sticker tool from the custom tool example.
[1]
The tool declares its child states with `children()` and which one to start in with
`initial`. Events are delivered to the current child state, not to the tool itself.
[2]
Idle is the initial state. Its job is to work out what the user is trying to do and hand off
to the right state. `this.parent.transition(id, info)` switches states; `info` is passed to
the new state's `onEnter`.
[a] Set the cursor on entering. Every child state receives `onEnter`.
[b] Because this tool has no shape-level hit testing of its own, the pointer event's
target is always 'canvas'. We use `editor.getShapeAtPoint` to check for a shape under
the pointer and re-dispatch the event with `target: 'shape'` so one switch handles both
cases. Shift-clicking a shape updates it in place; otherwise we go to Pointing.
[c] Double clicks arrive with a `phase`; we only act on 'up' so the action runs once.
Double-clicking empty canvas creates a sticker; double-clicking a sticker deletes it.
[3]
Pointing is a transitional state between pointer down and either pointer up (a click) or a
drag.
[a] Remember which shape (if any) was under the pointer.
[b] Pointer up without dragging means it was a click; go back to Idle.
[c] `editor.inputs.getIsDragging()` becomes true once the pointer has moved past the drag
threshold, so we don't start dragging on a tiny wobble.
[4]
Dragging updates the sticker while the pointer moves.
[a] If we're dragging an existing sticker, keep its id. Otherwise create a new one at the
pointer. We store the id rather than the shape record so we always read fresh data.
[b] Pointer up ends the drag; back to Idle.
[c] Cycle through the emojis based on how far the pointer has moved from where the drag
started (`getOriginPagePoint`).
[5]
Pass the tool to `Tldraw` and start in it with `initialState`. For this demo we hide the UI
and put some instructions on the canvas.
*/
```
--------
# Editable custom shape
Category: Shapes & tools
Keywords: editing, canedit, double click, interactive, emoji picker, shape state, editing state
A custom shape that becomes interactive when you double-click it.
The editor has at most one editing shape at a time. While a shape is being edited it can't be dragged, resized, or rotated, and pointer events reach its content. Only shapes whose util returns true from `canEdit` can enter this state; the user gets there by double-clicking the shape or selecting it and pressing Enter, and leaves it with Escape or by clicking the canvas.
The default shapes mostly use editing for text, but it's a general mechanism. This example's shape shows an emoji, and while editing it shows a button that cycles to the next emoji with `editor.updateShape`. The component reads `editor.getEditingShapeId()` to decide what to render, turns on `pointerEvents` only while editing, and marks pointer-down events as handled so clicking the button doesn't start a drag. `onEditEnd` spins the shape when editing finishes.
Try double-clicking the shape, clicking Next a few times, then pressing Escape. The relevant code is in `EditableShapeUtil.tsx`; for a walkthrough of the shape util basics, see the custom shape example.
## App.tsx
```tsx
import { Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { EditableShapeUtil } from './EditableShapeUtil'
const customShapeUtils = [EditableShapeUtil]
export default function EditableShapeExample() {
return (
)
}
/*
Introduction:
In tldraw, shapes can exist in an editing state. When shapes are in the editing state
they are focused and can't be dragged, resized or rotated. Shapes enter this state
when they are double-clicked. In our default shapes we mostly use this for editing text.
In this example we'll create a shape that renders an emoji and allows the user to change
the emoji when the shape is in the editing state.
Most of the relevant code for this is in the EditableShapeUtil.tsx file. If you want a more
in-depth explanation of the shape util, check out the custom shape example.
*/
```
## EditableShapeUtil.tsx
```tsx
import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLShape } from 'tldraw'
// There's a guide at the bottom of this file!
const MY_EDITABLE_SHAPE_TYPE = 'my-editable-shape'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_EDITABLE_SHAPE_TYPE]: {
w: number
h: number
animal: number
}
}
}
const ANIMAL_EMOJIS = ['🐶', '🐱', '🐨', '🐮', '🐴']
export type IMyEditableShape = TLShape
export class EditableShapeUtil extends BaseBoxShapeUtil {
static override type = MY_EDITABLE_SHAPE_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
animal: T.number,
}
// [1]
override canEdit(shape: IMyEditableShape) {
return true
}
// [1b]
override canEditWhileLocked(shape: IMyEditableShape) {
return true
}
getDefaultProps(): IMyEditableShape['props'] {
return {
w: 200,
h: 200,
animal: 0,
}
}
// [2]
component(shape: IMyEditableShape) {
// [a]
const isEditing = this.editor.getEditingShapeId() === shape.id
return (
{ANIMAL_EMOJIS[shape.props.animal]}
{/* [c] */}
{isEditing ? (
) : (
// [d] when not editing...
Double click to edit
)}
)
}
getIndicatorPath(shape: IMyEditableShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
// [3]
override onEditEnd(shape: IMyEditableShape) {
this.editor.animateShape(
{ ...shape, rotation: shape.rotation + Math.PI * 2 },
{ animation: { duration: 250 } }
)
}
}
/*
This is our shape util, which defines how our shape renders and behaves. For
more information on the shape util, check out the custom shape example.
[1]
We override the canEdit method to allow the shape to enter the editing state.
[1b] canEditWhileLocked allows the shape to be edited even when it is locked.
This is useful for shapes that should stay put but remain interactive.
[2]
The component renders differently depending on whether the shape is being edited.
[a] Reading `getEditingShapeId()` inside the component is reactive, so the
shape re-renders when it enters or leaves the editing state.
[b] While editing, we turn on pointer events and mark pointer-down events as
handled with `editor.markEventAsHandled` so the editor doesn't start a
drag or selection when the user clicks the button. Check out the
interactive shape example for more on this.
[c] The button cycles through the emojis with `editor.updateShape`.
[d] When not editing, we show a hint instead of the button.
[3]
The onEditEnd method is called when the shape exits the editing state. In this
case we spin the shape 360 degrees with `animateShape`.
*/
```
--------
# Flex layout shape
Category: Shapes & tools
Keywords: custom shape, flexbox, layout, frame, children, BaseFrameLikeShapeUtil
A frame-like shape that lets the browser's flexbox engine arrange its children.
The layout shape extends `BaseFrameLikeShapeUtil`, so it clips its children and reparents shapes in and out as they're dragged over it, like a frame. What's different is how children get positioned: the shape renders a hidden flex container with a placeholder div per child, and a `ResizeObserver` reads each placeholder's offset and writes it back to the child's `x`/`y`. A contextual toolbar exposes the flex direction, `justify-content`, and `align-items` for the selected layout.
The layout grows to fit its children. Dragging a shape over it shows an insertion line and, on drop, `onDropShapesOver` sets the child order from the pointer position. Dragging a child out to empty page space returns it to the page and shrinks the layout.
Try dragging the loose blue shape into the layout, reordering children by dragging, and switching direction and alignment in the toolbar. For a container that computes layouts itself instead, see the [frame layout modes](https://tldraw.dev/examples/frame-layouts) example.
## App.tsx
```tsx
import { memo, useLayoutEffect, useRef } from 'react'
import {
BaseFrameLikeShapeUtil,
Box,
Editor,
Geometry2d,
Group2d,
HTMLContainer,
RecordProps,
Rectangle2d,
T,
TLDragShapesOutInfo,
TLShape,
TLShapeId,
TLShapePartial,
TLComponents,
Tldraw,
TldrawUiButtonIcon,
TldrawUiContextualToolbar,
TldrawUiToolbarButton,
canonicalizeRotation,
clamp,
createShapeId,
getIndicesBetween,
last,
resizeBox,
toDomPrecision,
track,
useEditor,
useValue,
type TLResizeInfo,
} from 'tldraw'
import {
FLEX_CONTAINER_DEFAULT_LABEL,
FLEX_CONTAINER_GAP,
FLEX_CONTAINER_PADDING,
getChildPositions,
getDesiredSize,
getDropInLineStyle,
getDropOutLineStyle,
getFlexContainerStyles,
getMinimumContentSize,
type FlexContainerLayoutProps,
type FrameLabelBoxShape,
} from './FlexContainerHelpers'
import 'tldraw/tldraw.css'
import './flex-layout.css'
// There's a guide at the bottom of this file!
const FLEX_LAYOUT_SHAPE_TYPE = 'flex-layout'
const FLEX_LAYOUT_ID = createShapeId('flex-layout-example')
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[FLEX_LAYOUT_SHAPE_TYPE]: FlexContainerLayoutProps & {
w: number
h: number
}
}
}
// [2]
type FlexLayoutShape = TLShape
// [3]
const FRAME_HEADING_EXTRA_WIDTH = 12
const FRAME_HEADING_MIN_WIDTH = 32
const FRAME_HEADING_NOCOLORS_OFFSET_X = -7
const FRAME_HEADING_OFFSET_Y = 4
function getContainerHeadingSide(editor: Editor, shape: FrameLabelBoxShape): 0 | 1 | 2 | 3 {
const pageRotation = canonicalizeRotation(editor.getShapePageTransform(shape.id)!.rotation())
const offsetRotation = pageRotation + Math.PI / 4
const scaledRotation = (offsetRotation * (2 / Math.PI) + 4) % 4
return Math.floor(scaledRotation) as 0 | 1 | 2 | 3
}
function getContainerHeadingOpts(width: number) {
return {
fontSize: 12,
fontFamily: 'Inter, sans-serif',
textAlign: 'start' as const,
width,
height: 24,
padding: 0,
lineHeight: 1,
fontStyle: 'normal',
fontWeight: 'normal',
overflow: 'truncate-ellipsis' as const,
verticalTextAlign: 'middle' as const,
offsetY: -(32 + 2),
offsetX: 0,
}
}
function getContainerHeadingSize(
editor: Editor,
shape: FrameLabelBoxShape,
opts: ReturnType,
label: string
) {
const spans = editor.textMeasure.measureTextSpans(label, opts)
const firstSpan = spans[0]
const lastSpan = last(spans)!
const width = lastSpan.box.w + lastSpan.box.x - firstSpan.box.x
return new Box(0, -opts.height, width, opts.height)
}
function getContainerHeadingTranslation(shape: FrameLabelBoxShape, side: 0 | 1 | 2 | 3) {
const u = 'px'
const r = 'deg'
switch (side) {
case 0:
return ''
case 3:
return `translate(${toDomPrecision(shape.props.w)}${u}, 0${u}) rotate(90${r})`
case 2:
return `translate(${toDomPrecision(shape.props.w)}${u}, ${toDomPrecision(shape.props.h)}${u}) rotate(180${r})`
case 1:
return `translate(0${u}, ${toDomPrecision(shape.props.h)}${u}) rotate(270${r})`
default:
throw Error('labelSide out of bounds')
}
}
function getFlexContainerLabelGeometry(
editor: Editor,
shape: FrameLabelBoxShape,
label = FLEX_CONTAINER_DEFAULT_LABEL
) {
const z = editor.getEfficientZoomLevel()
const labelSide = getContainerHeadingSide(editor, shape)
const isVertical = labelSide % 2 === 1
const rotatedTopEdgeWidth = isVertical ? shape.props.h : shape.props.w
const opts = getContainerHeadingOpts(rotatedTopEdgeWidth)
const headingSize = getContainerHeadingSize(editor, shape, opts, label)
const extraWidth = FRAME_HEADING_EXTRA_WIDTH / z
const minWidth = FRAME_HEADING_MIN_WIDTH / z
const maxWidth = rotatedTopEdgeWidth + extraWidth
const labelWidth = headingSize.w / z
const labelHeight = headingSize.h / z
const clampedLabelWidth = clamp(labelWidth + extraWidth, minWidth, maxWidth)
const offsetX = FRAME_HEADING_NOCOLORS_OFFSET_X / z
const offsetY = FRAME_HEADING_OFFSET_Y / z
const width = isVertical ? labelHeight : clampedLabelWidth
const height = isVertical ? clampedLabelWidth : labelHeight
let x: number
let y: number
switch (labelSide) {
case 0:
x = offsetX
y = -(labelHeight + offsetY)
break
case 1:
x = -(labelHeight + offsetY)
y = shape.props.h - (offsetX + clampedLabelWidth)
break
case 2:
x = shape.props.w - (offsetX + clampedLabelWidth)
y = shape.props.h + offsetY
break
case 3:
x = shape.props.w + offsetY
y = offsetX
break
}
return new Rectangle2d({
x,
y,
width,
height,
isFilled: true,
isLabel: true,
excludeFromShapeBounds: true,
})
}
const FlexContainerHeading = memo(function FlexContainerHeading({
shape,
label = FLEX_CONTAINER_DEFAULT_LABEL,
}: {
shape: FrameLabelBoxShape
label?: string
}) {
const editor = useEditor()
const { side, translation } = useValue(
'flex container heading',
() => {
const labelSide = getContainerHeadingSide(editor, shape)
return {
side: labelSide,
translation: getContainerHeadingTranslation(shape, labelSide),
}
},
[editor, shape]
)
return (
)
}
/*
Each pair below creates a geo shape and an arrow, then binds the arrow's end terminal to the
shape with `editor.createBindings`. The arrow's `end` prop is only a fallback position; once
the binding exists, the arrow's endpoint is computed from the binding props.
[1]
`isPrecise: false`. The `normalizedAnchor` of (0.25, 0.5) is ignored and the arrow aims at
the shape's center, stopping at the edge. This is what you get when a user drags an arrow
onto a shape without pausing to pick a specific point.
[2]
`isPrecise: true` with the same anchor. Now the arrow aims at the anchor position (a quarter
of the way across, vertically centered), still stopping at the shape's edge because
`isExact` is false.
[3]
`isExact: true`. Instead of stopping at the edge, the arrow continues into the shape until it
reaches the anchor point itself, here the exact center.
[4]
Both flags together with an off-center anchor at (0.75, 0.75): the arrow enters the shape and
ends at that exact point.
*/
```
--------
# Custom geo types
Category: Shapes & tools
Keywords: geo, custom, shape, extend, configure, geometry, path, pathbuilder
Add new geo types (a rounded rectangle and a cross) to the built-in geo shape with `GeoShapeUtil.configure()`.
Instead of writing a whole new shape util, pass a `customGeoTypes` map to `GeoShapeUtil.configure()`. Each entry supplies a `getPath` function that returns a `PathBuilder` outline for a given width and height, plus a snap type, an icon, and an optional default size. The configured util replaces the default one in `shapeUtils`; the new types inherit labels, fill and dash styles, resizing, snapping, and SVG export, and they show up in the style panel's geo picker.
The example also registers icons for the new types through `assetUrls`, adds tool labels through the `translations` override, and puts the two new tools at the front of the toolbar with `ToolbarItem`.
Try selecting a shape and switching its geo type in the style panel, or use the new toolbar tools to draw more.
## App.tsx
```tsx
import {
DefaultToolbar,
DefaultToolbarContent,
GeoShapeUtil,
PathBuilder,
TLComponents,
TLUiAssetUrlOverrides,
TLUiOverrides,
Tldraw,
ToolbarItem,
toRichText,
} from 'tldraw'
import 'tldraw/tldraw.css'
// [1]
const CustomGeoShapeUtil = GeoShapeUtil.configure({
customGeoTypes: {
'rounded-rect': {
getPath(w, h, shape) {
// [a]
const isFilled = shape.props.fill !== 'none'
const r = Math.min(w, h) * 0.2
return new PathBuilder()
.moveTo(r, 0, { geometry: { isFilled } })
.lineTo(w - r, 0)
.circularArcTo(r, false, true, w, r)
.lineTo(w, h - r)
.circularArcTo(r, false, true, w - r, h)
.lineTo(r, h)
.circularArcTo(r, false, true, 0, h - r)
.lineTo(0, r)
.circularArcTo(r, false, true, r, 0)
.close()
},
snapType: 'polygon',
icon: 'geo-rounded-rect',
},
cross: {
getPath(w, h, shape) {
const isFilled = shape.props.fill !== 'none'
const armW = w / 3
const armH = h / 3
return new PathBuilder()
.moveTo(armW, 0, { geometry: { isFilled } })
.lineTo(w - armW, 0)
.lineTo(w - armW, armH)
.lineTo(w, armH)
.lineTo(w, h - armH)
.lineTo(w - armW, h - armH)
.lineTo(w - armW, h)
.lineTo(armW, h)
.lineTo(armW, h - armH)
.lineTo(0, h - armH)
.lineTo(0, armH)
.lineTo(armW, armH)
.close()
},
snapType: 'polygon',
icon: 'geo-cross',
defaultSize: { w: 200, h: 200 },
},
},
})
// [2]
const shapeUtils = [CustomGeoShapeUtil]
// [3]
const customAssetUrls: TLUiAssetUrlOverrides = {
icons: {
'geo-rounded-rect': '/geo-rounded-rect.svg',
'geo-cross': '/geo-cross.svg',
},
}
// [4]
const uiOverrides: TLUiOverrides = {
translations: {
en: {
'tool.rounded-rect': 'Rounded rectangle',
'tool.cross': 'Cross',
},
},
}
// [5]
const components: TLComponents = {
Toolbar: (props) => {
return (
)
},
}
export default function CustomGeoTypesExample() {
return (
)
}
/*
[1]
`GeoShapeUtil.configure()` takes a `customGeoTypes` map. Each entry becomes a new value for the
geo style and gets the same treatment as the built-in types: labels, fill/dash/color styles,
resizing, SVG export, snapping, and a slot in the style panel's geo picker.
- getPath: returns a PathBuilder describing the outline, given the current width and height
- snapType: 'polygon' (other handles snap to vertices + center) or 'blobby' (center only)
- icon: icon name for the style panel's geo picker (the toolbar uses 'geo-' + the type name)
- defaultSize: optional creation size when clicking (not dragging); defaults to 200x200
[a] `isFilled` on the first path segment tells the geometry whether the interior counts as
part of the shape for hit-testing. Without it, a solid-filled shape could only be clicked
on its outline.
[2]
Pass the configured util in place of the default. It's still `type: 'geo'`, so existing geo
shapes keep working, and it must be defined outside the component so the array is stable.
[3]
Icons need URLs. Register them under `assetUrls.icons`; the key must be 'geo-' followed by
the geo type name so the toolbar finds it, and using the same name for `icon` in [1] keeps
the style panel picker in sync.
[4]
Each custom geo type is registered as a tool automatically. Give it a label by translating
'tool.' followed by the geo type name.
[5]
Add the new tools to the toolbar with `ToolbarItem`, referencing them by geo type name.
[6]
The `geo` prop is typed as the built-in enum, so setting a custom value programmatically needs
a cast. Shapes created through the toolbar or the style panel don't have this problem.
*/
```
--------
# Custom shape geometry
Category: Shapes & tools
Keywords: custom geometry, getgeometry, polygon2d, rectangle2d, group2d, svg path, vertices, hit testing, shapeutil
Give a custom shape non-rectangular geometry with `Polygon2d`, `Rectangle2d`, and `Group2d`.
A shape's `getGeometry` method returns the geometry the editor uses for hit testing, selection bounds, snapping, and arrow bindings. This example draws a house with a door and builds matching geometry from a `Polygon2d` for the body and a `Rectangle2d` for the door, combined in a `Group2d`.
Try clicking just beside the roof: the pointer misses the shape because the geometry is a polygon, not the bounding box. Try binding an arrow to the shape to see it snap to the polygon's edges.
## App.tsx
```tsx
import {
Group2d,
Polygon2d,
RecordPropsType,
Rectangle2d,
ShapeUtil,
T,
TLResizeInfo,
TLShape,
Tldraw,
Vec,
resizeBox,
} from 'tldraw'
import 'tldraw/tldraw.css'
const HOUSE_TYPE = 'house'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[HOUSE_TYPE]: HouseShapeProps
}
}
const houseShapeProps = {
w: T.number,
h: T.number,
}
type HouseShapeProps = RecordPropsType
type HouseShape = TLShape
class HouseShapeUtil extends ShapeUtil {
static override type = HOUSE_TYPE
static override props = houseShapeProps
override getDefaultProps() {
return {
w: 100,
h: 100,
}
}
//[1]
override getGeometry(shape: HouseShape) {
const { house: houseGeometry } = getHouseVertices(shape)
const house = new Polygon2d({
points: houseGeometry,
isFilled: true,
})
const door = new Rectangle2d({
x: shape.props.w / 2 - shape.props.w / 10,
y: shape.props.h - shape.props.h / 4,
width: shape.props.w / 5,
height: shape.props.h / 4,
isFilled: true,
})
const geometry = new Group2d({
children: [house, door],
})
return geometry
}
// [2]
override component(shape: HouseShape) {
const { house: houseVertices, door: doorVertices } = getHouseVertices(shape)
const housePathData = 'M' + houseVertices[0] + 'L' + houseVertices.slice(1) + 'Z'
const doorPathData = 'M' + doorVertices[0] + 'L' + doorVertices.slice(1) + 'Z'
return (
)
}
// [3]
override getIndicatorPath(shape: HouseShape) {
const { house: houseVertices, door: doorVertices } = getHouseVertices(shape)
const housePathData = 'M' + houseVertices[0] + 'L' + houseVertices.slice(1) + 'Z'
const doorPathData = 'M' + doorVertices[0] + 'L' + doorVertices.slice(1) + 'Z'
return new Path2D(housePathData + doorPathData)
}
override onResize(shape: HouseShape, info: TLResizeInfo) {
return resizeBox(shape, info)
}
}
// [4]
function getHouseVertices(shape: HouseShape): { house: Vec[]; door: Vec[] } {
const { w, h } = shape.props
const halfW = w / 2
const roofStart = h / 2.5
const house = [
new Vec(0, roofStart), // Roof start (left)
new Vec(w, roofStart), // Roof start (right)
new Vec(w, h), // Bottom-right corner
new Vec(0, h), // Bottom-left corner
new Vec(0, roofStart), // Roof start (left)
new Vec(halfW, 0), // Roof peak
new Vec(w, roofStart), // Roof start (right)
]
const door = [
new Vec(halfW - w / 10, h), // Bottom-left corner
new Vec(halfW + w / 10, h), // Bottom-right corner
new Vec(halfW + w / 10, h - h / 4), // Top-right corner
new Vec(halfW - w / 10, h - h / 4), // Top-left corner
new Vec(halfW - w / 10, h), // Bottom-left corner
]
return { house, door }
}
const shapeUtils = [HouseShapeUtil]
export default function ShapeWithGeometryExample() {
return (
)
}
/*
This file shows a shape with custom (non-rectangular) geometry: a house with a door.
[1]
getGeometry returns the geometry the editor uses for hit testing, selection bounds,
snapping, and arrow binding. It does not have to match a rectangle: here the house body
is a Polygon2d and the door is a Rectangle2d, combined into a Group2d. Because the
geometry is a polygon rather than the bounding box, clicking in the empty corners
either side of the roof does not select the shape.
[2]
The component draws the same vertices as an SVG path. Vec's toString() gives "x, y", so
joining the vertices produces valid path data. The tl-svg-container class sizes the svg
to the shape and turns off pointer events on it.
[3]
getIndicatorPath returns a Path2D for the same outline; tldraw strokes it onto the canvas
overlay as the blue selection outline.
[4]
Both the geometry and the rendering derive from getHouseVertices, so hit testing always
matches what the user sees. Keep them in sync when you change how a shape looks.
*/
```
--------
# Custom shape migrations
Category: Shapes & tools
Keywords: migrations, schema versioning, createshapepropsmigrationids, createshapepropsmigrationsequence, up, down, backwards compatibility, data migration
Migrate a custom shape's props between versions with a migration sequence.
When you change a custom shape's props, documents saved with the old version still contain the old shape data. Migrations let the editor upgrade (or downgrade) that data as it loads, so old documents keep working. This example loads a snapshot containing a shape saved before it had a `color` prop; the shape util's `migrations` (built with `createShapePropsMigrationIds` and `createShapePropsMigrationSequence`) add the missing prop when the snapshot loads.
Read the guide at the bottom of the example file for how the editor decides which migrations to run.
## App.tsx
```tsx
import {
BaseBoxShapeUtil,
HTMLContainer,
T,
TLResizeInfo,
TLShape,
TLStoreSnapshot,
Tldraw,
createShapePropsMigrationIds,
createShapePropsMigrationSequence,
resizeBox,
} from 'tldraw'
import 'tldraw/tldraw.css'
import snapshot from './snapshot.json'
const MY_SHAPE_WITH_MIGRATIONS_TYPE = 'myshapewithmigrations' as const
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_SHAPE_WITH_MIGRATIONS_TYPE]: { w: number; h: number; color: string }
}
}
// There's a guide at the bottom of this file!
export type IMyShape = TLShape
// [1]
const versions = createShapePropsMigrationIds(
// this must match the shape type in the shape definition
MY_SHAPE_WITH_MIGRATIONS_TYPE,
{
AddColor: 1,
}
)
// [2]
export const myShapeMigrations = createShapePropsMigrationSequence({
sequence: [
{
id: versions.AddColor,
up(props) {
// props is a mutable copy, so it's safe to change it in place
props.color = 'lightblue'
},
down(props) {
delete props.color
},
},
],
})
export class MigratedShapeUtil extends BaseBoxShapeUtil {
static override type = MY_SHAPE_WITH_MIGRATIONS_TYPE
static override props = {
w: T.number,
h: T.number,
color: T.string,
}
// [3]
static override migrations = myShapeMigrations
getDefaultProps(): IMyShape['props'] {
return {
w: 300,
h: 300,
color: 'lightblue',
}
}
component(shape: IMyShape) {
return (
)
}
getIndicatorPath(shape: IMyShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
override onResize(shape: IMyShape, info: TLResizeInfo) {
return resizeBox(shape, info)
}
}
const customShapeUtils = [MigratedShapeUtil]
export default function ShapeWithMigrationsExample() {
return (
)
}
/*
Introduction:
Sometimes you'll want to update the way a shape works in your application without breaking older
versions of the shape that a user may have stored or persisted in memory.
This example shows how you can use our migrations system to upgrade (or downgrade) user's data
between different versions. Most of the code above is general "custom shape" code—see our custom
shape example for more details.
[1] First, we need IDs for each migration. List each change with its version number. Once you've
shipped a migration, it should not change again; add a new one instead.
[2] Next, we create a migration sequence. This is where we actually write our migration logic. Each
migration has three parts: an `id` (created in [1]), an `up` migration and a `down` migration. In
this case, the `up` migration adds the `color` prop to the shape, and the `down` migration removes
it.
In some cases (mainly in multiplayer sessions) a peer or server may need to take a later version of
a shape and migrate it down to an older version—in this case, it would run the down migrations in
order to get it to the needed version.
[3] Finally, we add our migrations to the ShapeUtil's static `migrations` property. This tells
tldraw about the migrations so they can be used with your shapes.
[4] To show the migration running, we load a snapshot that was saved before the `color` prop
existed. The migration runs as the snapshot loads, so the shape appears light blue.
How it works:
Each time the editor creates a snapshot (`editor.getSnapshot()`), it serializes all
of the records (the snapshot's `store`) as well as versions of each record that it contains (the
snapshot's `schema`). When the editor loads a snapshot, it compares its current schema with the
snapshot's schema to determine which migrations to apply to each record.
In this example, we have a snapshot (snapshot.json) that we created in version 0, however our shape
now has a 'color' prop that was added in version 1.
The snapshot looks something like this:
```json
{
"store": {
"shape:BqG5uIAa9ig2-ukfnxwBX": {
...,
"props": {
"w": 300,
"h": 300
}
}
},
"schema": {
...,
"recordVersions": {
"shape": {
"subTypeVersions": {
...,
"myshapewithmigrations": 0
}
}
}
}
}
```
The shape in the snapshot doesn't have a 'color' prop, and the schema's version for this shape is
0.
When the editor loads the snapshot, it will compare the serialized schema's version with its current
schema's version for the shape, which is 1 as defined in our shape's migrations. Since the
serialized version is older than its current version, it will use our migration to bring it up to
date: it will run the migration's `up` function, which will add the 'color' prop to the shape.
*/
```
--------
# Custom shape SVG export
Category: Shapes & tools
Keywords: svg export, toSvg, toBackgroundSvg, custom shape export, SvgExportContext, export image, copy as svg, foreignObject, shapeutil
Control how a custom shape looks when exported or copied as SVG or PNG with `toSvg`.
The "export as SVG/PNG" and "copy as SVG/PNG" actions call a shape util's `toSvg` (and optional `toBackgroundSvg`) methods. If a shape defines neither, its component is placed inside a `` in the exported SVG, which works but is less portable than a real SVG representation.
This shape's `toSvg` returns a `rect` matching its HTML component and reads `ctx.isDarkMode` from the `SvgExportContext` so the export uses the right fill for the requested mode. Select the shape and choose "Copy as SVG" or "Export as PNG" from the context menu to see it.
## App.tsx
```tsx
import {
Geometry2d,
HTMLContainer,
RecordProps,
Rectangle2d,
ShapeUtil,
SvgExportContext,
T,
Tldraw,
TLShape,
} from 'tldraw'
import 'tldraw/tldraw.css'
const MY_CUSTOM_SHAPE_TO_SVG_TYPE = 'my-custom-shape-to-svg'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[MY_CUSTOM_SHAPE_TO_SVG_TYPE]: { w: number; h: number }
}
}
// There's a guide at the bottom of this file!
type ICustomShape = TLShape
const LIGHT_FILL = '#ff8888'
const DARK_FILL = '#ffcccc'
export class MyShapeUtil extends ShapeUtil {
static override type = MY_CUSTOM_SHAPE_TO_SVG_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
}
getDefaultProps(): ICustomShape['props'] {
return {
w: 200,
h: 200,
}
}
override canResize(shape: ICustomShape) {
return false
}
getGeometry(shape: ICustomShape): Geometry2d {
return new Rectangle2d({
width: shape.props.w,
height: shape.props.h,
isFilled: true,
})
}
component(_shape: ICustomShape) {
const isDarkMode = this.editor.user.getIsDarkMode()
return
}
getIndicatorPath(shape: ICustomShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
// [1]
override toSvg(shape: ICustomShape, ctx: SvgExportContext) {
const fill = ctx.isDarkMode ? DARK_FILL : LIGHT_FILL
return
}
}
const customShape = [MyShapeUtil]
export default function CustomShapeToSvgExample() {
return (
)
}
/*
The "export as SVG/PNG" and "copy as SVG/PNG" actions call a shape util's `toSvg` (and
`toBackgroundSvg`) methods. If a shape defines neither, its component is rendered inside a
`` in the exported SVG instead. That works, but foreignObject content depends
on the viewer's browser and fonts, so a real SVG representation exports more reliably.
For more information on creating a custom shape, check out the custom shape example.
[1]
`toSvg` returns a React element to place in the export in the shape's own coordinate space
(the editor wraps it in a `` with the shape's page transform and opacity). Here a `rect`
matches the HTML component. Read `ctx.isDarkMode` rather than the editor's user preference,
because exports can be requested in either mode regardless of the current UI.
If your shape needs shared resources such as fonts, patterns, or filters, add them once to
the export's `` with `ctx.addExportDef({ key, getElement })`; defs with the same key
are only added once. Fonts used via `getFontFaces` are embedded automatically. A shape can
also define `toBackgroundSvg` for a layer that exports behind every shape's foreground layer,
as the highlighter shape does.
*/
```
--------
# Custom snapping
Category: Shapes & tools
Keywords: snapping, snap mode, bounds snapping, custom snapping, getboundssnapgeometry, geometry, custom shape, playing cards
Give a custom shape its own snap points with `getBoundsSnapGeometry`.
When shapes are moved in snap mode, they snap to the bounding boxes of nearby shapes by default. A shape util can override `getBoundsSnapGeometry` to return different points, which are used both when this shape is dragged and when other shapes snap against it.
The playing card shape here returns the corners and center of the small square around its top-left suit icon. Cards therefore snap together so that each icon stays visible when they're fanned out, like a hand of cards.
Try dragging one card over another; snap mode is turned on for you in `onMount`, and you can hold cmd/ctrl while dragging to snap when it's off. Use the joker tool in the toolbar (or press `c`) to add more cards.
## App.tsx
```tsx
import { Editor, TLStoreSnapshot, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import { PlayingCardTool } from './PlayingCardShape/playing-card-tool'
import { PlayingCardUtil } from './PlayingCardShape/playing-card-util'
import snapshot from './snapshot.json'
import { components, uiOverrides } from './ui-overrides'
// There's a guide at the bottom of this file!
// [1]
const customShapes = [PlayingCardUtil]
const customTools = [PlayingCardTool]
export default function BoundsSnappingShapeExample() {
// [2]
const handleMount = (editor: Editor) => {
editor.user.updateUserPreferences({ isSnapMode: true })
}
// [3]
return (
)
}
/*
Introduction:
This example shows how to create a shape with custom snapping geometry. When shapes are moved around
in snap mode, they snap to the bounds of other shapes by default. A shape can return custom snapping
geometry to snap to instead. This example creates a playing card shape. The cards are designed to
snap together so that the top-left icon remains visible when stacked, like a hand of cards in a game.
The most relevant code for this customisation is in playing-card-util.tsx.
[1]
We define the custom shape and tool arrays outside of the component so that they don't change on
every render, which would cause the editor to re-register them.
[2]
Snap mode is off by default; the user can still snap by holding cmd/ctrl while dragging. We turn it
on in the user preferences on mount so the custom snapping is obvious right away.
[3]
This is where we pass all our customisations to the Tldraw component.
[a] Our custom shape (playing-card-util.tsx) and tool (playing-card-tool.tsx).
[b] The UI overrides and components (ui-overrides.tsx) that add the tool to the toolbar and
the keyboard shortcuts dialog.
[c] Our handleMount function.
[d] A snapshot so that the editor starts with two cards in it. This isn't necessary, it just
makes the example clearer at first glance.
*/
```
## ui-overrides.tsx
```tsx
import {
DefaultKeyboardShortcutsDialog,
DefaultKeyboardShortcutsDialogContent,
DefaultToolbar,
DefaultToolbarContent,
TLComponents,
TLUiOverrides,
TldrawUiMenuItem,
useIsToolSelected,
useTools,
} from 'tldraw'
export const uiOverrides: TLUiOverrides = {
tools(editor, tools) {
// Create a tool item in the ui's context.
tools.PlayingCard = {
id: 'PlayingCard',
icon: 🃏,
label: 'Playing card',
kbd: 'c',
onSelect: () => {
editor.setCurrentTool('PlayingCard')
},
}
return tools
},
}
export const components: TLComponents = {
Toolbar: (props) => {
const tools = useTools()
const isCardSelected = useIsToolSelected(tools['PlayingCard'])
return (
)
},
KeyboardShortcutsDialog: (props) => {
const tools = useTools()
return (
)
},
}
// Same pattern as the custom-config example's ui-overrides.tsx; see the guide there.
```
## playing-card-tool.tsx
```tsx
import { BaseBoxShapeTool } from 'tldraw'
export class PlayingCardTool extends BaseBoxShapeTool {
static override id = 'PlayingCard'
static override initial = 'idle'
override shapeType = 'PlayingCard' as const
}
/*
This file contains our custom tool. The tool is a StateNode with the `id` "PlayingCard".
We get click-to-create and drag-to-create for free by extending BaseBoxShapeTool, but we
could handle events in our own way by overriding methods like onDoubleClick. For an example
of a tool with more custom functionality, check out the screenshot-tool example.
*/
```
## playing-card-util.tsx
```tsx
import {
BaseBoxShapeUtil,
BoundsSnapGeometry,
HTMLContainer,
RecordProps,
Rectangle2d,
T,
TLShape,
} from 'tldraw'
// There's a guide at the bottom of this file!
const PLAYING_CARD_TYPE = 'PlayingCard'
// [1]
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[PLAYING_CARD_TYPE]: {
w: number
h: number
suit: string
}
}
}
// [2]
export type IPlayingCard = TLShape
export class PlayingCardUtil extends BaseBoxShapeUtil {
// [3]
static override type = PLAYING_CARD_TYPE
static override props: RecordProps = {
w: T.number,
h: T.number,
suit: T.string,
}
// [4]
override isAspectRatioLocked(shape: IPlayingCard) {
return true
}
// [5]
getDefaultProps(): IPlayingCard['props'] {
const cardSuitsArray: string[] = ['♠️', '♣️', '♥️', '♦️']
const randomSuit = cardSuitsArray[Math.floor(Math.random() * cardSuitsArray.length)]
return {
w: 270,
h: 370,
suit: randomSuit,
}
}
// [6]
override getBoundsSnapGeometry(shape: IPlayingCard): BoundsSnapGeometry {
return {
points: new Rectangle2d({
width: shape.props.h / 4.5,
height: shape.props.h / 4.5,
isFilled: true,
}).bounds.cornersAndCenter,
}
}
// [7]
component(shape: IPlayingCard) {
return (
{shape.props.suit}
{shape.props.suit}
)
}
// [8]
getIndicatorPath(shape: IPlayingCard) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
/*
This is a utility class for the PlayingCard shape. This is where you define the shape's behavior,
how it renders (its component and indicator), and how it handles different events. The most relevant
part of the code to custom snapping can be found in [6].
[1]
First, we extend TLGlobalShapePropsMap to add our shape's props to the global type system. For this
shape, we define width (w), height (h), and suit as the shape's properties.
[2]
Define the shape type using TLShape with the shape's type as a type argument.
[3]
We define the shape's type and props for the editor. The validators make sure the store always has
shape data we can trust: width and height are numbers, and suit is a string.
[4]
We lock the aspect ratio so cards keep their proportions when resized.
[5]
getDefaultProps determines what our shape looks like when click-creating one. In this case, we
want the shape to be 270x370 pixels with a random suit.
[6]
This is the important part for custom snapping. getBoundsSnapGeometry returns the points that the
shape snaps to and that other shapes snap against, instead of the default bounding box. Here it's
the corners and center of the square in the top left that contains the suit, the same size as the
span defined in [7]. That's what lets a card snap into place just below or beside another card's
suit icon.
[7]
The component method controls what the shape looks like. It returns a div with the suit in the
center and a span with the suit in the top left. HTMLContainer is a div wrapper that the tldraw
library exports with the css needed to position it correctly.
[8]
getIndicatorPath returns a Path2D for the blue outline that appears around the shape when it's
selected or hovered. tldraw strokes it onto the canvas overlay.
*/
```
--------
# Frame layout modes
Category: Shapes & tools
Keywords: frame, container, layout, grid, spotlight, resize, video, reparent, onChildrenChange, BaseFrameLikeShapeUtil
A frame-like board shape that arranges its children in five swappable layouts.
This example shows how to give one frame-like container several ways to organize what's inside it. The board shape has a `layout` prop, and each mode is a small pure function from the children's boxes to new boxes, so adding an arrangement means adding one entry to a record.
Because a layout returns boxes rather than points, it sizes its children as well as placing them. A row gives every card the same height, a column the same width, and spotlight scales the left-most card up to a hero with the rest as thumbnails beside it. The `free` mode arranges nothing and behaves like a plain frame.
The board re-runs its layout from `onChildrenChange`, so it responds to cards being added, deleted, resized, or restored by undo. Select a board to switch its mode; drag cards between boards and they land wherever you drop them.
For a container that hands layout to the browser instead, see the [flex layout shape](https://tldraw.dev/examples/flex-layout) example.
## App.tsx
```tsx
import {
BaseFrameLikeShapeUtil,
Box,
EASINGS,
Editor,
Geometry2d,
Group2d,
HTMLContainer,
RecordProps,
Rectangle2d,
T,
TLComponents,
TLDragShapesOutInfo,
TLShape,
TLShapeId,
TLShapePartial,
Tldraw,
TldrawUiContextualToolbar,
TldrawUiToolbarButton,
createShapeId,
track,
useEditor,
useValue,
} from 'tldraw'
import 'tldraw/tldraw.css'
import {
BOARD_HEADER_HEIGHT,
BOARD_LAYOUTS,
BOARD_PADDING,
BoardLayoutMode,
arrangeBoard,
} from './BoardLayouts'
import {
NOTE_CARD_SHAPE_TYPE,
NoteCardShapeUtil,
VIDEO_CARD_SHAPE_TYPE,
VideoCardShapeUtil,
} from './MediaCardShapes'
import './frame-layouts.css'
// There's a guide at the bottom of this file!
const BOARD_SHAPE_TYPE = 'layout-board'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[BOARD_SHAPE_TYPE]: { w: number; h: number; name: string; layout: BoardLayoutMode }
}
}
type BoardShape = TLShape
// [1]
class LayoutBoardShapeUtil extends BaseFrameLikeShapeUtil {
static override type = BOARD_SHAPE_TYPE
static override props: RecordProps = {
w: T.nonZeroNumber,
h: T.nonZeroNumber,
name: T.string,
layout: T.literalEnum('free', 'row', 'column', 'grid', 'spotlight'),
}
override getDefaultProps(): BoardShape['props'] {
return { w: 320, h: 240, name: 'Board', layout: 'free' }
}
// [2]
override canReceiveNewChildrenOfType(shape: BoardShape, type: TLShape['type']) {
if (shape.isLocked) return false
return type === VIDEO_CARD_SHAPE_TYPE || type === NOTE_CARD_SHAPE_TYPE
}
// [3]
override canResize(shape: BoardShape) {
return shape.props.layout === 'free'
}
override hideResizeHandles(shape: BoardShape) {
return shape.props.layout !== 'free'
}
override canResizeChildren() {
return false
}
// [4]
override getGeometry(shape: BoardShape): Geometry2d {
return new Group2d({
children: [
new Rectangle2d({ width: shape.props.w, height: shape.props.h, isFilled: false }),
new Rectangle2d({
width: shape.props.w,
height: BOARD_HEADER_HEIGHT,
isFilled: true,
isLabel: true,
}),
],
})
}
// [5]
override onChildrenChange(shape: BoardShape) {
if (this.editor.isIn('select.translating')) return
return getBoardLayoutChanges(this.editor, shape)
}
// [6]
override onDropShapesOver(shape: BoardShape) {
animateBoardLayout(this.editor, shape.id)
}
override onDragShapesOut(shape: BoardShape, shapes: TLShape[], info: TLDragShapesOutInfo) {
super.onDragShapesOut(shape, shapes, info)
animateBoardLayout(this.editor, shape.id)
}
override component(shape: BoardShape) {
return
}
override getText(shape: BoardShape) {
return shape.props.name
}
override getIndicatorPath(shape: BoardShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
const EPSILON = 0.01
// [7]
function getBoardLayoutChanges(editor: Editor, board: BoardShape): TLShapePartial[] {
const children = editor
.getSortedChildIdsForParent(board.id)
.map((id) => editor.getShape(id))
.filter((child): child is TLShape => !!child)
.map((child) => ({ child, size: editor.getShapeGeometry(child).bounds }))
const byId = new Map(children.map((entry) => [entry.child.id, entry]))
const originX = BOARD_PADDING
const originY = BOARD_HEADER_HEIGHT + BOARD_PADDING
const result = arrangeBoard(
board.props.layout,
children.map(({ child, size }) => ({
id: child.id,
x: child.x - originX,
y: child.y - originY,
w: size.width,
h: size.height,
}))
)
if (!result) return []
const changes: TLShapePartial[] = []
for (const box of result.boxes) {
const { child, size } = byId.get(box.id)!
const x = originX + box.x
const y = originY + box.y
const moved = Math.abs(child.x - x) > EPSILON || Math.abs(child.y - y) > EPSILON
const resized =
Math.abs(size.width - box.w) > EPSILON || Math.abs(size.height - box.h) > EPSILON
if (!moved && !resized) continue
changes.push({
id: child.id,
type: child.type,
x,
y,
...(resized && { props: { w: box.w, h: box.h } }),
} as TLShapePartial)
}
if (
Math.abs(board.props.w - result.w) > EPSILON ||
Math.abs(board.props.h - result.h) > EPSILON
) {
changes.push({ id: board.id, type: board.type, props: { w: result.w, h: result.h } })
}
return changes
}
function applyBoardLayout(editor: Editor, boardId: TLShapeId) {
const board = editor.getShape(boardId)
if (board) editor.updateShapes(getBoardLayoutChanges(editor, board))
}
function animateBoardLayout(editor: Editor, boardId: TLShapeId) {
const board = editor.getShape(boardId)
if (!board) return
editor.animateShapes(getBoardLayoutChanges(editor, board), {
animation: { duration: 220, easing: EASINGS.easeInOutCubic },
})
}
function BoardComponent({ shape }: { shape: BoardShape }) {
const editor = useEditor()
const count = useValue('card count', () => editor.getSortedChildIdsForParent(shape.id).length, [
editor,
shape.id,
])
return (
)
}
// [8]
const BoardLayoutToolbar = track(function BoardLayoutToolbar() {
const editor = useEditor()
const board = useValue(
'selected board',
() => {
if (!editor.isIn('select.idle')) return null
const shape = editor.getOnlySelectedShape()
return shape?.type === BOARD_SHAPE_TYPE ? (shape as BoardShape) : null
},
[editor]
)
if (!board) return null
const setLayout = (layout: BoardLayoutMode) => {
editor.markHistoryStoppingPoint('change board layout')
editor.run(() => {
editor.updateShape({ id: board.id, type: board.type, props: { layout } })
animateBoardLayout(editor, board.id)
})
editor.getContainer().focus()
}
const getSelectionBounds = () => {
const bounds = editor.getSelectionRotatedScreenBounds()
return bounds ? new Box(bounds.x, bounds.y, bounds.width, 0) : undefined
}
return (
{Object.entries(BOARD_LAYOUTS).map(([mode, { label }]) => (
setLayout(mode as BoardLayoutMode)}
>
{label}
))}
)
})
const shapeUtils = [LayoutBoardShapeUtil, VideoCardShapeUtil, NoteCardShapeUtil]
const components: TLComponents = { InFrontOfTheCanvas: BoardLayoutToolbar }
// [9]
const video = (url = '/fluid.mp4') => ({ type: VIDEO_CARD_SHAPE_TYPE, props: { url } }) as const
const note = (text: string, color: string) =>
({ type: NOTE_CARD_SHAPE_TYPE, props: { text, color } }) as const
const DEMO_BOARDS: Array<{
name: string
layout: BoardLayoutMode
x: number
y: number
w?: number
h?: number
cards: Array | ReturnType>
}> = [
{
name: 'Video wall',
layout: 'grid',
x: 80,
y: 100,
cards: [video(), video('/bonk.webm'), video(), note('Pick a hero shot', '#ffd43b')],
},
{
name: 'Up next',
layout: 'column',
x: 860,
y: 100,
cards: [video('/bonk.webm'), note('Intro cut', '#b2f2bb'), note('Color pass', '#ffc9c9')],
},
{
name: 'Moodboard',
layout: 'free',
x: 1140,
y: 100,
w: 460,
h: 340,
cards: [video(), note('Loose vibes', '#eebefa')],
},
{
name: 'Filmstrip',
layout: 'row',
x: 80,
y: 560,
cards: [video(), video('/bonk.webm'), note('End card', '#99e9f2')],
},
{
name: 'Stage',
layout: 'spotlight',
x: 860,
y: 560,
cards: [video(), video('/bonk.webm'), video(), note('Now playing', '#ffd43b')],
},
]
function createDemoContent(editor: Editor) {
for (const { name, layout, cards, x, y, ...size } of DEMO_BOARDS) {
const id = createShapeId(name)
editor.createShape({ id, type: BOARD_SHAPE_TYPE, x, y, props: { name, layout, ...size } })
// Cascaded from the top of the content area, so every layout's position sort agrees
// with this order and a `free` board still looks hand-placed
editor.createShapes(
cards.map((card, i) => ({
...card,
parentId: id,
x: BOARD_PADDING + i * 130,
y: BOARD_HEADER_HEIGHT + BOARD_PADDING + i * 80,
}))
)
applyBoardLayout(editor, id)
}
// A few loose cards, ready to be dragged onto a board
editor.createShapes([
{ ...video('/bonk.webm'), x: 80, y: 960 },
{ ...note('Add captions', '#ffd43b'), x: 340, y: 940 },
{ ...note('B-roll', '#b2f2bb'), x: 560, y: 1000 },
])
editor.zoomToFit()
}
export default function FrameLayoutsExample() {
return (
{
if (editor.getCurrentPageShapeIds().size > 0) return
createDemoContent(editor)
}}
/>
)
}
/*
This example shows one frame-like container arranging the same children in different ways. A
board shape has a `layout` prop, and swapping it swaps the arrangement. The layouts themselves
are pure functions over boxes and live in `BoardLayouts.ts`; this file is the SDK integration.
[1]
BaseFrameLikeShapeUtil gives the board its frame behavior: clipping children, providing their
background, and reparenting shapes in and out as they're dragged over it.
[2]
canReceiveNewChildrenOfType gates what the board picks up. This one takes cards only, so
dragging a drawn shape over it does nothing.
[3]
Only `free` boards are resizable by hand. The arranging layouts size the board to fit their
content, so its handles are hidden.
[4]
An unfilled body plus a filled header. Clicks inside the body pass through to the cards the way
a frame's interior does, while the header stays clickable for selecting and moving the board.
The header rectangle needs `isLabel` for that: frame-like shapes ignore interior fills so that
brush selection works inside them.
[5]
onChildrenChange is the main trigger. It runs whenever a child is added, removed, deleted,
restored by undo, moved, or resized, and whatever it returns gets applied. Re-running the
layout produces no further changes once everything sits in its slot, so this settles in a pass
rather than looping. The one case to skip is an in-progress drag, where correcting positions
would fight the pointer.
[6]
Drags finish through the frame-like callbacks instead: onDropShapesOver when cards land on the
board, onDragShapesOut when one leaves and the rest close the gap. Both animate, and because
every shape here extends BaseBoxShapeUtil, animateShapes tweens size as well as position.
[7]
Turn a layout into store changes: a new position for each card that has drifted from its slot,
new `w`/`h` for cards the layout resized, and a new size for the board so it hugs its content.
[8]
A contextual toolbar for the selected board, built from the same BOARD_LAYOUTS record that
defines the modes.
[9]
Seed a board per mode plus a few loose cards. The cards start on a diagonal and applyBoardLayout
snaps them into place, which is the same path the board takes at runtime.
*/
```
## BoardLayouts.ts
```ts
import { TLShapeId } from 'tldraw'
// There's a guide at the bottom of this file!
export const BOARD_PADDING = 16
export const BOARD_GAP = 12
export const BOARD_HEADER_HEIGHT = 36
const EMPTY_WIDTH = 240
const EMPTY_HEIGHT = 168
const CARD_HEIGHT = 120
const CARD_WIDTH = 180
const HERO_HEIGHT = 240
const THUMBNAIL_HEIGHT = 80
export type BoardLayoutMode = 'free' | 'row' | 'column' | 'grid' | 'spotlight'
/** A child's box, relative to the board's content area. */
export interface LayoutBox {
id: TLShapeId
x: number
y: number
w: number
h: number
}
export interface BoardLayout {
label: string
/** `null` arranges nothing, so the board behaves like a plain frame. */
arrange: ((children: LayoutBox[]) => { boxes: LayoutBox[]; w: number; h: number }) | null
}
const midX = (box: LayoutBox) => box.x + box.w / 2
const midY = (box: LayoutBox) => box.y + box.h / 2
/** Scale a box to a target height or width, keeping its aspect ratio. */
const toHeight = (box: LayoutBox, h: number) => ({ ...box, w: (box.w / box.h) * h, h })
const toWidth = (box: LayoutBox, w: number) => ({ ...box, w, h: (box.h / box.w) * w })
// [1]
export const BOARD_LAYOUTS: Record = {
free: {
label: 'Free',
arrange: null,
},
// [2]
row: {
label: 'Row',
arrange(children) {
let x = 0
const boxes = [...children]
.sort((a, b) => midX(a) - midX(b))
.map((box) => {
const next = { ...toHeight(box, CARD_HEIGHT), x, y: 0 }
x += next.w + BOARD_GAP
return next
})
return { boxes, w: x - BOARD_GAP, h: CARD_HEIGHT }
},
},
column: {
label: 'Column',
arrange(children) {
let y = 0
const boxes = [...children]
.sort((a, b) => midY(a) - midY(b))
.map((box) => {
const next = { ...toWidth(box, CARD_WIDTH), x: 0, y }
y += next.h + BOARD_GAP
return next
})
return { boxes, w: CARD_WIDTH, h: y - BOARD_GAP }
},
},
grid: {
label: 'Grid',
arrange(children) {
const cells = children.map((box) => toHeight(box, CARD_HEIGHT))
const cellW = Math.max(...cells.map((box) => box.w))
// Read the cards in rows: group them into horizontal bands, then left to right
const band = (box: LayoutBox) => Math.round(midY(box) / (CARD_HEIGHT + BOARD_GAP))
const sorted = cells.sort((a, b) => band(a) - band(b) || midX(a) - midX(b))
const columns = Math.ceil(Math.sqrt(sorted.length))
const rows = Math.ceil(sorted.length / columns)
const boxes = sorted.map((box, i) => ({
...box,
x: (i % columns) * (cellW + BOARD_GAP) + (cellW - box.w) / 2,
y: Math.floor(i / columns) * (CARD_HEIGHT + BOARD_GAP),
}))
return {
boxes,
w: columns * cellW + (columns - 1) * BOARD_GAP,
h: rows * CARD_HEIGHT + (rows - 1) * BOARD_GAP,
}
},
},
spotlight: {
label: 'Spotlight',
arrange(children) {
const [first, ...rest] = [...children].sort((a, b) => midX(a) - midX(b))
const hero = toHeight(first, HERO_HEIGHT)
const thumbnails = rest
.sort((a, b) => midY(a) - midY(b))
.map((box) => toHeight(box, THUMBNAIL_HEIGHT))
const stackH =
thumbnails.length * THUMBNAIL_HEIGHT + Math.max(0, thumbnails.length - 1) * BOARD_GAP
const h = Math.max(HERO_HEIGHT, stackH)
const stackW = Math.max(0, ...thumbnails.map((box) => box.w))
let y = (h - stackH) / 2
const boxes = [{ ...hero, x: 0, y: (h - HERO_HEIGHT) / 2 }]
for (const thumbnail of thumbnails) {
boxes.push({ ...thumbnail, x: hero.w + BOARD_GAP, y })
y += thumbnail.h + BOARD_GAP
}
return { boxes, w: hero.w + (thumbnails.length ? BOARD_GAP + stackW : 0), h }
},
},
}
// [3]
export function arrangeBoard(mode: BoardLayoutMode, children: LayoutBox[]) {
const { arrange } = BOARD_LAYOUTS[mode]
if (!arrange) return null
const { boxes, w, h } = children.length ? arrange(children) : { boxes: [], w: 0, h: 0 }
return {
boxes,
w: Math.max(EMPTY_WIDTH, w + BOARD_PADDING * 2),
h: Math.max(EMPTY_HEIGHT, h + BOARD_HEADER_HEIGHT + BOARD_PADDING * 2),
}
}
/*
This file is the layout engine, and it never touches the editor. A layout takes the boxes of
a board's children and returns where they should go, which is why the same code arranges
video cards, note cards, or any other shape the board accepts.
[1]
Each mode is one entry in a record: a label plus a function from boxes to boxes. Adding a
mode (masonry, ring, timeline) means adding an entry here and a value to the board's `layout`
prop validator.
Every mode sorts the cards by their current position before assigning slots, so wherever you
drop a card is where it lands in the order. There's no separate index to keep in sync.
[2]
Because a layout returns whole boxes rather than points, it sizes its children as well as
placing them, and each mode decides what that means: a row gives every card the same height,
a column the same width, and spotlight scales the left-most card up to a hero and the rest
down to thumbnails. Drop a card to the left of the hero to promote it.
Sizes come from constants rather than from the cards, so switching modes lands on the same
result every time instead of compounding. The trade-off is that hand-resizing a card only
sticks on a `free` board, where nothing else owns its size.
[3]
Arrange the children and add the board's padding and header back, with a minimum size so an
empty board is still a usable drop target. Returns `null` for `free`, which arranges nothing.
*/
```
## MediaCardShapes.tsx
```tsx
import { BaseBoxShapeUtil, HTMLContainer, RecordProps, T, TLShape } from 'tldraw'
// There's a guide at the bottom of this file!
export const VIDEO_CARD_SHAPE_TYPE = 'video-card'
export const NOTE_CARD_SHAPE_TYPE = 'media-note-card'
declare module 'tldraw' {
export interface TLGlobalShapePropsMap {
[VIDEO_CARD_SHAPE_TYPE]: { w: number; h: number; url: string }
[NOTE_CARD_SHAPE_TYPE]: { w: number; h: number; text: string; color: string }
}
}
export type VideoCardShape = TLShape
export type NoteCardShape = TLShape
// [1]
export class VideoCardShapeUtil extends BaseBoxShapeUtil {
static override type = VIDEO_CARD_SHAPE_TYPE
static override props: RecordProps = {
w: T.nonZeroNumber,
h: T.nonZeroNumber,
url: T.string,
}
override getDefaultProps(): VideoCardShape['props'] {
return { w: 192, h: 108, url: '/fluid.mp4' }
}
// [2]
override isAspectRatioLocked() {
return true
}
override component(shape: VideoCardShape) {
return (
)
}
override getIndicatorPath(shape: VideoCardShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
export class NoteCardShapeUtil extends BaseBoxShapeUtil {
static override type = NOTE_CARD_SHAPE_TYPE
static override props: RecordProps = {
w: T.nonZeroNumber,
h: T.nonZeroNumber,
text: T.string,
color: T.string,
}
override getDefaultProps(): NoteCardShape['props'] {
return { w: 144, h: 96, text: 'Note', color: '#ffd43b' }
}
override component(shape: NoteCardShape) {
return (
{shape.props.text}
)
}
override getText(shape: NoteCardShape) {
return shape.props.text
}
override getIndicatorPath(shape: NoteCardShape) {
const path = new Path2D()
path.rect(0, 0, shape.props.w, shape.props.h)
return path
}
}
/*
Two shape types for the board to organize, with different default sizes so you can see how
each layout handles a mix. Neither knows anything about the board: the board reads their
geometry and moves them, so any shape type it accepts works the same way.
[1]
Both extend BaseBoxShapeUtil, which gives them `w`/`h` geometry, resize handles, and a
`getInterpolatedProps` that tweens size. That last one is what lets the board animate a card
to a new size rather than snapping it.
[2]
The video keeps its aspect ratio when you resize it by hand, and the layouts scale cards
proportionally, so it never stretches.
*/
```
## frame-layouts.css
```css
.layout-board {
box-sizing: border-box;
background-color: var(--tl-color-low);
border: 1px solid var(--tl-color-divider);
border-radius: 10px;
}
.layout-board__header {
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 0 12px;
background-color: var(--tl-color-panel);
border-bottom: 1px solid var(--tl-color-divider);
border-radius: 10px 10px 0 0;
font: var(--tl-font-body);
font-size: 13px;
}
.layout-board__name {
font-weight: 500;
color: var(--tl-color-text-1);
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.layout-board__badge {
flex-shrink: 0;
font-size: 11px;
color: var(--tl-color-text-3);
background-color: var(--tl-color-muted-2);
border-radius: 99px;
padding: 2px 8px;
white-space: nowrap;
}
.media-card {
box-sizing: border-box;
border-radius: 8px;
overflow: hidden;
box-shadow: var(--tl-shadow-1);
}
.media-card--video {
background-color: var(--tl-color-text);
}
.media-card--video video {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
pointer-events: none;
}
.media-card--note {
display: grid;
place-items: center;
padding: 8px;
text-align: center;
font: var(--tl-font-body);
font-size: 13px;
color: hsl(0, 0%, 15%);
}
```
--------
# Keyboard math input
Category: Shapes & tools
Keywords: custom shape, shapeutil, katex, math, latex, equation, shorthand, editing state, custom tool, toolbar, auto-size
Type math equations with a plain keyboard, using a custom shape rendered with KaTeX.
This example adds a math equation shape that behaves like a text shape. Pick the math tool from the toolbar (or press M), click the canvas, and type shorthand: `1/2` becomes a fraction, `sqrt(2)` a radical, `x^2` a superscript, `pi` the symbol, and so on. A preview bubble above the shape renders the equation live as you type. Press Enter or Escape (or click away) and the equation renders in place of what you typed. Double-click any equation to edit its shorthand again.
The shape stores the shorthand exactly as typed. A small translator (`shorthand.ts`) rewrites it into LaTeX, which is rendered with [KaTeX](https://katex.org). Raw LaTeX commands pass through the translator untouched, so `\frac{a}{b}` works too.
## App.tsx
```tsx
import 'katex/dist/katex.min.css'
import {
DefaultToolbar,
DefaultToolbarContent,
TLComponents,
TLUiOverrides,
Tldraw,
TldrawUiMenuItem,
createShapeId,
toRichText,
useIsToolSelected,
useTools,
} from 'tldraw'
import 'tldraw/tldraw.css'
import { MathShapeUtil } from './MathShapeUtil'
import { MathTool } from './MathTool'
import './keyboard-math-input.css'
// There's a guide at the bottom of this file!
const customShapeUtils = [MathShapeUtil]
const customTools = [MathTool]
// [1]
const uiOverrides: TLUiOverrides = {
tools(editor, tools) {
tools.math = {
id: 'math',
icon: 'tool-math',
label: 'Math',
kbd: 'm',
onSelect: () => editor.setCurrentTool('math'),
}
return tools
},
}
function Toolbar() {
const tools = useTools()
const isMathSelected = useIsToolSelected(tools.math)
return (