Skip to content

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

8.5 KB
Raw Blame
import type {FileTreeGetDocRequestInput} from "../../types/api";
import {hasClosestBlock} from "../util/hasClosest";
import {getSelectionOffset} from "../util/selectionOffsets";
import {fetchPost} from "../../util/fetch";
import {onGet} from "../util/onGet";
import {Constants} from "../../constants";
import {setStorageVal} from "../util/compatibility";
import {isSupportCSSHL} from "../render/searchMarkRender";
import {isEncryptedBox} from "../../util/pathName";
import {getContenteditableElement} from "../wysiwyg/getBlock";
import {getSavedScrollRange, getScrollRequestParams} from "./scrollRequest";
import {getSavedTabFocusTarget} from "../util/focusRestore";

export const saveScroll = (protyle: IProtyle, getObject = false) => {
    if (!protyle.wysiwyg.element.firstElementChild || window.siyuan.config.readonly ||
        (protyle.element.dataset.databaseRowId && !getObject)) {
        // 报错或者空白页面
        return undefined;
    }
    const attr: IScrollAttr = {
        rootId: protyle.block.rootID,
        ...getSavedScrollRange(
            protyle.wysiwyg.element.firstElementChild.getAttribute("data-node-id"),
            protyle.wysiwyg.element.lastElementChild.getAttribute("data-node-id"),
        ),
        scrollTop: protyle.contentElement.scrollTop || parseInt(protyle.contentElement.getAttribute("data-scrolltop")) || 0,
    };
    let range: Range;
    if (getSelection().rangeCount > 0) {
        range = getSelection().getRangeAt(0);
    }
    // 光标位于文档标题时用文档 id 作为焦点标识 https://github.com/siyuan-note/siyuan/issues/17456
    if (range && protyle.title?.editElement?.contains(range.startContainer)) {
        const position = getSelectionOffset(protyle.title.editElement, undefined, range);
        attr.focusId = protyle.block.rootID;
        attr.focusStart = position.start;
        attr.focusEnd = position.end;
    } else {
        if (!range || !protyle.wysiwyg.element.contains(range.startContainer)) {
            range = protyle.toolbar.range;
        }
        if (range && protyle.wysiwyg.element.contains(range.startContainer)) {
            const blockElement = hasClosestBlock(range.startContainer);
            if (blockElement) {
                const target = getSavedTabFocusTarget(blockElement);
                attr.focusId = target.getAttribute("data-node-id");
                if (target === blockElement) {
                    const position = getSelectionOffset(getContenteditableElement(blockElement) || blockElement, undefined, range);
                    attr.focusStart = position.start;
                    attr.focusEnd = position.end;
                }
            }
        }
    }

    if (protyle.block.showAll) {
        attr.zoomInId = protyle.block.id;
    }
    if (getObject) {
        return attr;
    }

    if (isEncryptedBox(protyle.notebookId)) {
        delete window.siyuan.storage[Constants.LOCAL_FILEPOSITION][protyle.block.rootID];
        return Promise.resolve(true);
    }
    window.siyuan.storage[Constants.LOCAL_FILEPOSITION][protyle.block.rootID] = attr;
    return new Promise(resolve => {
        setStorageVal(Constants.LOCAL_FILEPOSITION, window.siyuan.storage[Constants.LOCAL_FILEPOSITION], () => {
            resolve(true);
        });
    });
};

export const getDocByScroll = (options: {
    protyle: IProtyle,
    scrollAttr?: IScrollAttr,
    mergedOptions?: IProtyleOptions,
    cb?: (keys: string[]) => void,
    beforeAVRender?: () => void,
    afterAVRender?: () => void | Promise<void>,
    onRenderError?: () => void,
    focus?: boolean,
    updateReadonly?: boolean,
    signal?: AbortSignal,
    fail?: (invalid?: boolean) => void,
    isValid?: () => boolean,
}) => {
    const fetchDoc = (params: FileTreeGetDocRequestInput, callback: (response: IWebSocketData) => void) => {
        params.includeDocInfo = true;
        let handled = false;
        void fetchPost("/api/filetree/getDoc", params, (response) => {
            handled = true;
            callback(response);
        }, undefined, undefined, options.signal).then(() => {
            if (!handled) {
                options.onRenderError?.();
                options.fail?.();
            }
        });
    };
    let actions: TProtyleAction[] = [];
    if (options.mergedOptions) {
        actions = options.mergedOptions.action;
    } else {
        if (options.focus) {
            actions = [Constants.CB_GET_UNUNDO, Constants.CB_GET_FOCUS];
        } else {
            actions = [Constants.CB_GET_UNUNDO];
        }
    }
    const renderDoc = (response: IWebSocketData) => {
        if (response.code !== 0) {
            options.onRenderError?.();
        }
        try {
            onGet({
                scrollPosition: options.mergedOptions?.scrollPosition,
                data: response,
                protyle: options.protyle,
                action: actions,
                scrollAttr: options.scrollAttr,
                afterCB: options.cb ? () => {
                    options.cb(response.data.keywords);
                } : undefined,
                updateReadonly: options.updateReadonly,
                isValid: options.isValid,
                beforeAVRender: options.beforeAVRender,
                afterAVRender: options.afterAVRender,
                onAVRenderError: options.onRenderError,
            });
        } catch (error) {
            console.error(error);
            options.onRenderError?.();
            options.fail?.();
            return;
        }
    };
    if (options.scrollAttr?.zoomInId && options.scrollAttr?.rootId && options.scrollAttr.zoomInId !== options.scrollAttr.rootId) {
        const getDocParam: FileTreeGetDocRequestInput = {
            id: options.scrollAttr.zoomInId,
            size: Constants.SIZE_GET_MAX,
            query: options.protyle.query?.key,
            queryMethod: options.protyle.query?.method,
            queryTypes: options.protyle.query?.types ? {...options.protyle.query.types} : undefined,
            querySubTypes: options.protyle.query?.subTypes,
            highlight: !isSupportCSSHL(),
        };
        if (isEncryptedBox(options.protyle.notebookId)) {
            getDocParam.notebook = options.protyle.notebookId;
        }
        fetchDoc(getDocParam, response => {
            if (response.code === 1) {
                const getDocParam: FileTreeGetDocRequestInput = {
                    id: options.scrollAttr.rootId || options.mergedOptions?.blockId || options.protyle.block?.rootID || options.scrollAttr.startId,
                    ...getScrollRequestParams(window.siyuan.config.editor.dynamicLoadBlocks),
                    query: options.protyle.query?.key,
                    queryMethod: options.protyle.query?.method,
                    queryTypes: options.protyle.query?.types ? {...options.protyle.query.types} : undefined,
                    querySubTypes: options.protyle.query?.subTypes,
                    highlight: !isSupportCSSHL(),
                };
                if (isEncryptedBox(options.protyle.notebookId)) {
                    getDocParam.notebook = options.protyle.notebookId;
                }
                fetchDoc(getDocParam, response => {
                    if (response.code !== 0 && options.fail) {
                        options.fail(true);
                        return;
                    }
                    renderDoc(response);
                });
            } else {
                if (response.code !== 0 && options.fail) {
                    options.fail(true);
                    return;
                }
                actions.push(Constants.CB_GET_ALL);
                renderDoc(response);
            }
        });
        return;
    }
    const getDocParam: FileTreeGetDocRequestInput = {
        id: options.scrollAttr?.rootId || options.mergedOptions?.blockId || options.protyle.block?.rootID || options.scrollAttr?.startId,
        ...getScrollRequestParams(
            window.siyuan.config.editor.dynamicLoadBlocks,
            options.scrollAttr?.startId,
            options.scrollAttr?.endId,
        ),
        query: options.protyle.query?.key,
        queryMethod: options.protyle.query?.method,
        queryTypes: options.protyle.query?.types ? {...options.protyle.query.types} : undefined,
        querySubTypes: options.protyle.query?.subTypes,
        highlight: !isSupportCSSHL(),
    };
    if (isEncryptedBox(options.protyle.notebookId)) {
        getDocParam.notebook = options.protyle.notebookId;
    }
    fetchDoc(getDocParam, response => {
        if (response.code !== 0 && options.fail) {
            options.fail(true);
            return;
        }
        renderDoc(response);
    });
};