Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

4.5 KB
Raw Blame
/**
 * Copyright 2023-present DreamNum Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type { ICustomRange, IDocumentBody } from '@univerjs/core';
import type { IThreadCommentMention } from '@univerjs/thread-comment';
import { createParagraphId, createSectionId, CustomRangeType, getBodySlice } from '@univerjs/core';

interface IThreadCommentEditorFocusService {
    focus: (editorId: string) => void;
}

interface IFocusableThreadCommentEditor {
    focus: () => void;
}

export type TextNode = {
    type: 'text';
    content: string;
} | {
    type: 'mention';
    content: IThreadCommentMention;
} | {
    type: 'hyperlink';
    content: string;
    range: ICustomRange;
};

const transformDocument2TextNodesInParagraph = (doc: IDocumentBody) => {
    const { dataStream, customRanges } = doc;
    const end = dataStream.endsWith('\r\n') ? dataStream.length - 2 : dataStream.length;
    const textNodes: TextNode[] = [];

    let lastIndex = 0;

    customRanges?.forEach((range) => {
        if (lastIndex < range.startIndex) {
            textNodes.push({
                type: 'text',
                content: dataStream.slice(lastIndex, range.startIndex),
            });
        }
        const content = dataStream.slice(range.startIndex, range.endIndex + 1);
        if (range.rangeType === CustomRangeType.MENTION) {
            textNodes.push({ type: 'mention', content: { label: content, id: range.rangeId } });
        } else if (range.rangeType === CustomRangeType.HYPERLINK) {
            textNodes.push({ type: 'hyperlink', content, range });
        } else {
            textNodes.push({ type: 'text', content });
        }
        lastIndex = range.endIndex + 1;
    });

    textNodes.push({
        type: 'text',
        content: dataStream.slice(lastIndex, end),
    });
    return textNodes;
};

export const transformDocument2TextNodes = (doc: IDocumentBody) => {
    if (!doc) {
        return [];
    }
    const { paragraphs = [] } = doc;

    return paragraphs.map((paragraph, index) => {
        const lastIndex = index === 0 ? 0 : paragraphs[index - 1].startIndex + 1;
        const body = getBodySlice(doc, lastIndex, paragraph.startIndex);
        return transformDocument2TextNodesInParagraph(body);
    });
};

export const transformTextNodes2Document = (nodes: TextNode[]): IDocumentBody => {
    let str = '';
    const customRanges: Required<IDocumentBody['customRanges']> = [];

    nodes.forEach((node) => {
        switch (node.type) {
            case 'text':
                str += node.content;
                break;
            case 'mention': {
                const start = str.length;
                str += node.content.label;
                const end = str.length - 1;
                customRanges.push({
                    rangeId: node.content.id,
                    rangeType: CustomRangeType.MENTION,
                    startIndex: start,
                    endIndex: end,
                    properties: {},
                    wholeEntity: true,
                });
                break;
            }
            case 'hyperlink': {
                const startIndex = str.length;
                str += node.content;
                customRanges.push({ ...node.range, startIndex, endIndex: str.length - 1 });
                break;
            }

            default:
                break;
        }
    });

    str += '\r\n';

    return {
        textRuns: [],
        paragraphs: [
            {
                startIndex: str.length - 2,
                paragraphId: createParagraphId(new Set()),
                paragraphStyle: {},
            },
        ],
        sectionBreaks: [
            {
                sectionId: createSectionId(new Set()),
                startIndex: str.length - 1,
            },
        ],
        dataStream: str,
        customRanges,
    };
};

export function focusThreadCommentEditor(
    editorService: IThreadCommentEditorFocusService,
    editorId: string,
    editor?: IFocusableThreadCommentEditor | null
) {
    editorService.focus(editorId);
    editor?.focus();
}