anki/ts/editor/editable.ts

44 lines
1.1 KiB
TypeScript
Raw Normal View History

2021-04-13 10:57:08 +02:00
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { nodeIsInline, caretToEnd } from "./helpers";
function containsInlineContent(field: Element): boolean {
if (field.childNodes.length === 0) {
// for now, for all practical purposes, empty fields are in block mode
return false;
}
for (const child of field.children) {
if (!nodeIsInline(child)) {
return false;
}
}
return true;
}
export class Editable extends HTMLElement {
set fieldHTML(content: string) {
this.innerHTML = content;
if (containsInlineContent(this)) {
this.appendChild(document.createElement("br"));
}
}
get fieldHTML(): string {
return containsInlineContent(this) && this.innerHTML.endsWith("<br>")
? this.innerHTML.slice(0, -4) // trim trailing <br>
: this.innerHTML;
}
2021-05-06 23:33:28 +02:00
connectedCallback(): void {
this.setAttribute("contenteditable", "");
}
caretToEnd() {
caretToEnd(this);
}
}