diff --git a/ts/editor/codable.ts b/ts/editor/codable.ts index ca9cb0e62..383a0027e 100644 --- a/ts/editor/codable.ts +++ b/ts/editor/codable.ts @@ -5,10 +5,10 @@ import * as CodeMirror from "codemirror/lib/codemirror"; import "codemirror/mode/htmlmixed/htmlmixed"; const codeMirrorOptions = { - lineNumbers: true, - lineWrapping: true, mode: "htmlmixed", theme: "monokai", + lineNumbers: true, + lineWrapping: true, }; const parser = new DOMParser(); @@ -26,15 +26,15 @@ export class Codable extends HTMLTextAreaElement { this.setAttribute("hidden", ""); } - toggle(html: string): string { - return this.codeMirror ? this.teardown() : this.setup(html); - } - - setup(html: string): string { + setup(html: string): void { this.active = true; this.value = html; this.codeMirror = CodeMirror.fromTextArea(this, codeMirrorOptions); - return ""; + } + + focus(): void { + this.codeMirror.focus(); + this.codeMirror.setCursor(this.codeMirror.lineCount(), 0); } teardown(): string { diff --git a/ts/editor/editable.scss b/ts/editor/editable.scss index 26c35131a..7eba170b7 100644 --- a/ts/editor/editable.scss +++ b/ts/editor/editable.scss @@ -40,3 +40,7 @@ img.drawing { filter: unquote("invert() hue-rotate(180deg)"); } } + +[hidden] { + display: none; +} diff --git a/ts/editor/editingArea.ts b/ts/editor/editingArea.ts index 5d217aee9..f03f62dfd 100644 --- a/ts/editor/editingArea.ts +++ b/ts/editor/editingArea.ts @@ -10,6 +10,7 @@ import type { Codable } from "./codable"; import { updateActiveButtons } from "./toolbar"; import { bridgeCommand } from "./lib"; +import { caretToEnd } from "./helpers"; import { onInput, onKey, onKeyUp } from "./inputHandlers"; import { onFocus, onBlur } from "./focusHandlers"; @@ -126,10 +127,29 @@ export class EditingArea extends HTMLDivElement { this.editable.blur(); } + hasFocus(): boolean { + return document.activeElement === this; + } + toggleHtmlEdit(): void { - const output = this.codable.toggle(this.fieldHTML); - if (output) { - this.fieldHTML = output; + const hadFocus = this.hasFocus(); + + if (this.codable.active) { + const html = this.codable.teardown(); + this.fieldHTML = html; + + this.editable.hidden = false; + if (hadFocus) { + this.focusEditable(); + caretToEnd(this); + } + } else { + this.editable.hidden = true; + this.codable.setup(this.fieldHTML); + + if (hadFocus) { + this.codable.focus(); + } } } }