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): support worksheet background images (#7714)

wpxp123456279c049cde00
diff --git a/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts b/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts
index 8bf90b2b1b..67d285a279 100644
--- a/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts
+++ b/packages/core/src/sheets/__tests__/clone-worksheet-data.spec.ts
@@ -16,6 +16,7 @@
import type { IWorksheetData } from '../typedef';
import { describe, expect, it } from 'vitest';
+import { ImageSourceType } from '../../services/image-io/image-io.service';
import { Tools } from '../../shared/tools';
import { BooleanNumber } from '../../types/enum';
import { cloneWorksheetData } from '../clone';
@@ -86,6 +87,10 @@ function createTestWorksheetData(rowCount: number, colCount: number): IWorksheet
hidden: BooleanNumber.FALSE,
},
showGridlines: BooleanNumber.TRUE,
+ backgroundImage: {
+ source: 'data:image/png;base64,background',
+ imageSourceType: ImageSourceType.BASE64,
+ },
rightToLeft: BooleanNumber.FALSE,
};
}
@@ -117,6 +122,8 @@ describe('cloneWorksheetData', () => {
expect(cloned).not.toHaveProperty('visibility');
expect(cloned.rowCount).toBe(original.rowCount);
expect(cloned.columnCount).toBe(original.columnCount);
+ expect(cloned.backgroundImage).toEqual(original.backgroundImage);
+ expect(cloned.backgroundImage).not.toBe(original.backgroundImage);
// Verify freeze is deeply cloned
expect(cloned.freeze).toEqual(original.freeze);
diff --git a/packages/core/src/sheets/clone.ts b/packages/core/src/sheets/clone.ts
index b446f259ab..b47de89b80 100644
--- a/packages/core/src/sheets/clone.ts
+++ b/packages/core/src/sheets/clone.ts
@@ -293,6 +293,12 @@ export function cloneWorksheetData(worksheet: IWorksheetData): IWorksheetData {
defaultRowHeight: worksheet.defaultRowHeight,
showGridlines: worksheet.showGridlines,
rightToLeft: worksheet.rightToLeft,
+ backgroundImage: worksheet.backgroundImage
+ ? {
+ source: worksheet.backgroundImage.source,
+ imageSourceType: worksheet.backgroundImage.imageSourceType,
+ }
+ : undefined,
// Freeze - simple object with primitive values
freeze: {
diff --git a/packages/core/src/sheets/typedef.ts b/packages/core/src/sheets/typedef.ts
index 7e947c676e..871c10a540 100644
--- a/packages/core/src/sheets/typedef.ts
+++ b/packages/core/src/sheets/typedef.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import type { ImageSourceType } from '../services/image-io/image-io.service';
import type { IResources } from '../services/resource-manager/type';
import type { IObjectArrayPrimitiveType, IObjectMatrixPrimitiveType, Nullable } from '../shared';
import type { BooleanNumber } from '../types/enum';
@@ -99,6 +100,12 @@ export enum WorksheetHiddenState {
VERY_HIDDEN = 2,
}
+/** Image displayed behind the worksheet grid. */
+export interface IWorksheetBackgroundImage {
+ source: string;
+ imageSourceType: ImageSourceType;
+}
+
/**
* Snapshot of a worksheet.
*/
@@ -160,6 +167,9 @@ export interface IWorksheetData {
*/
gridlinesColor?: string;
+ /** Image tiled behind the worksheet grid. It is not included when printing. */
+ backgroundImage?: IWorksheetBackgroundImage;
+
rightToLeft: BooleanNumber;
/**
diff --git a/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts b/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts
index e94b61cc20..bdd63ca8bd 100644
--- a/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts
+++ b/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts
@@ -20,6 +20,7 @@ import { Rectangle } from '@univerjs/core';
import { ComponentExtension } from '../../extension';
export enum SHEET_EXTENSION_TYPE {
+ BACKGROUND,
GRID,
}
diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.ts
index 12506a1494..8cfd420866 100644
--- a/packages/engine-render/src/components/sheets/spreadsheet.ts
+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts
@@ -33,7 +33,7 @@ import { Canvas } from '../../canvas';
import { Documents } from '../docs/document';
import { SpreadsheetExtensionRegistry } from '../extension';
import { sheetContentViewportKeys, sheetHeaderViewportKeys } from './constants';
-import { SHEET_EXTENSION_PREFIX } from './extensions/sheet-extension';
+import { SHEET_EXTENSION_PREFIX, SHEET_EXTENSION_TYPE } from './extensions/sheet-extension';
import { SheetComponent } from './sheet-component';
const OBJECT_KEY = '__SHEET_EXTENSION_FONT_DOCUMENT_INSTANCE__';
@@ -344,7 +344,6 @@ export class Spreadsheet extends SheetComponent {
return;
}
const hasMergeData = spreadsheetSkeleton.worksheet.getMergeData().length > 0;
- this._drawAuxiliary(ctx, hasMergeData);
const parentScale = this.getParentScale();
const diffRanges = this._refreshIncrementalState && viewportInfo.diffBounds
@@ -363,13 +362,32 @@ export class Spreadsheet extends SheetComponent {
}))
: viewRanges;
const extensions = this.getExtensionsByOrder();
- const sparseExtensionFeatures = !isMergeRepair && hasSparseExtension(extensions)
+ const backgroundExtensions = extensions.filter((extension) => extension.type === SHEET_EXTENSION_TYPE.BACKGROUND);
+ const gridExtensions = extensions.filter((extension) => extension.type !== SHEET_EXTENSION_TYPE.BACKGROUND);
+ const sparseExtensionFeatures = !isMergeRepair && hasSparseExtension(gridExtensions)
? scanSparseExtensionFeatures(spreadsheetSkeleton, viewRanges)
: null;
// At this moment, ctx.transform is at topLeft of sheet content, cell(0, 0)
const scene = this.getScene();
- for (const extension of extensions) {
+ for (const extension of backgroundExtensions) {
+ const timeKey = `${SHEET_EXTENSION_PREFIX}${extension.uKey}`;
+ const st = Tools.now();
+ extension.draw(ctx, parentScale, spreadsheetSkeleton, diffRanges, {
+ viewRanges,
+ checkOutOfViewBound: true,
+ hasMergeData,
+ viewportKey: viewportInfo.viewportKey,
+ viewBound: viewportInfo.cacheBound,
+ diffBounds: viewportInfo.diffBounds,
+ } as IDrawInfo);
+ const cost = Tools.now() - st;
+ this.addRenderFrameTimeMetricToScene(timeKey, cost, scene);
+ }
+
+ this._drawAuxiliary(ctx, hasMergeData);
+
+ for (const extension of gridExtensions) {
if (shouldSkipSparseExtension(extension.uKey, sparseExtensionFeatures)) {
continue;
}
diff --git a/packages/sheets-drawing-ui/src/commands/commands/worksheet-background-image.command.ts b/packages/sheets-drawing-ui/src/commands/commands/worksheet-background-image.command.ts
new file mode 100644
index 0000000000..05f244deed
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/worksheet-background-image.command.ts
@@ -0,0 +1,50 @@
+/**
+ * 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 { ICommand, Nullable } from '@univerjs/core';
+import { CommandType, ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { getCurrentTypeOfRenderer, IRenderManagerService } from '@univerjs/engine-render';
+import { SetWorksheetBackgroundImageCommand } from '@univerjs/sheets-drawing';
+import { SheetDrawingUpdateController } from '../../controllers/sheet-drawing-update.controller';
+
+export interface IAddWorksheetBackgroundImageCommandParams {
+ files?: Nullable<File[]>;
+}
+
+export const AddWorksheetBackgroundImageCommand: ICommand<IAddWorksheetBackgroundImageCommandParams> = {
+ id: 'sheet.command.add-worksheet-background-image',
+ type: CommandType.COMMAND,
+ handler: (accessor, params) => {
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const renderManagerService = accessor.get(IRenderManagerService);
+
+ return getCurrentTypeOfRenderer(
+ UniverInstanceType.UNIVER_SHEET,
+ univerInstanceService,
+ renderManagerService
+ )
+ ?.with(SheetDrawingUpdateController)
+ .setWorksheetBackgroundImage(params?.files) ?? false;
+ },
+};
+
+export const DeleteWorksheetBackgroundImageCommand: ICommand = {
+ id: 'sheet.command.delete-worksheet-background-image',
+ type: CommandType.COMMAND,
+ handler: (accessor) => accessor.get(ICommandService).executeCommand(SetWorksheetBackgroundImageCommand.id, {
+ backgroundImage: null,
+ }),
+};
diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-update.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-update.controller.spec.ts
index 431a4c50ef..6139e028ec 100644
--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-update.controller.spec.ts
+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-update.controller.spec.ts
@@ -14,10 +14,10 @@
* limitations under the License.
*/
-import { DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS } from '@univerjs/core';
+import { DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, ImageSourceType } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { SetDrawingSelectedOperation } from '@univerjs/drawing';
-import { SetDrawingArrangeCommand, SetSheetDrawingCommand } from '@univerjs/sheets-drawing';
+import { SetDrawingArrangeCommand, SetSheetDrawingCommand, SetWorksheetBackgroundImageCommand } from '@univerjs/sheets-drawing';
import { Subject } from 'rxjs';
import { describe, expect, it, vi } from 'vitest';
import { GroupSheetDrawingCommand } from '../../commands/commands/group-sheet-drawing.command';
@@ -49,7 +49,7 @@ function createSkeleton() {
};
}
-function createController(options?: { openFiles?: unknown[] }) {
+function createController(options?: { imageParam?: unknown; openFiles?: unknown[] }) {
const featurePluginOrderUpdate$ = new Subject<any>();
const featurePluginUpdate$ = new Subject<any[]>();
const featurePluginGroupUpdate$ = new Subject<any[]>();
@@ -81,6 +81,10 @@ function createController(options?: { openFiles?: unknown[] }) {
getCurrentLastSelection: vi.fn(() => undefined),
})),
};
+ const imageIoService = {
+ saveImage: vi.fn(async () => options?.imageParam),
+ addImageSourceCache: vi.fn(),
+ };
const controller = new SheetDrawingUpdateController(
{
unitId: 'unit-1',
@@ -93,7 +97,7 @@ function createController(options?: { openFiles?: unknown[] }) {
commandService as never,
{ interceptAfterCommand: vi.fn(() => ({ dispose: vi.fn() })) } as never,
{ getCellWithCoordByOffset: vi.fn() } as never,
- { saveImage: vi.fn(), addImageSourceCache: vi.fn() } as never,
+ imageIoService as never,
{ openFile: vi.fn(async () => options?.openFiles ?? []) } as never,
sheetDrawingService as never,
{
@@ -118,6 +122,7 @@ function createController(options?: { openFiles?: unknown[] }) {
return {
controller,
commandService,
+ imageIoService,
sheetDrawingService,
featurePluginOrderUpdate$,
featurePluginUpdate$,
@@ -128,6 +133,29 @@ function createController(options?: { openFiles?: unknown[] }) {
}
describe('SheetDrawingUpdateController', () => {
+ it('uploads and sets a worksheet background image', async () => {
+ const file = { name: 'background.png' };
+ const imageParam = {
+ source: 'data:image/png;base64,background',
+ imageSourceType: ImageSourceType.BASE64,
+ };
+ const { controller, commandService, imageIoService } = createController({
+ openFiles: [file],
+ imageParam,
+ });
+ commandService.executeCommand.mockResolvedValue(true);
+
+ await expect(controller.setWorksheetBackgroundImage()).resolves.toBe(true);
+ expect(imageIoService.saveImage).toHaveBeenCalledWith(file);
+ expect(commandService.executeCommand).toHaveBeenCalledWith(SetWorksheetBackgroundImageCommand.id, {
+ unitId: 'unit-1',
+ subUnitId: 'sheet-1',
+ backgroundImage: imageParam,
+ });
+
+ controller.dispose();
+ });
+
it('reports empty and over-limit file selections without inserting images', async () => {
const empty = createController({ openFiles: [] });
diff --git a/packages/sheets-drawing-ui/src/controllers/render-controllers/worksheet-background.render-controller.ts b/packages/sheets-drawing-ui/src/controllers/render-controllers/worksheet-background.render-controller.ts
new file mode 100644
index 0000000000..a78e690395
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/controllers/render-controllers/worksheet-background.render-controller.ts
@@ -0,0 +1,48 @@
+/**
+ * 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 { IRenderContext, IRenderModule, Spreadsheet } from '@univerjs/engine-render';
+import type { ISetWorksheetBackgroundImageMutationParams } from '@univerjs/sheets-drawing';
+import { Disposable, ICommandService, Inject, Injector } from '@univerjs/core';
+import { SetWorksheetBackgroundImageMutation } from '@univerjs/sheets-drawing';
+import { WorksheetBackgroundImageExtension } from '../../views/background/worksheet-background-image.extension';
+
+export class WorksheetBackgroundRenderController extends Disposable implements IRenderModule {
+ constructor(
+ private readonly _context: IRenderContext,
+ @ICommandService commandService: ICommandService,
+ @Inject(Injector) injector: Injector
+ ) {
+ super();
+
+ const spreadsheet = this._context.mainComponent as Spreadsheet;
+ const extension = new WorksheetBackgroundImageExtension(injector, () => {
+ spreadsheet.makeForceDirty(true);
+ this._context.scene.makeDirty();
+ });
+ this.disposeWithMe(spreadsheet.register(extension));
+ this.disposeWithMe(commandService.onCommandExecuted((command) => {
+ const params = command.params as Partial<ISetWorksheetBackgroundImageMutationParams> | undefined;
+ if (
+ command.id === SetWorksheetBackgroundImageMutation.id &&
+ params?.unitId === this._context.unitId
+ ) {
+ spreadsheet.makeForceDirty(true);
+ this._context.scene.makeDirty();
+ }
+ }));
+ }
+}
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
index fd06c2598b..84ce01ba35 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-update.controller.ts
@@ -72,6 +72,7 @@ import {
ISheetDrawingService,
SetDrawingArrangeCommand,
SetSheetDrawingCommand,
+ SetWorksheetBackgroundImageCommand,
transformToAxisAlignPosition,
transformToDrawingPosition,
} from '@univerjs/sheets-drawing';
@@ -199,6 +200,55 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
return false;
}
+ async setWorksheetBackgroundImage(files?: Nullable<File[]>): Promise<boolean> {
+ const selectedFiles = files ?? await this._fileOpenerService.openFile({
+ multiple: false,
+ accept: DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','),
+ });
+ const file = selectedFiles[0];
+ if (!file) {
+ return false;
+ }
+
+ let imageParam: Nullable<IImageIoServiceParam>;
+ try {
+ imageParam = await this._imageIoService.saveImage(file);
+ } catch (error) {
+ const type = (error as Error).message;
+ if (type === ImageUploadStatusType.ERROR_EXCEED_SIZE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t<LocaleKey>('sheets-drawing-ui.update-status.exceedMaxSize', String(getDrawingImageAllowSize() / (1024 * 1024))),
+ });
+ } else if (type === ImageUploadStatusType.ERROR_IMAGE_TYPE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t<LocaleKey>('sheets-drawing-ui.update-status.invalidImageType'),
+ });
+ } else if (type === ImageUploadStatusType.ERROR_IMAGE) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t<LocaleKey>('sheets-drawing-ui.update-status.invalidImage'),
+ });
+ }
+ return false;
+ }
+
+ if (!imageParam) {
+ return false;
+ }
+
+ const { unitId, subUnitId } = this._getUnitInfo();
+ return this._commandService.executeCommand(SetWorksheetBackgroundImageCommand.id, {
+ unitId,
+ subUnitId,
+ backgroundImage: {
+ source: imageParam.source,
+ imageSourceType: imageParam.imageSourceType,
+ },
+ });
+ }
+
insertCellImageByFile(file: File, location?: ISheetLocationBase) {
return this._insertCellImage(file, location);
}
diff --git a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts b/packages/sheets-drawing-ui/src/controllers/ui.controller.ts
index e9c6513602..0cfe2a654e 100644
--- a/packages/sheets-drawing-ui/src/controllers/ui.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/ui.controller.ts
@@ -24,6 +24,10 @@ import { InsertCellImageCommand, InsertFloatImageCommand } from '../commands/com
import { MoveDrawingsCommand } from '../commands/commands/move-drawings.command';
import { SaveCellImagesCommand } from '../commands/commands/save-cell-images.command';
import { UngroupSheetDrawingCommand } from '../commands/commands/ungroup-sheet-drawing.command';
+import {
+ AddWorksheetBackgroundImageCommand,
+ DeleteWorksheetBackgroundImageCommand,
+} 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 { COMPONENT_SHEET_DRAWING_PANEL } from '../views/sheet-image-panel/component-name';
@@ -54,6 +58,8 @@ export class SheetDrawingUIController extends Disposable {
[
InsertFloatImageCommand,
InsertCellImageCommand,
+ AddWorksheetBackgroundImageCommand,
+ DeleteWorksheetBackgroundImageCommand,
SidebarSheetDrawingOperation,
EditSheetDrawingOperation,
GroupSheetDrawingCommand,
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
index 2380cfd3f5..149674e7a6 100644
--- a/packages/sheets-drawing-ui/src/index.ts
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -23,6 +23,11 @@ export type { IInsertImageCommandParams } from './commands/commands/insert-image
export { MoveDrawingsCommand } from './commands/commands/move-drawings.command';
export { SaveCellImagesCommand } from './commands/commands/save-cell-images.command';
export { UngroupSheetDrawingCommand } from './commands/commands/ungroup-sheet-drawing.command';
+export {
+ AddWorksheetBackgroundImageCommand,
+ DeleteWorksheetBackgroundImageCommand,
+} from './commands/commands/worksheet-background-image.command';
+export type { IAddWorksheetBackgroundImageCommandParams } from './commands/commands/worksheet-background-image.command';
export { EditSheetDrawingOperation } from './commands/operations/edit-sheet-drawing.operation';
export { SidebarSheetDrawingOperation } from './commands/operations/open-drawing-panel.operation';
export type { IUniverSheetsDrawingUIConfig } from './config/config';
diff --git a/packages/sheets-drawing-ui/src/locale/ar-SA.ts b/packages/sheets-drawing-ui/src/locale/ar-SA.ts
index 90bee333b4..131cc6b4f7 100644
--- a/packages/sheets-drawing-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-drawing-ui/src/locale/ar-SA.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'صورة',
+ backgroundImage: {
+ title: 'صورة الخلفية',
+ add: 'إضافة صورة خلفية',
+ delete: 'حذف صورة الخلفية',
+ },
uploadLoading: {
loading: 'جارٍ التحميل..., المتبقي',
},
diff --git a/packages/sheets-drawing-ui/src/locale/ca-ES.ts b/packages/sheets-drawing-ui/src/locale/ca-ES.ts
index 8a05641cb8..4750d20483 100644
--- a/packages/sheets-drawing-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-drawing-ui/src/locale/ca-ES.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Imatge',
+ backgroundImage: {
+ title: 'Imatge de fons',
+ add: 'Afegeix una imatge de fons',
+ delete: 'Suprimeix la imatge de fons',
+ },
uploadLoading: {
loading: 'S\'està carregant..., restant',
},
diff --git a/packages/sheets-drawing-ui/src/locale/de-DE.ts b/packages/sheets-drawing-ui/src/locale/de-DE.ts
index 352a404245..950f30ca9d 100644
--- a/packages/sheets-drawing-ui/src/locale/de-DE.ts
+++ b/packages/sheets-drawing-ui/src/locale/de-DE.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Bild',
+ backgroundImage: {
+ title: 'Hintergrundbild',
+ add: 'Hintergrundbild hinzufügen',
+ delete: 'Hintergrundbild löschen',
+ },
uploadLoading: {
loading: 'Wird geladen..., verbleibend',
},
diff --git a/packages/sheets-drawing-ui/src/locale/en-US.ts b/packages/sheets-drawing-ui/src/locale/en-US.ts
index bcaac81c32..623c0cb283 100644
--- a/packages/sheets-drawing-ui/src/locale/en-US.ts
+++ b/packages/sheets-drawing-ui/src/locale/en-US.ts
@@ -17,6 +17,11 @@
const locale = {
'sheets-drawing-ui': {
title: 'Image',
+ backgroundImage: {
+ title: 'Background Image',
+ add: 'Add Background Image',
+ delete: 'Delete Background Image',
+ },
uploadLoading: {
loading: 'Loading..., remaining',
},
diff --git a/packages/sheets-drawing-ui/src/locale/es-ES.ts b/packages/sheets-drawing-ui/src/locale/es-ES.ts
index 81c935b425..d17729c1f7 100644
--- a/packages/sheets-drawing-ui/src/locale/es-ES.ts
+++ b/packages/sheets-drawing-ui/src/locale/es-ES.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Imagen',
+ backgroundImage: {
+ title: 'Imagen de fondo',
+ add: 'Añadir imagen de fondo',
+ delete: 'Eliminar imagen de fondo',
+ },
uploadLoading: {
loading: 'Cargando..., restante',
},
diff --git a/packages/sheets-drawing-ui/src/locale/fa-IR.ts b/packages/sheets-drawing-ui/src/locale/fa-IR.ts
index 88d2dad461..bc6ed900d5 100644
--- a/packages/sheets-drawing-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-drawing-ui/src/locale/fa-IR.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'تصویر',
+ backgroundImage: {
+ title: 'تصویر پس‌زمینه',
+ add: 'افزودن تصویر پس‌زمینه',
+ delete: 'حذف تصویر پس‌زمینه',
+ },
uploadLoading: {
loading: 'در حال بارگیری...، باقی مانده',
},
diff --git a/packages/sheets-drawing-ui/src/locale/fr-FR.ts b/packages/sheets-drawing-ui/src/locale/fr-FR.ts
index 4554e483b2..41df4f91f6 100644
--- a/packages/sheets-drawing-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-drawing-ui/src/locale/fr-FR.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Image',
+ backgroundImage: {
+ title: 'Image d’arrière-plan',
+ add: 'Ajouter une image d’arrière-plan',
+ delete: 'Supprimer l’image d’arrière-plan',
+ },
uploadLoading: {
loading: 'Chargement..., restant',
},
diff --git a/packages/sheets-drawing-ui/src/locale/id-ID.ts b/packages/sheets-drawing-ui/src/locale/id-ID.ts
index 54b66ac113..6bf48ff747 100644
--- a/packages/sheets-drawing-ui/src/locale/id-ID.ts
+++ b/packages/sheets-drawing-ui/src/locale/id-ID.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Gambar',
+ backgroundImage: {
+ title: 'Gambar Latar Belakang',
+ add: 'Tambahkan Gambar Latar Belakang',
+ delete: 'Hapus Gambar Latar Belakang',
+ },
uploadLoading: {
loading: 'Memuat..., tersisa',
},
diff --git a/packages/sheets-drawing-ui/src/locale/it-IT.ts b/packages/sheets-drawing-ui/src/locale/it-IT.ts
index f2c9bafe10..8a7cbd79ed 100644
--- a/packages/sheets-drawing-ui/src/locale/it-IT.ts
+++ b/packages/sheets-drawing-ui/src/locale/it-IT.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Immagine',
+ backgroundImage: {
+ title: 'Immagine di sfondo',
+ add: 'Aggiungi immagine di sfondo',
+ delete: 'Elimina immagine di sfondo',
+ },
uploadLoading: {
loading: 'Caricamento..., rimanente',
},
diff --git a/packages/sheets-drawing-ui/src/locale/ja-JP.ts b/packages/sheets-drawing-ui/src/locale/ja-JP.ts
index 1c1f7fdd6d..0e972fc286 100644
--- a/packages/sheets-drawing-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-drawing-ui/src/locale/ja-JP.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: '画像',
+ backgroundImage: {
+ title: '背景画像',
+ add: '背景画像を追加',
+ delete: '背景画像を削除',
+ },
uploadLoading: {
loading: '読み込み中...',
},
diff --git a/packages/sheets-drawing-ui/src/locale/ko-KR.ts b/packages/sheets-drawing-ui/src/locale/ko-KR.ts
index 44b1ece32f..5a2d2307b8 100644
--- a/packages/sheets-drawing-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-drawing-ui/src/locale/ko-KR.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: '이미지',
+ backgroundImage: {
+ title: '배경 이미지',
+ add: '배경 이미지 추가',
+ delete: '배경 이미지 삭제',
+ },
uploadLoading: {
loading: '로딩중...',
},
diff --git a/packages/sheets-drawing-ui/src/locale/pl-PL.ts b/packages/sheets-drawing-ui/src/locale/pl-PL.ts
index d364b34ef8..dacc16d813 100644
--- a/packages/sheets-drawing-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-drawing-ui/src/locale/pl-PL.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Obraz',
+ backgroundImage: {
+ title: 'Obraz tła',
+ add: 'Dodaj obraz tła',
+ delete: 'Usuń obraz tła',
+ },
uploadLoading: {
loading: 'Ładowanie..., pozostało',
},
diff --git a/packages/sheets-drawing-ui/src/locale/pt-BR.ts b/packages/sheets-drawing-ui/src/locale/pt-BR.ts
index 39a2c98635..c4c77ea76a 100644
--- a/packages/sheets-drawing-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-drawing-ui/src/locale/pt-BR.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Imagem',
+ backgroundImage: {
+ title: 'Imagem de fundo',
+ add: 'Adicionar imagem de fundo',
+ delete: 'Excluir imagem de fundo',
+ },
uploadLoading: {
loading: 'Carregando..., restante',
},
diff --git a/packages/sheets-drawing-ui/src/locale/ru-RU.ts b/packages/sheets-drawing-ui/src/locale/ru-RU.ts
index 280219b9b5..52de1edccc 100644
--- a/packages/sheets-drawing-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-drawing-ui/src/locale/ru-RU.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Изображение',
+ backgroundImage: {
+ title: 'Фоновое изображение',
+ add: 'Добавить фоновое изображение',
+ delete: 'Удалить фоновое изображение',
+ },
uploadLoading: {
loading: 'Загрузка...',
},
diff --git a/packages/sheets-drawing-ui/src/locale/sk-SK.ts b/packages/sheets-drawing-ui/src/locale/sk-SK.ts
index 6daa29a5f9..df72c3b894 100644
--- a/packages/sheets-drawing-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-drawing-ui/src/locale/sk-SK.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Obrázok',
+ backgroundImage: {
+ title: 'Obrázok pozadia',
+ add: 'Pridať obrázok pozadia',
+ delete: 'Odstrániť obrázok pozadia',
+ },
uploadLoading: {
loading: 'Načítava sa..., zostáva',
},
diff --git a/packages/sheets-drawing-ui/src/locale/vi-VN.ts b/packages/sheets-drawing-ui/src/locale/vi-VN.ts
index e001ac667a..9c588ce910 100644
--- a/packages/sheets-drawing-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-drawing-ui/src/locale/vi-VN.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: 'Hình ảnh',
+ backgroundImage: {
+ title: 'Hình nền',
+ add: 'Thêm hình nền',
+ delete: 'Xóa hình nền',
+ },
uploadLoading: {
loading: 'Đang tải lên, hiện còn lại',
},
diff --git a/packages/sheets-drawing-ui/src/locale/zh-CN.ts b/packages/sheets-drawing-ui/src/locale/zh-CN.ts
index ab02ac5c94..834b887f9a 100644
--- a/packages/sheets-drawing-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-drawing-ui/src/locale/zh-CN.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: '图片',
+ backgroundImage: {
+ title: '背景图片',
+ add: '添加背景图片',
+ delete: '删除背景图片',
+ },
uploadLoading: {
loading: '正在上传,当前剩余',
},
diff --git a/packages/sheets-drawing-ui/src/locale/zh-HK.ts b/packages/sheets-drawing-ui/src/locale/zh-HK.ts
index 50b0c9da39..4adb34bca5 100644
--- a/packages/sheets-drawing-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-drawing-ui/src/locale/zh-HK.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: '圖片',
+ backgroundImage: {
+ title: '背景圖片',
+ add: '新增背景圖片',
+ delete: '刪除背景圖片',
+ },
uploadLoading: {
loading: '正在上傳,目前剩餘',
},
diff --git a/packages/sheets-drawing-ui/src/locale/zh-TW.ts b/packages/sheets-drawing-ui/src/locale/zh-TW.ts
index 50b0c9da39..4adb34bca5 100644
--- a/packages/sheets-drawing-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-drawing-ui/src/locale/zh-TW.ts
@@ -19,6 +19,11 @@ import type enUS from './en-US';
const locale: typeof enUS = {
'sheets-drawing-ui': {
title: '圖片',
+ backgroundImage: {
+ title: '背景圖片',
+ add: '新增背景圖片',
+ delete: '刪除背景圖片',
+ },
uploadLoading: {
loading: '正在上傳,目前剩餘',
},
diff --git a/packages/sheets-drawing-ui/src/menu/mobile-schema.ts b/packages/sheets-drawing-ui/src/menu/mobile-schema.ts
index 7e98334960..50a31ac9c9 100644
--- a/packages/sheets-drawing-ui/src/menu/mobile-schema.ts
+++ b/packages/sheets-drawing-ui/src/menu/mobile-schema.ts
@@ -15,11 +15,21 @@
*/
import type { MenuSchemaType } from '@univerjs/ui';
-import { ContextMenuGroup, ContextMenuPosition, RibbonInsertGroup } from '@univerjs/ui';
+import { ContextMenuGroup, ContextMenuPosition, RibbonDataGroup, RibbonInsertGroup } from '@univerjs/ui';
import { InsertCellImageCommand, InsertFloatImageCommand } from '../commands/commands/insert-image.command';
import { SaveCellImagesCommand } from '../commands/commands/save-cell-images.command';
+import {
+ AddWorksheetBackgroundImageCommand,
+ DeleteWorksheetBackgroundImageCommand,
+} from '../commands/commands/worksheet-background-image.command';
import { ImageMenuFactory, SHEETS_IMAGE_MENU_ID, UploadCellImageMenuFactory, UploadFloatImageMenuFactory } from './image.menu';
import { SaveCellImagesMenuFactory } from './save-images.menu';
+import {
+ AddWorksheetBackgroundImageMenuFactory,
+ DeleteWorksheetBackgroundImageMenuFactory,
+ WORKSHEET_BACKGROUND_IMAGE_MENU_ID,
+ WorksheetBackgroundImageMenuFactory,
+} from './worksheet-background-image.menu';
export const mobileMenuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
@@ -36,6 +46,20 @@ export const mobileMenuSchema: MenuSchemaType = {
},
},
},
+ [RibbonDataGroup.ORGANIZATION]: {
+ [WORKSHEET_BACKGROUND_IMAGE_MENU_ID]: {
+ order: 22,
+ menuItemFactory: WorksheetBackgroundImageMenuFactory,
+ [AddWorksheetBackgroundImageCommand.id]: {
+ order: 0,
+ menuItemFactory: AddWorksheetBackgroundImageMenuFactory,
+ },
+ [DeleteWorksheetBackgroundImageCommand.id]: {
+ order: 1,
+ menuItemFactory: DeleteWorksheetBackgroundImageMenuFactory,
+ },
+ },
+ },
[ContextMenuPosition.MAIN_AREA]: {
[ContextMenuGroup.OTHERS]: {
[SaveCellImagesCommand.id]: {
diff --git a/packages/sheets-drawing-ui/src/menu/schema.ts b/packages/sheets-drawing-ui/src/menu/schema.ts
index b603b0c068..ffee0f6253 100644
--- a/packages/sheets-drawing-ui/src/menu/schema.ts
+++ b/packages/sheets-drawing-ui/src/menu/schema.ts
@@ -15,11 +15,27 @@
*/
import type { MenuSchemaType } from '@univerjs/ui';
-import { ContextMenuGroup, ContextMenuPosition, RibbonInsertGroup } from '@univerjs/ui';
+import {
+ ContextMenuGroup,
+ ContextMenuPosition,
+ RibbonInsertGroup,
+ RibbonPosition,
+ RibbonViewGroup,
+} from '@univerjs/ui';
import { InsertCellImageCommand, InsertFloatImageCommand } from '../commands/commands/insert-image.command';
import { SaveCellImagesCommand } from '../commands/commands/save-cell-images.command';
+import {
+ AddWorksheetBackgroundImageCommand,
+ DeleteWorksheetBackgroundImageCommand,
+} from '../commands/commands/worksheet-background-image.command';
import { ImageMenuFactory, SHEETS_IMAGE_MENU_ID, UploadCellImageMenuFactory, UploadFloatImageMenuFactory } from './image.menu';
import { SaveCellImagesMenuFactory } from './save-images.menu';
+import {
+ AddWorksheetBackgroundImageMenuFactory,
+ DeleteWorksheetBackgroundImageMenuFactory,
+ WORKSHEET_BACKGROUND_IMAGE_MENU_ID,
+ WorksheetBackgroundImageMenuFactory,
+} from './worksheet-background-image.menu';
export const menuSchema: MenuSchemaType = {
[RibbonInsertGroup.MEDIA]: {
@@ -37,6 +53,23 @@ export const menuSchema: MenuSchemaType = {
},
},
},
+ [RibbonPosition.VIEW]: {
+ [RibbonViewGroup.DISPLAY]: {
+ [WORKSHEET_BACKGROUND_IMAGE_MENU_ID]: {
+ order: 3,
+ gridLayout: { row: 1, column: 3, rowSpan: 2, showLabel: true },
+ menuItemFactory: WorksheetBackgroundImageMenuFactory,
+ [AddWorksheetBackgroundImageCommand.id]: {
+ order: 0,
+ menuItemFactory: AddWorksheetBackgroundImageMenuFactory,
+ },
+ [DeleteWorksheetBackgroundImageCommand.id]: {
+ order: 1,
+ menuItemFactory: DeleteWorksheetBackgroundImageMenuFactory,
+ },
+ },
+ },
+ },
[ContextMenuPosition.MAIN_AREA]: {
[ContextMenuGroup.OTHERS]: {
[SaveCellImagesCommand.id]: {
diff --git a/packages/sheets-drawing-ui/src/menu/worksheet-background-image.menu.ts b/packages/sheets-drawing-ui/src/menu/worksheet-background-image.menu.ts
new file mode 100644
index 0000000000..15512abc1d
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/menu/worksheet-background-image.menu.ts
@@ -0,0 +1,107 @@
+/**
+ * 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 { IAccessor, Workbook } from '@univerjs/core';
+import type { IMenuItem } from '@univerjs/ui';
+import type { LocaleKey } from '../locale/types';
+import {
+ DisposableCollection,
+ ICommandService,
+ IUniverInstanceService,
+ UniverInstanceType,
+} from '@univerjs/core';
+import {
+ SetWorksheetActiveOperation,
+ WorkbookEditablePermission,
+ WorksheetEditPermission,
+} from '@univerjs/sheets';
+import { SetWorksheetBackgroundImageMutation } from '@univerjs/sheets-drawing';
+import { getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
+import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
+import { combineLatest, map, Observable } from 'rxjs';
+import {
+ AddWorksheetBackgroundImageCommand,
+ DeleteWorksheetBackgroundImageCommand,
+} from '../commands/commands/worksheet-background-image.command';
+
+export const WORKSHEET_BACKGROUND_IMAGE_MENU_ID = 'sheet.menu.worksheet-background-image';
+
+function worksheetBackgroundImagePresent$(accessor: IAccessor): Observable<boolean> {
+ const commandService = accessor.get(ICommandService);
+ const instanceService = accessor.get(IUniverInstanceService);
+
+ return new Observable<boolean>((observer) => {
+ const getValue = () => {
+ const workbook = instanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ return !!workbook?.getActiveSheet().getConfig().backgroundImage;
+ };
+ const disposables = new DisposableCollection();
+ disposables.add(commandService.onCommandExecuted((command) => {
+ if (
+ command.id === SetWorksheetBackgroundImageMutation.id ||
+ command.id === SetWorksheetActiveOperation.id
+ ) {
+ observer.next(getValue());
+ }
+ }));
+ disposables.add(instanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe(() => {
+ observer.next(getValue());
+ }));
+ observer.next(getValue());
+ return () => disposables.dispose();
+ });
+}
+
+function worksheetBackgroundImagePermissionDisabled$(accessor: IAccessor) {
+ return getCurrentRangeDisable$(accessor, {
+ workbookTypes: [WorkbookEditablePermission],
+ worksheetTypes: [WorksheetEditPermission],
+ });
+}
+
+export function WorksheetBackgroundImageMenuFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
+ return {
+ id: WORKSHEET_BACKGROUND_IMAGE_MENU_ID,
+ type: MenuItemType.SUBITEMS,
+ icon: 'AddImageIcon',
+ tooltip: 'sheets-drawing-ui.backgroundImage.title',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ disabled$: worksheetBackgroundImagePermissionDisabled$(accessor),
+ };
+}
+
+export function AddWorksheetBackgroundImageMenuFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
+ return {
+ id: AddWorksheetBackgroundImageCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'sheets-drawing-ui.backgroundImage.add',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ disabled$: worksheetBackgroundImagePermissionDisabled$(accessor),
+ };
+}
+
+export function DeleteWorksheetBackgroundImageMenuFactory(accessor: IAccessor): IMenuItem<LocaleKey> {
+ const permissionDisabled$ = worksheetBackgroundImagePermissionDisabled$(accessor);
+ return {
+ id: DeleteWorksheetBackgroundImageCommand.id,
+ type: MenuItemType.BUTTON,
+ title: 'sheets-drawing-ui.backgroundImage.delete',
+ hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SHEET),
+ disabled$: combineLatest([permissionDisabled$, worksheetBackgroundImagePresent$(accessor)]).pipe(
+ map(([permissionDisabled, present]) => permissionDisabled || !present)
+ ),
+ };
+}
diff --git a/packages/sheets-drawing-ui/src/mobile-plugin.ts b/packages/sheets-drawing-ui/src/mobile-plugin.ts
index d3f047e8fe..d0caba4d5a 100644
--- a/packages/sheets-drawing-ui/src/mobile-plugin.ts
+++ b/packages/sheets-drawing-ui/src/mobile-plugin.ts
@@ -42,6 +42,7 @@ import { DrawingContextMenuController } from './controllers/drawing-context-menu
import { MobileComponentsController } from './controllers/mobile/components.controller';
import { SheetCellImageHoverRenderController } from './controllers/render-controllers/sheet-celll-image-hover.render-controller';
import { SheetsDrawingRenderController } from './controllers/render-controllers/sheet-drawing.render-controller';
+import { WorksheetBackgroundRenderController } from './controllers/render-controllers/worksheet-background.render-controller';
import { SheetCellImageAutofillController } from './controllers/sheet-cell-image-autofill.controller';
import { SheetCellImageCopyPasteController } from './controllers/sheet-cell-image-copy-paste.controller';
import { SheetCellImageController } from './controllers/sheet-cell-image.controller';
@@ -148,6 +149,7 @@ export class UniverSheetsDrawingMobileUIPlugin extends Plugin {
[SheetDrawingActiveRenderController],
[SheetsDrawingRenderController],
[SheetCellImageHoverRenderController],
+ [WorksheetBackgroundRenderController],
] as Dependency[]).forEach((module) => {
this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, module));
});
diff --git a/packages/sheets-drawing-ui/src/plugin.ts b/packages/sheets-drawing-ui/src/plugin.ts
index 339588fdc0..565667ea90 100644
--- a/packages/sheets-drawing-ui/src/plugin.ts
+++ b/packages/sheets-drawing-ui/src/plugin.ts
@@ -40,6 +40,7 @@ import { ComponentsController } from './controllers/components.controller';
import { DrawingContextMenuController } from './controllers/drawing-context-menu.controller';
import { SheetCellImageHoverRenderController } from './controllers/render-controllers/sheet-celll-image-hover.render-controller';
import { SheetsDrawingRenderController } from './controllers/render-controllers/sheet-drawing.render-controller';
+import { WorksheetBackgroundRenderController } from './controllers/render-controllers/worksheet-background.render-controller';
import { SheetCellImageAutofillController } from './controllers/sheet-cell-image-autofill.controller';
import { SheetCellImageCopyPasteController } from './controllers/sheet-cell-image-copy-paste.controller';
import { SheetCellImageController } from './controllers/sheet-cell-image.controller';
@@ -149,6 +150,7 @@ export class UniverSheetsDrawingUIPlugin extends Plugin {
[SheetDrawingActiveRenderController],
[SheetsDrawingRenderController],
[SheetCellImageHoverRenderController],
+ [WorksheetBackgroundRenderController],
] as Dependency[]).forEach((m) => {
this.disposeWithMe(this._renderManagerService.registerRenderModule(UniverInstanceType.UNIVER_SHEET, m));
});
diff --git a/packages/sheets-drawing-ui/src/views/background/worksheet-background-image.extension.ts b/packages/sheets-drawing-ui/src/views/background/worksheet-background-image.extension.ts
new file mode 100644
index 0000000000..304a570f98
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/views/background/worksheet-background-image.extension.ts
@@ -0,0 +1,81 @@
+/**
+ * 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 { Injector, IRange, IScale } from '@univerjs/core';
+import type { IDrawInfo, SpreadsheetSkeleton, UniverRenderingContext } from '@univerjs/engine-render';
+import { ImageCacheMap } from '@univerjs/core';
+import { SHEET_EXTENSION_TYPE, SheetExtension } from '@univerjs/engine-render';
+
+export const WORKSHEET_BACKGROUND_IMAGE_EXTENSION_KEY = 'WorksheetBackgroundImageExtension';
+
+export class WorksheetBackgroundImageExtension extends SheetExtension {
+ override uKey = WORKSHEET_BACKGROUND_IMAGE_EXTENSION_KEY;
+ override type = SHEET_EXTENSION_TYPE.BACKGROUND;
+
+ private readonly _imageCache: ImageCacheMap;
+
+ constructor(injector: Injector, private readonly _requestRender: () => void) {
+ super();
+ this._imageCache = new ImageCacheMap(injector);
+ }
+
+ override draw(
+ ctx: UniverRenderingContext,
+ _parentScale: IScale,
+ spreadsheetSkeleton: SpreadsheetSkeleton,
+ diffRanges: IRange[],
+ drawInfo: IDrawInfo
+ ): void {
+ const backgroundImage = spreadsheetSkeleton.worksheet.getConfig().backgroundImage;
+ if (!backgroundImage) {
+ return;
+ }
+
+ const image = this._imageCache.getImage(
+ backgroundImage.imageSourceType,
+ backgroundImage.source,
+ this._requestRender,
+ this._requestRender
+ );
+ if (!image || !image.complete || image.naturalWidth === 0 || image.getAttribute('data-error')) {
+ return;
+ }
+
+ const pattern = ctx.createPattern(image, 'repeat');
+ if (!pattern) {
+ return;
+ }
+
+ const ranges = diffRanges.length > 0 ? diffRanges : drawInfo.viewRanges;
+ const { columnWidthAccumulation, rowHeightAccumulation } = spreadsheetSkeleton;
+ if (!columnWidthAccumulation || !rowHeightAccumulation) {
+ return;
+ }
+
+ ctx.save();
+ ctx.fillStyle = pattern;
+ ranges.forEach((range) => {
+ const startX = range.startColumn > 0 ? columnWidthAccumulation[range.startColumn - 1] : 0;
+ const startY = range.startRow > 0 ? rowHeightAccumulation[range.startRow - 1] : 0;
+ const endX = columnWidthAccumulation[range.endColumn];
+ const endY = rowHeightAccumulation[range.endRow];
+ if (endX != null && endY != null) {
+ ctx.fillRect(startX, startY, endX - startX, endY - startY);
+ }
+ });
+ ctx.restore();
+ }
+}
diff --git a/packages/sheets-drawing/src/commands/commands/set-worksheet-background-image.command.ts b/packages/sheets-drawing/src/commands/commands/set-worksheet-background-image.command.ts
new file mode 100644
index 0000000000..845cb36f4f
--- /dev/null
+++ b/packages/sheets-drawing/src/commands/commands/set-worksheet-background-image.command.ts
@@ -0,0 +1,74 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, ICommand, IWorksheetBackgroundImage, Nullable } from '@univerjs/core';
+import type { ISetWorksheetBackgroundImageMutationParams } from '../mutations/set-worksheet-background-image.mutation';
+import { CommandType, ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+import { SetWorksheetBackgroundImageMutation } from '../mutations/set-worksheet-background-image.mutation';
+
+export interface ISetWorksheetBackgroundImageCommandParams {
+ unitId?: string;
+ subUnitId?: string;
+ backgroundImage: Nullable<IWorksheetBackgroundImage>;
+}
+
+export const SetWorksheetBackgroundImageCommand: ICommand<ISetWorksheetBackgroundImageCommandParams> = {
+ id: 'sheet.command.set-worksheet-background-image',
+ type: CommandType.COMMAND,
+ handler: (accessor: IAccessor, params) => {
+ if (!params) {
+ return false;
+ }
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), params);
+ if (!target) {
+ return false;
+ }
+
+ const { unitId, subUnitId, worksheet } = target;
+ const previous = worksheet.getConfig().backgroundImage;
+ const next = params.backgroundImage;
+ if (previous?.source === next?.source && previous?.imageSourceType === next?.imageSourceType) {
+ return false;
+ }
+
+ const commandService = accessor.get(ICommandService);
+ const undoRedoService = accessor.get(IUndoRedoService);
+ const redoParams: ISetWorksheetBackgroundImageMutationParams = {
+ unitId,
+ subUnitId,
+ backgroundImage: next ? { ...next } : null,
+ };
+ const undoParams: ISetWorksheetBackgroundImageMutationParams = {
+ unitId,
+ subUnitId,
+ backgroundImage: previous ? { ...previous } : null,
+ };
+
+ const result = commandService.syncExecuteCommand(SetWorksheetBackgroundImageMutation.id, redoParams);
+ if (!result) {
+ return false;
+ }
+
+ undoRedoService.pushUndoRedo({
+ unitID: unitId,
+ undoMutations: [{ id: SetWorksheetBackgroundImageMutation.id, params: undoParams }],
+ redoMutations: [{ id: SetWorksheetBackgroundImageMutation.id, params: redoParams }],
+ });
+
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing/src/commands/mutations/set-worksheet-background-image.mutation.ts b/packages/sheets-drawing/src/commands/mutations/set-worksheet-background-image.mutation.ts
new file mode 100644
index 0000000000..2c7c73ba36
--- /dev/null
+++ b/packages/sheets-drawing/src/commands/mutations/set-worksheet-background-image.mutation.ts
@@ -0,0 +1,45 @@
+/**
+ * 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 { IMutation, IWorksheetBackgroundImage, Nullable } from '@univerjs/core';
+import { CommandType, IUniverInstanceService } from '@univerjs/core';
+import { getSheetCommandTarget } from '@univerjs/sheets';
+
+export interface ISetWorksheetBackgroundImageMutationParams {
+ unitId: string;
+ subUnitId: string;
+ backgroundImage: Nullable<IWorksheetBackgroundImage>;
+}
+
+export const SetWorksheetBackgroundImageMutation: IMutation<ISetWorksheetBackgroundImageMutationParams> = {
+ id: 'sheet.mutation.set-worksheet-background-image',
+ type: CommandType.MUTATION,
+ handler: (accessor, params) => {
+ const target = getSheetCommandTarget(accessor.get(IUniverInstanceService), params);
+ if (!target) {
+ return false;
+ }
+
+ const config = target.worksheet.getConfig();
+ if (params.backgroundImage) {
+ config.backgroundImage = { ...params.backgroundImage };
+ } else {
+ delete config.backgroundImage;
+ }
+
+ return true;
+ },
+};
diff --git a/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts b/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts
index 08e29ea174..f0f7760935 100644
--- a/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts
+++ b/packages/sheets-drawing/src/controllers/sheet-drawing.controller.ts
@@ -26,7 +26,9 @@ import { RemoveSheetDrawingCommand } from '../commands/commands/remove-sheet-dra
import { SetDrawingArrangeCommand } from '../commands/commands/set-drawing-arrange.command';
import { SetSheetDrawingPlacementCommand } from '../commands/commands/set-sheet-drawing-placement.command';
import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.command';
+import { SetWorksheetBackgroundImageCommand } from '../commands/commands/set-worksheet-background-image.command';
import { DrawingApplyType, SetDrawingApplyMutation } from '../commands/mutations/set-drawing-apply.mutation';
+import { SetWorksheetBackgroundImageMutation } from '../commands/mutations/set-worksheet-background-image.mutation';
import { ClearSheetDrawingTransformerOperation } from '../commands/operations/clear-drawing-transformer.operation';
import { ISheetDrawingService } from '../services/sheet-drawing.service';
@@ -69,6 +71,7 @@ export class SheetsDrawingLoadController extends Disposable {
this._initSheetChange();
this.disposeWithMe(this._commandService.registerCommand(SetDrawingApplyMutation));
+ this.disposeWithMe(this._commandService.registerCommand(SetWorksheetBackgroundImageMutation));
}
private _initCommands() {
@@ -78,6 +81,7 @@ export class SheetsDrawingLoadController extends Disposable {
RemoveSheetDrawingCommand,
SetDrawingArrangeCommand,
SetSheetDrawingPlacementCommand,
+ SetWorksheetBackgroundImageCommand,
ClearSheetDrawingTransformerOperation,
].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));
}
diff --git a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
index 0e52fdaf14..c75a71cdf3 100644
--- a/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
+++ b/packages/sheets-drawing/src/facade/__tests__/f-worksheet.spec.ts
@@ -391,6 +391,34 @@ describe('FWorksheetDrawingMixin group drawings', () => {
});
});
+describe('FWorksheetDrawingMixin background image', () => {
+ let univer: Univer;
+ let injector: Injector;
+
+ beforeEach(() => {
+ const testBed = createSheetsDrawingTestBed();
+ univer = testBed.univer;
+ injector = testBed.injector;
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ it('sets, returns, and deletes the worksheet background image', () => {
+ const fWorksheet = createFacade(injector);
+
+ expect(fWorksheet.getBackgroundImage()).toBeNull();
+ expect(fWorksheet.setBackgroundImage('https://example.com/background.png')).toBe(fWorksheet);
+ expect(fWorksheet.getBackgroundImage()).toEqual({
+ source: 'https://example.com/background.png',
+ imageSourceType: ImageSourceType.URL,
+ });
+ expect(fWorksheet.deleteBackgroundImage()).toBe(fWorksheet);
+ expect(fWorksheet.getBackgroundImage()).toBeNull();
+ });
+});
+
function createFacade(injector: Injector): FWorksheetDrawingMixin {
const workbook = injector.get(IUniverInstanceService).getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
const worksheet = workbook.getSheetBySheetId('sheet1')!;
diff --git a/packages/sheets-drawing/src/facade/f-worksheet.ts b/packages/sheets-drawing/src/facade/f-worksheet.ts
index 72f806535f..97cb636f8f 100644
--- a/packages/sheets-drawing/src/facade/f-worksheet.ts
+++ b/packages/sheets-drawing/src/facade/f-worksheet.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { IDrawingParam, IGroupBaseBound } from '@univerjs/core';
+import type { IDrawingParam, IGroupBaseBound, IWorksheetBackgroundImage, Nullable } from '@univerjs/core';
import type { IFBlobSource } from '@univerjs/core/facade';
import type { IDrawingGroupUpdateParam, IDrawingJsonUndo1 } from '@univerjs/drawing';
import type { ISheetDrawing, ISheetDrawingPlacement, ISheetDrawingPlacementInput, ISheetImage } from '@univerjs/sheets-drawing';
@@ -22,7 +22,7 @@ import { DrawingTypeEnum, generateRandomId, ImageSourceType, IUndoRedoService }
import { isGroupableDrawingType } from '@univerjs/drawing';
import { getGroupState, transformObjectOutOfGroup } from '@univerjs/engine-render';
import { SheetSkeletonService } from '@univerjs/sheets';
-import { DrawingApplyType, getSheetDrawingPlacement, InsertSheetDrawingCommand, ISheetDrawingService, normalizeSheetDrawingPlacement, RemoveSheetDrawingCommand, SetDrawingApplyMutation, SetSheetDrawingCommand, SetSheetDrawingPlacementCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
+import { DrawingApplyType, getSheetDrawingPlacement, InsertSheetDrawingCommand, ISheetDrawingService, normalizeSheetDrawingPlacement, RemoveSheetDrawingCommand, SetDrawingApplyMutation, SetSheetDrawingCommand, SetSheetDrawingPlacementCommand, SetWorksheetBackgroundImageCommand, SheetDrawingAnchorType } from '@univerjs/sheets-drawing';
import { FWorksheet } from '@univerjs/sheets/facade';
import { FOverGridImage, FOverGridImageBuilder } from './f-over-grid-image';
@@ -47,6 +47,26 @@ export interface ISheetDrawingLayout {
* @ignore
*/
export interface IFWorksheetDrawingMixin {
+ /**
+ * Returns the image tiled behind the worksheet grid.
+ * @returns {IWorksheetBackgroundImage | null} The worksheet background image, or `null` when absent.
+ */
+ getBackgroundImage(): Nullable<IWorksheetBackgroundImage>;
+
+ /**
+ * Sets the image tiled behind the worksheet grid. Worksheet background images are not printed.
+ * @param {string} source Image source.
+ * @param {ImageSourceType} imageSourceType Image source type.
+ * @returns The current worksheet instance for chaining.
+ */
+ setBackgroundImage(source: string, imageSourceType?: ImageSourceType): this;
+
+ /**
+ * Deletes the image tiled behind the worksheet grid.
+ * @returns The current worksheet instance for chaining.
+ */
+ deleteBackgroundImage(): this;
+
/**
* Insert an image to the sheet
* @param {string} url - The image url
@@ -521,6 +541,29 @@ export class FWorksheetDrawingMixin extends FWorksheet implements IFWorksheetDra
return this._injector.get(IUndoRedoService);
}
+ override getBackgroundImage(): Nullable<IWorksheetBackgroundImage> {
+ const backgroundImage = this._worksheet.getConfig().backgroundImage;
+ return backgroundImage ? { ...backgroundImage } : null;
+ }
+
+ override setBackgroundImage(source: string, imageSourceType: ImageSourceType = ImageSourceType.URL): this {
+ this._commandService.syncExecuteCommand(SetWorksheetBackgroundImageCommand.id, {
+ unitId: this._fWorkbook.getId(),
+ subUnitId: this.getSheetId(),
+ backgroundImage: { source, imageSourceType },
+ });
+ return this;
+ }
+
+ override deleteBackgroundImage(): this {
+ this._commandService.syncExecuteCommand(SetWorksheetBackgroundImageCommand.id, {
+ unitId: this._fWorkbook.getId(),
+ subUnitId: this.getSheetId(),
+ backgroundImage: null,
+ });
+ return this;
+ }
+
override async insertImage(url: IFBlobSource | string, column?: number, row?: number, offsetX?: number, offsetY?: number): Promise<boolean> {
const imageBuilder = this.newOverGridImage();
if (typeof url === 'string') {
diff --git a/packages/sheets-drawing/src/index.ts b/packages/sheets-drawing/src/index.ts
index cda6c724e5..3cb0677fc9 100644
--- a/packages/sheets-drawing/src/index.ts
+++ b/packages/sheets-drawing/src/index.ts
@@ -29,8 +29,12 @@ export { SetSheetDrawingPlacementCommand } from './commands/commands/set-sheet-d
export type { ISetSheetDrawingPlacementCommandParams } from './commands/commands/set-sheet-drawing-placement.command';
export { SetSheetDrawingCommand } from './commands/commands/set-sheet-drawing.command';
export type { ISetDrawingCommandParams } from './commands/commands/set-sheet-drawing.command';
+export { SetWorksheetBackgroundImageCommand } from './commands/commands/set-worksheet-background-image.command';
+export type { ISetWorksheetBackgroundImageCommandParams } from './commands/commands/set-worksheet-background-image.command';
export { DrawingApplyType, SetDrawingApplyMutation } from './commands/mutations/set-drawing-apply.mutation';
export type { ISetDrawingApplyMutationParams } from './commands/mutations/set-drawing-apply.mutation';
+export { SetWorksheetBackgroundImageMutation } from './commands/mutations/set-worksheet-background-image.mutation';
+export type { ISetWorksheetBackgroundImageMutationParams } from './commands/mutations/set-worksheet-background-image.mutation';
export { ClearSheetDrawingTransformerOperation } from './commands/operations/clear-drawing-transformer.operation';
export { isKnownSheetNonRotatableDrawingType, resolveSheetDrawingRotateEnabled } from './common/rotate-enabled';
export type { IUniverSheetsDrawingConfig } from './config/config';