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(sheet): correct drawing interaction states (#7519)
wpxp12345641f3d4d02bb1
diff --git a/packages/drawing-ui/src/commands/operations/image-crop.operation.ts b/packages/drawing-ui/src/commands/operations/image-crop.operation.tsindex 77b6eef4d9..7516de8d1a 100644--- a/packages/drawing-ui/src/commands/operations/image-crop.operation.ts+++ b/packages/drawing-ui/src/commands/operations/image-crop.operation.ts@@ -20,15 +20,20 @@ import { CommandType } from '@univerjs/core';export const OpenImageCropOperation: IOperation<IDrawingSearch> = {id: 'sheet.operation.open-image-crop',type: CommandType.OPERATION,- handler: (accessor, params) => {+ handler: (_accessor, _params) => {return true;},};-export const CloseImageCropOperation: IOperation<{ isAuto?: boolean }> = {+export interface ICloseImageCropOperationParams {+ isAuto?: boolean;+ isCancel?: boolean;+}++export const CloseImageCropOperation: IOperation<ICloseImageCropOperationParams> = {id: 'sheet.operation.close-image-crop',type: CommandType.OPERATION,- handler: (accessor, params) => {+ handler: (_accessor, _params) => {return true;},};@@ -53,7 +58,7 @@ export interface IOpenImageCropOperationBySrcRectParams {export const AutoImageCropOperation: IOperation<IOpenImageCropOperationBySrcRectParams> = {id: 'sheet.operation.Auto-image-crop',type: CommandType.OPERATION,- handler: (accessor, params) => {+ handler: (_accessor, _params) => {return true;},};diff --git a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.tsindex b7e3819f77..9ab3f1fa12 100644--- a/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts+++ b/packages/drawing-ui/src/controllers/__tests__/image-cropper.controller.spec.ts@@ -20,6 +20,7 @@ import { MessageType } from '@univerjs/design';import { getDrawingShapeKeyByDrawingSearch, SetDrawingSelectedOperation } from '@univerjs/drawing';import { ImageCropperObject } from '@univerjs/drawing-ui';import { CURSOR_TYPE, Image } from '@univerjs/engine-render';+import { KeyCode } from '@univerjs/ui';import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';import { AutoImageCropOperation, CloseImageCropOperation, CropType, OpenImageCropOperation } from '../../commands/operations/image-crop.operation';@@ -78,7 +79,8 @@ describe('ImageCropperController', () => {renderManagerService as never,{ getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn() } as never,{ show: vi.fn() } as never,- { t: vi.fn((key: string) => key) } as never+ { t: vi.fn((key: string) => key) } as never,+ { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } as never);// handlers: [OpenImageCrop, CloseImageCrop, AutoImageCrop]@@ -86,7 +88,7 @@ describe('ImageCropperController', () => {expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(CloseImageCropOperation.id, { isAuto: true });expect(image.srcRect).toEqual({ left: 25, top: 0, right: 25, bottom: 0 });- expect(commandService.executeCommand).toHaveBeenCalledWith(OpenImageCropOperation.id, focusDrawing);+ expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(OpenImageCropOperation.id, focusDrawing);controller.dispose();});@@ -121,7 +123,8 @@ describe('ImageCropperController', () => {renderManagerService as never,{ getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn() } as never,messageService as never,- { t: vi.fn((key: string) => key) } as never+ { t: vi.fn((key: string) => key) } as never,+ { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } as never);commandHandlers[2]({ id: AutoImageCropOperation.id, params: { cropType: CropType.R1_1 } } as never);@@ -158,6 +161,7 @@ describe('ImageCropperController', () => {refreshControls: vi.fn(),clearCopperControl: vi.fn(),createControlForCopper: vi.fn(),+ detachFrom: vi.fn(),changeStart$: new Subject(),changeEnd$: new Subject(),clearControl$: new Subject(),@@ -169,7 +173,7 @@ describe('ImageCropperController', () => {getObject: vi.fn(() => image),getTransformerByCreate: vi.fn(() => transformer),getTransformer: vi.fn(() => transformer),- addObject: vi.fn((obj: any) => {+ addObject: vi.fn((obj: ImageCropperObject) => {createdCropper = obj;return { attachTransformerTo: vi.fn() };}),@@ -182,7 +186,8 @@ describe('ImageCropperController', () => {renderManagerService as never,{ getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn() } as never,{ show: vi.fn() } as never,- { t: vi.fn((key: string) => key) } as never+ { t: vi.fn((key: string) => key) } as never,+ { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } as never);// OpenImageCrop handler@@ -197,4 +202,171 @@ describe('ImageCropperController', () => {expect(commandService.syncExecuteCommand).toHaveBeenCalledWith(SetDrawingSelectedOperation.id, [focusDrawing]);controller.dispose();});++ it('registers confirm and cancel shortcuts only while crop mode is open', () => {+ const focusDrawing = { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' };+ const imageKey = getDrawingShapeKeyByDrawingSearch(focusDrawing);+ const image = createImage(imageKey);+ const commandHandlers: Array<(cmd: ICommandInfo) => void> = [];+ const commandService = {+ onCommandExecuted: vi.fn((handler) => {+ commandHandlers.push(handler);+ return { dispose: vi.fn() };+ }),+ executeCommand: vi.fn(),+ syncExecuteCommand: vi.fn((id, params) => {+ if (id === CloseImageCropOperation.id) {+ commandHandlers[1]({ id, params } as never);+ }+ return true;+ }),+ };+ const transformer = {+ clearControls: vi.fn(),+ refreshControls: vi.fn(),+ clearCopperControl: vi.fn(),+ createControlForCopper: vi.fn(),+ detachFrom: vi.fn(),+ changeStart$: new Subject(),+ changeEnd$: new Subject(),+ clearControl$: new Subject(),+ };+ let createdCropper: ImageCropperObject | null = null;+ const scene = {+ getAllObjectsByOrder: vi.fn(() => createdCropper ? [createdCropper] : []),+ getObject: vi.fn(() => image),+ getTransformerByCreate: vi.fn(() => transformer),+ getTransformer: vi.fn(() => transformer),+ addObject: vi.fn((object: ImageCropperObject) => {+ createdCropper = object;+ return { attachTransformerTo: vi.fn() };+ }),+ };+ const firstEnterShortcutDisposable = { dispose: vi.fn() };+ const firstCancelShortcutDisposable = { dispose: vi.fn() };+ const secondEnterShortcutDisposable = { dispose: vi.fn() };+ const secondCancelShortcutDisposable = { dispose: vi.fn() };+ const shortcutDisposables = [+ firstEnterShortcutDisposable,+ firstCancelShortcutDisposable,+ secondEnterShortcutDisposable,+ secondCancelShortcutDisposable,+ ];+ const shortcutService = {+ registerShortcut: vi.fn(() => shortcutDisposables.shift()!),+ };+ const controller = new ImageCropperController(+ commandService as never,+ {+ getDrawingByParam: vi.fn(() => ({ drawingType: DrawingTypeEnum.DRAWING_IMAGE })),+ getDrawingOKey: vi.fn(() => ({ ...focusDrawing, transform: image.getState() })),+ featurePluginUpdateNotification: vi.fn(),+ } as never,+ { getRenderUnitById: vi.fn(() => ({ scene })) } as never,+ { getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn(() => null) } as never,+ { show: vi.fn() } as never,+ { t: vi.fn((key: string) => key) } as never,+ shortcutService as never+ );++ commandHandlers[0]({ id: OpenImageCropOperation.id, params: focusDrawing } as never);++ expect(shortcutService.registerShortcut).toHaveBeenCalledWith(expect.objectContaining({+ id: CloseImageCropOperation.id,+ binding: KeyCode.ENTER,+ }));+ expect(shortcutService.registerShortcut).toHaveBeenCalledWith(expect.objectContaining({+ id: CloseImageCropOperation.id,+ binding: KeyCode.ESC,+ staticParameters: { isCancel: true },+ }));++ const firstCropperDispose = vi.spyOn(createdCropper!, 'dispose');+ commandHandlers[0]({ id: OpenImageCropOperation.id, params: focusDrawing } as never);+ expect(firstCropperDispose).toHaveBeenCalledOnce();++ const secondCropperDispose = vi.spyOn(createdCropper!, 'dispose');+ commandHandlers[1]({ id: CloseImageCropOperation.id, params: { isCancel: true } } as never);+ expect(transformer.detachFrom).toHaveBeenCalledWith(createdCropper);+ expect(secondCropperDispose).toHaveBeenCalledOnce();+ expect(firstEnterShortcutDisposable.dispose).toHaveBeenCalledOnce();+ expect(firstCancelShortcutDisposable.dispose).toHaveBeenCalledOnce();+ expect(secondEnterShortcutDisposable.dispose).toHaveBeenCalledOnce();+ expect(secondCancelShortcutDisposable.dispose).toHaveBeenCalledOnce();++ controller.dispose();+ });++ it('restores the image state from before auto crop without publishing changes when cancelled', () => {+ const focusDrawing = { unitId: 'unit-1', subUnitId: 'sheet-1', drawingId: 'd1' };+ const imageKey = getDrawingShapeKeyByDrawingSearch(focusDrawing);+ const image = createImage(imageKey);+ image.transformByState({ left: 10, top: 20, width: 100, height: 50, angle: 0 });+ const originalTransform = image.getState();+ const originalSrcRect = image.srcRect;+ const commandHandlers: Array<(cmd: ICommandInfo) => void> = [];+ const commandService = {+ onCommandExecuted: vi.fn((handler) => {+ commandHandlers.push(handler);+ return { dispose: vi.fn() };+ }),+ executeCommand: vi.fn(),+ syncExecuteCommand: vi.fn((id, params) => {+ if (id === OpenImageCropOperation.id) {+ commandHandlers[0]({ id, params } as never);+ }+ return true;+ }),+ };+ const drawingManagerService = {+ getFocusDrawings: vi.fn(() => [focusDrawing]),+ getDrawingByParam: vi.fn(() => ({ drawingType: DrawingTypeEnum.DRAWING_IMAGE })),+ getDrawingOKey: vi.fn(() => ({ ...focusDrawing, drawingType: DrawingTypeEnum.DRAWING_IMAGE })),+ featurePluginUpdateNotification: vi.fn(),+ };+ const refreshedImageStates: ReturnType<Image['getState']>[] = [];+ const transformer = {+ clearControls: vi.fn(),+ refreshControls: vi.fn(() => refreshedImageStates.push(image.getState())),+ clearCopperControl: vi.fn(),+ createControlForCopper: vi.fn(),+ detachFrom: vi.fn(),+ changeStart$: new Subject(),+ changeEnd$: new Subject(),+ clearControl$: new Subject(),+ };+ let createdCropper: ImageCropperObject | null = null;+ const scene = {+ getAllObjectsByOrder: vi.fn(() => createdCropper ? [createdCropper] : []),+ getObject: vi.fn(() => image),+ getTransformerByCreate: vi.fn(() => transformer),+ getTransformer: vi.fn(() => transformer),+ addObject: vi.fn((object: ImageCropperObject) => {+ createdCropper = object;+ return { attachTransformerTo: vi.fn() };+ }),+ };+ const controller = new ImageCropperController(+ commandService as never,+ drawingManagerService as never,+ { getRenderUnitById: vi.fn(() => ({ scene })) } as never,+ { getCurrentTypeOfUnit$: vi.fn(() => new Subject()), getFocusedUnit: vi.fn(() => ({ getUnitId: () => focusDrawing.unitId })) } as never,+ { show: vi.fn() } as never,+ { t: vi.fn((key: string) => key) } as never,+ { registerShortcut: vi.fn(() => ({ dispose: vi.fn() })) } as never+ );++ commandHandlers[2]({ id: AutoImageCropOperation.id, params: { cropType: CropType.R1_1 } } as never);+ expect(image.srcRect).not.toBeNull();+ expect(createdCropper).not.toBeNull();+ refreshedImageStates.length = 0;+ commandHandlers[1]({ id: CloseImageCropOperation.id, params: { isCancel: true } } as never);++ expect(drawingManagerService.featurePluginUpdateNotification).not.toHaveBeenCalled();+ expect(image.getState()).toEqual(originalTransform);+ expect(image.srcRect).toBe(originalSrcRect);+ expect(refreshedImageStates).toEqual([originalTransform]);++ controller.dispose();+ });});diff --git a/packages/drawing-ui/src/controllers/image-cropper.controller.ts b/packages/drawing-ui/src/controllers/image-cropper.controller.tsindex 2ca2242798..d260170fff 100644--- a/packages/drawing-ui/src/controllers/image-cropper.controller.ts+++ b/packages/drawing-ui/src/controllers/image-cropper.controller.ts@@ -17,11 +17,12 @@import type { ICommandInfo, IDrawingSearch, ISrcRect, ITransformState, Nullable, Workbook } from '@univerjs/core';import type { IImageData } from '@univerjs/drawing';import type { BaseObject, Scene } from '@univerjs/engine-render';-import type { IOpenImageCropOperationBySrcRectParams } from '../commands/operations/image-crop.operation';+import type { ICloseImageCropOperationParams, IOpenImageCropOperationBySrcRectParams } from '../commands/operations/image-crop.operation';import type { LocaleKey } from '../locale/types';import {checkIfMove,Disposable,+ DisposableCollection,ICommandService,Inject,IUniverInstanceService,@@ -35,7 +36,7 @@ import {SetDrawingSelectedOperation,} from '@univerjs/drawing';import { CURSOR_TYPE, degToRad, Image, IRenderManagerService, precisionTo, Vector2 } from '@univerjs/engine-render';-import { IMessageService } from '@univerjs/ui';+import { IMessageService, IShortcutService, KeyCode } from '@univerjs/ui';import { of, switchMap } from 'rxjs';import {AutoImageCropOperation,@@ -45,8 +46,23 @@ import {} from '../commands/operations/image-crop.operation';import { ImageCropperObject } from '../views/crop/image-cropper-object';+interface IImageCropSnapshot {+ transform: ITransformState;+ srcRect: Nullable<ISrcRect>;+}++interface IImageCropSession {+ scene: Scene;+ imageShape: Image;+ imageCropperObject: ImageCropperObject;+}+export class ImageCropperController extends Disposable {private _sceneListenerOnImageMap: WeakSet<Scene> = new WeakSet();+ private readonly _cropShortcutDisposables = new DisposableCollection();+ private readonly _cropSnapshots = new WeakMap<ImageCropperObject, IImageCropSnapshot>();+ private _pendingCropSnapshot: Nullable<IImageCropSnapshot> = null;+ private _activeCropSession: Nullable<IImageCropSession> = null;constructor(@ICommandService private readonly _commandService: ICommandService,@@ -54,10 +70,12 @@ export class ImageCropperController extends Disposable {@IRenderManagerService private readonly _renderManagerService: IRenderManagerService,@IUniverInstanceService private _univerInstanceService: IUniverInstanceService,@IMessageService private readonly _messageService: IMessageService,- @Inject(LocaleService) private readonly _localeService: LocaleService+ @Inject(LocaleService) private readonly _localeService: LocaleService,+ @IShortcutService private readonly _shortcutService: IShortcutService) {super();+ this.disposeWithMe(this._cropShortcutDisposables);this._init();}@@ -121,9 +139,13 @@ export class ImageCropperController extends Disposable {return;}- this._updateCropperObject(cropType, imageShape);-- this._commandService.executeCommand(OpenImageCropOperation.id, { unitId, subUnitId, drawingId });+ this._pendingCropSnapshot = this._captureCropSnapshot(imageShape);+ try {+ this._updateCropperObject(cropType, imageShape);+ this._commandService.syncExecuteCommand(OpenImageCropOperation.id, { unitId, subUnitId, drawingId });+ } finally {+ this._pendingCropSnapshot = null;+ }}));}@@ -226,6 +248,10 @@ export class ImageCropperController extends Disposable {return;}+ if (this._activeCropSession != null) {+ this._commandService.syncExecuteCommand(CloseImageCropOperation.id, { isAuto: true });+ }+const { unitId, subUnitId, drawingId } = params;const renderObject = this._renderManagerService.getRenderUnitById(unitId);@@ -271,8 +297,11 @@ export class ImageCropperController extends Disposable {prstGeom: imageShape.prstGeom,applyTransform: imageShape.calculateTransformWithSrcRect(),});+ this._cropSnapshots.set(imageCropperObject, this._pendingCropSnapshot ?? this._captureCropSnapshot(imageShape));+ this._pendingCropSnapshot = null;scene.addObject(imageCropperObject, imageShape.getLayerIndex() + 1).attachTransformerTo(imageCropperObject);+ this._activeCropSession = { scene, imageShape, imageCropperObject };transformer?.createControlForCopper(imageCropperObject);this._addHoverForImageCopper(imageCropperObject);@@ -280,6 +309,8 @@ export class ImageCropperController extends Disposable {transformer?.refreshControls();imageCropperObject.makeDirty(true);+ this._registerCropShortcuts();+this._commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, [{ unitId, subUnitId, drawingId }]);}));@@ -302,57 +333,47 @@ export class ImageCropperController extends Disposable {return;}- const currentUnit = this._univerInstanceService.getFocusedUnit();-- if (currentUnit == null) {- return;- }-- const unitId = currentUnit.getUnitId();- const renderObject = this._renderManagerService.getRenderUnitById(unitId);-- const scene = renderObject?.scene;-- if (scene == null) {- return true;- }-- const imageCropperObject = this._searchCropObject(scene);- if (imageCropperObject == null) {- return;- }- const imageShape = this._getApplyObjectByCropObject(imageCropperObject);- if (imageShape == null) {+ const cropSession = this._activeCropSession;+ if (cropSession == null) {return;}+ const { scene, imageShape, imageCropperObject } = cropSession;const transformer = scene.getTransformerByCreate();transformer.detachFrom(imageCropperObject);transformer.clearCopperControl();- const srcRect = this._getSrcRectByTransformState(imageShape, imageCropperObject);-- const drawingParam = this._drawingManagerService.getDrawingOKey(imageShape.oKey);- if (drawingParam != null) {- const { left, top, height, width } = imageCropperObject;- this._drawingManagerService.featurePluginUpdateNotification([{- ...drawingParam,- transform: {- ...drawingParam.transform,- left,- top,- height,- width,- },- srcRect: srcRect.srcRectAngle,- }] as IImageData[]);+ const params = command.params as ICloseImageCropOperationParams | undefined;+ if (params?.isCancel) {+ this._restoreCropSnapshot(imageShape, imageCropperObject);+ } else {+ const srcRect = this._getSrcRectByTransformState(imageShape, imageCropperObject);+ const drawingParam = this._drawingManagerService.getDrawingOKey(imageShape.oKey);+ if (drawingParam != null) {+ const { left, top, height, width } = imageCropperObject;+ this._drawingManagerService.featurePluginUpdateNotification([{+ ...drawingParam,+ transform: {+ ...drawingParam.transform,+ left,+ top,+ height,+ width,+ },+ srcRect: srcRect.srcRectAngle,+ }] as IImageData[]);+ }+ imageShape.setSrcRect({ ...srcRect.srcRectAngle });}- imageShape.setSrcRect({ ...srcRect.srcRectAngle });imageShape.closeRenderByCropper();imageShape.makeDirty(true);+ transformer.refreshControls();- imageCropperObject?.dispose();+ this._cropSnapshots.delete(imageCropperObject);+ imageCropperObject.dispose();+ this._activeCropSession = null;+ this._cropShortcutDisposables.dispose();}));@@ -380,6 +401,36 @@ export class ImageCropperController extends Disposable {return applyObject;}+ private _captureCropSnapshot(imageShape: Image): IImageCropSnapshot {+ return {+ transform: imageShape.getState(),+ srcRect: imageShape.srcRect == null ? imageShape.srcRect : { ...imageShape.srcRect },+ };+ }++ private _restoreCropSnapshot(imageShape: Image, imageCropperObject: ImageCropperObject): void {+ const snapshot = this._cropSnapshots.get(imageCropperObject);+ if (snapshot) {+ imageShape.transformByStateCloseCropper(snapshot.transform);+ imageShape.setSrcRect(snapshot.srcRect);+ }+ }++ private _registerCropShortcuts(): void {+ this._cropShortcutDisposables.dispose();+ this._cropShortcutDisposables.add(this._shortcutService.registerShortcut({+ id: CloseImageCropOperation.id,+ binding: KeyCode.ENTER,+ priority: 1000,+ }));+ this._cropShortcutDisposables.add(this._shortcutService.registerShortcut({+ id: CloseImageCropOperation.id,+ binding: KeyCode.ESC,+ priority: 1000,+ staticParameters: { isCancel: true },+ }));+ }+private _addListenerOnImage(scene: Scene) {const transformer = scene.getTransformerByCreate();@@ -462,9 +513,9 @@ export class ImageCropperController extends Disposable {}private _getSrcRectByTransformState(applyObject: BaseObject, imageCropperObject: ImageCropperObject) {- const { left, top, height, width, strokeWidth, angle: copperAngle } = imageCropperObject;+ const { left, top, height, width } = imageCropperObject;- const { left: applyLeft, top: applyTop, width: applyWidth, height: applyHeight, angle: applyAngle, strokeWidth: applyStrokeWidth } = applyObject;+ const { left: applyLeft, top: applyTop, width: applyWidth, height: applyHeight, angle: applyAngle } = applyObject;const newLeft = left - applyLeft;const newTop = top - applyTop;diff --git a/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts b/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.tsindex 23d47f8139..ad32b48767 100644--- a/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/operations/__tests__/open-drawing-panel.operation.spec.ts@@ -34,6 +34,7 @@ describe('SidebarSheetDrawingOperation', () => {expect(testBed.sidebarService.visible).toBe(true);expect(testBed.sidebarService.options).toMatchObject({+ id: COMPONENT_SHEET_DRAWING_PANEL,header: { title: 'sheets-drawing-ui.panel.title' },children: { label: COMPONENT_SHEET_DRAWING_PANEL },width: 360,@@ -49,14 +50,17 @@ describe('SidebarSheetDrawingOperation', () => {drawingManagerService.registerDrawingData(testBed.unitId, {[testBed.subUnitId]: {- 'drawing-1': {- unitId: testBed.unitId,- subUnitId: testBed.subUnitId,- drawingId: 'drawing-1',- drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ data: {+ 'drawing-1': {+ unitId: testBed.unitId,+ subUnitId: testBed.subUnitId,+ drawingId: 'drawing-1',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ },},+ order: ['drawing-1'],},- } as never);+ });drawingManagerService.focusDrawing([{unitId: testBed.unitId,subUnitId: testBed.subUnitId,diff --git a/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.tsindex 1b772508fc..89ad16126e 100644--- a/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts+++ b/packages/sheets-drawing-ui/src/commands/operations/open-drawing-panel.operation.ts@@ -16,8 +16,8 @@import type { IAccessor, ICommand } from '@univerjs/core';import type { LocaleKey } from '../../locale/types';-import { CommandType, ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';-import { SetDrawingSelectedOperation } from '@univerjs/drawing';+import { CommandType, DrawingTypeEnum, ICommandService, IUniverInstanceService, LocaleService } from '@univerjs/core';+import { IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';import { getSheetCommandTarget } from '@univerjs/sheets';import { ISidebarService } from '@univerjs/ui';import { COMPONENT_SHEET_DRAWING_PANEL } from '../../views/sheet-image-panel/component-name';@@ -33,7 +33,7 @@ export const SidebarSheetDrawingOperation: ICommand = {const sidebarService = accessor.get(ISidebarService);const localeService = accessor.get(LocaleService);const univerInstanceService = accessor.get(IUniverInstanceService);- // const drawingManagerService = accessor.get(IDrawingManagerService);+ const drawingManagerService = accessor.get(IDrawingManagerService);const commandService = accessor.get(ICommandService);const target = getSheetCommandTarget(univerInstanceService);@@ -42,17 +42,21 @@ export const SidebarSheetDrawingOperation: ICommand = {switch (params.value) {case 'open':sidebarService.open({+ id: COMPONENT_SHEET_DRAWING_PANEL,header: { title: localeService.t<LocaleKey>('sheets-drawing-ui.panel.title') },children: { label: COMPONENT_SHEET_DRAWING_PANEL },onClose: () => {- commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, []);+ const focusedDrawings = drawingManagerService.getFocusDrawings();+ if (focusedDrawings.length === 1 && focusedDrawings[0].drawingType === DrawingTypeEnum.DRAWING_IMAGE) {+ commandService.syncExecuteCommand(SetDrawingSelectedOperation.id, []);+ }},width: 360,});break;case 'close':default:- sidebarService.close();+ sidebarService.close(COMPONENT_SHEET_DRAWING_PANEL);break;}return true;diff --git a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts b/packages/sheets-drawing-ui/src/controllers/ui.controller.tsindex bea7086d3b..ad71294cdf 100644--- a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts+++ b/packages/sheets-drawing-ui/src/controllers/ui.controller.ts@@ -14,8 +14,9 @@* limitations under the License.*/-import { Disposable, ICommandService } from '@univerjs/core';-import { IMenuManagerService, IShortcutService } from '@univerjs/ui';+import { Disposable, DrawingTypeEnum, ICommandService, Inject } from '@univerjs/core';+import { IDrawingManagerService } from '@univerjs/drawing';+import { IMenuManagerService, IShortcutService, ISidebarService } from '@univerjs/ui';import { DeleteDrawingsCommand } from '../commands/commands/delete-drawings.command';import { FlipSheetDrawingCommand } from '../commands/commands/flip-drawings.command';import { GroupSheetDrawingCommand } from '../commands/commands/group-sheet-drawing.command';@@ -26,6 +27,7 @@ import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-dimport { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';import { SidebarSheetDrawingOperation } from '../commands/operations/open-drawing-panel.operation';import { menuSchema } from '../menu/schema';+import { COMPONENT_SHEET_DRAWING_PANEL } from '../views/sheet-image-panel/component-name';import {DeleteDrawingsShortcutItem,MoveDrawingDownShortcutItem,@@ -38,7 +40,9 @@ export class SheetDrawingUIController extends Disposable {constructor(@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@ICommandService private readonly _commandService: ICommandService,- @IShortcutService private readonly _shortcutService: IShortcutService+ @IShortcutService private readonly _shortcutService: IShortcutService,+ @IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,+ @Inject(ISidebarService) private readonly _sidebarService: ISidebarService) {super();@@ -80,10 +84,25 @@ export class SheetDrawingUIController extends Disposable {});}+ private _initImagePanel(): void {+ this.disposeWithMe(this._drawingManagerService.focus$.subscribe((drawings) => {+ if (!this._sidebarService.visible || this._sidebarService.options.id !== COMPONENT_SHEET_DRAWING_PANEL) {+ return;+ }++ if (drawings.length === 1 && drawings[0].drawingType === DrawingTypeEnum.DRAWING_IMAGE) {+ return;+ }++ this._sidebarService.close(COMPONENT_SHEET_DRAWING_PANEL);+ }));+ }+private _init(): void {this._initCommands();this._initCustomComponents();this._initMenus();this._initShortcuts();+ this._initImagePanel();}}diff --git a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.tsindex 7ddf0088a8..460bac7d6b 100644--- a/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts+++ b/packages/sheets-ui/src/services/__tests__/canvas-pop-manager.service.spec.ts@@ -185,6 +185,7 @@ function createSheetHarness() {} as DOMRect);const transformChange$ = createEventSubject<unknown>();+ const viewMainScrollAfter$ = createEventSubject<unknown>();const clientRect$ = new BehaviorSubject({});const worksheet = {getSheetId: () => 'sheet-1',@@ -217,16 +218,18 @@ function createSheetHarness() {}),};const sheetSelectionRenderService = { selectionMoving: false };+ const viewport = {+ left: 0,+ top: 0,+ viewportScrollX: 0,+ viewportScrollY: 0,+ onScrollAfter$: viewMainScrollAfter$,+ };const render = {getInjector: vi.fn(() => injector),scene: {getAncestorScale: () => ({ scaleX: 1, scaleY: 1 }),- getViewport: () => ({- left: 0,- top: 0,- viewportScrollX: 0,- viewportScrollY: 0,- }),+ getViewport: () => viewport,},engine: {clientRect$,@@ -269,8 +272,9 @@ function createSheetHarness() {canvas,clientRect$,transformChange$,+ viewMainScrollAfter$,sheetSelectionRenderService,- viewport: { viewportScrollX: 0, viewportScrollY: 0 },+ viewport,};}@@ -297,7 +301,7 @@ describe('SheetCanvasPopManagerService', () => {});it('anchors a drawing popup with the registered menu offset and removes it when closed', () => {- const { service, popupService, canvas } = createSheetHarness();+ const { service, popupService, canvas, viewport, viewMainScrollAfter$ } = createSheetHarness();const targetObject = {left: 20,top: 10,@@ -319,6 +323,13 @@ describe('SheetCanvasPopManagerService', () => {});expect(disposable.canDispose()).toBe(false);+ const positions: unknown[] = [];+ popupService.lastPopup()!.anchorRect$!.subscribe((position) => positions.push(position));+ viewport.viewportScrollX = 5;+ viewport.viewportScrollY = 4;+ viewMainScrollAfter$.emit({});+ expect(positions[positions.length - 1]).toEqual({ left: 40, right: 144, top: 48, bottom: 92 });+disposable.dispose();expect(popupService.removedIds).toEqual(['popup-1']);expect(popupService.popups.size).toBe(0);diff --git a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts b/packages/sheets-ui/src/services/canvas-pop-manager.service.tsindex 57b50810c4..2db521bb81 100644--- a/packages/sheets-ui/src/services/canvas-pop-manager.service.ts+++ b/packages/sheets-ui/src/services/canvas-pop-manager.service.ts@@ -39,7 +39,7 @@ import {toDisposable,UniverInstanceType,} from '@univerjs/core';-import { IRenderManagerService, RENDER_CLASS_TYPE } from '@univerjs/engine-render';+import { IRenderManagerService, RENDER_CLASS_TYPE, SHEET_VIEWPORT_KEY } from '@univerjs/engine-render';import {COMMAND_LISTENER_SKELETON_CHANGE,IRefSelectionsService,@@ -277,6 +277,11 @@ export class SheetCanvasPopManagerService extends Disposable {}}));+ const viewMain = currentRender.scene.getViewport(SHEET_VIEWPORT_KEY.VIEW_MAIN);+ if (viewMain) {+ disposable.add(viewMain.onScrollAfter$.subscribeEvent(() => position$.next(calc())));+ }+return {position,position$,