Skip to content

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

6.7 KB
Raw Blame
import {getFrontend, isMobile} from "../util/functions";
import {Dialog} from "../dialog";
import {closeNativeSettings, openNativeSettings} from "../config/setting/nativeWindow";
import {isSettingsWindow} from "../config/setting/windowContext";
import {fitSettingsWindowDialog} from "../config/setting/windowDialog";
import {genUUID} from "../util/genID";

export class Setting {
    private items: IPluginSettingOption[] = [];
    private confirmCallback: () => void;
    private destroyCallback: () => void;
    private width: string;
    private height: string;
    private openInWindow: boolean;
    private windowKey = "plugin-" + genUUID();
    private windowOpen = false;
    private closeWindowCallback: () => void;
    private windowSession = 0;
    public dialog:Dialog;

    constructor(options: {
        height?: string,
        width?: string,
        destroyCallback?: () => void
        confirmCallback?: () => void
        openInWindow?: boolean
    }) {
        this.confirmCallback = options.confirmCallback;
        this.destroyCallback = options.destroyCallback;
        this.width = options.width || (isMobile() ? "92vw" : "768px");
        this.height = options.height || "80vh";
        this.openInWindow = options.openInWindow === true;
    }

    public addItem(options: IPluginSettingOption) {
        this.items.push(options);
    }

    public open(name: string) {
        if (this.openInWindow && getFrontend().startsWith("desktop") && !isSettingsWindow()) {
            if (!this.windowOpen) {
                this.windowOpen = true;
                this.windowSession++;
            }
            const session = this.windowSession;
            const closed = () => {
                if (!this.windowOpen || session !== this.windowSession) return;
                this.windowOpen = false;
                this.dialog = undefined;
                this.items.forEach(item => {
                    if (item.actionElement && item.actionElement.ownerDocument !== document) {
                        document.adoptNode(item.actionElement);
                    }
                });
                this.destroyCallback?.();
            };
            this.closeWindowCallback = closed;
            void openNativeSettings(window.siyuan.ws.app, {}, {
                name, closed, isOpen: () => this.windowOpen && session === this.windowSession,
                mount: create => {
                    this.dialog = create({width: this.width, height: this.height, items: this.items,
                        confirmCallback: this.confirmCallback, destroyCallback: closed});
                },
            }, this.windowKey).catch(error => {
                closed();
                console.error(error);
            });
            return;
        }
        const windowRoot = isSettingsWindow() && window.siyuan.dialogs.length === 0;
        const dialog = new Dialog({
            title: name,
            content: `<div class="b3-dialog__content">
</div>
<div class="b3-dialog__action${this.confirmCallback ? "" : " fn__none"}">
    <button class="b3-button b3-button--cancel">${window.siyuan.languages.cancel}</button>
    <div class="fn__space${this.confirmCallback ? "" : " fn__none"}"></div>
    <button class="b3-button b3-button--text${this.confirmCallback ? "" : " fn__none"}">${window.siyuan.languages.save}</button>
</div>`,
            width: this.width,
            height: this.height,
            destroyCallback: () => {
                if (this.destroyCallback) {
                    this.destroyCallback();
                }
                if (windowRoot) {
                    window.close();
                }
            }
        });
        const contentElement = dialog.element.querySelector(".b3-dialog__content");
        this.items.forEach((item) => {
            let html = "";
            let actionElement = item.actionElement;
            if (!item.actionElement && item.createActionElement) {
                actionElement = item.createActionElement();
            }
            const tagName = actionElement?.classList.contains("b3-switch") ? "label" : "div";
            if (typeof item.direction === "undefined") {
                item.direction = (!actionElement || "TEXTAREA" === actionElement.tagName) ? "row" : "column";
            }
            const titleBlock = `<div class="config-name">${item.title}</div>
        ${item.description ? `<div class="b3-label__text">${item.description}</div>` : ""}`;
            if (item.direction === "row") {
                html = `<${tagName} class="b3-label config-item">
    <div class="fn__block">
        ${titleBlock}
        <div class="fn__hr"></div>
    </div>
</${tagName}>`;
            } else {
                html = `<${tagName} class="fn__flex b3-label config-item">
    <div class="fn__flex-1">
        ${titleBlock}
    </div>
    <span class="fn__space${actionElement ? "" : " fn__none"}"></span>
</${tagName}>`;
            }
            contentElement.insertAdjacentHTML("beforeend", html);
            if (actionElement) {
                if (["INPUT", "TEXTAREA"].includes(actionElement.tagName)) {
                    dialog.bindInput(actionElement as HTMLInputElement, () => {
                        btnsElement[1].dispatchEvent(new CustomEvent("click"));
                    }, actionElement.tagName === "INPUT");
                }
                if (item.direction === "row") {
                    contentElement.lastElementChild.lastElementChild.insertAdjacentElement("beforeend", actionElement);
                    actionElement.classList.add("fn__block");
                } else {
                    actionElement.classList.remove("fn__block");
                    actionElement.classList.add("fn__flex-center");
                    if (!actionElement.classList.contains("b3-switch")) {
                        actionElement.classList.add("fn__size200");
                    }
                    contentElement.lastElementChild.insertAdjacentElement("beforeend", actionElement);
                }
            }
        });
        (contentElement.querySelector("input, textarea") as HTMLElement)?.focus();
        const btnsElement = dialog.element.querySelectorAll(".b3-dialog__action .b3-button");
        btnsElement[0].addEventListener("click", () => {
            dialog.destroy();
        });
        btnsElement[1].addEventListener("click", () => {
            if (this.confirmCallback) {
                this.confirmCallback();
            }
            dialog.destroy();
        });
        this.dialog = dialog;
        if (windowRoot) {
            fitSettingsWindowDialog(dialog);
        }
    }

    public close() {
        if (this.windowOpen) {
            closeNativeSettings(this.windowKey);
            this.closeWindowCallback?.();
        } else {
            this.dialog?.destroy();
        }
    }
}