Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

2.7 KB
Raw Blame
import {addScript} from "../util/addScript";
import {isFoldedRenderContent} from "./foldedContent";
import {Constants} from "../../constants";
import {genIconHTML} from "./util";
import {hasClosestByClassName} from "../util/hasClosest";
import {looseJsonParse} from "../../util/functions";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {MERMAID_SANITIZE_OPTIONS} from "./mermaidSanitize";

const ABCJS_PARAMS_KEY = "%%params";

// Read the abcjsParams from the content if it exists.
// The params *must* be the first line of the content in the form:
// %%params JSON
const getAbcParams = (abcString: string): any => {
    let params = {
        responsive: "resize",
    };
    const firstLine = abcString.substring(0, abcString.indexOf("\n"));
    if (firstLine.startsWith(ABCJS_PARAMS_KEY)) {
        try {
            params = looseJsonParse(firstLine.substring(ABCJS_PARAMS_KEY.length));
        } catch (e) {
            console.error(`Failed to parse ABCJS params: ${e}`);
        }
    }
    return params;
};

export const abcRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
    let abcElements: Element[] | NodeListOf<Element> = [];
    if (element.getAttribute("data-subtype") === "abc" && element.getAttribute("data-render") !== "true") {
        abcElements = [element];
    } else {
        abcElements = element.querySelectorAll('[data-subtype="abc"]:not([data-render="true"])');
    }
    abcElements = Array.from(abcElements).filter(item => !isFoldedRenderContent(item));
    if (abcElements.length === 0) {
        return;
    }
    addScript(`${cdn}/js/abcjs/abcjs-basic-min.js?v=6.7.1`, "protyleAbcjsScript").then(() => {
        const wysiwygElement = hasClosestByClassName(element, "protyle-wysiwyg", true);
        abcElements.forEach((e: HTMLDivElement) => {
            e.setAttribute("data-render", "true");
            if (!e.firstElementChild.classList.contains("protyle-icons")) {
                e.insertAdjacentHTML("afterbegin", genIconHTML(wysiwygElement));
            }
            const renderElement = e.firstElementChild.nextElementSibling as HTMLElement;
            renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false"></div>`;
            const abcString = Lute.UnEscapeHTMLStr(e.getAttribute("data-content"));
            window.ABCJS.renderAbc(renderElement.lastElementChild, abcString, getAbcParams(abcString));
            if (getHostCapabilities().remoteKernel) {
                renderElement.lastElementChild.innerHTML = window.DOMPurify.sanitize(
                    renderElement.lastElementChild.innerHTML, MERMAID_SANITIZE_OPTIONS);
            }
        });
    });
};