Editor focus

In this example, we drive the editor's focus in order to turn on and off keyboard shortcuts.

The editor's focus is different from—but usually corresponds to—the browser's concept of "focus", which is related to the document's active element.

Unfortunately, the browser's focus cannot be relied on to determine whether the editor's keyboard shortcuts should work. While its possible to detect whether the document's active element is a descendant of the Tldraw component's own element, it's not 100% reliable. For example, iframes are not considered descendants of their parents, and many menus are portalled into different parts of the document tree.

For these reasons, the responsibility falls to you, dear developer, to manage focus for your Tldraw editor, especially in cases where there are more than one editor on the same page.

import { useRef } from 'react'
import { Editor, Tldraw } from 'tldraw'
import 'tldraw/tldraw.css'
import './editor-focus.css'

export default function EditorFocusExample() {
	const editorRef = useRef<Editor | null>(null)
	return (
		<div style={{ padding: 32 }}>
			<input type="text" placeholder="Test me" />
			<p>
				You should be able to type in this text input without worrying about triggering editor
				shortcuts even when the editor is focused.
			</p>
			<div>
				<h2>Controlled Focus</h2>
				<div style={{ display: 'flex', gap: 4 }}>
					<input
						id="focus"
						type="checkbox"
						onChange={(e) => {
							if (e.target.checked) {
								editorRef.current?.focus()
							} else {
								editorRef.current?.blur()
							}
						}}
					/>
					<label htmlFor="focus">Focus</label>
				</div>
			</div>
			<p>
				The checkbox controls the editor’s <code>instanceState.isFocused</code> property.
			</p>
			<p>
				When the editor is “focused”, its keyboard shortcuts will work. When it is not focused, the
				keyboard shortcuts will not work.
			</p>
			<div style={{ width: 800, maxWidth: '100%', height: 500 }}>
				<Tldraw
					autoFocus={false}
					onMount={(editor) => {
						editorRef.current = editor
					}}
				/>
			</div>
		</div>
	)
}
Is this page helpful?
Prev
Derived view
Next
Indicators logic