UNPKG

@tldraw/editor

Version:

tldraw infinite canvas SDK (editor).

69 lines (68 loc) 2.42 kB
class FocusManager { constructor(editor, autoFocus) { this.editor = editor; this.disposeSideEffectListener = editor.sideEffects.registerAfterChangeHandler( "instance", (prev, next) => { if (prev.isFocused !== next.isFocused) { this.updateContainerClass(); } } ); const currentFocusState = editor.getInstanceState().isFocused; if (autoFocus !== currentFocusState) { editor.updateInstanceState({ isFocused: !!autoFocus }); } this.updateContainerClass(); document.body.addEventListener("keydown", this.handleKeyDown.bind(this)); document.body.addEventListener("mousedown", this.handleMouseDown.bind(this)); } disposeSideEffectListener; /** * The editor's focus state and the container's focus state * are not necessarily always in sync. For that reason we * can't rely on the css `:focus` or `:focus-within` selectors to style the * editor when it is in focus. * * For that reason we synchronize the editor's focus state with a * special class on the container: tl-container__focused */ updateContainerClass() { const container = this.editor.getContainer(); const instanceState = this.editor.getInstanceState(); if (instanceState.isFocused) { container.classList.add("tl-container__focused"); } else { container.classList.remove("tl-container__focused"); } container.classList.add("tl-container__no-focus-ring"); } handleKeyDown(keyEvent) { const container = this.editor.getContainer(); if (this.editor.isIn("select.editing_shape")) return; if (document.activeElement === container && this.editor.getSelectedShapeIds().length > 0) return; if (["Tab", "ArrowUp", "ArrowDown"].includes(keyEvent.key)) { container.classList.remove("tl-container__no-focus-ring"); } } handleMouseDown() { const container = this.editor.getContainer(); container.classList.add("tl-container__no-focus-ring"); } focus() { this.editor.getContainer().focus(); } blur() { this.editor.complete(); this.editor.getContainer().blur(); } dispose() { document.body.removeEventListener("keydown", this.handleKeyDown.bind(this)); document.body.removeEventListener("mousedown", this.handleMouseDown.bind(this)); this.disposeSideEffectListener?.(); } } export { FocusManager }; //# sourceMappingURL=FocusManager.mjs.map