Skip to content

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

54.5 KB
Raw Blame
import {confirmDialog} from "../../dialog/confirmDialog";
import {showMessage} from "../../dialog/message";
import {escapeAttr, escapeHtml} from "../../util/escape";
import {genUUID} from "../../util/genID";
import {
    entryCatalog,
    getEntryCatalogChildren,
    getEntryCatalogPathChain,
    IEntryCatalogNode,
    IEntryCatalogSection,
    isEntryCatalogNodeConfigurable,
    isEntryOrderSortable,
    refreshDockCatalog,
    refreshSlashMenuCatalog,
    refreshTopBarCatalog,
    refreshToolbarCatalogEntries,
    SLASH_MENU_FREQUENT_PATH,
    TOP_BAR_ROOT_PATH,
    STATUS_BAR_ROOT_PATH,
} from "./catalog";
import {
    createEntryProfileSnapshot,
    createEntryOrderSnapshot,
    ENTRY_PROFILE_FULL,
    ENTRY_PROFILE_SIMPLE,
    ENTRY_VISIBILITY_VERSION,
    getActiveEntryProfile,
    getEntryProfileDefaultVisibility,
    saveEntryVisibility,
    TEntryVisibilityTemplate,
} from "./runtime";
import {
    mergeEntryOrderPreservingUnknown,
    moveEntryOrder,
    resolveEntryOrder,
    resolveEntryOrderWithBoundaryDefaults,
} from "./order";
import {
    getProfileEntryVisibility,
    getSavedEntryOrder,
    isEntryVisibilityImportVersionSupported,
    normalizeEntryVisibilityImportProfile,
    resetEntryProfileOrder,
    TEntryVisibilityImportProfile,
} from "./profile";
import {getHostCapabilities} from "../../util/hostCapabilities";
import {isMobile} from "../../util/functions";
import {isInMobileApp} from "../../protyle/util/compatibility";
import {bindTouchOrder} from "./touchOrder";
import {TOOLBAR_ENTRY_ROOT_PATH} from "../../protyle/toolbar/defaults";
import {MOBILE_TOOLBAR_CONTEXT_KEYS} from "./mobileToolbarContext";
import {getSettingsOwnerApp} from "../setting/windowContext";
/// #if !MOBILE
import {getSettingsWindowHost, isSettingsWindow} from "../setting/windowContext";
import {getEditorToolbarCatalogSnapshot} from "../../protyle/toolbar/catalogSnapshot";
/// #endif
import {
    DOCK_ORDER_SCOPES,
    DOCK_ORDER_SCOPES_BY_SIDE,
    getDockEntryOrderSnapshot,
    getDefaultDockEntryOrderSnapshot,
    getDockOrderScopeLabelKey,
    isDockOrderScope,
    mergeDockEntryOrderSnapshot,
    moveDockEntryOrderSnapshot,
    TDockOrderScope,
    TDockOrderSnapshot,
} from "./dockOrder";

const getVisibleEntryCatalog = () => isMobile() ? entryCatalog.filter(item =>
    item.key === TOOLBAR_ENTRY_ROOT_PATH || item.key === "editor.slash" || item.key === "editor.image" ||
    item.key === "editor.blockEmbed")
    .map(item => item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, sortable: false,
        children: item.children.filter(child => MOBILE_TOOLBAR_CONTEXT_KEYS.includes(child.key))} : item) : entryCatalog.map(item =>
    item.key === TOOLBAR_ENTRY_ROOT_PATH ? {...item, children: item.children.filter(child => !child.key.startsWith("mobile-"))} :
    item.key === TOP_BAR_ROOT_PATH && !isInMobileApp() ?
        {...item, children: item.children.filter(child => child.key !== "barExit")} : item);

type TImportFile = {
    type: "siyuan-entry-profile" | "siyuan-entry-profile-bundle";
    version: number;
    profile?: TEntryVisibilityImportProfile;
    profiles?: TEntryVisibilityImportProfile[];
};

const cloneConfig = () => JSON.parse(JSON.stringify(
    window.siyuan.config.appearance.entryVisibility
)) as Config.IEntryVisibility;

const templateLabel = (template: TEntryVisibilityTemplate) => template === ENTRY_PROFILE_SIMPLE
    ? window.siyuan.languages.entrySimple
    : window.siyuan.languages.entryFull;

const uniqueName = (name: string, profiles = window.siyuan.config.appearance.entryVisibility.profiles) => {
    const normalized = name.trim() || window.siyuan.languages.entryCustomProfile;
    if (!profiles.some((item) => item.name === normalized)) {
        return normalized;
    }
    let index = 2;
    while (profiles.some((item) => item.name === `${normalized} (${index})`)) {
        index++;
    }
    return `${normalized} (${index})`;
};

const downloadJSON = (name: string, data: unknown) => {
    if (!getHostCapabilities().importExport) {
        return;
    }
    const blob = new Blob([JSON.stringify(data, undefined, 2)], {type: "application/json"});
    const url = URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = name.replace(/[\\/:*?"<>|]/g, "-");
    anchor.click();
    URL.revokeObjectURL(url);
};

const exportProfile = (profile: Config.IEntryVisibilityProfile) => {
    downloadJSON(`${profile.name}.siyuan-entry.json`, {
        type: "siyuan-entry-profile",
        version: ENTRY_VISIBILITY_VERSION,
        profile,
    } satisfies TImportFile);
};

const exportBundle = () => {
    downloadJSON("入口方案.siyuan-entry-bundle.json", {
        type: "siyuan-entry-profile-bundle",
        version: ENTRY_VISIBILITY_VERSION,
        profiles: window.siyuan.config.appearance.entryVisibility.profiles,
    } satisfies TImportFile);
};

const createProfile = (template: TEntryVisibilityTemplate, current = false, name?: string) => {
    const profile: Config.IEntryVisibilityProfile = {
        id: genUUID(),
        name: uniqueName(name || window.siyuan.languages.entryCustomProfile),
        defaults: template,
        entries: {},
        orders: createEntryOrderSnapshot(current),
    };
    if (current) {
        const active = getActiveEntryProfile();
        profile.defaults = active?.defaults || (active ? undefined :
            window.siyuan.config.appearance.entryVisibility.active === ENTRY_PROFILE_SIMPLE ? ENTRY_PROFILE_SIMPLE : ENTRY_PROFILE_FULL);
        profile.entries = {...active?.entries};
    }
    return profile;
};

const duplicateProfile = (profile: Config.IEntryVisibilityProfile) => {
    const copy = JSON.parse(JSON.stringify(profile)) as Config.IEntryVisibilityProfile;
    copy.id = genUUID();
    copy.name = uniqueName(`${profile.name} ${window.siyuan.languages.duplicateCopy}`);
    copy.orders ||= createEntryOrderSnapshot();
    return copy;
};

const getEntryViewHost = (root: HTMLElement) => root.closest<HTMLElement>(".config__tab-container") || root;

const getEntryViews = (root: HTMLElement) => Array.from(getEntryViewHost(root).children)
    .filter((element): element is HTMLElement =>
        element instanceof HTMLElement && element.classList.contains("config-entry-visibility__view"));

const removeEntryView = (root: HTMLElement, view?: HTMLElement) => {
    const views = view ? [view] : getEntryViews(root);
    views.forEach((item) => {
        const remove = () => {
            if (!item.parentElement) {
                return;
            }
            item.remove();
            root.dispatchEvent(new CustomEvent("siyuan-entry-profile-closed", {bubbles: true}));
        };
        item.classList.remove("config__view--show");
        item.addEventListener("transitionend", (event) => {
            if (event.propertyName === "opacity") {
                remove();
            }
        });
        window.setTimeout(remove, 300);
    });
};

const createEntryView = (root: HTMLElement) => {
    removeEntryView(root);
    const view = document.createElement("div");
    view.className = "config-entry-visibility__view config__view";
    if (isMobile()) {
        view.classList.add("config-entry-visibility__view--mobile");
    }
    view.innerHTML = `<div class="b3-dialog__header fn__flex">
    <div class="block__logo fn__pointer fn__flex-1" data-action="back">
        <svg class="block__logoicon"><use xlink:href="#iconLeft"></use></svg>
        <span class="ft__breakword">${window.siyuan.languages.entryVisibility}</span>
    </div>
</div>
<div class="b3-dialog__body fn__flex-1"></div>`;
    getEntryViewHost(root).append(view);
    view.getBoundingClientRect();
    view.classList.add("config__view--show");
    return view;
};

const profileCard = (
    id: string,
    name: string,
    builtin: boolean,
    active: boolean,
) => `<div class="b3-card${active ? " b3-card--current" : ""}" data-profile-id="${escapeAttr(id)}" data-action="${builtin ? "view" : "edit"}">
    <div class="fn__flex-1 fn__flex-column">
        <div class="b3-card__info b3-card__info--left fn__flex-1">
            <div class="fn__ellipsis config-name">${escapeHtml(name)}</div>
            <div class="b3-card__desc">${builtin ? window.siyuan.languages.entryBuiltin : window.siyuan.languages.entryCustom}${active ? ` · ${window.siyuan.languages.current}` : ""}${builtin ? ` · ${id === ENTRY_PROFILE_SIMPLE ? window.siyuan.languages.entrySimpleTip : window.siyuan.languages.entryFullTip}` : ""}</div>
        </div>
    </div>
    <div class="b3-card__actions b3-card__actions--right">
        ${active ? "" : `<button class="b3-button b3-button--outline" data-action="activate">${window.siyuan.languages.use}</button>`}
        <button class="block__icon block__icon--show ariaLabel" data-action="duplicate" data-position="north" aria-label="${window.siyuan.languages.duplicateCopy}"><svg><use xlink:href="#iconCopy"></use></svg></button>
        ${builtin || !getHostCapabilities().importExport ? "" : `<button class="block__icon block__icon--show ariaLabel" data-action="export" data-position="north" aria-label="${window.siyuan.languages.export}"><svg><use xlink:href="#iconDownload"></use></svg></button>`}
        <button class="block__icon block__icon--show${builtin ? " fn__none" : " block__icon--warning"} ariaLabel" data-action="delete" data-position="north" aria-label="${window.siyuan.languages.delete}"><svg><use xlink:href="#iconTrashcan"></use></svg></button>
    </div>
</div>`;

const renderProfileCards = (root: HTMLElement) => {
    const container = root.querySelector<HTMLElement>("[data-type='entry-profiles']");
    if (!container) {
        return;
    }
    const config = window.siyuan.config.appearance.entryVisibility;
    const cards = [
        profileCard(ENTRY_PROFILE_SIMPLE, window.siyuan.languages.entrySimple, true,
            config.active === ENTRY_PROFILE_SIMPLE),
        profileCard(ENTRY_PROFILE_FULL, window.siyuan.languages.entryFull, true,
            config.active === ENTRY_PROFILE_FULL),
        ...config.profiles.map((profile) => profileCard(profile.id, profile.name, false,
            config.active === profile.id)),
    ];
    container.innerHTML = `<div class="b3-cards b3-cards--nowrap">${cards.join("")}</div>`;
};

const resolveProfileEntryOrder = (profile: Config.IEntryVisibilityProfile, parentPath: string,
                                  defaultOrder: string[], separatorKeys: Set<string>) => {
    if (parentPath === TOP_BAR_ROOT_PATH) {
        return resolveEntryOrderWithBoundaryDefaults(defaultOrder, profile.orders?.[parentPath], "drag", separatorKeys);
    }
    if (parentPath === STATUS_BAR_ROOT_PATH) {
        return resolveEntryOrderWithBoundaryDefaults(defaultOrder, profile.orders?.[parentPath], "spacer", separatorKeys);
    }
    return resolveEntryOrder(defaultOrder, getSavedEntryOrder(profile, parentPath, defaultOrder), separatorKeys);
};

const getProfileEntryOrder = (profile: Config.IEntryVisibilityProfile, parentPath: string,
                              nodes = getEntryCatalogChildren(parentPath) || []) => resolveProfileEntryOrder(
    profile,
    parentPath,
    nodes.map((item) => item.key),
    new Set(nodes.filter((item) => item.type === "separator").map((item) => item.key)),
);

const orderEntryNodes = (profile: Config.IEntryVisibilityProfile, parentPath: string,
                         nodes: IEntryCatalogNode[]) => {
    const indexes = new Map(getProfileEntryOrder(profile, parentPath, nodes).map((key, index) => [key, index]));
    return [...nodes].sort((itemA, itemB) =>
        (indexes.get(itemA.key) ?? Number.MAX_SAFE_INTEGER) - (indexes.get(itemB.key) ?? Number.MAX_SAFE_INTEGER));
};

const renderEntrySwitch = (profile: Config.IEntryVisibilityProfile, path: string, item: IEntryCatalogNode,
                           parentEnabled: boolean, readOnly: boolean,
                           label = item.type === "separator" ? window.siyuan.languages.entrySeparator : item.label()) => {
    return `<input class="b3-switch" type="checkbox"
    aria-label="${escapeAttr(label)}" data-entry-path="${escapeAttr(path)}"${readOnly ? ' data-entry-readonly aria-disabled="true"' : ""}
    ${!parentEnabled && !readOnly ? " disabled" : ""}${getProfileEntryVisibility(profile, path,
        getEntryProfileDefaultVisibility(profile, path)) ? " checked" : ""}>`;
};

const renderEntryRows = (profile: Config.IEntryVisibilityProfile, prefix: string,
                         nodes: IEntryCatalogNode[], depth: number, selectedPaths: string[],
                         parentEnabled: boolean, readOnly: boolean, sortable: boolean,
                         getItemPath = (item: IEntryCatalogNode) => `${prefix}.${item.key}`) => nodes.map((item) => {
        const path = getItemPath(item);
        const configurable = isEntryCatalogNodeConfigurable(item);
        const draggable = sortable && parentEnabled && configurable;
        if (item.type === "separator") {
            const separatorIndex = (getEntryCatalogChildren(prefix) || nodes)
                .filter(node => node.type === "separator").findIndex(node => node.key === item.key) + 1;
            const label = window.siyuan.languages.entrySeparator +
                (prefix === TOOLBAR_ENTRY_ROOT_PATH ? ` ${separatorIndex}` : "");
            return `<div class="config-entry-visibility__row config-entry-visibility__row--separator${parentEnabled ? "" : " config-entry-visibility__row--disabled"}${readOnly ? " config-entry-visibility__row--readonly" : ""}"
                data-entry-row data-entry-key="${escapeAttr(item.key)}" data-entry-parent="${escapeAttr(prefix)}">
                ${draggable ? `<span class="block__icon block__icon--show config-entry-visibility__drag" draggable="${!isMobile()}"><svg><use xlink:href="#iconDrag"></use></svg></span>` : ""}
                <span class="config-entry-visibility__label">${escapeHtml(label)}</span>
                ${renderEntrySwitch(profile, path, item, parentEnabled, readOnly, label)}
                <span class="config-entry-visibility__arrow-space"></span>
            </div>`;
        }
        const label = item.label();
        const hasChildren = Boolean(item.children?.length);
        const selected = selectedPaths[depth] === path;
        const rowTag = hasChildren || !configurable ? "div" : "label";
        const rowType = hasChildren ? "navigable" : configurable ? "toggleable" : "fixed";
        return `<${rowTag} class="config-entry-visibility__row config-entry-visibility__row--${rowType}${selected ? " config-entry-visibility__row--current" : ""}${parentEnabled ? "" : " config-entry-visibility__row--disabled"}${readOnly ? " config-entry-visibility__row--readonly" : ""}"
            data-entry-row data-entry-key="${escapeAttr(item.key)}" data-entry-parent="${escapeAttr(prefix)}" data-entry-path-row="${escapeAttr(path)}"${hasChildren ? ` data-action="navigate-entry" data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}"` : ""}>
            ${draggable ? `<span class="block__icon block__icon--show config-entry-visibility__drag" draggable="${!isMobile()}"><svg><use xlink:href="#iconDrag"></use></svg></span>` : ""}
            ${hasChildren ? `<button class="config-entry-visibility__navigate" data-action="navigate-entry"
                data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}" title="${escapeAttr(label)}">
                <span>${escapeHtml(label)}</span>
            </button>` : `<span class="config-entry-visibility__label" title="${escapeAttr(label)}">${escapeHtml(label)}</span>`}
            ${configurable ? renderEntrySwitch(profile, path, item, parentEnabled, readOnly) : ""}
            ${hasChildren ? `<button class="block__icon block__icon--show config-entry-visibility__arrow" data-action="navigate-entry"
                data-entry-path="${escapeAttr(path)}" data-entry-depth="${depth}" aria-label="${escapeAttr(window.siyuan.languages.expand)}">
                <svg><use xlink:href="#iconRight"></use></svg>
            </button>` : '<span class="config-entry-visibility__arrow-space"></span>'}
        </${rowTag}>`;
    }).join("");

const renderEntryColumn = (profile: Config.IEntryVisibilityProfile, title: string, prefix: string,
                           nodes: IEntryCatalogNode[], depth: number, selectedPaths: string[],
                           parentEnabled: boolean, readOnly: boolean, sortable: boolean,
                           getItemPath = (item: IEntryCatalogNode) => `${prefix}.${item.key}`) => `<section class="config-entry-visibility__column"
    data-entry-column data-entry-depth="${depth}">
    <div class="config-entry-visibility__column-title">
        ${isMobile() && depth > 0 ? `<button class="block__icon block__icon--show" data-action="back-entry"
            data-entry-parent="${escapeAttr(prefix)}" aria-label="${escapeAttr(window.siyuan.languages.back)}">
            <svg><use xlink:href="#iconLeft"></use></svg>
        </button>` : ""}
        <span class="fn__ellipsis fn__flex-1" title="${escapeAttr(title)}">${escapeHtml(title)}</span>
        ${sortable ? renderOrderReset(prefix) : ""}
    </div>
    <div class="config-entry-visibility__column-list">
        ${renderEntryRows(profile, prefix, nodes.filter(item => `${prefix}.${item.key}` === SLASH_MENU_FREQUENT_PATH),
            depth, selectedPaths, true, readOnly, false, getItemPath)}
        ${renderEntryRows(profile, prefix, nodes.filter(item => `${prefix}.${item.key}` !== SLASH_MENU_FREQUENT_PATH),
            depth, selectedPaths, parentEnabled, readOnly, sortable, getItemPath)}
    </div>
</section>`;

const renderOrderReset = (prefix?: string) => `<button class="block__icon block__icon--show ariaLabel"
    data-action="${prefix ? "reset-entry-order" : "reset-all-entry-orders"}"${prefix ? ` data-entry-parent="${escapeAttr(prefix)}"` : ""} data-position="north"
    aria-label="${escapeAttr(window.siyuan.languages[prefix ? "entryResetOrder" : "entryResetAllOrders"])}">
    <svg><use xlink:href="#iconRefresh"></use></svg>
</button>`;

const getDirectDisplayRoot = (section: IEntryCatalogSection) => section.children.length === 1 &&
    section.children[0].displayChildrenDirectly
    ? section.children[0]
    : undefined;

const renderEntryLocation = (profile: Config.IEntryVisibilityProfile, item: IEntryCatalogSection,
                             current: boolean, readOnly: boolean) => {
    const label = item.label();
    const className = `b3-list-item config-entry-visibility__location${current ? " config-entry-visibility__location--current" : ""}`;
    const directDisplayRoot = getDirectDisplayRoot(item);
    if (!directDisplayRoot) {
        return `<button class="${className}" data-action="select-entry-section"
            data-entry-section="${escapeAttr(item.key)}" title="${escapeAttr(label)}">
            <span class="b3-list-item__text">${escapeHtml(label)}</span>
            <svg class="b3-list-item__arrow"><use xlink:href="#iconRight"></use></svg>
        </button>`;
    }
    const directDisplayRootPath = `${item.key}.${directDisplayRoot.key}`;
    return `<div class="${className}" data-action="select-entry-section"
        data-entry-section="${escapeAttr(item.key)}">
        <button class="config-entry-visibility__location-navigate" data-action="select-entry-section"
            data-entry-section="${escapeAttr(item.key)}" title="${escapeAttr(label)}">
            <span class="b3-list-item__text">${escapeHtml(label)}</span>
        </button>
        ${renderEntrySwitch(profile, directDisplayRootPath, directDisplayRoot, true, readOnly)}
        <button class="block__icon block__icon--show config-entry-visibility__location-arrow"
            data-action="select-entry-section" data-entry-section="${escapeAttr(item.key)}"
            aria-label="${escapeAttr(window.siyuan.languages.expand)}">
            <svg><use xlink:href="#iconRight"></use></svg>
        </button>
    </div>`;
};

type TDockSide = keyof typeof DOCK_ORDER_SCOPES_BY_SIDE;

const DOCK_SECTION_KEY = "dock";
const DOCK_SIDES = Object.keys(DOCK_ORDER_SCOPES_BY_SIDE) as TDockSide[];
const getDockSideLabel = (side: TDockSide) => `${window.siyuan.languages.entryDock} - ${
    window.siyuan.languages[side === "left" ? "marginLeft" : "marginRight"]}`;

const getEntryOrderContext = (parentPath: string, dockOrderSnapshot: TDockOrderSnapshot) => {
    if (isDockOrderScope(parentPath)) {
        const defaultOrder = [...dockOrderSnapshot[parentPath]];
        const dockNodes = new Map((getEntryCatalogChildren(DOCK_SECTION_KEY) || []).map((item) => [item.key, item]));
        return {
            defaultOrder,
            nodes: defaultOrder.map((key) => dockNodes.get(key))
                .filter((item): item is IEntryCatalogNode => Boolean(item)),
            separatorKeys: new Set<string>(),
        };
    }
    const nodes = getEntryCatalogChildren(parentPath) || [];
    return {
        defaultOrder: nodes.map((item) => item.key),
        nodes,
        separatorKeys: new Set(nodes.filter((item) => item.type === "separator").map((item) => item.key)),
    };
};

const getDockScopeLabel = (scope: TDockOrderScope) => {
    const labelKey = getDockOrderScopeLabelKey(scope);
    return window.siyuan.languages[labelKey] || labelKey;
};

const getDockScopeNodes = (
    scope: TDockOrderScope,
    snapshot: TDockOrderSnapshot,
) => {
    const nodes = new Map((getEntryCatalogChildren(DOCK_SECTION_KEY) || []).map((item) => [item.key, item]));
    return snapshot[scope]
        .map((key) => nodes.get(key))
        .filter((item): item is IEntryCatalogNode => Boolean(item));
};

const renderDockColumns = (
    columns: string[],
    profile: Config.IEntryVisibilityProfile,
    selectedPaths: string[],
    readOnly: boolean,
    snapshot: TDockOrderSnapshot,
    visiblePaths?: Set<string>,
) => {
    const profileSnapshot = mergeDockEntryOrderSnapshot(snapshot, profile.orders);
    DOCK_SIDES.forEach((side) => {
        const groups = DOCK_ORDER_SCOPES_BY_SIDE[side].map((scope) => {
            const scopeLabel = getDockScopeLabel(scope);
            const nodes = getDockScopeNodes(scope, profileSnapshot);
            const visibleNodes = visiblePaths
                ? nodes.filter((item) => visiblePaths.has(`${DOCK_SECTION_KEY}.${item.key}`))
                : nodes;
            return `<section class="config-entry-visibility__dock-group" data-entry-drop-scope="${scope}">
                <div class="config-entry-visibility__dock-group-title">
                    <span class="fn__ellipsis fn__flex-1" title="${escapeAttr(scopeLabel)}">${escapeHtml(scopeLabel)}</span>
                    ${!visiblePaths && !readOnly ? renderOrderReset(scope) : ""}
                </div>
                <div class="config-entry-visibility__dock-list" data-entry-drop-scope="${scope}">
                    ${renderEntryRows(
        profile,
        scope,
        visibleNodes,
        0,
        selectedPaths,
        true,
        readOnly,
        !visiblePaths && !readOnly,
        (item) => `${DOCK_SECTION_KEY}.${item.key}`,
    )}
                    ${visibleNodes.length === 0
        ? `<div class="config-entry-visibility__dock-empty">${window.siyuan.languages.emptyContent}</div>`
        : ""}
                </div>
            </section>`;
        }).join("");
        columns.push(`<section class="config-entry-visibility__column config-entry-visibility__dock-column" data-entry-column>
            <div class="config-entry-visibility__column-title">
                <span class="fn__ellipsis fn__flex-1" title="${escapeAttr(getDockSideLabel(side))}">${escapeHtml(getDockSideLabel(side))}</span>
            </div>
            <div class="config-entry-visibility__column-list">${groups}</div>
        </section>`);
    });
};

const getDockEntrySelectedPaths = (key: string) => [`${DOCK_SECTION_KEY}.${key}`];

const renderEntryColumns = (profile: Config.IEntryVisibilityProfile, sectionKey: string,
                            selectedPaths: string[], readOnly: boolean, visiblePaths?: Set<string>,
                            visibleSectionKeys?: Set<string>, dockOrderSnapshot = getDockEntryOrderSnapshot()) => {
    const catalog = getVisibleEntryCatalog();
    const sections = visibleSectionKeys
        ? catalog.filter((item) => visibleSectionKeys.has(item.key))
        : catalog;
    const section = sections.find((item) => item.key === sectionKey) || sections[0] || catalog[0];
    const locationColumn = `<section class="config-entry-visibility__column config-entry-visibility__column--locations" data-entry-column>
    <div class="config-entry-visibility__column-title">
        <span class="fn__ellipsis fn__flex-1">${window.siyuan.languages.position}</span>
        ${readOnly ? "" : renderOrderReset()}
    </div>
    <div class="config-entry-visibility__column-list">
        ${sections.map((item) => renderEntryLocation(profile, item, item.key === section.key, readOnly)).join("")}
    </div>
</section>`;
    const columns = isMobile() ? [] : [locationColumn];
    if (section.key === DOCK_SECTION_KEY) {
        renderDockColumns(columns, profile, selectedPaths, readOnly, dockOrderSnapshot, visiblePaths);
        return `<div class="config-entry-visibility__columns">${columns.join("")}</div>`;
    }
    const directDisplayRoot = getDirectDisplayRoot(section);
    const directDisplayRootPath = directDisplayRoot ? `${section.key}.${directDisplayRoot.key}` : "";
    const columnSelectedPaths = directDisplayRoot && selectedPaths[0] === directDisplayRootPath
        ? selectedPaths.slice(1)
        : selectedPaths;
    let nodes = directDisplayRoot?.children || section.children;
    let prefix = directDisplayRoot ? directDisplayRootPath : section.key;
    let title = directDisplayRoot?.label() || section.label();
    let parentEnabled = directDisplayRoot
        ? getProfileEntryVisibility(profile, directDisplayRootPath,
            getEntryProfileDefaultVisibility(profile, directDisplayRootPath))
        : true;
    let depth = 0;
    while (nodes.length > 0) {
        const orderedNodes = orderEntryNodes(profile, prefix, nodes);
        const columnNodes = visiblePaths
            ? orderedNodes.filter((item) => item.type !== "separator" && visiblePaths.has(`${prefix}.${item.key}`))
            : orderedNodes;
        if (columnNodes.length === 0) {
            break;
        }
        columns.push(renderEntryColumn(profile, title, prefix, columnNodes, depth, columnSelectedPaths,
            parentEnabled, readOnly, !visiblePaths && isEntryOrderSortable(prefix) && !readOnly));
        const selectedPath = columnSelectedPaths[depth];
        const selectedNode = selectedPath && columnNodes.find((item) => `${prefix}.${item.key}` === selectedPath);
        if (!selectedNode?.children?.length) {
            break;
        }
        parentEnabled = parentEnabled && getProfileEntryVisibility(profile, selectedPath,
            getEntryProfileDefaultVisibility(profile, selectedPath));
        nodes = selectedNode.children;
        prefix = selectedPath;
        title = selectedNode.label();
        depth++;
    }
    return `<div class="config-entry-visibility__columns">${columns.join("")}</div>`;
};

interface IEntrySearchResult {
    section: IEntryCatalogSection;
    item: IEntryCatalogNode;
    path: string;
    labels: string[];
}

const getEntrySearchResults = (query: string) => {
    const results: IEntrySearchResult[] = [];
    const visit = (section: IEntryCatalogSection, prefix: string, nodes: IEntryCatalogNode[], labels: string[]) => {
        nodes.forEach((item) => {
            if (item.type === "separator" || !isEntryCatalogNodeConfigurable(item)) {
                return;
            }
            const path = `${prefix}.${item.key}`;
            const itemLabels = [...labels, item.label()];
            if (itemLabels.join(" - ").toLowerCase().includes(query)) {
                results.push({section, item, path, labels: itemLabels});
            }
            if (item.children) {
                visit(section, path, item.children, itemLabels);
            }
        });
    };
    getVisibleEntryCatalog().forEach((section) => {
        visit(section, section.key, section.children, [section.label()]);
    });
    return results;
};

const getEntrySearchFilter = (query: string) => {
    const results = getEntrySearchResults(query);
    const visiblePaths = new Set<string>();
    const visibleSectionKeys = new Set<string>();
    results.forEach((result) => {
        visibleSectionKeys.add(result.section.key);
        getEntryCatalogPathChain(result.section.key, result.path).forEach((path) => visiblePaths.add(path));
    });
    return {results, visiblePaths, visibleSectionKeys};
};

const getProfileDockOrderSnapshot = (builtin: boolean) => {
    let snapshot: TDockOrderSnapshot;
    /// #if !MOBILE
    if (isSettingsWindow()) {
        try {
            const ownerSnapshot = getSettingsWindowHost()?.getDockOrderSnapshot();
            const seen = new Set<string>();
            if (ownerSnapshot && DOCK_ORDER_SCOPES.every(scope => Array.isArray(ownerSnapshot[scope]) &&
                ownerSnapshot[scope].every(key => {
                    if (typeof key !== "string" || !key || seen.has(key)) {
                        return false;
                    }
                    seen.add(key);
                    return true;
                }))) {
                snapshot = Object.fromEntries(DOCK_ORDER_SCOPES.map(scope => [scope, [...ownerSnapshot[scope]]])) as
                    TDockOrderSnapshot;
            }
        } catch (error) {
            console.warn("Could not read settings owner dock order", error);
        }
    }
    /// #endif
    snapshot ||= getDockEntryOrderSnapshot();
    return builtin ? snapshot : getDefaultDockEntryOrderSnapshot(snapshot);
};

const refreshEditorToolbarCatalog = (plugins: NonNullable<ReturnType<typeof getSettingsOwnerApp>>["plugins"]) => {
    /// #if !MOBILE
    refreshToolbarCatalogEntries(getSettingsWindowHost()?.getEditorToolbarCatalogSnapshot() ||
        getEditorToolbarCatalogSnapshot(plugins));
    /// #endif
};

const openProfileEditor = (root: HTMLElement, profileID?: string) => {
    const plugins = getSettingsOwnerApp()?.plugins || [];
    refreshEditorToolbarCatalog(plugins);
    refreshTopBarCatalog(plugins);
    refreshDockCatalog(plugins);
    refreshSlashMenuCatalog(plugins);
    const builtin = profileID === ENTRY_PROFILE_SIMPLE || profileID === ENTRY_PROFILE_FULL;
    const dockOrderSnapshot = getProfileDockOrderSnapshot(builtin);
    let selectedTemplate: TEntryVisibilityTemplate | "current" = ENTRY_PROFILE_SIMPLE;
    const existing = profileID
        ? window.siyuan.config.appearance.entryVisibility.profiles.find((item) => item.id === profileID)
        : undefined;
    const draft: Config.IEntryVisibilityProfile = builtin
        ? {
            id: profileID,
            name: templateLabel(profileID),
            entries: createEntryProfileSnapshot(profileID),
            orders: createEntryOrderSnapshot(),
        }
        : existing
        ? JSON.parse(JSON.stringify(existing)) as Config.IEntryVisibilityProfile
        : createProfile(ENTRY_PROFILE_SIMPLE);
    draft.orders ||= createEntryOrderSnapshot();
    const initialJSON = JSON.stringify(draft);
    const creating = !builtin && !existing;
    const view = createEntryView(root);
    const body = view.querySelector<HTMLElement>(".b3-dialog__body");
    body.innerHTML = `<div class="b3-dialog__content config-entry-visibility__content">
    ${isMobile() ? '<div class="config-entry-visibility__mobile-header">' : ""}
    ${builtin ? "" : `<div class="config-group">
        <div class="config-title">${creating ? window.siyuan.languages.entryCreateProfile : escapeHtml(draft.name)}</div>
        <div class="config-items">
            <label class="fn__flex b3-label config-item">
                <div class="fn__flex-1"><div class="config-name">${window.siyuan.languages.name}</div></div>
                <span class="fn__space"></span>
                <input class="b3-text-field fn__flex-center fn__size200" data-profile-field="name" value="${escapeAttr(draft.name)}">
            </label>
            ${creating ? `<label class="fn__flex b3-label config-item">
                <div class="fn__flex-1"><div class="config-name">${window.siyuan.languages.entryBasedOn}</div></div>
                <span class="fn__space"></span>
                <select class="b3-select fn__flex-center fn__size200" data-profile-field="template">
                    <option value="simple">${window.siyuan.languages.entrySimple}</option>
                    <option value="full">${window.siyuan.languages.entryFull}</option>
                    <option value="current">${window.siyuan.languages.current}</option>
                </select>
            </label>` : ""}
        </div>
    </div>`}
    <div class="config-group">
        ${builtin ? `<div class="config-title">${escapeHtml(draft.name)}</div>` : ""}
        <div class="fn__flex config-entry-visibility__search">
            <input spellcheck="false" class="b3-text-field fn__flex-1" data-type="entry-search" placeholder="${escapeAttr(window.siyuan.languages.searchPlaceholder)}">
        </div>
    </div>
    ${isMobile() ? `<div class="config-entry-visibility__mobile-controls">
        <select class="b3-select" data-type="entry-section" aria-label="${escapeAttr(window.siyuan.languages.position)}"></select>
        <div data-type="entry-mobile-options"></div>
    </div></div>` : ""}
    <div class="config-entry-visibility__browser" data-type="entry-browser"></div>
</div>
<div class="b3-dialog__action">
    ${builtin || !isMobile() ? "" : `<button class="b3-button b3-button--outline config-entry-visibility__reset-orders ariaLabel" data-action="reset-all-entry-orders" data-position="north" aria-label="${escapeAttr(window.siyuan.languages.entryResetAllOrders)}"><span class="fn__ellipsis">${window.siyuan.languages.entryResetAllOrders}</span></button><span class="fn__space fn__flex-1"></span>`}
    ${builtin ? `<button class="b3-button b3-button--text" data-action="cancel">${window.siyuan.languages.close}</button>` : `<button class="b3-button b3-button--cancel" data-action="cancel">${window.siyuan.languages.cancel}</button>
    <span class="fn__space"></span>
    <button class="b3-button b3-button--text" data-action="confirm">${window.siyuan.languages.confirm}</button>`}
</div>`;
    const browser = view.querySelector<HTMLElement>("[data-type='entry-browser']");
    const searchInput = view.querySelector<HTMLInputElement>("[data-type='entry-search']");
    let selectedSectionKey = getVisibleEntryCatalog()[0].key;
    let selectedPaths: string[] = [];
    let previousQuery = "";
    let dragging: {
        parentPath: string;
        sourceKey: string;
        defaultOrder?: string[];
        order?: string[];
        dockOrder?: TDockOrderSnapshot;
    } | undefined;
    const clearDropTarget = () => {
        browser.querySelectorAll(".config-entry-visibility__row--drop-before, .config-entry-visibility__row--drop-after")
            .forEach((item) => item.classList.remove("config-entry-visibility__row--drop-before",
                "config-entry-visibility__row--drop-after"));
        browser.querySelectorAll(".config-entry-visibility__dock-group--drop")
            .forEach((item) => item.classList.remove("config-entry-visibility__dock-group--drop"));
    };
    const renderBrowser = (scrollToEnd = false, resetEntryColumns = false, revealSelection = false) => {
        const oldColumns = Array.from(browser.querySelectorAll<HTMLElement>("[data-entry-column]"));
        const oldScrollTops = oldColumns.map((column) => column.querySelector<HTMLElement>(
            ".config-entry-visibility__column-list")?.scrollTop || 0);
        const oldColumnsContainer = browser.querySelector<HTMLElement>(".config-entry-visibility__columns");
        const oldScrollLeft = oldColumnsContainer?.scrollLeft || 0;
        const query = searchInput.value.trim().toLowerCase();
        const queryChanged = query !== previousQuery;
        const filter = query ? getEntrySearchFilter(query) : undefined;
        if (filter && filter.results.length === 0) {
            browser.innerHTML = `<div class="b3-list--empty">${window.siyuan.languages.emptyContent}</div>`;
            previousQuery = query;
            return;
        }
        if (filter && queryChanged) {
            const target = filter.results.find((item) => item.section.key === selectedSectionKey) || filter.results[0];
            selectedSectionKey = target.section.key;
            selectedPaths = target.section.key === DOCK_SECTION_KEY
                ? getDockEntrySelectedPaths(target.item.key)
                : getEntryCatalogPathChain(target.section.key, target.path);
            scrollToEnd = true;
            resetEntryColumns = true;
            revealSelection = true;
        }
        if (isMobile()) {
            const sections = getVisibleEntryCatalog().filter(item => !filter || filter.visibleSectionKeys.has(item.key));
            const section = sections.find(item => item.key === selectedSectionKey) || sections[0];
            selectedSectionKey = section.key;
            view.querySelector("[data-type='entry-section']").innerHTML = sections.map(item =>
                `<option value="${escapeAttr(item.key)}"${item.key === section.key ? " selected" : ""}>${escapeHtml(item.label())}</option>`).join("");
            const directRoot = getDirectDisplayRoot(section);
            view.querySelector("[data-type='entry-mobile-options']").innerHTML = directRoot ? `
                <label class="fn__flex b3-label config-item">
                    <div class="fn__flex-1"><div class="config-name">${escapeHtml(directRoot.label())}</div></div>
                    ${renderEntrySwitch(draft, `${section.key}.${directRoot.key}`, directRoot, true, builtin)}
                </label>` : "";
        }
        browser.innerHTML = renderEntryColumns(draft, selectedSectionKey, selectedPaths, builtin,
            filter?.visiblePaths, filter?.visibleSectionKeys, dockOrderSnapshot);
        previousQuery = query;
        const columnsContainer = browser.querySelector<HTMLElement>(".config-entry-visibility__columns");
        const columns = Array.from(browser.querySelectorAll<HTMLElement>("[data-entry-column]"));
        columns.forEach((column, index) => {
            const list = column.querySelector<HTMLElement>(".config-entry-visibility__column-list");
            if (list) {
                list.scrollTop = resetEntryColumns && (isMobile() || index > 0) ? 0 : oldScrollTops[index] || 0;
                if (revealSelection) {
                    const current = list.querySelector<HTMLElement>(
                        ".config-entry-visibility__location--current, .config-entry-visibility__row--current");
                    if (current) {
                        list.scrollTop = Math.max(0, current.offsetTop - list.clientHeight / 2);
                    }
                }
            }
        });
        if (columnsContainer) {
            columnsContainer.scrollLeft = scrollToEnd ? columnsContainer.scrollWidth : oldScrollLeft;
        }
    };
    const leaveEditor = () => {
        disposeTouchOrder();
        removeEntryView(root, view);
    };
    const closeEditor = () => {
        if (JSON.stringify(draft) !== initialJSON) {
            confirmDialog(window.siyuan.languages.confirm, window.siyuan.languages.discardUnsavedChanges, leaveEditor);
            return;
        }
        leaveEditor();
    };
    renderBrowser();
    searchInput.addEventListener("input", () => renderBrowser());
    browser.addEventListener("dragstart", (event: DragEvent) => {
        if (isMobile() || builtin || searchInput.value.trim()) {
            event.preventDefault();
            return;
        }
        const handle = (event.target as Element).closest<HTMLElement>(".config-entry-visibility__drag");
        const row = handle?.closest<HTMLElement>("[data-entry-row]");
        if (!row?.dataset.entryParent || !row.dataset.entryKey) {
            event.preventDefault();
            return;
        }
        dragging = {parentPath: row.dataset.entryParent, sourceKey: row.dataset.entryKey};
        row.classList.add("config-entry-visibility__row--dragging");
        event.dataTransfer.effectAllowed = "move";
        event.dataTransfer.setData("text/plain", row.dataset.entryKey);
    });
    const updateDropTarget = (target: Element, clientY: number) => {
        if (!dragging) {
            return;
        }
        const row = target?.closest<HTMLElement>("[data-entry-row]");
        if (isDockOrderScope(dragging.parentPath)) {
            const dropScopeElement = target?.closest<HTMLElement>("[data-entry-drop-scope]");
            const targetScopeValue = row?.dataset.entryParent || dropScopeElement?.dataset.entryDropScope || "";
            if (!isDockOrderScope(targetScopeValue)) {
                clearDropTarget();
                dragging.dockOrder = undefined;
                return;
            }
            const targetKey = row?.dataset.entryParent === targetScopeValue ? row.dataset.entryKey : undefined;
            const after = targetKey
                ? clientY >= row.getBoundingClientRect().top + row.offsetHeight / 2
                : undefined;
            const movedOrder = moveDockEntryOrderSnapshot(
                mergeDockEntryOrderSnapshot(dockOrderSnapshot, draft.orders),
                dragging.sourceKey,
                targetScopeValue,
                targetKey,
                after,
            );
            clearDropTarget();
            dragging.dockOrder = movedOrder;
            if (!movedOrder) {
                return;
            }
            if (targetKey) {
                row.classList.add(`config-entry-visibility__row--drop-${after ? "after" : "before"}`);
            } else {
                dropScopeElement?.closest(".config-entry-visibility__dock-group")
                    ?.classList.add("config-entry-visibility__dock-group--drop");
            }
            return;
        }
        if (!row || row.dataset.entryParent !== dragging.parentPath || !row.dataset.entryKey ||
            `${row.dataset.entryParent}.${row.dataset.entryKey}` === SLASH_MENU_FREQUENT_PATH) {
            clearDropTarget();
            dragging.order = undefined;
            return;
        }
        const context = getEntryOrderContext(dragging.parentPath, dockOrderSnapshot);
        dragging.defaultOrder = context.defaultOrder;
        const order = resolveProfileEntryOrder(
            draft,
            dragging.parentPath,
            context.defaultOrder,
            context.separatorKeys,
        );
        const after = clientY >= row.getBoundingClientRect().top + row.offsetHeight / 2;
        const movedOrder = moveEntryOrder(order, dragging.sourceKey, row.dataset.entryKey, after,
            context.separatorKeys);
        clearDropTarget();
        dragging.order = movedOrder;
        if (!movedOrder) {
            return;
        }
        row.classList.add(`config-entry-visibility__row--drop-${after ? "after" : "before"}`);
    };
    const saveDrop = () => {
        if (dragging && isDockOrderScope(dragging.parentPath)) {
            if (!dragging.dockOrder) {
                return;
            }
            draft.orders ||= {};
            DOCK_ORDER_SCOPES.forEach((scope) => {
                draft.orders[scope] = [...dragging.dockOrder[scope]];
            });
            dragging = undefined;
            renderBrowser();
            return;
        }
        if (!dragging?.defaultOrder || !dragging.order) {
            return;
        }
        draft.orders ||= {};
        const context = getEntryOrderContext(dragging.parentPath, dockOrderSnapshot);
        const savedOrder = getSavedEntryOrder(draft, dragging.parentPath, dragging.defaultOrder);
        const separatorKeys = new Set([
            ...context.separatorKeys,
            ...(savedOrder || []).filter((key) =>
                key.startsWith("separator_") || key.startsWith("plugin-separator:")),
        ]);
        draft.orders[dragging.parentPath] = mergeEntryOrderPreservingUnknown(
            dragging.defaultOrder,
            savedOrder,
            dragging.order,
            separatorKeys,
        );
        dragging = undefined;
        renderBrowser();
    };
    const cancelDrag = () => {
        dragging = undefined;
        clearDropTarget();
        browser.querySelector(".config-entry-visibility__row--dragging")?.classList.remove(
            "config-entry-visibility__row--dragging");
    };
    browser.addEventListener("dragover", (event: DragEvent) => {
        updateDropTarget(event.target as Element, event.clientY);
        if (dragging?.order || dragging?.dockOrder) {
            event.preventDefault();
            event.dataTransfer.dropEffect = "move";
        }
    });
    browser.addEventListener("drop", (event: DragEvent) => {
        event.preventDefault();
        saveDrop();
        cancelDrag();
    });
    browser.addEventListener("dragend", cancelDrag);
    const disposeTouchOrder = isMobile() ? bindTouchOrder(browser, {
        start: (row) => {
            if (builtin || searchInput.value.trim() || !row.dataset.entryParent || !row.dataset.entryKey) {
                return false;
            }
            dragging = {parentPath: row.dataset.entryParent, sourceKey: row.dataset.entryKey};
            row.classList.add("config-entry-visibility__row--dragging");
            return true;
        },
        move: updateDropTarget,
        drop: () => {
            saveDrop();
            cancelDrag();
        },
        cancel: cancelDrag,
    }) : () => {};
    view.addEventListener("input", (event) => {
        if (builtin) {
            return;
        }
        const target = event.target as HTMLInputElement;
        if (target.dataset.profileField === "name") {
            draft.name = target.value;
        }
    });
    view.addEventListener("change", (event) => {
        const control = event.target as HTMLInputElement | HTMLSelectElement;
        if (control.dataset.type === "entry-section") {
            selectedSectionKey = control.value;
            selectedPaths = [];
            renderBrowser(false, true);
            return;
        }
        if (builtin) {
            return;
        }
        const target = event.target as HTMLInputElement | HTMLSelectElement;
        if (target.matches("[data-entry-path]")) {
            draft.entries[(target as HTMLInputElement).dataset.entryPath] = (target as HTMLInputElement).checked;
            renderBrowser();
            return;
        }
        if (target.dataset.profileField !== "template") {
            return;
        }
        selectedTemplate = target.value as TEntryVisibilityTemplate | "current";
        const template = createProfile(selectedTemplate === "current" ? ENTRY_PROFILE_FULL : selectedTemplate,
            selectedTemplate === "current");
        draft.defaults = template.defaults;
        draft.entries = template.entries;
        draft.orders = template.orders;
        renderBrowser();
    });
    view.addEventListener("click", (event) => {
        if ((event.target as Element).closest(".config-entry-visibility__drag")) {
            event.preventDefault();
            return;
        }
        const entrySwitch = (event.target as HTMLElement).closest<HTMLInputElement>("input[data-entry-path]");
        if (entrySwitch) {
            if (entrySwitch.hasAttribute("data-entry-readonly")) {
                event.preventDefault();
                showMessage(window.siyuan.languages.entryBuiltinReadonlyTip);
            }
            return;
        }
        const actionElement = (event.target as HTMLElement).closest<HTMLElement>("[data-action]");
        const action = actionElement?.dataset.action;
        if (!builtin && (action === "reset-entry-order" || action === "reset-all-entry-orders")) {
            cancelDrag();
            resetEntryProfileOrder(draft, action === "reset-entry-order" ? actionElement.dataset.entryParent : undefined);
            renderBrowser();
        } else if (action === "back" || action === "cancel") {
            closeEditor();
        } else if (action === "select-entry-section") {
            selectedSectionKey = actionElement.dataset.entrySection;
            selectedPaths = [];
            renderBrowser(true, true);
        } else if (action === "navigate-entry") {
            const depth = Number(actionElement.dataset.entryDepth);
            selectedPaths = selectedPaths.slice(0, depth);
            selectedPaths[depth] = actionElement.dataset.entryPath;
            renderBrowser(true);
        } else if (action === "back-entry") {
            selectedPaths = getEntryCatalogPathChain(selectedSectionKey, actionElement.dataset.entryParent).slice(0, -1);
            renderBrowser(true);
        } else if (!builtin && action === "confirm") {
            const nameInput = view.querySelector<HTMLInputElement>("[data-profile-field='name']");
            const name = draft.name.trim();
            if (!name) {
                nameInput.focus();
                return;
            }
            const config = cloneConfig();
            draft.name = uniqueName(name, config.profiles.filter((item) => item.id !== existing?.id));
            if (existing) {
                config.profiles = config.profiles.map((item) => item.id === existing.id ? draft : item);
            } else {
                config.profiles.push(draft);
            }
            saveEntryVisibility(config);
            renderProfileCards(root);
            leaveEditor();
        }
    });
    const nameInput = view.querySelector<HTMLInputElement>("[data-profile-field='name']");
    if (creating && nameInput) {
        nameInput.select();
    }
};

const importProfiles = async (root: HTMLElement, file: File) => {
    if (!getHostCapabilities().importExport) {
        return;
    }
    try {
        const data = JSON.parse(await file.text()) as TImportFile;
        if (!isEntryVisibilityImportVersionSupported(data.version, ENTRY_VISIBILITY_VERSION)) {
            throw new Error("unsupported version");
        }
        let imported: TEntryVisibilityImportProfile[];
        if (data.type === "siyuan-entry-profile" && data.profile) {
            imported = [data.profile];
        } else if (data.type === "siyuan-entry-profile-bundle" && Array.isArray(data.profiles)) {
            imported = data.profiles;
        } else {
            throw new Error("invalid type");
        }
        const config = cloneConfig();
        let importedCount = 0;
        imported.forEach((item) => {
            const profile = normalizeEntryVisibilityImportProfile(item, data.version, createEntryOrderSnapshot());
            if (!profile) {
                return;
            }
            config.profiles.push({
                id: genUUID(),
                name: uniqueName(profile.name, config.profiles),
                entries: profile.entries,
                orders: profile.orders,
            });
            importedCount++;
        });
        if (imported.length > 0 && importedCount === 0) {
            throw new Error("invalid profiles");
        }
        saveEntryVisibility(config);
        renderProfileCards(root);
        showMessage(window.siyuan.languages.imported);
    } catch (error) {
        console.warn("import entry visibility profile failed", error);
        showMessage(window.siyuan.languages.entryImportInvalid, 6000, "error");
    }
};

export const genEntryVisibilityHtml = () => `<div class="b3-label config-item" data-type="entry-visibility">
    <div class="fn__flex">
        <div><div class="config-name">${window.siyuan.languages.entryVisibility}</div><div class="b3-label__text">${isMobile() ? window.siyuan.languages.mobileToolbarEntryTip : window.siyuan.languages.entryVisibilityTip}</div></div>
        <span class="fn__space fn__flex-1"></span>
        ${getHostCapabilities().importExport ? `<button class="b3-button b3-button--outline" data-action="import"><svg class="b3-button__icon"><use xlink:href="#iconUpload"></use></svg>${window.siyuan.languages.import}</button>
        <span class="fn__space"></span>
        <button class="b3-button b3-button--outline" data-action="export-all"><svg class="b3-button__icon"><use xlink:href="#iconDownload"></use></svg>${window.siyuan.languages.export}</button>
        <span class="fn__space"></span>` : ""}
        <button class="b3-button b3-button--outline" data-action="create"><svg class="b3-button__icon"><use xlink:href="#iconAdd"></use></svg>${window.siyuan.languages.entryCreateProfile}</button>
        <input class="fn__none" data-type="entry-import" type="file" accept="application/json,.json">
    </div>
    <div class="fn__hr"></div>
    <div data-type="entry-profiles"></div>
</div>`;

export const mountEntryVisibility = (root: HTMLElement) => {
    const plugins = getSettingsOwnerApp()?.plugins || [];
    refreshDockCatalog(plugins);
    refreshSlashMenuCatalog(plugins);
    renderProfileCards(root);
    root.querySelector("[data-action='create']")?.addEventListener("click", () => openProfileEditor(root));
    root.querySelector("[data-action='export-all']")?.addEventListener("click", exportBundle);
    const fileInput = root.querySelector<HTMLInputElement>("[data-type='entry-import']");
    root.querySelector("[data-action='import']")?.addEventListener("click", () => fileInput.click());
    fileInput.addEventListener("change", () => {
        const file = fileInput.files?.[0];
        fileInput.value = "";
        if (file) {
            void importProfiles(root, file);
        }
    });
    root.querySelector("[data-type='entry-profiles']")?.addEventListener("click", (event) => {
        const card = (event.target as Element).closest<HTMLElement>("[data-profile-id]");
        const action = (event.target as Element).closest<HTMLElement>("[data-action]")?.dataset.action;
        if (!card || !action) {
            return;
        }
        const id = card.dataset.profileId;
        const config = cloneConfig();
        const profile = config.profiles.find((item) => item.id === id);
        if (action === "activate") {
            config.active = id;
            saveEntryVisibility(config);
            renderProfileCards(root);
        } else if (action === "edit" || action === "view") {
            openProfileEditor(root, id);
        } else if (action === "duplicate") {
            const template = id as TEntryVisibilityTemplate;
            const copy = profile ? duplicateProfile(profile) : createProfile(template, false,
                `${templateLabel(template)} ${window.siyuan.languages.duplicateCopy}`);
            config.profiles.push(copy);
            saveEntryVisibility(config);
            renderProfileCards(root);
        } else if (action === "export" && profile) {
            exportProfile(profile);
        } else if (action === "delete" && profile) {
            confirmDialog(window.siyuan.languages.deleteOpConfirm,
                window.siyuan.languages.confirmDeleteTip.replace("${x}", escapeHtml(profile.name)), () => {
                    const latest = cloneConfig();
                    latest.profiles = latest.profiles.filter((item) => item.id !== profile.id);
                    if (latest.active === profile.id) {
                        latest.active = ENTRY_PROFILE_FULL;
                    }
                    saveEntryVisibility(latest);
                    renderProfileCards(root);
                }, undefined, true);
        }
    });
};