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(docs): add chart lifecycle extension seams (#7216)
siamfa718c33943d
diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex 89c9c2b59d..f05b8c95f9 100644--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -19,10 +19,12 @@ import {ArrangeTypeEnum,awaitTime,BooleanNumber,+ CommandType,Direction,DisposableCollection,DrawingTypeEnum,ICommandService,+ IUndoRedoService,IUniverInstanceService,ObjectRelativeFromH,ObjectRelativeFromV,@@ -38,7 +40,9 @@ import {} from '@univerjs/docs';import {DocDrawingController as CoreDocDrawingController,+ DocDrawingAdapterService,DocDrawingService,+ IDocDrawingAdapterService,IDocDrawingService,} from '@univerjs/docs-drawing';import { DocSelectionRenderService } from '@univerjs/docs-ui';@@ -128,6 +132,26 @@ function createDrawingDocData(): IDocumentData {};}+function createChartDrawingDocData(): IDocumentData {+ return {+ ...createDrawingDocData(),+ drawings: {+ 'shape-1': {+ drawingId: 'shape-1',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: DrawingTypeEnum.DRAWING_CHART,+ chartId: 'chart-1',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ positionH: { posOffset: 1 },+ positionV: { posOffset: 2 },+ },+ } as never,+ },+ };+}+function createMultiDrawingDocData(): IDocumentData {return {id: 'test-doc',@@ -301,6 +325,8 @@ function setupDrawingTestBed(docData: IDocumentData, dependencies: Dependency[]injector.add([DocDrawingService]);injector.add([IDocDrawingService, { useClass: DocDrawingService }]);+ injector.add([DocDrawingAdapterService]);+ injector.add([IDocDrawingAdapterService, { useClass: DocDrawingAdapterService }]);injector.add([IDrawingManagerService, { useClass: DrawingManagerService }]);injector.add([DocContentInsertService]);injector.add([DocRefreshDrawingsService]);@@ -438,6 +464,49 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});+ it('uses an explicit text range from command params for drawing insertion', async () => {+ const insertOffset = 3;+ const testBed = setupDrawingTestBed(createBaseDocData());++ testBed.selectionManager.__TEST_ONLY_add([{+ startOffset: 0,+ endOffset: 0,+ collapsed: true,+ isActive: true,+ segmentId: '',+ style: null as never,+ }]);++ expect(await testBed.commandService.executeCommand(InsertDocDrawingCommand.id, {+ textRange: {+ startOffset: insertOffset,+ endOffset: insertOffset,+ collapsed: true,+ segmentId: '',+ },+ drawings: [{+ drawingId: 'shape-1',+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawingType: 'image',+ layoutType: PositionedObjectLayoutType.WRAP_SQUARE,+ docTransform: {+ positionH: { posOffset: 1 },+ positionV: { posOffset: 2 },+ },+ }],+ })).toBe(true);+ await awaitTime(0);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;++ expect(doc.getBody()?.dataStream).toBe('Hel\blo\r\n');+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: insertOffset, blockId: 'shape-1' }]);++ testBed.univer.dispose();+ });+it('replaces the selected drawing block when inserting a new drawing over a selection', async () => {const testBed = setupDrawingTestBed(createDrawingDocData());@@ -498,6 +567,83 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});+ it('includes drawing adapter resource mutations in the same undo item when deleting a drawing', async () => {+ const testBed = setupDrawingTestBed(createChartDrawingDocData());+ const removeResourceMutation = {+ id: 'test.mutation.remove-doc-chart-resource',+ type: CommandType.MUTATION,+ handler: vi.fn(() => true),+ };+ const restoreResourceMutation = {+ id: 'test.mutation.restore-doc-chart-resource',+ type: CommandType.MUTATION,+ handler: vi.fn(() => true),+ };+ testBed.commandService.registerCommand(removeResourceMutation);+ testBed.commandService.registerCommand(restoreResourceMutation);+ const getRemoveDrawingMutationInfos = vi.fn(() => ({+ redoMutations: [{ id: removeResourceMutation.id, params: { chartId: 'chart-1' } }],+ undoMutations: [{ id: restoreResourceMutation.id, params: { chartId: 'chart-1' } }],+ }));+ testBed.get(IDocDrawingAdapterService).registerAdapter({ getRemoveDrawingMutationInfos });++ testBed.docDrawingService.focusDrawing([{ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' }]);++ expect(await testBed.commandService.executeCommand(DeleteDocDrawingsCommand.id)).toBe(true);+ await awaitTime(0);++ expect(getRemoveDrawingMutationInfos).toHaveBeenCalledWith({+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawing: expect.objectContaining({+ drawingId: 'shape-1',+ drawingType: DrawingTypeEnum.DRAWING_CHART,+ chartId: 'chart-1',+ }),+ removeDrawings: [expect.objectContaining({ drawingId: 'shape-1' })],+ });+ expect(removeResourceMutation.handler).toHaveBeenCalled();++ const undoItem = testBed.get(IUndoRedoService).pitchTopUndoElement();+ expect(undoItem?.redoMutations.map((mutation) => mutation.id)).toEqual([+ removeResourceMutation.id,+ RichTextEditingMutation.id,+ ]);+ expect(undoItem?.undoMutations.map((mutation) => mutation.id)).toEqual([+ restoreResourceMutation.id,+ RichTextEditingMutation.id,+ ]);++ testBed.univer.dispose();+ });++ it('does not delete the document drawing when adapter resource removal fails', async () => {+ const testBed = setupDrawingTestBed(createChartDrawingDocData());+ const removeResourceMutation = {+ id: 'test.mutation.remove-doc-chart-resource',+ type: CommandType.MUTATION,+ handler: vi.fn(() => false),+ };+ testBed.commandService.registerCommand(removeResourceMutation);+ testBed.get(IDocDrawingAdapterService).registerAdapter({+ getRemoveDrawingMutationInfos: () => ({+ redoMutations: [{ id: removeResourceMutation.id, params: { chartId: 'chart-1' } }],+ undoMutations: [{ id: 'test.mutation.restore-doc-chart-resource', params: { chartId: 'chart-1' } }],+ }),+ });++ testBed.docDrawingService.focusDrawing([{ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' }]);++ expect(await testBed.commandService.executeCommand(DeleteDocDrawingsCommand.id)).toBe(false);++ const doc = testBed.get(IUniverInstanceService)+ .getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;+ expect(doc.getSnapshot().drawings?.['shape-1']).toMatchObject({ drawingId: 'shape-1' });+ expect(doc.getBody()?.customBlocks).toEqual([{ startIndex: 0, blockId: 'shape-1' }]);++ testBed.univer.dispose();+ });+it('moves a focused floating drawing by updating the persisted doc transform', async () => {const testBed = setupDrawingTestBed(createDrawingDocData());diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.tsindex bc6b595f71..2528ed469e 100644--- a/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/insert-doc-drawing.command.ts@@ -55,7 +55,8 @@ export const InsertDocDrawingCommand: ICommand = {}const unitId = documentDataModel.getUnitId();- const contentInsertRange = getContentInsertRange(accessor, unitId);+ const explicitTextRange = params.textRange == null ? null : normalizeTextRange(params.textRange);+ const contentInsertRange = explicitTextRange ?? getContentInsertRange(accessor, unitId);const targetTextRange = contentInsertRange? {...activeTextRange,@@ -194,3 +195,14 @@ function getContentInsertRange(accessor: IAccessor, unitId: string): ITextRangePreturn null;}}++function normalizeTextRange(textRange: ITextRangeParam): ITextRangeParam {+ const endOffset = textRange.endOffset ?? textRange.startOffset;++ return {+ ...textRange,+ endOffset,+ collapsed: textRange.collapsed ?? textRange.startOffset === endOffset,+ segmentId: textRange.segmentId ?? '',+ };+}diff --git a/packages/docs-drawing-ui/src/commands/commands/interfaces.ts b/packages/docs-drawing-ui/src/commands/commands/interfaces.tsindex e801a03a90..f5552c5579 100644--- a/packages/docs-drawing-ui/src/commands/commands/interfaces.ts+++ b/packages/docs-drawing-ui/src/commands/commands/interfaces.ts@@ -14,12 +14,13 @@* limitations under the License.*/-import type { DrawingTypeEnum } from '@univerjs/core';+import type { DrawingTypeEnum, ITextRangeParam } from '@univerjs/core';import type { IDocDrawing } from '@univerjs/docs-drawing';export interface IInsertDrawingCommandParams {unitId: string;drawings: IDocDrawing[];+ textRange?: ITextRangeParam;}export interface IDeleteDrawingCommandParam {diff --git a/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts b/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.tsindex 97e01aed39..a7b17ba9df 100644--- a/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts+++ b/packages/docs-drawing-ui/src/commands/commands/remove-doc-drawing.command.ts@@ -14,14 +14,16 @@* limitations under the License.*/-import type { DocumentDataModel, IAccessor, ICommand, IMutationInfo, JSONXActions } from '@univerjs/core';+import type { DocumentDataModel, IAccessor, ICommand, IDisposable, IMutationInfo, JSONXActions } from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import type { IDocDrawing } from '@univerjs/docs-drawing';import type { ITextRangeWithStyle } from '@univerjs/engine-render';import type { IDeleteDrawingCommandParams } from './interfaces';import {CommandType,getRichTextEditPath,ICommandService,+ IUndoRedoService,IUniverInstanceService,JSONX,MemoryCursor,@@ -30,6 +32,7 @@ import {UniverInstanceType,} from '@univerjs/core';import { RichTextEditingMutation } from '@univerjs/docs';+import { IDocDrawingAdapterService } from '@univerjs/docs-drawing';import { DocSelectionRenderService } from '@univerjs/docs-ui';import { IRenderManagerService } from '@univerjs/engine-render';@@ -42,6 +45,8 @@ export const RemoveDocDrawingCommand: ICommand = {// eslint-disable-next-line max-lines-per-functionhandler: (accessor: IAccessor, params?: IDeleteDrawingCommandParams) => {const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);+ const drawingAdapterService = accessor.get(IDocDrawingAdapterService);const univerInstanceService = accessor.get(IUniverInstanceService);const renderManagerService = accessor.get(IRenderManagerService);const documentDataModel = univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);@@ -64,7 +69,60 @@ export const RemoveDocDrawingCommand: ICommand = {.filter((block) => !!block).sort((a, b) => a!.startIndex > b!.startIndex ? 1 : -1);- const unitId = removeDrawings[0].unitId;+ const unitId = removeDrawings[0]?.unitId;+ if (unitId == null || removeCustomBlocks.length === 0) {+ return false;+ }++ const drawings = documentDataModel.getDrawings() ?? {};+ const removeDrawingParamById = new Map(removeDrawings.map((drawing) => [drawing.drawingId, drawing]));+ const removeDrawingSnapshots = removeCustomBlocks+ .map((block) => drawings[block!.blockId] as IDocDrawing | undefined)+ .filter((drawing): drawing is IDocDrawing => drawing != null);++ const resourceRedoMutations: IMutationInfo[] = [];+ const resourceUndoMutations: IMutationInfo[] = [];+ const resourceMutationGroups: Array<{ redoMutations: IMutationInfo[]; undoMutations: IMutationInfo[] }> = [];++ for (const block of removeCustomBlocks) {+ const { blockId } = block!;+ const drawing = drawings[blockId] as IDocDrawing | undefined;+ if (drawing == null) {+ continue;+ }++ const removeDrawingParam = removeDrawingParamById.get(blockId);+ const mutationInfos = drawingAdapterService.getRemoveDrawingMutationInfos({+ unitId,+ subUnitId: removeDrawingParam?.subUnitId ?? unitId,+ drawing,+ removeDrawings: removeDrawingSnapshots,+ });++ if (mutationInfos.redoMutations.length === 0 && mutationInfos.undoMutations.length === 0) {+ continue;+ }++ resourceRedoMutations.push(...mutationInfos.redoMutations);+ resourceUndoMutations.push(...mutationInfos.undoMutations);+ resourceMutationGroups.push(mutationInfos);+ }++ if (!executeResourceMutationGroups(resourceMutationGroups, commandService)) {+ return false;+ }++ const historyId = `doc-drawing-remove-resource:${unitId}:${removeCustomBlocks.map((block) => block!.blockId).join(',')}`;+ let batchingDisposable: IDisposable | null = null;+ if (resourceRedoMutations.length > 0 || resourceUndoMutations.length > 0) {+ batchingDisposable = undoRedoService.__tempBatchingUndoRedo(unitId);+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ redoMutations: resourceRedoMutations,+ undoMutations: resourceUndoMutations,+ id: historyId,+ });+ }const memoryCursor = new MemoryCursor();@@ -113,11 +171,10 @@ export const RemoveDocDrawingCommand: ICommand = {for (const block of removeCustomBlocks) {const { blockId } = block!;- const drawing = (documentDataModel.getDrawings() ?? {})[blockId];const drawingOrder = documentDataModel.getDrawingsOrder();const drawingIndex = drawingOrder!.indexOf(blockId);- const removeDrawingAction = jsonX.removeOp(['drawings', blockId], drawing);+ const removeDrawingAction = jsonX.removeOp(['drawings', blockId], drawings[blockId]);const removeDrawingOrderAction = jsonX.removeOp(['drawingsOrder', drawingIndex], blockId);rawActions.push(removeDrawingAction!);@@ -133,6 +190,48 @@ export const RemoveDocDrawingCommand: ICommand = {IRichTextEditingMutationParams>(doMutation.id, doMutation.params);+ if (!result && batchingDisposable != null) {+ batchingDisposable.dispose();+ undoRedoService.rollback(historyId, unitId);+ return false;+ }++ batchingDisposable?.dispose();return Boolean(result);},};++function executeResourceMutationGroups(+ mutationGroups: Array<{ redoMutations: IMutationInfo[]; undoMutations: IMutationInfo[] }>,+ commandService: ICommandService+): boolean {+ const executedUndoGroups: IMutationInfo[][] = [];++ for (const mutationGroup of mutationGroups) {+ const result = executeMutations(mutationGroup.redoMutations, commandService);+ if (!result) {+ executeMutationGroups([...executedUndoGroups].reverse(), commandService);+ return false;+ }++ executedUndoGroups.push(mutationGroup.undoMutations);+ }++ return true;+}++function executeMutationGroups(mutationGroups: IMutationInfo[][], commandService: ICommandService): void {+ mutationGroups.forEach((mutations) => {+ executeMutations(mutations, commandService);+ });+}++function executeMutations(mutations: IMutationInfo[], commandService: ICommandService): boolean {+ for (const mutation of mutations) {+ if (!commandService.syncExecuteCommand(mutation.id, mutation.params)) {+ return false;+ }+ }++ return true;+}diff --git a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.tsindex 965528b36b..965766f14b 100644--- a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts+++ b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts@@ -15,6 +15,7 @@*/import type { DocumentDataModel, IDisposable, Nullable } from '@univerjs/core';+import type { IDocDrawing } from '@univerjs/docs-drawing';import type { BaseObject, Scene } from '@univerjs/engine-render';import {DrawingTypeEnum,@@ -28,6 +29,7 @@ import {UniverInstanceType,} from '@univerjs/core';import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import { IDocDrawingAdapterService } from '@univerjs/docs-drawing';import { IDrawingManagerService } from '@univerjs/drawing';import {COMPONENT_IMAGE_POPUP_MENU,@@ -52,6 +54,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,@IContextService private readonly _contextService: IContextService,+ @IDocDrawingAdapterService private readonly _drawingAdapterService: IDocDrawingAdapterService,@ICommandService private readonly _commandService: ICommandService) {@@ -240,13 +243,18 @@ export class DocDrawingPopupMenuController extends RxDisposable {}private _getImageMenuItems(unitId: string, subUnitId: string, drawingId: string, drawingType: number) {+ const drawing = this._drawingManagerService.getDrawingByParam({ unitId, subUnitId, drawingId }) as IDocDrawing | null;+ const editCommandInfo = drawing+ ? this._drawingAdapterService.getEditDrawingCommandInfo({ unitId, subUnitId, drawing })+ : null;+return [{- label: 'docs-drawing-ui.image-popup.edit',+ label: editCommandInfo?.label ?? 'docs-drawing-ui.image-popup.edit',index: 0,- commandId: EditDocDrawingOperation.id,- commandParams: { unitId, subUnitId, drawingId },- disable: drawingType === DrawingTypeEnum.DRAWING_DOM,+ commandId: editCommandInfo?.commandId ?? EditDocDrawingOperation.id,+ commandParams: editCommandInfo?.commandParams ?? { unitId, subUnitId, drawingId },+ disable: editCommandInfo?.disable ?? drawingType === DrawingTypeEnum.DRAWING_DOM,},{label: 'docs-drawing-ui.image-popup.delete',diff --git a/packages/docs-drawing/src/index.ts b/packages/docs-drawing/src/index.tsindex cf214e626e..2ee785b675 100644--- a/packages/docs-drawing/src/index.ts+++ b/packages/docs-drawing/src/index.ts@@ -19,6 +19,12 @@ export { DOCS_DRAWING_PLUGIN, getDocDrawingRenderOrder } from './controllers/docexport type { IDocDrawingModel } from './controllers/doc-drawing.controller';export { DocDrawingController } from './controllers/doc-drawing.controller';export { UniverDocsDrawingPlugin } from './plugin';+export { DocDrawingAdapterService, IDocDrawingAdapterService } from './services/doc-drawing-adapter.service';+export type {+ IDocDrawingAdapter,+ IDocDrawingMutationInfos,+ IDocDrawingRemoveMutationInfoParams,+} from './services/doc-drawing-adapter.service';export { DocDrawingService, IDocDrawingService } from './services/doc-drawing.service';export type { IDocDrawing, IDocImage } from './services/doc-drawing.service';export { type IDocFloatDom } from './services/doc-drawing.service';diff --git a/packages/docs-drawing/src/plugin.ts b/packages/docs-drawing/src/plugin.tsindex 82afeabbfc..2a78205534 100644--- a/packages/docs-drawing/src/plugin.ts+++ b/packages/docs-drawing/src/plugin.ts@@ -20,6 +20,7 @@ import { IConfigService, Inject, Injector, merge, Plugin, touchDependencies, Uniimport pkg from '../package.json';import { defaultPluginConfig, DOCS_DRAWING_PLUGIN_CONFIG_KEY } from './config/config';import { DocDrawingController, DOCS_DRAWING_PLUGIN } from './controllers/doc-drawing.controller';+import { DocDrawingAdapterService, IDocDrawingAdapterService } from './services/doc-drawing-adapter.service';import { DocDrawingService, IDocDrawingService } from './services/doc-drawing.service';export class UniverDocsDrawingPlugin extends Plugin {@@ -47,6 +48,8 @@ export class UniverDocsDrawingPlugin extends Plugin {override onStarting(): void {([[DocDrawingController],+ [DocDrawingAdapterService],+ [IDocDrawingAdapterService, { useClass: DocDrawingAdapterService }],[DocDrawingService],[IDocDrawingService, { useClass: DocDrawingService }],] as Dependency[]).forEach((dependency) => this._injector.add(dependency));diff --git a/packages/docs-drawing/src/services/__tests__/doc-drawing-adapter.service.spec.ts b/packages/docs-drawing/src/services/__tests__/doc-drawing-adapter.service.spec.tsnew file mode 100644index 0000000000..859ce5f8e8--- /dev/null+++ b/packages/docs-drawing/src/services/__tests__/doc-drawing-adapter.service.spec.ts@@ -0,0 +1,74 @@+/**+ * 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 { describe, expect, it } from 'vitest';+import { DocDrawingAdapterService } from '../doc-drawing-adapter.service';++describe('DocDrawingAdapterService', () => {+ it('collects removal mutations from registered drawing adapters in order', () => {+ const service = new DocDrawingAdapterService();+ service.registerAdapter({+ getRemoveDrawingMutationInfos: () => ({+ redoMutations: [{ id: 'redo-1', params: { value: 1 } }],+ undoMutations: [{ id: 'undo-1', params: { value: 1 } }],+ }),+ });+ service.registerAdapter({+ getRemoveDrawingMutationInfos: () => ({+ redoMutations: [{ id: 'redo-2', params: { value: 2 } }],+ undoMutations: [{ id: 'undo-2', params: { value: 2 } }],+ }),+ });++ expect(service.getRemoveDrawingMutationInfos({+ unitId: 'doc-1',+ subUnitId: 'doc-1',+ drawing: { drawingId: 'drawing-1' } as never,+ removeDrawings: [{ drawingId: 'drawing-1' } as never],+ })).toEqual({+ redoMutations: [+ { id: 'redo-1', params: { value: 1 } },+ { id: 'redo-2', params: { value: 2 } },+ ],+ undoMutations: [+ { id: 'undo-1', params: { value: 1 } },+ { id: 'undo-2', params: { value: 2 } },+ ],+ });+ });++ it('unregisters disposed adapters', () => {+ const service = new DocDrawingAdapterService();+ const disposable = service.registerAdapter({+ getRemoveDrawingMutationInfos: () => ({+ redoMutations: [{ id: 'redo-1', params: {} }],+ undoMutations: [{ id: 'undo-1', params: {} }],+ }),+ });++ disposable.dispose();++ expect(service.getRemoveDrawingMutationInfos({+ unitId: 'doc-1',+ subUnitId: 'doc-1',+ drawing: { drawingId: 'drawing-1' } as never,+ removeDrawings: [{ drawingId: 'drawing-1' } as never],+ })).toEqual({+ redoMutations: [],+ undoMutations: [],+ });+ });+});diff --git a/packages/docs-drawing/src/services/doc-drawing-adapter.service.ts b/packages/docs-drawing/src/services/doc-drawing-adapter.service.tsnew file mode 100644index 0000000000..f9f649f394--- /dev/null+++ b/packages/docs-drawing/src/services/doc-drawing-adapter.service.ts@@ -0,0 +1,106 @@+/**+ * 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 { IDisposable, IMutationInfo } from '@univerjs/core';+import type { IDocDrawing } from './doc-drawing.service';+import { createIdentifier, toDisposable } from '@univerjs/core';++export interface IDocDrawingRemoveMutationInfoParams {+ unitId: string;+ subUnitId: string;+ drawing: IDocDrawing;+ removeDrawings: readonly IDocDrawing[];+}++export interface IDocDrawingEditCommandInfoParams {+ unitId: string;+ subUnitId: string;+ drawing: IDocDrawing;+}++export interface IDocDrawingMutationInfos {+ redoMutations: IMutationInfo[];+ undoMutations: IMutationInfo[];+}++export interface IDocDrawingEditCommandInfo {+ label?: string;+ commandId: string;+ commandParams?: unknown;+ disable?: boolean;+}++export interface IDocDrawingAdapter {+ getRemoveDrawingMutationInfos?: (+ params: IDocDrawingRemoveMutationInfoParams+ ) => IDocDrawingMutationInfos | null | undefined;+ getEditDrawingCommandInfo?: (+ params: IDocDrawingEditCommandInfoParams+ ) => IDocDrawingEditCommandInfo | null | undefined;+}++export interface IDocDrawingAdapterService {+ registerAdapter(adapter: IDocDrawingAdapter): IDisposable;+ getRemoveDrawingMutationInfos(params: IDocDrawingRemoveMutationInfoParams): IDocDrawingMutationInfos;+ getEditDrawingCommandInfo(params: IDocDrawingEditCommandInfoParams): IDocDrawingEditCommandInfo | null;+}++export const IDocDrawingAdapterService = createIdentifier<IDocDrawingAdapterService>('doc.drawing-adapter.service');++export class DocDrawingAdapterService implements IDocDrawingAdapterService {+ private readonly _adapters: IDocDrawingAdapter[] = [];++ registerAdapter(adapter: IDocDrawingAdapter): IDisposable {+ this._adapters.push(adapter);++ return toDisposable(() => {+ const index = this._adapters.indexOf(adapter);+ if (index >= 0) {+ this._adapters.splice(index, 1);+ }+ });+ }++ getRemoveDrawingMutationInfos(params: IDocDrawingRemoveMutationInfoParams): IDocDrawingMutationInfos {+ const mutationInfos: IDocDrawingMutationInfos = {+ redoMutations: [],+ undoMutations: [],+ };++ for (const adapter of this._adapters) {+ const nextMutationInfos = adapter.getRemoveDrawingMutationInfos?.(params);+ if (!nextMutationInfos) {+ continue;+ }++ mutationInfos.redoMutations.push(...nextMutationInfos.redoMutations);+ mutationInfos.undoMutations.push(...nextMutationInfos.undoMutations);+ }++ return mutationInfos;+ }++ getEditDrawingCommandInfo(params: IDocDrawingEditCommandInfoParams): IDocDrawingEditCommandInfo | null {+ for (const adapter of this._adapters) {+ const commandInfo = adapter.getEditDrawingCommandInfo?.(params);+ if (commandInfo) {+ return commandInfo;+ }+ }++ return null;+ }+}diff --git a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts b/packages/docs-ui/src/commands/commands/clipboard.inner.command.tsindex 0f03549f22..17dfd60d13 100644--- a/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts+++ b/packages/docs-ui/src/commands/commands/clipboard.inner.command.ts@@ -16,10 +16,13 @@import type {DocumentDataModel,+ IAccessor,ICommand,ICustomTable,+ IDisposable,IDocumentBody,IDocumentData,+ IDrawingParam,IMutationInfo,ITextRange,JSONXActions,@@ -33,6 +36,7 @@ import {generateRandomId,getRichTextEditPath,ICommandService,+ IUndoRedoService,IUniverInstanceService,JSONX,MemoryCursor,@@ -44,6 +48,8 @@ import {} from '@univerjs/core';import { DocSelectionManagerService, RichTextEditingMutation } from '@univerjs/docs';import { getCustomDecorationAtPosition, getCustomRangeAtPosition } from '../../basics/paragraph';+import type { IDocClipboardPasteCustomBlockMapping } from '../../services/clipboard/doc-paste-mutation-adapter.service';+import { IDocClipboardPasteAdapterService } from '../../services/clipboard/doc-paste-mutation-adapter.service';import { getCommandSkeleton } from '../util';import { getDeleteRowContentActionParams, getDeleteRowsActionsParams, getDeleteTableActionParams } from './table/table';@@ -94,8 +100,10 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {handler: async (accessor, params: IInnerPasteCommandParams) => {const { segmentId, textRanges, doc } = params;const commandService = accessor.get(ICommandService);+ const undoRedoService = accessor.get(IUndoRedoService);const docSelectionManagerService = accessor.get(DocSelectionManagerService);const univerInstanceService = accessor.get(IUniverInstanceService);+ const pasteAdapterService = getPasteAdapterService(accessor);const selections = docSelectionManagerService.getTextRanges();const rectRanges = docSelectionManagerService.getRectRanges();const { body, tableSource, drawings } = doc;@@ -126,6 +134,9 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {const textX = new TextX();const jsonX = JSONX.getInstance();const rawActions: JSONXActions = [];+ const resourceRedoMutations: IMutationInfo[] = [];+ const resourceUndoMutations: IMutationInfo[] = [];+ const resourceMutationGroups: Array<{ redoMutations: IMutationInfo[]; undoMutations: IMutationInfo[] }> = [];const hasTable = !!body.tables?.length;const hasCustomBlock = !!body.customBlocks?.length;@@ -173,6 +184,7 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {if (hasCustomBlock && drawings) {const drawingLen = docDataModel.getSnapshot().drawingsOrder?.length ?? 0;+ const customBlockMappings: IDocClipboardPasteCustomBlockMapping[] = [];for (const block of cloneBody.customBlocks!) {const { blockId } = block;@@ -181,15 +193,42 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {block.blockId = drawingId;- const drawing = Tools.deepClone(drawings[blockId]);+ const sourceDrawing = drawings[blockId] as IDrawingParam;+ const drawing = Tools.deepClone(sourceDrawing) as IDrawingParam;drawing.drawingId = drawingId;- const action = jsonX.insertOp(['drawings', drawingId], drawing);- const orderAction = jsonX.insertOp(['drawingsOrder', drawingLen], drawingId);+ customBlockMappings.push({+ sourceBlockId: blockId,+ targetBlockId: drawingId,+ sourceDrawing,+ targetDrawing: drawing,+ });+ }++ if (customBlockMappings.length > 0 && pasteAdapterService) {+ const mutationInfos = pasteAdapterService.getPasteMutationInfos({+ unitId,+ segmentId,+ doc,+ sourceBody: body,+ targetBody: cloneBody,+ customBlockMappings,+ });++ if (mutationInfos.redoMutations.length > 0 || mutationInfos.undoMutations.length > 0) {+ resourceRedoMutations.push(...mutationInfos.redoMutations);+ resourceUndoMutations.push(...mutationInfos.undoMutations);+ resourceMutationGroups.push(mutationInfos);+ }+ }++ customBlockMappings.forEach(({ targetBlockId, targetDrawing }) => {+ const action = jsonX.insertOp(['drawings', targetBlockId], targetDrawing);+ const orderAction = jsonX.insertOp(['drawingsOrder', drawingLen], targetBlockId);rawActions.push(action!);rawActions.push(orderAction!);- }+ });}const customRange = getCustomRangeAtPosition(originBody.customRanges ?? [], endOffset, UNITS.includes(unitId));@@ -235,15 +274,81 @@ export const InnerPasteCommand: ICommand<IInnerPasteCommandParams> = {return JSONX.compose(acc, cur as JSONXActions);}, null as JSONXActions);+ if (!executeResourceMutationGroups(resourceMutationGroups, commandService)) {+ return false;+ }++ const historyId = `doc-paste-resource:${unitId}:${Date.now()}`;+ let batchingDisposable: IDisposable | null = null;+ if (resourceRedoMutations.length > 0 || resourceUndoMutations.length > 0) {+ batchingDisposable = undoRedoService.__tempBatchingUndoRedo(unitId);+ undoRedoService.pushUndoRedo({+ unitID: unitId,+ redoMutations: resourceRedoMutations,+ undoMutations: resourceUndoMutations,+ id: historyId,+ });+ }+const result = commandService.syncExecuteCommand<IRichTextEditingMutationParams,IRichTextEditingMutationParams>(doMutation.id, doMutation.params);+ if (!result && batchingDisposable != null) {+ batchingDisposable.dispose();+ undoRedoService.rollback(historyId, unitId);+ return false;+ }++ batchingDisposable?.dispose();return Boolean(result);},};+function getPasteAdapterService(accessor: IAccessor) {+ try {+ return accessor.get(IDocClipboardPasteAdapterService);+ } catch {+ return null;+ }+}++function executeResourceMutationGroups(+ mutationGroups: Array<{ redoMutations: IMutationInfo[]; undoMutations: IMutationInfo[] }>,+ commandService: ICommandService+): boolean {+ const executedUndoGroups: IMutationInfo[][] = [];++ for (const mutationGroup of mutationGroups) {+ const result = executeMutations(mutationGroup.redoMutations, commandService);+ if (!result) {+ executeMutationGroups([...executedUndoGroups].reverse(), commandService);+ return false;+ }++ executedUndoGroups.push(mutationGroup.undoMutations);+ }++ return true;+}++function executeMutationGroups(mutationGroups: IMutationInfo[][], commandService: ICommandService): void {+ mutationGroups.forEach((mutations) => {+ executeMutations(mutations, commandService);+ });+}++function executeMutations(mutations: IMutationInfo[], commandService: ICommandService): boolean {+ for (const mutation of mutations) {+ if (!commandService.syncExecuteCommand(mutation.id, mutation.params)) {+ return false;+ }+ }++ return true;+}+// TODO: WORKAROUND to fix https://github.com/dream-num/univer-pro/issues/2560.function adjustSelectionByTable(selection: ITextRange, tables: ICustomTable[]): ITextRange {const { startOffset, endOffset } = selection;diff --git a/packages/docs-ui/src/index.ts b/packages/docs-ui/src/index.tsindex cf9a1a62d7..b713a7bb6a 100644--- a/packages/docs-ui/src/index.ts+++ b/packages/docs-ui/src/index.ts@@ -194,6 +194,16 @@ export { menuSchema as DocsUIMenuSchema } from './menu/schema';export { UniverDocsUIPlugin } from './plugin';export * from './services';export { IDocClipboardService } from './services/clipboard/clipboard.service';+export {+ DocClipboardPasteAdapterService,+ IDocClipboardPasteAdapterService,+} from './services/clipboard/doc-paste-mutation-adapter.service';+export type {+ IDocClipboardPasteAdapter,+ IDocClipboardPasteCustomBlockMapping,+ IDocClipboardPasteMutationInfoParams,+ IDocClipboardPasteMutationInfos,+} from './services/clipboard/doc-paste-mutation-adapter.service';export { convertBodyToHtml } from './services/clipboard/udm-to-html/convertor';export { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';export type { DocHtmlExportTransformer } from './services/clipboard/udm-to-html/doc-html-export.service';diff --git a/packages/docs-ui/src/plugin.ts b/packages/docs-ui/src/plugin.tsindex a9a3311ecc..2d3d84b914 100644--- a/packages/docs-ui/src/plugin.ts+++ b/packages/docs-ui/src/plugin.ts@@ -117,6 +117,7 @@ import { DocRenderController } from './controllers/render-controllers/doc.renderimport { DocZoomRenderController } from './controllers/render-controllers/zoom.render-controller';import { DocUIController } from './controllers/ui.controller';import { DocClipboardService, IDocClipboardService } from './services/clipboard/clipboard.service';+import { DocClipboardPasteAdapterService, IDocClipboardPasteAdapterService } from './services/clipboard/doc-paste-mutation-adapter.service';import { DocHtmlExportService } from './services/clipboard/udm-to-html/doc-html-export.service';import { DocAutoFormatService } from './services/doc-auto-format.service';import { DocEventManagerService } from './services/doc-event-manager.service';@@ -373,6 +374,8 @@ export class UniverDocsUIPlugin extends Plugin {[DocParagraphSettingController],[IEditorService, { useClass: EditorService }],[IDocClipboardService, { useClass: DocClipboardService }],+ [DocClipboardPasteAdapterService],+ [IDocClipboardPasteAdapterService, { useClass: DocClipboardPasteAdapterService }],[DocHtmlExportService],[DocCanvasPopManagerService],[DocsRenderService],diff --git a/packages/docs-ui/src/services/clipboard/clipboard.service.ts b/packages/docs-ui/src/services/clipboard/clipboard.service.tsindex 2fcef1669f..b9714e39ad 100644--- a/packages/docs-ui/src/services/clipboard/clipboard.service.ts+++ b/packages/docs-ui/src/services/clipboard/clipboard.service.ts@@ -76,7 +76,12 @@ HtmlToUDMService.use(WordPastePlugin);export interface IClipboardPropertyItem { }+export interface IDocClipboardCopyDocDataContext {+ sourceDocuments: IDocumentData[];+}+export interface IDocClipboardHook {+ onCopyDocData?(doc: Partial<IDocumentData>, context: IDocClipboardCopyDocDataContext): Partial<IDocumentData>;onCopyProperty?(start: number, end: number): IClipboardPropertyItem;onCopyContent?(start: number, end: number): string;onBeforePaste?: (body: IDocumentBody) => IDocumentBody;@@ -394,6 +399,7 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ}if (internalDocData) {+ internalDocData = this._applyCopyDocDataHooks(internalDocData, documentList);internalJson = createInternalClipboardFragment(internalDocData);html = embedInternalClipboardFragment(html, internalJson);}@@ -415,6 +421,12 @@ export class DocClipboardService extends Disposable implements IDocClipboardServ});}+ private _applyCopyDocDataHooks(doc: Partial<IDocumentData>, sourceDocuments: IDocumentData[]): Partial<IDocumentData> {+ return this._clipboardHooks.reduce((currentDoc, hook) => {+ return hook.onCopyDocData?.(currentDoc, { sourceDocuments }) ?? currentDoc;+ }, doc);+ }+private _getDocumentBodyInRanges(sliceType: SliceBodyType, ranges?: ITextRangeWithStyle[]) {const docDataModel = this._univerInstanceService.getCurrentUnitOfType<DocumentDataModel>(UniverInstanceType.UNIVER_DOC);const allRanges = ranges ?? this._docSelectionManagerService.getDocRanges();diff --git a/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts b/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.tsnew file mode 100644index 0000000000..8c531f6cc1--- /dev/null+++ b/packages/docs-ui/src/services/clipboard/doc-paste-mutation-adapter.service.ts@@ -0,0 +1,86 @@+/**+ * 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 { IDisposable, IDocumentBody, IDocumentData, IDrawingParam, IMutationInfo } from '@univerjs/core';+import { createIdentifier, toDisposable } from '@univerjs/core';++export interface IDocClipboardPasteCustomBlockMapping {+ sourceBlockId: string;+ targetBlockId: string;+ sourceDrawing: IDrawingParam;+ targetDrawing: IDrawingParam;+}++export interface IDocClipboardPasteMutationInfoParams {+ unitId: string;+ segmentId: string;+ doc: Partial<IDocumentData>;+ sourceBody: IDocumentBody;+ targetBody: IDocumentBody;+ customBlockMappings: IDocClipboardPasteCustomBlockMapping[];+}++export interface IDocClipboardPasteMutationInfos {+ redoMutations: IMutationInfo[];+ undoMutations: IMutationInfo[];+}++export interface IDocClipboardPasteAdapter {+ getPasteMutationInfos?: (+ params: IDocClipboardPasteMutationInfoParams+ ) => IDocClipboardPasteMutationInfos | null | undefined;+}++export interface IDocClipboardPasteAdapterService {+ registerAdapter(adapter: IDocClipboardPasteAdapter): IDisposable;+ getPasteMutationInfos(params: IDocClipboardPasteMutationInfoParams): IDocClipboardPasteMutationInfos;+}++export const IDocClipboardPasteAdapterService = createIdentifier<IDocClipboardPasteAdapterService>('doc.clipboard-paste-adapter.service');++export class DocClipboardPasteAdapterService implements IDocClipboardPasteAdapterService {+ private readonly _adapters: IDocClipboardPasteAdapter[] = [];++ registerAdapter(adapter: IDocClipboardPasteAdapter): IDisposable {+ this._adapters.push(adapter);++ return toDisposable(() => {+ const index = this._adapters.indexOf(adapter);+ if (index >= 0) {+ this._adapters.splice(index, 1);+ }+ });+ }++ getPasteMutationInfos(params: IDocClipboardPasteMutationInfoParams): IDocClipboardPasteMutationInfos {+ const mutationInfos: IDocClipboardPasteMutationInfos = {+ redoMutations: [],+ undoMutations: [],+ };++ for (const adapter of this._adapters) {+ const nextMutationInfos = adapter.getPasteMutationInfos?.(params);+ if (!nextMutationInfos) {+ continue;+ }++ mutationInfos.redoMutations.push(...nextMutationInfos.redoMutations);+ mutationInfos.undoMutations.push(...nextMutationInfos.undoMutations);+ }++ return mutationInfos;+ }+}