anki/ts/editor/codable.ts

90 lines
2.3 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 21:45:11 +02:00
import "codemirror/addon/edit/closetag.js";
2021-06-17 14:44:03 +02:00
2021-06-18 00:27:07 +02:00
import { setCodableButtons } from "./toolbar";
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 },
2021-06-17 21:45:11 +02:00
autoCloseTags: true,
2021-06-18 01:32:46 +02:00
extraKeys: { Tab: false, "Shift-Tab": false },
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.body.innerHTML;
}
2021-06-17 13:46:25 +02:00
export class Codable extends HTMLTextAreaElement {
codeMirror: CodeMirror | undefined;
get active(): boolean {
return Boolean(this.codeMirror);
}
2021-06-17 17:08:33 +02:00
set fieldHTML(content: string) {
if (this.active) {
this.codeMirror.setValue(content);
} else {
this.value = content;
}
}
get fieldHTML(): string {
return parseHTML(this.active ? this.codeMirror.getValue() : this.value);
}
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.fieldHTML = html;
2021-06-17 17:08:33 +02:00
this.codeMirror = CodeMirror.fromTextArea(this, codeMirrorOptions);
}
teardown(): string {
this.codeMirror.toTextArea();
this.codeMirror = undefined;
return this.fieldHTML;
}
focus(): void {
this.codeMirror.focus();
2021-06-18 00:27:07 +02:00
setCodableButtons();
}
caretToEnd(): void {
this.codeMirror.setCursor(this.codeMirror.lineCount(), 0);
2021-06-17 17:08:33 +02:00
}
surroundSelection(before: string, after: string): void {
const selection = this.codeMirror.getSelection();
this.codeMirror.replaceSelection(before + selection + after);
}
onEnter(): void {
/* default */
}
onPaste(): void {
/* default */
2021-06-17 14:44:03 +02:00
}
2021-06-17 13:46:25 +02:00
}