Skip to content

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

6.5 KB
Raw Blame
import {Constants} from "../../constants";
import {isInEmbedBlock} from "../util/hasClosest";
import {restoreTableVirtualizationDOM} from "../util/tableVirtualizationDOM";

export const getSearchMarkRanges = (rootElement: HTMLElement, keys: string[], excludeSelector?: string) => {
    const textNodes: Node[] = [];
    const textNodesSize: number[] = [];
    const excludedTextNodeCounts: number[] = [];
    let currentSize = 0;
    let excludedTextNodeCount = 0;
    const treeWalker = document.createTreeWalker(rootElement, NodeFilter.SHOW_TEXT);
    let currentNode = treeWalker.nextNode();
    while (currentNode) {
        textNodes.push(currentNode);
        currentSize += currentNode.textContent.length;
        textNodesSize.push(currentSize);
        if (excludeSelector && currentNode.parentElement?.closest(excludeSelector)) {
            excludedTextNodeCount++;
        }
        excludedTextNodeCounts.push(excludedTextNodeCount);
        currentNode = treeWalker.nextNode();
    }
    const text = rootElement.textContent;
    const matches: {range: Range, startIndex: number}[] = [];
    keys.forEach(key => {
        if (!key) {
            return;
        }
        let startIndex = 0;
        let currentNodeIndex = 0;
        while ((startIndex = text.indexOf(key, startIndex)) !== -1) {
            const endIndex = startIndex + key.length;
            while (currentNodeIndex < textNodes.length && textNodesSize[currentNodeIndex] <= startIndex) {
                currentNodeIndex++;
            }
            const startNodeIndex = currentNodeIndex;
            while (currentNodeIndex < textNodes.length && textNodesSize[currentNodeIndex] < endIndex) {
                currentNodeIndex++;
            }
            const excludedCountBefore = startNodeIndex ? excludedTextNodeCounts[startNodeIndex - 1] : 0;
            if (excludedTextNodeCounts[currentNodeIndex] === excludedCountBefore) {
                const range = document.createRange();
                range.setStart(textNodes[startNodeIndex], startIndex -
                    (startNodeIndex ? textNodesSize[startNodeIndex - 1] : 0));
                range.setEnd(textNodes[currentNodeIndex], endIndex -
                    (currentNodeIndex ? textNodesSize[currentNodeIndex - 1] : 0));
                matches.push({range, startIndex});
            }
            startIndex = endIndex;
        }
    });
    return matches;
};

export const searchMarkRender = (protyle: IProtyle, keys: string[], hlId?: string | number, cb?: () => void,
                                 options?: {
                                     rootElement?: HTMLElement,
                                     currentElement?: Element,
                                     excludeSelector?: string,
                                     isValid?: () => boolean,
                                     ranges?: Range[],
                                 }) => {
    if (!isSupportCSSHL() || ((!keys || keys.length === 0) && !hlId)) {
        return;
    }
    setTimeout(() => {
        if (options?.isValid && !options.isValid()) {
            return;
        }
        restoreTableVirtualizationDOM(protyle.wysiwyg.element);
        protyle.highlight.markHL.clear();
        protyle.highlight.mark.clear();
        protyle.highlight.rangeIndex = 0;
        protyle.highlight.ranges = [];
        let isSetHL = false;
        let hlBlockElement = options?.currentElement;
        if (!hlBlockElement && typeof hlId === "string") {
            Array.from(protyle.wysiwyg.element.querySelectorAll(`[data-node-id='${hlId}']`)).find(item => {
                if (!isInEmbedBlock(item)) {
                    hlBlockElement = item;
                    return true;
                }
            });
        }

        if (!hlBlockElement && hlId === protyle.block.rootID && protyle.title && !protyle.title.element.classList.contains("fn__none")) {
            hlBlockElement = protyle.title.element;
        }

        const rootElement = options?.rootElement || protyle.contentElement;
        const text = rootElement.textContent;
        const rangeIndexes: { range: Range, startIndex: number, isCurrent: boolean }[] = [];
        if (options?.ranges) {
            options.ranges.forEach(range => {
                if (!rootElement.contains(range.commonAncestorContainer)) {
                    return;
                }
                const prefix = document.createRange();
                prefix.selectNodeContents(rootElement);
                prefix.setEnd(range.startContainer, range.startOffset);
                const isCurrent = !isSetHL && !!hlBlockElement?.contains(range.startContainer);
                isSetHL = isSetHL || isCurrent;
                rangeIndexes.push({range, startIndex: prefix.toString().length, isCurrent});
            });
        } else if (keys && keys.length > 0) {
            getSearchMarkRanges(rootElement, keys, options?.excludeSelector).forEach(match => {
                const isCurrent = !isSetHL && !!hlBlockElement?.contains(match.range.endContainer);
                isSetHL = isSetHL || isCurrent;
                rangeIndexes.push({...match, isCurrent});
            });
        }

        // 没有匹配到关键字,但是有高亮块时,需将其添加进去
        if (!isSetHL && hlBlockElement) {
            const range = new Range();
            range.selectNodeContents(hlBlockElement);
            range.collapse(true);
            rangeIndexes.push({range, startIndex: text.indexOf(hlBlockElement.textContent), isCurrent: true});
        }

        rangeIndexes.sort((b, a) => {
            if (a.startIndex > b.startIndex) {
                return -1;
            } else {
                return 0;
            }
        }).forEach((item, index) => {
            if ((typeof hlId === "string" && item.isCurrent) || (typeof hlId === "number" && hlId === index)) {
                protyle.highlight.rangeIndex = index;
                protyle.highlight.markHL.add(item.range);
            } else {
                protyle.highlight.mark.add(item.range);
            }
            protyle.highlight.ranges.push(item.range);
        });
        CSS.highlights.set("search-mark-" + protyle.highlight.styleElement.dataset.uuid, protyle.highlight.mark);
        if (typeof hlId !== "undefined") {
            CSS.highlights.set("search-mark-hl-" + protyle.highlight.styleElement.dataset.uuid, protyle.highlight.markHL);
        }
        if (cb) {
            cb();
        }
    }, protyle.wysiwyg.element.querySelector(".hljs") ? Constants.TIMEOUT_TRANSITION : 0);
};

export const isSupportCSSHL = () => {
    return !!(CSS && CSS.highlights);
};