anki/ts/editor/codable.ts

49 lines
1.2 KiB
TypeScript
Raw Normal View History

2021-06-17 13:46:25 +02:00
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
2021-06-17 18:36:12 +02:00
import * as CodeMirror from "codemirror/lib/codemirror";
import "codemirror/mode/htmlmixed/htmlmixed";
2021-06-17 14:44:03 +02:00
2021-06-17 17:08:33 +02:00
const codeMirrorOptions = {
lineNumbers: true,
2021-06-17 17:18:00 +02:00
lineWrapping: true,
2021-06-17 17:08:33 +02:00
mode: "htmlmixed",
2021-06-17 17:18:00 +02:00
theme: "monokai",
};
2021-06-17 15:30:05 +02:00
const parser = new DOMParser();
2021-06-17 13:46:25 +02:00
export class Codable extends HTMLTextAreaElement {
codeMirror: CodeMirror | undefined;
active: boolean;
constructor() {
super();
this.active = false;
}
2021-06-17 17:08:33 +02:00
2021-06-17 14:44:03 +02:00
connectedCallback(): void {
2021-06-17 15:30:05 +02:00
this.setAttribute("hidden", "");
2021-06-17 17:08:33 +02:00
}
toggle(html: string): string {
2021-06-17 17:18:00 +02:00
return this.codeMirror ? this.teardown() : this.setup(html);
2021-06-17 17:08:33 +02:00
}
setup(html: string): string {
this.active = true;
this.value = html;
2021-06-17 17:08:33 +02:00
this.codeMirror = CodeMirror.fromTextArea(this, codeMirrorOptions);
return "";
2021-06-17 17:08:33 +02:00
}
teardown(): string {
this.active = false;
2021-06-17 17:08:33 +02:00
this.codeMirror.toTextArea();
this.codeMirror = undefined;
const doc = parser.parseFromString(this.value, "text/html");
return doc.documentElement.innerHTML;
2021-06-17 14:44:03 +02:00
}
2021-06-17 13:46:25 +02:00
}