Skip to content

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.

feat(sheets-drawing): support image opacity (#7812)

wpxp1234566d85291319b5
diff --git a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
index ea69019d4d..b36a19a290 100644
--- a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
+++ b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts
@@ -247,6 +247,7 @@ describe('ImageUpdateController', () => {
drawingType: DrawingTypeEnum.DRAWING_IMAGE,
imageSourceType: ImageSourceType.BASE64,
source: 'data:image/png;base64,Zm9v',
+ opacity: 0.4,
srcRect: { bottom: 0, left: 0, right: 0, top: 0 },
subUnitId: 'sheet-1',
transform,
@@ -258,6 +259,7 @@ describe('ImageUpdateController', () => {
setClipBounds: vi.fn(),
setPrstGeom: vi.fn(),
setSrcRect: vi.fn(),
+ setOpacity: vi.fn(),
transformByState: vi.fn(),
};
const scene = {
@@ -280,7 +282,11 @@ describe('ImageUpdateController', () => {
drawingManagerService as never,
{} as never,
{} as never,
- { getUnit: vi.fn(() => createSheetUnit()), getFocusedUnit: vi.fn(() => createSheetUnit()) } as never,
+ {
+ getUnit: vi.fn(() => createSheetUnit()),
+ getFocusedUnit: vi.fn(() => createSheetUnit()),
+ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET),
+ } as never,
{ renderImages: vi.fn() } as never
);
@@ -300,6 +306,7 @@ describe('ImageUpdateController', () => {
width: 100,
});
expect(imageShape.setClipBounds).toHaveBeenCalledWith(transform.clipBounds);
+ expect(imageShape.setOpacity).toHaveBeenCalledWith(0.4);
expect(scene.removeObject).toHaveBeenCalledWith(imageShape);
expect(scene.addObject).toHaveBeenCalledWith(imageShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);
});
diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.ts
index 0afe25ffc7..0089650690 100644
--- a/packages/drawing-ui/src/controllers/image-update.controller.ts
+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts
@@ -25,8 +25,9 @@ import {
Inject,
IUniverInstanceService,
toDisposable,
+ UniverInstanceType,
} from '@univerjs/core';
-import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
+import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, normalizeImageOpacity, SetDrawingSelectedOperation } from '@univerjs/drawing';
import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';
import { bufferTime, filter, map } from 'rxjs';
import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';
@@ -224,7 +225,7 @@ export class ImageUpdateController extends Disposable {
return;
}
- const { transform, drawingType, srcRect, prstGeom, source, imageSourceType } = drawingParam;
+ const { transform, drawingType, srcRect, prstGeom, source, imageSourceType, opacity } = drawingParam;
if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {
return;
@@ -256,6 +257,11 @@ export class ImageUpdateController extends Disposable {
ensureDrawingRenderLayer(scene, imageShape, drawingParam);
imageShape.setSrcRect(srcRect);
imageShape.setPrstGeom(prstGeom);
+ syncImageOpacity(
+ imageShape,
+ opacity,
+ this._currentUniverService.getUnitType(unitId) === UniverInstanceType.UNIVER_SHEET
+ );
if (source != null && source.length > 0 && (imageSourceType === ImageSourceType.BASE64 || imageSourceType === ImageSourceType.URL)) {
imageShape.changeSource(source);
}
@@ -296,3 +302,9 @@ export class ImageUpdateController extends Disposable {
);
}
}
+
+function syncImageOpacity(image: Image, opacity: number | undefined, isSheet: boolean): void {
+ if (isSheet || opacity !== undefined) {
+ image.setOpacity(normalizeImageOpacity(opacity));
+ }
+}
diff --git a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts
index 98ed274ce0..8fe6459976 100644
--- a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts
+++ b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts
@@ -378,6 +378,32 @@ describe('DrawingRenderService', () => {
expect(image.visible).toBe(true);
});
+ it('applies image opacity and restores the sheet default for legacy models', async () => {
+ const { service, scene, univerInstanceService } = createHarness();
+ univerInstanceService.unitType = UniverInstanceType.UNIVER_SHEET;
+
+ await service.renderImages(imageParam({ opacity: 0.35 }), scene as unknown as Scene);
+
+ const key = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' });
+ const image = scene.objects.get(key) as Image;
+ expect(image.opacity).toBe(0.35);
+
+ image.setOpacity(0.2);
+ await service.renderImages(imageParam(), scene as unknown as Scene);
+ expect(image.opacity).toBe(1);
+ });
+
+ it('preserves transient document image opacity when the model has no opacity', async () => {
+ const { service, scene } = createHarness();
+ const key = drawingKey({ unitId: 'book-1', subUnitId: 'sheet-1', drawingId: 'drawing-1' });
+ const image = new Image(key, { ...BASE_TRANSFORM, opacity: 0.5, url: 'existing-image' });
+ scene.objects.set(key, image);
+
+ await service.renderImages(imageParam(), scene as unknown as Scene);
+
+ expect(image.opacity).toBe(0.5);
+ });
+
it('uses cached native images instead of resolving the source again', async () => {
const { service, scene, imageIoService } = createHarness();
const nativeImage = document.createElement('img');
diff --git a/packages/drawing-ui/src/services/drawing-render.service.ts b/packages/drawing-ui/src/services/drawing-render.service.ts
index 2ecf16df84..9f5351f9df 100644
--- a/packages/drawing-ui/src/services/drawing-render.service.ts
+++ b/packages/drawing-ui/src/services/drawing-render.service.ts
@@ -31,6 +31,7 @@ import {
import {
getDrawingShapeKeyByDrawingSearch,
IDrawingManagerService,
+ normalizeImageOpacity,
} from '@univerjs/drawing';
import { DRAWING_OBJECT_LAYER_INDEX, Image, Rect } from '@univerjs/engine-render';
import { IGalleryService } from '@univerjs/ui';
@@ -100,6 +101,7 @@ export class DrawingRenderService {
transforms: multiTransforms,
adjustValues,
hidden,
+ opacity,
} = imageParam;
const { docxHeaderFooterDrawing, layoutType } = imageParam as IImageData & {
docxHeaderFooterDrawing?: boolean;
@@ -135,6 +137,9 @@ export class DrawingRenderService {
if (imageShape != null) {
imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });
(imageShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);
+ if (this._univerInstanceService.getUnitType(unitId) === UniverInstanceType.UNIVER_SHEET || opacity !== undefined) {
+ (imageShape as Image).setOpacity(normalizeImageOpacity(opacity));
+ }
if ('hidden' in imageParam) {
hidden ? imageShape.hide() : imageShape.show();
}
@@ -144,7 +149,11 @@ export class DrawingRenderService {
const orders = this._drawingManagerService.getDrawingOrder(unitId, subUnitId);
const zIndex = orders.indexOf(drawingId);
- const imageConfig: IImageProps = { ...transform, zIndex: zIndex === -1 ? (orders.length - 1) : zIndex };
+ const imageConfig: IImageProps = {
+ ...transform,
+ opacity: normalizeImageOpacity(opacity),
+ zIndex: zIndex === -1 ? (orders.length - 1) : zIndex,
+ };
const imageNativeCache = this._imageIoService.getImageSourceCache(source, imageSourceType);
let shouldBeCache = false;
diff --git a/packages/drawing/src/index.ts b/packages/drawing/src/index.ts
index e4dde8c007..8804643c81 100644
--- a/packages/drawing/src/index.ts
+++ b/packages/drawing/src/index.ts
@@ -40,5 +40,6 @@ export type { ICreateDrawingCopyPlanOptions, IDrawingCopyPlan } from './utils/dr
export { DRAWING_GROUPABLE_TYPES, isGroupableDrawingType } from './utils/drawing-group';
export { getDrawingShapeKeyByDrawingSearch } from './utils/get-image-shape-key';
export { getImageSize } from './utils/get-image-size';
+export { normalizeImageOpacity } from './utils/image-opacity';
export { resolveDrawingRotateEnabled } from './utils/rotate-enabled';
export type { IDrawingRotateEnabledResolverOptions } from './utils/rotate-enabled';
diff --git a/packages/drawing/src/models/image-model-interface.ts b/packages/drawing/src/models/image-model-interface.ts
index 9cf4e89077..080bac2dcd 100644
--- a/packages/drawing/src/models/image-model-interface.ts
+++ b/packages/drawing/src/models/image-model-interface.ts
@@ -19,6 +19,8 @@ import type { IDrawingParam, ImageSourceType, ISrcRect, Nullable, Serializable }
export interface IImageData extends IDrawingParam {
imageSourceType: ImageSourceType;
source: string;
+ /** Whole-image opacity from 0 (transparent) through 1 (opaque). Defaults to 1. */
+ opacity?: number;
/**
* 20.1.8.55 srcRect (Source Rectangle)
*/
diff --git a/packages/drawing/src/utils/image-opacity.ts b/packages/drawing/src/utils/image-opacity.ts
new file mode 100644
index 0000000000..b5af135e9a
--- /dev/null
+++ b/packages/drawing/src/utils/image-opacity.ts
@@ -0,0 +1,23 @@
+/**
+ * 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.
+ */
+
+export function normalizeImageOpacity(opacity: number | undefined): number {
+ if (opacity === undefined || !Number.isFinite(opacity)) {
+ return 1;
+ }
+
+ return Math.min(Math.max(opacity, 0), 1);
+}
diff --git a/packages/sheets-drawing-ui/src/commands/operations/preview-sheet-image-opacity.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/preview-sheet-image-opacity.operation.ts
new file mode 100644
index 0000000000..0e73b02bcc
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/operations/preview-sheet-image-opacity.operation.ts
@@ -0,0 +1,44 @@
+/**
+ * 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 { IDrawingSearch, IOperation } from '@univerjs/core';
+import { CommandType } from '@univerjs/core';
+import { getDrawingShapeKeyByDrawingSearch } from '@univerjs/drawing';
+import { Image, IRenderManagerService } from '@univerjs/engine-render';
+
+export interface IPreviewSheetImageOpacityOperationParams extends IDrawingSearch {
+ opacity: number;
+}
+
+export const PreviewSheetImageOpacityOperation: IOperation<IPreviewSheetImageOpacityOperationParams> = {
+ id: 'sheet.operation.preview-image-opacity',
+ type: CommandType.OPERATION,
+ handler: (accessor, params) => {
+ if (!params || !Number.isFinite(params.opacity)) {
+ return false;
+ }
+
+ const renderManagerService = accessor.get(IRenderManagerService);
+ const scene = renderManagerService.getRenderUnitById(params.unitId)?.scene;
+ const image = scene?.getObject(getDrawingShapeKeyByDrawingSearch(params));
+ if (!(image instanceof Image)) {
+ return false;
+ }
+
+ image.setOpacity(Math.min(Math.max(params.opacity, 0), 1));
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts b/packages/sheets-drawing-ui/src/controllers/ui.controller.ts
index 0cfe2a654e..1dcf80a38e 100644
--- a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/ui.controller.ts
@@ -30,6 +30,7 @@ import {
} from '../commands/commands/worksheet-background-image.command';
import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';
import { SidebarSheetDrawingOperation } from '../commands/operations/open-drawing-panel.operation';
+import { PreviewSheetImageOpacityOperation } from '../commands/operations/preview-sheet-image-opacity.operation';
import { COMPONENT_SHEET_DRAWING_PANEL } from '../views/sheet-image-panel/component-name';
import {
DeleteDrawingsShortcutItem,
@@ -68,6 +69,7 @@ export class SheetDrawingUIController extends Disposable {
DeleteDrawingsCommand,
SaveCellImagesCommand,
FlipSheetDrawingCommand,
+ PreviewSheetImageOpacityOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
diff --git a/packages/sheets-drawing-ui/src/locale/ar-SA.ts b/packages/sheets-drawing-ui/src/locale/ar-SA.ts
index 131cc6b4f7..06e57422d2 100644
--- a/packages/sheets-drawing-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-drawing-ui/src/locale/ar-SA.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'يمكن رفع {0} صور فقط في المرة الواحدة',
invalidImage: 'صورة غير صالحة',
},
+ 'image-transparency': {
+ title: 'الشفافية',
+ },
'drawing-anchor': {
title: 'خصائص المرساة',
both: 'النقل والتحجيم مع الخلايا',
diff --git a/packages/sheets-drawing-ui/src/locale/ca-ES.ts b/packages/sheets-drawing-ui/src/locale/ca-ES.ts
index 4750d20483..482dfcb371 100644
--- a/packages/sheets-drawing-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-drawing-ui/src/locale/ca-ES.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Només es poden pujar {0} imatges alhora',
invalidImage: 'Imatge no vàlida',
},
+ 'image-transparency': {
+ title: 'Transparència',
+ },
'drawing-anchor': {
title: 'Propietats d’ancoratge',
both: 'Mou i canvia la mida amb les cel·les',
diff --git a/packages/sheets-drawing-ui/src/locale/de-DE.ts b/packages/sheets-drawing-ui/src/locale/de-DE.ts
index 950f30ca9d..46be7fe77d 100644
--- a/packages/sheets-drawing-ui/src/locale/de-DE.ts
+++ b/packages/sheets-drawing-ui/src/locale/de-DE.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Es können nur {0} Bilder gleichzeitig hochgeladen werden',
invalidImage: 'Ungültiges Bild',
},
+ 'image-transparency': {
+ title: 'Transparenz',
+ },
'drawing-anchor': {
title: 'Anker-Eigenschaften',
both: 'Mit Zellen verschieben und skalieren',
diff --git a/packages/sheets-drawing-ui/src/locale/en-US.ts b/packages/sheets-drawing-ui/src/locale/en-US.ts
index 623c0cb283..f3f2677201 100644
--- a/packages/sheets-drawing-ui/src/locale/en-US.ts
+++ b/packages/sheets-drawing-ui/src/locale/en-US.ts
@@ -62,6 +62,9 @@ const locale = {
exceedMaxCount: 'Only {0} images can be uploaded at a time',
invalidImage: 'Invalid image',
},
+ 'image-transparency': {
+ title: 'Transparency',
+ },
'drawing-anchor': {
title: 'Anchor Properties',
both: 'Move and size with cells',
diff --git a/packages/sheets-drawing-ui/src/locale/es-ES.ts b/packages/sheets-drawing-ui/src/locale/es-ES.ts
index d17729c1f7..32f13659f7 100644
--- a/packages/sheets-drawing-ui/src/locale/es-ES.ts
+++ b/packages/sheets-drawing-ui/src/locale/es-ES.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Solo se pueden subir {0} imágenes a la vez',
invalidImage: 'Imagen no válida',
},
+ 'image-transparency': {
+ title: 'Transparencia',
+ },
'drawing-anchor': {
title: 'Propiedades de anclaje',
both: 'Mover y cambiar tamaño con las celdas',
diff --git a/packages/sheets-drawing-ui/src/locale/fa-IR.ts b/packages/sheets-drawing-ui/src/locale/fa-IR.ts
index bc6ed900d5..9b5fe75034 100644
--- a/packages/sheets-drawing-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-drawing-ui/src/locale/fa-IR.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'فقط {0} تصویر می‌توانند همزمان آپلود شوند',
invalidImage: 'تصویر نامعتبر است',
},
+ 'image-transparency': {
+ title: 'شفافیت',
+ },
'drawing-anchor': {
title: 'خواص لنگر',
both: 'جابه‌جایی و تغییر اندازه با سلول‌ها',
diff --git a/packages/sheets-drawing-ui/src/locale/fr-FR.ts b/packages/sheets-drawing-ui/src/locale/fr-FR.ts
index 41df4f91f6..d1c1f82d8d 100644
--- a/packages/sheets-drawing-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-drawing-ui/src/locale/fr-FR.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Seulement {0} images peuvent être téléchargées à la fois',
invalidImage: 'Image invalide',
},
+ 'image-transparency': {
+ title: 'Transparence',
+ },
'drawing-anchor': {
title: 'Propriétés de l\'ancre',
both: 'Déplacer et redimensionner avec les cellules',
diff --git a/packages/sheets-drawing-ui/src/locale/id-ID.ts b/packages/sheets-drawing-ui/src/locale/id-ID.ts
index 6bf48ff747..b986cdfffb 100644
--- a/packages/sheets-drawing-ui/src/locale/id-ID.ts
+++ b/packages/sheets-drawing-ui/src/locale/id-ID.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Hanya {0} gambar yang dapat diunggah dalam satu waktu',
invalidImage: 'Gambar tidak valid',
},
+ 'image-transparency': {
+ title: 'Transparansi',
+ },
'drawing-anchor': {
title: 'Properti Jangkar',
both: 'Pindah dan ukur bersama sel',
diff --git a/packages/sheets-drawing-ui/src/locale/it-IT.ts b/packages/sheets-drawing-ui/src/locale/it-IT.ts
index 8a7cbd79ed..924ab36620 100644
--- a/packages/sheets-drawing-ui/src/locale/it-IT.ts
+++ b/packages/sheets-drawing-ui/src/locale/it-IT.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'È possibile caricare solo {0} immagini alla volta',
invalidImage: 'Immagine non valida',
},
+ 'image-transparency': {
+ title: 'Trasparenza',
+ },
'drawing-anchor': {
title: 'Proprietà ancoraggio',
both: 'Sposta e ridimensiona con le celle',
diff --git a/packages/sheets-drawing-ui/src/locale/ja-JP.ts b/packages/sheets-drawing-ui/src/locale/ja-JP.ts
index 0e972fc286..d17b64dcb9 100644
--- a/packages/sheets-drawing-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-drawing-ui/src/locale/ja-JP.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: '一度にアップロードできるのは {0} 個までです',
invalidImage: '無効な画像です',
},
+ 'image-transparency': {
+ title: '透明度',
+ },
'drawing-anchor': {
title: 'プロパティ',
both: 'セルに合わせて移動やサイズ変更をする',
diff --git a/packages/sheets-drawing-ui/src/locale/ko-KR.ts b/packages/sheets-drawing-ui/src/locale/ko-KR.ts
index 5a2d2307b8..5def674251 100644
--- a/packages/sheets-drawing-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-drawing-ui/src/locale/ko-KR.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: '한 번에 {0}개까지만 업로드할 수 있습니다',
invalidImage: '유효하지 않은 이미지입니다',
},
+ 'image-transparency': {
+ title: '투명도',
+ },
'drawing-anchor': {
title: '고정 위치 설정',
both: '셀과 함께 이동 및 크기 조절',
diff --git a/packages/sheets-drawing-ui/src/locale/pl-PL.ts b/packages/sheets-drawing-ui/src/locale/pl-PL.ts
index dacc16d813..f6c0a8f68e 100644
--- a/packages/sheets-drawing-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-drawing-ui/src/locale/pl-PL.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Jednocześnie można przesłać tylko {0} obrazów',
invalidImage: 'Nieprawidłowy obraz',
},
+ 'image-transparency': {
+ title: 'Przezroczystość',
+ },
'drawing-anchor': {
title: 'Właściwości kotwicy',
both: 'Przesuwaj i zmieniaj rozmiar razem z komórkami',
diff --git a/packages/sheets-drawing-ui/src/locale/pt-BR.ts b/packages/sheets-drawing-ui/src/locale/pt-BR.ts
index c4c77ea76a..f30053fb6d 100644
--- a/packages/sheets-drawing-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-drawing-ui/src/locale/pt-BR.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Apenas {0} imagens podem ser enviadas de cada vez',
invalidImage: 'Imagem inválida',
},
+ 'image-transparency': {
+ title: 'Transparência',
+ },
'drawing-anchor': {
title: 'Propriedades da âncora',
both: 'Mover e dimensionar com as células',
diff --git a/packages/sheets-drawing-ui/src/locale/ru-RU.ts b/packages/sheets-drawing-ui/src/locale/ru-RU.ts
index 52de1edccc..2bf7bc4932 100644
--- a/packages/sheets-drawing-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-drawing-ui/src/locale/ru-RU.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'За один раз можно загрузить только {0} изображений',
invalidImage: 'Недопустимое изображение',
},
+ 'image-transparency': {
+ title: 'Прозрачность',
+ },
'drawing-anchor': {
title: 'Свойства привязки',
both: 'Перемещать и изменять размер с ячейками',
diff --git a/packages/sheets-drawing-ui/src/locale/sk-SK.ts b/packages/sheets-drawing-ui/src/locale/sk-SK.ts
index df72c3b894..bd334528e6 100644
--- a/packages/sheets-drawing-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-drawing-ui/src/locale/sk-SK.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Naraz možno nahrať iba {0} obrázkov',
invalidImage: 'Neplatný obrázok',
},
+ 'image-transparency': {
+ title: 'Priehľadnosť',
+ },
'drawing-anchor': {
title: 'Vlastnosti ukotvenia',
both: 'Presúvať a meniť veľkosť s bunkami',
diff --git a/packages/sheets-drawing-ui/src/locale/vi-VN.ts b/packages/sheets-drawing-ui/src/locale/vi-VN.ts
index 9c588ce910..cbdee1fb24 100644
--- a/packages/sheets-drawing-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-drawing-ui/src/locale/vi-VN.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: 'Chỉ có thể tải lên {0} hình ảnh một lần',
invalidImage: 'Hình ảnh không hợp lệ',
},
+ 'image-transparency': {
+ title: 'Độ trong suốt',
+ },
'drawing-anchor': {
title: 'Thuộc tính neo',
both: 'Di chuyển và thay đổi kích thước cùng với ô',
diff --git a/packages/sheets-drawing-ui/src/locale/zh-CN.ts b/packages/sheets-drawing-ui/src/locale/zh-CN.ts
index 834b887f9a..1e28344d4f 100644
--- a/packages/sheets-drawing-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-drawing-ui/src/locale/zh-CN.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: '图片只能一次上传{0}张',
invalidImage: '无效图片',
},
+ 'image-transparency': {
+ title: '透明度',
+ },
'drawing-anchor': {
title: '锚点属性',
both: '与单元格一起移动和调整大小',
diff --git a/packages/sheets-drawing-ui/src/locale/zh-HK.ts b/packages/sheets-drawing-ui/src/locale/zh-HK.ts
index 4adb34bca5..d755745b11 100644
--- a/packages/sheets-drawing-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-drawing-ui/src/locale/zh-HK.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: '圖片只能一次上傳{0}張',
invalidImage: '無效圖片',
},
+ 'image-transparency': {
+ title: '透明度',
+ },
'drawing-anchor': {
title: '錨點屬性',
both: '與儲存格一起移動和調整大小',
diff --git a/packages/sheets-drawing-ui/src/locale/zh-TW.ts b/packages/sheets-drawing-ui/src/locale/zh-TW.ts
index 4adb34bca5..d755745b11 100644
--- a/packages/sheets-drawing-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-drawing-ui/src/locale/zh-TW.ts
@@ -64,6 +64,9 @@ const locale: typeof enUS = {
exceedMaxCount: '圖片只能一次上傳{0}張',
invalidImage: '無效圖片',
},
+ 'image-transparency': {
+ title: '透明度',
+ },
'drawing-anchor': {
title: '錨點屬性',
both: '與儲存格一起移動和調整大小',
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
index 0c71e63fd9..02c0a07d6a 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingAnchor.tsx
@@ -31,6 +31,7 @@ import {
} from '@univerjs/sheets-drawing';
import { useDependency } from '@univerjs/ui';
import { useEffect, useState } from 'react';
+import { isSheetDrawing } from './sheet-drawing-panel.util';
import type { LocaleKey } from '../../locale/types';
@@ -39,10 +40,6 @@ export interface ISheetDrawingAnchorProps {
}
export const SheetDrawingAnchor = (props: ISheetDrawingAnchorProps) => {
- function isSheetDrawing(drawing: IDrawingParam | undefined): drawing is ISheetDrawing {
- return Boolean(drawing && 'sheetTransform' in drawing && 'axisAlignSheetTransform' in drawing);
- }
-
function getAnchorKind(value: string | number | boolean): SheetDrawingAnchorType | null {
if (
value === SheetDrawingAnchorType.Position ||
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx
index 167053cdd7..3ed6ade144 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetDrawingPanel.tsx
@@ -18,6 +18,7 @@ import { IDrawingManagerService } from '@univerjs/drawing';
import { DrawingCommonPanel } from '@univerjs/drawing-ui';
import { useDependency, useObservable } from '@univerjs/ui';
import { SheetDrawingAnchor } from './SheetDrawingAnchor';
+import { SheetImageTransparency } from './SheetImageTransparency';
export const SheetDrawingPanel = () => {
const drawingManagerService = useDependency(IDrawingManagerService);
@@ -31,6 +32,7 @@ export const SheetDrawingPanel = () => {
return !!drawings?.length && (
<div className="univer-text-sm">
<DrawingCommonPanel drawings={drawings} />
+ <SheetImageTransparency drawings={drawings} />
<SheetDrawingAnchor drawings={drawings} />
</div>
);
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetImageTransparency.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetImageTransparency.tsx
new file mode 100644
index 0000000000..311c400475
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetImageTransparency.tsx
@@ -0,0 +1,177 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import type { ISheetImage } from '@univerjs/sheets-drawing';
+import type { LocaleKey } from '../../locale/types';
+import { DrawingTypeEnum, ICommandService, LocaleService } from '@univerjs/core';
+import { normalizeImageOpacity } from '@univerjs/drawing';
+import { ISheetDrawingService, SetSheetDrawingCommand } from '@univerjs/sheets-drawing';
+import { useDependency } from '@univerjs/ui';
+import { useEffect, useRef, useState } from 'react';
+import { PreviewSheetImageOpacityOperation } from '../../commands/operations/preview-sheet-image-opacity.operation';
+import { isSheetDrawing } from './sheet-drawing-panel.util';
+import { SheetImageTransparencySlider } from './SheetImageTransparencySlider';
+
+const IMAGE_TRANSPARENCY_PRESETS = [0, 15, 30, 50, 65, 80];
+
+export interface ISheetImageTransparencyProps {
+ drawings: IDrawingParam[];
+}
+
+export const SheetImageTransparency = ({ drawings }: ISheetImageTransparencyProps) => {
+ const commandService = useDependency(ICommandService);
+ const localeService = useDependency(LocaleService);
+ const sheetDrawingService = useDependency(ISheetDrawingService);
+ const drawingParam = isSheetDrawing(drawings[0]) ? drawings[0] : undefined;
+ const currentDrawing = drawingParam
+ ? sheetDrawingService.getDrawingByParam(drawingParam) ?? drawingParam
+ : undefined;
+ const image = currentDrawing?.drawingType === DrawingTypeEnum.DRAWING_IMAGE
+ ? currentDrawing as ISheetImage
+ : undefined;
+ const modelOpacity = normalizeImageOpacity(image?.opacity);
+ const modelTransparency = Math.round((1 - modelOpacity) * 100);
+ const [previewState, setPreviewState] = useState<{
+ unitId: string;
+ subUnitId: string;
+ drawingId: string;
+ transparency: number;
+ } | null>(null);
+ const previewPendingRef = useRef(false);
+ const [, setModelRevision] = useState(0);
+ const transparency = image &&
+ previewState?.unitId === image.unitId &&
+ previewState.subUnitId === image.subUnitId &&
+ previewState.drawingId === image.drawingId
+ ? previewState.transparency
+ : modelTransparency;
+
+ useEffect(() => {
+ if (!drawingParam) {
+ return;
+ }
+
+ const subscription = sheetDrawingService.update$.subscribe((updatedDrawings) => {
+ const drawingUpdated = updatedDrawings.some((updatedDrawing) =>
+ updatedDrawing.unitId === drawingParam.unitId &&
+ updatedDrawing.subUnitId === drawingParam.subUnitId &&
+ updatedDrawing.drawingId === drawingParam.drawingId
+ );
+ if (drawingUpdated) {
+ setModelRevision((revision) => revision + 1);
+ }
+ });
+
+ return () => subscription.unsubscribe();
+ }, [drawingParam, sheetDrawingService]);
+
+ useEffect(() => {
+ previewPendingRef.current = false;
+ return () => {
+ if (!previewPendingRef.current || !image) {
+ return;
+ }
+
+ commandService.syncExecuteCommand(PreviewSheetImageOpacityOperation.id, {
+ unitId: image.unitId,
+ subUnitId: image.subUnitId,
+ drawingId: image.drawingId,
+ opacity: modelOpacity,
+ });
+ };
+ }, [commandService, image, modelOpacity, modelTransparency]);
+
+ if (!image) {
+ return null;
+ }
+
+ const title = localeService.t<LocaleKey>('sheets-drawing-ui.image-transparency.title');
+ const { unitId, subUnitId, drawingId } = image;
+
+ function previewTransparency(nextTransparency: number) {
+ const normalizedTransparency = normalizeTransparency(nextTransparency);
+ const opacity = transparencyToOpacity(normalizedTransparency);
+ previewPendingRef.current = true;
+ setPreviewState({ unitId, subUnitId, drawingId, transparency: normalizedTransparency });
+ commandService.syncExecuteCommand(PreviewSheetImageOpacityOperation.id, {
+ unitId,
+ subUnitId,
+ drawingId,
+ opacity,
+ });
+ }
+
+ function commitTransparency(nextTransparency: number) {
+ const normalizedTransparency = normalizeTransparency(nextTransparency);
+ const opacity = transparencyToOpacity(normalizedTransparency);
+ previewPendingRef.current = false;
+ setPreviewState(null);
+ if (opacity === modelOpacity) {
+ return;
+ }
+
+ const changed = commandService.syncExecuteCommand(SetSheetDrawingCommand.id, {
+ unitId,
+ drawings: [{
+ unitId,
+ subUnitId,
+ drawingId,
+ opacity,
+ }],
+ });
+ if (!changed) {
+ commandService.syncExecuteCommand(PreviewSheetImageOpacityOperation.id, {
+ unitId,
+ subUnitId,
+ drawingId,
+ opacity: modelOpacity,
+ });
+ }
+ }
+
+ return (
+ <section className="univer-grid univer-gap-2 univer-py-2 univer-text-gray-400">
+ <header
+ className="
+ univer-text-gray-600
+ dark:!univer-text-gray-200
+ "
+ >
+ {title}
+ </header>
+ <SheetImageTransparencySlider
+ value={transparency}
+ shortcuts={IMAGE_TRANSPARENCY_PRESETS}
+ ariaLabel={title}
+ onChange={previewTransparency}
+ onChangeComplete={commitTransparency}
+ />
+ </section>
+ );
+};
+
+function normalizeTransparency(transparency: number): number {
+ if (!Number.isFinite(transparency)) {
+ return 0;
+ }
+
+ return Math.min(Math.max(Math.round(transparency), 0), 100);
+}
+
+function transparencyToOpacity(transparency: number): number {
+ return (100 - transparency) / 100;
+}
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetImageTransparencySlider.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetImageTransparencySlider.tsx
new file mode 100644
index 0000000000..d95f2a0bc4
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/SheetImageTransparencySlider.tsx
@@ -0,0 +1,428 @@
+/**
+ * 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 { IDropdownMenuProps } from '@univerjs/design';
+import type { KeyboardEvent, PointerEvent } from 'react';
+import { LocaleService } from '@univerjs/core';
+import { borderClassName, Button, clsx, DropdownMenu, Input } from '@univerjs/design';
+import { IconManager, useDependency, useObservable } from '@univerjs/ui';
+import { useEffect, useRef, useState } from 'react';
+
+const MIN_TRANSPARENCY = 0;
+const MAX_TRANSPARENCY = 100;
+const TRANSPARENCY_STEP = 1;
+const TRANSPARENCY_PAGE_STEP = 10;
+const DRAG_PREVIEW_INTERVAL = 50;
+
+export interface ISheetImageTransparencySliderProps {
+ value: number;
+ shortcuts: number[];
+ ariaLabel: string;
+ disabled?: boolean;
+ onChange?: (value: number) => void;
+ onChangeComplete?: (value: number) => void;
+}
+
+export function SheetImageTransparencySlider(props: ISheetImageTransparencySliderProps) {
+ const {
+ value,
+ shortcuts,
+ ariaLabel,
+ disabled = false,
+ onChange,
+ onChangeComplete,
+ } = props;
+ const localeService = useDependency(LocaleService);
+ const direction = useObservable(localeService.direction$, localeService.getDirection());
+ const isRtl = direction === 'rtl';
+ const sliderRailRef = useRef<HTMLDivElement>(null);
+ const dragValueRef = useRef(value);
+ const pendingDragValueRef = useRef<number | null>(null);
+ const lastPreviewedDragValueRef = useRef(value);
+ const dragPreviewTimerRef = useRef<number | null>(null);
+ const dragCleanupRef = useRef<(() => void) | null>(null);
+ const [isDragging, setIsDragging] = useState(false);
+ const [dragValue, setDragValue] = useState(value);
+
+ useEffect(() => () => {
+ dragCleanupRef.current?.();
+ clearDragPreviewTimer();
+ }, []);
+
+ function getValueByClientX(clientX: number) {
+ const rail = sliderRailRef.current;
+ if (!rail) {
+ return value;
+ }
+
+ const railRect = rail.getBoundingClientRect();
+ if (railRect.width <= 0) {
+ return value;
+ }
+
+ let ratio = (clientX - railRect.left) / railRect.width;
+ ratio = Math.min(Math.max(ratio, 0), 1);
+ if (isRtl) {
+ ratio = 1 - ratio;
+ }
+
+ return normalizeTransparency(MIN_TRANSPARENCY + ratio * (MAX_TRANSPARENCY - MIN_TRANSPARENCY));
+ }
+
+ function clearDragPreviewTimer() {
+ if (dragPreviewTimerRef.current != null) {
+ window.clearTimeout(dragPreviewTimerRef.current);
+ dragPreviewTimerRef.current = null;
+ }
+ }
+
+ function previewDragValue(nextValue: number) {
+ if (nextValue === lastPreviewedDragValueRef.current) {
+ return;
+ }
+
+ lastPreviewedDragValueRef.current = nextValue;
+ onChange?.(nextValue);
+ }
+
+ function flushDragPreview() {
+ clearDragPreviewTimer();
+
+ const nextValue = pendingDragValueRef.current;
+ pendingDragValueRef.current = null;
+ if (nextValue != null) {
+ previewDragValue(nextValue);
+ }
+ }
+
+ function scheduleDragPreview(nextValue: number) {
+ pendingDragValueRef.current = nextValue;
+ if (dragPreviewTimerRef.current != null) {
+ return;
+ }
+
+ dragPreviewTimerRef.current = window.setTimeout(() => {
+ dragPreviewTimerRef.current = null;
+ const pendingValue = pendingDragValueRef.current;
+ pendingDragValueRef.current = null;
+ if (pendingValue != null) {
+ previewDragValue(pendingValue);
+ }
+ }, DRAG_PREVIEW_INTERVAL);
+ }
+
+ function updateDragValue(clientX: number) {
+ const nextValue = getValueByClientX(clientX);
+ dragValueRef.current = nextValue;
+ setDragValue(nextValue);
+ return nextValue;
+ }
+
+ function handlePointerDown(e: PointerEvent<HTMLDivElement>) {
+ if (disabled) {
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ dragCleanupRef.current?.();
+ clearDragPreviewTimer();
+ pendingDragValueRef.current = null;
+ lastPreviewedDragValueRef.current = value;
+ setIsDragging(true);
+ scheduleDragPreview(updateDragValue(e.clientX));
+
+ function cleanup() {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ window.removeEventListener('pointercancel', handlePointerUp);
+ dragCleanupRef.current = null;
+ }
+
+ function handlePointerMove(event: globalThis.PointerEvent) {
+ scheduleDragPreview(updateDragValue(event.clientX));
+ }
+
+ function handlePointerUp() {
+ cleanup();
+ flushDragPreview();
+ setIsDragging(false);
+ onChangeComplete?.(dragValueRef.current);
+ }
+
+ dragCleanupRef.current = cleanup;
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ window.addEventListener('pointercancel', handlePointerUp);
+ }
+
+ function handleSliderKeyDown(e: KeyboardEvent<HTMLButtonElement>) {
+ let nextValue: number | null = null;
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
+ nextValue = value - TRANSPARENCY_STEP;
+ } else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
+ nextValue = value + TRANSPARENCY_STEP;
+ } else if (e.key === 'PageDown') {
+ nextValue = value - TRANSPARENCY_PAGE_STEP;
+ } else if (e.key === 'PageUp') {
+ nextValue = value + TRANSPARENCY_PAGE_STEP;
+ } else if (e.key === 'Home') {
+ nextValue = MIN_TRANSPARENCY;
+ } else if (e.key === 'End') {
+ nextValue = MAX_TRANSPARENCY;
+ }
+
+ if (nextValue == null || disabled) {
+ return;
+ }
+
+ e.preventDefault();
+ e.stopPropagation();
+ const normalizedValue = normalizeTransparency(nextValue);
+ onChange?.(normalizedValue);
+ onChangeComplete?.(normalizedValue);
+ }
+
+ const visualValue = isDragging ? dragValue : value;
+ const sliderOffset = normalizeTransparency(visualValue);
+ const handleOffset = isRtl ? MAX_TRANSPARENCY - sliderOffset : sliderOffset;
+
+ return (
+ <div
+ className={clsx('univer-flex univer-select-none univer-items-center univer-gap-1.5', {
+ 'univer-cursor-not-allowed': disabled,
+ })}
+ >
+ <div className="univer-flex univer-h-6 univer-min-w-0 univer-flex-1 univer-items-center">
+ <div
+ className={clsx(`
+ univer-relative univer-h-1.5 univer-w-full univer-rounded-full univer-bg-gray-200 univer-px-1.5
+ univer-transition-colors
+ dark:!univer-bg-gray-600
+ `, {
+ 'univer-opacity-60': disabled,
+ })}
+ >
+ <div
+ ref={sliderRailRef}
+ data-u-comp="sheet-image-transparency-slider-track"
+ className="
+ univer-relative univer-h-1.5 univer-bg-gray-200
+ dark:!univer-bg-gray-600
+ "
+ onPointerDown={handlePointerDown}
+ >
+ <div
+ className={clsx(`
+ univer-bg-primary-500/60 univer-absolute univer-top-0 univer-h-full univer-rounded-full
+ `, isRtl ? 'univer-right-0' : 'univer-left-0')}
+ style={{ width: `${sliderOffset}%` }}
+ />
+ <button
+ className={clsx(`
+ univer-absolute univer-top-1/2 univer-size-3.5 -univer-translate-x-1/2
+ -univer-translate-y-1/2 univer-rounded-full univer-bg-gray-0 univer-shadow-sm
+ focus-visible:univer-outline-none focus-visible:univer-ring-2
+ focus-visible:univer-ring-primary-100
+ dark:!univer-bg-gray-800
+ `, borderClassName, {
+ 'univer-cursor-pointer hover:univer-border-primary-600 hover:univer-shadow-md': !disabled,
+ 'univer-cursor-not-allowed': disabled,
+ 'univer-scale-105 univer-border-primary-600 univer-shadow-md': isDragging,
+ 'univer-transition-all': !isDragging,
+ 'univer-transition-none': isDragging,
+ })}
+ role="slider"
+ aria-label={ariaLabel}
+ aria-valuemin={MIN_TRANSPARENCY}
+ aria-valuemax={MAX_TRANSPARENCY}
+ aria-valuenow={visualValue}
+ aria-valuetext={`${visualValue}%`}
+ disabled={disabled}
+ type="button"
+ style={{ left: `${handleOffset}%` }}
+ onKeyDown={handleSliderKeyDown}
+ />
+ </div>
+ </div>
+ </div>
+
+ <SheetImageTransparencyInput
+ value={value}
+ shortcuts={shortcuts}
+ ariaLabel={ariaLabel}
+ disabled={disabled}
+ onChange={onChange}
+ onChangeComplete={onChangeComplete}
+ />
+ </div>
+ );
+}
+
+interface ISheetImageTransparencyInputProps extends ISheetImageTransparencySliderProps {}
+
+function SheetImageTransparencyInput(props: ISheetImageTransparencyInputProps) {
+ const {
+ value,
+ shortcuts,
+ ariaLabel,
+ disabled = false,
+ onChange,
+ onChangeComplete,
+ } = props;
+ const iconManager = useDependency(IconManager);
+ const localeService = useDependency(LocaleService);
+ const isEditingRef = useRef(false);
+ const [listVisible, setListVisible] = useState(false);
+ const [inputValue, setInputValue] = useState(() => `${value}%`);
+
+ useEffect(() => {
+ if (!isEditingRef.current) {
+ setInputValue(`${value}%`);
+ }
+ }, [value]);
+
+ function emitValue(nextValue: number) {
+ const normalizedValue = normalizeTransparency(nextValue);
+ onChange?.(normalizedValue);
+ onChangeComplete?.(normalizedValue);
+ }
+
+ function handleSelect(nextValue: number) {
+ if (disabled) {
+ return;
+ }
+
+ setListVisible(false);
+ emitValue(nextValue);
+ }
+
+ function handleFocus() {
+ if (disabled) {
+ return;
+ }
+
+ isEditingRef.current = true;
+ setInputValue(String(value));
+ }
+
+ function commitInput() {
+ if (disabled || !isEditingRef.current) {
+ return;
+ }
+
+ const parsedValue = parseTransparency(inputValue);
+ isEditingRef.current = false;
+ if (parsedValue == null) {
+ setInputValue(`${value}%`);
+ return;
+ }
+
+ if (parsedValue === value) {
+ setInputValue(`${parsedValue}%`);
+ return;
+ }
+
+ emitValue(parsedValue);
+ }
+
+ function handleKeyDown(e: KeyboardEvent<HTMLInputElement>) {
+ e.stopPropagation();
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ commitInput();
+ e.currentTarget.blur();
+ }
+ }
+
+ const items: IDropdownMenuProps['items'] = [{
+ type: 'radio',
+ value: value.toString(),
+ options: shortcuts.map((shortcut) => ({ value: shortcut.toString(), label: `${shortcut}%` })),
+ onSelect: (selectedValue: string) => handleSelect(Number(selectedValue)),
+ }];
+ const MoreDownIcon = iconManager.get('MoreDownIcon');
+
+ return (
+ <div
+ className={clsx(`
+ univer-flex univer-h-6 univer-w-[68px] univer-flex-shrink-0 univer-items-center univer-overflow-hidden
+ univer-rounded-md univer-border univer-border-gray-200 univer-bg-gray-0
+ dark:!univer-border-gray-600 dark:!univer-bg-gray-800
+ `, {
+ 'univer-opacity-60': disabled,
+ })}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Input
+ className="
+ univer-box-border univer-h-6 univer-min-w-0 univer-flex-1 univer-border-none univer-bg-transparent
+ [&_input:focus]:!univer-ring-0
+ [&_input]:univer-h-6 [&_input]:univer-w-full [&_input]:univer-border-none
+ [&_input]:!univer-bg-transparent [&_input]:univer-px-1 [&_input]:univer-text-center
+ [&_input]:univer-text-xs [&_input]:univer-tabular-nums
+ "
+ inputClass="univer-w-full"
+ size="mini"
+ aria-label={ariaLabel}
+ value={inputValue}
+ disabled={disabled}
+ type="text"
+ onChange={setInputValue}
+ onFocus={handleFocus}
+ onBlur={commitInput}
+ onKeyDown={handleKeyDown}
+ />
+
+ <DropdownMenu
+ align="end"
+ items={items}
+ open={listVisible}
+ disabled={disabled}
+ onOpenChange={setListVisible}
+ >
+ <Button
+ className="univer-h-6 univer-w-4 univer-rounded-none univer-p-0"
+ size="small"
+ variant="text"
+ aria-label={localeService.t('ui.accessibility.menu')}
+ disabled={disabled}
+ >
+ <MoreDownIcon
+ className="
+ univer-size-3 univer-text-gray-500
+ dark:!univer-text-gray-300
+ "
+ />
+ </Button>
+ </DropdownMenu>
+ </div>
+ );
+}
+
+function parseTransparency(rawValue: string): number | null {
+ const normalizedValue = rawValue.trim().replace(/%$/, '').trim();
+ if (normalizedValue === '') {
+ return null;
+ }
+
+ const parsedValue = Number(normalizedValue);
+ return Number.isFinite(parsedValue) ? normalizeTransparency(parsedValue) : null;
+}
+
+function normalizeTransparency(value: number): number {
+ return Math.min(Math.max(Math.round(value), MIN_TRANSPARENCY), MAX_TRANSPARENCY);
+}
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
index 5500c9322f..6d03b555ad 100644
--- a/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/__tests__/SheetDrawingPanelBehavior.spec.tsx
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-import type { ISheetDrawing } from '@univerjs/sheets-drawing';
+import type { ISheetDrawing, ISheetImage } from '@univerjs/sheets-drawing';
import type { Root } from 'react-dom/client';
-import { DrawingTypeEnum, ImageSourceType } from '@univerjs/core';
+import { DrawingTypeEnum, ImageSourceType, LocaleService, LocaleType, RedoCommand, UndoCommand } from '@univerjs/core';
import { IDrawingManagerService } from '@univerjs/drawing';
import { UniverDrawingUIPlugin } from '@univerjs/drawing-ui';
-import { IRenderManagerService } from '@univerjs/engine-render';
+import { Image, IRenderManagerService } from '@univerjs/engine-render';
import { InsertSheetDrawingCommand, ISheetDrawingService, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import { ComponentManager, IconManager, RediContext } from '@univerjs/ui';
import { act } from 'react';
@@ -27,6 +27,8 @@ import { createRoot } from 'react-dom/client';
import { Subject } from 'rxjs';
import { afterEach, describe, expect, it } from 'vitest';
import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';
+import { PreviewSheetImageOpacityOperation } from '../../../commands/operations/preview-sheet-image-opacity.operation';
+import sheetsDrawingUiEnUS from '../../../locale/en-US';
import { SheetDrawingPanel } from '../SheetDrawingPanel';
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
@@ -43,11 +45,14 @@ class TestTransformer {
changeNotification: () => undefined,
};
}
+
+ debounceRefreshControls() {}
}
class TestScene {
ancestorLeft = 0;
ancestorTop = 0;
+ readonly image = new Image('test-image', { opacity: 1 });
constructor(private readonly _transformer: TestTransformer) {}
@@ -63,6 +68,14 @@ class TestScene {
getTransformerByCreate() {
return this._transformer;
}
+
+ getTransformer() {
+ return this._transformer;
+ }
+
+ getObject() {
+ return this.image;
+ }
}
class TestRenderManagerService {
@@ -281,4 +294,150 @@ describe('SheetDrawingPanel behavior', () => {
expect(container.firstElementChild).toBeNull();
});
+
+ it('renders single-image transparency and supports preview, commit, undo, and redo', async () => {
+ currentTestBed = createSheetsDrawingUiTestBed(undefined, [
+ [IRenderManagerService, { useClass: TestRenderManagerService as never }],
+ [IconManager],
+ [ComponentManager],
+ ]);
+ currentTestBed.injector.createInstance(UniverDrawingUIPlugin, {}).onStarting();
+ currentTestBed.commandService.registerCommand(PreviewSheetImageOpacityOperation);
+ currentTestBed.get(LocaleService).load({ [LocaleType.EN_US]: sheetsDrawingUiEnUS });
+ const drawingManagerService = currentTestBed.get(IDrawingManagerService);
+ const sheetDrawingService = currentTestBed.get(ISheetDrawingService);
+ const renderManagerService = currentTestBed.get(IRenderManagerService) as unknown as TestRenderManagerService;
+ const drawing = createSheetDrawing(
+ currentTestBed.unitId,
+ currentTestBed.subUnitId,
+ 'drawing-opacity',
+ SheetDrawingAnchorType.Position
+ );
+
+ await currentTestBed.commandService.executeCommand(InsertSheetDrawingCommand.id, {
+ unitId: currentTestBed.unitId,
+ drawings: [drawing],
+ });
+
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <SheetDrawingPanel />
+ </RediContext.Provider>
+ );
+ drawingManagerService.focusDrawing([drawing]);
+ await Promise.resolve();
+ });
+
+ const transparencyInput = container.querySelector<HTMLInputElement>('input[aria-label="Transparency"]');
+ const transparencySlider = container.querySelector<HTMLButtonElement>('[role="slider"][aria-label="Transparency"]');
+ expect(transparencyInput?.value).toBe('0%');
+ expect(transparencySlider?.getAttribute('aria-valuenow')).toBe('0');
+ const headers = Array.from(container.querySelectorAll('header')).map((header) => header.textContent);
+ expect(headers.indexOf('Transparency')).toBeLessThan(headers.indexOf('Anchor Properties'));
+ const sliderTrack = container.querySelector<HTMLDivElement>('[data-u-comp="sheet-image-transparency-slider-track"]')!;
+ Object.defineProperty(sliderTrack, 'getBoundingClientRect', {
+ value: () => ({
+ bottom: 6,
+ height: 6,
+ left: 0,
+ right: 100,
+ top: 0,
+ width: 100,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ }),
+ });
+
+ await act(async () => {
+ sliderTrack.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, clientX: 35 }));
+ window.dispatchEvent(new MouseEvent('pointermove', { clientX: 65 }));
+ await Promise.resolve();
+ });
+
+ expect(transparencySlider?.getAttribute('aria-valuenow')).toBe('65');
+ expect(renderManagerService.scene.image.opacity).toBe(1);
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: drawing.drawingId,
+ }) as ISheetImage | undefined)?.opacity).toBeUndefined();
+
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 60));
+ });
+
+ expect(renderManagerService.scene.image.opacity).toBe(0.35);
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: drawing.drawingId,
+ }) as ISheetImage | undefined)?.opacity).toBeUndefined();
+
+ await act(async () => {
+ window.dispatchEvent(new MouseEvent('pointerup'));
+ await Promise.resolve();
+ });
+
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: drawing.drawingId,
+ }) as ISheetImage | undefined)?.opacity).toBe(0.35);
+ expect(transparencyInput?.value).toBe('65%');
+ expect(transparencySlider?.getAttribute('aria-valuenow')).toBe('65');
+
+ let commandResult = false;
+ await act(async () => {
+ commandResult = await currentTestBed!.commandService.executeCommand(UndoCommand.id);
+ await Promise.resolve();
+ });
+ expect(commandResult).toBe(true);
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: drawing.drawingId,
+ }) as ISheetImage | undefined)?.opacity).toBeUndefined();
+ expect(transparencyInput?.value).toBe('0%');
+ expect(transparencySlider?.getAttribute('aria-valuenow')).toBe('0');
+
+ await act(async () => {
+ commandResult = await currentTestBed!.commandService.executeCommand(RedoCommand.id);
+ await Promise.resolve();
+ });
+ expect(commandResult).toBe(true);
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: drawing.drawingId,
+ }) as ISheetImage | undefined)?.opacity).toBe(0.35);
+ expect(transparencyInput?.value).toBe('65%');
+ expect(transparencySlider?.getAttribute('aria-valuenow')).toBe('65');
+
+ const presetButton = transparencyInput?.parentElement?.parentElement?.querySelector<HTMLButtonElement>('button');
+ await act(async () => {
+ presetButton?.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+ const preset80 = Array.from(document.body.querySelectorAll<HTMLElement>('[role="menuitemradio"]'))
+ .find((item) => item.textContent?.trim() === '80%');
+ expect(preset80).toBeDefined();
+
+ await act(async () => {
+ preset80!.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+ expect((sheetDrawingService.getDrawingByParam({
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ drawingId: drawing.drawingId,
+ }) as ISheetImage | undefined)?.opacity).toBe(0.2);
+ expect(transparencyInput?.value).toBe('80%');
+ expect(transparencySlider?.getAttribute('aria-valuenow')).toBe('80');
+ });
});
diff --git a/packages/sheets-drawing-ui/src/views/sheet-image-panel/sheet-drawing-panel.util.ts b/packages/sheets-drawing-ui/src/views/sheet-image-panel/sheet-drawing-panel.util.ts
new file mode 100644
index 0000000000..a57e694e66
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/sheet-image-panel/sheet-drawing-panel.util.ts
@@ -0,0 +1,22 @@
+/**
+ * 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 { IDrawingParam } from '@univerjs/core';
+import type { ISheetDrawing } from '@univerjs/sheets-drawing';
+
+export function isSheetDrawing(drawing: IDrawingParam | undefined): drawing is ISheetDrawing {
+ return Boolean(drawing && 'sheetTransform' in drawing && 'axisAlignSheetTransform' in drawing);
+}
diff --git a/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts
index 33964169ea..11de32d31f 100644
--- a/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts
+++ b/packages/sheets-drawing/src/facade/__tests__/f-over-grid-image.spec.ts
@@ -83,6 +83,11 @@ describe('FOverGridImage', () => {
expect(builder.getSource()).toBe('https://example.com/drawing-1.png');
expect(builder.getSourceType()).toBe(ImageSourceType.URL);
+ expect(builder.getOpacity()).toBe(1);
+ expect(builder.setOpacity(0.4)).toBe(builder);
+ expect(builder.getOpacity()).toBe(0.4);
+ expect(() => builder.setOpacity(Number.NaN)).toThrow(RangeError);
+ expect(() => builder.setOpacity(1.01)).toThrow(RangeError);
expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining('FOverGridImageBuilder but get 0'));
warnSpy.mockRestore();
@@ -96,6 +101,14 @@ describe('FOverGridImage', () => {
const fImage = injector.createInstance(FOverGridImage, image);
+ expect(fImage.getOpacity()).toBe(1);
+ expect(fImage.setOpacity(0)).toBe(true);
+ expect(fImage.getOpacity()).toBe(0);
+ expect(fImage.setOpacity(1)).toBe(true);
+ expect(getStoredImage('drawing-1').opacity).toBe(1);
+ expect(() => fImage.setOpacity(Number.POSITIVE_INFINITY)).toThrow(RangeError);
+ expect(() => fImage.setOpacity(-0.01)).toThrow(RangeError);
+
expect(fImage.setSource('https://example.com/updated.png', ImageSourceType.URL)).toBe(true);
expect(getStoredImage('drawing-1').source).toBe('https://example.com/updated.png');
diff --git a/packages/sheets-drawing/src/facade/f-over-grid-image.ts b/packages/sheets-drawing/src/facade/f-over-grid-image.ts
index b789563346..efe8540bb8 100644
--- a/packages/sheets-drawing/src/facade/f-over-grid-image.ts
+++ b/packages/sheets-drawing/src/facade/f-over-grid-image.ts
@@ -316,6 +316,25 @@ export class FOverGridImageBuilder {
return this._image.imageSourceType;
}
+ /**
+ * Set the whole-image opacity from zero (transparent) through one (opaque).
+ * @param {number} opacity The opacity from 0 through 1.
+ * @returns {FOverGridImageBuilder} This builder.
+ */
+ setOpacity(opacity: number): FOverGridImageBuilder {
+ validateImageOpacity(opacity);
+ this._image.opacity = opacity;
+ return this;
+ }
+
+ /**
+ * Get the configured whole-image opacity.
+ * @returns {number} The opacity from 0 (transparent) through 1 (opaque).
+ */
+ getOpacity(): number {
+ return this._image.opacity ?? 1;
+ }
+
/**
* Set the horizontal position of the image
* @param {number} column - The column index of the image start position, start at 0
@@ -902,6 +921,38 @@ export class FOverGridImage extends FBase {
return getSheetDrawingPlacement(current ?? this._image);
}
+ /**
+ * Get the current whole-image opacity.
+ * @returns {number} The opacity from 0 (transparent) through 1 (opaque).
+ */
+ getOpacity(): number {
+ const current = this._sheetDrawingService.getDrawingByParam({
+ unitId: this._image.unitId,
+ subUnitId: this._image.subUnitId,
+ drawingId: this._image.drawingId,
+ }) as ISheetImage | undefined;
+
+ return current?.opacity ?? this._image.opacity ?? 1;
+ }
+
+ /**
+ * Set the whole-image opacity from zero (transparent) through one (opaque).
+ * @param {number} opacity The opacity from 0 through 1.
+ * @returns {boolean} Whether the update succeeded.
+ */
+ setOpacity(opacity: number): boolean {
+ validateImageOpacity(opacity);
+ return this._commandService.syncExecuteCommand(SetSheetDrawingCommand.id, {
+ unitId: this._image.unitId,
+ drawings: [{
+ unitId: this._image.unitId,
+ subUnitId: this._image.subUnitId,
+ drawingId: this._image.drawingId,
+ opacity,
+ }],
+ });
+ }
+
/**
* Set this image's explicit placement through the drawing command.
* `Position`, `Both`, and `None` correspond to OneCell, TwoCell, and
@@ -1269,3 +1320,9 @@ export class FOverGridImage extends FBase {
});
}
}
+
+function validateImageOpacity(opacity: number): void {
+ if (!Number.isFinite(opacity) || opacity < 0 || opacity > 1) {
+ throw new RangeError('Sheet image opacity must be between 0 and 1.');
+ }
+}