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.

refactor: use file opener service to get file content (#3370)

Wenzhao Hu7a855d576109
diff --git a/packages/docs-drawing-ui/src/commands/commands/insert-image.command.ts b/packages/docs-drawing-ui/src/commands/commands/insert-image.command.ts
new file mode 100644
index 0000000000..360054ad5d
--- /dev/null
+++ b/packages/docs-drawing-ui/src/commands/commands/insert-image.command.ts
@@ -0,0 +1,34 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { DocDrawingUpdateRenderController } from '../../controllers/render-controllers/doc-drawing-update.render-controller';
+
+export interface IInsertDocImageCommandParams {
+ files: Nullable<File[]>;
+};
+
+export const InsertDocImageCommand: ICommand<IInsertDocImageCommandParams> = {
+ id: 'doc.command.insert-float-image',
+ type: CommandType.COMMAND,
+ handler: (accessor) => {
+ const renderManagerService = accessor.get(IRenderManagerService);
+ return renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_DOC)
+ ?.with(DocDrawingUpdateRenderController).insertDocImage() ?? false;
+ },
+};
diff --git a/packages/docs-drawing-ui/src/commands/operations/insert-image.operation.ts b/packages/docs-drawing-ui/src/commands/operations/insert-image.operation.ts
deleted file mode 100644
index 151e010c0e..0000000000
--- a/packages/docs-drawing-ui/src/commands/operations/insert-image.operation.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 { IOperation, Nullable } from '@univerjs/core';
-import { CommandType } from '@univerjs/core';
-
-export interface IInsertImageOperationParams {
- files: Nullable<File[]>;
-};
-
-/**
- * @deprecated Do not use command as event!
- */
-export const InsertDocImageOperation: IOperation<IInsertImageOperationParams> = {
- id: 'doc.operation.insert-float-image',
- type: CommandType.OPERATION,
- handler: () => true,
-};
diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts
index c6f01cc3c3..6133d13303 100644
--- a/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing.controller.ts
@@ -14,14 +14,11 @@
* limitations under the License.
*/
-import { Disposable, ICommandService, Inject, Injector, LifecycleStages, OnLifecycle } from '@univerjs/core';
+import { Disposable, ICommandService, Inject, LifecycleStages, OnLifecycle } from '@univerjs/core';
import { ComponentManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';
import { AddImageSingle } from '@univerjs/icons';
-import { UploadFileMenu } from '../views/upload-component/UploadFile';
-import { COMPONENT_DOC_UPLOAD_FILE_MENU } from '../views/upload-component/component-name';
import { ImageUploadIcon } from '../views/menu/image.menu';
-import { InsertDocImageOperation } from '../commands/operations/insert-image.operation';
import { COMPONENT_DOC_DRAWING_PANEL } from '../views/doc-image-panel/component-name';
import { DocDrawingPanel } from '../views/doc-image-panel/DocDrawingPanel';
@@ -36,13 +33,13 @@ import { UngroupDocDrawingCommand } from '../commands/commands/ungroup-doc-drawi
import { GroupDocDrawingCommand } from '../commands/commands/group-doc-drawing.command';
import { InsertDocDrawingCommand } from '../commands/commands/insert-doc-drawing.command';
import { IMoveInlineDrawingCommand, ITransformNonInlineDrawingCommand, UpdateDocDrawingDistanceCommand, UpdateDocDrawingWrappingStyleCommand, UpdateDocDrawingWrapTextCommand, UpdateDrawingDocTransformCommand } from '../commands/commands/update-doc-drawing.command';
+import { InsertDocImageCommand } from '../commands/commands/insert-image.command';
import { DeleteDrawingsShortcutItem, MoveDrawingDownShortcutItem, MoveDrawingLeftShortcutItem, MoveDrawingRightShortcutItem, MoveDrawingUpShortcutItem } from './shortcuts/drawing.shortcut';
import { menuSchema } from './menu.schema';
@OnLifecycle(LifecycleStages.Ready, DocDrawingUIController)
export class DocDrawingUIController extends Disposable {
constructor(
- @Inject(Injector) private readonly _injector: Injector,
@Inject(ComponentManager) private readonly _componentManager: ComponentManager,
@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,
@ICommandService private readonly _commandService: ICommandService,
@@ -56,7 +53,6 @@ export class DocDrawingUIController extends Disposable {
private _initCustomComponents(): void {
const componentManager = this._componentManager;
this.disposeWithMe(componentManager.register(ImageUploadIcon, AddImageSingle));
- this.disposeWithMe(componentManager.register(COMPONENT_DOC_UPLOAD_FILE_MENU, UploadFileMenu));
this.disposeWithMe(componentManager.register(COMPONENT_DOC_DRAWING_PANEL, DocDrawingPanel));
}
@@ -66,7 +62,7 @@ export class DocDrawingUIController extends Disposable {
private _initCommands() {
[
- InsertDocImageOperation,
+ InsertDocImageCommand,
InsertDocDrawingCommand,
UpdateDocDrawingWrappingStyleCommand,
UpdateDocDrawingDistanceCommand,
diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
index 61def40f04..5b0fe58522 100644
--- a/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/doc-drawing-update.render-controller.ts
@@ -17,8 +17,8 @@
import type { DocumentDataModel, ICommandInfo, IDocDrawingPosition, Nullable } from '@univerjs/core';
import { BooleanNumber, Disposable, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, Inject, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, PositionedObjectLayoutType, WrapTextType } from '@univerjs/core';
import type { IImageIoServiceParam } from '@univerjs/drawing';
-import { DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, DrawingTypeEnum, getDrawingShapeKeyByDrawingSearch, getImageSize, IDrawingManagerService, IImageIoService, ImageUploadStatusType } from '@univerjs/drawing';
-import { IMessageService } from '@univerjs/ui';
+import { DRAWING_IMAGE_ALLOW_IMAGE_LIST, DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, DrawingTypeEnum, getDrawingShapeKeyByDrawingSearch, getImageSize, IDrawingManagerService, IImageIoService, ImageUploadStatusType } from '@univerjs/drawing';
+import { IFileOpenerService, IMessageService } from '@univerjs/ui';
import { MessageType } from '@univerjs/design';
import type { IDocDrawing } from '@univerjs/docs-drawing';
import { IDocDrawingService } from '@univerjs/docs-drawing';
@@ -27,8 +27,6 @@ import { docDrawingPositionToTransform } from '@univerjs/docs-ui';
import type { Documents, Image, IRenderContext, IRenderModule } from '@univerjs/engine-render';
import { DocumentEditArea, IRenderManagerService, ITextSelectionRenderManager } from '@univerjs/engine-render';
-import type { IInsertImageOperationParams } from '../../commands/operations/insert-image.operation';
-import { InsertDocImageOperation } from '../../commands/operations/insert-image.operation';
import type { IInsertDrawingCommandParams } from '../../commands/commands/interfaces';
import { type ISetDrawingArrangeCommandParams, SetDocDrawingArrangeCommand } from '../../commands/commands/set-drawing-arrange.command';
import { InsertDocDrawingCommand } from '../../commands/commands/insert-doc-drawing.command';
@@ -40,6 +38,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
constructor(
private readonly _context: IRenderContext<DocumentDataModel>,
@ICommandService private readonly _commandService: ICommandService,
+ @IFileOpenerService private readonly _fileOpenerService: IFileOpenerService,
@Inject(TextSelectionManagerService) private readonly _textSelectionManagerService: TextSelectionManagerService,
@IRenderManagerService private readonly _renderManagerSrv: IRenderManagerService,
@IImageIoService private readonly _imageIoService: IImageIoService,
@@ -54,7 +53,6 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
) {
super();
- this._initCommandListeners();
this._updateDrawingListener();
this._updateOrderListener();
this._groupDrawingListener();
@@ -63,34 +61,25 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen
this._editAreaChangeListener();
}
- /**
- * Upload image to cell or float image
- */
- private _initCommandListeners() {
- this.disposeWithMe(
- this._commandService.onCommandExecuted(async (command: ICommandInfo) => {
- if (command.id === InsertDocImageOperation.id) {
- const params = command.params as IInsertImageOperationParams;
- if (params.files == null) {
- return;
- }
-
- const fileLength = params.files.length;
-
- if (fileLength > DRAWING_IMAGE_COUNT_LIMIT) {
- this._messageService.show({
- type: MessageType.Error,
- content: this._localeService.t('update-status.exceedMaxCount', String(DRAWING_IMAGE_COUNT_LIMIT)),
- });
- return;
- }
+ async insertDocImage(): Promise<boolean> {
+ const files = await this._fileOpenerService.openFile({
+ multiple: true,
+ accept: DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','),
+ });
- this._imageIoService.setWaitCount(fileLength);
+ const fileLength = files.length;
+ if (fileLength > DRAWING_IMAGE_COUNT_LIMIT) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.exceedMaxCount', String(DRAWING_IMAGE_COUNT_LIMIT)),
+ });
+ return false;
+ } else if (fileLength === 0) {
+ return false;
+ }
- await this._insertFloatImages(params.files);
- }
- })
- );
+ await this._insertFloatImages(files);
+ return true;
}
// eslint-disable-next-line max-lines-per-function
diff --git a/packages/docs-drawing-ui/src/index.ts b/packages/docs-drawing-ui/src/index.ts
index b4c22a4a74..ac925161d2 100644
--- a/packages/docs-drawing-ui/src/index.ts
+++ b/packages/docs-drawing-ui/src/index.ts
@@ -28,9 +28,8 @@ export { UngroupDocDrawingCommand } from './commands/commands/ungroup-doc-drawin
export { ClearDocDrawingTransformerOperation } from './commands/operations/clear-drawing-transformer.operation';
export { EditDocDrawingOperation } from './commands/operations/edit-doc-drawing.operation';
-export { InsertDocImageOperation } from './commands/operations/insert-image.operation';
+export { InsertDocImageCommand } from './commands/commands/insert-image.command';
export { SidebarDocDrawingOperation } from './commands/operations/open-drawing-panel.operation';
export { IMAGE_MENU_ID } from './views/menu/image.menu';
-export { COMPONENT_DOC_UPLOAD_FILE_MENU } from './views/upload-component/component-name';
// #endregion
diff --git a/packages/docs-drawing-ui/src/views/menu/image.menu.ts b/packages/docs-drawing-ui/src/views/menu/image.menu.ts
index 5b558ef1f7..606513901f 100644
--- a/packages/docs-drawing-ui/src/views/menu/image.menu.ts
+++ b/packages/docs-drawing-ui/src/views/menu/image.menu.ts
@@ -17,14 +17,13 @@
import { getMenuHiddenObservable, type IMenuItem, MenuItemType } from '@univerjs/ui';
import { IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import type { IAccessor } from '@univerjs/core';
-
import { TextSelectionManagerService } from '@univerjs/docs';
import { Observable } from 'rxjs';
-import { COMPONENT_DOC_UPLOAD_FILE_MENU } from '../upload-component/component-name';
+import { InsertDocImageCommand } from '../../commands/commands/insert-image.command';
export const ImageUploadIcon = 'addition-and-subtraction-single';
export const IMAGE_MENU_ID = 'doc.menu.image';
-export const IMAGE_MENU_UPLOAD_FLOAT_ID = 'doc.menu.image.upload.float';
+export const IMAGE_MENU_UPLOAD_FLOAT_ID = InsertDocImageCommand.id;
// TODO: @Jocs, remove this when cell support drawing.
const getDisableWhenSelectionInTableObservable = (accessor: IAccessor) => {
@@ -76,10 +75,7 @@ export function UploadFloatImageMenuFactory(_accessor: IAccessor): IMenuItem {
return {
id: IMAGE_MENU_UPLOAD_FLOAT_ID,
title: 'docImage.upload.float',
- type: MenuItemType.SELECTOR,
- label: {
- name: COMPONENT_DOC_UPLOAD_FILE_MENU,
- },
+ type: MenuItemType.BUTTON,
hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_DOC),
};
}
diff --git a/packages/docs-drawing-ui/src/views/upload-component/UploadFile.tsx b/packages/docs-drawing-ui/src/views/upload-component/UploadFile.tsx
deleted file mode 100644
index dab53188b5..0000000000
--- a/packages/docs-drawing-ui/src/views/upload-component/UploadFile.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 { ICommandService, useDependency } from '@univerjs/core';
-import React, { useRef } from 'react';
-import { DRAWING_IMAGE_ALLOW_IMAGE_LIST } from '@univerjs/drawing';
-import { InsertDocImageOperation } from '../../commands/operations/insert-image.operation';
-import styles from './index.module.less';
-
-export const UploadFileMenu = () => {
- const commandService = useDependency(ICommandService);
-
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- const handleButtonClick = () => {
- fileInputRef.current?.click();
- };
-
- const imageAccept = DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(',');
-
- const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
- const fileList = event.target.files;
-
- if (fileList == null) {
- return;
- }
-
- const files: File[] = Array.from(fileList);
-
- commandService.executeCommand(InsertDocImageOperation.id, { files });
-
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- };
-
- return (
- <div onClick={handleButtonClick} className={styles.uploadFileMenu}>
- <input
- type="file"
- className={styles.uploadFileMenuInput}
- ref={fileInputRef}
- onChange={handleFileChange}
- accept={imageAccept}
- multiple
- />
- </div>
- );
-};
diff --git a/packages/docs-drawing-ui/src/views/upload-component/component-name.ts b/packages/docs-drawing-ui/src/views/upload-component/component-name.ts
deleted file mode 100644
index d268d7573a..0000000000
--- a/packages/docs-drawing-ui/src/views/upload-component/component-name.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 const COMPONENT_DOC_UPLOAD_FILE_MENU = 'COMPONENT_DOC_UPLOAD_FILE_MENU';
diff --git a/packages/docs-drawing-ui/src/views/upload-component/index.module.less b/packages/docs-drawing-ui/src/views/upload-component/index.module.less
deleted file mode 100644
index 963abf12ee..0000000000
--- a/packages/docs-drawing-ui/src/views/upload-component/index.module.less
+++ /dev/null
@@ -1,12 +0,0 @@
-.upload-file {
- &-menu {
- position: absolute;
- height: 100%;
- width: 100%;
- text-align: center;
-
- &-input {
- display: none;
- }
- }
-}
diff --git a/packages/sheets-drawing-ui/src/commands/commands/insert-image.command.ts b/packages/sheets-drawing-ui/src/commands/commands/insert-image.command.ts
new file mode 100644
index 0000000000..7b59548e2c
--- /dev/null
+++ b/packages/sheets-drawing-ui/src/commands/commands/insert-image.command.ts
@@ -0,0 +1,34 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { SheetDrawingUpdateController } from '../../controllers/sheet-drawing-update.controller';
+
+export interface IInsertImageCommandParams {
+ files: Nullable<File[]>;
+};
+
+export const InsertFloatImageCommand: ICommand<IInsertImageCommandParams> = {
+ id: 'sheet.command.insert-float-image',
+ type: CommandType.COMMAND,
+ handler: (accessor) => {
+ const renderManagerService = accessor.get(IRenderManagerService);
+ return renderManagerService.getCurrentTypeOfRenderer(UniverInstanceType.UNIVER_SHEET)
+ ?.with(SheetDrawingUpdateController).insertFloatImage() ?? false;
+ },
+};
diff --git a/packages/sheets-drawing-ui/src/commands/operations/insert-image.operation.ts b/packages/sheets-drawing-ui/src/commands/operations/insert-image.operation.ts
deleted file mode 100644
index 2338996b42..0000000000
--- a/packages/sheets-drawing-ui/src/commands/operations/insert-image.operation.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 { IOperation, Nullable } from '@univerjs/core';
-import { CommandType } from '@univerjs/core';
-
-export interface IInsertImageOperationParams {
- files: Nullable<File[]>;
-};
-
-export const InsertFloatImageOperation: IOperation<IInsertImageOperationParams> = {
- id: 'sheet.operation.insert-float-image',
- type: CommandType.OPERATION,
- handler: (accessor, params) => {
- return true;
- },
-};
-
-export const InsertCellImageOperation: IOperation<IInsertImageOperationParams> = {
- id: 'sheet.operation.insert-cell-image',
- type: CommandType.OPERATION,
- handler: (accessor, params) => {
- return true;
- },
-};
diff --git a/packages/sheets-drawing-ui/src/controllers/menu.schema.ts b/packages/sheets-drawing-ui/src/controllers/menu.schema.ts
index f485b60524..b03a04a656 100644
--- a/packages/sheets-drawing-ui/src/controllers/menu.schema.ts
+++ b/packages/sheets-drawing-ui/src/controllers/menu.schema.ts
@@ -17,14 +17,14 @@
import type { MenuSchemaType } from '@univerjs/ui';
import { RibbonStartGroup } from '@univerjs/ui';
import { IMAGE_MENU_ID, ImageMenuFactory, UploadFloatImageMenuFactory } from '../views/menu/image.menu';
-import { InsertFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertFloatImageCommand } from '../commands/commands/insert-image.command';
export const menuSchema: MenuSchemaType = {
[RibbonStartGroup.FORMULAS_INSERT]: {
[IMAGE_MENU_ID]: {
order: 3,
menuItemFactory: ImageMenuFactory,
- [InsertFloatImageOperation.id]: {
+ [InsertFloatImageCommand.id]: {
order: 0,
menuItemFactory: UploadFloatImageMenuFactory,
},
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 275159da32..2bdbedeb17 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
@@ -14,20 +14,18 @@
* limitations under the License.
*/
-import type { ICommandInfo, IRange, Nullable, Workbook } from '@univerjs/core';
+import type { IRange, Nullable, Workbook } from '@univerjs/core';
import { Disposable, FOCUSING_COMMON_DRAWINGS, ICommandService, IContextService, Inject, LocaleService } from '@univerjs/core';
import type { IImageData, IImageIoServiceParam } from '@univerjs/drawing';
-import { DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, DrawingTypeEnum, getImageSize, IDrawingManagerService, IImageIoService, ImageUploadStatusType } from '@univerjs/drawing';
+import { DRAWING_IMAGE_ALLOW_IMAGE_LIST, DRAWING_IMAGE_ALLOW_SIZE, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, DrawingTypeEnum, getImageSize, IDrawingManagerService, IImageIoService, ImageUploadStatusType } from '@univerjs/drawing';
import type { ISheetDrawing, ISheetDrawingPosition } from '@univerjs/sheets-drawing';
import { ISheetDrawingService } from '@univerjs/sheets-drawing';
import type { WorkbookSelections } from '@univerjs/sheets';
import { SheetsSelectionsService } from '@univerjs/sheets';
import { attachRangeWithCoord, ISheetSelectionRenderService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
-import { IMessageService } from '@univerjs/ui';
+import { IFileOpenerService, IMessageService } from '@univerjs/ui';
import { MessageType } from '@univerjs/design';
import type { IRenderContext, IRenderModule } from '@univerjs/engine-render';
-import type { IInsertImageOperationParams } from '../commands/operations/insert-image.operation';
-import { InsertCellImageOperation, InsertFloatImageOperation } from '../commands/operations/insert-image.operation';
import { InsertSheetDrawingCommand } from '../commands/commands/insert-sheet-drawing.command';
import type { IInsertDrawingCommandParams, ISetDrawingCommandParams } from '../commands/commands/interfaces';
import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.command';
@@ -45,6 +43,7 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
@ICommandService private readonly _commandService: ICommandService,
@ISheetSelectionRenderService private readonly _selectionRenderService: ISheetSelectionRenderService,
@IImageIoService private readonly _imageIoService: IImageIoService,
+ @IFileOpenerService private readonly _fileOpenerService: IFileOpenerService,
@ISheetDrawingService private readonly _sheetDrawingService: ISheetDrawingService,
@IDrawingManagerService private readonly _drawingManagerService: IDrawingManagerService,
@IContextService private readonly _contextService: IContextService,
@@ -56,52 +55,31 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
this._workbookSelections = selectionManagerService.getWorkbookSelections(this._context.unitId);
- this._initCommandListeners();
this._updateImageListener();
this._updateOrderListener();
this._groupDrawingListener();
this._focusDrawingListener();
}
- /**
- * Upload image to cell or float image
- */
- private _initCommandListeners() {
- this.disposeWithMe(
- this._commandService.onCommandExecuted(async (command: ICommandInfo) => {
- if (command.id === InsertCellImageOperation.id || command.id === InsertFloatImageOperation.id) {
- const params = command.params as IInsertImageOperationParams;
- if (params.files == null) {
- return;
- }
-
- const fileLength = params.files.length;
-
- if (fileLength > DRAWING_IMAGE_COUNT_LIMIT) {
- this._messageService.show({
- type: MessageType.Error,
- content: this._localeService.t('update-status.exceedMaxCount', String(DRAWING_IMAGE_COUNT_LIMIT)),
- });
- return;
- }
-
- this._imageIoService.setWaitCount(fileLength);
- if (command.id === InsertCellImageOperation.id) {
- params.files.forEach(async (file) => {
- await this._insertCellImage(file);
- });
- } else {
- params.files.forEach(async (file) => {
- await this._insertFloatImage(file);
- });
- }
- }
- })
- );
- }
+ async insertFloatImage(): Promise<boolean> {
+ const files = await this._fileOpenerService.openFile({
+ multiple: true,
+ accept: DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','),
+ });
- private async _insertCellImage(file: File) {
- // TODO: empty
+ const fileLength = files.length;
+ if (fileLength > DRAWING_IMAGE_COUNT_LIMIT) {
+ this._messageService.show({
+ type: MessageType.Error,
+ content: this._localeService.t('update-status.exceedMaxCount', String(DRAWING_IMAGE_COUNT_LIMIT)),
+ });
+ return false;
+ } else if (fileLength === 0) {
+ return false;
+ }
+
+ files.forEach(async (file) => await this._insertFloatImage(file));
+ return true;
}
private async _insertFloatImage(file: File) {
@@ -134,13 +112,9 @@ export class SheetDrawingUpdateController extends Disposable implements IRenderM
}
const info = this._getUnitInfo();
- if (info == null) {
- return;
- }
const { unitId, subUnitId } = info;
const { imageId, imageSourceType, source, base64Cache } = imageParam;
const { width, height, image } = await getImageSize(base64Cache || '');
-
const { width: sceneWidth, height: sceneHeight } = this._context.scene;
this._imageIoService.addImageSourceCache(source, imageSourceType, image);
diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts
index 083948db11..9f30128d8f 100644
--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts
+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing.controller.ts
@@ -18,10 +18,8 @@ import { Disposable, ICommandService, Inject, Injector, LifecycleStages, OnLifec
import { ComponentManager, IMenuManagerService, IShortcutService } from '@univerjs/ui';
import { AddImageSingle } from '@univerjs/icons';
-import { UploadFileMenu } from '../views/upload-component/UploadFile';
-import { COMPONENT_UPLOAD_FILE_MENU } from '../views/upload-component/component-name';
import { IMAGE_UPLOAD_ICON } from '../views/menu/image.menu';
-import { InsertCellImageOperation, InsertFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertFloatImageCommand } from '../commands/commands/insert-image.command';
import { InsertSheetDrawingCommand } from '../commands/commands/insert-sheet-drawing.command';
import { RemoveSheetDrawingCommand } from '../commands/commands/remove-sheet-drawing.command';
import { SetSheetDrawingCommand } from '../commands/commands/set-sheet-drawing.command';
@@ -56,7 +54,6 @@ export class SheetDrawingUIController extends Disposable {
private _initCustomComponents(): void {
const componentManager = this._componentManager;
this.disposeWithMe(componentManager.register(IMAGE_UPLOAD_ICON, AddImageSingle));
- this.disposeWithMe(componentManager.register(COMPONENT_UPLOAD_FILE_MENU, UploadFileMenu));
this.disposeWithMe(componentManager.register(COMPONENT_SHEET_DRAWING_PANEL, SheetDrawingPanel));
}
@@ -66,8 +63,7 @@ export class SheetDrawingUIController extends Disposable {
private _initCommands() {
[
- InsertFloatImageOperation,
- InsertCellImageOperation,
+ InsertFloatImageCommand,
InsertSheetDrawingCommand,
RemoveSheetDrawingCommand,
SetSheetDrawingCommand,
diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.ts
index 36a69f2c85..7f4ee5ce4c 100644
--- a/packages/sheets-drawing-ui/src/index.ts
+++ b/packages/sheets-drawing-ui/src/index.ts
@@ -30,7 +30,7 @@ export { UngroupSheetDrawingCommand } from './commands/commands/ungroup-sheet-dr
export { ClearSheetDrawingTransformerOperation } from './commands/operations/clear-drawing-transformer.operation';
export { EditSheetDrawingOperation } from './commands/operations/edit-sheet-drawing.operation';
-export { InsertFloatImageOperation, InsertCellImageOperation } from './commands/operations/insert-image.operation';
+export { InsertFloatImageCommand, type IInsertImageCommandParams } from './commands/commands/insert-image.command';
export { SidebarSheetDrawingOperation } from './commands/operations/open-drawing-panel.operation';
export { IMAGE_MENU_ID } from './views/menu/image.menu';
diff --git a/packages/sheets-drawing-ui/src/views/menu/image.menu.ts b/packages/sheets-drawing-ui/src/views/menu/image.menu.ts
index 521e287223..700413dda4 100644
--- a/packages/sheets-drawing-ui/src/views/menu/image.menu.ts
+++ b/packages/sheets-drawing-ui/src/views/menu/image.menu.ts
@@ -19,8 +19,7 @@ import type { IAccessor } from '@univerjs/core';
import { UniverInstanceType } from '@univerjs/core';
import { getCurrentRangeDisable$ } from '@univerjs/sheets-ui';
import { RangeProtectionPermissionEditPoint, WorkbookEditablePermission, WorksheetEditPermission } from '@univerjs/sheets';
-import { COMPONENT_UPLOAD_FILE_MENU, UploadFileType } from '../upload-component/component-name';
-import { InsertCellImageOperation, InsertFloatImageOperation } from '../../commands/operations/insert-image.operation';
+import { InsertFloatImageCommand } from '../../commands/commands/insert-image.command';
export const IMAGE_UPLOAD_ICON = 'addition-and-subtraction-single';
export const IMAGE_MENU_ID = 'sheet.menu.image';
@@ -38,30 +37,9 @@ export function ImageMenuFactory(accessor: IAccessor): IMenuItem {
export function UploadFloatImageMenuFactory(_accessor: IAccessor): IMenuItem {
return {
- id: InsertFloatImageOperation.id,
+ id: InsertFloatImageCommand.id,
title: 'sheetImage.upload.float',
- type: MenuItemType.SELECTOR,
- label: {
- name: COMPONENT_UPLOAD_FILE_MENU,
- props: {
- type: UploadFileType.floatImage,
- },
- },
- hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_SHEET),
- };
-}
-
-export function UploadCellImageMenuFactory(_accessor: IAccessor): IMenuItem {
- return {
- id: InsertCellImageOperation.id,
- title: 'sheetImage.upload.cell',
- type: MenuItemType.SELECTOR,
- label: {
- name: COMPONENT_UPLOAD_FILE_MENU,
- props: {
- type: UploadFileType.cellImage,
- },
- },
+ type: MenuItemType.BUTTON,
hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_SHEET),
};
}
diff --git a/packages/sheets-drawing-ui/src/views/upload-component/UploadFile.tsx b/packages/sheets-drawing-ui/src/views/upload-component/UploadFile.tsx
deleted file mode 100644
index 0fed121341..0000000000
--- a/packages/sheets-drawing-ui/src/views/upload-component/UploadFile.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 { Nullable } from '@univerjs/core';
-import { ICommandService, useDependency } from '@univerjs/core';
-import React, { useRef } from 'react';
-import type { ICustomComponentProps } from '@univerjs/ui';
-import { DRAWING_IMAGE_ALLOW_IMAGE_LIST } from '@univerjs/drawing';
-import { InsertCellImageOperation, InsertFloatImageOperation } from '../../commands/operations/insert-image.operation';
-import styles from './index.module.less';
-import { UploadFileType } from './component-name';
-
-export interface IUploadFileProps extends ICustomComponentProps<Nullable<File>> {
- type: UploadFileType;
-}
-
-export const UploadFileMenu = (props: IUploadFileProps) => {
- const { type } = props;
-
- const commandService = useDependency(ICommandService);
-
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- const handleButtonClick = () => {
- fileInputRef.current?.click();
- };
-
- const imageAccept = DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(',');
-
- const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
- const fileList = event.target.files;
-
- if (fileList == null) {
- return;
- }
-
- const files: File[] = Array.from(fileList);
-
- if (type === UploadFileType.floatImage) {
- commandService.executeCommand(InsertFloatImageOperation.id, { files });
- } else if (type === UploadFileType.cellImage) {
- commandService.executeCommand(InsertCellImageOperation.id, { files });
- }
-
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- };
-
- return (
- <div onClick={handleButtonClick} className={styles.uploadFileMenu}>
- <input
- type="file"
- className={styles.uploadFileMenuInput}
- ref={fileInputRef}
- onChange={handleFileChange}
- accept={imageAccept}
- multiple
- />
- </div>
- );
-};
diff --git a/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts b/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts
index 5cd1cb4841..34564bda50 100644
--- a/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts
+++ b/packages/sheets-drawing-ui/src/views/upload-component/component-name.ts
@@ -14,8 +14,6 @@
* limitations under the License.
*/
-export const COMPONENT_UPLOAD_FILE_MENU = 'COMPONENT_UPLOAD_FILE_MENU';
-
export enum UploadFileType {
cellImage,
floatImage,
diff --git a/packages/sheets-drawing-ui/src/views/upload-component/index.module.less b/packages/sheets-drawing-ui/src/views/upload-component/index.module.less
deleted file mode 100644
index 963abf12ee..0000000000
--- a/packages/sheets-drawing-ui/src/views/upload-component/index.module.less
+++ /dev/null
@@ -1,12 +0,0 @@
-.upload-file {
- &-menu {
- position: absolute;
- height: 100%;
- width: 100%;
- text-align: center;
-
- &-input {
- display: none;
- }
- }
-}
diff --git a/packages/slides-ui/src/commands/operations/insert-image.operation.ts b/packages/slides-ui/src/commands/operations/insert-image.operation.ts
index e9c58d9293..357d865fc2 100644
--- a/packages/slides-ui/src/commands/operations/insert-image.operation.ts
+++ b/packages/slides-ui/src/commands/operations/insert-image.operation.ts
@@ -14,33 +14,34 @@
* limitations under the License.
*/
-import type { ICommand, Nullable, SlideDataModel } from '@univerjs/core';
-import { CommandType, IUniverInstanceService, PageElementType } from '@univerjs/core';
-import { getImageSize, IImageIoService } from '@univerjs/drawing';
+import type { ICommand, SlideDataModel } from '@univerjs/core';
+import { CommandType, IUniverInstanceService, PageElementType, UniverInstanceType } from '@univerjs/core';
+import { DRAWING_IMAGE_ALLOW_IMAGE_LIST, getImageSize, IImageIoService } from '@univerjs/drawing';
+import { IFileOpenerService } from '@univerjs/ui';
import { CanvasView } from '../../controllers/canvas-view';
-export interface IInsertImageOperationParams {
- files: Nullable<File[]>;
- unitId: string;
-};
-
-export const InsertSlideFloatImageOperation: ICommand<IInsertImageOperationParams> = {
- id: 'slide.operation.insert-float-image',
- type: CommandType.OPERATION,
+export const InsertSlideFloatImageCommand: ICommand<{}> = {
+ id: 'slide.command.insert-float-image',
+ type: CommandType.COMMAND,
handler: async (accessor, params) => {
- const imageIoService = accessor.get(IImageIoService);
- if (!params?.files?.length) return false;
+ const univerInstanceService = accessor.get(IUniverInstanceService);
+ const unitId = univerInstanceService.getCurrentUnitForType(UniverInstanceType.UNIVER_SLIDE)?.getUnitId();
+ if (!unitId) return false;
- const imageParam = await imageIoService.saveImage(params.files[0]);
+ const fileOpenerService = accessor.get(IFileOpenerService);
+ const files = await fileOpenerService.openFile({
+ multiple: true,
+ accept: DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(','),
+ });
+ if (files.length !== 1) return false;
+
+ const imageIoService = accessor.get(IImageIoService);
+ const imageParam = await imageIoService.saveImage(files[0]);
if (!imageParam) return false;
const { imageId, imageSourceType, source, base64Cache } = imageParam;
const { width, height, image } = await getImageSize(base64Cache || '');
- const univerInstanceService = accessor.get(IUniverInstanceService);
- // const slideData = univerInstanceService.getCurrentUnitForType<SlideDataModel>(UniverInstanceType.UNIVER_SLIDE);
-
- const unitId = params.unitId;
const slideData = univerInstanceService.getUnit<SlideDataModel>(unitId);
if (!slideData) return false;
@@ -70,29 +71,12 @@ export const InsertSlideFloatImageOperation: ICommand<IInsertImageOperationParam
activePage.pageElements[imageId] = data;
slideData.updatePage(activePage.id, activePage);
- const canvasview = accessor.get(CanvasView);
- const sceneObject = canvasview.createObjectToPage(data, activePage.id, unitId);
+ const canvasView = accessor.get(CanvasView);
+ const sceneObject = canvasView.createObjectToPage(data, activePage.id, unitId);
if (sceneObject) {
- canvasview.setObjectActiveByPage(sceneObject, activePage.id, unitId);
+ canvasView.setObjectActiveByPage(sceneObject, activePage.id, unitId);
}
- // console.log(slideData);
- // {
- // "id": "background1",
- // "zIndex": 0,
- // "left": 0,
- // "top": 0,
- // "width": 960,
- // "height": 540,
- // "title": "background",
- // "description": "",
- // "type": 1,
- // "image": {
- // "imageProperties": {
- // "contentUrl": "https://minio.cnbabylon.com/univer/slide/Picture1.jpg"
- // }
- // }
- // }
return true;
},
};
diff --git a/packages/slides-ui/src/components/upload-component/UploadFile.tsx b/packages/slides-ui/src/components/upload-component/UploadFile.tsx
deleted file mode 100644
index 7970042046..0000000000
--- a/packages/slides-ui/src/components/upload-component/UploadFile.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Copyright 2023-present DreamNum Inc.
- *
- * 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 { Nullable } from '@univerjs/core';
-import { ICommandService, IUniverInstanceService, useDependency } from '@univerjs/core';
-import React, { useRef } from 'react';
-import type { ICustomComponentProps } from '@univerjs/ui';
-import { useObservable } from '@univerjs/ui';
-import { DRAWING_IMAGE_ALLOW_IMAGE_LIST } from '@univerjs/drawing';
-import { InsertSlideFloatImageOperation } from '../../commands/operations/insert-image.operation';
-import styles from './index.module.less';
-import { UploadFileType } from './component-name';
-
-export interface IUploadFileProps extends ICustomComponentProps<Nullable<File>> {
- type: UploadFileType;
-}
-
-export const UploadFileMenu = (props: IUploadFileProps) => {
- const { type } = props;
-
- const commandService = useDependency(ICommandService);
- const univerInstanceService = useDependency(IUniverInstanceService);
- const focused = useObservable(univerInstanceService.focused$);
-
- const fileInputRef = useRef<HTMLInputElement>(null);
-
- const handleButtonClick = () => {
- fileInputRef.current?.click();
- };
-
- const imageAccept = DRAWING_IMAGE_ALLOW_IMAGE_LIST.map((image) => `.${image.replace('image/', '')}`).join(',');
-
- const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
- const fileList = event.target.files;
-
- if (fileList == null) {
- return;
- }
-
- const files: File[] = Array.from(fileList);
-
- if (type === UploadFileType.floatImage) {
- commandService.executeCommand(InsertSlideFloatImageOperation.id, { files, unitId: focused });
- }
-
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- };
-
- return (
- <div onClick={handleButtonClick} className={styles.uploadFileMenu}>
- <input
- type="file"
- className={styles.uploadFileMenuInput}
- ref={fileInputRef}
- onChange={handleFileChange}
- accept={imageAccept}
- multiple
- />
- </div>
- );
-};
diff --git a/packages/slides-ui/src/components/upload-component/index.module.less b/packages/slides-ui/src/components/upload-component/index.module.less
deleted file mode 100644
index 963abf12ee..0000000000
--- a/packages/slides-ui/src/components/upload-component/index.module.less
+++ /dev/null
@@ -1,12 +0,0 @@
-.upload-file {
- &-menu {
- position: absolute;
- height: 100%;
- width: 100%;
- text-align: center;
-
- &-input {
- display: none;
- }
- }
-}
diff --git a/packages/slides-ui/src/controllers/image.menu.ts b/packages/slides-ui/src/controllers/image.menu.ts
index 7ef0e3539d..95d323dde5 100644
--- a/packages/slides-ui/src/controllers/image.menu.ts
+++ b/packages/slides-ui/src/controllers/image.menu.ts
@@ -18,8 +18,7 @@ import type { IMenuItem } from '@univerjs/ui';
import { getMenuHiddenObservable, MenuItemType } from '@univerjs/ui';
import type { IAccessor } from '@univerjs/core';
import { UniverInstanceType } from '@univerjs/core';
-import { COMPONENT_UPLOAD_FILE_MENU, UploadFileType } from '../components/upload-component/component-name';
-import { InsertSlideFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertSlideFloatImageCommand } from '../commands/operations/insert-image.operation';
export const IMAGE_UPLOAD_ICON = 'addition-and-subtraction-single';
export const IMAGE_MENU_ID = 'slide.menu.image';
@@ -31,21 +30,14 @@ export function SlideImageMenuFactory(accessor: IAccessor): IMenuItem {
icon: IMAGE_UPLOAD_ICON,
tooltip: 'slide.image.insert.title',
hidden$: getMenuHiddenObservable(accessor, UniverInstanceType.UNIVER_SLIDE),
- // disabled$: getCurrentRangeDisable$(accessor, { workbookTypes: [WorkbookEditablePermission], worksheetTypes: [WorksheetEditPermission], rangeTypes: [RangeProtectionPermissionEditPoint] }),
};
}
export function UploadSlideFloatImageMenuFactory(_accessor: IAccessor): IMenuItem {
return {
- id: InsertSlideFloatImageOperation.id,
+ id: InsertSlideFloatImageCommand.id,
title: 'slide.image.insert.float',
- type: MenuItemType.SELECTOR,
- label: {
- name: COMPONENT_UPLOAD_FILE_MENU,
- props: {
- type: UploadFileType.floatImage,
- },
- },
+ type: MenuItemType.BUTTON,
hidden$: getMenuHiddenObservable(_accessor, UniverInstanceType.UNIVER_SLIDE),
};
}
diff --git a/packages/slides-ui/src/controllers/menu.schema.ts b/packages/slides-ui/src/controllers/menu.schema.ts
index 87df6e66f7..6c6035a70f 100644
--- a/packages/slides-ui/src/controllers/menu.schema.ts
+++ b/packages/slides-ui/src/controllers/menu.schema.ts
@@ -17,7 +17,7 @@
import type { MenuSchemaType } from '@univerjs/ui';
import { RibbonStartGroup } from '@univerjs/ui';
import { SlideAddTextCommand } from '../commands/operations/insert-text.operation';
-import { InsertSlideFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertSlideFloatImageCommand } from '../commands/operations/insert-image.operation';
import { InsertSlideShapeRectangleCommand } from '../commands/operations/insert-shape.operation';
import { SlideAddTextMenuItemFactory } from './text.menu';
import { IMAGE_MENU_ID, SlideImageMenuFactory, UploadSlideFloatImageMenuFactory } from './image.menu';
@@ -32,7 +32,7 @@ export const menuSchema: MenuSchemaType = {
[IMAGE_MENU_ID]: {
order: 0,
menuItemFactory: SlideImageMenuFactory,
- [InsertSlideFloatImageOperation.id]: {
+ [InsertSlideFloatImageCommand.id]: {
order: 0,
menuItemFactory: UploadSlideFloatImageMenuFactory,
},
diff --git a/packages/slides-ui/src/controllers/slide-ui.controller.ts b/packages/slides-ui/src/controllers/slide-ui.controller.ts
index a542c56d47..912ea4caea 100644
--- a/packages/slides-ui/src/controllers/slide-ui.controller.ts
+++ b/packages/slides-ui/src/controllers/slide-ui.controller.ts
@@ -19,15 +19,13 @@ import { AddImageSingle, GraphSingle, TextSingle } from '@univerjs/icons';
import { BuiltInUIPart, ComponentManager, IMenuManagerService, IShortcutService, IUIPartsService } from '@univerjs/ui';
import { ActivateSlidePageOperation } from '../commands/operations/activate.operation';
import { DeleteSlideElementOperation } from '../commands/operations/delete-element.operation';
-import { InsertSlideFloatImageOperation } from '../commands/operations/insert-image.operation';
+import { InsertSlideFloatImageCommand } from '../commands/operations/insert-image.operation';
import { InsertSlideShapeRectangleCommand, InsertSlideShapeRectangleOperation, ToggleSlideEditSidebarOperation } from '../commands/operations/insert-shape.operation';
import { SlideAddTextCommand, SlideAddTextOperation } from '../commands/operations/insert-text.operation';
import { SetSlidePageThumbOperation } from '../commands/operations/set-thumb.operation';
import { SetTextEditArrowOperation } from '../commands/operations/text-edit.operation';
import { SlideImagePopupMenu } from '../components/image-popup-menu/ImagePopupMenu';
import { COMPONENT_SLIDE_IMAGE_POPUP_MENU } from '../components/image-popup-menu/component-name';
-import { UploadFileMenu } from '../components/upload-component/UploadFile';
-import { COMPONENT_UPLOAD_FILE_MENU } from '../components/upload-component/component-name';
import { SlideEditorContainer } from '../views/editor-container';
import { SlideSideBar } from '../components/slide-bar/SlideBar';
import Sidebar, { COMPONENT_SLIDE_SIDEBAR } from '../components/sidebar/Sidebar';
@@ -70,7 +68,6 @@ export class SlidesUIController extends Disposable {
this.disposeWithMe(componentManager.register(IMAGE_UPLOAD_ICON, AddImageSingle));
this.disposeWithMe(componentManager.register(TEXT_ICON_ID, TextSingle));
this.disposeWithMe(componentManager.register(GRAPH_SINGLE_ICON, GraphSingle));
- this.disposeWithMe(componentManager.register(COMPONENT_UPLOAD_FILE_MENU, UploadFileMenu));
this.disposeWithMe(componentManager.register(COMPONENT_SLIDE_IMAGE_POPUP_MENU, SlideImagePopupMenu));
this.disposeWithMe(componentManager.register(COMPONENT_SLIDE_SIDEBAR, Sidebar));
}
@@ -80,7 +77,7 @@ export class SlidesUIController extends Disposable {
AppendSlideOperation,
ActivateSlidePageOperation,
SetSlidePageThumbOperation,
- InsertSlideFloatImageOperation,
+ InsertSlideFloatImageCommand,
SlideAddTextOperation,
SlideAddTextCommand,
InsertSlideShapeRectangleOperation,
diff --git a/packages/slides-ui/src/index.ts b/packages/slides-ui/src/index.ts
index cbe2997b6a..6d027f505a 100644
--- a/packages/slides-ui/src/index.ts
+++ b/packages/slides-ui/src/index.ts
@@ -29,7 +29,7 @@ export { menuSchema } from './controllers/menu.schema';
// #region - all commands
export { ActivateSlidePageOperation } from './commands/operations/activate.operation';
export { DeleteSlideElementOperation } from './commands/operations/delete-element.operation';
-export { InsertSlideFloatImageOperation } from './commands/operations/insert-image.operation';
+export { InsertSlideFloatImageCommand } from './commands/operations/insert-image.operation';
export { InsertSlideShapeRectangleOperation, InsertSlideShapeRectangleCommand } from './commands/operations/insert-shape.operation';
export { SetSlidePageThumbOperation } from './commands/operations/set-thumb.operation';
export { AppendSlideOperation } from './commands/operations/append-slide.operation';
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 0708aca395..0c8d6f757a 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -32,6 +32,7 @@ export { IUIController, type IWorkbenchOptions } from './controllers/ui/ui.contr
export { type IUniverUIConfig } from './controllers/config.schema';
export { DesktopUIController } from './controllers/ui/ui-desktop.controller';
export { IUIPartsService, BuiltInUIPart, UIPartsService } from './services/parts/parts.service';
+export { type IOpenFileOptions, IFileOpenerService } from './services/file-opener/file-opener.service';
export { DesktopBeforeCloseService, IBeforeCloseService } from './services/before-close/before-close.service';
export { CopyCommand, CutCommand, PasteCommand } from './services/clipboard/clipboard.command';
export {
diff --git a/packages/ui/src/services/file-opener/desktop-file-opener.service.tsx b/packages/ui/src/services/file-opener/desktop-file-opener.service.tsx
new file mode 100644
index 0000000000..481853ce9a
--- /dev/null
+++ b/packages/ui/src/services/file-opener/desktop-file-opener.service.tsx
@@ -0,0 +1,97 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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.
+ */
+
+/* eslint-disable react-refresh/only-export-components */
+
+import React, { useCallback, useEffect, useRef } from 'react';
+
+import { connectInjector, Disposable, Inject, Injector, useDependency, useObservable } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { BuiltInUIPart, IUIPartsService } from '../parts/parts.service';
+import type { IOpenFileOptions } from './file-opener.service';
+import { IFileOpenerService } from './file-opener.service';
+
+interface IOpenFileRequest extends IOpenFileOptions {
+ onFileSelected: (files: File[]) => void;
+}
+
+export class DesktopFileOpenerService extends Disposable implements IFileOpenerService {
+ private readonly _fileOpenRequest$ = new Subject<IOpenFileRequest | null>();
+ readonly fileOpenRequest$ = this._fileOpenRequest$.asObservable();
+
+ constructor(
+ @Inject(Injector) injector: Injector,
+ @IUIPartsService private readonly _uiPartsService: IUIPartsService
+ ) {
+ super();
+
+ this.disposeWithMe(this._uiPartsService.registerComponent(
+ BuiltInUIPart.GLOBAL, () => connectInjector(DesktopFileOpenerWrapper, injector)));
+ }
+
+ openFile(options?: IOpenFileOptions): Promise<File[]> {
+ // eslint-disable-next-line ts/no-this-alias
+ const service = this;
+
+ return new Promise((resolve) => {
+ const request: IOpenFileRequest = {
+ ...options,
+ onFileSelected(files) {
+ resolve(files);
+ service._fileOpenRequest$.next(null);
+ },
+ };
+
+ this._fileOpenRequest$.next(request);
+ });
+ }
+}
+
+function DesktopFileOpener(props: { request: IOpenFileRequest }) {
+ const { request } = props;
+ const { accept, onFileSelected, multiple } = request;
+ const fileInputRef = useRef<HTMLInputElement>(null);
+
+ const handleFileChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
+ const fileList = event.target.files;
+ onFileSelected(fileList ? Array.from(fileList) : []);
+
+ if (fileInputRef.current) fileInputRef.current.value = '';
+ }, [onFileSelected]);
+
+ useEffect(() => {
+ if (fileInputRef.current) fileInputRef.current.click();
+ }, []);
+
+ return (
+ <input
+ type="file"
+ ref={fileInputRef}
+ onChange={handleFileChange}
+ accept={accept}
+ multiple={multiple}
+ />
+ );
+}
+
+function DesktopFileOpenerWrapper() {
+ const desktopFileOpenerService = useDependency(IFileOpenerService) as DesktopFileOpenerService;
+ const request = useObservable(desktopFileOpenerService.fileOpenRequest$, null);
+
+ if (!request) return null;
+ return <DesktopFileOpener request={request} />;
+}
+
diff --git a/packages/slides-ui/src/components/upload-component/component-name.ts b/packages/ui/src/services/file-opener/file-opener.service.ts
similarity index 61%
rename from packages/slides-ui/src/components/upload-component/component-name.ts
rename to packages/ui/src/services/file-opener/file-opener.service.ts
index 8de3b86201..e7b7da5364 100644
--- a/packages/slides-ui/src/components/upload-component/component-name.ts
+++ b/packages/ui/src/services/file-opener/file-opener.service.ts
@@ -14,9 +14,19 @@
* limitations under the License.
*/
-export const COMPONENT_UPLOAD_FILE_MENU = 'SLIDE_COMPONENT_UPLOAD_FILE_MENU';
+import { createIdentifier } from '@univerjs/core';
-export enum UploadFileType {
- cellImage,
- floatImage,
+export interface IOpenFileOptions {
+ accept?: string;
+ multiple?: boolean;
}
+
+export interface IFileOpenerService {
+ openFile(options?: IOpenFileOptions): Promise<File[]>;
+}
+
+/**
+ * This service is used to upload files.
+ */
+export const IFileOpenerService = createIdentifier<IFileOpenerService>('univer.ui.file-opener.service');
+
diff --git a/packages/ui/src/ui-plugin.ts b/packages/ui/src/ui-plugin.ts
index 21a624d3eb..c3d9304983 100644
--- a/packages/ui/src/ui-plugin.ts
+++ b/packages/ui/src/ui-plugin.ts
@@ -57,6 +57,8 @@ import { CanvasFloatDomService } from './services/dom/canvas-dom-layer.service';
import { IMenuManagerService, MenuManagerService } from './services/menu/menu-manager.service';
import type { IUniverUIConfig } from './controllers/config.schema';
import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';
+import { IFileOpenerService } from './services/file-opener/file-opener.service';
+import { DesktopFileOpenerService } from './services/file-opener/desktop-file-opener.service';
export const UNIVER_UI_PLUGIN_NAME = 'UNIVER_UI_PLUGIN';
@@ -111,6 +113,7 @@ export class UniverUIPlugin extends Plugin {
[IMessageService, { useClass: DesktopMessageService, lazy: true }],
[ILocalStorageService, { useClass: DesktopLocalStorageService, lazy: true }],
[IBeforeCloseService, { useClass: DesktopBeforeCloseService }],
+ [IFileOpenerService, { useClass: DesktopFileOpenerService }],
[IEditorService, { useClass: EditorService }],
[IRangeSelectorService, { useClass: RangeSelectorService }],
[ICanvasPopupService, { useClass: CanvasPopupService }],