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(sheets-drawing): transform drawings with sheet structure (#7312)
wpxp123456aa61a8462350
diff --git a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.tsindex 17c95a1d1d..ba8d351fce 100644--- a/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts+++ b/packages/drawing/src/services/__tests__/drawing-manager-impl.service.spec.ts@@ -354,6 +354,20 @@ describe('UnitDrawingService', () => {expect(service.getFocusDrawings()).toEqual([]);});+ it('does not add omitted multi-transform fields during a transform refresh', () => {+ const drawing = createDrawing('a', { transform: { left: 0, top: 0 } });+ service.applyJson1(unitId, subUnitId, service.getBatchAddOp([drawing]).redo);++ service.refreshTransform([{ ...drawing, transform: { left: 1, top: 2 } }]);++ expect(service.getDrawingByParam(createSearch('a'))).toEqual({+ ...drawing,+ transform: { left: 1, top: 2 },+ });+ expect(Object.hasOwn(service.getDrawingByParam(createSearch('a'))!, 'transforms')).toBe(false);+ expect(Object.hasOwn(service.getDrawingByParam(createSearch('a'))!, 'isMultiTransform')).toBe(false);+ });+it('should update drawing order in all directions', () => {service.registerDrawingData(unitId, {[subUnitId]: {diff --git a/packages/drawing/src/services/drawing-manager-impl.service.ts b/packages/drawing/src/services/drawing-manager-impl.service.tsindex 14fb80c072..e16080fb70 100644--- a/packages/drawing/src/services/drawing-manager-impl.service.ts+++ b/packages/drawing/src/services/drawing-manager-impl.service.ts@@ -166,8 +166,12 @@ export class UnitDrawingService<T extends IDrawingParam> implements IUnitDrawing}param.transform = updateParam.transform;- param.transforms = updateParam.transforms;- param.isMultiTransform = updateParam.isMultiTransform;+ if (Object.hasOwn(updateParam, 'transforms')) {+ param.transforms = updateParam.transforms;+ }+ if (Object.hasOwn(updateParam, 'isMultiTransform')) {+ param.isMultiTransform = updateParam.isMultiTransform;+ }if ('behindText' in updateParam) {(param as T & IDrawingRefreshMetadata).behindText = (updateParam as T & IDrawingRefreshMetadata).behindText;diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.tsnew file mode 100644index 0000000000..9561d76e40--- /dev/null+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-active-render.controller.ts@@ -0,0 +1,117 @@+/**+ * 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 { ICommandInfo, IDrawingParam, Workbook } from '@univerjs/core';+import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';+import type { ISetWorksheetActiveOperationParams } from '@univerjs/sheets';+import type { ISheetDrawing } from '@univerjs/sheets-drawing';+import { Disposable, ICommandService, Inject } from '@univerjs/core';+import { IDrawingManagerService } from '@univerjs/drawing';+import { SetWorksheetActiveOperation, SheetSkeletonService } from '@univerjs/sheets';+import { drawingPositionToTransform, ISheetDrawingService } from '@univerjs/sheets-drawing';++export class SheetDrawingActiveRenderController extends Disposable implements IRenderModule {+ constructor(+ private readonly _context: IRenderContext<Workbook>,+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService,+ @ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService+ ) {+ super();+ this._commandListener();+ }++ private _commandListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === SetWorksheetActiveOperation.id) {+ const { unitId, subUnitId } = command.params as ISetWorksheetActiveOperationParams;+ this._updateDrawings(unitId, subUnitId);+ }+ })+ );++ this.disposeWithMe(+ this._context.activated$.subscribe((activated) => {+ const { unit, unitId } = this._context;+ if (activated) {+ this._updateDrawings(unitId, unit.getActiveSheet().getSheetId());+ } else {+ this._clearDrawings(unitId);+ }+ })+ );+ }++ private _clearDrawings(selfUnitId: string): void {+ setTimeout(() => {+ const drawingMap = this._drawingManagerService.drawingManagerData;+ const removeDrawings: IDrawingParam[] = [];++ Object.keys(drawingMap ?? {}).forEach((unitId) => {+ const subUnitMap = drawingMap[unitId] ?? {};+ Object.keys(subUnitMap).forEach((subUnitId) => {+ const drawingData = subUnitMap[subUnitId]?.data ?? {};+ Object.keys(drawingData).forEach((drawingId) => {+ if (unitId === selfUnitId) {+ removeDrawings.push(drawingData[drawingId]);+ }+ });+ });+ });++ this._sheetDrawingService.removeNotification(removeDrawings);+ this._drawingManagerService.removeNotification(removeDrawings);+ });+ }++ private _updateDrawings(showUnitId: string, showSubunitId: string): void {+ setTimeout(() => {+ const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(showUnitId, showSubunitId);+ const drawingMap = this._drawingManagerService.drawingManagerData;+ const insertDrawings: IDrawingParam[] = [];+ const removeDrawings: IDrawingParam[] = [];++ Object.keys(drawingMap ?? {}).forEach((unitId) => {+ if (unitId !== showUnitId) {+ return;+ }++ const subUnitMap = drawingMap[unitId] ?? {};+ Object.keys(subUnitMap).forEach((subUnitId) => {+ const drawingData = subUnitMap[subUnitId]?.data ?? {};+ Object.keys(drawingData).forEach((drawingId) => {+ if (unitId === showUnitId && subUnitId === showSubunitId) {+ const drawing = drawingData[drawingId] as ISheetDrawing;+ if (drawing.sheetTransform) {+ drawing.transform = drawingPositionToTransform(drawing.sheetTransform, sheetSkeletonParam);+ }+ insertDrawings.push(drawingData[drawingId]);+ } else {+ removeDrawings.push(drawingData[drawingId]);+ }+ });+ });+ });++ this._sheetDrawingService.removeNotification(removeDrawings);+ this._sheetDrawingService.addNotification(insertDrawings);+ this._drawingManagerService.removeNotification(removeDrawings);+ this._drawingManagerService.addNotification(insertDrawings);+ }, 0);+ }+}diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.tsindex 40d355598f..ee2d226c49 100644--- a/packages/sheets-drawing-ui/src/plugin.ts+++ b/packages/sheets-drawing-ui/src/plugin.ts@@ -41,11 +41,11 @@ import { SheetsDrawingRenderController } from './controllers/render-controllers/import { SheetCellImageAutofillController } from './controllers/sheet-cell-image-autofill.controller';import { SheetCellImageCopyPasteController } from './controllers/sheet-cell-image-copy-paste.controller';import { SheetCellImageController } from './controllers/sheet-cell-image.controller';+import { SheetDrawingActiveRenderController } from './controllers/sheet-drawing-active-render.controller';import { SheetsDrawingCopyPasteController } from './controllers/sheet-drawing-copy-paste.controller';import { SheetsDrawingGroupCopyPasteController } from './controllers/sheet-drawing-group-copy-paste.controller';import { SheetDrawingPermissionController } from './controllers/sheet-drawing-permission.controller';import { SheetDrawingPrintingController } from './controllers/sheet-drawing-printing.controller';-import { SheetDrawingTransformAffectedController } from './controllers/sheet-drawing-transform-affected.controller';import { SheetDrawingUpdateController } from './controllers/sheet-drawing-update.controller';import { SheetDrawingUIController } from './controllers/ui.controller';import { touchSheetsDrawingFloatingHostCapabilityWhenReady } from './embed/floating-host';@@ -133,7 +133,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {private _registerRenderModules(): void {([[SheetDrawingUpdateController],- [SheetDrawingTransformAffectedController],+ [SheetDrawingActiveRenderController],[SheetsDrawingRenderController],[SheetCellImageHoverRenderController],] as Dependency[]).forEach((m) => {diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.ts b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.tssimilarity index 77%rename from packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.tsrename to packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.tsindex da8f0b0fc1..37eb44f07c 100644--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.ts+++ b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.ts@@ -40,6 +40,8 @@ function createSkeleton(options: { rowHeights?: number[]; colWidths?: number[] }columnHeaderHeight: 0,rowTotalHeight: 2000,columnTotalWidth: 1000,+ makeDirty: vi.fn(),+ calculate: vi.fn(),getNoMergeCellWithCoordByIndex: vi.fn((row: number, column: number) => {const startY = sumRows(row);const startX = sumCols(column);@@ -132,12 +134,60 @@ function createController(options: { drawingData?: Record<string, any>; skeletoncontroller._sheetDrawingService = sheetDrawingService;controller._drawingManagerService = drawingManagerService;controller._commandService = { syncExecuteCommand: vi.fn() };+ controller._transformPlanService = {+ transform: vi.fn(() => ({ preRedos: [], redos: [], preUndos: [], undos: [] })),+ };controller._getUnitIdAndSubUnitId = vi.fn(() => ({ unitId: UNIT_ID, subUnitId: SUB_UNIT_ID }));return { controller, skeleton, sheetDrawingService, drawingManagerService };}describe('SheetDrawingTransformAffectedController', () => {+ it('finalizes complete drawing candidates through extensions in mutation order', () => {+ const skeleton = createSkeleton();+ const drawing = createDrawing({ drawingId: 'extended' }, skeleton);+ const { controller, sheetDrawingService } = createController({+ skeleton,+ drawingData: { [drawing.drawingId]: drawing },+ });+ controller._transformPlanService.transform.mockImplementation((plan: any) => {+ const candidate = plan.updates.get(drawing.drawingId);+ expect(candidate).toMatchObject({+ drawingId: drawing.drawingId,+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ anchorType: SheetDrawingAnchorType.Both,+ });+ plan.updates.set(drawing.drawingId, {+ ...candidate,+ transform: { ...candidate.transform, left: 77, top: 88 },+ });+ return {+ preRedos: [{ id: 'feature.pre-redo', params: {} }],+ redos: [{ id: 'feature.redo', params: {} }],+ preUndos: [{ id: 'feature.pre-undo', params: {} }],+ undos: [{ id: 'feature.undo', params: {} }],+ };+ });++ const result = controller._moveColInterceptor({+ range: { startRow: 0, endRow: 9, startColumn: 0, endColumn: 0 },+ }, 'insert');++ expect(result.redos.map(({ id }: any) => id)).toEqual([+ 'feature.pre-redo',+ SetDrawingApplyMutation.id,+ 'feature.redo',+ ClearSheetDrawingTransformerOperation.id,+ ]);+ expect(result.undos.map(({ id }: any) => id)).toEqual([+ 'feature.pre-undo',+ SetDrawingApplyMutation.id,+ 'feature.undo',+ ClearSheetDrawingTransformerOperation.id,+ ]);+ expect(sheetDrawingService.getBatchUpdateOp.mock.calls[0][0][0].transform).toMatchObject({ left: 77, top: 88 });+ });+it('removes drawings covered by deleted rows and shifts drawings below into undoable mutations', () => {const skeleton = createSkeleton();const deleted = createDrawing({@@ -214,6 +264,62 @@ describe('SheetDrawingTransformAffectedController', () => {expect(result.redos).toContainEqual({ id: ClearSheetDrawingTransformerOperation.id, params: [UNIT_ID] });});+ it('shrinks a both-anchored drawing when deleted rows cover its top anchor', () => {+ const skeleton = createSkeleton();+ const drawing = createDrawing({+ drawingId: 'row-delete-top-anchor',+ sheetTransform: {+ from: { row: 2, column: 1, rowOffset: 5, columnOffset: 0 },+ to: { row: 6, column: 2, rowOffset: 5, columnOffset: 5 },+ },+ }, skeleton);+ const { controller, sheetDrawingService } = createController({+ skeleton,+ drawingData: { [drawing.drawingId]: drawing },+ });++ controller._moveRowInterceptor({+ range: { startRow: 2, endRow: 4, startColumn: 0, endColumn: 9 },+ }, 'remove');+ const updatedDrawing = sheetDrawingService.getBatchUpdateOp.mock.calls[0][0][0];++ expect(updatedDrawing).toMatchObject({+ transform: { top: 40, height: 25 },+ sheetTransform: {+ from: { row: 2, rowOffset: 0 },+ to: { row: 3, rowOffset: 5 },+ },+ });+ });++ it('shrinks a both-anchored drawing when deleted columns cover its left anchor', () => {+ const skeleton = createSkeleton();+ const drawing = createDrawing({+ drawingId: 'column-delete-left-anchor',+ sheetTransform: {+ from: { row: 1, column: 2, rowOffset: 0, columnOffset: 5 },+ to: { row: 2, column: 6, rowOffset: 5, columnOffset: 5 },+ },+ }, skeleton);+ const { controller, sheetDrawingService } = createController({+ skeleton,+ drawingData: { [drawing.drawingId]: drawing },+ });++ controller._moveColInterceptor({+ range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 4 },+ }, 'remove');+ const updatedDrawing = sheetDrawingService.getBatchUpdateOp.mock.calls[0][0][0];++ expect(updatedDrawing).toMatchObject({+ transform: { left: 20, width: 15 },+ sheetTransform: {+ from: { column: 2, columnOffset: 0 },+ to: { column: 3, columnOffset: 5 },+ },+ });+ });+it('updates both-anchored drawings when hidden rows cut through their top edge', () => {const skeleton = createSkeleton();const drawing = createDrawing({@@ -334,6 +440,7 @@ describe('SheetDrawingTransformAffectedController', () => {});expect(result.redos).toEqual([{ id: SetDrawingApplyMutation.id, params: { unitId: UNIT_ID, subUnitId: SUB_UNIT_ID, op: 'update-redo', objects: [updatedDrawing], type: DrawingApplyType.UPDATE } },+ { id: ClearSheetDrawingTransformerOperation.id, params: [UNIT_ID] },]);});});diff --git a/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.ts b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.tsnew file mode 100644index 0000000000..85e5423eaf--- /dev/null+++ b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-headless.spec.ts@@ -0,0 +1,223 @@+/**+ * 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 { ISheetDrawing } from '../../services/sheet-drawing.service';+import { Direction, DrawingTypeEnum, ImageSourceType, RANGE_TYPE, RedoCommandId, UndoCommandId } from '@univerjs/core';+import {+ DeleteRangeMoveLeftCommand,+ DeleteRangeMoveUpCommand,+ InsertColCommand,+ InsertRangeMoveDownCommand,+ InsertRangeMoveRightCommand,+ InsertRowCommand,+ MoveColsCommand,+ MoveRangeCommand,+ MoveRowsCommand,+ RemoveColCommand,+ RemoveRowCommand,+ SetColHiddenCommand,+ SetColWidthCommand,+ SetRowHeightCommand,+ SetRowHiddenCommand,+ SetWorksheetRowAutoHeightMutation,+ SheetSkeletonService,+} from '@univerjs/sheets';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { createSheetsDrawingTestBed } from '../../__tests__/create-sheets-drawing-test-bed';+import { drawingPositionToTransform } from '../../basics/transform-position';+import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-drawing.command';+import { ISheetDrawingService, SheetDrawingAnchorType } from '../../services/sheet-drawing.service';++describe('sheet drawing transforms without UI plugins', () => {+ let testBed: ReturnType<typeof createSheetsDrawingTestBed>;++ beforeEach(() => {+ testBed = createSheetsDrawingTestBed();+ });++ afterEach(() => testBed.univer.dispose());++ async function insertDrawing() {+ const sheetTransform = {+ from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },+ to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },+ };+ const skeleton = testBed.get(SheetSkeletonService).getSkeletonParam('test', 'sheet1');+ const drawing: ISheetDrawing = {+ unitId: 'test',+ subUnitId: 'sheet1',+ drawingId: 'drawing-1',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ imageSourceType: ImageSourceType.URL,+ source: 'https://example.com/drawing.png',+ anchorType: SheetDrawingAnchorType.Both,+ sheetTransform,+ axisAlignSheetTransform: sheetTransform,+ transform: drawingPositionToTransform(sheetTransform, skeleton)!,+ };+ expect(await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [drawing],+ })).toBe(true);+ return testBed.get(ISheetDrawingService);+ }++ function getDrawing(service: ISheetDrawingService) {+ return service.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-1' })!;+ }++ it('inserts rows and restores the exact drawing through undo and redo', async () => {+ const service = await insertDrawing();+ const before = structuredClone(getDrawing(service));++ expect(await testBed.commandService.executeCommand(InsertRowCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 },+ direction: Direction.DOWN,+ })).toBe(true);+ const after = structuredClone(getDrawing(service));+ expect(after.transform?.height).toBeGreaterThan(before.transform?.height ?? 0);++ expect(testBed.commandService.syncExecuteCommand(UndoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(before);+ expect(testBed.commandService.syncExecuteCommand(RedoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(after);+ });++ it('resizes both-anchored drawings when row height changes', async () => {+ const service = await insertDrawing();+ const before = structuredClone(getDrawing(service));++ expect(testBed.commandService.syncExecuteCommand(SetRowHeightCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 }],+ value: 40,+ })).toBe(true);+ const after = structuredClone(getDrawing(service));+ expect(after.transform?.height).toBeGreaterThan(before.transform?.height ?? 0);++ expect(testBed.commandService.syncExecuteCommand(UndoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(before);+ expect(testBed.commandService.syncExecuteCommand(RedoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(after);+ });++ it.each([+ ['remove row', RemoveRowCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 },+ }],+ ['insert column', InsertColCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ direction: Direction.RIGHT,+ range: { startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 },+ }],+ ['remove column', RemoveColCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 },+ }],+ ['insert cells down', InsertRangeMoveDownCommand.id, {+ range: { startRow: 2, endRow: 2, startColumn: 1, endColumn: 3 },+ }],+ ['insert cells right', InsertRangeMoveRightCommand.id, {+ range: { startRow: 1, endRow: 4, startColumn: 2, endColumn: 2 },+ }],+ ['delete cells up', DeleteRangeMoveUpCommand.id, {+ range: { startRow: 2, endRow: 2, startColumn: 1, endColumn: 3 },+ }],+ ['delete cells left', DeleteRangeMoveLeftCommand.id, {+ range: { startRow: 1, endRow: 4, startColumn: 2, endColumn: 2 },+ }],+ ['set column width', SetColWidthCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ value: 120,+ ranges: [{ startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 }],+ }],+ ['hide row', SetRowHiddenCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 2, endRow: 2, startColumn: 0, endColumn: 19 }],+ }],+ ['hide column', SetColHiddenCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ ranges: [{ startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 }],+ }],+ ['move rows', MoveRowsCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 1, endRow: 4, startColumn: 0, endColumn: 19, rangeType: RANGE_TYPE.ROW },+ fromRange: { startRow: 1, endRow: 4, startColumn: 0, endColumn: 19 },+ toRange: { startRow: 8, endRow: 11, startColumn: 0, endColumn: 19 },+ }],+ ['move columns', MoveColsCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 19, startColumn: 1, endColumn: 3, rangeType: RANGE_TYPE.COLUMN },+ fromRange: { startRow: 0, endRow: 19, startColumn: 1, endColumn: 3 },+ toRange: { startRow: 0, endRow: 19, startColumn: 7, endColumn: 9 },+ }],+ ['move range', MoveRangeCommand.id, {+ fromUnitId: 'test',+ fromSubUnitId: 'sheet1',+ toUnitId: 'test',+ toSubUnitId: 'sheet1',+ fromRange: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 },+ toRange: { startRow: 8, endRow: 11, startColumn: 7, endColumn: 9 },+ }],+ ])('%s changes drawing geometry and round-trips exactly', async (_name, commandId, params) => {+ const service = await insertDrawing();+ const before = structuredClone(getDrawing(service));++ expect(await testBed.commandService.executeCommand(commandId, params)).toBe(true);+ const after = structuredClone(getDrawing(service));+ expect(after).not.toEqual(before);++ expect(await testBed.commandService.executeCommand(UndoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(before);+ expect(await testBed.commandService.executeCommand(RedoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(after);+ });++ it('refreshes direct auto-height mutations and their inverse without UI', async () => {+ const service = await insertDrawing();+ const before = structuredClone(getDrawing(service));+ const worksheet = testBed.workbook.getSheetBySheetId('sheet1')!;+ const originalHeight = worksheet.getRowHeight(2);++ expect(testBed.commandService.syncExecuteCommand(SetWorksheetRowAutoHeightMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ rowsAutoHeightInfo: [{ row: 2, autoHeight: originalHeight + 30 }],+ })).toBe(true);+ await Promise.resolve();+ expect(getDrawing(service).transform?.height).toBeGreaterThan(before.transform?.height ?? 0);++ expect(testBed.commandService.syncExecuteCommand(SetWorksheetRowAutoHeightMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ rowsAutoHeightInfo: [{ row: 2, autoHeight: originalHeight }],+ })).toBe(true);+ await Promise.resolve();+ expect(getDrawing(service)).toEqual(before);+ });+});diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts b/packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.tssimilarity index 81%rename from packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.tsrename to packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.tsindex 09463ee61a..4f43eb63d4 100644--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-transform-affected.controller.ts+++ b/packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import type { ICommandInfo, IDrawingParam, IMutationInfo, IRange, ITransformState, Nullable, Workbook } from '@univerjs/core';+import type { ICommandInfo, IMutationInfo, IRange, ITransformState, Nullable } from '@univerjs/core';import type { IDrawingJsonUndo1 } from '@univerjs/drawing';-import type { IRenderContext, IRenderModule, SpreadsheetSkeleton } from '@univerjs/engine-render';+import type { SpreadsheetSkeleton } from '@univerjs/engine-render';import type {IDeleteRangeMoveLeftCommandParams,IDeleteRangeMoveUpCommandParams,@@ -40,14 +40,14 @@ import type {ISetRowVisibleMutationParams,ISetSpecificColsVisibleCommandParams,ISetSpecificRowsVisibleCommandParams,- ISetWorksheetActiveOperationParams,ISetWorksheetColWidthMutationParams,ISetWorksheetRowAutoHeightMutationParams,ISetWorksheetRowHeightMutationParams,ISetWorksheetRowIsAutoHeightMutationParams,ISheetSkeletonManagerParam,} from '@univerjs/sheets';-import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';+import type { ISheetDrawingTransformExtensionResult, ISheetDrawingTransformPlan } from '../services/sheet-drawing-transform-plan.service';+import type { ISheetDrawing, ISheetDrawingPosition } from '../services/sheet-drawing.service';import { Disposable, ICommandService, Inject, IUniverInstanceService, RANGE_TYPE, Rectangle } from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';import {@@ -76,7 +76,6 @@ import {SetRowVisibleMutation,SetSpecificColsVisibleCommand,SetSpecificRowsVisibleCommand,- SetWorksheetActiveOperation,SetWorksheetColWidthMutation,SetWorksheetRowAutoHeightMutation,SetWorksheetRowHeightMutation,@@ -85,17 +84,11 @@ import {SheetSkeletonService,SheetsSelectionsService,} from '@univerjs/sheets';-import {- ClearSheetDrawingTransformerOperation,- DrawingApplyType,- drawingPositionToTransform,- ISheetDrawingService,- SetDrawingApplyMutation,- SheetDrawingAnchorType,- transformToAxisAlignPosition,- transformToDrawingPosition,-} from '@univerjs/sheets-drawing';-import { ISheetSelectionRenderService } from '@univerjs/sheets-ui';+import { drawingPositionToTransform, transformToAxisAlignPosition, transformToDrawingPosition } from '../basics/transform-position';+import { DrawingApplyType, SetDrawingApplyMutation } from '../commands/mutations/set-drawing-apply.mutation';+import { ClearSheetDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';+import { SheetDrawingTransformPlanService } from '../services/sheet-drawing-transform-plan.service';+import { ISheetDrawingService, SheetDrawingAnchorType } from '../services/sheet-drawing.service';enum RangeMoveUndoType {deleteLeft,@@ -140,22 +133,22 @@ const REFRESH_MUTATIONS = [SetWorksheetColWidthMutation.id,];-export class SheetDrawingTransformAffectedController extends Disposable implements IRenderModule {+export class SheetDrawingTransformAffectedController extends Disposable {+ private _currentCommand: ICommandInfo = { id: '', params: {} };+constructor(- private readonly _context: IRenderContext<Workbook>,@ICommandService private readonly _commandService: ICommandService,@Inject(SheetSkeletonService) private readonly _sheetSkeletonService: SheetSkeletonService,- @ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,@Inject(SheetInterceptorService) private readonly _sheetInterceptorService: SheetInterceptorService,@Inject(SheetsSelectionsService) private readonly _selectionManagerService: SheetsSelectionsService,@ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,- @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,+ @Inject(SheetDrawingTransformPlanService) private readonly _transformPlanService: SheetDrawingTransformPlanService) {super();this._sheetInterceptorListener();- this._commandListener();this._sheetRefreshListener();}@@ -171,6 +164,8 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenreturn { redos: [], undos: [] };}+ this._currentCommand = commandInfo;+if (id === InsertRowCommand.id) {return this._moveRowInterceptor(params as IInsertRowCommandParams, 'insert');} else if ([MoveColsCommand.id, MoveRowsCommand.id, MoveRangeCommand.id].includes(id)) {@@ -293,6 +288,96 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen);}+ private _finalizePlan(+ unitId: string,+ subUnitId: string,+ updates: Array<Partial<ISheetDrawing>>,+ deletes: Array<Partial<ISheetDrawing>> = [],+ mode: ISheetDrawingTransformPlan['mode'] = 'command',+ command: ICommandInfo = this._currentCommand+ ) {+ const skeleton = this._sheetSkeletonService.getSkeleton(unitId, subUnitId);+ if (!skeleton) {+ return { redos: [], undos: [] };+ }++ const data = this._sheetDrawingService.getDrawingData(unitId, subUnitId);+ const originals = new Map(Object.entries(data));+ const plan: ISheetDrawingTransformPlan = {+ command,+ mode,+ unitId,+ subUnitId,+ skeleton,+ originals,+ updates: new Map(),+ deletes: new Set(deletes.map(({ drawingId }) => drawingId).filter((drawingId): drawingId is string => Boolean(drawingId))),+ };++ updates.forEach((patch) => {+ if (!patch.drawingId) return;+ const original = originals.get(patch.drawingId);+ if (!original) return;+ plan.updates.set(patch.drawingId, {+ ...original,+ ...patch,+ transform: { ...original.transform, ...patch.transform },+ sheetTransform: patch.sheetTransform ?? original.sheetTransform,+ axisAlignSheetTransform: patch.axisAlignSheetTransform ?? original.axisAlignSheetTransform,+ });+ });++ const feature = this._transformPlanService.transform(plan);+ if (mode === 'refresh') {+ const changed = [...plan.updates.values()].filter((drawing) => JSON.stringify(originals.get(drawing.drawingId)) !== JSON.stringify(drawing));+ if (changed.length) {+ this._sheetDrawingService.refreshTransform(changed);+ this._drawingManagerService.refreshTransform(changed);+ this._commandService.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id, [unitId]);+ }+ return { redos: [], undos: [] };+ }++ return this._createPlanMutations(plan, feature);+ }++ private _getCalculatedSkeletonParam(unitId: string, subUnitId: string) {+ const skeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);+ if (!skeletonParam) return;+ skeletonParam.skeleton.makeDirty(true);+ skeletonParam.skeleton.calculate();+ return skeletonParam;+ }++ private _createPlanMutations(plan: ISheetDrawingTransformPlan, feature: Required<ISheetDrawingTransformExtensionResult>) {+ const { unitId, subUnitId } = plan;+ const redos: IMutationInfo[] = [...feature.preRedos];+ const undos: IMutationInfo[] = [...feature.preUndos];+ const updates = [...plan.updates.values()].filter(({ drawingId }) => !plan.deletes.has(drawingId));++ if (updates.length) {+ const { undo, redo, objects } = this._sheetDrawingService.getBatchUpdateOp(updates) as IDrawingJsonUndo1;+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });+ }++ if (plan.deletes.size) {+ const drawings = [...plan.deletes].map((drawingId) => ({ unitId, subUnitId, drawingId })) as ISheetDrawing[];+ const { undo, redo, objects } = this._sheetDrawingService.getBatchRemoveOp(drawings) as IDrawingJsonUndo1;+ redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.REMOVE } });+ undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.INSERT } });+ }++ redos.push(...feature.redos);+ undos.push(...feature.undos);+ if (redos.length || undos.length) {+ redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });+ undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });+ }++ return { redos, undos };+ }+private _getRangeMoveUndo(range: IRange, type: RangeMoveUndoType) {const target = getSheetCommandTarget(this._univerInstanceService);if (!target) {@@ -300,11 +385,11 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}const { unitId, subUnitId } = target;+ if (!this._getCalculatedSkeletonParam(unitId, subUnitId)) {+ return { redos: [], undos: [] };+ }const drawingData = this._sheetDrawingService.getDrawingData(unitId, subUnitId);- const redos: IMutationInfo[] = [];- const undos: IMutationInfo[] = [];-const updateDrawings: Partial<ISheetDrawing>[] = [];const deleteDrawings: Partial<ISheetDrawing>[] = [];@@ -317,33 +402,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemendeleteDrawings.push(...deleteDrawingsPart);});- if (updateDrawings.length === 0 && deleteDrawings.length === 0) {- return { redos: [], undos: [] };- }-- if (updateDrawings.length > 0) {- const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const { undo, redo, objects } = updateJsonOp;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });- }-- if (deleteDrawings.length > 0) {- const deleteJsonOp = this._sheetDrawingService.getBatchRemoveOp(deleteDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const deleteUndo = deleteJsonOp.undo;- const deleteRedo = deleteJsonOp.redo;- const deleteObjects = deleteJsonOp.objects;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteRedo, objects: deleteObjects, type: DrawingApplyType.REMOVE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteUndo, objects: deleteObjects, type: DrawingApplyType.INSERT } });- }-- redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });- undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });-- return {- redos,- undos,- };+ return this._finalizePlan(unitId, subUnitId, updateDrawings, deleteDrawings);}// eslint-disable-next-line max-lines-per-function,complexity@@ -446,10 +505,11 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen// eslint-disable-next-line max-lines-per-functionprivate _getDrawingUndoForColVisible(unitId: string, subUnitId: string, ranges: IRange[]) {- const skeleton = this._sheetSkeletonService.getSkeleton(unitId, subUnitId);- if (!skeleton) {+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);+ if (!sheetSkeletonParam) {return { redos: [], undos: [] };}+ const { skeleton } = sheetSkeletonParam;const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId);const updateDrawings: ISheetDrawing[] = [];@@ -567,53 +627,20 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}});- if (updateDrawings.length === 0 && preUpdateDrawings.length === 0) {- return { redos: [], undos: [] };- }-- const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, updateDrawings);-- const preRedos: IMutationInfo[] = [];- const preUndos: IMutationInfo[] = [];-- if (preUpdateDrawings.length > 0) {- const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, preUpdateDrawings);- preRedos.push(...redos);- preUndos.push(...undos);- }-- return {- redos,- undos,- preRedos,- preUndos,- };+ return this._finalizePlan(unitId, subUnitId, [...preUpdateDrawings, ...updateDrawings]);}private _createUndoAndRedoMutation(unitId: string, subUnitId: string, updateDrawings: ISheetDrawing[]) {- const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const { undo, redo, objects } = updateJsonOp;- const redos: IMutationInfo[] = [- { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } },- { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },- ];- const undos: IMutationInfo[] = [- { id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } },- { id: ClearSheetDrawingTransformerOperation.id, params: [unitId] },- ];-- return {- redos,- undos,- };+ return this._finalizePlan(unitId, subUnitId, updateDrawings);}// eslint-disable-next-line max-lines-per-functionprivate _getDrawingUndoForRowVisible(unitId: string, subUnitId: string, ranges: IRange[]) {- const skeleton = this._sheetSkeletonService.getSkeleton(unitId, subUnitId);- if (!skeleton) {+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);+ if (!sheetSkeletonParam) {return { redos: [], undos: [] };}+ const { skeleton } = sheetSkeletonParam;const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId);const updateDrawings: ISheetDrawing[] = [];@@ -731,31 +758,11 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}});- if (updateDrawings.length === 0 && preUpdateDrawings.length === 0) {- return { redos: [], undos: [] };- }-- const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, updateDrawings);-- const preRedos: IMutationInfo[] = [];- const preUndos: IMutationInfo[] = [];-- if (preUpdateDrawings.length > 0) {- const { redos, undos } = this._createUndoAndRedoMutation(unitId, subUnitId, preUpdateDrawings);- preRedos.push(...redos);- preUndos.push(...undos);- }-- return {- redos,- undos,- preRedos,- preUndos,- };+ return this._finalizePlan(unitId, subUnitId, [...preUpdateDrawings, ...updateDrawings]);}private _getDrawingUndoForRowAndColSize(unitId: string, subUnitId: string, ranges: IRange[]) {- const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);if (!sheetSkeletonParam) {return { redos: [], undos: [] };}@@ -826,7 +833,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}private _moveRangeInterceptor(unitId: string, subUnitId: string, fromRange: IRange, toRange: IRange) {- const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);if (!sheetSkeletonParam) {return { redos: [], undos: [] };}@@ -865,8 +872,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}});- const redos: IMutationInfo[] = [];- const undos: IMutationInfo[] = [];const rowOffset = toRange.startRow - fromRange.startRow;const colOffset = toRange.startColumn - fromRange.startColumn;@@ -888,17 +893,9 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenreturn params;});- if (updateDrawings.length) {- const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const { undo, redo, objects } = updateJsonOp;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });- }-- return { redos, undos };+ return this._finalizePlan(unitId, subUnitId, updateDrawings);}- // eslint-disable-next-line max-lines-per-functionprivate _moveRowInterceptor(params: IInsertRowCommandParams | IRemoveRowColCommandParams, type: 'insert' | 'remove') {const target = this._getUnitIdAndSubUnitId(params, type);if (!target) {@@ -906,7 +903,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}const { unitId, subUnitId } = target;- const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);if (!sheetSkeletonParam) {return { redos: [], undos: [] };}@@ -915,9 +912,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenconst rowStartIndex = range.startRow;const rowEndIndex = range.endRow;- const redos: IMutationInfo[] = [];- const undos: IMutationInfo[] = [];-const data = this._sheetDrawingService.getDrawingData(unitId, subUnitId);const updateDrawings: Partial<ISheetDrawing>[] = [];const deleteDrawings: Partial<ISheetDrawing>[] = [];@@ -972,36 +966,9 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenupdateDrawings.push(params);});- if (updateDrawings.length === 0 && deleteDrawings.length === 0) {- return { redos: [], undos: [] };- }-- if (updateDrawings.length > 0) {- const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const { undo, redo, objects } = updateJsonOp;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });- }-- if (deleteDrawings.length > 0) {- const deleteJsonOp = this._sheetDrawingService.getBatchRemoveOp(deleteDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const deleteUndo = deleteJsonOp.undo;- const deleteRedo = deleteJsonOp.redo;- const deleteObjects = deleteJsonOp.objects;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteRedo, objects: deleteObjects, type: DrawingApplyType.REMOVE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteUndo, objects: deleteObjects, type: DrawingApplyType.INSERT } });- }-- redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });- undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });-- return {- redos,- undos,- };+ return this._finalizePlan(unitId, subUnitId, updateDrawings, deleteDrawings);}- // eslint-disable-next-line max-lines-per-functionprivate _moveColInterceptor(params: IInsertColCommandParams | IRemoveRowColCommandParams, type: 'insert' | 'remove') {const target = this._getUnitIdAndSubUnitId(params, type);if (!target) {@@ -1009,7 +976,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}const { unitId, subUnitId } = target;- const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);if (!sheetSkeletonParam) {return { redos: [], undos: [] };}@@ -1018,9 +985,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenconst colStartIndex = range.startColumn;const colEndIndex = range.endColumn;- const redos: IMutationInfo[] = [];- const undos: IMutationInfo[] = [];-const data = this._sheetDrawingService.getDrawingData(unitId, subUnitId);const updateDrawings: Partial<ISheetDrawing>[] = [];const deleteDrawings: Partial<ISheetDrawing>[] = [];@@ -1075,30 +1039,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenupdateDrawings.push(params);});- if (updateDrawings.length === 0 && deleteDrawings.length === 0) {- return { redos: [], undos: [] };- }-- if (updateDrawings.length > 0) {- const updateJsonOp = this._sheetDrawingService.getBatchUpdateOp(updateDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const { undo, redo, objects } = updateJsonOp;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: redo, objects, type: DrawingApplyType.UPDATE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: undo, objects, type: DrawingApplyType.UPDATE } });- }-- if (deleteDrawings.length > 0) {- const deleteJsonOp = this._sheetDrawingService.getBatchRemoveOp(deleteDrawings as ISheetDrawing[]) as IDrawingJsonUndo1;- const deleteUndo = deleteJsonOp.undo;- const deleteRedo = deleteJsonOp.redo;- const deleteObjects = deleteJsonOp.objects;- redos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteRedo, objects: deleteObjects, type: DrawingApplyType.REMOVE } });- undos.push({ id: SetDrawingApplyMutation.id, params: { unitId, subUnitId, op: deleteUndo, objects: deleteObjects, type: DrawingApplyType.INSERT } });- }-- redos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });- undos.push({ id: ClearSheetDrawingTransformerOperation.id, params: [unitId] });-- return { redos, undos };+ return this._finalizePlan(unitId, subUnitId, updateDrawings, deleteDrawings);}private _expandCol(@@ -1169,7 +1110,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenreturn null;}- // eslint-disable-next-line max-lines-per-function+ // eslint-disable-next-line max-lines-per-function, complexityprivate _shrinkCol(colStartIndex: number,colEndIndex: number,@@ -1225,7 +1166,14 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen};}} else if (fromColumn >= colStartIndex && fromColumn <= colEndIndex) {- if (fromColumn === colStartIndex) {+ if (anchorType === SheetDrawingAnchorType.Both) {+ newSheetTransform = {+ from: { ...from, column: colStartIndex, columnOffset: 0 },+ to: { ...to, column: toColumn - colCount },+ };+ newTransform = drawingPositionToTransform(newSheetTransform, sheetSkeletonParam);+ axisAlignSheetTransform = transformToAxisAlignPosition(newTransform!, skeleton);+ } else if (fromColumn === colStartIndex) {newTransform = { ...transform, left: (transform.left || 0) - sheetTransform.from.columnOffset };} else {const selectionCell = attachRangeWithCoord(skeleton, {@@ -1237,8 +1185,10 @@ export class SheetDrawingTransformAffectedController extends Disposable implemennewTransform = { ...transform, left: (transform.left || 0) - selectionCell.endX + selectionCell.startX - sheetTransform.from.columnOffset };}- newSheetTransform = transformToDrawingPosition(newTransform, skeleton);- axisAlignSheetTransform = transformToAxisAlignPosition(newTransform, skeleton) as ISheetDrawingPosition;+ if (!newSheetTransform) {+ newSheetTransform = transformToDrawingPosition(newTransform!, skeleton);+ axisAlignSheetTransform = transformToAxisAlignPosition(newTransform!, skeleton);+ }} else if (toColumn >= colStartIndex && toColumn <= colEndIndex && anchorType === SheetDrawingAnchorType.Both) {// shrink end col left, then set toColOffset to full cell widthconst selectionCell = attachRangeWithCoord(skeleton, {@@ -1336,7 +1286,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenreturn null;}- // eslint-disable-next-line max-lines-per-function+ // eslint-disable-next-line max-lines-per-function, complexityprivate _shrinkRow(rowStartIndex: number,rowEndIndex: number,@@ -1392,8 +1342,14 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen};}} else if (fromRow >= rowStartIndex && fromRow <= rowEndIndex) {- // shrink start and end row up, then set fromRowOffset to 0- if (fromRow === rowStartIndex) {+ if (anchorType === SheetDrawingAnchorType.Both) {+ newSheetTransform = {+ from: { ...from, row: rowStartIndex, rowOffset: 0 },+ to: { ...to, row: toRow - rowCount },+ };+ newTransform = drawingPositionToTransform(newSheetTransform, sheetSkeletonParam);+ axisAlignSheetTransform = transformToAxisAlignPosition(newTransform!, skeleton);+ } else if (fromRow === rowStartIndex) {newTransform = { ...transform, top: (transform.top || 0) - sheetTransform.from.rowOffset };} else {const selectionCell = attachRangeWithCoord(skeleton, {@@ -1404,8 +1360,10 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen});newTransform = { ...transform, top: (transform.top || 0) - selectionCell.endY + selectionCell.startY - sheetTransform.from.rowOffset };}- newSheetTransform = transformToDrawingPosition(newTransform, skeleton);- axisAlignSheetTransform = transformToAxisAlignPosition(newTransform, skeleton) as ISheetDrawingPosition;+ if (!newSheetTransform) {+ newSheetTransform = transformToDrawingPosition(newTransform!, skeleton);+ axisAlignSheetTransform = transformToAxisAlignPosition(newTransform!, skeleton);+ }} else if (toRow >= rowStartIndex && toRow <= rowEndIndex && anchorType === SheetDrawingAnchorType.Both) {// shrink end row up, then set toRowOffset to full cell heightconst selectionCell = attachRangeWithCoord(skeleton, {@@ -1432,97 +1390,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenreturn null;}- private _commandListener() {- this.disposeWithMe(- // TODO@weird94: this should subscribe to the command service- // but the skeleton changes like other render modules. These two signals are not equivalent.- // As a temp solution, I subscribed to activate$ here.- this._commandService.onCommandExecuted((command: ICommandInfo) => {- if (command.id === SetWorksheetActiveOperation.id) {- const { unitId, subUnitId } = command.params as ISetWorksheetActiveOperationParams;- this._updateDrawings(unitId, subUnitId);- }- })- );-- this.disposeWithMe(- this._context.activated$.subscribe((activated) => {- const { unit, unitId } = this._context;- if (activated) {- const subUnitId = unit.getActiveSheet().getSheetId();- this._updateDrawings(unitId, subUnitId);- } else {- // Better, dispose the command service listener here.- this._clearDrawings(unitId);- }- })- );- }-- private _clearDrawings(selfUnitId: string): void {- setTimeout(() => {- const drawingMap = this._drawingManagerService.drawingManagerData;- const removeDrawings: IDrawingParam[] = [];-- // TODO@weird94: should add a iterating function- Object.keys(drawingMap ?? {}).forEach((unitId) => {- const subUnitMap = drawingMap[unitId] ?? {};-- Object.keys(subUnitMap).forEach((subUnitId) => {- const drawingData = subUnitMap[subUnitId]?.data ?? {};-- Object.keys(drawingData).forEach((drawingId) => {- if (unitId === selfUnitId) {- removeDrawings.push(drawingData[drawingId]);- }- });- });- });-- this._sheetDrawingService.removeNotification(removeDrawings);- this._drawingManagerService.removeNotification(removeDrawings);- });- }-- private _updateDrawings(showUnitId: string, showSubunitId: string): void {- // TODO@weird94: remove the setTimeout here- setTimeout(() => {- const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(showUnitId, showSubunitId);- const drawingMap = this._drawingManagerService.drawingManagerData;- const insertDrawings: IDrawingParam[] = [];- const removeDrawings: IDrawingParam[] = [];-- Object.keys(drawingMap ?? {}).forEach((unitId) => {- if (unitId !== showUnitId) {- return;- }-- const subUnitMap = drawingMap[unitId] ?? {};-- Object.keys(subUnitMap).forEach((subUnitId) => {- const drawingData = subUnitMap[subUnitId]?.data ?? {};-- Object.keys(drawingData).forEach((drawingId) => {- if (unitId === showUnitId && subUnitId === showSubunitId) {- const drawing = drawingData[drawingId] as ISheetDrawing;- if (drawing.sheetTransform) {- drawing.transform = drawingPositionToTransform(drawing.sheetTransform, sheetSkeletonParam);- }- insertDrawings.push(drawingData[drawingId]);- } else {- removeDrawings.push(drawingData[drawingId]);- }- });- });- });-- this._sheetDrawingService.removeNotification(removeDrawings);- this._sheetDrawingService.addNotification(insertDrawings);- this._drawingManagerService.removeNotification(removeDrawings);- this._drawingManagerService.addNotification(insertDrawings);- }, 0);- }-private _sheetRefreshListener() {this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {@@ -1530,7 +1397,7 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenreturn;}- requestIdleCallback(() => {+ queueMicrotask(() => {const params = command.params as| ISetRowVisibleMutationParams| ISetRowHiddenMutationParams@@ -1557,14 +1424,14 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}));}- this._refreshDrawingTransform(unitId, subUnitId, ranges);+ this._refreshDrawingTransform(command, unitId, subUnitId, ranges);});}));}- private _refreshDrawingTransform(unitId: string, subUnitId: string, ranges: IRange[]) {- const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);+ private _refreshDrawingTransform(command: ICommandInfo, unitId: string, subUnitId: string, ranges: IRange[]) {+ const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId) ?? {};const updateDrawings: ISheetDrawing[] = [];@@ -1603,7 +1470,9 @@ export class SheetDrawingTransformAffectedController extends Disposable implemenupdateDrawings.push({...drawing,transform: {- ...newTransform,+ ...transform,+ left: newTransform?.left,+ top: newTransform?.top,width: isPositionAnchor ? transform?.width : newTransform?.width,height: isPositionAnchor ? transform?.height : newTransform?.height,},@@ -1613,13 +1482,6 @@ export class SheetDrawingTransformAffectedController extends Disposable implemen}});- if (updateDrawings.length === 0) {- return;- }-- this._sheetDrawingService.refreshTransform(updateDrawings);- this._drawingManagerService.refreshTransform(updateDrawings);-- this._commandService.syncExecuteCommand(ClearSheetDrawingTransformerOperation.id, [unitId]);+ this._finalizePlan(unitId, subUnitId, updateDrawings, [], 'refresh', command);}}diff --git a/packages/sheets-drawing/src/index.ts b/packages/sheets-drawing/src/index.tsindex d41b8eb5e2..7eff9f9665 100644--- a/packages/sheets-drawing/src/index.ts+++ b/packages/sheets-drawing/src/index.ts@@ -34,6 +34,12 @@ export { isKnownSheetNonRotatableDrawingType, resolveSheetDrawingRotateEnabled }export type { IUniverSheetsDrawingConfig } from './config/config';export { SHEET_DRAWING_PLUGIN } from './controllers/sheet-drawing.controller';export { UniverSheetsDrawingPlugin } from './plugin';+export { SheetDrawingTransformPlanService } from './services/sheet-drawing-transform-plan.service';+export type {+ ISheetDrawingTransformExtension,+ ISheetDrawingTransformExtensionResult,+ ISheetDrawingTransformPlan,+} from './services/sheet-drawing-transform-plan.service';export { ISheetDrawingService, SheetDrawingAnchorType, SheetDrawingService } from './services/sheet-drawing.service';export type {IFloatDomData,diff --git a/packages/sheets-drawing/src/plugin.ts b/packages/sheets-drawing/src/plugin.tsindex d4307a9063..aefc4374a7 100644--- a/packages/sheets-drawing/src/plugin.ts+++ b/packages/sheets-drawing/src/plugin.ts@@ -20,7 +20,9 @@ import { DependentOn, IConfigService, Inject, Injector, merge, Plugin, UniverInsimport { UniverDrawingPlugin } from '@univerjs/drawing';import pkg from '../package.json';import { defaultPluginConfig, SHEETS_DRAWING_PLUGIN_CONFIG_KEY } from './config/config';+import { SheetDrawingTransformAffectedController } from './controllers/sheet-drawing-transform-affected.controller';import { SHEET_DRAWING_PLUGIN, SheetsDrawingLoadController } from './controllers/sheet-drawing.controller';+import { SheetDrawingTransformPlanService } from './services/sheet-drawing-transform-plan.service';import { ISheetDrawingService, SheetDrawingService } from './services/sheet-drawing.service';@DependentOn(UniverDrawingPlugin)@@ -49,9 +51,12 @@ export class UniverSheetsDrawingPlugin extends Plugin {override onStarting(): void {([[SheetsDrawingLoadController],+ [SheetDrawingTransformPlanService],+ [SheetDrawingTransformAffectedController],[ISheetDrawingService, { useClass: SheetDrawingService }],] as Dependency[]).forEach((dependency) => this._injector.add(dependency));this._injector.get(SheetsDrawingLoadController);+ this._injector.get(SheetDrawingTransformAffectedController);}}diff --git a/packages/sheets-drawing/src/services/__tests__/sheet-drawing-transform-plan.service.spec.ts b/packages/sheets-drawing/src/services/__tests__/sheet-drawing-transform-plan.service.spec.tsnew file mode 100644index 0000000000..bca93423c6--- /dev/null+++ b/packages/sheets-drawing/src/services/__tests__/sheet-drawing-transform-plan.service.spec.ts@@ -0,0 +1,66 @@+/**+ * 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 { ISheetDrawingTransformPlan } from '../sheet-drawing-transform-plan.service';+import { describe, expect, it, vi } from 'vitest';+import { SheetDrawingTransformPlanService } from '../sheet-drawing-transform-plan.service';++describe('SheetDrawingTransformPlanService', () => {+ it('runs extensions by priority and aggregates feature mutations', () => {+ const service = new SheetDrawingTransformPlanService();+ const calls: string[] = [];++ service.register({+ priority: 0,+ transform: () => {+ calls.push('low');+ return {+ redos: [{ id: 'low-redo', params: {} }],+ undos: [{ id: 'low-undo', params: {} }],+ };+ },+ });+ service.register({+ priority: 100,+ transform: () => {+ calls.push('high');+ return {+ preRedos: [{ id: 'high-pre-redo', params: {} }],+ preUndos: [{ id: 'high-pre-undo', params: {} }],+ };+ },+ });++ const result = service.transform({ mode: 'command' } as ISheetDrawingTransformPlan);++ expect(calls).toEqual(['high', 'low']);+ expect(result.preRedos).toEqual([{ id: 'high-pre-redo', params: {} }]);+ expect(result.redos).toEqual([{ id: 'low-redo', params: {} }]);+ expect(result.preUndos).toEqual([{ id: 'high-pre-undo', params: {} }]);+ expect(result.undos).toEqual([{ id: 'low-undo', params: {} }]);+ });++ it('stops running an extension after disposal', () => {+ const service = new SheetDrawingTransformPlanService();+ const transform = vi.fn(() => ({}));+ const disposable = service.register({ transform });++ disposable.dispose();+ service.transform({ mode: 'command' } as ISheetDrawingTransformPlan);++ expect(transform).not.toHaveBeenCalled();+ });+});diff --git a/packages/sheets-drawing/src/services/sheet-drawing-transform-plan.service.ts b/packages/sheets-drawing/src/services/sheet-drawing-transform-plan.service.tsnew file mode 100644index 0000000000..b2565dc57d--- /dev/null+++ b/packages/sheets-drawing/src/services/sheet-drawing-transform-plan.service.ts@@ -0,0 +1,78 @@+/**+ * 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 { ICommandInfo, IDisposable, IMutationInfo } from '@univerjs/core';+import type { SpreadsheetSkeleton } from '@univerjs/engine-render';+import type { ISheetDrawing } from './sheet-drawing.service';+import { toDisposable } from '@univerjs/core';++export interface ISheetDrawingTransformPlan {+ command: ICommandInfo;+ mode: 'command' | 'refresh';+ unitId: string;+ subUnitId: string;+ skeleton: SpreadsheetSkeleton;+ originals: ReadonlyMap<string, ISheetDrawing>;+ updates: Map<string, ISheetDrawing>;+ deletes: Set<string>;+}++export interface ISheetDrawingTransformExtensionResult {+ preRedos?: IMutationInfo[];+ redos?: IMutationInfo[];+ preUndos?: IMutationInfo[];+ undos?: IMutationInfo[];+}++export interface ISheetDrawingTransformExtension {+ priority?: number;+ transform(plan: ISheetDrawingTransformPlan): ISheetDrawingTransformExtensionResult | void;+}++function createEmptyResult(): Required<ISheetDrawingTransformExtensionResult> {+ return { preRedos: [], redos: [], preUndos: [], undos: [] };+}++export class SheetDrawingTransformPlanService {+ private readonly _extensions: ISheetDrawingTransformExtension[] = [];++ register(extension: ISheetDrawingTransformExtension): IDisposable {+ this._extensions.push(extension);+ this._extensions.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));++ return toDisposable(() => {+ const index = this._extensions.indexOf(extension);+ if (index >= 0) {+ this._extensions.splice(index, 1);+ }+ });+ }++ transform(plan: ISheetDrawingTransformPlan): Required<ISheetDrawingTransformExtensionResult> {+ return this._extensions.reduce((all, extension) => {+ const next = extension.transform(plan);+ if (!next) {+ return all;+ }++ all.preRedos.push(...(next.preRedos ?? []));+ all.redos.push(...(next.redos ?? []));+ all.preUndos.push(...(next.preUndos ?? []));+ all.undos.push(...(next.undos ?? []));+ return all;+ }, createEmptyResult());+ }+}