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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat: add replace content command (#530)
Ran Luo376ee00d4e21
diff --git a/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.ts b/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.tsnew file mode 100644index 0000000000..70969e7ac8--- /dev/null+++ b/packages/base-docs/src/commands/commands/__tests__/replace-content.command.spec.ts@@ -0,0 +1,107 @@+/* eslint-disable no-magic-numbers */++import {+ ICommand,+ ICommandService,+ IDocumentData,+ IUniverInstanceService,+ RedoCommand,+ UndoCommand,+ Univer,+} from '@univerjs/core';+import { Injector } from '@wendellhu/redi';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { NORMAL_TEXT_SELECTION_PLUGIN_NAME } from '../../../basics/docs-view-key';+import { TextSelectionManagerService } from '../../../services/text-selection-manager.service';+import { RichTextEditingMutation } from '../../mutations/core-editing.mutation';+import { ReplaceContentCommand } from '../replace-content.command';+import { createCommandTestBed } from './create-command-test-bed';++const TEST_DOCUMENT_DATA_EN: IDocumentData = {+ id: 'test-doc',+ body: {+ dataStream: '=SUM(A2:B4)\r\n',+ },+ documentStyle: {+ pageSize: {+ width: 594.3,+ height: 840.51,+ },+ marginTop: 72,+ marginBottom: 72,+ marginRight: 90,+ marginLeft: 90,+ },+};++describe('replace content of document', () => {+ let univer: Univer;+ let get: Injector['get'];+ let commandService: ICommandService;++ function getDataStream() {+ const univerInstanceService = get(IUniverInstanceService);+ const docsModel = univerInstanceService.getUniverDocInstance('test-doc');++ if (docsModel?.body?.dataStream == null) {+ return '';+ }++ return docsModel?.body?.dataStream;+ }++ beforeEach(() => {+ const testBed = createCommandTestBed(TEST_DOCUMENT_DATA_EN);+ univer = testBed.univer;+ get = testBed.get;++ commandService = get(ICommandService);+ commandService.registerCommand(ReplaceContentCommand);+ commandService.registerCommand(RichTextEditingMutation as unknown as ICommand);++ const selectionManager = get(TextSelectionManagerService);++ selectionManager.setCurrentSelection({+ pluginName: NORMAL_TEXT_SELECTION_PLUGIN_NAME,+ unitId: 'test-doc',+ });++ selectionManager.add([+ {+ startOffset: 5,+ endOffset: 5,+ collapsed: false,+ segmentId: '',+ },+ ]);+ });++ afterEach(() => univer.dispose());++ describe('replace content of document and reserve undo and redo stack', () => {+ it('Should pass the test case when replace content', async () => {+ expect(getDataStream().length).toBe(13);+ const commandParams = {+ unitId: 'test-doc',+ body: {+ dataStream: '=AVERAGE(A4:B8)',+ }, // Do not contain `\r\n` at the end.+ textRanges: [],+ segmentId: '',+ };++ await commandService.executeCommand(ReplaceContentCommand.id, commandParams);++ expect(getDataStream().length).toBe(17);++ await commandService.executeCommand(UndoCommand.id);++ expect(getDataStream().length).toBe(13);++ await commandService.executeCommand(RedoCommand.id);++ expect(getDataStream().length).toBe(17);+ });+ });+});diff --git a/packages/base-docs/src/commands/commands/replace-content.command.ts b/packages/base-docs/src/commands/commands/replace-content.command.tsnew file mode 100644index 0000000000..3cf5bfb4e6--- /dev/null+++ b/packages/base-docs/src/commands/commands/replace-content.command.ts@@ -0,0 +1,102 @@+import { ITextRangeWithStyle } from '@univerjs/base-render';+import {+ CommandType,+ ICommand,+ ICommandService,+ IDocumentBody,+ IMutationInfo,+ IUndoRedoService,+ IUniverInstanceService,+} from '@univerjs/core';++import { TextSelectionManagerService } from '../../services/text-selection-manager.service';+import { IRichTextEditingMutationParams, RichTextEditingMutation } from '../mutations/core-editing.mutation';++interface IReplaceContentCommandParams {+ unitId: string;+ body: IDocumentBody; // Do not contain `\r\n` at the end.+ textRanges: ITextRangeWithStyle[];+ segmentId?: string;+}++// Replace all content with new body, and reserve undo/redo stack.+export const ReplaceContentCommand: ICommand<IReplaceContentCommandParams> = {+ id: 'doc.command-replace-content',++ type: CommandType.COMMAND,++ handler: async (accessor, params: IReplaceContentCommandParams) => {+ const { unitId, body, textRanges, segmentId = '' } = params;+ const univerInstanceService = accessor.get(IUniverInstanceService);+ const commandService = accessor.get(ICommandService);+ const textSelectionManagerService = accessor.get(TextSelectionManagerService);+ const undoRedoService = accessor.get(IUndoRedoService);++ const prevBody = univerInstanceService.getCurrentUniverDocInstance().getSnapshot().body;+ const selections = textSelectionManagerService.getSelections();++ if (prevBody == null) {+ return false;+ }++ if (!Array.isArray(selections) || selections.length === 0) {+ return false;+ }++ const doMutation: IMutationInfo<IRichTextEditingMutationParams> = {+ id: RichTextEditingMutation.id,+ params: {+ unitId,+ mutations: [],+ },+ };++ doMutation.params.mutations.push({+ t: 'd',+ len: prevBody?.dataStream.length - 2,+ line: 0,+ segmentId,+ });++ doMutation.params.mutations.push({+ t: 'i',+ body,+ len: body.dataStream.length,+ line: 0,+ segmentId,+ });++ const result = commandService.syncExecuteCommand<+ IRichTextEditingMutationParams,+ IRichTextEditingMutationParams+ >(doMutation.id, doMutation.params);++ textSelectionManagerService.replaceTextRanges(textRanges);++ if (result) {+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ undoMutations: [{ id: RichTextEditingMutation.id, params: result }],+ redoMutations: [{ id: RichTextEditingMutation.id, params: doMutation.params }],+ undo() {+ commandService.syncExecuteCommand(RichTextEditingMutation.id, result);++ textSelectionManagerService.replaceTextRanges(selections);++ return true;+ },+ redo() {+ commandService.syncExecuteCommand(RichTextEditingMutation.id, doMutation.params);++ textSelectionManagerService.replaceTextRanges(textRanges);++ return true;+ },+ });++ return true;+ }++ return false;+ },+};diff --git a/packages/base-docs/src/doc-plugin.ts b/packages/base-docs/src/doc-plugin.tsindex e26b9e166b..9b8518a75e 100644--- a/packages/base-docs/src/doc-plugin.ts+++ b/packages/base-docs/src/doc-plugin.ts@@ -32,6 +32,7 @@ import {SetInlineFormatTextColorCommand,SetInlineFormatUnderlineCommand,} from './commands/commands/inline-format.command';+import { ReplaceContentCommand } from './commands/commands/replace-content.command';import { SetDocZoomRatioCommand } from './commands/commands/set-doc-zoom-ratio.command';import { RichTextEditingMutation } from './commands/mutations/core-editing.mutation';import { MoveCursorOperation, MoveSelectionOperation } from './commands/operations/cursor.operation';@@ -124,6 +125,7 @@ export class DocPlugin extends Plugin {IMEInputCommand,RichTextEditingMutation,CoverCommand,+ ReplaceContentCommand,SetDocZoomRatioCommand,SetDocZoomRatioOperation,SetTextSelectionsOperation,diff --git a/packages/base-docs/src/index.ts b/packages/base-docs/src/index.tsindex de757ea4de..5f94ba82bf 100644--- a/packages/base-docs/src/index.ts+++ b/packages/base-docs/src/index.ts@@ -24,6 +24,7 @@ export {SetInlineFormatTextColorCommand,SetInlineFormatUnderlineCommand,} from './commands/commands/inline-format.command';+export { ReplaceContentCommand } from './commands/commands/replace-content.command';export {type IRichTextEditingMutationParams,RichTextEditingMutation,diff --git a/packages/core/src/types/interfaces/i-document-data.ts b/packages/core/src/types/interfaces/i-document-data.tsindex 96b17c42b1..e13533792c 100644--- a/packages/core/src/types/interfaces/i-document-data.ts+++ b/packages/core/src/types/interfaces/i-document-data.ts@@ -107,8 +107,6 @@ export interface IDocumentBody {customRanges?: ICustomRange[]; // plugin注册,实现针对stream的特殊逻辑,超链接,field,structured document tags, bookmark,comment}-export interface placeHolder {}-export interface IDocStyle {name: string;basedOn: string;