2022-03-31 03:17:13 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
|
|
|
|
import {
|
|
|
|
fragmentToString,
|
|
|
|
nodeContainsInlineContent,
|
|
|
|
nodeIsElement,
|
|
|
|
} from "../../lib/dom";
|
|
|
|
import { createDummyDoc } from "../../lib/parsing";
|
2022-10-27 01:11:36 +02:00
|
|
|
import { decoratedElements } from "../decorated-elements";
|
2022-03-31 03:17:13 +02:00
|
|
|
|
|
|
|
function adjustInputHTML(html: string): string {
|
|
|
|
for (const component of decoratedElements) {
|
|
|
|
html = component.toUndecorated(html);
|
|
|
|
}
|
|
|
|
|
|
|
|
return html;
|
|
|
|
}
|
|
|
|
|
|
|
|
function adjustInputFragment(fragment: DocumentFragment): void {
|
|
|
|
if (nodeContainsInlineContent(fragment)) {
|
2022-09-28 03:35:06 +02:00
|
|
|
fragment.appendChild(document.createElement("br"));
|
2022-03-31 03:17:13 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-25 05:42:54 +02:00
|
|
|
export function storedToFragment(storedHTML: string): DocumentFragment {
|
2022-03-31 03:17:13 +02:00
|
|
|
/* We need .createContextualFragment so that customElements are initialized */
|
|
|
|
const fragment = document
|
|
|
|
.createRange()
|
2022-04-25 05:42:54 +02:00
|
|
|
.createContextualFragment(createDummyDoc(adjustInputHTML(storedHTML)));
|
2022-03-31 03:17:13 +02:00
|
|
|
|
|
|
|
adjustInputFragment(fragment);
|
|
|
|
return fragment;
|
|
|
|
}
|
|
|
|
|
|
|
|
function adjustOutputFragment(fragment: DocumentFragment): void {
|
|
|
|
if (
|
2022-09-28 03:35:06 +02:00
|
|
|
fragment.hasChildNodes() &&
|
|
|
|
nodeIsElement(fragment.lastChild!) &&
|
2022-03-31 03:17:13 +02:00
|
|
|
nodeContainsInlineContent(fragment) &&
|
2022-09-28 03:35:06 +02:00
|
|
|
fragment.lastChild!.tagName === "BR"
|
2022-03-31 03:17:13 +02:00
|
|
|
) {
|
2022-09-28 03:35:06 +02:00
|
|
|
fragment.lastChild!.remove();
|
2022-03-31 03:17:13 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function adjustOutputHTML(html: string): string {
|
|
|
|
for (const component of decoratedElements) {
|
|
|
|
html = component.toStored(html);
|
|
|
|
}
|
|
|
|
|
|
|
|
return html;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function fragmentToStored(fragment: DocumentFragment): string {
|
|
|
|
const clone = document.importNode(fragment, true);
|
|
|
|
adjustOutputFragment(clone);
|
|
|
|
|
2022-04-25 05:42:54 +02:00
|
|
|
const storedHTML = adjustOutputHTML(fragmentToString(clone));
|
|
|
|
return storedHTML;
|
2022-03-31 03:17:13 +02:00
|
|
|
}
|