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.3 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 { IDocumentBody } from '../../../types/interfaces/i-document-data';
import type { TextXAction } from './action-types';
import { MemoryCursor } from '../../../common/memory-cursor';
import { UpdateDocsAttributeType } from '../../../shared/command-enum';
import { Tools } from '../../../shared/tools';
import { TextXActionType } from './action-types';
import { updateAttributeByDelete } from './apply-utils/delete-apply';
import { updateAttributeByInsert } from './apply-utils/insert-apply';
import { updateAttribute } from './apply-utils/update-apply';
import { applyRangeUpdates, getRangeUpdates, validateRangeUpdates } from './custom-range-update';

function updateApply(
    doc: IDocumentBody,
    updateBody: IDocumentBody,
    textLength: number,
    currentIndex: number,
    coverType = UpdateDocsAttributeType.COVER
): IDocumentBody {
    return updateAttribute(doc, updateBody, textLength, currentIndex, coverType);
}

function deleteApply(
    doc: IDocumentBody,
    textLength: number,
    currentIndex: number
): IDocumentBody {
    if (textLength <= 0) {
        return { dataStream: '' };
    }

    return updateAttributeByDelete(doc, textLength, currentIndex);
}

function insertApply(
    doc: IDocumentBody,
    insertBody: IDocumentBody,
    textLength: number,
    currentIndex: number
) {
    // No need to insert empty text.
    if (textLength === 0) {
        return;
    }

    updateAttributeByInsert(doc, insertBody, textLength, currentIndex);
}

export function textXApply(doc: IDocumentBody, actions: TextXAction[]): IDocumentBody {
    if (actions.some((action) => action.t !== TextXActionType.RETAIN && action.valueRangeId !== undefined &&
        (typeof action.valueRangeId !== 'string' || !action.valueRangeId))) {
        throw new Error('Invalid scalar value range identity.');
    }
    const updates = getRangeUpdates(actions);
    if (updates.length) {
        const resultLength = actions.reduce((length, action) => {
            if (action.t === TextXActionType.INSERT) {
                return length + action.len;
            }
            if (action.t === TextXActionType.DELETE) {
                return length - action.len;
            }
            return length;
        }, doc.dataStream.length);
        validateRangeUpdates(updates, resultLength);
    }
    const memoryCursor = new MemoryCursor();

    memoryCursor.reset();

    actions.forEach((action) => {
        switch (action.t) {
            case TextXActionType.RETAIN: {
                const { coverType, body, len } = action;
                if (body != null) {
                    // Attribute apply mutates its payload while normalizing ranges.
                    updateApply(doc, Tools.deepClone(body), len, memoryCursor.cursor, coverType);
                }

                memoryCursor.moveCursor(len);
                break;
            }

            case TextXActionType.INSERT: {
                const { body, len } = action;
                // Plain typing only reads dataStream. Structural inserts still clone their local metadata payload.
                const insertBody = onlyHasDataStream(body) ? body : Tools.deepClone(body);

                insertApply(doc, insertBody, len, memoryCursor.cursor);
                memoryCursor.moveCursor(len);
                break;
            }

            case TextXActionType.DELETE: {
                const { len } = action;
                deleteApply(doc, len, memoryCursor.cursor);
                break;
            }
            default:
                throw new Error(`Unknown action type for action: ${action}.`);
        }
    });

    applyRangeUpdates(doc, updates);
    return doc;
}

function onlyHasDataStream(body: IDocumentBody): boolean {
    return Object.keys(body).length === 1 && typeof body.dataStream === 'string';
}