anki/ts/editor/codable.ts

71 lines
1.8 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 20:27:34 +02:00
import "codemirror/addon/fold/foldcode";
import "codemirror/addon/fold/foldgutter";
import "codemirror/addon/fold/xml-fold";
import "codemirror/addon/edit/matchtags.js";
2021-06-17 14:44:03 +02:00
2021-06-17 17:08:33 +02:00
const codeMirrorOptions = {
mode: "htmlmixed",
2021-06-17 17:18:00 +02:00
theme: "monokai",
lineNumbers: true,
lineWrapping: true,
2021-06-17 20:27:34 +02:00
foldGutter: true,
gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
matchTags: { bothTags: true },
viewportMargin: Infinity,
2021-06-17 17:18:00 +02:00
};
2021-06-17 15:30:05 +02:00
const parser = new DOMParser();
function parseHTML(html: string): string {
const doc = parser.parseFromString(html, "text/html");
return doc.documentElement.innerHTML;
}
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
set fieldHTML(content: string) {
this.value = content;
}
get fieldHTML(): string {
return parseHTML(this.codeMirror.getValue());
}
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
}
setup(html: string): void {
this.active = true;
this.fieldHTML = html;
2021-06-17 17:08:33 +02:00
this.codeMirror = CodeMirror.fromTextArea(this, codeMirrorOptions);
}
focus(): void {
this.codeMirror.focus();
}
caretToEnd(): void {
this.codeMirror.setCursor(this.codeMirror.lineCount(), 0);
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;
return parseHTML(this.value);
2021-06-17 14:44:03 +02:00
}
2021-06-17 13:46:25 +02:00
}