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
fix(sheets-drawing): preserve move-only anchor geometry (#7813)
Univer7ec57999adf1
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.tsindex 4a5d0d46be..2fabd63990 100644--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-active-render.controller.spec.ts@@ -30,7 +30,6 @@ import {} from '@univerjs/sheets-drawing';import { BehaviorSubject } from 'rxjs';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { createSheetsDrawingUiTestBed } from '../../__tests__/create-sheets-drawing-ui-test-bed';import { SheetDrawingActiveRenderController } from '../sheet-drawing-active-render.controller';@@ -38,13 +37,16 @@ function createTestBed() {const bed = createSheetsDrawingUiTestBed();const activated$ = new BehaviorSubject(false);const context = { unit: bed.workbook, unitId: bed.unitId, activated$ } as unknown as IRenderContext<Workbook>;- bed.injector.add([SheetDrawingActiveRenderController, {- useFactory: () => bed.injector.createInstance(SheetDrawingActiveRenderController, context),- }]);+ const createController = () => bed.injector.createInstance(SheetDrawingActiveRenderController, context);+ bed.injector.add([SheetDrawingActiveRenderController, { useFactory: createController }]);return { ...bed, activated$ };}-async function insertDrawing(bed: ReturnType<typeof createTestBed>, anchorType: SheetDrawingAnchorType | undefined) {+async function insertDrawing(+ bed: ReturnType<typeof createTestBed>,+ anchorType: SheetDrawingAnchorType | undefined,+ position?: { left: number; top: number }+) {const sheetTransform = {from: { row: 3, column: 3, rowOffset: 0, columnOffset: 0 },to: { row: 6, column: 6, rowOffset: 0, columnOffset: 0 },@@ -61,7 +63,7 @@ async function insertDrawing(bed: ReturnType<typeof createTestBed>, anchorType:anchorType,sheetTransform,axisAlignSheetTransform: sheetTransform,- transform: { left, top, width, height },+ transform: { left, top, width, height, ...position },};expect(await bed.commandService.executeCommand(InsertSheetDrawingCommand.id, {unitId: bed.unitId,@@ -119,15 +121,30 @@ describe('SheetDrawingActiveRenderController', () => {}});- it('preserves unanchored geometry during activation', async () => {+ it.each([SheetDrawingAnchorType.None, undefined])('activates absolute or legacy cell-anchored geometry (%s)', async (anchorType) => {const bed = createTestBed();try {- const drawing = await insertDrawing(bed, SheetDrawingAnchorType.None);+ const drawing = await insertDrawing(bed, anchorType, { left: 1000, top: 2000 });bed.get(SheetDrawingActiveRenderController);bed.activated$.next(true);vi.runOnlyPendingTimers();- expect(bed.get(IDrawingManagerService).getDrawingByParam(drawing)).toEqual(drawing);- expect(bed.get(ISheetDrawingService).getDrawingByParam(drawing)).toEqual(drawing);+ const current = bed.get(ISheetDrawingService).getDrawingByParam(drawing)!;+ expect(bed.get(IDrawingManagerService).getDrawingByParam(drawing)).toEqual(current);+ if (anchorType === SheetDrawingAnchorType.None) {+ expect(current).toEqual(drawing);+ } else {+ const skeleton = bed.get(SheetSkeletonService).getSkeletonParam(bed.unitId, bed.subUnitId);+ const position = drawingPositionToTransform(drawing.sheetTransform, skeleton)!;+ expect(current.transform).toMatchObject({+ left: position.left,+ top: position.top,+ width: drawing.transform!.width,+ height: drawing.transform!.height,+ });+ expect(current.transform?.left).not.toBe(1000);+ expect(current.transform?.top).not.toBe(2000);+ expect(getSheetDrawingPlacement(current).kind).toBe(SheetDrawingAnchorType.Position);+ }} finally {bed.univer.dispose();bed.activated$.complete();diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.tsindex 0cf7c91445..b008c78651 100644--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-copy-paste.controller.spec.ts@@ -14,42 +14,44 @@* limitations under the License.*/-import type { IRange } from '@univerjs/core';+import type { IRange, IWorkbookData } from '@univerjs/core';+import type { IDrawingJsonUndo1 } from '@univerjs/drawing';+import type { ISheetImage } from '@univerjs/sheets-drawing';import type { ISheetClipboardHook } from '@univerjs/sheets-ui';-import { DrawingTypeEnum, ICommandService, ImageSourceType, Injector, ObjectMatrix } from '@univerjs/core';+import {+ BooleanNumber,+ DrawingTypeEnum,+ ImageSourceType,+ LocaleType,+ ObjectMatrix,+ UniverInstanceType,+} from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';-import { IRenderManagerService } from '@univerjs/engine-render';import { SheetSkeletonService } from '@univerjs/sheets';-import { RemoveSheetDrawingCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';-import { COPY_TYPE, ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE } from '@univerjs/sheets-ui';-import { IClipboardInterfaceService } from '@univerjs/ui';-import { describe, expect, it, vi } from 'vitest';-+import { ISheetDrawingService, RemoveSheetDrawingCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';+import {+ COPY_TYPE,+ IMarkSelectionService,+ ISheetClipboardService,+ MarkSelectionService,+ PREDEFINED_HOOK_NAME_PASTE,+ SheetClipboardService,+} from '@univerjs/sheets-ui';+import {+ DesktopNotificationService,+ IClipboardInterfaceService,+ INotificationService,+ IPlatformService,+ IUIPartsService,+ PlatformService,+ UIPartsService,+} from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createSheetsDrawingUiTestBed } from '../../__tests__/create-sheets-drawing-ui-test-bed';import { InsertFloatImageCommand } from '../../commands/commands/insert-image.command';import { SheetsDrawingCopyPasteController } from '../sheet-drawing-copy-paste.controller';-function createSkeleton() {- return {- getNoMergeCellWithCoordByIndex: vi.fn((row: number, column: number) => ({- startX: column * 10,- endX: column * 10 + 10,- startY: row * 20,- endY: row * 20 + 20,- })),- getCellIndexAndOffsetByPosition: vi.fn((left: number, top: number) => {- const column = Math.floor(left / 10);- const row = Math.floor(top / 20);- return {- column,- row,- columnOffset: left - column * 10,- rowOffset: top - row * 20,- };- }),- };-}--function createImageDrawing(overrides: Record<string, unknown> = {}) {+function createImageDrawing(overrides: Partial<ISheetImage> = {}): ISheetImage {return {unitId: 'unit-1',subUnitId: 'sheet-1',@@ -90,42 +92,70 @@ interface ITestClipboardHook extends ISheetClipboardHook {onPasteUnrecognized: NonNullable<ISheetClipboardHook['onPasteUnrecognized']>;}-function createController(options?: { focusedDrawings?: IImageDrawing[]; drawingData?: Record<string, object> }) {- let hook: ISheetClipboardHook | undefined;- const skeleton = createSkeleton();- const drawingService = {- getFocusDrawings: vi.fn(() => options?.focusedDrawings ?? []),- getDrawingData: vi.fn(() => options?.drawingData ?? {}),- getBatchAddOp: vi.fn((drawings: IImageDrawing[]) => ({ undo: 'add-undo', redo: 'add-redo', objects: drawings })),- getBatchUpdateOp: vi.fn((drawings: IImageDrawing[]) => ({ undo: 'update-undo', redo: 'update-redo', objects: drawings })),- };- const commandService = {- executeCommand: vi.fn(),- };- const clipboardInterfaceService = { writeText: vi.fn() };- const hookDisposable = { dispose: vi.fn() };- const sheetClipboardService = {- addClipboardHook: vi.fn((config: ISheetClipboardHook) => {- hook = config;- return hookDisposable;- }),+const testBeds: ReturnType<typeof createSheetsDrawingUiTestBed>[] = [];++function createWorkbookData(unitId: string, subUnitId: string): IWorkbookData {+ return {+ id: unitId,+ name: 'Book',+ appVersion: '1.0.0',+ locale: LocaleType.EN_US,+ styles: {},+ sheetOrder: [subUnitId],+ sheets: {+ [subUnitId]: {+ id: subUnitId,+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ defaultRowHeight: 20,+ defaultColumnWidth: 10,+ rowHeader: { width: 0, hidden: BooleanNumber.TRUE },+ columnHeader: { height: 0, hidden: BooleanNumber.TRUE },+ cellData: {},+ },+ },};+}- const injector = new Injector([- [ISheetClipboardService, { useValue: sheetClipboardService }],- [IRenderManagerService, { useValue: {} }],- [SheetSkeletonService, { useValue: { getSkeleton: vi.fn(() => skeleton) } }],- [IDrawingManagerService, { useValue: drawingService }],+function createController(options?: { focusedDrawings?: IImageDrawing[]; drawingData?: Record<string, object> }) {+ const clipboardInterfaceService = { writeText: vi.fn() };+ const bed = createSheetsDrawingUiTestBed(createWorkbookData('unit-1', 'sheet-1'), [+ [ISheetClipboardService, { useClass: SheetClipboardService }],+ [IMarkSelectionService, { useClass: MarkSelectionService }],[IClipboardInterfaceService, { useValue: clipboardInterfaceService }],- [ICommandService, { useValue: commandService }],+ [INotificationService, { useClass: DesktopNotificationService }],+ [IPlatformService, { useClass: PlatformService }],+ [IUIPartsService, { useClass: UIPartsService }],[SheetsDrawingCopyPasteController],]);- const controller = injector.get(SheetsDrawingCopyPasteController);+ testBeds.push(bed);+ bed.univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData('unit-2', 'sheet-2'));+ const skeletonService = bed.get(SheetSkeletonService);+ skeletonService.ensureSkeleton('unit-1', 'sheet-1');+ skeletonService.ensureSkeleton('unit-2', 'sheet-2');+ const drawingManager = bed.get(IDrawingManagerService);+ const data: Record<string, object> = { ...options?.drawingData };+ for (const drawing of options?.focusedDrawings ?? []) {+ data[drawing.drawingId] = drawing;+ }+ const drawingData = { 'sheet-1': { data, order: Object.keys(data) } };+ bed.get(ISheetDrawingService).registerDrawingData('unit-1', drawingData as never);+ drawingManager.registerDrawingData('unit-1', drawingData as never);+ drawingManager.focusDrawing(options?.focusedDrawings ?? []);+ const drawingService = {+ getBatchAddOp: vi.spyOn(drawingManager, 'getBatchAddOp'),+ };+ const commandService = { executeCommand: vi.spyOn(bed.commandService, 'executeCommand') };+ const sheetClipboardService = bed.get(ISheetClipboardService);+ const addClipboardHook = vi.spyOn(sheetClipboardService, 'addClipboardHook');+ const controller = bed.get(SheetsDrawingCopyPasteController);+ const hookDisposable = addClipboardHook.mock.results[0].value;+ vi.spyOn(hookDisposable, 'dispose');return {controller,- hook: hook as ITestClipboardHook,- skeleton,+ hook: sheetClipboardService.getClipboardHooks()[0] as ITestClipboardHook,drawingService,commandService,clipboardInterfaceService,@@ -134,6 +164,10 @@ function createController(options?: { focusedDrawings?: IImageDrawing[]; drawing}describe('SheetsDrawingCopyPasteController', () => {+ afterEach(() => {+ testBeds.splice(0).forEach((bed) => bed.univer.dispose());+ vi.restoreAllMocks();+ });it('cancels all pending clipboard writes when disposed', () => {vi.useFakeTimers();const { controller, hook, clipboardInterfaceService } = createController({@@ -197,14 +231,14 @@ describe('SheetsDrawingCopyPasteController', () => {}});- it('copies default position-anchored images contained in a cell range', () => {- const positionOnlyDrawing = createImageDrawing({- drawingId: 'position-only',- anchorType: undefined,+ it('does not copy explicitly absolute images with a cell range', () => {+ const defaultDrawing = createImageDrawing({+ drawingId: 'absolute-anchor',+ anchorType: SheetDrawingAnchorType.None,});const { controller, hook, drawingService } = createController({drawingData: {- [positionOnlyDrawing.drawingId]: positionOnlyDrawing,+ [defaultDrawing.drawingId]: defaultDrawing,},});@@ -229,18 +263,17 @@ describe('SheetsDrawingCopyPasteController', () => {{ copyId: 'range-copy', copyType: COPY_TYPE.COPY, pasteType: PREDEFINED_HOOK_NAME_PASTE.DEFAULT_PASTE });- expect(drawingService.getBatchAddOp).toHaveBeenCalledTimes(1);- expect(drawingService.getBatchAddOp.mock.calls[0][0]).toMatchObject([{- unitId: 'unit-2',- subUnitId: 'sheet-2',- transform: { left: 35, top: 45, width: 10, height: 20 },- }]);+ expect(drawingService.getBatchAddOp).not.toHaveBeenCalled();controller.dispose();});- it('copies drawings contained in a cell range and pastes them with the range offset', () => {- const containedDrawing = createImageDrawing();+ it.each([+ SheetDrawingAnchorType.Both,+ SheetDrawingAnchorType.Position,+ undefined,+ ])('copies contained images with range offsets (%s)', (anchorType) => {+ const containedDrawing = createImageDrawing({ anchorType });const outsideDrawing = createImageDrawing({drawingId: 'outside-image',transform: { left: 80, top: 80, width: 10, height: 20 },@@ -298,8 +331,9 @@ describe('SheetsDrawingCopyPasteController', () => {},});expect(pastedDrawing.drawingId).not.toBe(containedDrawing.drawingId);+ const addOperation = drawingService.getBatchAddOp.mock.results[0].value as IDrawingJsonUndo1;expect(mutations.redos).toEqual([- expect.objectContaining({ params: expect.objectContaining({ op: 'add-redo', objects: [pastedDrawing] }) }),+ expect.objectContaining({ params: expect.objectContaining({ op: addOperation.redo, objects: addOperation.objects }) }),]);controller.dispose();@@ -340,8 +374,9 @@ describe('SheetsDrawingCopyPasteController', () => {transform: { left: 40, top: 60, width: 10, height: 20 },});expect(pastedDrawing.drawingId).not.toBe(focusedDrawing.drawingId);+ const addOperation = drawingService.getBatchAddOp.mock.results[0].value as IDrawingJsonUndo1;expect(mutations.redos).toEqual([- expect.objectContaining({ params: expect.objectContaining({ op: 'add-redo', objects: [pastedDrawing] }) }),+ expect.objectContaining({ params: expect.objectContaining({ op: addOperation.redo, objects: addOperation.objects }) }),]);controller.dispose();diff --git a/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.render-controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.render-controller.spec.tsindex b3ad3ff5ef..1364dfb976 100644--- a/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.render-controller.spec.ts+++ b/packages/sheets-drawing-ui/src/controllers/render-controllers/__tests__/sheet-drawing.render-controller.spec.ts@@ -15,136 +15,138 @@*/import type { ISheetDrawing } from '@univerjs/sheets-drawing';-import { DrawingTypeEnum, Injector } from '@univerjs/core';+import type { Subscription } from 'rxjs';+import { DrawingTypeEnum, LocaleType, UniverInstanceType } from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';+import { CanvasColorService, ICanvasColorService, IRenderManagerService } from '@univerjs/engine-render';import { SheetSkeletonService } from '@univerjs/sheets';import { ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';import { describe, expect, it, vi } from 'vitest';-+import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';import { SheetsDrawingRenderController } from '../sheet-drawing.render-controller';describe('SheetsDrawingRenderController', () => {- it('initializes sheet drawing data and materializes sheet transforms for render objects', () => {- const drawingWithSheetTransform: Partial<ISheetDrawing> = {- unitId: 'unit-1',- subUnitId: 'sheet-1',- drawingId: 'drawing-1',- sheetTransform: {- from: { row: 1, column: 2, rowOffset: 0, columnOffset: 0 },- to: { row: 3, column: 4, rowOffset: 0, columnOffset: 0 },- },- };- const drawingWithoutSkeleton: Partial<ISheetDrawing> = {- unitId: 'unit-1',- subUnitId: 'missing-sheet',- drawingId: 'drawing-2',- anchorType: SheetDrawingAnchorType.Both,- sheetTransform: {- from: { row: 5, column: 6, rowOffset: 0, columnOffset: 0 },- to: { row: 7, column: 8, rowOffset: 0, columnOffset: 0 },- },- };- const groupedDrawing: Partial<ISheetDrawing> = {- unitId: 'unit-1',- subUnitId: 'sheet-1',- drawingId: 'drawing-4',- groupId: 'group-1',- anchorType: SheetDrawingAnchorType.Position,- transform: { left: 2, top: 3, width: 40, height: 50 },- sheetTransform: {- from: { row: 1, column: 2, rowOffset: 0, columnOffset: 0 },- to: { row: 3, column: 4, rowOffset: 0, columnOffset: 0 },+ it('renders legacy cell anchors while preserving explicit absolute and group-local bounds', () => {+ const canvasContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(+ { setTransform: vi.fn(), clearRect: vi.fn() } as unknown as CanvasRenderingContext2D+ );+ const bed = createSheetsDrawingUiTestBed({+ id: 'unit-1',+ name: 'Book',+ appVersion: '1.0.0',+ locale: LocaleType.EN_US,+ styles: {},+ sheetOrder: ['sheet-1'],+ sheets: {+ 'sheet-1': {+ id: 'sheet-1',+ name: 'Sheet1',+ rowCount: 20,+ columnCount: 20,+ defaultRowHeight: 36,+ defaultColumnWidth: 12,+ cellData: {},+ },},- };- const drawingGroup: Partial<ISheetDrawing> = {- unitId: 'unit-1',- subUnitId: 'sheet-1',- drawingId: 'drawing-5',- drawingType: DrawingTypeEnum.DRAWING_GROUP,- anchorType: SheetDrawingAnchorType.Both,- sheetTransform: {+ }, [[ICanvasColorService, { useClass: CanvasColorService }]]);+ const subscriptions: Subscription[] = [];+ try {+ const sheetTransform = {from: { row: 1, column: 2, rowOffset: 0, columnOffset: 0 },to: { row: 3, column: 4, rowOffset: 0, columnOffset: 0 },- },- };- const absoluteDrawing: Partial<ISheetDrawing> = {- unitId: 'unit-1',- subUnitId: 'sheet-1',- drawingId: 'drawing-6',- anchorType: SheetDrawingAnchorType.None,- transform: { left: 240, top: 96, width: 120, height: 80 },- sheetTransform: {- from: { row: 0, column: 0, rowOffset: 96, columnOffset: 240 },- to: { row: 0, column: 0, rowOffset: 176, columnOffset: 360 },- },- };- const drawingData = {- 'sheet-1': {- data: {- 'drawing-1': drawingWithSheetTransform,- 'drawing-3': { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'drawing-3' },- 'drawing-4': groupedDrawing,- 'drawing-5': drawingGroup,- 'drawing-6': absoluteDrawing,+ };+ const legacy: Partial<ISheetDrawing> = {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ drawingId: 'legacy-anchor',+ drawingType: DrawingTypeEnum.DRAWING_DOM,+ sheetTransform,+ transform: { left: 1000, top: 2000, width: 24, height: 72 },+ };+ const missingSkeleton: Partial<ISheetDrawing> = {+ unitId: 'unit-1',+ subUnitId: 'missing-sheet',+ drawingId: 'missing-skeleton',+ anchorType: SheetDrawingAnchorType.Both,+ sheetTransform,+ };+ const grouped: Partial<ISheetDrawing> = {+ ...legacy,+ drawingId: 'grouped',+ groupId: 'group-1',+ anchorType: SheetDrawingAnchorType.Position,+ transform: { left: 2, top: 3, width: 40, height: 50 },+ };+ const group: Partial<ISheetDrawing> = {+ ...legacy,+ drawingId: 'group',+ drawingType: DrawingTypeEnum.DRAWING_GROUP,+ anchorType: SheetDrawingAnchorType.Both,+ };+ const absolute: Partial<ISheetDrawing> = {+ ...legacy,+ drawingId: 'absolute',+ anchorType: SheetDrawingAnchorType.None,+ transform: { left: 240, top: 96, width: 120, height: 80 },+ };+ const drawingData = {+ 'sheet-1': {+ data: {+ [legacy.drawingId!]: legacy,+ [grouped.drawingId!]: grouped,+ [group.drawingId!]: group,+ [absolute.drawingId!]: absolute,+ 'missing-transform': { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'missing-transform' },+ },+ order: ['legacy-anchor', 'grouped', 'group', 'absolute', 'missing-transform'],},- },- 'missing-sheet': {- data: {- 'drawing-2': drawingWithoutSkeleton,+ 'missing-sheet': {+ data: { [missingSkeleton.drawingId!]: missingSkeleton },+ order: ['missing-skeleton'],},- },- };- const sheetDrawingService = {- initializeNotification: vi.fn(),- getDrawingDataForUnit: vi.fn(() => drawingData),- };- const drawingManagerService = {- registerDrawingData: vi.fn(),- initializeNotification: vi.fn(),- };- const skeletonParam = {- skeleton: {- getNoMergeCellWithCoordByIndex: (row: number, column: number) => ({- startX: column * 12,- endX: (column + 1) * 12,- startY: row * 36,- endY: (row + 1) * 36,- }),- rowHeaderWidth: 10,- columnHeaderHeight: 20,- columnTotalWidth: 1000,- rowTotalHeight: 2000,- rowHeaderWidthAndMarginLeft: 10,- columnHeaderHeightAndMarginTop: 20,- },- };- const sheetSkeletonService = {- getSkeletonParam: vi.fn((unitId: string, subUnitId: string) => {- if (unitId === 'unit-1' && subUnitId === 'sheet-1') {- return skeletonParam;- }-- return null;- }),- };-- const injector = new Injector([- [ISheetDrawingService, { useValue: sheetDrawingService }],- [IDrawingManagerService, { useValue: drawingManagerService }],- [SheetSkeletonService, { useValue: sheetSkeletonService }],- ]);- const controller = injector.createInstance(SheetsDrawingRenderController, { unitId: 'unit-1' } as never);-- expect(sheetDrawingService.initializeNotification).toHaveBeenCalledWith('unit-1');- expect(drawingWithSheetTransform.transform).toMatchObject({ left: 24, top: 36, width: 24, height: 72 });- expect(drawingGroup.transform).toMatchObject({ left: 14, top: 16, width: 24, height: 72 });- expect(groupedDrawing.transform).toEqual({ left: 2, top: 3, width: 40, height: 50 });- expect(absoluteDrawing.transform).toEqual({ left: 240, top: 96, width: 120, height: 80 });- expect(drawingWithoutSkeleton).not.toHaveProperty('transform');- expect(drawingManagerService.registerDrawingData).toHaveBeenCalledWith('unit-1', drawingData);- expect(drawingManagerService.initializeNotification).toHaveBeenCalledWith('unit-1');+ };+ const sheetDrawingService = bed.get(ISheetDrawingService);+ const drawingManagerService = bed.get(IDrawingManagerService);+ const skeleton = bed.get(SheetSkeletonService).ensureSkeleton('unit-1', 'sheet-1');+ if (!skeleton) {+ throw new Error('Expected the Sheet skeleton to exist.');+ }+ sheetDrawingService.registerDrawingData('unit-1', drawingData as never);+ const sheetDrawingsAdded = vi.fn();+ const renderDrawingsAdded = vi.fn();+ subscriptions.push(+ sheetDrawingService.add$.subscribe(sheetDrawingsAdded),+ drawingManagerService.add$.subscribe(renderDrawingsAdded)+ );+ const renderManager = bed.get(IRenderManagerService);+ renderManager.registerRenderModule(UniverInstanceType.UNIVER_SHEET, [SheetsDrawingRenderController]);+ const render = renderManager.createRender('unit-1');+ render.with(SheetsDrawingRenderController);- controller.dispose();- injector.dispose();+ const initializedDrawings = Object.values(drawingData).flatMap((subUnit) => Object.values(subUnit.data));+ expect(sheetDrawingsAdded).toHaveBeenCalledExactlyOnceWith(expect.arrayContaining(initializedDrawings));+ expect(renderDrawingsAdded).toHaveBeenCalledExactlyOnceWith(expect.arrayContaining(initializedDrawings));+ const marker = skeleton.getNoMergeCellWithCoordByIndex(1, 2);+ expect(legacy.transform).toMatchObject({ left: marker.startX, top: marker.startY, width: 24, height: 72 });+ expect(legacy).not.toHaveProperty('anchorType');+ expect(group.transform).toMatchObject({+ left: marker.startX - skeleton.rowHeaderWidthAndMarginLeft,+ top: marker.startY - skeleton.columnHeaderHeightAndMarginTop,+ width: 24,+ height: 72,+ });+ expect(grouped.transform).toEqual({ left: 2, top: 3, width: 40, height: 50 });+ expect(absolute.transform).toEqual({ left: 240, top: 96, width: 120, height: 80 });+ expect(missingSkeleton).not.toHaveProperty('transform');+ expect(drawingManagerService.getDrawingByParam({+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ drawingId: 'legacy-anchor',+ })?.transform).toEqual(legacy.transform);+ } finally {+ subscriptions.forEach((subscription) => subscription.unsubscribe());+ bed.univer.dispose();+ canvasContext.mockRestore();+ }});});diff --git a/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.ts b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.tsindex 7f7a720be9..adc77e1e56 100644--- a/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.ts+++ b/packages/sheets-drawing/src/controllers/__tests__/sheet-drawing-transform-affected.controller.spec.ts@@ -14,10 +14,23 @@* limitations under the License.*/-import type { Workbook } from '@univerjs/core';+import type { IWorkbookData, Workbook } from '@univerjs/core';import type { ISheetDrawingPlacement } from '../../services/sheet-drawing-placement';import type { ISheetDrawing } from '../../services/sheet-drawing.service';-import { Direction, DrawingTypeEnum, ICommandService, ImageSourceType, Injector, IUniverInstanceService, RANGE_TYPE, RedoCommandId, Tools, UndoCommandId, UniverInstanceType } from '@univerjs/core';+import {+ Direction,+ DrawingTypeEnum,+ ICommandService,+ ImageSourceType,+ Injector,+ IResourceLoaderService,+ IUniverInstanceService,+ RANGE_TYPE,+ RedoCommandId,+ Tools,+ UndoCommandId,+ UniverInstanceType,+} from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';import {DeleteRangeMoveLeftCommand,@@ -51,10 +64,15 @@ import { InsertSheetDrawingCommand } from '../../commands/commands/insert-sheet-import { SetSheetDrawingPlacementCommand } from '../../commands/commands/set-sheet-drawing-placement.command';import { DrawingApplyType, SetDrawingApplyMutation } from '../../commands/mutations/set-drawing-apply.mutation';import { ClearSheetDrawingTransformerOperation } from '../../commands/operations/clear-drawing-transformer.operation';-import { applySheetDrawingPlacement, getSheetDrawingPlacement, normalizeSheetDrawingPlacement } from '../../services/sheet-drawing-placement';+import {+ applySheetDrawingPlacement,+ getSheetDrawingPlacement,+ normalizeSheetDrawingPlacement,+} from '../../services/sheet-drawing-placement';import { SheetDrawingTransformPlanService } from '../../services/sheet-drawing-transform-plan.service';import { ISheetDrawingService, SheetDrawingAnchorType } from '../../services/sheet-drawing.service';import { SheetDrawingTransformAffectedController } from '../sheet-drawing-transform-affected.controller';+import { SHEET_DRAWING_PLUGIN } from '../sheet-drawing.controller';const UNIT_ID = 'unit-1';const SUB_UNIT_ID = 'sheet-1';@@ -574,7 +592,7 @@ describe('sheet drawing transforms without UI plugins', () => {afterEach(() => testBed.univer.dispose());- async function insertDrawing() {+ async function insertDrawing(anchorType: SheetDrawingAnchorType | undefined) {const sheetTransform = {from: { row: 1, column: 1, rowOffset: 0, columnOffset: 0 },to: { row: 4, column: 3, rowOffset: 0, columnOffset: 0 },@@ -587,7 +605,7 @@ describe('sheet drawing transforms without UI plugins', () => {drawingType: DrawingTypeEnum.DRAWING_IMAGE,imageSourceType: ImageSourceType.URL,source: 'https://example.com/drawing.png',- anchorType: SheetDrawingAnchorType.Both,+ anchorType,sheetTransform,axisAlignSheetTransform: sheetTransform,transform: drawingPositionToTransform(sheetTransform, skeleton)!,@@ -603,8 +621,29 @@ describe('sheet drawing transforms without UI plugins', () => {return service.getDrawingByParam({ unitId: 'test', subUnitId: 'sheet1', drawingId: 'drawing-1' })!;}+ it.each([DeleteRangeMoveLeftCommand.id, DeleteRangeMoveUpCommand.id])('%s removes a legacy cell anchor and preserves an explicit absolute image', async (commandId) => {+ const service = await insertDrawing(undefined);+ const before = structuredClone(getDrawing(service));+ const absolute = { ...before, drawingId: 'absolute-image', anchorType: SheetDrawingAnchorType.None };+ expect(await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [absolute],+ })).toBe(true);++ expect(await testBed.commandService.executeCommand(commandId, {+ range: { startRow: 1, endRow: 4, startColumn: 1, endColumn: 3 },+ })).toBe(true);+ expect(getDrawing(service)).toBeUndefined();+ expect(service.getDrawingByParam(absolute)).toEqual(absolute);+ expect(await testBed.commandService.executeCommand(UndoCommandId)).toBe(true);+ expect(getDrawing(service)).toEqual(before);+ expect(await testBed.commandService.executeCommand(RedoCommandId)).toBe(true);+ expect(getDrawing(service)).toBeUndefined();+ expect(service.getDrawingByParam(absolute)).toEqual(absolute);+ });+it('inserts rows and restores the exact drawing through undo and redo', async () => {- const service = await insertDrawing();+ const service = await insertDrawing(SheetDrawingAnchorType.Both);const before = structuredClone(getDrawing(service));expect(await testBed.commandService.executeCommand(InsertRowCommand.id, {@@ -675,7 +714,7 @@ describe('sheet drawing transforms without UI plugins', () => {subUnitId: 'sheet1',ranges: [{ startRow: 0, endRow: 19, startColumn: 2, endColumn: 2 }],}],- ])('%s preserves the three placement contracts in headless mode', async (_name, commandId, params) => {+ ])('%s preserves explicit and default placement contracts in headless mode', async (_name, commandId, params) => {const skeleton = testBed.get(SheetSkeletonService).ensureSkeleton('test', 'sheet1');if (!skeleton) {throw new Error('Expected the Sheet skeleton to exist.');@@ -760,6 +799,8 @@ describe('sheet drawing transforms without UI plugins', () => {const after = readDrawings();expect(after[0].transform).not.toEqual(before[0].transform);expect(after[2].transform).toEqual(before[2].transform);+ expect(after[3].transform).toEqual(after[0].transform);+ expect(getSheetDrawingPlacement(after[3])).toEqual(getSheetDrawingPlacement(after[0]));expect(getSheetDrawingPlacement(after[2])).toEqual(getSheetDrawingPlacement(before[2]));expect(after[0].transform?.width).toBe(before[0].transform?.width);expect(after[0].transform?.height).toBe(before[0].transform?.height);@@ -787,8 +828,93 @@ describe('sheet drawing transforms without UI plugins', () => {expect(readDrawings()).toEqual(after);});+ it.each([+ [DeltaRowHeightCommand.id, { anchorRow: 2, deltaY: 48 }, SheetDrawingAnchorType.Position],+ [DeltaColumnWidthCommand.id, { anchorCol: 2, deltaX: 48 }, SheetDrawingAnchorType.Position],+ [DeltaRowHeightCommand.id, { anchorRow: 2, deltaY: 48 }, undefined],+ [DeltaColumnWidthCommand.id, { anchorCol: 2, deltaX: 48 }, undefined],+ ])('%s with %j preserves drawing size for anchor %s', async (commandId, params, anchorType) => {+ const service = await insertDrawing(anchorType);+ const before = structuredClone(getDrawing(service).transform);+ testBed.get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ }]);++ expect(await testBed.commandService.executeCommand(commandId, params)).toBe(true);+ expect(getDrawing(service).transform).toEqual(before);+ });++ it.each([SheetDrawingAnchorType.Position, undefined])('keeps anchor %s drawing size across auto-height and a preceding column resize', async (anchorType) => {+ const service = await insertDrawing(anchorType);+ const before = structuredClone(getDrawing(service).transform)!;+ const worksheet = testBed.workbook.getSheetBySheetId('sheet1')!;+ testBed.get(SheetsSelectionsService).setSelections('test', 'sheet1', [{+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ primary: null,+ }]);++ testBed.commandService.syncExecuteCommand(SetWorksheetRowAutoHeightMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ rowsAutoHeightInfo: [{ row: 2, autoHeight: worksheet.getRowHeight(2) + 30 }],+ });+ await Promise.resolve();+ await testBed.commandService.executeCommand(DeltaColumnWidthCommand.id, { anchorCol: 0, deltaX: 48 });++ expect(getDrawing(service).transform).toEqual({ ...before, left: before.left! + 48 });+ });++ it('round-trips legacy floating cell anchors through saved resources and undo/redo', async () => {+ const service = await insertDrawing(undefined);+ const original = getDrawing(service);+ const floating = { ...original, drawingId: 'legacy-floating', drawingType: DrawingTypeEnum.DRAWING_DOM };+ expect(await testBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {+ unitId: 'test',+ drawings: [floating],+ })).toBe(true);+ const snapshot = testBed.get(IResourceLoaderService).saveUnit<IWorkbookData>('test');+ if (!snapshot) {+ throw new Error('Expected the Sheet snapshot to exist.');+ }+ const resource = snapshot.resources.find(({ name }) => name === SHEET_DRAWING_PLUGIN);+ if (!resource) {+ throw new Error('Expected the drawing resource to exist.');+ }+ const persisted = JSON.parse(resource.data).sheet1.data['legacy-floating'];+ expect(persisted).not.toHaveProperty('anchorType');+ const restored = createSheetsDrawingTestBed(snapshot);+ try {+ const restoredService = restored.get(ISheetDrawingService);+ const readDrawing = () => restoredService.getDrawingByParam(floating)!;+ const before = structuredClone(readDrawing());+ expect(getSheetDrawingPlacement(before)).toMatchObject({+ kind: SheetDrawingAnchorType.Position,+ from: floating.sheetTransform.from,+ width: floating.transform?.width,+ height: floating.transform?.height,+ });+ expect(await restored.commandService.executeCommand(InsertRowCommand.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 19 },+ direction: Direction.UP,+ })).toBe(true);+ const after = structuredClone(readDrawing());+ expect(after.transform?.top).toBeGreaterThan(before.transform?.top ?? 0);+ expect(after.transform?.width).toBe(before.transform?.width);+ expect(after.transform?.height).toBe(before.transform?.height);+ expect(await restored.commandService.executeCommand(UndoCommandId)).toBe(true);+ expect(readDrawing()).toEqual(before);+ expect(await restored.commandService.executeCommand(RedoCommandId)).toBe(true);+ expect(readDrawing()).toEqual(after);+ } finally {+ restored.univer.dispose();+ }+ });+it('resizes both-anchored drawings when row height changes', async () => {- const service = await insertDrawing();+ const service = await insertDrawing(SheetDrawingAnchorType.Both);const before = structuredClone(getDrawing(service));expect(testBed.commandService.syncExecuteCommand(SetRowHeightCommand.id, {@@ -807,7 +933,7 @@ describe('sheet drawing transforms without UI plugins', () => {});it('updates placement through a command and round-trips through undo and redo', async () => {- const service = await insertDrawing();+ const service = await insertDrawing(SheetDrawingAnchorType.Both);const before = structuredClone(getDrawing(service));const placement: ISheetDrawingPlacement = {kind: SheetDrawingAnchorType.None,@@ -983,7 +1109,7 @@ describe('sheet drawing transforms without UI plugins', () => {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 service = await insertDrawing(SheetDrawingAnchorType.Both);const before = structuredClone(getDrawing(service));expect(await testBed.commandService.executeCommand(commandId, params)).toBe(true);@@ -997,7 +1123,7 @@ describe('sheet drawing transforms without UI plugins', () => {});it('refreshes direct auto-height mutations and their inverse without UI', async () => {- const service = await insertDrawing();+ const service = await insertDrawing(SheetDrawingAnchorType.Both);const before = structuredClone(getDrawing(service));const worksheet = testBed.workbook.getSheetBySheetId('sheet1')!;const originalHeight = worksheet.getRowHeight(2);diff --git a/packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.ts b/packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.tsindex dec08c1871..543b53e0d3 100644--- a/packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.ts+++ b/packages/sheets-drawing/src/controllers/sheet-drawing-transform-affected.controller.ts@@ -40,7 +40,10 @@ import type {ISetWorksheetRowIsAutoHeightMutationParams,ISheetSkeletonManagerParam,} from '@univerjs/sheets';-import type { ISheetDrawingTransformExtensionResult, ISheetDrawingTransformPlan } from '../services/sheet-drawing-transform-plan.service';+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, Rectangle } from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';@@ -77,9 +80,14 @@ import {SheetInterceptorService,SheetSkeletonService,} from '@univerjs/sheets';-import { drawingPositionToTransform, transformToAxisAlignPosition, transformToDrawingPosition } from '../basics/transform-position';+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 { applySheetDrawingPlacement, getSheetDrawingPlacement } from '../services/sheet-drawing-placement';import { SheetDrawingTransformPlanService } from '../services/sheet-drawing-transform-plan.service';import { ISheetDrawingService, SheetDrawingAnchorType } from '../services/sheet-drawing.service';@@ -348,7 +356,7 @@ export class SheetDrawingTransformAffectedController extends Disposable {const { sheetTransform, anchorType = SheetDrawingAnchorType.Position, transform, unitId, subUnitId, drawingId } = drawing;const sheetSkeletonParam = this._sheetSkeletonService.getSkeletonParam(unitId, subUnitId);- if (!sheetTransform || !transform || !sheetSkeletonParam) {+ if (anchorType === SheetDrawingAnchorType.None || !sheetTransform || !transform || !sheetSkeletonParam) {return {updateDrawings,deleteDrawings,@@ -709,23 +717,19 @@ export class SheetDrawingTransformAffectedController extends Disposable {if (anchorType === SheetDrawingAnchorType.None) {this._remainDrawingSize(transform, updateDrawings, drawing, skeleton);} else {- const { from, to } = sheetTransform;- const { row: fromRow, column: fromColumn } = from;- const { row: toRow, column: toColumn } = to;+ const { row: toRow, column: toColumn } = sheetTransform.to;for (let i = 0; i < ranges.length; i++) {const range = ranges[i];- const { startRow, endRow, startColumn, endColumn } = range;+ const { startRow, startColumn } = range;if (toRow < startRow || toColumn < startColumn) {continue;}if (anchorType === SheetDrawingAnchorType.Position) {- if ((fromRow <= startRow && toRow >= endRow) || (fromColumn <= startColumn && toColumn >= endColumn)) {- this._remainDrawingSize(transform, updateDrawings, drawing, skeleton);- continue;- }+ updateDrawings.push(applySheetDrawingPlacement(drawing, getSheetDrawingPlacement(drawing), skeleton));+ break;}const newTransform = drawingPositionToTransform({ ...sheetTransform }, sheetSkeletonParam);@@ -1358,6 +1362,10 @@ export class SheetDrawingTransformAffectedController extends Disposable {private _refreshDrawingTransform(command: ICommandInfo, unitId: string, subUnitId: string, ranges: IRange[]) {const sheetSkeletonParam = this._getCalculatedSkeletonParam(unitId, subUnitId);+ if (!sheetSkeletonParam) {+ return;+ }+const drawingData = this._drawingManagerService.getDrawingData(unitId, subUnitId) ?? {};const updateDrawings: ISheetDrawing[] = [];@@ -1391,7 +1399,11 @@ export class SheetDrawingTransformAffectedController extends Disposable {endColumn: toColumn,}) || fromRow > endRow || fromColumn > endColumn) {- const isPositionAnchor = anchorType === SheetDrawingAnchorType.Position;+ if (anchorType === SheetDrawingAnchorType.Position) {+ updateDrawings.push(applySheetDrawingPlacement(drawing, getSheetDrawingPlacement(drawing), sheetSkeletonParam.skeleton));+ break;+ }+const newTransform = drawingPositionToTransform(sheetTransform, sheetSkeletonParam);updateDrawings.push({...drawing,@@ -1399,8 +1411,8 @@ export class SheetDrawingTransformAffectedController extends Disposable {...transform,left: newTransform?.left,top: newTransform?.top,- width: isPositionAnchor ? transform?.width : newTransform?.width,- height: isPositionAnchor ? transform?.height : newTransform?.height,+ width: newTransform?.width,+ height: newTransform?.height,},});break;diff --git a/packages/sheets-drawing/src/services/sheet-drawing.service.ts b/packages/sheets-drawing/src/services/sheet-drawing.service.tsindex da68c08e1f..9ffef1ddc4 100644--- a/packages/sheets-drawing/src/services/sheet-drawing.service.ts+++ b/packages/sheets-drawing/src/services/sheet-drawing.service.ts@@ -47,6 +47,7 @@ export interface ISheetDrawingBase {* this property is used to store the excel drawing axis alignment position, which is not always the same as the sheetTransform.*/axisAlignSheetTransform: ISheetDrawingPosition;+ /** Defaults to Position: the drawing moves with cells while retaining its size. */anchorType?: SheetDrawingAnchorType;}