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): introduce URL image service to centralize URL image (#6434)

WEI ZHANGfc5ae911ac76
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index b4cb661e17..40c5cce8dd 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -104,7 +104,9 @@ export { IConfirmService, TestConfirmService } from './services/confirm/confirm.
export * from './services/context/context';
export { ContextService, IContextService } from './services/context/context.service';
export { ErrorService, type IError } from './services/error/error.service';
-export { IImageIoService, type IImageIoServiceParam, ImageSourceType, ImageUploadStatusType } from './services/image-io/image-io.service';
+export { IImageIoService, ImageSourceType, ImageUploadStatusType } from './services/image-io/image-io.service';
+export type { IImageIoServiceParam } from './services/image-io/image-io.service';
+export { IURLImageService } from './services/image-io/url-image.service';
export { type ICreateUnitOptions, IUniverInstanceService, UniverInstanceService } from './services/instance/instance.service';
export { LifecycleStages } from './services/lifecycle/lifecycle';
export { LifecycleService, LifecycleUnreachableError } from './services/lifecycle/lifecycle.service';
diff --git a/packages/core/src/services/image-io/url-image.service.ts b/packages/core/src/services/image-io/url-image.service.ts
new file mode 100644
index 0000000000..0fe11b882d
--- /dev/null
+++ b/packages/core/src/services/image-io/url-image.service.ts
@@ -0,0 +1,43 @@
+/**
+ * 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 { IDisposable } from '../../common/di';
+import { createIdentifier } from '../../common/di';
+
+export interface IURLImageService {
+ /**
+ * Get image url or base64.
+ * if there is a custom downloader, return the result of the downloader (usually base64).
+ * if there is no custom downloader, return the original url.
+ * @param url image url
+ */
+ getImage(url: string): Promise<string>;
+
+ /**
+ * Download image to blob
+ * @param url image url
+ */
+ downloadImage(url: string): Promise<Blob>;
+
+ /**
+ * Register a custom image downloader for URL images
+ * @param downloader The downloader function that takes a URL and returns a base64 string
+ * @returns A disposable object to unregister the downloader
+ */
+ registerURLImageDownloader(downloader: (url: string) => Promise<string>): IDisposable;
+}
+
+export const IURLImageService = createIdentifier<IURLImageService>('core.url-image.service');
diff --git a/packages/core/src/shared/cache/image-cache.ts b/packages/core/src/shared/cache/image-cache.ts
index b341cccde8..73beb93ecc 100644
--- a/packages/core/src/shared/cache/image-cache.ts
+++ b/packages/core/src/shared/cache/image-cache.ts
@@ -16,6 +16,7 @@
import type { Injector } from '@wendellhu/redi';
import { IImageIoService, ImageSourceType } from '../../services/image-io/image-io.service';
+import { IURLImageService } from '../../services/image-io/url-image.service';
import { LRUMap } from '../lru/lru-map';
export class ImageCacheMap {
@@ -41,6 +42,7 @@ export class ImageCacheMap {
(async () => {
const newImageElement = new Image();
const imageIoService = this._injector.has(IImageIoService) ? this._injector.get(IImageIoService) : null;
+ const urlImageService = this._injector.has(IURLImageService) ? this._injector.get(IURLImageService) : null;
if (imageSourceType === ImageSourceType.UUID) {
try {
@@ -48,6 +50,13 @@ export class ImageCacheMap {
} catch (error) {
console.error(error);
}
+ } else if (imageSourceType === ImageSourceType.URL) {
+ try {
+ const url = await urlImageService?.getImage(source);
+ newImageElement.src = url || source;
+ } catch (error) {
+ newImageElement.src = source;
+ }
} else {
newImageElement.src = source;
}
diff --git a/packages/drawing-ui/src/services/drawing-render.service.ts b/packages/drawing-ui/src/services/drawing-render.service.ts
index 8caedfa5ad..83a230d0ac 100644
--- a/packages/drawing-ui/src/services/drawing-render.service.ts
+++ b/packages/drawing-ui/src/services/drawing-render.service.ts
@@ -17,7 +17,7 @@
import type { IDrawingSearch } from '@univerjs/core';
import type { IDocFloatDomData, IImageData } from '@univerjs/drawing';
import type { IImageProps, IRectProps, Scene } from '@univerjs/engine-render';
-import { DrawingTypeEnum } from '@univerjs/core';
+import { DrawingTypeEnum, IURLImageService } from '@univerjs/core';
import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, IImageIoService, ImageSourceType } from '@univerjs/drawing';
import { DRAWING_OBJECT_LAYER_INDEX, Image, Rect } from '@univerjs/engine-render';
import { IGalleryService } from '@univerjs/ui';
@@ -29,7 +29,8 @@ export class DrawingRenderService {
constructor(
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
@IImageIoService private readonly _imageIoService: IImageIoService,
- @IGalleryService private readonly _galleryService: IGalleryService
+ @IGalleryService private readonly _galleryService: IGalleryService,
+ @IURLImageService private readonly _urlImageService: IURLImageService
) { }
// eslint-disable-next-line max-lines-per-function
@@ -90,10 +91,18 @@ export class DrawingRenderService {
console.error(error);
continue;
}
+ } else if (imageSourceType === ImageSourceType.URL) {
+ try {
+ imageConfig.url = await this._urlImageService.getImage(source);
+ } catch (error) {
+ console.error(error);
+ imageConfig.url = source;
+ }
+ shouldBeCache = true;
} else {
imageConfig.url = source;
+ shouldBeCache = true;
}
- shouldBeCache = true;
}
if (scene.getObject(imageShapeKey)) {
diff --git a/packages/drawing/src/index.ts b/packages/drawing/src/index.ts
index 418f7bc60a..99faed012d 100644
--- a/packages/drawing/src/index.ts
+++ b/packages/drawing/src/index.ts
@@ -36,5 +36,6 @@ export { IDrawingManagerService } from './services/drawing-manager.service';
export { ImageIoService } from './services/image-io-impl.service';
export { IImageIoService, ImageSourceType, ImageUploadStatusType } from './services/image-io.service';
export type { IImageIoServiceParam } from './services/image-io.service';
+export { URLImageService } from './services/url-image.service';
export { getDrawingShapeKeyByDrawingSearch } from './utils/get-image-shape-key';
export { getImageSize } from './utils/get-image-size';
diff --git a/packages/drawing/src/plugin.ts b/packages/drawing/src/plugin.ts
index eea59aab72..c3ad8811e6 100644
--- a/packages/drawing/src/plugin.ts
+++ b/packages/drawing/src/plugin.ts
@@ -17,13 +17,14 @@
import type { Dependency } from '@univerjs/core';
import type { IUniverDrawingConfig } from './controllers/config.schema';
-import { ICommandService, IConfigService, Inject, Injector, merge, mergeOverrideWithDependencies, Plugin } from '@univerjs/core';
+import { ICommandService, IConfigService, Inject, Injector, IURLImageService, merge, mergeOverrideWithDependencies, Plugin } from '@univerjs/core';
import { SetDrawingSelectedOperation } from './commands/operations/set-drawing-selected.operation';
import { defaultPluginConfig, DRAWING_PLUGIN_CONFIG_KEY } from './controllers/config.schema';
import { DrawingManagerService } from './services/drawing-manager-impl.service';
import { IDrawingManagerService } from './services/drawing-manager.service';
import { ImageIoService } from './services/image-io-impl.service';
import { IImageIoService } from './services/image-io.service';
+import { URLImageService } from './services/url-image.service';
const PLUGIN_NAME = 'UNIVER_DRAWING_PLUGIN';
@@ -55,6 +56,7 @@ export class UniverDrawingPlugin extends Plugin {
private _initDependencies(): void {
const dependencies: Dependency[] = [
[IImageIoService, { useClass: ImageIoService }],
+ [IURLImageService, { useClass: URLImageService }],
[IDrawingManagerService, { useClass: DrawingManagerService }],
];
diff --git a/packages/drawing/src/services/url-image.service.ts b/packages/drawing/src/services/url-image.service.ts
new file mode 100644
index 0000000000..7c9e7a8dbb
--- /dev/null
+++ b/packages/drawing/src/services/url-image.service.ts
@@ -0,0 +1,56 @@
+/**
+ * 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 { IDisposable, IURLImageService } from '@univerjs/core';
+import { Disposable, toDisposable } from '@univerjs/core';
+
+export class URLImageService extends Disposable implements IURLImageService {
+ private _urlImageDownloader: ((url: string) => Promise<string>) | null = null;
+
+ registerURLImageDownloader(downloader: (url: string) => Promise<string>): IDisposable {
+ this._urlImageDownloader = downloader;
+ return toDisposable(() => {
+ this._urlImageDownloader = null;
+ });
+ }
+
+ async getImage(url: string): Promise<string> {
+ if (this._urlImageDownloader) {
+ try {
+ return await this._urlImageDownloader(url);
+ } catch (error) {
+ console.error(`Custom downloader failed for ${url}, falling back to default behavior:`, error);
+ }
+ }
+
+ return url;
+ }
+
+ async downloadImage(url: string): Promise<Blob> {
+ if (this._urlImageDownloader) {
+ try {
+ const base64 = await this._urlImageDownloader(url);
+ const response = await fetch(base64);
+ return await response.blob();
+ } catch (error) {
+ console.error(`Custom downloader failed for ${url}, falling back to default fetch:`, error);
+ }
+ }
+
+ const response = await fetch(url);
+ return await response.blob();
+ }
+}
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 95db45dfd6..d8b766d146 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
@@ -21,7 +21,7 @@ import type { ISheetLocationBase, WorkbookSelectionModel } from '@univerjs/sheet
import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import type { IInsertDrawingCommandParams, ISetDrawingCommandParams } from '../commands/commands/interfaces';
import type { ISetDrawingArrangeCommandParams } from '../commands/commands/set-drawing-arrange.command';
-import { BooleanNumber, BuildTextUtils, createDocumentModelWithStyle, Disposable, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, generateRandomId, ICommandService, IContextService, ImageSourceType, Inject, Injector, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
+import { BooleanNumber, BuildTextUtils, createDocumentModelWithStyle, Disposable, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, generateRandomId, ICommandService, IContextService, ImageSourceType, Inject, Injector, IURLImageService, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
import { MessageType } from '@univerjs/design';
import { docDrawingPositionToTransform } from '@univerjs/docs-ui';
import { DRAWING_IMAGE_ALLOW_IMAGE_LIST, DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, getImageSize, IDrawingManagerService, IImageIoService, ImageUploadStatusType, SetDrawingSelectedOperation } from '@univerjs/drawing';
@@ -108,7 +108,8 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
@IMessageService private readonly _messageService: IMessageService,
@Inject(LocaleService) private readonly _localeService: LocaleService,
@Inject(SheetsSelectionsService) selectionManagerService: SheetsSelectionsService,
- @Inject(Injector) private readonly _injector: Injector
+ @Inject(Injector) private readonly _injector: Injector,
+ @IURLImageService private readonly _urlImageService: IURLImageService
) {
super();
@@ -353,7 +354,13 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
// eslint-disable-next-line max-lines-per-function
async insertCellImageByUrl(url: string, location?: ISheetLocationBase) {
- const { width, height, image } = await getImageSize(url || '');
+ let src = url;
+ try {
+ src = await this._urlImageService.getImage(url);
+ } catch (error) {
+ console.error(`Failed to get image from URLImageService: ${url}`, error);
+ }
+ const { width, height, image } = await getImageSize(src || '');
this._imageIoService.addImageSourceCache(url, ImageSourceType.URL, image);
const selection = this._workbookSelections.getCurrentLastSelection();
if (!selection) {
diff --git a/packages/sheets-drawing-ui/src/facade/f-univer.ts b/packages/sheets-drawing-ui/src/facade/f-univer.ts
index c0c5d438aa..1c98726f6a 100644
--- a/packages/sheets-drawing-ui/src/facade/f-univer.ts
+++ b/packages/sheets-drawing-ui/src/facade/f-univer.ts
@@ -25,10 +25,10 @@ import type {
IBeforeFloatDomUpdateParam,
IBeforeOverGridImageChangeParamObject,
} from './f-event';
-import { CanceledError, DrawingTypeEnum, ICommandService } from '@univerjs/core';
+import { CanceledError, DrawingTypeEnum, ICommandService, IURLImageService } from '@univerjs/core';
import { FUniver } from '@univerjs/core/facade';
import { IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';
-import { IBatchSaveImagesService, InsertSheetDrawingCommand, RemoveSheetDrawingCommand, SetSheetDrawingCommand } from '@univerjs/sheets-drawing-ui';
+import { InsertSheetDrawingCommand, RemoveSheetDrawingCommand, SetSheetDrawingCommand } from '@univerjs/sheets-drawing-ui';
import { FOverGridImage } from './f-over-grid-image';
interface IBeforeOverGridImageInsertParam extends IEventBase {
@@ -496,8 +496,8 @@ export class FUniverDrawingMixin extends FUniver {
* ```
*/
registerURLImageDownloader(downloader: (url: string) => Promise<string>): IDisposable {
- const batchSaveImagesService = this._injector.get(IBatchSaveImagesService);
- return batchSaveImagesService.registerURLImageDownloader(downloader);
+ const urlImageService = this._injector.get(IURLImageService);
+ return urlImageService.registerURLImageDownloader(downloader);
}
}
diff --git a/packages/sheets-drawing-ui/src/services/batch-save-images.service.ts b/packages/sheets-drawing-ui/src/services/batch-save-images.service.ts
index 41a44a4cc6..06d77a70eb 100644
--- a/packages/sheets-drawing-ui/src/services/batch-save-images.service.ts
+++ b/packages/sheets-drawing-ui/src/services/batch-save-images.service.ts
@@ -16,7 +16,7 @@
import type { ICellData, IDisposable, IRange, Nullable, Workbook } from '@univerjs/core';
import type { IImageData } from '@univerjs/drawing';
-import { createIdentifier, Disposable, IImageIoService, ImageSourceType, Inject, IUniverInstanceService, toDisposable, UniverInstanceType } from '@univerjs/core';
+import { createIdentifier, Disposable, IImageIoService, ImageSourceType, Inject, IUniverInstanceService, IURLImageService, UniverInstanceType } from '@univerjs/core';
import { SheetsSelectionsService } from '@univerjs/sheets';
declare global {
@@ -252,23 +252,20 @@ async function imageSourceToBlob(source: string, imageSourceType: ImageSourceTyp
}
export class BatchSaveImagesService extends Disposable implements IBatchSaveImagesService {
- private _urlImageDownloader: Nullable<(url: string) => Promise<string>> = null;
-
constructor(
@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,
@Inject(SheetsSelectionsService) private readonly _selectionService: SheetsSelectionsService,
- @IImageIoService private readonly _imageIoService: IImageIoService
+ @IImageIoService private readonly _imageIoService: IImageIoService,
+ @IURLImageService private readonly _urlImageService: IURLImageService
) {
super();
}
+ /**
+ * @deprecated Use IURLImageService directly
+ */
registerURLImageDownloader(downloader: (url: string) => Promise<string>): IDisposable {
- this._urlImageDownloader = downloader;
- return toDisposable(() => {
- if (this._urlImageDownloader === downloader) {
- this._urlImageDownloader = null;
- }
- });
+ return this._urlImageService.registerURLImageDownloader(downloader);
}
getCellImagesInSelection(): ICellImageInfo[] {
@@ -688,14 +685,8 @@ export class BatchSaveImagesService extends Disposable implements IBatchSaveImag
return imageSourceToBlob(imageUrl, ImageSourceType.URL);
}
- if (imageInfo.imageSourceType === ImageSourceType.URL && this._urlImageDownloader) {
- try {
- const base64 = await this._urlImageDownloader(imageInfo.source);
- return imageSourceToBlob(base64, ImageSourceType.BASE64);
- } catch (error) {
- console.error(`Custom downloader failed for ${imageInfo.source}, falling back to default fetch:`, error);
- // Fallback to default fetch if custom downloader fails
- }
+ if (imageInfo.imageSourceType === ImageSourceType.URL) {
+ return this._urlImageService.downloadImage(imageInfo.source);
}
return imageSourceToBlob(imageInfo.source, imageInfo.imageSourceType);