API

The editor's methods, the hooks of a kind of shape, and the components.

Read from the library's source when this site was built, so it says what the code says. Every method is called on the editor (editor.select(ids)); a method's arguments that name shapes take their ids.

Editor

new Editor({ plugins, store?, initialTool?, assets? }). The editor owns the document (its store and history), the view (camera, selection) and the tools. Its values are signals: .get() reads and is reactive in Svelte, .peek() reads without tracking, .set() writes.

State

readonly store: Store<DrawRecord>
Every record of the document: pages, shapes, files.
readonly history: History<DrawRecord>
Undo and redo of this user's changes.
readonly root: StateNode
The root of the tools' state machines; the tools are its children.
readonly assets: AssetStore
Where files are kept (see EditorOptions.assets).
readonly readOnly = atom(false)
True while the document may be looked at but not changed (see setReadOnly).
readonly camera = atom<Camera>({ x: 0, y: 0, z: 1 })
The view: a point on the screen is the page point × z + (x, y).
readonly viewport = atom({ w: 0, h: 0 })
The canvas's size on screen.
readonly pageId = atom('')
The id of the page being looked at.
readonly selection = atom<readonly string[]>([])
The ids of the selected shapes.
readonly hovered = atom<string | null>(null)
The id of the shape under the pointer, if one is outlined.
readonly brush = atom<Box | null>(null)
The marquee, in page space, while one is being dragged.
readonly cursor = atom('default')
A CSS cursor name.
readonly style = atom<ShapeStyle>(DEFAULT_STYLE)
The style the next shape gets.
readonly editing = atom<string | null>(null)
The shape whose content is being typed into, if any (see startEditing).
readonly erasing = atom<readonly string[]>([])
The shapes the eraser has touched and will remove on release.
readonly focusedGroup = atom<string | null>(null)
The group that was stepped into: clicks pick what is in it, not the group.
readonly snapLines = atom<readonly SnapLine[]>([])
The guides shown while a move or a resize snaps to other shapes.
readonly lasso = atom<readonly Vec[]>([])
The path of a lasso selection while it is drawn (page space).
readonly grid = atom({ show: true, snap: false })
The dot grid: whether it shows, and whether moved shapes land on it. This screen's own.
readonly laser = atom<readonly Vec[]>([])
The trail of the laser pointer (page space): shown for a moment, never part of the document.
readonly culling = atom(true)
False while every shape must be on screen at once (a picture is being made of the page).
readonly pointerPage = atom<Vec>({ x: 0, y: 0 })
Where this user's pointer is on the page (for the others to see).
readonly peers = atom<readonly Peer[]>([])
The other people looking at this document right now (see persist.ts).
clipboard: ShapeRecord[] = []
What was copied last, for a paste where the system clipboard cannot be read.
readonly toolPath = atom('')
The active path of the tool tree, like select.idle.
readonly inputs = { screen: { x: 0, y: 0 } as Vec, page: { x: 0, y: 0 } as Vec, originScreen: { x: 0, y: 0 } as Vec, originPage: { x: 0, y: 0 } as Vec, shift: false, alt: false, meta: false, isDown: false, isDragging: false, pressure: 0.5, isPen: false }
The pointer and modifier keys as of the last event.

Document and pages

getPages(): PageRecord[]
The document's pages, in order.
getPage(): PageRecord | undefined
The page being looked at.
setPage(id: string)
Shows another page. What was going on is dropped; each page keeps its own view.
createPage(name?: string): PageRecord
Adds a page after the last one and shows it.
renamePage(id: string, name: string)
deletePage(id: string)
Removes a page and everything on it. The last page stays.
getDocument(): DocumentFile
The whole document, to save to a file or hand to another editor.
loadDocument(records: readonly DrawRecord[], source: 'user' | 'remote' = 'remote')
Replaces the document with records. What is loaded is not an undo step. As remote (what storage held: the other tabs loaded it too) nothing is saved or sent for it; as user (a file this user opened) it is saved and sent like any other change.
setReadOnly(readOnly: boolean)
While read-only, tools other than select and hand are refused and nothing can be changed.

Tools

get tool(): string
The active tool's id (select, draw, …).
setTool(path: string, info?: unknown)
Switches tool. path may reach into the tool (select.resizing), info goes with it.
dispatch(event: DrawEvent): void
The one way events come in.

Measured sizes

getMeasured(id: string): { w: number; h: number } | undefined
The size the renderer measured for a shape whose size the core cannot know (text). It is not part of the document: every screen measures its own, so nothing is written, undone or sent for it. Undefined where nothing has measured (a test, a server).
setMeasured(id: string, size: { w: number; h: number } | undefined)
Called by a shape's view with what it measured; undefined when the view goes away.

Editing

canEdit(id: string): boolean
Whether the shape's content can be typed into (its util says so).
startEditing(id: string, options: { creating?: boolean } = {})
Starts typing into a shape: selects it and sets editing, which the shape's view turns into a text field. Everything typed until stopEditing is one undo step.
stopEditing()
Ends typing and keeps what was typed. The shape stays selected.

Shapes

util<S extends ShapeRecord = ShapeRecord>(kind: string): ShapeUtil<S>
The util that owns shapes of kind.
getUtils(): ReadonlyMap<string, ShapeUtil>
Every registered kind with its util, in the order the plugins brought them.
hasUtil(kind: string): boolean
getShape<S extends ShapeRecord = ShapeRecord>(id: string): S | undefined
getShapeIds(): readonly string[]
The current page's shape ids, bottom to top.
getShapes(): ShapeRecord[]
The current page's shapes, bottom to top.
getSelectedShapes(): ShapeRecord[]
createShape(shape: NewShape): ShapeRecord
createShapes(shapes: NewShape[]): ShapeRecord[]
updateShape(id: string, patch: ShapePatch)
updateShapes(patches: ({ id: string } & ShapePatch)[])
Patches shapes in one change. props and style are merged into what is there.
deleteShapes(ids: readonly string[])
Removes the shapes and everything inside them.
releaseTies(ids: readonly string[] = this.selection.peek())
Cuts the ties from ids to shapes outside of ids: an attached arrow that is moved without its shape lets go of it, and stays where it shows.
getBindTargetAt(point: Vec, exclude: readonly (string | null | undefined)[] = []): ShapeRecord | undefined
The topmost shape a line's end at point (page space) attaches to. By its box, not its line: a hollow shape is a target all over.
getChildren(parentId: string): ShapeRecord[]
The shapes directly in parentId (a page, a group, a frame), bottom to top.
getLeaves(shapes: readonly ShapeRecord[]): ShapeRecord[]
The shapes with every group among them replaced by what is in it.
isLocked(shape: ShapeRecord): boolean
Whether the shape, or anything it sits in, is locked.
getShapePageRotation(shape: ShapeRecord): number
How far the shape is turned on the page: its own turn plus every parent's.
shapeToPage(shape: ShapeRecord, point: Vec): Vec
A point in the shape's own space, as a point on the page.
pageToShape(shape: ShapeRecord, point: Vec): Vec
A point on the page, as a point in the shape's own space.
pageToParent(shape: ShapeRecord, point: Vec): Vec
A point on the page, in the space the shape's x/y are in (its parent's).
getShapePageOrigin(shape: ShapeRecord): Vec
Where the shape's origin is on the page.
getShapePageBounds(shape: ShapeRecord): Box
The upright box around the shape on the page (around its corners, if it is turned).
getShapeAtPoint(point: Vec, options: { locked?: boolean } = {}): ShapeRecord | undefined
The topmost shape touching point (page space), or undefined. Locked shapes are passed over unless locked is set; what a frame cuts off is not there.
getSelectable(shape: ShapeRecord): ShapeRecord
What a click on shape picks: the outermost group it is in, up to the group that was stepped into (focusedGroup); the shape itself when it is in no group.
isInFocus(shape: ShapeRecord): boolean
Whether the shape is in the group that was stepped into (always, when none was).
getShapesInBox(area: Box): ShapeRecord[]
Every shape whose bounds touch area (page space).
bringToFront(ids: readonly string[] = this.selection.peek())
sendToBack(ids: readonly string[] = this.selection.peek())
bringForward(ids: readonly string[] = this.selection.peek())
One step up: above the next sibling that is not moving too.
sendBackward(ids: readonly string[] = this.selection.peek())
One step down.

Selection

select(ids: readonly string[])
selectAll()
Selects everything that can be picked (groups as one, locked shapes not at all).
getSelectionRoots(): ShapeRecord[]
The selected shapes that are not inside another selected shape, and not locked.
getSelectionBounds(): Box | undefined
The upright box around everything selected (page space), or undefined.
getSelectionFrame(): { rotation: number; bounds: Box } | undefined
The box the selection's handles sit on. bounds is in the page turned back by rotation: one turned shape keeps its own box, several shapes get an upright one.
canResizeSelection(): boolean
Whether the selection shows resize handles: nothing in it is locked, all of it resizes, and all of it is turned the same way as the box the handles sit on.
canRotateSelection(): boolean
Whether the selection shows the handle that turns it.
getRotateHandle(): Vec | null
Where the handle that turns the selection sits (page space): above its top edge.
isRotateHandleAt(screen: Vec): boolean
getResizePatch(shape: ShapeRecord, target: Box, rotation: number, flip: { x: boolean; y: boolean }): { id: string } & ShapePatch
The change that puts shape's box at target, a box in the page turned back by rotation (which is how far the shape itself is turned on the page).
getShapeHandles(): { shape: ShapeRecord; handles: ShapeHandle[] } | null
The handles of the one selected shape, in page space, when its kind has its own (a line's two ends). Null otherwise.
getShapeHandleAt(screen: Vec): string | null
The id of the selected shape's own handle under screen, if any.
getHandleAt(screen: Vec): Handle | null
The resize handle under screen, if the selection has handles there.
deleteSelection()
getContent(ids: readonly string[] = this.selection.peek()): ShapeRecord[]
The shapes, and all that is in them, as records that stand on their own: placed on the page, tied only to each other. This is what goes on the clipboard.
getContentAssets(content: readonly ShapeRecord[]): AssetRecord[]
The asset records the shapes show (an image's file), for a clipboard that leaves the tab.
putContent(content: readonly ShapeRecord[], options: { at?: Vec; offset?: number; assets?: readonly AssetRecord[] } = {}): ShapeRecord[]
Adds content (from getContent) to the page as new shapes and selects them. With at its middle lands on that page point; otherwise it lands offset down and right of where it came from. assets are the files the shapes show, added where this document lacks them.
duplicateSelection(offset = 16)
Copies the selection a little down and right (or offset away), and selects the copies.
copy(): ShapeRecord[]
Puts the selection on the clipboard the editor keeps (clipboard), and returns it.
cut(): ShapeRecord[]
paste(content: readonly ShapeRecord[] = this.clipboard, at?: Vec, assets?: readonly AssetRecord[])
Pastes content (the editor's own clipboard by default), its middle at at if given.
pasteText(text: string, at: Vec)
Pastes plain text as a shape, its middle at at: the first kind that says it is made from text (ShapeUtil.fromText) makes it. Nothing happens when no kind does.
async addFiles(files: readonly Blob[], at: Vec): Promise<ShapeRecord[]>
Adds dropped, pasted or picked files as shapes around at: for each file, the first kind that says it is made from it (ShapeUtil.fromFile) makes the shape. Other files are passed over. All of it is one undo step.
toggleSelection(id: string)
Flips a switch (ShapeUtil.toggles) on every selected shape that has it.
nudgeSelection(dx: number, dy: number)
Moves the selection by a step (the arrow keys).
alignSelection(edge: AlignEdge)
Lines the selected shapes up along one edge (or the middle) of the box around them.
distributeSelection(axis: 'x' | 'y')
Spreads three or more selected shapes so the gaps between them are equal.
flipSelection(axis: 'x' | 'y')
Mirrors the selection left to right (x) or top to bottom (y) within its box.
toggleLock()
Locks the selection, or unlocks it when all of it is locked. A locked shape lets go.
canGroupSelection(): boolean
Whether the selection can be made a group: two or more shapes with the same parent.
groupSelection()
Makes the selected shapes one group, in the place of the topmost of them.
ungroupSelection()
Takes the selected groups apart; what was in them stays where it shows.
settle(ids: readonly string[] = this.selection.peek())
After shapes were made or moved: each whose middle now lies on a frame becomes that frame's, each that left its frame becomes the page's. It stays where it shows.
snapBox(moving: Box, exclude: ReadonlySet<string>): Vec
How far to shift moving (a box on the page) so that one of its edges or its middle meets another shape's. Shows the guides for it in snapLines.
snapPoint(point: Vec, exclude: ReadonlySet<string>, axes: { x: boolean; y: boolean }): Vec
point moved onto another shape's edge or middle where one is near, on the given axes.
setStyle(patch: Partial<ShapeStyle>)
Sets a style on the selection (on what is in a selected group) and for the next shape.

Camera

screenToPage(point: Vec): Vec
pageToScreen(point: Vec): Vec
pan(dx: number, dy: number)
Moves the view by screen pixels.
zoomTo(zoom: number, anchor?: Vec)
Zooms to zoom, keeping the page point under anchor (screen; the centre by default) still.
zoomIn()
zoomOut()
resetZoom()
zoomToFit()
Fits every shape on the page into view (never closer than 100%).
zoomToBounds(bounds: Box, padding = 32)
Brings a box on the page into view, as large as fits.
getViewportPageBounds(): Box
The part of the page that is on screen.
zoomToSelection()
Brings the selection into view, as large as fits (never past 100%).

History

undo()
redo()

ShapeUtil

The base class of a kind of shape. defaultProps, bounds and resize are required; every other hook has a default.

static kind: string
The kind of the records this util owns.
readonly editor: Editor
readonly styles: readonly StyleKey[] = ['color', 'fill', 'size', 'look', 'opacity']
The styles this kind shows; the style panel offers only these for it.
readonly group: boolean = false
True for a kind that is nothing but what is in it (a group): a click on anything in it picks the whole, and resizing it resizes what is in it.
readonly frame: boolean = false
True for a kind that takes in what is dropped on it and cuts it off at its edge (a frame).
defaultProps(): S['props']
Props of a new shape of this kind.
bounds(shape: S): Box
The shape's bounds in its own space (its x/y is the origin).
hitTest(shape: S, point: Vec, margin: number): boolean
Whether point (in the shape's own space) touches the shape, within margin.
outline(shape: S): string
The outline shown while the shape is hovered or selected: an SVG path in its own space.
canEdit(_shape: S): boolean
Whether the shape holds content to type into (a note's text). A double click or Enter then sets editor.editing to the shape, and its view shows the text field.
fromText(_text: string): S['props'] | undefined
The props of a shape of this kind made from pasted plain text. Undefined for a kind that is not made from text.
async fromFile(_file: Blob): Promise<{ props: S['props']; assets: AssetRecord[] } | undefined>
A shape of this kind made from a dropped, pasted or picked file: its props, and the asset records it needs. Undefined for a file this kind is not made from.
assets(_shape: S): string[]
The ids of the asset records the shape shows (an image's file).
toggles(_shape: S): { id: string; on: boolean }[]
Switches the shape offers in the right-click menu (a line's arrowheads).
toggle(_shape: S, _id: string): ShapePatch | undefined
The change when the switch id is flipped.
onEditEnd(_shape: S): void
Called when typing into the shape ends (a text with no words left removes itself).
canResize(_shape: S): boolean
rotate(_shape: S, _angle: number, _pivot: Vec): ShapePatch | undefined
The change when the shape is turned by angle around pivot (page space), for a kind that does not simply turn around its origin (a line moves its two ends instead). Undefined for the usual turn.
handles(_shape: S): ShapeHandle[]
Handles of the shape's own, like a line's two ends. A shape with any shows these instead of the resize box while it is the only one selected.
dragHandle(_shape: S, _handle: string, _point: Vec): ShapePatch | undefined
The change to the shape when its handle handle is dragged to point (page space).
canBind(_shape: S): boolean
Whether a line's end can attach to this shape.
edgePoint(shape: S, from: Vec, to: Vec): Vec
Where a line coming from from towards to (both in the shape's own space, to inside the shape) meets the shape's edge: where an attached arrow stops.
ties(_shape: S): string[]
The ids of the other shapes this one is tied to (the shapes a line is attached to).
retie(_shape: S, _map: (id: string) => string | null): ShapePatch | undefined
The change that re-ties the shape: map gives, for each shape it is tied to, the id to tie to instead, or null to cut the tie. A cut tie leaves the shape where it shows now. Undefined when nothing changes. The editor calls this when a tied shape is moved alone, copied, or loses the shape it was tied to.
resize(shape: S, target: Box, flip: { x: boolean; y: boolean }): ResizeResult<S>
The shape after its bounds are moved to target (in the parent's space). shape is the shape as it was when the resize began; flip says whether the drag crossed over an axis.

StateNode

The base class of a tool and of each of its states. A state handles only the events it has a method for; the rest walk on down the active path.

static id: string
The name of this state among its siblings (a tool's id is what setTool takes).
static initial?: string
The child that becomes active when this state is entered.
static children?: () => StateNodeConstructor[]
readonly editor: Editor
readonly parent?: StateNode
readonly children = new Map<string, StateNode>()
readonly current = atom<StateNode | undefined>(undefined)
The active child, if this state has children and is active.
isActive = false
get id(): string
addChild(Child: StateNodeConstructor)
path(): string
The active path below this state, like select.translating.
transition(path: string, info?: unknown)
Makes the child path the active one (idle, or deeper: select.resizing). info goes to the onEnter of the last state on the path.
enter(info: unknown)
exit()
handleEvent(event: DrawEvent)
Runs this state's handler, then the active child's (unless the handler moved on).
onEnter?(info: unknown): void
onExit?(): void
onPointerDown?(event: PointerInfo): void
onPointerMove?(event: PointerInfo): void
onPointerUp?(event: PointerInfo): void
onDoubleClick?(event: PointerInfo): void
onKeyDown?(event: KeyInfo): void
onKeyUp?(event: KeyInfo): void
onCancel?(event: CancelInfo): void
Escape, or the browser took the pointer away: drop what is in progress.

Components

From @klementine/draw/svelte.

Draw
the whole whiteboard in one tag: the canvas, the toolbar, the style panel, the page menu and the zoom control. Fills its parent: give the parent a size.
plugins decide what it can do (the built-in ones by default; add your own shapes and tools to the list). Pass an editor to own it (to script it, save it, or sync its store); otherwise Draw makes one. For another arrangement, compose Canvas and the parts yourself.
Canvas
the surface an editor is shown and worked on. It draws the editor's shapes through the plugins' views, and turns pointer, wheel and key events into the editor's events; every decision about what an event means is the editor's and its tools'.
children sit above the surface (a toolbar, a panel) and do not send it events. Name the canvas with label. Fills its parent: give the parent a size.
Also the canvas's: copy, cut and paste through the system clipboard, two-finger pinch and pan on a touch screen, and the right-click menu (labels translates it).
DrawToolbar
the tools of every plugin in one bar, then undo and redo. The picked tool is the editor's; picking here and pressing a tool's key are the same thing.
StylePanel
the look of what is selected, or of the next shape when nothing is. One row for each style the selected kinds have (a line has no fill, a text has a typeface); every row always has one pick. Nothing shows for kinds with no styles (a frame).
StyleRow
one row of the style panel: a few choices of which exactly one is picked. options name the choices, item draws one (a colour dot, an icon). Picking the picked one again keeps it: a style always has a value.
ZoomControl
out, the zoom in percent (press it to go back to 100%), in, and show everything.
GeoView
a closed shape in a box (rectangle, ellipse, star, …), as a pen stroke (sketch) or as exact lines, with the words written in it.
DrawView
one freehand stroke, filled as the outline of where the pen went. A highlighter's stroke is a wide, even, see-through line instead.
LineView
a line or an arrow, straight or bent, as pen strokes (sketch) or as exact lines. Its run comes from lineGeometry, so an attached end follows its shape.
TextView
words on the canvas. The core cannot measure text, so the view tells the editor how large the words are on this screen (editor.setMeasured). That size is not part of the document: nothing is written for it.
FrameView
a frame's box, with its name above the top left corner.
TextLabel
the words of a shape, and the field they become while the shape is typed into (editor.editing). The element around it sets the typeface, size and alignment.
CanvasMenu
what the canvas's right-click menu offers for the selection: clipboard, order, alignment, flipping, grouping, locking, deleting. Only what applies shows. It is the inside of a ContextMenuContent; Canvas puts it there.
PageMenu
the page being looked at, and the menu to go to another, add one, rename or delete this one. Renaming turns the button into a field; Enter keeps the name, Escape drops it.
Minimap
the whole page small, with the part on screen marked. Press or drag in it to go there.
NoteView
a sticky note. Flat bright paper with a slightly darker band on top where the glue is, handwriting, and a slight tilt of its own (from its id, so it never changes), the way a note lands when it is stuck on by hand. It is paper, so it keeps its colour and dark writing in both themes. A view may be plain HTML; it need not be SVG.
ImageView
a picture, from the asset record the shape points at.
LinkView
a web address. A known video shows its player, any other address a card with where it leads. Like every shape it is moved and resized by the canvas; a double click makes it live (the card can be followed, the player played) until Escape.