Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
feat(drawing): preserve and manage OLE attachments across Office hosts (#7961)
Univer4e6a56e45c86
diff --git a/README.md b/README.mdindex 707496d9b2..3584e4b61a 100644--- a/README.md+++ b/README.md@@ -385,6 +385,7 @@ Repository-local notes worth reading before deeper changes:- [Naming Convention](./docs/NAMING_CONVENTION.md): file, folder, interface, plugin, command, and dependency injection token conventions.- [Fixing Memory Leaks](./docs/FIX_MEMORY_LEAK.md): common leak patterns and debugging workflow for Univer instances.- [Architecture TLDRs](./docs/tldr): concise notes for formula engine, web worker, permission, selection, and ref-range behavior.+- [OLE attachments](./packages/drawing/docs/ole-attachments.md): drawing resources, JSON and online transport, previews, and optional Pro conversion integration.## 💬 Communitydiff --git a/packages/core/src/types/interfaces/i-drawing.ts b/packages/core/src/types/interfaces/i-drawing.tsindex 4d28fc6eab..2c6829dae1 100644--- a/packages/core/src/types/interfaces/i-drawing.ts+++ b/packages/core/src/types/interfaces/i-drawing.ts@@ -96,6 +96,8 @@ export enum DrawingTypeEnum {* Spreadsheet Timeline control.*/DRAWING_TIMELINE = 11,+ /** Independent Office attachment; its preview image is separate from its original file. */+ DRAWING_OLE = 12,}export type DrawingType = DrawingTypeEnum | number;diff --git a/packages/docs-drawing-ui/package.json b/packages/docs-drawing-ui/package.jsonindex 6b745b274c..390d39a46b 100644--- a/packages/docs-drawing-ui/package.json+++ b/packages/docs-drawing-ui/package.json@@ -83,12 +83,12 @@"@univerjs/drawing-ui": "workspace:*","@univerjs/engine-render": "workspace:*","@univerjs/icons": "1.47.0",+ "@univerjs/protocol": "workspace:*","@univerjs/ui": "workspace:*"},"devDependencies": {"@testing-library/react": "^16.3.3","@univerjs-infra/shared": "workspace:*",- "@univerjs/protocol": "workspace:*","postcss": "^8.5.32","react": "18.3.1","rxjs": "7.8.2",diff --git a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex 33e3403c2e..f127ed29b7 100644--- a/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/docs-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -701,8 +701,35 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});- it('deletes a focused drawing through the command pipeline and removes it from the document and services', async () => {- const testBed = setupDrawingTestBed(createDrawingDocData());+ it('persists an OLE online link in the document and restores it through undo and redo', async () => {+ const data = createDrawingDocData();+ Object.assign(data.drawings!['shape-1'], { drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'retained' });+ const testBed = setupDrawingTestBed(data);+ vi.spyOn(testBed.get(DocSkeletonManagerService), 'getSkeleton').mockReturnValue({} as never);+ const doc = testBed.get(IUniverInstanceService).getUnit<DocumentDataModel>('test-doc', UniverInstanceType.UNIVER_DOC)!;+ const online = { unitId: 'child', type: UniverInstanceType.UNIVER_SHEET };+ expect(await testBed.commandService.executeCommand<IUpdateDrawingDocTransformCommandParams>(UpdateDrawingDocTransformCommand.id, {+ unitId: 'test-doc',+ subUnitId: 'test-doc',+ drawings: [{ drawingId: 'shape-1', key: 'oleOnlineUnit', value: online }, { drawingId: 'shape-1', key: 'oleFileName', value: '预算.xlsx' }],+ })).toBe(true);+ await awaitTime(350);+ const read = () => JSON.parse(JSON.stringify(doc.getSnapshot().drawings!['shape-1']));+ expect(read()).toMatchObject({ oleAttachmentId: 'retained', oleOnlineUnit: online, oleFileName: '预算.xlsx' });+ expect(await testBed.commandService.executeCommand(UndoCommand.id)).toBe(true);+ expect(read()).not.toHaveProperty('oleOnlineUnit');+ expect(read()).not.toHaveProperty('oleFileName');+ expect(await testBed.commandService.executeCommand(RedoCommand.id)).toBe(true);+ expect(read()).toMatchObject({ oleOnlineUnit: online, oleFileName: '预算.xlsx' });+ testBed.univer.dispose();+ });++ it.each([false, true])('deletes a focused drawing through the command pipeline and removes it from the document and services (OLE: %s)', async (ole) => {+ const data = createDrawingDocData();+ if (ole) {+ Object.assign(data.drawings!['shape-1'], { drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'retained-attachment' });+ }+ const testBed = setupDrawingTestBed(data);testBed.docDrawingService.focusDrawing([{ unitId: 'test-doc', subUnitId: 'test-doc', drawingId: 'shape-1' }]);@@ -856,8 +883,12 @@ describe('docs drawing commands integration', () => {testBed.univer.dispose();});- it('moves a focused floating drawing by updating the persisted doc transform', async () => {- const testBed = setupDrawingTestBed(createDrawingDocData());+ it.each([false, true])('moves a focused floating drawing by updating the persisted doc transform (OLE: %s)', async (ole) => {+ const data = createDrawingDocData();+ if (ole) {+ Object.assign(data.drawings!['shape-1'], { drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'retained-attachment' });+ }+ const testBed = setupDrawingTestBed(data);vi.spyOn(testBed.get(DocSkeletonManagerService), 'getSkeleton').mockReturnValue({getSkeletonData: () => null,} as never);diff --git a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.tsindex 3f50cd42c0..3212e269a6 100644--- a/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.ts+++ b/packages/docs-drawing-ui/src/controllers/__tests__/doc-drawing-printing.controller.spec.ts@@ -40,7 +40,7 @@ import {} from '@univerjs/core';import { DocPrintInterceptorService } from '@univerjs/docs-ui';import { DrawingManagerService, getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';-import { DrawingImageClipService, DrawingRenderService } from '@univerjs/drawing-ui';+import { DrawingImageClipService, DrawingRenderService, OleUIService } from '@univerjs/drawing-ui';import { Documents, DocumentSkeleton, DocumentViewModel, Engine, Scene } from '@univerjs/engine-render';import { ComponentManager, IGalleryService } from '@univerjs/ui';import { EMPTY, Subject } from 'rxjs';@@ -104,6 +104,7 @@ describe('DocDrawingPrintingController with real layout and drawing services', (} }]);injector.add([DrawingImageClipService]);injector.add([DrawingRenderService]);+ injector.add([OleUIService, { useValue: { bindObject: vi.fn() } as never }]);injector.add([ComponentManager]);injector.add([DocPrintInterceptorService]);injector.add([DocDrawingPrintingController]);@@ -221,10 +222,12 @@ describe('DocDrawingPrintingController with real layout and drawing services', (}it('prints table-cell images with their host page and omits the other body page', () => {+ const render = vi.spyOn(univer.__getInjector().get(DrawingRenderService), 'renderDrawing');const page = skeleton.getSkeletonData()!.pages[0];expect(page.skeTables.get('table')!.rows[0].cells[0].skeDrawings.has('cell-image')).toBe(true);collect(0);expect(renderedImageIds()).toEqual(['body-first', 'cell-image', 'header-image', 'footer-image']);+ expect(render.mock.calls.every((call) => call[2]?.interactive === false)).toBe(true);});it('prints repeated header and footer images on the second page', () => {diff --git a/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.ts b/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.tsindex 4f2f2708ad..935e200379 100644--- a/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.ts+++ b/packages/docs-drawing-ui/src/controllers/doc-drawing-printing.controller.ts@@ -53,7 +53,7 @@ export class DocDrawingPrintingController extends Disposable {}const drawing = subUnitData.data[id];if (drawing.drawingType !== DrawingTypeEnum.DRAWING_CHART && drawing.drawingType !== DrawingTypeEnum.DRAWING_DOM) {- this._drawingRenderService.renderDrawing(drawing, scene);+ this._drawingRenderService.renderDrawing(drawing, scene, { interactive: false });}});}diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.tsindex f9100a9bcf..b76e0281b6 100644--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-transform-update.controller.spec.ts@@ -32,12 +32,34 @@ import {} from '@univerjs/core';import { DocSkeletonManagerService, RichTextEditingMutation } from '@univerjs/docs';import { EditorService, IEditorService } from '@univerjs/docs-ui';-import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';-import { DrawingImageClipService, DrawingRenderService } from '@univerjs/drawing-ui';+import {+ getDrawingShapeKeyByDrawingSearch,+ IDrawingManagerService,+ OleService,+ SetDrawingSelectedOperation,+} from '@univerjs/drawing';+import { DrawingImageClipService, DrawingRenderService, OleUIService } from '@univerjs/drawing-ui';import { DrawingUpdateController } from '@univerjs/drawing-ui/controllers/drawing-update.controller.ts';import { ImageUpdateController } from '@univerjs/drawing-ui/controllers/image-update.controller.ts';-import { Documents, DocumentSkeletonPageType, Liquid, Rect, setDocsTableRenderViewportProvider } from '@univerjs/engine-render';-import { DesktopGalleryService, IGalleryService, IUIPartsService, UIPartsService } from '@univerjs/ui';+import {+ Documents,+ DocumentSkeletonPageType,+ Liquid,+ Rect,+ setDocsTableRenderViewportProvider,+} from '@univerjs/engine-render';+import {+ DesktopDialogService,+ DesktopGalleryService,+ DesktopMessageService,+ DesktopNotificationService,+ IDialogService,+ IGalleryService,+ IMessageService,+ INotificationService,+ IUIPartsService,+ UIPartsService,+} from '@univerjs/ui';import { EMPTY, Subject } from 'rxjs';import { afterEach, describe, expect, it, vi } from 'vitest';import type { DocumentDrawingPublicationProgress } from '../doc-drawing-transform-update.controller';@@ -106,6 +128,11 @@ async function createRepeatedImageTestBed(unitId: string) {} }]);injector.add([IUIPartsService, { useClass: UIPartsService }]);injector.add([IGalleryService, { useClass: DesktopGalleryService }]);+ injector.add([IDialogService, { useClass: DesktopDialogService }]);+ injector.add([IMessageService, { useClass: DesktopMessageService }]);+ injector.add([INotificationService, { useClass: DesktopNotificationService }]);+ injector.add([OleService]);+ injector.add([OleUIService]);injector.add([DrawingImageClipService]);injector.add([DrawingRenderService]);injector.add([DrawingUpdateController]);diff --git a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.tsindex cf8f4fa63f..cbecc1c6d1 100644--- a/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts+++ b/packages/docs-drawing-ui/src/controllers/render-controllers/__tests__/doc-drawing-update.render-controller.spec.ts@@ -511,11 +511,12 @@ describe('DocDrawingUpdateRenderController', () => {expect(getShape('body-drawing').setOpacity).toHaveBeenLastCalledWith(0.5);});- it('removes read-only drawings from picking and transformer interaction, then restores both', async () => {+ it.each([DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_OLE])('keeps read-only drawings unmodifiable while preserving OLE browsing (%s)', async (drawingType) => {const { getShape, permissionService, scene, transformer } = createController({drawings: {'body-drawing': {drawingId: 'body-drawing',+ drawingType,isMultiTransform: BooleanNumber.FALSE,},},@@ -523,7 +524,7 @@ describe('DocDrawingUpdateRenderController', () => {setDocumentPermissionValue(permissionService, 'doc-1', 'doc-1', UnitAction.Edit, false);- expect(getShape('body-drawing').evented).toBe(false);+ expect(getShape('body-drawing').evented).toBe(drawingType === DrawingTypeEnum.DRAWING_OLE);expect(transformer.clearControlByIds).toHaveBeenCalledWith(['doc-1#-#doc-1#-#body-drawing']);expect(getShape('body-drawing').transformerConfig).toMatchObject({moveEnabled: false,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.tsindex 4e615b0f8e..12f97add5d 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@@ -523,7 +523,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRenif (drawingShapes.length) {for (const shape of drawingShapes) {scene.detachTransformerFrom(shape);- this._setTransformerEditable(shape, editable);+ this._setTransformerEditable(shape, editable, drawing);try {// Repeated header/footer drawings are faded by the content cover,// never individually: an opaque picture must still hide pictures below it.@@ -595,7 +595,7 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRen}}- private _setTransformerEditable(shape: BaseObject, editable: boolean): void {+ private _setTransformerEditable(shape: BaseObject, editable: boolean, drawing: IDocDrawing): void {if (editable) {const config = this._editableTransformerConfigs.get(shape);if (config) {@@ -616,7 +616,8 @@ export class DocDrawingUpdateRenderController extends Disposable implements IRenif (!this._editableEventedStates.has(shape)) {this._editableEventedStates.set(shape, shape.evented);}- shape.evented = false;+ // OLE attachments remain browsable without enabling drawing transforms.+ shape.evented = drawing.drawingType === DrawingTypeEnum.DRAWING_OLE;this._context.scene.getTransformer()?.clearControlByIds([shape.oKey]);shape.transformerConfig = {...shape.transformerConfig,diff --git a/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts b/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.tsindex aa3a83ce04..2b520cc9b7 100644--- a/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts+++ b/packages/docs-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts@@ -28,16 +28,20 @@ import {toDisposable,} from '@univerjs/core';import { setDocumentPermissionValue } from '@univerjs/docs';-import { DocDrawingService, IDocDrawingAdapterService, IDocDrawingService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';+import {+ DocDrawingService,+ IDocDrawingAdapterService,+ IDocDrawingService,+ RemoveDocDrawingCommand,+} from '@univerjs/docs-drawing';import { DocCanvasPopManagerService, MOBILE_DOC_ELEMENT_MENU } from '@univerjs/docs-ui';import { IDrawingManagerService } from '@univerjs/drawing';-import { COMPONENT_MOBILE_IMAGE_POPUP_MENU, OpenImageCropOperation } from '@univerjs/drawing-ui';+import { COMPONENT_MOBILE_IMAGE_POPUP_MENU, OleUIService, OpenImageCropOperation } from '@univerjs/drawing-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { UnitAction } from '@univerjs/protocol';import { ContextMenuPosition, IContextMenuService, IMenuManagerService } from '@univerjs/ui';import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';-import { EditDocDrawingOperation } from '../../commands/operations/edit-doc-drawing.operation';import { MobileDocDrawingPopupMenuController } from '../../controllers/mobile/drawing-popup-menu.controller';import { DocDrawingFloatingToolbarAdapterService } from '../../services/doc-drawing-floating-toolbar-adapter.service';@@ -47,6 +51,7 @@ function createControllerHarness(drawingType = DrawingTypeEnum.DRAWING_IMAGE, moconst unitId = 'doc-1';const drawingId = 'drawing-1';const injector = new Injector();+ injector.add([OleUIService, { useValue: { registerHost: () => toDisposable(() => undefined) } as never }]);const createControl$ = new Subject<void>();const clearControl$ = new Subject<boolean>();const changing$ = new Subject<void>();diff --git a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.tsindex 5a321adfaa..569bc2b388 100644--- a/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts+++ b/packages/docs-drawing-ui/src/menu/drawing-popup-menu.controller.ts@@ -15,6 +15,7 @@*/import type { DocumentDataModel, IDisposable, INeedCheckDisposable, Nullable } from '@univerjs/core';+import type { IOlePreviewContext } from '@univerjs/drawing-ui';import type { BaseObject, Scene } from '@univerjs/engine-render';import {DrawingTypeEnum,@@ -34,17 +35,30 @@ import {getDocumentDrawingSegmentId,getDocumentEntityParentPermissionObjectIds,getDocumentEntityPermissionObjectId,+ getDocumentPermissionValue,+ setDocumentPermissionValue,+ UniverDocsPlugin,} from '@univerjs/docs';-import { IDocDrawingAdapterService, IDocDrawingService, RemoveDocDrawingCommand } from '@univerjs/docs-drawing';-import { DocCanvasPopManagerService } from '@univerjs/docs-ui';+import {+ IDocDrawingAdapterService,+ IDocDrawingService,+ RemoveDocDrawingCommand,+ UniverDocsDrawingPlugin,+ UpdateDrawingDocTransformCommand,+} from '@univerjs/docs-drawing';+import { DocCanvasPopManagerService, DocPageLayoutService, UniverDocsUIPlugin } from '@univerjs/docs-ui';import { IDrawingManagerService } from '@univerjs/drawing';import {COMPONENT_IMAGE_POPUP_MENU,+ createOlePreviewViewer,ImageCropperObject,ImageResetSizeOperation,+ OleUIService,OpenImageCropOperation,+ registerOlePreviewRenderer,} from '@univerjs/drawing-ui';import { IRenderManagerService } from '@univerjs/engine-render';+import { UnitAction } from '@univerjs/protocol';import {ContextMenuPosition,FloatingObjectToolbarPosition,@@ -55,6 +69,7 @@ import {import { takeUntil } from 'rxjs';import { EditDocDrawingOperation } from '../commands/operations/edit-doc-drawing.operation';import { SidebarDocDrawingOperation } from '../commands/operations/open-drawing-panel.operation';+import { UniverDocsDrawingUIPlugin } from '../plugin';import { DocDrawingFloatingToolbarAdapterService } from '../services/doc-drawing-floating-toolbar-adapter.service';interface IDrawingPopupTarget {@@ -83,10 +98,19 @@ export class DocDrawingPopupMenuController extends RxDisposable {@ICommandService private readonly _commandService: ICommandService,@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@IPermissionService private readonly _permissionService: IPermissionService,- @IContextMenuService private readonly _contextMenuService: IContextMenuService+ @IContextMenuService private readonly _contextMenuService: IContextMenuService,+ @Inject(OleUIService) private readonly _oleUI: OleUIService) {super();+ this.disposeWithMe(this._oleUI.registerHost(UniverInstanceType.UNIVER_DOC, {+ isEditable: (drawing) => this._drawingManagerService.getDrawingEditable() && getDocumentPermissionValue(this._permissionService, drawing.unitId, drawing.unitId, UnitAction.Edit),+ attach: (object, componentKey, extraProps, drawing, direction = 'top-center') => this._canvasPopManagerService.attachPopupToObject(object, { componentKey, extraProps, direction, portal: true, offset: direction === 'top-center' ? [0, 8] : [0, 0] }, drawing.unitId),+ rename: (drawing, name) => this._commandService.executeCommand(UpdateDrawingDocTransformCommand.id, { unitId: drawing.unitId, subUnitId: drawing.subUnitId, drawings: [{ drawingId: drawing.drawingId, key: 'oleFileName', value: name }] }),+ saveOnlineUnit: (drawing, online) => this._commandService.executeCommand(UpdateDrawingDocTransformCommand.id, { unitId: drawing.unitId, subUnitId: drawing.subUnitId, drawings: [{ drawingId: drawing.drawingId, key: 'oleOnlineUnit', value: online }] }),+ remove: (drawing) => this._commandService.executeCommand(RemoveDocDrawingCommand.id, { unitId: drawing.unitId, drawings: [{ ...drawing, drawingType: DrawingTypeEnum.DRAWING_OLE }] }),+ }));+this._init();}@@ -337,6 +361,7 @@ export class DocDrawingPopupMenuController extends RxDisposable {if (!drawingParam ||drawingParam.drawingType === DrawingTypeEnum.DRAWING_DOM ||+ drawingParam.drawingType === DrawingTypeEnum.DRAWING_OLE ||drawingParam.drawingType === DrawingTypeEnum.DRAWING_SHAPE) {this._clearPopups(unitId);@@ -471,3 +496,14 @@ export class DocDrawingPopupMenuController extends RxDisposable {});}}++function createDocOlePreview(context: IOlePreviewContext): IDisposable {+ return createOlePreviewViewer({ ...context, onResize: (render) => render.with(DocPageLayoutService).calculatePagePosition(), setReadonly: (permissions, unitId) => setDocumentPermissionValue(permissions, unitId, unitId, UnitAction.Edit, false), register: (viewer) => {+ viewer.registerPlugin(UniverDocsPlugin);+ viewer.registerPlugin(UniverDocsUIPlugin);+ viewer.registerPlugin(UniverDocsDrawingPlugin);+ viewer.registerPlugin(UniverDocsDrawingUIPlugin);+ } });+}++registerOlePreviewRenderer(UniverInstanceType.UNIVER_DOC, createDocOlePreview);diff --git a/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts b/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.tsindex 7731a6dac9..b6a7b28c12 100644--- a/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts+++ b/packages/docs-drawing/src/commands/commands/update-doc-drawing-transform.command.ts@@ -14,8 +14,19 @@* limitations under the License.*/-import type { DocumentDataModel, IAccessor, ICommand, IObjectPositionH, IObjectPositionV, ISize, ISrcRect, JSONXActions, Nullable } from '@univerjs/core';+import type {+ DocumentDataModel,+ IAccessor,+ ICommand,+ IObjectPositionH,+ IObjectPositionV,+ ISize,+ ISrcRect,+ JSONXActions,+ Nullable,+} from '@univerjs/core';import type { IRichTextEditingMutationParams } from '@univerjs/docs';+import type { IOleOnlineUnit } from '@univerjs/drawing';import type { IDocImage } from '../../services/doc-drawing.service';import {CommandType,@@ -27,13 +38,12 @@ import {UniverInstanceType,} from '@univerjs/core';import { DocHistoryAction, RichTextEditingMutation } from '@univerjs/docs';-import { findDocDrawing } from '../../services/doc-drawing-source';export interface IDrawingDocTransform {drawingId: string;- key: 'size' | 'angle' | 'positionH' | 'positionV' | 'flipX' | 'flipY' | 'srcRect' | 'prstGeom' | 'adjustValues';- value: ISize | number | boolean | IObjectPositionH | IObjectPositionV | Nullable<ISrcRect> | IDocImage['prstGeom'] | IDocImage['adjustValues'];+ key: 'size' | 'angle' | 'positionH' | 'positionV' | 'flipX' | 'flipY' | 'srcRect' | 'prstGeom' | 'adjustValues' | 'oleOnlineUnit' | 'oleFileName';+ value: ISize | number | boolean | IObjectPositionH | IObjectPositionV | Nullable<ISrcRect> | IDocImage['prstGeom'] | IDocImage['adjustValues'] | IOleOnlineUnit | string;}export interface IUpdateDrawingDocTransformCommandParams {@@ -74,12 +84,15 @@ export const UpdateDrawingDocTransformCommand: ICommand = {return false;}const oldDrawing = source.drawing;- const isImageProperty = key === 'srcRect' || key === 'prstGeom' || key === 'adjustValues';- const oldValue = isImageProperty+ if ((key === 'oleOnlineUnit' || key === 'oleFileName') && oldDrawing.drawingType !== DrawingTypeEnum.DRAWING_OLE) {+ return false;+ }+ const isDrawingProperty = key === 'srcRect' || key === 'prstGeom' || key === 'adjustValues' || key === 'oleOnlineUnit' || key === 'oleFileName';+ const oldValue = isDrawingProperty? (key in oldDrawing ? Reflect.get(oldDrawing, key) : undefined): oldDrawing?.docTransform?.[key];if (!Tools.diffValue(oldValue, value)) {- const path = isImageProperty+ const path = isDrawingProperty? [...source.path, key]: [...source.path, 'docTransform', key];// Optional transform fields such as flips do not exist in older documents.diff --git a/packages/docs-ui/src/controllers/__tests__/ui.controller.spec.ts b/packages/docs-ui/src/controllers/__tests__/ui.controller.spec.tsnew file mode 100644index 0000000000..e1fa61265f--- /dev/null+++ b/packages/docs-ui/src/controllers/__tests__/ui.controller.spec.ts@@ -0,0 +1,91 @@+/**+ * 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.+ */++// @vitest-environment happy-dom++import type { DocumentDataModel, IDocumentData } from '@univerjs/core';+import { ICommandService, IPermissionService, IUniverInstanceService, Univer, UniverInstanceType } from '@univerjs/core';+import { setDocumentPermissionValue, UniverDocsPlugin } from '@univerjs/docs';+import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';+import { UnitAction } from '@univerjs/protocol';+import {+ DesktopLayoutService,+ ILayoutService,+ IMenuManagerService,+ IPlatformService,+ IShortcutService,+ IUIPartsService,+ IUIRuntimeScopeService,+ MenuManagerService,+ PlatformService,+ ShortcutService,+ UIPartsService,+ UIRuntimeScopeService,+} from '@univerjs/ui';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { RefreshHeaderFooterFieldsCommand } from '../../commands/commands/refresh-header-footer-fields.command';+import { DocUIController } from '../ui.controller';++const cleanups: Array<() => void> = [];+afterEach(() => cleanups.splice(0).reverse().forEach((dispose) => dispose()));++function createTestBed(editable: boolean) {+ const univer = new Univer();+ cleanups.push(() => univer.dispose());+ const injector = univer.__getInjector();+ injector.add([IRenderManagerService, { useClass: RenderManagerService }]);+ injector.add([ILayoutService, { useClass: DesktopLayoutService }]);+ injector.add([IMenuManagerService, { useClass: MenuManagerService }]);+ injector.add([IUIPartsService, { useClass: UIPartsService }]);+ injector.add([IPlatformService, { useClass: PlatformService }]);+ injector.add([IUIRuntimeScopeService, { useClass: UIRuntimeScopeService }]);+ injector.add([IShortcutService, { useClass: ShortcutService }]);+ injector.add([DocUIController]);+ univer.registerPlugin(UniverDocsPlugin);+ const instances = injector.get(IUniverInstanceService);+ const model = instances.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, { id: 'field-refresh-doc', body: { dataStream: 'Read me\r\n' }, documentStyle: {} }, { makeCurrent: false });+ const other = instances.createUnit<IDocumentData, DocumentDataModel>(UniverInstanceType.UNIVER_DOC, { id: 'other-doc', body: { dataStream: 'Other\r\n' }, documentStyle: {} }, { makeCurrent: false });+ const permissions = injector.get(IPermissionService);+ setDocumentPermissionValue(permissions, model.getUnitId(), model.getUnitId(), UnitAction.Edit, editable);+ const commandService = injector.get(ICommandService);+ const syncExecuteCommand = vi.spyOn(commandService, 'syncExecuteCommand');+ injector.get(DocUIController);+ return { instances, model, other, permissions, syncExecuteCommand };+}++describe('Doc UI automatic field refresh', () => {+ it.each([false, true])('refreshes on open only when the current document is editable (editable: %s)', (editable) => {+ const h = createTestBed(editable);+ h.instances.setCurrentUnitForType(h.model.getUnitId());+ h.instances.setCurrentUnitForType(h.model.getUnitId());+ expect(h.syncExecuteCommand.mock.calls.filter(([id]) => id === RefreshHeaderFooterFieldsCommand.id)).toEqual(editable+ ? [[RefreshHeaderFooterFieldsCommand.id, { unitId: h.model.getUnitId(), onOpen: true }]]+ : []);+ });++ it('does not mark a skipped readonly document as refreshed before a later editable focus', () => {+ const h = createTestBed(false);+ h.instances.setCurrentUnitForType(h.model.getUnitId());+ expect(h.syncExecuteCommand.mock.calls.filter(([id]) => id === RefreshHeaderFooterFieldsCommand.id)).toEqual([]);+ setDocumentPermissionValue(h.permissions, h.model.getUnitId(), h.model.getUnitId(), UnitAction.Edit, true);+ h.instances.setCurrentUnitForType(h.other.getUnitId());+ h.instances.setCurrentUnitForType(h.model.getUnitId());+ h.instances.setCurrentUnitForType(h.other.getUnitId());+ h.instances.setCurrentUnitForType(h.model.getUnitId());+ expect(h.syncExecuteCommand.mock.calls.filter(([id, params]) => id === RefreshHeaderFooterFieldsCommand.id && (params as { unitId: string }).unitId === h.model.getUnitId()))+ .toEqual([[RefreshHeaderFooterFieldsCommand.id, { unitId: h.model.getUnitId(), onOpen: true }]]);+ });+});diff --git a/packages/docs-ui/src/controllers/ui.controller.ts b/packages/docs-ui/src/controllers/ui.controller.tsindex b5879a1320..05b9f2b4e7 100644--- a/packages/docs-ui/src/controllers/ui.controller.ts+++ b/packages/docs-ui/src/controllers/ui.controller.ts@@ -21,11 +21,14 @@ import {IConfigService,Inject,Injector,+ IPermissionService,IUniverInstanceService,Optional,UniverInstanceType,} from '@univerjs/core';+import { getDocumentPermissionValue } from '@univerjs/docs';import { IRenderManagerService } from '@univerjs/engine-render';+import { UnitAction } from '@univerjs/protocol';import {BuiltInUIPart,connectInjector,@@ -143,10 +146,15 @@ export class DocUIController extends Disposable {private _initDateTimeFields(): void {const refreshed = new WeakSet<DocumentDataModel>();this.disposeWithMe(this._univerInstanceService.getCurrentTypeOfUnit$<DocumentDataModel>(UniverInstanceType.UNIVER_DOC).subscribe((model) => {- if (model && !refreshed.has(model)) {- refreshed.add(model);- this._commandService.syncExecuteCommand(RefreshHeaderFooterFieldsCommand.id, { unitId: model.getUnitId(), onOpen: true });+ if (!model || refreshed.has(model)) {+ return;}+ const unitId = model.getUnitId();+ if (!getDocumentPermissionValue(this._injector.get(IPermissionService), unitId, unitId, UnitAction.Edit)) {+ return;+ }+ refreshed.add(model);+ this._commandService.syncExecuteCommand(RefreshHeaderFooterFieldsCommand.id, { unitId, onOpen: true });}));}diff --git a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.tsindex ac090434eb..e4639f24f6 100644--- a/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts+++ b/packages/docs-ui/src/services/selection/__tests__/doc-selection-render.service.spec.ts@@ -359,12 +359,16 @@ function createRealSelectionRenderService(options: {documentData?: IDocumentData;embedInteractionBoundaryService?: Partial<EmbedInteractionBoundaryService>;embedRuntimeFocusCoordinator?: EmbedRuntimeFocusCoordinator;+ layoutMounted?: boolean;mainComponent?: unknown;mobile?: boolean;scene?: unknown;unitId?: string;} = {}) {TestLayoutService.reset();+ if (options.layoutMounted === false) {+ TestLayoutService.root.remove();+ }TestDocSkeletonManagerService.reset();const univer = new Univer();const injector = univer.__getInjector();@@ -1203,6 +1207,22 @@ describe('DocSelectionRenderService', () => {expect(focusSpy).toHaveBeenCalledTimes(2);});+ it.each(['focus', 'sync'] as const)('keeps %s inside a modal after its layout mounts late', (action) => {+ const { input, renderUnit, service, univer } = createRealSelectionRenderService({ layoutMounted: false });+ cleanup.push(() => renderUnit.dispose(), () => univer.dispose());+ expect(service.selectionContainer.parentElement).toBe(document.body);++ const dialog = document.createElement('div');+ dialog.setAttribute('role', 'dialog');+ dialog.appendChild(TestLayoutService.root);+ document.body.appendChild(dialog);++ service[action]();++ expect(document.activeElement).toBe(input);+ expect(dialog.contains(document.activeElement)).toBe(true);+ });+it('does not steal focus back from an embedded runtime during selection sync', () => {const embedCanvas = document.createElement('canvas');embedCanvas.tabIndex = 0;diff --git a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts b/packages/docs-ui/src/services/selection/doc-selection-render.service.tsindex 4355f21bf6..9b73296a88 100644--- a/packages/docs-ui/src/services/selection/doc-selection-render.service.ts+++ b/packages/docs-ui/src/services/selection/doc-selection-render.service.ts@@ -621,6 +621,8 @@ export class DocSelectionRenderService extends RxDisposable implements IRenderMo}focus(): void {+ // The layout may mount after the input; keep focus inside its owning modal.+ this._ensureHostContainer();if (!this._input.hasAttribute('tabindex')) {this._input.tabIndex = -1;}diff --git a/packages/drawing-ui/README.md b/packages/drawing-ui/README.mdindex 8189a23033..cc0d0d030f 100644--- a/packages/drawing-ui/README.md+++ b/packages/drawing-ui/README.md@@ -34,6 +34,18 @@ univer.registerPlugin(UniverDrawingUIPlugin);// Merge EnUS into your Univer locale map when this package contributes UI text.```+## OLE online conversion++For collaborative Sheets, Docs and Slides, configure `ole.getLink` on `UniverDrawingPlugin`. The existing Pro `UniverExchangeClientPlugin` installs `ole.convertOffice`, `ole.convertToOnline` and the exact-Unit collaboration check; it preserves application-provided callbacks. Conversion keeps stage progress on the source page. The host's normal drawing mutation commands save only `{ unitId, type }` on the original drawing. After that reference is saved, a persistent completion notification offers an Open action. A new tab opens only when the user clicks Open, either in that notification or in the drawing toolbar. The original attachment is retained.++`ole.getLink(unitId, type)` synchronously resolves a relative or absolute HTTP(S) URL on every Open action, including the completion notification. It is not called during conversion. There is no default application route. Without this callback, online actions stay hidden; preview and download follow their own capabilities. Legacy stored `url` fields are ignored, so changing the configured domain or route does not require rewriting existing online references.++The shared `OleObject` in this package paints OLE attachment glyphs and captions directly on Canvas. It reuses existing engine image geometry, clipping and hit testing; OLE render paths skip native bitmap loading and caching. No additional plugin registration is required.++Common Drawing UI owns the toolbar, preview dialog and temporary viewer lifecycle. The existing `@univerjs/sheets-drawing-ui`, `@univerjs/docs-drawing-ui` and `@univerjs-pro/slides-ui` modules supply their own read-only renderers. Cross-type preview requires the target product UI module, styles and locale resources to be loaded: a Sheet-only application must also load the Doc UI module to preview Word attachments. Module loading registers a stateless renderer without creating a target Unit or requiring another OLE plugin registration. If no renderer or application override is available, Preview is disabled with a localized explanation before reading or converting the attachment; Download remains available. Applications may override `ole.previewOffice` or `ole.createOfficePreview`. See the [integration guide](../drawing/docs/ole-attachments.md).++Keep the source page open until reference saving completes. Closing the host stops local polling and progress UI; it does not delete an online Unit already created by the server. Applications own durable task recovery. A failed reference save can be retried in the same session without converting the attachment again.+## Resources- [Documentation](https://docs.univer.ai)diff --git a/packages/drawing-ui/src/__tests__/mobile-plugin.spec.ts b/packages/drawing-ui/src/__tests__/mobile-plugin.spec.tsnew file mode 100644index 0000000000..6810c55c60--- /dev/null+++ b/packages/drawing-ui/src/__tests__/mobile-plugin.spec.ts@@ -0,0 +1,52 @@+/**+ * 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.+ */++// @vitest-environment happy-dom++import { IImageIoService, IURLImageService, Univer } from '@univerjs/core';+import { IDrawingManagerService, OleService } from '@univerjs/drawing';+import { ComponentManager, IconManager, IDialogService, IGalleryService, IMessageService, INotificationService } from '@univerjs/ui';+import { EMPTY } from 'rxjs';+import { describe, expect, it, vi } from 'vitest';+import { UniverDrawingMobileUIPlugin } from '../mobile-plugin';+import { DrawingRenderService } from '../services/drawing-render.service';+import { OleUIService } from '../services/ole-ui.service';++describe('mobile drawing dependencies', () => {+ it('resolves the existing image renderer after mobile plugin startup', () => {+ const univer = new Univer();+ try {+ const injector = univer.__getInjector();+ injector.add([IImageIoService, { useValue: {} as never }]);+ injector.add([IURLImageService, { useValue: {} as never }]);+ injector.add([IGalleryService, { useValue: {} as never }]);+ injector.add([IDialogService, { useValue: {} as never }]);+ injector.add([IMessageService, { useValue: {} as never }]);+ injector.add([INotificationService, { useValue: {} as never }]);+ injector.add([IDrawingManagerService, { useValue: { focus$: EMPTY, remove$: EMPTY } as never }]);+ injector.add([OleService, { useValue: { getResource: () => undefined } as never }]);+ const register = vi.fn(() => ({ dispose: vi.fn() }));+ injector.add([ComponentManager, { useValue: { register } as never }]);+ injector.add([IconManager, { useValue: { register } as never }]);+ const plugin = injector.createInstance(UniverDrawingMobileUIPlugin, {});+ plugin.onStarting();+ expect(injector.get(DrawingRenderService)).toBeInstanceOf(DrawingRenderService);+ expect(injector.get(OleUIService)).toBeInstanceOf(OleUIService);+ } finally {+ univer.dispose();+ }+ });+});diff --git a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.tsindex b36a19a290..5efa3aba3d 100644--- a/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts+++ b/packages/drawing-ui/src/controllers/__tests__/image-update.controller.spec.ts@@ -230,7 +230,7 @@ describe('ImageUpdateController', () => {controller.dispose();});- it('applies refreshed transform, clip bounds, and behind-text layer to existing images', () => {+ it.each([DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_OLE])('updates geometry while loading bitmap sources only for images (type: %s)', (drawingType) => {const add$ = new Subject();const update$ = new Subject<Array<{ unitId: string; subUnitId: string; drawingId: string }>>();const transform = {@@ -244,7 +244,7 @@ describe('ImageUpdateController', () => {const imageParam = {behindText: true,drawingId: 'shape-3',- drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ drawingType,imageSourceType: ImageSourceType.BASE64,source: 'data:image/png;base64,Zm9v',opacity: 0.4,@@ -307,6 +307,7 @@ describe('ImageUpdateController', () => {});expect(imageShape.setClipBounds).toHaveBeenCalledWith(transform.clipBounds);expect(imageShape.setOpacity).toHaveBeenCalledWith(0.4);+ expect(imageShape.changeSource.mock.calls).toEqual(drawingType === DrawingTypeEnum.DRAWING_IMAGE ? [[imageParam.source]] : []);expect(scene.removeObject).toHaveBeenCalledWith(imageShape);expect(scene.addObject).toHaveBeenCalledWith(imageShape, DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX);});diff --git a/packages/drawing-ui/src/controllers/components.controller.ts b/packages/drawing-ui/src/controllers/components.controller.tsindex b729c8cddd..7ea6a22244 100644--- a/packages/drawing-ui/src/controllers/components.controller.ts+++ b/packages/drawing-ui/src/controllers/components.controller.ts@@ -27,15 +27,27 @@ import {UngroupIcon,} from '@univerjs/icons';import { ComponentManager, IconManager } from '@univerjs/ui';+import {+ OLE_NAME_COMPONENT,+ OLE_OFFICE_PREVIEW_COMPONENT,+ OLE_POPUP_COMPONENT,+ OLE_PREVIEW_COMPONENT,+} from '../services/ole-ui.service';import {COMPONENT_IMAGE_POPUP_MENU,} from '../views/image-popup-menu/component-name';import { ImagePopupMenu } from '../views/image-popup-menu/ImagePopupMenu';--import { DRAWING_ALIGN_COMPONENT, DRAWING_ARRANGE_COMPONENT, DRAWING_GROUP_COMPONENT, DRAWING_TRANSFORM_COMPONENT, IMAGE_CROPPER_COMPONENT } from '../views/panel/component-name';+import { OleName } from '../views/ole/OleName';+import { OleOfficePreview, OlePopup, OlePreview } from '../views/ole/OlePopup';+import {+ DRAWING_ALIGN_COMPONENT,+ DRAWING_ARRANGE_COMPONENT,+ DRAWING_GROUP_COMPONENT,+ DRAWING_TRANSFORM_COMPONENT,+ IMAGE_CROPPER_COMPONENT,+} from '../views/panel/component-name';import { DrawingAlign } from '../views/panel/DrawingAlign';import { DrawingArrange } from '../views/panel/DrawingArrange';-import { DrawingGroup } from '../views/panel/DrawingGroup';import { DrawingTransform } from '../views/panel/DrawingTransform';import { ImageCropper } from '../views/panel/ImageCropper';@@ -54,6 +66,10 @@ export class ComponentsController extends Disposable {private _registerComponents(): void {([[COMPONENT_IMAGE_POPUP_MENU, ImagePopupMenu],+ [OLE_POPUP_COMPONENT, OlePopup],+ [OLE_NAME_COMPONENT, OleName],+ [OLE_PREVIEW_COMPONENT, OlePreview],+ [OLE_OFFICE_PREVIEW_COMPONENT, OleOfficePreview],[DRAWING_ARRANGE_COMPONENT, DrawingArrange],[DRAWING_ALIGN_COMPONENT, DrawingAlign],[DRAWING_GROUP_COMPONENT, DrawingGroup],diff --git a/packages/drawing-ui/src/controllers/image-update.controller.ts b/packages/drawing-ui/src/controllers/image-update.controller.tsindex 0089650690..533e2ed31e 100644--- a/packages/drawing-ui/src/controllers/image-update.controller.ts+++ b/packages/drawing-ui/src/controllers/image-update.controller.ts@@ -27,7 +27,12 @@ import {toDisposable,UniverInstanceType,} from '@univerjs/core';-import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService, normalizeImageOpacity, SetDrawingSelectedOperation } from '@univerjs/drawing';+import {+ getDrawingShapeKeyByDrawingSearch,+ IDrawingManagerService,+ normalizeImageOpacity,+ SetDrawingSelectedOperation,+} from '@univerjs/drawing';import { CURSOR_TYPE, IRenderManagerService } from '@univerjs/engine-render';import { bufferTime, filter, map } from 'rxjs';import { ImageResetSizeOperation } from '../commands/operations/image-reset-size.operation';@@ -227,7 +232,7 @@ export class ImageUpdateController extends Disposable {const { transform, drawingType, srcRect, prstGeom, source, imageSourceType, opacity } = drawingParam;- if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {+ if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE && drawingType !== DrawingTypeEnum.DRAWING_OLE) {return;}@@ -262,7 +267,7 @@ export class ImageUpdateController extends Disposable {opacity,this._currentUniverService.getUnitType(unitId) === UniverInstanceType.UNIVER_SHEET);- if (source != null && source.length > 0 && (imageSourceType === ImageSourceType.BASE64 || imageSourceType === ImageSourceType.URL)) {+ if (drawingType === DrawingTypeEnum.DRAWING_IMAGE && source != null && source.length > 0 && (imageSourceType === ImageSourceType.BASE64 || imageSourceType === ImageSourceType.URL)) {imageShape.changeSource(source);}});@@ -289,6 +294,9 @@ export class ImageUpdateController extends Disposable {}private _addDialogForImage(o: Image) {+ if (this._drawingManagerService.getDrawingOKey(o.oKey)?.drawingType === DrawingTypeEnum.DRAWING_OLE) {+ return;+ }const preview = () => {const native = o.getNative();if (native) {diff --git a/packages/drawing-ui/src/index.ts b/packages/drawing-ui/src/index.tsindex 66278abcfc..d5d4e96f03 100644--- a/packages/drawing-ui/src/index.ts+++ b/packages/drawing-ui/src/index.ts@@ -49,6 +49,9 @@ export { UniverDrawingUIPlugin } from './plugin';export { DrawingImageClipService, IMAGE_CLIP_SHAPE_PICKER_COMPONENT } from './services/drawing-image-clip.service';export type { ImageShapeClipDelegate } from './services/drawing-image-clip.service';export { DrawingRenderService } from './services/drawing-render.service';+export { createOlePreviewViewer, registerOlePreviewRenderer } from './services/ole-preview-viewer';+export type { IOlePreviewContext } from './services/ole-preview-viewer';+export { OleUIService } from './services/ole-ui.service';export {extractClipboardHtmlImageFiles,extractClipboardImageFiles,@@ -87,4 +90,5 @@ export type {IObjectListPanelLabels,ObjectListPanelTypeNameKey,} from './views/object-list-panel/ObjectListPanelBase';+export { OleObject } from './views/ole/ole-object';export { DrawingCommonPanel } from './views/panel/DrawingCommonPanel';diff --git a/packages/drawing-ui/src/locale/__tests__/en-US.spec.ts b/packages/drawing-ui/src/locale/__tests__/en-US.spec.tsnew file mode 100644index 0000000000..0150400862--- /dev/null+++ b/packages/drawing-ui/src/locale/__tests__/en-US.spec.ts@@ -0,0 +1,84 @@+/**+ * 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 { LocaleType } from '@univerjs/core';+import { Injector, LocaleService } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import l0 from '../ar-SA';+import l1 from '../ca-ES';+import l2 from '../de-DE';+import l3 from '../en-US';+import l4 from '../es-ES';+import l5 from '../fa-IR';+import l6 from '../fr-FR';+import l7 from '../id-ID';+import l8 from '../it-IT';+import l9 from '../ja-JP';+import l10 from '../ko-KR';+import l11 from '../pl-PL';+import l12 from '../pt-BR';+import l13 from '../ru-RU';+import l14 from '../sk-SK';+import l15 from '../vi-VN';+import l16 from '../zh-CN';+import l17 from '../zh-HK';+import l18 from '../zh-TW';++const locales = {+ 'ar-SA': l0['drawing-ui'].ole,+ 'ca-ES': l1['drawing-ui'].ole,+ 'de-DE': l2['drawing-ui'].ole,+ 'en-US': l3['drawing-ui'].ole,+ 'es-ES': l4['drawing-ui'].ole,+ 'fa-IR': l5['drawing-ui'].ole,+ 'fr-FR': l6['drawing-ui'].ole,+ 'id-ID': l7['drawing-ui'].ole,+ 'it-IT': l8['drawing-ui'].ole,+ 'ja-JP': l9['drawing-ui'].ole,+ 'ko-KR': l10['drawing-ui'].ole,+ 'pl-PL': l11['drawing-ui'].ole,+ 'pt-BR': l12['drawing-ui'].ole,+ 'ru-RU': l13['drawing-ui'].ole,+ 'sk-SK': l14['drawing-ui'].ole,+ 'vi-VN': l15['drawing-ui'].ole,+ 'zh-CN': l16['drawing-ui'].ole,+ 'zh-HK': l17['drawing-ui'].ole,+ 'zh-TW': l18['drawing-ui'].ole,+};++describe('OLE action localization', () => {+ it('covers every action and tooltip in all 19 supported locales', () => {+ expect(Object.keys(locales)).toHaveLength(19);+ const keys = Object.keys(locales['en-US']).sort();+ const injector = new Injector([[LocaleService]]);+ const locale = injector.get(LocaleService);+ locale.load(Object.fromEntries(Object.entries(locales).map(([language, ole]) => [language, { 'drawing-ui': { ole } }])));+ try {+ for (const [language, messages] of Object.entries(locales)) {+ locale.setLocale(language as LocaleType);+ locale.setDirection(language === 'ar-SA' || language === 'fa-IR' ? 'rtl' : 'ltr');+ expect(Object.keys(messages).sort(), language).toEqual(keys);+ const summary = locale.t('drawing-ui.ole.unavailableSummary', '2');+ expect(summary, language).toContain('2');+ expect(summary, language).not.toContain('{0}');+ for (const key of keys) {+ expect(locale.t(`drawing-ui.ole.${key}`), `${language}.${key}`).toBe(Reflect.get(messages, key));+ expect(locale.t(`drawing-ui.ole.${key}`)).not.toBe(`drawing-ui.ole.${key}`);+ }+ }+ } finally { injector.dispose(); }+ });+});diff --git a/packages/drawing-ui/src/locale/ar-SA.ts b/packages/drawing-ui/src/locale/ar-SA.tsindex 0d0bff4f1b..a2ee9844fb 100644--- a/packages/drawing-ui/src/locale/ar-SA.ts+++ b/packages/drawing-ui/src/locale/ar-SA.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'جارٍ قراءة المرفق…',+ progressUploading: 'جارٍ رفع المرفق…',+ progressCreating: 'جارٍ إنشاء الملف عبر الإنترنت…',+ progressSaving: 'جارٍ حفظ الرابط…',+ externalAttachment: 'مرفق مرتبط',+ externalHint: 'الملف الأصلي الذي يشير إليه هذا المرفق غير مضمّن في المستند. المعاينة والتنزيل غير متاحين.',+ missingHint: 'بيانات هذا المرفق مفقودة من المستند. المعاينة والتنزيل غير متاحين.',+ unavailableSummary: 'يحتوي هذا المستند على {0} من المرفقات غير المتاحة. تم الاحتفاظ بعناصرها النائبة. مرّر المؤشر فوق رمز التحذير لمعرفة السبب.',+ rename: 'إعادة تسمية',+ saveName: 'حفظ الاسم',+ cancel: 'إلغاء',+ invalidName: 'أدخل اسم ملف صالحًا لا يتجاوز 255 حرفًا.',+ renameFailed: 'تعذرت إعادة تسمية المرفق. حاول مرة أخرى.',+ actions: 'إجراءات المرفق',+ linkSaveFailed: 'تم إنشاء الملف عبر الإنترنت، لكن تعذر حفظ رابطه. أعد محاولة حفظ الرابط.',+ conversionFailed: 'تعذر تحويل هذا المرفق. يرجى المحاولة مجددًا.',+ converted: 'اكتمل التحويل',+ open: 'فتح',+ converting: 'جارٍ التحويل…',+ openSlide: 'فتح العرض التقديمي عبر الإنترنت في علامة تبويب جديدة',+ openDoc: 'فتح المستند عبر الإنترنت في علامة تبويب جديدة',+ openSheet: 'فتح جدول البيانات عبر الإنترنت في علامة تبويب جديدة',+ convertSlide: 'تحويل إلى عرض تقديمي عبر الإنترنت',+ convertDoc: 'تحويل إلى مستند عبر الإنترنت',+ convertSheet: 'تحويل إلى جدول بيانات عبر الإنترنت',+ nativePreviewHint: 'إذا تعذّر عرض الملف في المتصفح، نزّل الملف الأصلي.',+ attachment: 'مرفق OLE',+ external: 'الملف الخارجي غير متاح',+ missing: 'بيانات المرفق غير متاحة',+ opaque: 'بيانات OLE الأصلية (يمكن تنزيلها)',+ download: 'تنزيل',+ preview: 'معاينة',+ remove: 'حذف',+ failed: 'تعذّرت قراءة المرفق الأصلي. حاول مجددًا.',+ unsupported: 'المعاينة غير متاحة لهذا الملف. يمكنك تنزيل الملف الأصلي.',+ },mobile: { close: 'إغلاق', more: 'المزيد' },'image-cropper': {error: 'لا يمكن قص الكائنات غير الصورية.',diff --git a/packages/drawing-ui/src/locale/ca-ES.ts b/packages/drawing-ui/src/locale/ca-ES.tsindex b256d5a9ca..e028e37eef 100644--- a/packages/drawing-ui/src/locale/ca-ES.ts+++ b/packages/drawing-ui/src/locale/ca-ES.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'S’està llegint el fitxer adjunt…',+ progressUploading: 'S’està pujant el fitxer adjunt…',+ progressCreating: 'S’està creant el fitxer en línia…',+ progressSaving: 'S’està desant l’enllaç…',+ externalAttachment: 'Fitxer adjunt enllaçat',+ externalHint: 'El fitxer original d’aquest adjunt no està incrustat al document. La previsualització i la baixada no estan disponibles.',+ missingHint: 'Falten les dades d’aquest adjunt al document. La previsualització i la baixada no estan disponibles.',+ unavailableSummary: 'Aquest document conté {0} fitxers adjunts no disponibles. Se n’han conservat els marcadors. Passeu el cursor sobre la icona d’avís per veure’n el motiu.',+ rename: 'Canvia el nom',+ saveName: 'Desa el nom',+ cancel: 'Cancel·la',+ invalidName: 'Introduïu un nom de fitxer vàlid de fins a 255 caràcters.',+ renameFailed: 'No es pot canviar el nom de l’adjunt. Torneu-ho a provar.',+ actions: 'Accions del fitxer adjunt',+ linkSaveFailed: 'S’ha creat el fitxer en línia, però no s’ha pogut desar l’enllaç. Torna a provar de desar-lo.',+ conversionFailed: 'No s’ha pogut convertir aquest fitxer adjunt. Torna-ho a provar.',+ converted: 'Conversió completada',+ open: 'Obre',+ converting: 'S’està convertint…',+ openSlide: 'Obre la presentació en línia en una pestanya nova',+ openDoc: 'Obre el document en línia en una pestanya nova',+ openSheet: 'Obre el full de càlcul en línia en una pestanya nova',+ convertSlide: 'Converteix en presentació en línia',+ convertDoc: 'Converteix en document en línia',+ convertSheet: 'Converteix en full de càlcul en línia',+ nativePreviewHint: 'Si el navegador no pot mostrar el fitxer, baixa l’original.',+ attachment: 'Fitxer adjunt OLE',+ external: 'Fitxer extern no disponible',+ missing: 'Dades del fitxer adjunt no disponibles',+ opaque: 'Binari OLE original (es pot baixar)',+ download: 'Baixa',+ preview: 'Previsualitza',+ remove: 'Suprimeix',+ failed: 'No es pot llegir el fitxer adjunt original. Torna-ho a provar.',+ unsupported: 'La previsualització no està disponible per a aquest fitxer. Pots baixar l’original.',+ },mobile: { close: 'Tanca', more: 'Més' },'image-cropper': {error: 'No es poden retallar objectes que no siguin imatges.',diff --git a/packages/drawing-ui/src/locale/de-DE.ts b/packages/drawing-ui/src/locale/de-DE.tsindex e171a1ddd7..146c3e1656 100644--- a/packages/drawing-ui/src/locale/de-DE.ts+++ b/packages/drawing-ui/src/locale/de-DE.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Anhang wird gelesen…',+ progressUploading: 'Anhang wird hochgeladen…',+ progressCreating: 'Onlinedatei wird erstellt…',+ progressSaving: 'Link wird gespeichert…',+ externalAttachment: 'Verknüpfter Anhang',+ externalHint: 'Die Originaldatei dieses Anhangs ist nicht in dieses Dokument eingebettet. Vorschau und Download sind nicht verfügbar.',+ missingHint: 'Die Daten dieses Anhangs fehlen im Dokument. Vorschau und Download sind nicht verfügbar.',+ unavailableSummary: 'Dieses Dokument enthält {0} nicht verfügbare Anhänge. Die Platzhalter wurden beibehalten. Bewegen Sie den Zeiger über das Warnsymbol, um den Grund zu sehen.',+ rename: 'Umbenennen',+ saveName: 'Namen speichern',+ cancel: 'Abbrechen',+ invalidName: 'Geben Sie einen gültigen Dateinamen mit höchstens 255 Zeichen ein.',+ renameFailed: 'Der Anhang konnte nicht umbenannt werden. Versuchen Sie es erneut.',+ actions: 'Anhangaktionen',+ linkSaveFailed: 'Die Online-Datei wurde erstellt, aber ihr Link konnte nicht gespeichert werden. Erneut versuchen, um den Link zu speichern.',+ conversionFailed: 'Dieser Anhang konnte nicht umgewandelt werden. Bitte erneut versuchen.',+ converted: 'Konvertierung abgeschlossen',+ open: 'Öffnen',+ converting: 'Wird umgewandelt…',+ openSlide: 'Online-Präsentation in neuem Tab öffnen',+ openDoc: 'Online-Dokument in neuem Tab öffnen',+ openSheet: 'Online-Tabelle in neuem Tab öffnen',+ convertSlide: 'In Online-Präsentation umwandeln',+ convertDoc: 'In Online-Dokument umwandeln',+ convertSheet: 'In Online-Tabelle umwandeln',+ nativePreviewHint: 'Wenn der Browser die Datei nicht anzeigen kann, laden Sie das Original herunter.',+ attachment: 'OLE-Anhang',+ external: 'Externe Datei nicht verfügbar',+ missing: 'Anhangsdaten nicht verfügbar',+ opaque: 'Originale OLE-Binärdatei (Download verfügbar)',+ download: 'Herunterladen',+ preview: 'Vorschau',+ remove: 'Löschen',+ failed: 'Der Originalanhang konnte nicht gelesen werden. Bitte erneut versuchen.',+ unsupported: 'Für diese Datei ist keine Vorschau verfügbar. Sie können das Original herunterladen.',+ },mobile: { close: 'Schließen', more: 'Mehr' },'image-cropper': {error: 'Nicht-Bildobjekte können nicht zugeschnitten werden.',diff --git a/packages/drawing-ui/src/locale/en-US.ts b/packages/drawing-ui/src/locale/en-US.tsindex a37cee5d66..d714caa553 100644--- a/packages/drawing-ui/src/locale/en-US.ts+++ b/packages/drawing-ui/src/locale/en-US.ts@@ -16,6 +16,43 @@const locale = {'drawing-ui': {+ ole: {+ progressReading: 'Reading attachment…',+ progressUploading: 'Uploading attachment…',+ progressCreating: 'Creating online file…',+ progressSaving: 'Saving link…',+ externalAttachment: 'Linked attachment',+ externalHint: 'The original file referenced by this attachment is not embedded in this document. Preview and download are unavailable.',+ missingHint: 'This document is missing the attachment data. Preview and download are unavailable.',+ unavailableSummary: 'This document contains {0} unavailable attachments. Their placeholders have been kept. Hover over the warning icon for details.',+ rename: 'Rename',+ saveName: 'Save name',+ cancel: 'Cancel',+ invalidName: 'Enter a valid file name of at most 255 characters.',+ renameFailed: 'Unable to rename this attachment. Please retry.',+ actions: 'Attachment actions',+ linkSaveFailed: 'The online file was created, but its link could not be saved. Retry to save the link.',+ conversionFailed: 'Unable to convert this attachment. Please retry.',+ converted: 'Conversion complete',+ open: 'Open',+ converting: 'Converting…',+ openSlide: 'Open online presentation in new tab',+ openDoc: 'Open online document in new tab',+ openSheet: 'Open online spreadsheet in new tab',+ convertSlide: 'Convert to online presentation',+ convertDoc: 'Convert to online document',+ convertSheet: 'Convert to online spreadsheet',+ nativePreviewHint: 'If the browser cannot display this file, download the original.',+ attachment: 'OLE attachment',+ external: 'External file unavailable',+ missing: 'Attachment data unavailable',+ opaque: 'Original OLE binary (download available)',+ download: 'Download',+ preview: 'Preview',+ remove: 'Delete',+ failed: 'Unable to read the original attachment. Please retry.',+ unsupported: 'Online preview is unavailable for this file. You can download the original.',+ },mobile: { close: 'Close', more: 'More' },'image-cropper': {error: 'Cannot crop non-image objects.',diff --git a/packages/drawing-ui/src/locale/es-ES.ts b/packages/drawing-ui/src/locale/es-ES.tsindex 6979e7ed04..05f2e485fd 100644--- a/packages/drawing-ui/src/locale/es-ES.ts+++ b/packages/drawing-ui/src/locale/es-ES.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Leyendo el archivo adjunto…',+ progressUploading: 'Subiendo el archivo adjunto…',+ progressCreating: 'Creando el archivo en línea…',+ progressSaving: 'Guardando el enlace…',+ externalAttachment: 'Archivo adjunto vinculado',+ externalHint: 'El archivo original de este adjunto no está incrustado en el documento. La vista previa y la descarga no están disponibles.',+ missingHint: 'Faltan los datos de este adjunto en el documento. La vista previa y la descarga no están disponibles.',+ unavailableSummary: 'Este documento contiene {0} archivos adjuntos no disponibles. Se han conservado sus marcadores. Pase el cursor sobre el icono de advertencia para ver el motivo.',+ rename: 'Cambiar nombre',+ saveName: 'Guardar nombre',+ cancel: 'Cancelar',+ invalidName: 'Escribe un nombre de archivo válido de hasta 255 caracteres.',+ renameFailed: 'No se pudo cambiar el nombre del adjunto. Inténtalo de nuevo.',+ actions: 'Acciones del archivo adjunto',+ linkSaveFailed: 'Se creó el archivo en línea, pero no se pudo guardar el enlace. Reintenta guardar el enlace.',+ conversionFailed: 'No se pudo convertir este archivo adjunto. Inténtalo de nuevo.',+ converted: 'Conversión completada',+ open: 'Abrir',+ converting: 'Convirtiendo…',+ openSlide: 'Abrir la presentación en línea en una pestaña nueva',+ openDoc: 'Abrir el documento en línea en una pestaña nueva',+ openSheet: 'Abrir la hoja de cálculo en línea en una pestaña nueva',+ convertSlide: 'Convertir en presentación en línea',+ convertDoc: 'Convertir en documento en línea',+ convertSheet: 'Convertir en hoja de cálculo en línea',+ nativePreviewHint: 'Si el navegador no puede mostrar el archivo, descarga el original.',+ attachment: 'Archivo adjunto OLE',+ external: 'Archivo externo no disponible',+ missing: 'Datos del archivo adjunto no disponibles',+ opaque: 'Binario OLE original (descarga disponible)',+ download: 'Descargar',+ preview: 'Vista previa',+ remove: 'Eliminar',+ failed: 'No se puede leer el archivo adjunto original. Inténtalo de nuevo.',+ unsupported: 'La vista previa no está disponible para este archivo. Puedes descargar el original.',+ },mobile: { close: 'Cerrar', more: 'Más' },'image-cropper': {error: 'No se pueden recortar objetos que no sean imágenes.',diff --git a/packages/drawing-ui/src/locale/fa-IR.ts b/packages/drawing-ui/src/locale/fa-IR.tsindex fb9ec28b04..b372dd1806 100644--- a/packages/drawing-ui/src/locale/fa-IR.ts+++ b/packages/drawing-ui/src/locale/fa-IR.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'در حال خواندن پیوست…',+ progressUploading: 'در حال بارگذاری پیوست…',+ progressCreating: 'در حال ایجاد فایل آنلاین…',+ progressSaving: 'در حال ذخیره پیوند…',+ externalAttachment: 'پیوست پیوندشده',+ externalHint: 'فایل اصلی این پیوست در سند جاسازی نشده است. پیشنمایش و بارگیری در دسترس نیست.',+ missingHint: 'دادههای این پیوست در سند موجود نیست. پیشنمایش و بارگیری در دسترس نیست.',+ unavailableSummary: 'این سند دارای {0} پیوست غیرقابل دسترس است. جاینگهدارهای آنها حفظ شدهاند. برای دیدن دلیل، نشانگر را روی نماد هشدار ببرید.',+ rename: 'تغییر نام',+ saveName: 'ذخیره نام',+ cancel: 'لغو',+ invalidName: 'نام فایل معتبر با حداکثر ۲۵۵ نویسه وارد کنید.',+ renameFailed: 'تغییر نام پیوست انجام نشد. دوباره تلاش کنید.',+ actions: 'عملیات پیوست',+ linkSaveFailed: 'فایل آنلاین ایجاد شد، اما پیوند ذخیره نشد. ذخیره پیوند را دوباره امتحان کنید.',+ conversionFailed: 'تبدیل این پیوست ممکن نشد. دوباره تلاش کنید.',+ converted: 'تبدیل انجام شد',+ open: 'باز کردن',+ converting: 'در حال تبدیل…',+ openSlide: 'باز کردن ارائه آنلاین در زبانه جدید',+ openDoc: 'باز کردن سند آنلاین در زبانه جدید',+ openSheet: 'باز کردن صفحهگسترده آنلاین در زبانه جدید',+ convertSlide: 'تبدیل به ارائه آنلاین',+ convertDoc: 'تبدیل به سند آنلاین',+ convertSheet: 'تبدیل به صفحهگسترده آنلاین',+ nativePreviewHint: 'اگر مرورگر نمیتواند فایل را نمایش دهد، نسخهٔ اصلی را دانلود کنید.',+ attachment: 'پیوست OLE',+ external: 'فایل خارجی در دسترس نیست',+ missing: 'دادههای پیوست در دسترس نیست',+ opaque: 'دادهٔ باینری اصلی OLE (قابل دانلود)',+ download: 'بارگیری',+ preview: 'پیشنمایش',+ remove: 'حذف',+ failed: 'خواندن پیوست اصلی ممکن نیست. دوباره تلاش کنید.',+ unsupported: 'پیشنمایش این فایل در دسترس نیست. میتوانید نسخهٔ اصلی را دانلود کنید.',+ },mobile: { close: 'بستن', more: 'بیشتر' },'image-cropper': {error: 'کراپ کردن اشیاء غیرتصویری امکانپذیر نیست.',diff --git a/packages/drawing-ui/src/locale/fr-FR.ts b/packages/drawing-ui/src/locale/fr-FR.tsindex b3dd065914..f7d696fd07 100644--- a/packages/drawing-ui/src/locale/fr-FR.ts+++ b/packages/drawing-ui/src/locale/fr-FR.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Lecture de la pièce jointe…',+ progressUploading: 'Envoi de la pièce jointe…',+ progressCreating: 'Création du fichier en ligne…',+ progressSaving: 'Enregistrement du lien…',+ externalAttachment: 'Pièce jointe liée',+ externalHint: 'Le fichier source de cette pièce jointe n’est pas intégré au document. L’aperçu et le téléchargement sont indisponibles.',+ missingHint: 'Les données de cette pièce jointe sont absentes du document. L’aperçu et le téléchargement sont indisponibles.',+ unavailableSummary: 'Ce document contient {0} pièces jointes indisponibles. Leurs emplacements sont conservés. Survolez l’icône d’avertissement pour en connaître la raison.',+ rename: 'Renommer',+ saveName: 'Enregistrer le nom',+ cancel: 'Annuler',+ invalidName: 'Saisissez un nom de fichier valide de 255 caractères maximum.',+ renameFailed: 'Impossible de renommer cette pièce jointe. Réessayez.',+ actions: 'Actions de la pièce jointe',+ linkSaveFailed: 'Le fichier en ligne a été créé, mais son lien n’a pas pu être enregistré. Réessayez pour enregistrer le lien.',+ conversionFailed: 'Impossible de convertir cette pièce jointe. Réessayez.',+ converted: 'Conversion terminée',+ open: 'Ouvrir',+ converting: 'Conversion en cours…',+ openSlide: 'Ouvrir la présentation en ligne dans un nouvel onglet',+ openDoc: 'Ouvrir le document en ligne dans un nouvel onglet',+ openSheet: 'Ouvrir la feuille de calcul en ligne dans un nouvel onglet',+ convertSlide: 'Convertir en présentation en ligne',+ convertDoc: 'Convertir en document en ligne',+ convertSheet: 'Convertir en feuille de calcul en ligne',+ nativePreviewHint: 'Si le navigateur ne peut pas afficher le fichier, téléchargez l’original.',+ attachment: 'Pièce jointe OLE',+ external: 'Fichier externe indisponible',+ missing: 'Données de la pièce jointe indisponibles',+ opaque: 'Fichier binaire OLE original (téléchargement disponible)',+ download: 'Télécharger',+ preview: 'Aperçu',+ remove: 'Supprimer',+ failed: 'Impossible de lire la pièce jointe originale. Veuillez réessayer.',+ unsupported: 'L’aperçu de ce fichier est indisponible. Vous pouvez télécharger l’original.',+ },mobile: { close: 'Fermer', more: 'Plus' },'image-cropper': {error: 'Impossible de rogner des objets non image.',diff --git a/packages/drawing-ui/src/locale/id-ID.ts b/packages/drawing-ui/src/locale/id-ID.tsindex 85e75778e3..dcb6db913c 100644--- a/packages/drawing-ui/src/locale/id-ID.ts+++ b/packages/drawing-ui/src/locale/id-ID.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Membaca lampiran…',+ progressUploading: 'Mengunggah lampiran…',+ progressCreating: 'Membuat file online…',+ progressSaving: 'Menyimpan tautan…',+ externalAttachment: 'Lampiran tertaut',+ externalHint: 'File asli yang dirujuk oleh lampiran ini tidak disematkan dalam dokumen. Pratinjau dan unduhan tidak tersedia.',+ missingHint: 'Data lampiran ini tidak ada dalam dokumen. Pratinjau dan unduhan tidak tersedia.',+ unavailableSummary: 'Dokumen ini berisi {0} lampiran yang tidak tersedia. Penanda tempatnya dipertahankan. Arahkan kursor ke ikon peringatan untuk melihat alasannya.',+ rename: 'Ubah nama',+ saveName: 'Simpan nama',+ cancel: 'Batal',+ invalidName: 'Masukkan nama file yang valid dengan maksimal 255 karakter.',+ renameFailed: 'Tidak dapat mengubah nama lampiran ini. Coba lagi.',+ actions: 'Tindakan lampiran',+ linkSaveFailed: 'File online telah dibuat, tetapi tautannya tidak dapat disimpan. Coba simpan tautan lagi.',+ conversionFailed: 'Lampiran ini tidak dapat dikonversi. Silakan coba lagi.',+ converted: 'Konversi selesai',+ open: 'Buka',+ converting: 'Mengonversi…',+ openSlide: 'Buka presentasi online di tab baru',+ openDoc: 'Buka dokumen online di tab baru',+ openSheet: 'Buka spreadsheet online di tab baru',+ convertSlide: 'Konversi menjadi presentasi online',+ convertDoc: 'Konversi menjadi dokumen online',+ convertSheet: 'Konversi menjadi spreadsheet online',+ nativePreviewHint: 'Jika browser tidak dapat menampilkan file ini, unduh file aslinya.',+ attachment: 'Lampiran OLE',+ external: 'File eksternal tidak tersedia',+ missing: 'Data lampiran tidak tersedia',+ opaque: 'Biner OLE asli (dapat diunduh)',+ download: 'Unduh',+ preview: 'Pratinjau',+ remove: 'Hapus',+ failed: 'Tidak dapat membaca lampiran asli. Silakan coba lagi.',+ unsupported: 'Pratinjau tidak tersedia untuk file ini. Anda dapat mengunduh file aslinya.',+ },mobile: { close: 'Tutup', more: 'Lebih Banyak' },'image-cropper': {error: 'Tidak dapat memangkas objek non-gambar.',diff --git a/packages/drawing-ui/src/locale/it-IT.ts b/packages/drawing-ui/src/locale/it-IT.tsindex 141a489001..1b2275b6dc 100644--- a/packages/drawing-ui/src/locale/it-IT.ts+++ b/packages/drawing-ui/src/locale/it-IT.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Lettura dell’allegato…',+ progressUploading: 'Caricamento dell’allegato…',+ progressCreating: 'Creazione del file online…',+ progressSaving: 'Salvataggio del collegamento…',+ externalAttachment: 'Allegato collegato',+ externalHint: 'Il file originale di questo allegato non è incorporato nel documento. Anteprima e download non sono disponibili.',+ missingHint: 'I dati di questo allegato sono assenti dal documento. Anteprima e download non sono disponibili.',+ unavailableSummary: 'Questo documento contiene {0} allegati non disponibili. I segnaposto sono stati mantenuti. Passa il puntatore sull’icona di avviso per conoscere il motivo.',+ rename: 'Rinomina',+ saveName: 'Salva nome',+ cancel: 'Annulla',+ invalidName: 'Inserisci un nome file valido di massimo 255 caratteri.',+ renameFailed: 'Impossibile rinominare questo allegato. Riprova.',+ actions: 'Azioni dell’allegato',+ linkSaveFailed: 'Il file online è stato creato, ma non è stato possibile salvare il collegamento. Riprova a salvarlo.',+ conversionFailed: 'Impossibile convertire questo allegato. Riprova.',+ converted: 'Conversione completata',+ open: 'Apri',+ converting: 'Conversione in corso…',+ openSlide: 'Apri la presentazione online in una nuova scheda',+ openDoc: 'Apri il documento online in una nuova scheda',+ openSheet: 'Apri il foglio di calcolo online in una nuova scheda',+ convertSlide: 'Converti in presentazione online',+ convertDoc: 'Converti in documento online',+ convertSheet: 'Converti in foglio di calcolo online',+ nativePreviewHint: 'Se il browser non riesce a mostrare il file, scarica l’originale.',+ attachment: 'Allegato OLE',+ external: 'File esterno non disponibile',+ missing: 'Dati dell’allegato non disponibili',+ opaque: 'File binario OLE originale (download disponibile)',+ download: 'Scarica',+ preview: 'Anteprima',+ remove: 'Elimina',+ failed: 'Impossibile leggere l’allegato originale. Riprova.',+ unsupported: 'L’anteprima non è disponibile per questo file. Puoi scaricare l’originale.',+ },mobile: { close: 'Chiudi', more: 'Altro' },'image-cropper': {error: 'Impossibile ritagliare oggetti non immagine.',diff --git a/packages/drawing-ui/src/locale/ja-JP.ts b/packages/drawing-ui/src/locale/ja-JP.tsindex ab467d0053..241648e2e9 100644--- a/packages/drawing-ui/src/locale/ja-JP.ts+++ b/packages/drawing-ui/src/locale/ja-JP.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: '添付ファイルを読み込み中…',+ progressUploading: '添付ファイルをアップロード中…',+ progressCreating: 'オンラインファイルを作成中…',+ progressSaving: 'リンクを保存中…',+ externalAttachment: 'リンクされた添付ファイル',+ externalHint: 'この添付ファイルの参照先の元ファイルは文書に埋め込まれていないため、プレビューやダウンロードはできません。',+ missingHint: 'この文書には添付ファイルのデータがないため、プレビューやダウンロードはできません。',+ unavailableSummary: 'この文書には利用できない添付ファイルが {0} 件あります。プレースホルダーは保持されています。警告アイコンにカーソルを合わせると理由を確認できます。',+ rename: '名前の変更',+ saveName: '名前を保存',+ cancel: 'キャンセル',+ invalidName: '255 文字以内の有効なファイル名を入力してください。',+ renameFailed: '添付ファイルの名前を変更できません。再試行してください。',+ actions: '添付ファイルの操作',+ linkSaveFailed: 'オンラインファイルは作成されましたが、リンクを保存できませんでした。リンクの保存を再試行してください。',+ conversionFailed: '添付ファイルを変換できませんでした。再試行してください。',+ converted: '変換が完了しました',+ open: '開く',+ converting: '変換中…',+ openSlide: 'オンラインプレゼンテーションを新しいタブで開く',+ openDoc: 'オンラインドキュメントを新しいタブで開く',+ openSheet: 'オンラインスプレッドシートを新しいタブで開く',+ convertSlide: 'オンラインプレゼンテーションに変換',+ convertDoc: 'オンラインドキュメントに変換',+ convertSheet: 'オンラインスプレッドシートに変換',+ nativePreviewHint: 'ブラウザーで表示できない場合は、元のファイルをダウンロードしてください。',+ attachment: 'OLE 添付ファイル',+ external: '外部ファイルを利用できません',+ missing: '添付ファイルのデータを利用できません',+ opaque: '元の OLE バイナリ(ダウンロード可能)',+ download: 'ダウンロード',+ preview: 'プレビュー',+ remove: '削除',+ failed: '元の添付ファイルを読み取れませんでした。再試行してください。',+ unsupported: 'このファイルはプレビューできません。元のファイルをダウンロードできます。',+ },mobile: { close: '閉じる', more: 'もっと見る' },'image-cropper': {error: '画像以外のオブジェクトはトリミングできません。',diff --git a/packages/drawing-ui/src/locale/ko-KR.ts b/packages/drawing-ui/src/locale/ko-KR.tsindex 15f2b68156..78c5985066 100644--- a/packages/drawing-ui/src/locale/ko-KR.ts+++ b/packages/drawing-ui/src/locale/ko-KR.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: '첨부 파일을 읽는 중…',+ progressUploading: '첨부 파일을 업로드하는 중…',+ progressCreating: '온라인 파일을 만드는 중…',+ progressSaving: '링크를 저장하는 중…',+ externalAttachment: '연결된 첨부 파일',+ externalHint: '이 첨부 파일이 참조하는 원본 파일이 문서에 포함되어 있지 않아 미리 보기와 다운로드를 사용할 수 없습니다.',+ missingHint: '문서에 첨부 파일 데이터가 없어 미리 보기와 다운로드를 사용할 수 없습니다.',+ unavailableSummary: '문서에 사용할 수 없는 첨부 파일이 {0}개 있습니다. 자리 표시자는 유지됩니다. 경고 아이콘에 마우스를 올리면 이유를 확인할 수 있습니다.',+ rename: '이름 바꾸기',+ saveName: '이름 저장',+ cancel: '취소',+ invalidName: '255자 이내의 올바른 파일 이름을 입력하세요.',+ renameFailed: '첨부 파일 이름을 바꿀 수 없습니다. 다시 시도하세요.',+ actions: '첨부 파일 작업',+ linkSaveFailed: '온라인 파일이 생성되었지만 링크를 저장하지 못했습니다. 링크 저장을 다시 시도하세요.',+ conversionFailed: '첨부 파일을 변환하지 못했습니다. 다시 시도하세요.',+ converted: '변환 완료',+ open: '열기',+ converting: '변환 중…',+ openSlide: '새 탭에서 온라인 프레젠테이션 열기',+ openDoc: '새 탭에서 온라인 문서 열기',+ openSheet: '새 탭에서 온라인 스프레드시트 열기',+ convertSlide: '온라인 프레젠테이션으로 변환',+ convertDoc: '온라인 문서로 변환',+ convertSheet: '온라인 스프레드시트로 변환',+ nativePreviewHint: '브라우저에서 파일을 표시할 수 없으면 원본을 다운로드하세요.',+ attachment: 'OLE 첨부 파일',+ external: '외부 파일을 사용할 수 없습니다',+ missing: '첨부 파일 데이터를 사용할 수 없습니다',+ opaque: '원본 OLE 바이너리 (다운로드 가능)',+ download: '다운로드',+ preview: '미리 보기',+ remove: '삭제',+ failed: '원본 첨부 파일을 읽을 수 없습니다. 다시 시도하세요.',+ unsupported: '이 파일은 미리 볼 수 없습니다. 원본을 다운로드할 수 있습니다.',+ },mobile: { close: '닫기', more: '더 보기' },'image-cropper': {error: '이미지가 아닌 객체는 자를 수 없습니다.',diff --git a/packages/drawing-ui/src/locale/pl-PL.ts b/packages/drawing-ui/src/locale/pl-PL.tsindex e452aa33b2..7bfdf288d6 100644--- a/packages/drawing-ui/src/locale/pl-PL.ts+++ b/packages/drawing-ui/src/locale/pl-PL.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Odczytywanie załącznika…',+ progressUploading: 'Przesyłanie załącznika…',+ progressCreating: 'Tworzenie pliku online…',+ progressSaving: 'Zapisywanie łącza…',+ externalAttachment: 'Załącznik połączony',+ externalHint: 'Plik źródłowy tego załącznika nie jest osadzony w dokumencie. Podgląd i pobieranie są niedostępne.',+ missingHint: 'W dokumencie brakuje danych tego załącznika. Podgląd i pobieranie są niedostępne.',+ unavailableSummary: 'Liczba niedostępnych załączników w dokumencie: {0}. Ich symbole zastępcze zachowano. Najedź na ikonę ostrzeżenia, aby poznać przyczynę.',+ rename: 'Zmień nazwę',+ saveName: 'Zapisz nazwę',+ cancel: 'Anuluj',+ invalidName: 'Wpisz prawidłową nazwę pliku zawierającą maksymalnie 255 znaków.',+ renameFailed: 'Nie można zmienić nazwy załącznika. Spróbuj ponownie.',+ actions: 'Działania załącznika',+ linkSaveFailed: 'Utworzono plik online, ale nie zapisano łącza. Spróbuj ponownie zapisać łącze.',+ conversionFailed: 'Nie można przekonwertować tego załącznika. Spróbuj ponownie.',+ converted: 'Konwersja zakończona',+ open: 'Otwórz',+ converting: 'Konwertowanie…',+ openSlide: 'Otwórz prezentację online w nowej karcie',+ openDoc: 'Otwórz dokument online w nowej karcie',+ openSheet: 'Otwórz arkusz online w nowej karcie',+ convertSlide: 'Konwertuj na prezentację online',+ convertDoc: 'Konwertuj na dokument online',+ convertSheet: 'Konwertuj na arkusz online',+ nativePreviewHint: 'Jeśli przeglądarka nie wyświetla pliku, pobierz oryginał.',+ attachment: 'Załącznik OLE',+ external: 'Plik zewnętrzny jest niedostępny',+ missing: 'Dane załącznika są niedostępne',+ opaque: 'Oryginalny plik binarny OLE (można pobrać)',+ download: 'Pobierz',+ preview: 'Podgląd',+ remove: 'Usuń',+ failed: 'Nie można odczytać oryginalnego załącznika. Spróbuj ponownie.',+ unsupported: 'Podgląd tego pliku jest niedostępny. Możesz pobrać oryginał.',+ },mobile: { close: 'Zamknij', more: 'Więcej' },'image-cropper': {error: 'Nie można przyciąć obiektów innych niż obraz.',diff --git a/packages/drawing-ui/src/locale/pt-BR.ts b/packages/drawing-ui/src/locale/pt-BR.tsindex 06af83d9a8..89fa171371 100644--- a/packages/drawing-ui/src/locale/pt-BR.ts+++ b/packages/drawing-ui/src/locale/pt-BR.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Lendo anexo…',+ progressUploading: 'Enviando anexo…',+ progressCreating: 'Criando arquivo online…',+ progressSaving: 'Salvando link…',+ externalAttachment: 'Anexo vinculado',+ externalHint: 'O arquivo original deste anexo não está incorporado ao documento. A visualização e o download estão indisponíveis.',+ missingHint: 'Os dados deste anexo estão ausentes no documento. A visualização e o download estão indisponíveis.',+ unavailableSummary: 'Este documento contém {0} anexos indisponíveis. Seus espaços foram preservados. Passe o cursor sobre o ícone de aviso para ver o motivo.',+ rename: 'Renomear',+ saveName: 'Salvar nome',+ cancel: 'Cancelar',+ invalidName: 'Insira um nome de arquivo válido com até 255 caracteres.',+ renameFailed: 'Não foi possível renomear o anexo. Tente novamente.',+ actions: 'Ações do anexo',+ linkSaveFailed: 'O arquivo online foi criado, mas o link não pôde ser salvo. Tente salvar o link novamente.',+ conversionFailed: 'Não foi possível converter este anexo. Tente novamente.',+ converted: 'Conversão concluída',+ open: 'Abrir',+ converting: 'Convertendo…',+ openSlide: 'Abrir apresentação online em nova aba',+ openDoc: 'Abrir documento online em nova aba',+ openSheet: 'Abrir planilha online em nova aba',+ convertSlide: 'Converter em apresentação online',+ convertDoc: 'Converter em documento online',+ convertSheet: 'Converter em planilha online',+ nativePreviewHint: 'Se o navegador não conseguir exibir o arquivo, baixe o original.',+ attachment: 'Anexo OLE',+ external: 'Arquivo externo indisponível',+ missing: 'Dados do anexo indisponíveis',+ opaque: 'Binário OLE original (download disponível)',+ download: 'Baixar',+ preview: 'Visualizar',+ remove: 'Excluir',+ failed: 'Não foi possível ler o anexo original. Tente novamente.',+ unsupported: 'A prévia deste arquivo está indisponível. Você pode baixar o original.',+ },mobile: { close: 'Fechar', more: 'Mais' },'image-cropper': {error: 'Não é possível cortar objetos que não são imagens.',diff --git a/packages/drawing-ui/src/locale/ru-RU.ts b/packages/drawing-ui/src/locale/ru-RU.tsindex c9a6aef11e..22b423a7eb 100644--- a/packages/drawing-ui/src/locale/ru-RU.ts+++ b/packages/drawing-ui/src/locale/ru-RU.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Чтение вложения…',+ progressUploading: 'Загрузка вложения…',+ progressCreating: 'Создание онлайн-файла…',+ progressSaving: 'Сохранение ссылки…',+ externalAttachment: 'Связанное вложение',+ externalHint: 'Исходный файл этого вложения не встроен в документ. Просмотр и скачивание недоступны.',+ missingHint: 'В документе отсутствуют данные этого вложения. Просмотр и скачивание недоступны.',+ unavailableSummary: 'В документе есть недоступные вложения: {0}. Их места сохранены. Наведите указатель на значок предупреждения, чтобы узнать причину.',+ rename: 'Переименовать',+ saveName: 'Сохранить имя',+ cancel: 'Отмена',+ invalidName: 'Введите допустимое имя файла длиной до 255 символов.',+ renameFailed: 'Не удалось переименовать вложение. Повторите попытку.',+ actions: 'Действия с вложением',+ linkSaveFailed: 'Онлайн-файл создан, но ссылка не сохранена. Повторите сохранение ссылки.',+ conversionFailed: 'Не удалось преобразовать вложение. Повторите попытку.',+ converted: 'Преобразование завершено',+ open: 'Открыть',+ converting: 'Преобразование…',+ openSlide: 'Открыть онлайн-презентацию в новой вкладке',+ openDoc: 'Открыть онлайн-документ в новой вкладке',+ openSheet: 'Открыть онлайн-таблицу в новой вкладке',+ convertSlide: 'Преобразовать в онлайн-презентацию',+ convertDoc: 'Преобразовать в онлайн-документ',+ convertSheet: 'Преобразовать в онлайн-таблицу',+ nativePreviewHint: 'Если браузер не может отобразить файл, скачайте оригинал.',+ attachment: 'Вложение OLE',+ external: 'Внешний файл недоступен',+ missing: 'Данные вложения недоступны',+ opaque: 'Исходный двоичный файл OLE (доступен для скачивания)',+ download: 'Скачать',+ preview: 'Предпросмотр',+ remove: 'Удалить',+ failed: 'Не удалось прочитать исходное вложение. Повторите попытку.',+ unsupported: 'Предпросмотр этого файла недоступен. Вы можете скачать оригинал.',+ },mobile: { close: 'Закрыть', more: 'Больше' },'image-cropper': {error: 'Невозможно обрезать не изображения.',diff --git a/packages/drawing-ui/src/locale/sk-SK.ts b/packages/drawing-ui/src/locale/sk-SK.tsindex 66944b3777..ca26930eba 100644--- a/packages/drawing-ui/src/locale/sk-SK.ts+++ b/packages/drawing-ui/src/locale/sk-SK.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Čítanie prílohy…',+ progressUploading: 'Nahrávanie prílohy…',+ progressCreating: 'Vytváranie online súboru…',+ progressSaving: 'Ukladanie odkazu…',+ externalAttachment: 'Prepojená príloha',+ externalHint: 'Pôvodný súbor tejto prílohy nie je vložený do dokumentu. Náhľad a sťahovanie nie sú dostupné.',+ missingHint: 'V dokumente chýbajú údaje tejto prílohy. Náhľad a sťahovanie nie sú dostupné.',+ unavailableSummary: 'Počet nedostupných príloh v dokumente: {0}. Ich zástupné symboly boli zachované. Dôvod zobrazíte ukázaním na ikonu upozornenia.',+ rename: 'Premenovať',+ saveName: 'Uložiť názov',+ cancel: 'Zrušiť',+ invalidName: 'Zadajte platný názov súboru s najviac 255 znakmi.',+ renameFailed: 'Prílohu sa nepodarilo premenovať. Skúste to znova.',+ actions: 'Akcie prílohy',+ linkSaveFailed: 'Online súbor bol vytvorený, ale jeho odkaz sa nepodarilo uložiť. Skúste odkaz uložiť znova.',+ conversionFailed: 'Túto prílohu sa nepodarilo previesť. Skúste to znova.',+ converted: 'Prevod dokončený',+ open: 'Otvoriť',+ converting: 'Prebieha prevod…',+ openSlide: 'Otvoriť online prezentáciu na novej karte',+ openDoc: 'Otvoriť online dokument na novej karte',+ openSheet: 'Otvoriť online tabuľku na novej karte',+ convertSlide: 'Previesť na online prezentáciu',+ convertDoc: 'Previesť na online dokument',+ convertSheet: 'Previesť na online tabuľku',+ nativePreviewHint: 'Ak prehliadač nedokáže zobraziť súbor, stiahnite si originál.',+ attachment: 'Príloha OLE',+ external: 'Externý súbor nie je dostupný',+ missing: 'Údaje prílohy nie sú dostupné',+ opaque: 'Pôvodný binárny súbor OLE (možno stiahnuť)',+ download: 'Stiahnuť',+ preview: 'Ukážka',+ remove: 'Odstrániť',+ failed: 'Pôvodnú prílohu sa nepodarilo prečítať. Skúste to znova.',+ unsupported: 'Ukážka tohto súboru nie je dostupná. Môžete si stiahnuť originál.',+ },mobile: { close: 'Zavrieť', more: 'Viac' },'image-cropper': {error: 'Nedá sa orezať neobrázkový objekt.',diff --git a/packages/drawing-ui/src/locale/vi-VN.ts b/packages/drawing-ui/src/locale/vi-VN.tsindex 83f50ccdda..6dd738d52e 100644--- a/packages/drawing-ui/src/locale/vi-VN.ts+++ b/packages/drawing-ui/src/locale/vi-VN.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: 'Đang đọc tệp đính kèm…',+ progressUploading: 'Đang tải tệp đính kèm lên…',+ progressCreating: 'Đang tạo tệp trực tuyến…',+ progressSaving: 'Đang lưu liên kết…',+ externalAttachment: 'Tệp đính kèm được liên kết',+ externalHint: 'Tệp gốc mà tệp đính kèm này tham chiếu chưa được nhúng vào tài liệu. Không thể xem trước hoặc tải xuống.',+ missingHint: 'Tài liệu thiếu dữ liệu của tệp đính kèm này. Không thể xem trước hoặc tải xuống.',+ unavailableSummary: 'Tài liệu có {0} tệp đính kèm không khả dụng. Các vị trí của chúng được giữ lại. Di chuột lên biểu tượng cảnh báo để xem lý do.',+ rename: 'Đổi tên',+ saveName: 'Lưu tên',+ cancel: 'Hủy',+ invalidName: 'Nhập tên tệp hợp lệ có tối đa 255 ký tự.',+ renameFailed: 'Không thể đổi tên tệp đính kèm. Hãy thử lại.',+ actions: 'Thao tác với tệp đính kèm',+ linkSaveFailed: 'Đã tạo tệp trực tuyến nhưng không lưu được liên kết. Hãy thử lưu lại liên kết.',+ conversionFailed: 'Không thể chuyển đổi tệp đính kèm. Vui lòng thử lại.',+ converted: 'Chuyển đổi hoàn tất',+ open: 'Mở',+ converting: 'Đang chuyển đổi…',+ openSlide: 'Mở bản trình chiếu trực tuyến trong thẻ mới',+ openDoc: 'Mở tài liệu trực tuyến trong thẻ mới',+ openSheet: 'Mở bảng tính trực tuyến trong thẻ mới',+ convertSlide: 'Chuyển thành bản trình chiếu trực tuyến',+ convertDoc: 'Chuyển thành tài liệu trực tuyến',+ convertSheet: 'Chuyển thành bảng tính trực tuyến',+ nativePreviewHint: 'Nếu trình duyệt không thể hiển thị tệp, hãy tải bản gốc xuống.',+ attachment: 'Tệp đính kèm OLE',+ external: 'Tệp bên ngoài không khả dụng',+ missing: 'Dữ liệu tệp đính kèm không khả dụng',+ opaque: 'Tệp nhị phân OLE gốc (có thể tải xuống)',+ download: 'Tải xuống',+ preview: 'Xem trước',+ remove: 'Xóa',+ failed: 'Không thể đọc tệp đính kèm gốc. Vui lòng thử lại.',+ unsupported: 'Không có bản xem trước cho tệp này. Bạn có thể tải bản gốc xuống.',+ },mobile: { close: 'Đóng', more: 'Thêm' },'image-cropper': {error: 'Không thể cắt phần tử không phải hình ảnh',diff --git a/packages/drawing-ui/src/locale/zh-CN.ts b/packages/drawing-ui/src/locale/zh-CN.tsindex d158201407..23885ef1a0 100644--- a/packages/drawing-ui/src/locale/zh-CN.ts+++ b/packages/drawing-ui/src/locale/zh-CN.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: '正在读取附件…',+ progressUploading: '正在上传附件…',+ progressCreating: '正在创建在线文件…',+ progressSaving: '正在保存链接…',+ externalAttachment: '外链附件',+ externalHint: '此附件引用的原文件未嵌入当前文档,无法预览或下载。',+ missingHint: '当前文档缺少此附件的数据,无法预览或下载。',+ unavailableSummary: '文档中有 {0} 个不可用附件,已保留占位。悬停警告图标可查看原因。',+ rename: '重命名',+ saveName: '保存名称',+ cancel: '取消',+ invalidName: '请输入有效文件名,最多 255 个字符。',+ renameFailed: '无法重命名此附件,请重试。',+ actions: '附件操作',+ linkSaveFailed: '在线文件已创建,但链接保存失败。请重试保存链接。',+ conversionFailed: '附件转换失败,请重试。',+ converted: '转换完成',+ open: '打开',+ converting: '正在转换…',+ openSlide: '在新标签页打开在线幻灯片',+ openDoc: '在新标签页打开在线文档',+ openSheet: '在新标签页打开在线表格',+ convertSlide: '转换为在线幻灯片',+ convertDoc: '转换为在线文档',+ convertSheet: '转换为在线表格',+ nativePreviewHint: '如果浏览器无法显示此文件,请下载原文件。',+ attachment: 'OLE 附件',+ external: '外链文件不可用',+ missing: '附件数据不可用',+ opaque: '原始 OLE 二进制(可下载)',+ download: '下载',+ preview: '预览',+ remove: '删除',+ failed: '无法读取原始附件,请重试。',+ unsupported: '此文件暂不支持预览,可以下载原文件。',+ },mobile: { close: '关闭', more: '更多' },'image-cropper': {error: '无法裁剪非图片元素',diff --git a/packages/drawing-ui/src/locale/zh-HK.ts b/packages/drawing-ui/src/locale/zh-HK.tsindex d961c5f80b..35c6ea0ce6 100644--- a/packages/drawing-ui/src/locale/zh-HK.ts+++ b/packages/drawing-ui/src/locale/zh-HK.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: '正在讀取附件…',+ progressUploading: '正在上傳附件…',+ progressCreating: '正在建立線上檔案…',+ progressSaving: '正在儲存連結…',+ externalAttachment: '外部連結附件',+ externalHint: '此附件參照的原始檔案未嵌入目前文件,無法預覽或下載。',+ missingHint: '目前文件缺少此附件的資料,無法預覽或下載。',+ unavailableSummary: '文件中有 {0} 個無法使用的附件,已保留預留位置。將游標移至警告圖示可查看原因。',+ rename: '重新命名',+ saveName: '儲存名稱',+ cancel: '取消',+ invalidName: '請輸入有效檔名,最多 255 個字元。',+ renameFailed: '無法重新命名此附件,請重試。',+ actions: '附件操作',+ linkSaveFailed: '網上檔案已建立,但連結儲存失敗。請重試儲存連結。',+ conversionFailed: '附件轉換失敗,請重試。',+ converted: '轉換完成',+ open: '開啟',+ converting: '正在轉換…',+ openSlide: '在新分頁開啟網上簡報',+ openDoc: '在新分頁開啟網上文件',+ openSheet: '在新分頁開啟網上試算表',+ convertSlide: '轉換為網上簡報',+ convertDoc: '轉換為網上文件',+ convertSheet: '轉換為網上試算表',+ nativePreviewHint: '如果瀏覽器無法顯示此檔案,請下載原始檔案。',+ attachment: 'OLE 附件',+ external: '外部連結檔案無法使用',+ missing: '附件資料無法使用',+ opaque: '原始 OLE 二進位檔案(可下載)',+ download: '下載',+ preview: '預覽',+ remove: '刪除',+ failed: '無法讀取原始附件,請重試。',+ unsupported: '此檔案暫不支援預覽,可以下載原始檔案。',+ },mobile: { close: '關閉', more: '更多' },'image-cropper': {error: '無法裁切非圖片元素',diff --git a/packages/drawing-ui/src/locale/zh-TW.ts b/packages/drawing-ui/src/locale/zh-TW.tsindex daf9ee6b67..64312b9033 100644--- a/packages/drawing-ui/src/locale/zh-TW.ts+++ b/packages/drawing-ui/src/locale/zh-TW.ts@@ -18,6 +18,43 @@ import type enUS from './en-US';const locale: typeof enUS = {'drawing-ui': {+ ole: {+ progressReading: '正在讀取附件…',+ progressUploading: '正在上傳附件…',+ progressCreating: '正在建立線上檔案…',+ progressSaving: '正在儲存連結…',+ externalAttachment: '外部連結附件',+ externalHint: '此附件參照的原始檔案未嵌入目前文件,無法預覽或下載。',+ missingHint: '目前文件缺少此附件的資料,無法預覽或下載。',+ unavailableSummary: '文件中有 {0} 個無法使用的附件,已保留預留位置。將游標移至警告圖示可查看原因。',+ rename: '重新命名',+ saveName: '儲存名稱',+ cancel: '取消',+ invalidName: '請輸入有效檔名,最多 255 個字元。',+ renameFailed: '無法重新命名此附件,請重試。',+ actions: '附件操作',+ linkSaveFailed: '線上檔案已建立,但連結儲存失敗。請重試儲存連結。',+ conversionFailed: '附件轉換失敗,請重試。',+ converted: '轉換完成',+ open: '開啟',+ converting: '正在轉換…',+ openSlide: '在新分頁開啟線上簡報',+ openDoc: '在新分頁開啟線上文件',+ openSheet: '在新分頁開啟線上試算表',+ convertSlide: '轉換為線上簡報',+ convertDoc: '轉換為線上文件',+ convertSheet: '轉換為線上試算表',+ nativePreviewHint: '如果瀏覽器無法顯示此檔案,請下載原始檔案。',+ attachment: 'OLE 附件',+ external: '外部連結檔案無法使用',+ missing: '附件資料無法使用',+ opaque: '原始 OLE 二進位檔案(可下載)',+ download: '下載',+ preview: '預覽',+ remove: '刪除',+ failed: '無法讀取原始附件,請重試。',+ unsupported: '此檔案暫不支援預覽,可以下載原始檔案。',+ },mobile: { close: '關閉', more: '更多' },'image-cropper': {error: '無法裁切非圖片元素',diff --git a/packages/drawing-ui/src/mobile-plugin.ts b/packages/drawing-ui/src/mobile-plugin.tsindex 9a687c03d7..d98d3e9299 100644--- a/packages/drawing-ui/src/mobile-plugin.ts+++ b/packages/drawing-ui/src/mobile-plugin.ts@@ -15,10 +15,10 @@*/import type { Dependency } from '@univerjs/core';-import type { IUniverDrawingUIConfig } from './config/config';import { DependentOn, IConfigService, Inject, Injector, merge, Plugin } from '@univerjs/core';import { UniverDrawingPlugin } from '@univerjs/drawing';import { UniverRenderEnginePlugin } from '@univerjs/engine-render';+import type { IUniverDrawingUIConfig } from './config/config';import pkg from '../package.json';import { defaultPluginConfig, DRAWING_UI_PLUGIN_CONFIG_KEY } from './config/config';import { DrawingUpdateController } from './controllers/drawing-update.controller';@@ -28,6 +28,7 @@ import { MobileImageUpdateController } from './controllers/mobile/image-update.cimport { MobileDrawingUIController } from './controllers/mobile/ui.controller';import { DrawingImageClipService } from './services/drawing-image-clip.service';import { DrawingRenderService } from './services/drawing-render.service';+import { OleUIService } from './services/ole-ui.service';@DependentOn(UniverDrawingPlugin, UniverRenderEnginePlugin)export class UniverDrawingMobileUIPlugin extends Plugin {@@ -66,6 +67,7 @@ export class UniverDrawingMobileUIPlugin extends Plugin {const dependencies: Dependency[] = [[DrawingImageClipService],[DrawingRenderService],+ [OleUIService],[DrawingUpdateController],[MobileDrawingUIController],[MobileImageCropperController],diff --git a/packages/drawing-ui/src/plugin.ts b/packages/drawing-ui/src/plugin.tsindex 73415e0ee0..567288c155 100644--- a/packages/drawing-ui/src/plugin.ts+++ b/packages/drawing-ui/src/plugin.ts@@ -28,6 +28,7 @@ import { ImageUpdateController } from './controllers/image-update.controller';import { DrawingUIController } from './controllers/ui.controller';import { DrawingImageClipService } from './services/drawing-image-clip.service';import { DrawingRenderService } from './services/drawing-render.service';+import { OleUIService } from './services/ole-ui.service';@DependentOn(UniverDrawingPlugin, UniverRenderEnginePlugin)export class UniverDrawingUIPlugin extends Plugin {@@ -71,6 +72,7 @@ export class UniverDrawingUIPlugin extends Plugin {const dependencies: Dependency[] = [[DrawingImageClipService],[DrawingRenderService],+ [OleUIService],[DrawingUpdateController],[DrawingUIController],[ImageCropperController],diff --git a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.tsindex 8fe6459976..61c1c3b921 100644--- a/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts+++ b/packages/drawing-ui/src/services/__tests__/drawing-render.service.spec.ts@@ -38,8 +38,10 @@ import { DRAWING_OBJECT_LAYER_INDEX, Image, Rect } from '@univerjs/engine-renderimport { IGalleryService } from '@univerjs/ui';import { Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';+import { OleObject } from '../../views/ole/ole-object';import { DrawingImageClipService } from '../drawing-image-clip.service';import { DOC_DRAWING_BEHIND_TEXT_LAYER_INDEX, DrawingRenderService } from '../drawing-render.service';+import { OleUIService } from '../ole-ui.service';const BASE_TRANSFORM = {left: 10,@@ -273,6 +275,8 @@ function createScene(): IRecordedScene {function createHarness() {const injector = new Injector();+ const oleUI = { bindObject: vi.fn() };+ injector.add([OleUIService, { useValue: oleUI as never }]);injector.add([IDrawingManagerService, { useClass: TestDrawingManagerService as never }]);injector.add([IImageIoService, { useClass: TestImageIoService as never }]);@@ -284,6 +288,7 @@ function createHarness() {return {service: injector.get(DrawingRenderService),+ oleUI,drawingManagerService: injector.get(IDrawingManagerService) as unknown as TestDrawingManagerService,imageIoService: injector.get(IImageIoService) as unknown as TestImageIoService,urlImageService: injector.get(IURLImageService) as unknown as TestUrlImageService,@@ -295,6 +300,32 @@ function createHarness() {}describe('DrawingRenderService', () => {+ it('renders OLE attachments with their menu binding and disables rotation', async () => {+ const harness = createHarness();+ const drawing = imageParam({ drawingType: DrawingTypeEnum.DRAWING_OLE, imageSourceType: ImageSourceType.UUID });+ const readSource = vi.spyOn(harness.imageIoService, 'getImage');+ const readCache = vi.spyOn(harness.imageIoService, 'getImageSourceCache');+ await harness.service.renderImages(drawing, harness.scene as unknown as Scene);+ const object = harness.scene.addedObjects[0].object;+ expect(object).toBeInstanceOf(OleObject);+ expect(readSource).not.toHaveBeenCalled();+ expect(readCache).not.toHaveBeenCalled();+ expect(object.transformerConfig?.rotateEnabled).toBe(false);+ expect(harness.oleUI.bindObject).toHaveBeenCalledWith(object, drawing, true);+ });++ it.each([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC])('paints OLE print copies without registering editor interaction (host: %s)', async (type) => {+ const h = createHarness();+ h.univerInstanceService.unitType = type;+ const drawing = imageParam({ drawingType: DrawingTypeEnum.DRAWING_OLE });+ h.drawingManagerService.drawings.set(drawingKey(drawing), drawing);+ await h.service.renderImages(drawing, h.scene as unknown as Scene);+ const printScene = createScene();+ await h.service.renderDrawing(drawing, printScene as unknown as Scene, { allowInactiveSheet: true, interactive: false });+ expect(printScene.addedObjects[0].object).toBeInstanceOf(OleObject);+ expect(h.oleUI.bindObject.mock.calls.map((call) => call[2])).toEqual([true, false]);+ });+it('skips image rendering when the drawing is not renderable in the current context', async () => {const hiddenCase = createHarness();hiddenCase.drawingManagerService.visible = false;diff --git a/packages/drawing-ui/src/services/__tests__/ole-preview-viewer.spec.ts b/packages/drawing-ui/src/services/__tests__/ole-preview-viewer.spec.tsnew file mode 100644index 0000000000..d99b040b52--- /dev/null+++ b/packages/drawing-ui/src/services/__tests__/ole-preview-viewer.spec.ts@@ -0,0 +1,85 @@+/**+ * 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.+ */++// @vitest-environment happy-dom++import { IConfigService, IImageIoService, LocaleService, ThemeService, Univer, UniverInstanceType } from '@univerjs/core';+import { UI_PLUGIN_CONFIG_KEY } from '@univerjs/ui';+import { describe, expect, it } from 'vitest';+import { createOlePreviewViewer } from '../ole-preview-viewer';++describe('isolated OLE preview dependencies', () => {+ it.each([+ { type: UniverInstanceType.UNIVER_SHEET, footer: true },+ { type: UniverInstanceType.UNIVER_DOC, footer: false },+ { type: UniverInstanceType.UNIVER_SLIDE, footer: false },+ ])('keeps native worksheet navigation available only for Sheet previews ($type)', ({ type, footer }) => {+ const host = new Univer();+ const injector = host.__getInjector();+ const stop = new Error('preview configuration inspected');+ try {+ expect(() => createOlePreviewViewer({+ container: document.createElement('div'),+ data: {},+ type,+ locale: injector.get(LocaleService),+ theme: injector.get(ThemeService),+ config: injector.get(IConfigService),+ register: (viewer) => {+ expect(viewer.__getInjector().get(IConfigService).getConfig(UI_PLUGIN_CONFIG_KEY)).toMatchObject({+ footer,+ header: false,+ toolbar: false,+ contextMenu: false,+ });+ throw stop;+ },+ setReadonly: () => {},+ })).toThrow(stop);+ } finally {+ host.dispose();+ }+ });++ it('keeps standalone image IO when collaboration overrides disable it in the source instance', async () => {+ const host = new Univer();+ const injector = host.__getInjector();+ const config = injector.get(IConfigService);+ const override = [[IImageIoService, null]] as const;+ config.setConfig('drawing.config', { override });+ const stop = new Error('dependency check complete');+ let imageIO: IImageIoService | undefined;+ try {+ expect(() => createOlePreviewViewer({+ container: document.createElement('div'),+ data: {},+ type: UniverInstanceType.UNIVER_SLIDE,+ locale: injector.get(LocaleService),+ theme: injector.get(ThemeService),+ config,+ register: (viewer) => {+ imageIO = viewer.__getInjector().get(IImageIoService);+ throw stop;+ },+ setReadonly: () => {},+ })).toThrow(stop);+ expect(await imageIO!.getImage('data:image/png;base64,preview')).toBe('data:image/png;base64,preview');+ expect(config.getConfig('drawing.config')).toEqual({ override });+ } finally {+ host.dispose();+ }+ });+});diff --git a/packages/drawing-ui/src/services/__tests__/ole-ui.service.spec.ts b/packages/drawing-ui/src/services/__tests__/ole-ui.service.spec.tsnew file mode 100644index 0000000000..72e738d7e8--- /dev/null+++ b/packages/drawing-ui/src/services/__tests__/ole-ui.service.spec.ts@@ -0,0 +1,718 @@+/**+ * 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.+ */++// @vitest-environment happy-dom++import type { IOleConfig, IOleDrawing, IOleOnlineUnit, IOleResource } from '@univerjs/drawing';+import {+ DrawingTypeEnum,+ IConfigService,+ Injector,+ IUniverInstanceService,+ LocaleService,+ ThemeService,+ UniverInstanceType,+} from '@univerjs/core';+import { IDrawingManagerService, OleService, UnitDrawingService } from '@univerjs/drawing';+import { Image } from '@univerjs/engine-render';+import { IDialogService, IMessageService, INotificationService } from '@univerjs/ui';+import { Buffer } from 'node:buffer';+import { createHash, webcrypto } from 'node:crypto';+import { Subject } from 'rxjs';+import { afterEach, describe, expect, it, vi } from 'vitest';+import type { IOleHostActions } from '../ole-ui.service';+import { OleCanvasRenderer } from '../../views/ole/ole-canvas-renderer';+import { OleObject } from '../../views/ole/ole-object';+import * as previewRegistry from '../ole-preview-viewer';+import { OLE_POPUP_COMPONENT, OleUIService } from '../ole-ui.service';++const bytes = new TextEncoder().encode('%PDF-1.7 original');+const sha256 = createHash('sha256').update(bytes).digest('hex');+const injectors: Injector[] = [];++function harness(online = false, type = UniverInstanceType.UNIVER_SHEET) {+ vi.stubGlobal('crypto', webcrypto);+ const drawing = { unitId: 'host', subUnitId: 'page', drawingId: 'drawing', drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'ole-1' } as IOleDrawing;+ const resource = {+ version: 1,+ files: { [sha256]: { name: 'original.pdf', mimeType: 'application/pdf', size: bytes.length, sha256, ...(online ? { attachment: { source: 'stable-file', sourceType: 'UUID' } } : { data: Buffer.from(bytes).toString('base64') }) } },+ objects: { 'ole-1': { id: 'ole-1', fileId: sha256, external: false } },+ } as unknown as IOleResource;+ const focus$ = new Subject<unknown[]>();+ const remove$ = new Subject<unknown[]>();+ const enter$ = new Subject<void>();+ const leave$ = new Subject<void>();+ const pointerDown$ = new Subject<void>();+ const doubleClick$ = new Subject<void>();+ const events = (subject: Subject<void>) => ({ subscribeEvent: (callback: () => void) => subject.subscribe(callback) });+ const object = { makeDirty: vi.fn(), onPointerEnter$: events(enter$), onPointerLeave$: events(leave$), onPointerDown$: events(pointerDown$), onDblclick$: events(doubleClick$) };+ let present = true;+ const io = { upload: vi.fn(), read: vi.fn(async () => bytes.slice()) };+ const drawings = { focus$, remove$, getDrawingByParam: () => present ? drawing : undefined, getDrawingEditable: () => true };+ const disposed$ = new Subject<{ getUnitId: () => string }>();+ const config: IOleConfig = { attachmentIo: io };+ const messages = { show: vi.fn() };+ const dialogs = { open: vi.fn(), close: vi.fn() };+ const notifications = { show: vi.fn<INotificationService['show']>(() => ({ dispose: vi.fn() })) };+ const injector = new Injector([+ [OleService, { useValue: { getResource: () => resource } }],+ [IDrawingManagerService, { useValue: drawings }],+ [IUniverInstanceService, { useValue: { getUnit: () => ({ type }), getTypeOfUnitDisposed$: () => disposed$ } }],+ [IConfigService, { useValue: { getConfig: () => ({ ole: config }) } }],+ [LocaleService, { useValue: { t: (key: string, ...args: unknown[]) => args.length ? `${key}:${args.join(',')}` : key } }],+ [IMessageService, { useValue: messages }],+ [IDialogService, { useValue: dialogs }],+ [INotificationService, { useValue: notifications }],+ [ThemeService],+ [OleUIService],+ ]);+ injectors.push(injector);+ const service = injector.get(OleUIService);+ const attach = vi.fn<IOleHostActions['attach']>(() => ({ dispose: vi.fn() }));+ const remove = vi.fn(async () => true);+ service.registerHost(type, { attach, remove });+ service.bindObject(object as never, drawing);+ return { injector, service, drawing, resource, config, drawings, disposed$, messages, notifications, pointerDown$, restoreModel: () => {+ present = true;+ }, hideGlobalModel: () => {+ present = false;+ }, enter$, leave$, focus$, remove$, io, dialogs, attach, remove, removeModel: () => {+ present = false;+ remove$.next([drawing]);+ } };+}++afterEach(() => {+ injectors.splice(0).forEach((injector) => injector.dispose());+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ vi.useRealTimers();+});++describe('OLE local UI lifecycle', () => {+ it.each([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC, UniverInstanceType.UNIVER_SLIDE])('keeps selection on one toolbar and explicitly replaces it for rename (host: %s)', (type) => {+ const h = harness(false, type);+ const rename = vi.fn(async () => true);+ h.service.registerHost(type, { attach: h.attach, remove: h.remove, rename });+ const saved = JSON.stringify(h.resource);+ h.pointerDown$.next();+ expect(h.attach.mock.lastCall?.[1]).toBe(OLE_POPUP_COMPONENT);+ expect(h.attach).toHaveBeenCalledOnce();+ const toolbar = h.attach.mock.results[0].value;+ const actions = h.attach.mock.lastCall![2] as { rename: () => void };+ actions.rename();+ expect(toolbar.dispose).toHaveBeenCalledOnce();+ expect(h.attach.mock.lastCall?.[1]).toBe('drawing.ole-name');+ expect(h.attach.mock.lastCall?.[4]).toBe('top-center');+ expect(h.attach.mock.lastCall?.[2]).not.toHaveProperty('editing');+ const editor = h.attach.mock.results[1].value;+ h.focus$.next([]);+ h.focus$.next([h.drawing]);+ expect(editor.dispose).not.toHaveBeenCalled();+ const editorActions = h.attach.mock.lastCall![2] as { close: () => void };+ editorActions.close();+ expect(editor.dispose).toHaveBeenCalledOnce();+ h.pointerDown$.next();+ expect(h.attach.mock.lastCall?.[1]).toBe(OLE_POPUP_COMPONENT);+ expect(h.attach).toHaveBeenCalledTimes(3);+ expect(JSON.stringify(h.resource)).toBe(saved);+ expect(h.io.read).not.toHaveBeenCalled();+ });++ it.each([false, true])('selects an unavailable attachment without opening a separate name popup (external: %s)', (external) => {+ const h = harness();+ Object.assign(h.resource.objects['ole-1'], { external, fileId: undefined });+ h.pointerDown$.next();+ h.focus$.next([h.drawing]);+ expect(h.attach.mock.calls.every((call) => call[1] === OLE_POPUP_COMPONENT)).toBe(true);+ expect(h.attach.mock.lastCall?.[2]).toMatchObject({ available: false, rename: undefined });+ });++ it.each([false, true])('explains unavailable external attachments once without reading or mutating them (Unit: %s)', async (unit) => {+ const h = harness(unit);+ Object.assign(h.resource.objects['ole-1'], { external: true, fileId: undefined });+ const original = JSON.stringify(h.resource);+ const image = new Image('unavailable', { width: 128, height: 80 });+ h.service.bindObject(image, h.drawing, false);+ expect(h.messages.show).not.toHaveBeenCalled();+ h.service.bindObject(image, h.drawing);+ expect(h.messages.show).toHaveBeenCalledWith(expect.objectContaining({ content: 'drawing-ui.ole.unavailableSummary:1' }));+ const rebound = new Image('rebound', { width: 128, height: 80 });+ h.service.bindObject(rebound, h.drawing);+ h.focus$.next([h.drawing]);+ expect(h.messages.show).toHaveBeenCalledOnce();+ expect(h.attach.mock.lastCall?.[2]).toMatchObject({+ available: false,+ fileName: 'drawing-ui.ole.externalAttachment',+ status: 'drawing-ui.ole.externalHint',+ showConvert: false,+ rename: undefined,+ });+ await h.service.preview(h.drawing);+ expect(h.messages.show).toHaveBeenLastCalledWith(expect.objectContaining({ content: 'drawing-ui.ole.externalHint' }));+ expect(h.io.read).not.toHaveBeenCalled();+ expect(h.io.upload).not.toHaveBeenCalled();+ expect(h.dialogs.open).not.toHaveBeenCalled();+ expect(JSON.stringify(h.resource)).toBe(original);+ h.disposed$.next({ getUnitId: () => 'host' });+ const reopened = new Image('reopened', { width: 128, height: 80 });+ h.service.bindObject(reopened, h.drawing);+ expect(h.messages.show).toHaveBeenLastCalledWith(expect.objectContaining({ content: 'drawing-ui.ole.unavailableSummary:1' }));+ expect(h.messages.show).toHaveBeenCalledTimes(3);+ image.dispose();+ rebound.dispose();+ reopened.dispose();+ });++ it('distinguishes missing data from external links and preserves a known occurrence name', async () => {+ const h = harness();+ h.resource.objects['ole-1'].fileId = 'missing-file';+ h.drawing.oleFileName = 'known.pdf';+ h.focus$.next([h.drawing]);+ expect(h.attach.mock.lastCall?.[2]).toMatchObject({ available: false, fileName: 'known.pdf', status: 'drawing-ui.ole.missingHint' });+ await h.service.preview(h.drawing);+ expect(h.messages.show).toHaveBeenLastCalledWith(expect.objectContaining({ content: 'drawing-ui.ole.missingHint' }));+ expect(h.io.read).not.toHaveBeenCalled();+ expect(h.dialogs.open).not.toHaveBeenCalled();+ });++ it('installs live canvas content for existing OLE drawings without changing their snapshot', () => {+ const h = harness();+ const saved = JSON.stringify(h.resource);+ const image = new OleObject('canvas-ole', { width: 96, height: 64 });+ const setter = vi.spyOn(image, 'setRenderer');+ h.service.bindObject(image, h.drawing);+ expect(setter).toHaveBeenCalledWith(expect.any(OleCanvasRenderer));+ expect(JSON.stringify(h.resource)).toBe(saved);+ expect(h.io.read).not.toHaveBeenCalled();+ image.dispose();+ });++ it('renders thumbnails without replacing the interactive canvas binding', () => {+ const h = harness();+ const image = new OleObject('thumbnail', { width: 96, height: 64 });+ const setter = vi.spyOn(image, 'setRenderer');+ h.service.bindObject(image, h.drawing, false);+ expect(setter).toHaveBeenCalledWith(expect.any(OleCanvasRenderer));+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[0]).not.toBe(image);+ image.dispose();+ });++ it('hover and keyboard selection expose actions without reading or converting the attachment', () => {+ const h = harness(true);+ h.enter$.next();+ expect(h.attach).toHaveBeenCalledOnce();+ expect(h.attach.mock.calls[0][2]).toMatchObject({ available: true, fileName: 'original.pdf', download: expect.any(Function), preview: expect.any(Function), remove: expect.any(Function) });+ h.focus$.next([h.drawing]);+ expect(h.attach).toHaveBeenCalledTimes(2);+ expect(h.io.read).not.toHaveBeenCalled();+ expect(h.io.upload).not.toHaveBeenCalled();+ expect(h.dialogs.open).not.toHaveBeenCalled();+ });++ it('rechecks edit permission when an already open Delete action is invoked', async () => {+ const h = harness();+ let editable = true;+ h.service.registerHost(UniverInstanceType.UNIVER_SHEET, { attach: h.attach, remove: h.remove, isEditable: () => editable });+ h.enter$.next();+ const actions = h.attach.mock.lastCall![2] as { remove: () => Promise<void> };+ editable = false;+ await actions.remove();+ expect(h.remove).not.toHaveBeenCalled();+ });++ it('never opens a filename tooltip on hover', () => {+ vi.useFakeTimers();+ const h = harness();+ h.enter$.next();+ vi.advanceTimersByTime(1200);+ expect(h.attach).toHaveBeenCalledOnce();+ expect(h.attach.mock.lastCall?.[1]).toBe(OLE_POPUP_COMPONENT);+ });++ it.each([false, true])('renames only the occurrence and downloads the effective name (Unit: %s)', async (unit) => {+ const h = harness(unit);+ const original = JSON.stringify(h.resource);+ const rename = vi.fn(async (_drawing, name) => {+ h.drawing.oleFileName = name;+ return true;+ });+ h.service.registerHost(UniverInstanceType.UNIVER_SHEET, { attach: h.attach, remove: h.remove, rename });+ expect(await h.service.rename(h.drawing, '新名称')).toBeUndefined();+ expect(rename).toHaveBeenCalledWith(h.drawing, '新名称.pdf');+ expect(JSON.stringify(h.resource)).toBe(original);+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:renamed');+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ expect(this.download).toBe('新名称.pdf');+ });+ await h.service.download(h.drawing);+ expect(click).toHaveBeenCalledOnce();+ expect(h.io.upload).not.toHaveBeenCalled();+ });++ it('leaves another occurrence sharing the same file with its own name', async () => {+ const h = harness();+ const other = { ...h.drawing, drawingId: 'other', oleAttachmentId: 'ole-2' };+ h.resource.objects['ole-2'] = { ...h.resource.objects['ole-1'], id: 'ole-2', drawingId: 'other' };+ h.injector.add([UnitDrawingService]);+ const local = h.injector.get(UnitDrawingService);+ local.registerDrawingData('host', { page: { data: { drawing: { ...h.drawing }, other }, order: ['drawing', 'other'] } });+ h.service.registerHost(UniverInstanceType.UNIVER_SHEET, {+ attach: h.attach,+ remove: h.remove,+ drawingService: local,+ rename: async (drawing, name) => {+ (local.getDrawingByParam(drawing)! as IOleDrawing).oleFileName = name;+ return true;+ },+ });+ expect(await h.service.rename(h.drawing, 'renamed')).toBeUndefined();+ expect(local.getDrawingByParam(h.drawing)).toMatchObject({ oleFileName: 'renamed.pdf' });+ expect(local.getDrawingByParam(other)).not.toHaveProperty('oleFileName');+ expect(h.resource.files[sha256].name).toBe('original.pdf');+ });++ it('rejects invalid names, read-only changes and command failures without changing bytes', async () => {+ const h = harness();+ const rename = vi.fn(async () => false);+ h.service.registerHost(UniverInstanceType.UNIVER_SHEET, { attach: h.attach, remove: h.remove, rename });+ for (const value of ['', '../escape', 'a/b', 'a\\b', 'a?', 'x'.repeat(256)]) {+ expect(await h.service.rename(h.drawing, value)).toContain('invalidName');+ }+ expect(rename).not.toHaveBeenCalled();+ expect(await h.service.rename(h.drawing, 'valid')).toContain('renameFailed');+ h.service.registerHost(UniverInstanceType.UNIVER_SHEET, { attach: h.attach, remove: h.remove, rename, isEditable: () => false });+ expect(await h.service.rename(h.drawing, 'valid')).toContain('renameFailed');+ expect(rename).toHaveBeenCalledOnce();+ expect(h.drawing.oleFileName).toBeUndefined();+ expect(h.resource.files[sha256].name).toBe('original.pdf');+ });++ it('keeps the menu open when moving from the object onto its controls', () => {+ vi.useFakeTimers();+ const h = harness();+ h.enter$.next();+ h.leave$.next();+ const actions = h.attach.mock.calls[0][2] as { onEnter: () => void };+ actions.onEnter();+ vi.advanceTimersByTime(200);+ expect(h.attach.mock.results[0].value.dispose).not.toHaveBeenCalled();+ });++ it('opens the PDF only on request and does not mutate persisted attachment data', async () => {+ const h = harness();+ const saved = JSON.stringify(h.resource);+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:verified-pdf');+ await h.service.preview(h.drawing);+ expect(h.dialogs.open).toHaveBeenCalledWith(expect.objectContaining({ children: expect.objectContaining({ value: expect.stringContaining('blob:verified-pdf') }) }));+ expect(JSON.stringify(h.resource)).toBe(saved);+ });++ it.each(['application/pdf', 'application/msword'])('gives nested preview a stable focus owner for %s', async (mimeType) => {+ const h = harness();+ h.resource.files[sha256].mimeType = mimeType;+ h.config.convertOffice = vi.fn(async () => ({ type: UniverInstanceType.UNIVER_DOC, data: {} }));+ vi.spyOn(previewRegistry, 'getOlePreviewRenderer').mockReturnValue(vi.fn());+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:preview');+ const owner = document.createElement('div');+ owner.setAttribute('role', 'dialog');+ owner.tabIndex = -1;+ const button = document.createElement('button');+ owner.appendChild(button);+ document.body.appendChild(owner);+ button.focus();+ h.dialogs.open.mockImplementation(() => {+ expect(document.activeElement).toBe(owner);+ });+ try {+ await h.service.preview(h.drawing);+ expect(h.dialogs.open).toHaveBeenCalledOnce();+ button.remove();+ expect(document.activeElement).toBe(owner);+ } finally {+ owner.remove();+ }+ });++ it.each([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC])('uses one product UI factory whether its host already exists or not (host: %s)', async (type) => {+ const h = harness(false, type);+ h.resource.files[sha256].mimeType = 'application/msword';+ const data = { id: 'preview-doc' };+ h.config.convertOffice = vi.fn(async () => ({ type: UniverInstanceType.UNIVER_DOC, data }));+ const renderer = { dispose: vi.fn() };+ const factory = vi.fn(() => renderer);+ vi.spyOn(previewRegistry, 'getOlePreviewRenderer').mockImplementation((type) => type === UniverInstanceType.UNIVER_DOC ? factory : undefined);+ await h.service.preview(h.drawing);+ const id = h.dialogs.open.mock.lastCall![0].children.value;+ const container = document.createElement('div');+ const mounted = h.service.mountOfficePreview(id, container)!;+ await Promise.resolve();+ expect(factory).toHaveBeenCalledWith(expect.objectContaining({ container, data, type: UniverInstanceType.UNIVER_DOC, theme: h.injector.get(ThemeService) }));+ mounted.dispose();+ expect(renderer.dispose).toHaveBeenCalledOnce();+ });++ it.each([false, true])('does not read or convert Office attachments when their product UI is absent (Unit: %s)', async (unit) => {+ const h = harness(unit);+ h.resource.files[sha256].mimeType = 'application/msword';+ h.config.convertOffice = vi.fn();+ vi.spyOn(previewRegistry, 'getOlePreviewRenderer').mockReturnValue(undefined);+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[2]).toMatchObject({ available: true, previewAvailable: false });+ await h.service.preview(h.drawing);+ expect(h.config.convertOffice).not.toHaveBeenCalled();+ expect(h.io.read).not.toHaveBeenCalled();+ expect(h.dialogs.open).not.toHaveBeenCalled();+ expect(h.messages.show).toHaveBeenLastCalledWith(expect.objectContaining({ content: 'drawing-ui.ole.unsupported' }));+ });++ it('retains application preview overrides instead of replacing them with a registered product default', async () => {+ const h = harness();+ h.resource.files[sha256].mimeType = 'application/msword';+ h.config.convertOffice = vi.fn(async () => ({ type: UniverInstanceType.UNIVER_DOC, data: { id: 'preview-doc' } }));+ const custom = { dispose: vi.fn() };+ h.config.createOfficePreview = vi.fn(async () => custom);+ const factory = vi.fn();+ vi.spyOn(previewRegistry, 'getOlePreviewRenderer').mockReturnValue(factory);+ await h.service.preview(h.drawing);+ const mounted = h.service.mountOfficePreview(h.dialogs.open.mock.lastCall![0].children.value, document.createElement('div'))!;+ await Promise.resolve();+ expect(h.config.createOfficePreview).toHaveBeenCalledOnce();+ expect(factory).not.toHaveBeenCalled();+ mounted.dispose();+ expect(custom.dispose).toHaveBeenCalledOnce();+ });++ it('a remote deletion cancels a pending read and prevents the late preview from reopening', async () => {+ const h = harness(true);+ let finish!: (value: Uint8Array<ArrayBuffer>) => void;+ h.io.read.mockImplementation(() => new Promise((resolve) => {+ finish = resolve;+ }));+ const preview = h.service.preview(h.drawing);+ h.removeModel();+ finish(bytes);+ await expect(preview).rejects.toThrow('aborted');+ expect(h.dialogs.open).not.toHaveBeenCalled();+ });+ it('uses the host drawing service for slide focus, file lookup and remote deletion', async () => {+ const h = harness(true);+ h.injector.add([UnitDrawingService]);+ const separate = h.injector.get(UnitDrawingService);+ separate.registerDrawingData('host', { page: { data: { drawing: h.drawing }, order: ['drawing'] } });+ h.service.registerHost(UniverInstanceType.UNIVER_SHEET, { drawingService: separate, attach: h.attach, remove: h.remove });+ h.hideGlobalModel();+ separate.focusDrawing([h.drawing]);+ expect(h.attach).toHaveBeenCalledOnce();+ let finish!: (value: Uint8Array<ArrayBuffer>) => void;+ h.io.read.mockImplementation(() => new Promise((resolve) => {+ finish = resolve;+ }));+ const preview = h.service.preview(h.drawing);+ separate.removeNotification([h.drawing]);+ finish(bytes);+ await expect(preview).rejects.toThrow('aborted');+ expect(h.dialogs.open).not.toHaveBeenCalled();+ });+});++const online: IOleOnlineUnit = { unitId: 'created-doc', type: UniverInstanceType.UNIVER_DOC };+const onlineUrl = 'https://example.test/doc/created-doc';++function collaborativeHarness(type = UniverInstanceType.UNIVER_SHEET) {+ const h = harness(true, type);+ h.resource.files[sha256].mimeType = 'application/msword';+ h.resource.files[sha256].name = 'original.doc';+ h.config.isCollaborative = vi.fn((unitId) => unitId === 'host');+ const getLink = vi.fn((_unitId: string, _type: UniverInstanceType) => onlineUrl);+ h.config.getLink = getLink;+ const convert = vi.fn<NonNullable<IOleConfig['convertToOnline']>>(async () => online);+ h.config.convertToOnline = convert;+ const save = vi.fn(async (_drawing: unknown, value: IOleOnlineUnit) => {+ h.drawing.oleOnlineUnit = value;+ return true;+ });+ h.service.registerHost(type, { attach: h.attach, remove: h.remove, saveOnlineUnit: save });+ const open = vi.spyOn(window, 'open').mockReturnValue(null);+ return { ...h, convert, save, open, getLink };+}++describe('explicit collaborative OLE conversion', () => {+ it('shows conversion for the exact server host, but hides it for local JSON and PDF attachments', () => {+ const h = collaborativeHarness();+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[2]).toMatchObject({ showConvert: true, officeType: UniverInstanceType.UNIVER_DOC });+ expect(h.config.isCollaborative).toHaveBeenCalledWith('host');+ h.config.isCollaborative = () => false;+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[2].showConvert).toBe(false);+ h.config.isCollaborative = () => true;+ h.resource.files[sha256].mimeType = 'application/pdf';+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[2].showConvert).toBe(false);+ expect(h.convert).not.toHaveBeenCalled();+ expect(h.io.read).not.toHaveBeenCalled();+ });++ it('imports once, waits on the source page and opens only after an explicit user action', async () => {+ const h = collaborativeHarness();+ const before = JSON.stringify(h.resource);+ const first = h.service.convertToOnline(h.drawing);+ const second = h.service.convertToOnline(h.drawing);+ expect(first).toBe(second);+ expect(h.open).not.toHaveBeenCalled();+ await first;+ expect(h.convert).toHaveBeenCalledOnce();+ expect(h.convert).toHaveBeenCalledWith(expect.objectContaining({ fileId: 'stable-file', unitId: 'host' }));+ expect(h.convert.mock.calls[0][0]).not.toHaveProperty('bytes');+ expect(h.save).toHaveBeenCalledWith(h.drawing, online);+ expect(h.drawing.oleOnlineUnit).not.toHaveProperty('url');+ expect(h.getLink).not.toHaveBeenCalled();+ expect(h.open).not.toHaveBeenCalled();+ expect(h.notifications.show).toHaveBeenLastCalledWith(expect.objectContaining({+ type: 'success',+ title: 'drawing-ui.ole.converted',+ content: 'original.doc',+ action: { label: 'drawing-ui.ole.open', onClick: expect.any(Function) },+ }));+ expect(JSON.stringify(h.resource)).toBe(before);+ await h.service.convertToOnline(h.drawing);+ expect(h.convert).toHaveBeenCalledOnce();+ expect(h.io.read).not.toHaveBeenCalled();+ expect(h.open).toHaveBeenLastCalledWith(onlineUrl, '_blank', 'noopener,noreferrer');+ expect(h.attach.mock.lastCall?.[2].hasOnlineUnit).toBe(true);+ });++ it.each([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC, UniverInstanceType.UNIVER_SLIDE])('offers an Open action only after the link has been saved (host: %s)', async (type) => {+ const h = collaborativeHarness(type);+ let finishSave!: () => void;+ h.save.mockImplementation(async (_drawing, value) => {+ await new Promise<void>((resolve) => {+ finishSave = resolve;+ });+ h.drawing.oleOnlineUnit = value;+ return true;+ });+ const pending = h.service.convertToOnline(h.drawing);+ await vi.waitFor(() => expect(h.save).toHaveBeenCalledOnce());+ expect(h.open).not.toHaveBeenCalled();+ expect(h.drawing.oleOnlineUnit).toBeUndefined();+ expect(h.notifications.show).toHaveBeenCalledOnce();+ finishSave();+ await pending;+ expect(h.drawing.oleOnlineUnit).toEqual(online);+ expect(h.open).not.toHaveBeenCalled();+ const action = h.notifications.show.mock.calls.at(-1)![0].action;+ if (!action || typeof action !== 'object' || !('onClick' in action)) throw new Error('Missing Open action');+ h.config.getLink = vi.fn(() => 'https://new-domain.test/new-route/created-doc');+ action.onClick({} as never);+ expect(h.open).toHaveBeenCalledOnce();+ expect(h.open).toHaveBeenCalledWith('https://new-domain.test/new-route/created-doc', '_blank', 'noopener,noreferrer');+ h.injector.dispose();+ expect(h.notifications.show.mock.results.at(-1)!.value.dispose).toHaveBeenCalledOnce();+ });++ it('reports a failed completion Open and allows a corrected resolver without reconverting', async () => {+ const h = collaborativeHarness();+ await h.service.convertToOnline(h.drawing);+ const action = h.notifications.show.mock.calls.at(-1)![0].action;+ if (!action || typeof action !== 'object' || !('onClick' in action)) throw new Error('Missing Open action');+ h.config.getLink = () => {+ throw new Error('Application route unavailable');+ };+ action.onClick({} as never);+ await vi.waitFor(() => expect(h.messages.show).toHaveBeenCalledWith(expect.objectContaining({ content: 'drawing-ui.ole.failed' })));+ expect(h.open).not.toHaveBeenCalled();+ h.config.getLink = () => onlineUrl;+ action.onClick({} as never);+ expect(h.open).toHaveBeenCalledWith(onlineUrl, '_blank', 'noopener,noreferrer');+ expect(h.convert).toHaveBeenCalledOnce();+ expect(h.drawing.oleOnlineUnit).toEqual(online);+ });++ it('also keeps inline attachment conversion on the source page', async () => {+ const h = collaborativeHarness();+ delete h.resource.files[sha256].attachment;+ h.resource.files[sha256].data = Buffer.from(bytes).toString('base64');+ await h.service.convertToOnline(h.drawing);+ expect(h.convert).toHaveBeenCalledWith(expect.objectContaining({ bytes, unitId: 'host' }));+ expect(h.convert.mock.calls[0][0]).not.toHaveProperty('fileId');+ expect(h.drawing.oleOnlineUnit).toEqual(online);+ expect(h.notifications.show).toHaveBeenLastCalledWith(expect.objectContaining({ type: 'success' }));+ expect(h.open).not.toHaveBeenCalled();+ });++ it.each(['deletion', 'unit disposal'])('suppresses completion when %s occurs while saving the link', async (reason) => {+ const h = collaborativeHarness();+ let finishSave!: (value: boolean) => void;+ h.save.mockImplementation(() => new Promise<boolean>((resolve) => {+ finishSave = resolve;+ }));+ const pending = h.service.convertToOnline(h.drawing);+ await vi.waitFor(() => expect(h.save).toHaveBeenCalledOnce());+ if (reason === 'deletion') h.removeModel();+ else h.disposed$.next({ getUnitId: () => 'host' });+ finishSave(true);+ await pending;+ expect(h.notifications.show).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }));+ expect(h.open).not.toHaveBeenCalled();+ });++ it('retries saving a created link without creating a second online document', async () => {+ const h = collaborativeHarness();+ h.save.mockResolvedValueOnce(false);+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow('could not be saved');+ expect(h.open).not.toHaveBeenCalled();+ expect(h.drawing.oleOnlineUnit).toBeUndefined();+ expect(h.notifications.show).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }));+ await h.service.convertToOnline(h.drawing);+ expect(h.convert).toHaveBeenCalledOnce();+ expect(h.save).toHaveBeenCalledTimes(2);+ expect(h.drawing.oleOnlineUnit).toEqual(online);+ });++ it('does not import for a read-only host, but allows reopening a saved online document', async () => {+ const h = collaborativeHarness();+ h.drawings.getDrawingEditable = () => false;+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow('read-only');+ expect(h.convert).not.toHaveBeenCalled();+ expect(h.open).not.toHaveBeenCalled();+ h.drawing.oleOnlineUnit = online;+ await h.service.convertToOnline(h.drawing);+ expect(h.open).toHaveBeenCalledWith(onlineUrl, '_blank', 'noopener,noreferrer');+ });++ it('retains a conversion result but does not save its link after edit permission is revoked', async () => {+ const h = collaborativeHarness();+ let complete!: (value: IOleOnlineUnit) => void;+ h.convert.mockImplementation(() => new Promise((resolve) => {+ complete = resolve;+ }));+ const pending = h.service.convertToOnline(h.drawing);+ await vi.waitFor(() => expect(h.convert).toHaveBeenCalledOnce());+ h.drawings.getDrawingEditable = () => false;+ complete(online);+ await expect(pending).rejects.toThrow('could not be saved');+ expect(h.save).not.toHaveBeenCalled();+ expect(h.drawing.oleOnlineUnit).toBeUndefined();+ });++ it.each(['deletion', 'unit disposal'])('discards a late conversion after %s', async (reason) => {+ const h = collaborativeHarness();+ let complete!: (value: IOleOnlineUnit) => void;+ h.convert.mockImplementation(() => new Promise((resolve) => {+ complete = resolve;+ }));+ const pending = h.service.convertToOnline(h.drawing);+ await vi.waitFor(() => expect(h.convert).toHaveBeenCalledOnce());+ const progress = h.notifications.show.mock.results[0].value;+ expect(progress.dispose).not.toHaveBeenCalled();+ h.convert.mock.calls[0][0].onProgress?.('creating');+ if (reason === 'deletion') h.removeModel();+ else h.disposed$.next({ getUnitId: () => 'host' });+ expect(progress.dispose).toHaveBeenCalledOnce();+ expect(h.open).not.toHaveBeenCalled();+ complete(online);+ await pending;+ expect(h.save).not.toHaveBeenCalled();+ expect(h.drawing.oleOnlineUnit).toBeUndefined();+ expect(h.open).not.toHaveBeenCalled();+ });++ it('does not let a cancelled request overwrite a new conversion after deletion is undone', async () => {+ const h = collaborativeHarness();+ const complete: Array<(value: IOleOnlineUnit) => void> = [];+ h.convert.mockImplementation(() => new Promise((resolve) => {+ complete.push(resolve);+ }));+ const old = h.service.convertToOnline(h.drawing);+ await vi.waitFor(() => expect(h.convert).toHaveBeenCalledTimes(1));+ h.removeModel();+ h.restoreModel();+ const current = h.service.convertToOnline(h.drawing);+ await vi.waitFor(() => expect(h.convert).toHaveBeenCalledTimes(2));+ complete[0](online);+ await old;+ expect(h.service.convertToOnline(h.drawing)).toBe(current);+ expect(h.save).not.toHaveBeenCalled();+ complete[1]({ ...online, unitId: 'new-request' });+ await current;+ expect(h.drawing.oleOnlineUnit?.unitId).toBe('new-request');+ expect(h.save).toHaveBeenCalledOnce();+ });++ it('keeps failed imports and invalid Unit identities out of the drawing snapshot', async () => {+ const h = collaborativeHarness();+ h.convert.mockRejectedValueOnce(new Error('import failed'));+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow('import failed');+ h.convert.mockResolvedValueOnce({ ...online, unitId: '' });+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow('Invalid');+ expect(h.save).not.toHaveBeenCalled();+ expect(h.drawing.oleOnlineUnit).toBeUndefined();+ expect(h.open).not.toHaveBeenCalled();+ expect(h.notifications.show).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }));+ });++ it('ignores a legacy stored URL and resolves each Open with the current application config', async () => {+ const h = collaborativeHarness();+ const legacy = { ...online, url: 'javascript:alert(1)' };+ h.drawing.oleOnlineUnit = legacy;+ h.config.convertToOnline = undefined;+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[2]).toMatchObject({ showConvert: true, hasOnlineUnit: true });+ await h.service.convertToOnline(h.drawing);+ expect(h.open).toHaveBeenLastCalledWith(onlineUrl, '_blank', 'noopener,noreferrer');+ h.config.getLink = () => '/new-route/created-doc';+ await h.service.convertToOnline(h.drawing);+ expect(h.open).toHaveBeenLastCalledWith(new URL('/new-route/created-doc', window.location.href).href, '_blank', 'noopener,noreferrer');+ expect(h.convert).not.toHaveBeenCalled();+ expect(h.save).not.toHaveBeenCalled();+ expect(h.drawing.oleOnlineUnit).toBe(legacy);+ });++ it('strips legacy adapter URL fields before saving a new online reference', async () => {+ const h = collaborativeHarness();+ const legacy = { ...online, url: 'https://obsolete.test/old-route' };+ h.convert.mockResolvedValueOnce(legacy);+ await h.service.convertToOnline(h.drawing);+ expect(h.save).toHaveBeenCalledWith(h.drawing, { unitId: 'created-doc', type: UniverInstanceType.UNIVER_DOC });+ expect(h.drawing.oleOnlineUnit).not.toHaveProperty('url');+ expect(h.getLink).not.toHaveBeenCalled();+ });++ it('hides conversion without a resolver and never falls back to a legacy URL', async () => {+ const h = collaborativeHarness();+ h.config.getLink = undefined;+ h.enter$.next();+ expect(h.attach.mock.lastCall?.[2].showConvert).toBe(false);+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow();+ const legacy = { ...online, url: onlineUrl };+ h.drawing.oleOnlineUnit = legacy;+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow();+ expect(h.convert).not.toHaveBeenCalled();+ expect(h.open).not.toHaveBeenCalled();+ });++ it.each(['javascript:alert(1)', 'data:text/html,unsafe', ''])('rejects unsafe or empty resolved URLs on Open (%s)', async (url) => {+ const h = collaborativeHarness();+ h.drawing.oleOnlineUnit = online;+ h.config.getLink = () => url;+ await expect(h.service.convertToOnline(h.drawing)).rejects.toThrow('Invalid');+ expect(h.open).not.toHaveBeenCalled();+ expect(h.convert).not.toHaveBeenCalled();+ });+});diff --git a/packages/drawing-ui/src/services/drawing-render.service.ts b/packages/drawing-ui/src/services/drawing-render.service.tsindex 9f5351f9df..c69c6e66d3 100644--- a/packages/drawing-ui/src/services/drawing-render.service.ts+++ b/packages/drawing-ui/src/services/drawing-render.service.ts@@ -36,7 +36,9 @@ import {import { DRAWING_OBJECT_LAYER_INDEX, Image, Rect } from '@univerjs/engine-render';import { IGalleryService } from '@univerjs/ui';import { insertGroupObject } from '../controllers/utils';+import { OleObject } from '../views/ole/ole-object';import { DrawingImageClipService } from './drawing-image-clip.service';+import { OleUIService } from './ole-ui.service';// const IMAGE_VIEWER_DROPDOWN_PADDING = 50;@@ -81,11 +83,12 @@ export class DrawingRenderService {@IGalleryService private readonly _galleryService: IGalleryService,@IURLImageService private readonly _urlImageService: IURLImageService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService,- @Inject(DrawingImageClipService) private readonly _drawingImageClipService: DrawingImageClipService+ @Inject(DrawingImageClipService) private readonly _drawingImageClipService: DrawingImageClipService,+ @Inject(OleUIService) private readonly _oleUI: OleUIService) { }// eslint-disable-next-line max-lines-per-function, complexity- async renderImages(imageParam: IImageData, scene: Scene, options?: { allowInactiveSheet?: boolean }) {+ async renderImages(imageParam: IImageData, scene: Scene, options?: { allowInactiveSheet?: boolean; interactive?: boolean }) {const {transform: singleTransform,drawingType,@@ -108,7 +111,7 @@ export class DrawingRenderService {layoutType?: PositionedObjectLayoutType;};- if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE) {+ if (drawingType !== DrawingTypeEnum.DRAWING_IMAGE && drawingType !== DrawingTypeEnum.DRAWING_OLE) {return;}@@ -136,6 +139,9 @@ export class DrawingRenderService {const imageShape = scene.getObject(imageShapeKey);if (imageShape != null) {imageShape.transformByState({ left, top, width, height, angle, flipX, flipY, skewX, skewY });+ if (drawingType === DrawingTypeEnum.DRAWING_OLE) {+ imageShape.transformerConfig = { ...imageShape.transformerConfig, rotateEnabled: false };+ }(imageShape as Image).setClipBounds?.((transform as IDrawingTransformStateWithClipBounds).clipBounds);if (this._univerInstanceService.getUnitType(unitId) === UniverInstanceType.UNIVER_SHEET || opacity !== undefined) {(imageShape as Image).setOpacity(normalizeImageOpacity(opacity));@@ -154,30 +160,32 @@ export class DrawingRenderService {opacity: normalizeImageOpacity(opacity),zIndex: zIndex === -1 ? (orders.length - 1) : zIndex,};- const imageNativeCache = this._imageIoService.getImageSourceCache(source, imageSourceType);-let shouldBeCache = false;- if (isRenderableImageCache(imageNativeCache)) {- imageConfig.image = imageNativeCache;- } else {- if (imageSourceType === ImageSourceType.UUID) {- try {- imageConfig.url = await this._imageIoService.getImage(source);- } catch (error) {- console.error(error);- continue;- }- } else if (imageSourceType === ImageSourceType.URL) {- try {- imageConfig.url = await this._urlImageService.getImage(source);- } catch (error) {- console.error(error);+ if (drawingType !== DrawingTypeEnum.DRAWING_OLE) {+ const imageNativeCache = this._imageIoService.getImageSourceCache(source, imageSourceType);++ if (isRenderableImageCache(imageNativeCache)) {+ imageConfig.image = imageNativeCache;+ } else {+ if (imageSourceType === ImageSourceType.UUID) {+ try {+ imageConfig.url = await this._imageIoService.getImage(source);+ } catch (error) {+ 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;- } else {- imageConfig.url = source;- shouldBeCache = true;}}@@ -193,13 +201,16 @@ export class DrawingRenderService {}imageConfig.printable = true;- const image = new Image(imageShapeKey, imageConfig);+ const image = drawingType === DrawingTypeEnum.DRAWING_OLE+ ? new OleObject(imageShapeKey, imageConfig)+ : new Image(imageShapeKey, imageConfig);image.setClipService(this._drawingImageClipService);if (shouldBeCache) {this._imageIoService.addImageSourceCache(source, imageSourceType, image.getNative());}scene.addObject(image, getDrawingRenderLayerIndex(imageParam as IDrawingParamWithBehindText));+ this._oleUI.bindObject(image, imageParam, options?.interactive !== false);if (this._drawingManagerService.getDrawingEditable()) {scene.attachTransformerTo(image);}@@ -294,7 +305,7 @@ export class DrawingRenderService {return rects;}- renderDrawing(param: IDrawingSearch, scene: Scene, options?: { allowInactiveSheet?: boolean }) {+ renderDrawing(param: IDrawingSearch, scene: Scene, options?: { allowInactiveSheet?: boolean; interactive?: boolean }) {const drawingParam = this._drawingManagerService.getDrawingByParam(param);if (drawingParam == null) {return;@@ -302,6 +313,7 @@ export class DrawingRenderService {switch (drawingParam.drawingType) {case DrawingTypeEnum.DRAWING_IMAGE:+ case DrawingTypeEnum.DRAWING_OLE:return this.renderImages(drawingParam as IImageData, scene, options);default:}diff --git a/packages/drawing-ui/src/services/ole-preview-viewer.ts b/packages/drawing-ui/src/services/ole-preview-viewer.tsnew file mode 100644index 0000000000..bb29446a35--- /dev/null+++ b/packages/drawing-ui/src/services/ole-preview-viewer.ts@@ -0,0 +1,91 @@+/**+ * 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 { IConfigService, IDisposable, LocaleService, ThemeService } from '@univerjs/core';+import type { IUniverDrawingConfig } from '@univerjs/drawing';+import type { IRender } from '@univerjs/engine-render';+import { IPermissionService, IUniverInstanceService, LifecycleService, LifecycleStages, Univer, UniverInstanceType } from '@univerjs/core';+import { IDrawingManagerService, UniverDrawingPlugin } from '@univerjs/drawing';+import { IRenderManagerService, UniverRenderEnginePlugin } from '@univerjs/engine-render';+import { UniverUIPlugin } from '@univerjs/ui';++export interface IOlePreviewViewerOptions {+ container: HTMLElement;+ data: object;+ type: UniverInstanceType;+ locale: LocaleService;+ theme: ThemeService;+ config: IConfigService;+ register: (univer: Univer) => void;+ onResize?: (render: IRender) => void;+ setReadonly: (permissions: IPermissionService, unitId: string) => void;+}++export type IOlePreviewContext = Omit<IOlePreviewViewerOptions, 'register' | 'onResize' | 'setReadonly'>;+export type IOlePreviewRenderer = (context: IOlePreviewContext) => IDisposable;++const previewRenderers = new Map<UniverInstanceType, IOlePreviewRenderer>();++/** Product UI modules register stateless factories without creating Units or retaining an application. */+export function registerOlePreviewRenderer(type: UniverInstanceType, renderer: IOlePreviewRenderer): void {+ previewRenderers.set(type, renderer);+}++export function getOlePreviewRenderer(type: UniverInstanceType): IOlePreviewRenderer | undefined {+ return previewRenderers.get(type);+}++/** An isolated temporary Univer instance. The host's Unit list, revision and collaboration remain untouched. */+export function createOlePreviewViewer(options: IOlePreviewViewerOptions): IDisposable {+ const viewer = new Univer({ darkMode: options.theme.darkMode, locale: options.locale.getCurrentLocale(), locales: { [options.locale.getCurrentLocale()]: options.locale.getLocales() ?? {} }, theme: options.theme.getCurrentTheme() });+ try {+ viewer.registerPlugin(UniverRenderEnginePlugin);+ viewer.registerPlugin(UniverUIPlugin, { container: options.container, header: false, toolbar: false, footer: options.type === UniverInstanceType.UNIVER_SHEET, contextMenu: false });+ const drawing = options.config.getConfig<IUniverDrawingConfig>('drawing.config');+ // The standalone viewer owns its providers; source collaboration overrides require services absent here.+ viewer.registerPlugin(UniverDrawingPlugin, { ...drawing, override: undefined, ole: { ...drawing?.ole, isCollaborative: () => false, convertToOnline: undefined } });+ options.register(viewer);+ const unit = viewer.createUnit(options.type, options.data);+ const injector = viewer.__getInjector();+ injector.get(IUniverInstanceService).focusUnit(unit.getUnitId());+ let disposed = false;+ let frame: number | undefined;+ // A dialog mounts its engine after the first layout. Resize after render modules subscribe.+ injector.get(LifecycleService).onStage(LifecycleStages.Rendered).then(() => {+ if (!disposed) {+ options.setReadonly(injector.get(IPermissionService), unit.getUnitId());+ injector.get(IDrawingManagerService).setDrawingEditable(false);+ frame = requestAnimationFrame(() => injector.get(IRenderManagerService).getRenderUnitById(unit.getUnitId())?.engine.resize());+ }+ }).catch(() => undefined);+ const render = injector.get(IRenderManagerService).getRenderUnitById(unit.getUnitId());+ const resize = render?.engine.onTransformChange$.subscribeEvent(() => options.onResize?.(render));+ const permissions = injector.get(IPermissionService);+ options.setReadonly(permissions, unit.getUnitId());+ injector.get(IDrawingManagerService).setDrawingEditable(false);+ return { dispose: () => {+ disposed = true;+ if (frame != null) {+ cancelAnimationFrame(frame);+ }+ resize?.unsubscribe();+ viewer.dispose();+ } };+ } catch (error) {+ viewer.dispose();+ throw error;+ }+}diff --git a/packages/drawing-ui/src/services/ole-ui.service.ts b/packages/drawing-ui/src/services/ole-ui.service.tsnew file mode 100644index 0000000000..9580667744--- /dev/null+++ b/packages/drawing-ui/src/services/ole-ui.service.ts@@ -0,0 +1,677 @@+/**+ * 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, IDrawingParam, IDrawingSearch, Nullable } from '@univerjs/core';+import type {+ IOleConfig,+ IOleDrawing,+ IOleOnlineUnit,+ IUnitDrawingService,+ IUniverDrawingConfig,+} from '@univerjs/drawing';+import type { BaseObject } from '@univerjs/engine-render';+import {+ Disposable,+ IConfigService,+ Inject,+ IUniverInstanceService,+ LocaleService,+ ThemeService,+ toDisposable,+ UniverInstanceType,+} from '@univerjs/core';+import { MessageType } from '@univerjs/design';+import { getOleOfficeType, IDrawingManagerService, OleService, readOleFile } from '@univerjs/drawing';+import { IDialogService, IMessageService, INotificationService } from '@univerjs/ui';+import type { LocaleKey } from '../locale/types';+import { OleCanvasRenderer } from '../views/ole/ole-canvas-renderer';+import { OleObject } from '../views/ole/ole-object';+import { createOleConversionProgress } from '../views/ole/OleConversionProgress';+import { getOlePreviewRenderer } from './ole-preview-viewer';++export const OLE_NAME_COMPONENT = 'drawing.ole-name';+export const OLE_POPUP_COMPONENT = 'drawing.ole-popup';+export const OLE_PREVIEW_COMPONENT = 'drawing.ole-preview';+export const OLE_OFFICE_PREVIEW_COMPONENT = 'drawing.ole-office-preview';++export interface IOleHostActions {+ drawingService?: Pick<IUnitDrawingService<IDrawingParam>, 'getDrawingByParam' | 'getDrawingEditable' | 'focus$' | 'remove$'>;+ isEditable?: (drawing: IDrawingSearch) => boolean;+ attach: (object: BaseObject, componentKey: string, extraProps: Record<string, unknown>, drawing: IDrawingSearch, direction?: 'top-center' | 'bottom-center') => IDisposable;+ remove: (drawing: IDrawingSearch) => Promise<boolean>;+ rename?: (drawing: IDrawingSearch, name: string) => Promise<boolean>;+ saveOnlineUnit?: (drawing: IDrawingSearch, online: IOleOnlineUnit) => Promise<boolean>;+}++function key(drawing: IDrawingSearch): string {+ return `${drawing.unitId}\u0000${drawing.subUnitId}\u0000${drawing.drawingId}`;+}++function attachmentId(drawing: Nullable<IDrawingParam>): string | undefined {+ const value = drawing as (Partial<IOleDrawing> & { element?: { oleAttachmentId?: string } }) | undefined;+ return value?.oleAttachmentId ?? value?.element?.oleAttachmentId;+}++function onlineUnit(drawing: Nullable<IDrawingParam>): IOleOnlineUnit | undefined {+ const value = drawing as (Partial<IOleDrawing> & { element?: Partial<IOleDrawing> }) | undefined;+ const online = value?.oleOnlineUnit ?? value?.element?.oleOnlineUnit;+ return online ? { unitId: online.unitId, type: online.type } : undefined;+}++class OleLinkSaveError extends Error {}++/** UI state stays local. Original bytes and collaborative geometry stay in their model resources. */+export class OleUIService extends Disposable {+ private readonly _hosts = new Map<UniverInstanceType, IOleHostActions>();+ private readonly _bindings = new Map<string, { object: BaseObject; dispose: () => void }>();+ private readonly _previews = new Map<string, AbortController>();+ private readonly _officeViews = new Map<string, { type: UniverInstanceType; data: object }>();+ private readonly _onlinePending = new Map<string, { controller: AbortController; promise: Promise<void> }>();+ private readonly _onlineResults = new Map<string, { attachmentId: string; online: IOleOnlineUnit }>();+ private readonly _captionColor = { value: '', warning: '' };+ private readonly _reportedUnits = new Set<string>();+ private _popup?: IDisposable;+ private _namePopup?: IDisposable;+ private _closeTimer?: ReturnType<typeof setTimeout>;++ constructor(+ @Inject(OleService) private readonly _oleService: OleService,+ @IDrawingManagerService private readonly _drawings: IDrawingManagerService,+ @IUniverInstanceService private readonly _instances: IUniverInstanceService,+ @IConfigService private readonly _config: IConfigService,+ @Inject(LocaleService) private readonly _locale: LocaleService,+ @IMessageService private readonly _messages: IMessageService,+ @IDialogService private readonly _dialogs: IDialogService,+ @INotificationService private readonly _notifications: INotificationService,+ @Inject(ThemeService) private readonly _theme: ThemeService+ ) {+ super();+ this.disposeWithMe(this._theme.currentTheme$.subscribe((value) => {+ this._captionColor.value = value.gray[900];+ this._captionColor.warning = value.yellow[600];+ for (const binding of this._bindings.values()) {+ binding.object.makeDirty(true);+ }+ }));+ this.disposeWithMe(this._drawings.remove$.subscribe((items) => this._handleRemoved(items)));+ this.disposeWithMe(this._drawings.focus$.subscribe((items) => this._handleFocused(items)));+ for (const type of [UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC, UniverInstanceType.UNIVER_SLIDE]) {+ this.disposeWithMe(this._instances.getTypeOfUnitDisposed$(type).subscribe((unit) => {+ this._reportedUnits.delete(unit.getUnitId());+ const prefix = `${unit.getUnitId()}\u0000`;+ const keys = new Set([...this._bindings.keys(), ...this._onlinePending.keys(), ...this._onlineResults.keys(), ...this._previews.keys(), ...this._officeViews.keys()]);+ const drawings = [...keys].filter((id) => id.startsWith(prefix)).map((id) => {+ const [unitId, subUnitId, drawingId] = id.split('\u0000');+ return { unitId, subUnitId, drawingId };+ });+ if (drawings.length) {+ this._handleRemoved(drawings);+ }+ }));+ }+ }++ private _handleRemoved(items: IDrawingSearch[]): void {+ for (const item of items) {+ this._onlinePending.get(key(item))?.controller.abort();+ this._onlinePending.delete(key(item));+ this._onlineResults.delete(key(item));+ this._bindings.get(key(item))?.dispose();+ this._bindings.delete(key(item));+ this._previews.get(key(item))?.abort();+ this._previews.delete(key(item));+ this._officeViews.delete(key(item));+ this._dialogs.close(`ole-preview-${key(item)}`);+ }+ this._closePopup();+ this._closeName();+ }++ private _handleFocused(items: IDrawingParam[]): void {+ if (items.length === 1 && attachmentId(this._getDrawing(items[0]))) {+ const binding = this._bindings.get(key(items[0]));+ if (binding) {+ this._show(binding.object, items[0]);+ }+ } else { this._closePopup(); }+ }++ private _getDrawing(drawing: IDrawingSearch): Nullable<IDrawingParam> {+ const type = this._instances.getUnit(drawing.unitId)?.type;+ return (type == null ? undefined : this._hosts.get(type)?.drawingService)?.getDrawingByParam(drawing)+ ?? this._drawings.getDrawingByParam(drawing);+ }++ registerHost(type: UniverInstanceType, actions: IOleHostActions): IDisposable {+ this._hosts.set(type, actions);+ const service = actions.drawingService;+ const remove = service?.remove$.subscribe((items) => this._handleRemoved(items));+ const focus = service?.focus$.subscribe((items) => this._handleFocused(items));+ const registration = toDisposable(() => {+ remove?.unsubscribe();+ focus?.unsubscribe();+ if (this._hosts.get(type) === actions) {+ this._hosts.delete(type);+ }+ });+ this.disposeWithMe(registration);+ return registration;+ }++ bindObject(object: BaseObject, drawing: IDrawingSearch, interactive = true): void {+ if (!attachmentId(this._getDrawing(drawing))) {+ return;+ }+ const id = key(drawing);+ if (this._bindings.get(id)?.object === object) {+ return;+ }+ if (object instanceof OleObject) {+ const resource = this._oleService.getResource(drawing.unitId);+ const record = resource?.objects[attachmentId(this._getDrawing(drawing))!];+ const file = record?.fileId ? resource?.files[record.fileId] : undefined;+ const color = this._captionColor;+ const unavailable = record?.external || !file;+ const renderer = new OleCanvasRenderer(+ this._fileName(drawing),+ file?.mimeType ?? '',+ () => color.value,+ () => this._fileName(drawing),+ unavailable ? { label: this._locale.t<LocaleKey>(record?.external ? 'drawing-ui.ole.external' : 'drawing-ui.ole.missing'), color: () => color.warning } : undefined+ );+ object.setRenderer(renderer);+ }+ if (!interactive) return;+ this._reportUnavailable(drawing.unitId);+ this._bindings.get(id)?.dispose();+ const enter = object.onPointerEnter$.subscribeEvent(() => {+ this._show(object, drawing);+ });+ const leave = object.onPointerLeave$.subscribeEvent(() => {+ this._scheduleClose();+ });+ const click = object.onPointerDown$.subscribeEvent(() => {+ this._show(object, drawing);+ });+ const doubleClick = object.onDblclick$.subscribeEvent(() => {+ return this._act(() => this.preview(drawing));+ });+ this._bindings.set(id, { object, dispose: () => {+ enter.unsubscribe();+ leave.unsubscribe();+ click.unsubscribe();+ doubleClick.unsubscribe();+ } });+ }++ private _oleConfig(): IOleConfig {+ return this._config.getConfig<IUniverDrawingConfig>('drawing.config')?.ole ?? {};+ }++ private _show(object: BaseObject, drawing: IDrawingSearch): void {+ if (this._namePopup) return;+ clearTimeout(this._closeTimer);+ const type = this._instances.getUnit(drawing.unitId)?.type;+ const host = type == null ? undefined : this._hosts.get(type);+ if (!host || !attachmentId(this._getDrawing(drawing))) {+ return;+ }+ this._closePopup();+ const id = attachmentId(this._getDrawing(drawing))!;+ const resource = this._oleService.getResource(drawing.unitId);+ const record = resource?.objects[id];+ const file = record?.fileId ? resource?.files[record.fileId] : undefined;+ const available = !!file && !record?.external;+ const savedOnline = onlineUnit(this._getDrawing(drawing));+ const officeType = savedOnline?.type ?? (file ? getOleOfficeType(file.mimeType) : undefined);+ const config = this._oleConfig();+ const canConvert = !!config.getLink && config.isCollaborative?.(drawing.unitId) === true &&+ (!!savedOnline || (available && !!config.convertToOnline && !!host.saveOnlineUnit && officeType != null));+ let statusKey: LocaleKey = 'drawing-ui.ole.attachment';+ if (record?.external) {+ statusKey = 'drawing-ui.ole.external';+ } else if (record?.status === 'missing') {+ statusKey = 'drawing-ui.ole.missing';+ } else if (record?.status === 'opaque') {+ statusKey = 'drawing-ui.ole.opaque';+ }+ this._popup = host.attach(object, OLE_POPUP_COMPONENT, {+ available,+ previewAvailable: available && this._canPreview(file.mimeType),+ officeType,+ showConvert: canConvert,+ hasOnlineUnit: !!savedOnline,+ converting: this._onlinePending.has(key(drawing)),+ convert: () => this._act(() => this.convertToOnline(drawing), 'drawing-ui.ole.conversionFailed'),+ fileName: this._fileName(drawing),+ rename: available && host.rename ? () => this._showName(object, drawing) : undefined,+ status: this._locale.t<LocaleKey>(record?.external ? 'drawing-ui.ole.externalHint' : !available ? 'drawing-ui.ole.missingHint' : statusKey),+ editable: host.isEditable?.(drawing) ?? host.drawingService?.getDrawingEditable() ?? this._drawings.getDrawingEditable(),+ onEnter: () => clearTimeout(this._closeTimer),+ onLeave: () => this._scheduleClose(),+ download: () => this._act(() => this.download(drawing)),+ preview: () => this._act(() => this.preview(drawing)),+ remove: () => this._act(async () => {+ const editable = host.isEditable?.(drawing) ?? host.drawingService?.getDrawingEditable() ?? this._drawings.getDrawingEditable();+ if (editable && await host.remove(drawing)) {+ this._closePopup();+ }+ }),+ }, drawing);+ }++ private _reportUnavailable(unitId: string): void {+ if (this._reportedUnits.has(unitId)) return;+ const resource = this._oleService.getResource(unitId);+ const count = Object.values(resource?.objects ?? {}).filter((record) =>+ record.external || !record.fileId || !resource?.files[record.fileId]+ ).length;+ if (count > 0) {+ this._reportedUnits.add(unitId);+ this._messages.show({ type: MessageType.Info, content: this._locale.t<LocaleKey>('drawing-ui.ole.unavailableSummary', String(count)) });+ }+ }++ private _fileName(drawing: IDrawingSearch): string {+ const current = this._getDrawing(drawing) as (Partial<IOleDrawing> & { element?: Partial<IOleDrawing> }) | undefined;+ const resource = this._oleService.getResource(drawing.unitId);+ const id = attachmentId(current as IDrawingParam);+ const record = id ? resource?.objects[id] : undefined;+ const fileId = record?.fileId;+ return current?.oleFileName ?? current?.element?.oleFileName+ ?? record?.fileName ?? (fileId ? resource?.files[fileId]?.name : undefined) ?? this._locale.t<LocaleKey>(record?.external ? 'drawing-ui.ole.externalAttachment' : 'drawing-ui.ole.attachment');+ }++ private _showName(object: BaseObject, drawing: IDrawingSearch): void {+ this._closePopup();+ this._closeName();+ const type = this._instances.getUnit(drawing.unitId)?.type;+ const host = type == null ? undefined : this._hosts.get(type);+ if (!host || !attachmentId(this._getDrawing(drawing))) {+ return;+ }+ this._namePopup = host.attach(object, OLE_NAME_COMPONENT, {+ fileName: this._fileName(drawing),+ close: () => this._closeName(),+ save: (baseName: string) => this.rename(drawing, baseName),+ }, drawing, 'top-center');+ }++ async rename(drawing: IDrawingSearch, baseName: string): Promise<string | undefined> {+ const type = this._instances.getUnit(drawing.unitId)?.type;+ const host = type == null ? undefined : this._hosts.get(type);+ const current = this._getDrawing(drawing);+ const editable = host?.isEditable?.(drawing) ?? host?.drawingService?.getDrawingEditable() ?? this._drawings.getDrawingEditable();+ const name = this._fileName(drawing);+ const dot = name.lastIndexOf('.');+ const extension = dot > 0 ? name.slice(dot) : '';+ const base = baseName.trim();+ if (!base || /[<>:"/\\|?*\u0000-\u001F\u007F]/.test(base) || /[. ]$/.test(base) || Array.from(base + extension).length > 255) {+ return this._locale.t<LocaleKey>('drawing-ui.ole.invalidName');+ }+ if (!current || !attachmentId(current) || !editable || !host?.rename) {+ return this._locale.t<LocaleKey>('drawing-ui.ole.renameFailed');+ }+ try {+ if (base + extension !== name && !await host.rename(drawing, base + extension)) {+ return this._locale.t<LocaleKey>('drawing-ui.ole.renameFailed');+ }+ this._bindings.get(key(drawing))?.object.makeDirty(true);+ this._closeName();+ } catch {+ return this._locale.t<LocaleKey>('drawing-ui.ole.renameFailed');+ }+ }++ private _closeName(): void {+ this._namePopup?.dispose();+ this._namePopup = undefined;+ }++ private _scheduleClose(): void {+ clearTimeout(this._closeTimer);+ this._closeTimer = setTimeout(() => this._closePopup(), 180);+ }++ private _closePopup(): void {+ clearTimeout(this._closeTimer);+ this._popup?.dispose();+ this._popup = undefined;+ }++ private async _act(action: () => Promise<void>, errorKey: LocaleKey = 'drawing-ui.ole.failed'): Promise<void> {+ try {+ await action();+ } catch (error) {+ this._messages.show({ type: MessageType.Error, content: this._locale.t<LocaleKey>(error instanceof OleLinkSaveError ? 'drawing-ui.ole.linkSaveFailed' : errorKey) });+ }+ }++ private async _file(drawing: IDrawingSearch, signal?: AbortSignal) {+ const id = attachmentId(this._getDrawing(drawing));+ const resource = this._oleService.getResource(drawing.unitId);+ const object = id ? resource?.objects[id] : undefined;+ const file = object?.fileId ? resource?.files[object.fileId] : undefined;+ if (!id || !file || object?.external) {+ throw new Error('OLE attachment is unavailable');+ }+ const bytes = await readOleFile(file, this._oleConfig().attachmentIo, signal);+ if (attachmentId(this._getDrawing(drawing)) !== id) {+ throw new Error('OLE object was removed');+ }+ return { id, file: { ...file, name: this._fileName(drawing) }, bytes };+ }++ convertToOnline(drawing: IDrawingSearch): Promise<void> {+ const id = key(drawing);+ const pending = this._onlinePending.get(id);+ if (pending) {+ return pending.promise;+ }+ const controller = new AbortController();+ const promise = this._convertToOnline(drawing, controller).finally(() => {+ if (this._onlinePending.get(id)?.controller === controller) {+ this._onlinePending.delete(id);+ }+ const binding = this._bindings.get(id);+ if (binding) {+ this._show(binding.object, drawing);+ }+ });+ this._onlinePending.set(id, { controller, promise });+ return promise;+ }++ private _onlineReference(online: IOleOnlineUnit): IOleOnlineUnit {+ if (typeof online?.unitId !== 'string' || !online.unitId.trim() || ![UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC, UniverInstanceType.UNIVER_SLIDE].includes(online.type)) {+ throw new Error('Invalid OLE online Unit reference');+ }+ return { unitId: online.unitId, type: online.type };+ }++ private _onlineUrl(online: IOleOnlineUnit): string {+ const reference = this._onlineReference(online);+ const link = this._oleConfig().getLink?.(reference.unitId, reference.type);+ if (typeof link !== 'string' || !link.trim()) throw new Error('Invalid OLE online Unit link');+ const url = new URL(link, window.location.href);+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error('Invalid OLE online Unit link');+ return url.href;+ }++ private _showOnlineComplete(name: string, online: IOleOnlineUnit): void {+ this.disposeWithMe(this._notifications.show({+ type: 'success',+ title: this._locale.t<LocaleKey>('drawing-ui.ole.converted'),+ content: name,+ position: 'bottom-right',+ duration: Infinity,+ classNames: {+ toast: `+ !univer-grid !univer-grid-cols-[20px_minmax(0,1fr)] !univer-items-start !univer-gap-x-3+ !univer-gap-y-3 !univer-rounded-xl !univer-border-gray-200 !univer-bg-gray-0 univer-font-sans+ dark:!univer-border-gray-700 dark:!univer-bg-gray-800+ `,+ icon: '!univer-m-0 !univer-self-start [&>svg]:!univer-top-0',+ content: '!univer-min-w-0 !univer-gap-1 univer-pe-5',+ title: '!univer-text-sm !univer-font-medium !univer-leading-5',+ description: '!univer-truncate !univer-text-xs !univer-leading-5',+ actionButton: `+ univer-col-start-2 univer-justify-self-end !univer-m-0 !univer-h-8 !univer-rounded-lg+ !univer-bg-primary-600 !univer-px-3 !univer-text-sm !univer-font-medium !univer-text-gray-0+ hover:!univer-bg-primary-500+ `,+ closeButton: `+ !univer-start-auto !univer-end-2 !univer-top-2 !univer-transform-none !univer-rounded-md+ !univer-border-0 !univer-bg-transparent !univer-text-gray-500+ hover:!univer-bg-gray-100+ dark:!univer-text-gray-300 dark:hover:!univer-bg-gray-700+ `,+ },+ action: {+ label: this._locale.t<LocaleKey>('drawing-ui.ole.open'),+ onClick: () => this._act(async () => {+ window.open(this._onlineUrl(online), '_blank', 'noopener,noreferrer');+ }),+ },+ }));+ }++ private async _convertToOnline(drawing: IDrawingSearch, controller: AbortController): Promise<void> {+ const config = this._oleConfig();+ const current = this._getDrawing(drawing);+ const type = this._instances.getUnit(drawing.unitId)?.type;+ const host = type == null ? undefined : this._hosts.get(type);+ if (!current || !config.isCollaborative?.(drawing.unitId) || !config.getLink) {+ throw new Error('OLE online conversion requires a collaborative Unit');+ }+ const existing = onlineUnit(current);+ if (existing) {+ window.open(this._onlineUrl(existing), '_blank', 'noopener,noreferrer');+ return;+ }+ if (!config.convertToOnline || !host?.saveOnlineUnit) throw new Error('OLE online conversion is unavailable');+ if (!(host.isEditable?.(drawing) ?? host.drawingService?.getDrawingEditable() ?? this._drawings.getDrawingEditable())) {+ throw new Error('OLE link is read-only');+ }+ const objectId = attachmentId(current);+ const resource = this._oleService.getResource(drawing.unitId);+ const record = objectId ? resource?.objects[objectId] : undefined;+ const file = record?.fileId ? resource?.files[record.fileId] : undefined;+ const officeType = file ? getOleOfficeType(file.mimeType) : undefined;+ if (!file || record?.external || officeType == null) {+ throw new Error('Unsupported online conversion');+ }+ const progress = createOleConversionProgress(this._notifications, this._locale, this._fileName(drawing));+ const cancelProgress = () => progress.dispose();+ controller.signal.addEventListener('abort', cancelProgress, { once: true });+ try {+ const cached = this._onlineResults.get(key(drawing));+ let online = cached && cached.attachmentId === objectId ? cached.online : undefined;+ if (!online) {+ const request = {+ unitId: drawing.unitId,+ attachmentId: objectId!,+ name: this._fileName(drawing),+ mimeType: file.mimeType,+ signal: controller.signal,+ onProgress: progress.update,+ };+ if (file.data == null && file.attachment?.sourceType === 'UUID' && file.attachment.source) {+ online = await config.convertToOnline({ ...request, fileId: file.attachment.source });+ } else {+ const { bytes } = await this._file(drawing, controller.signal);+ online = await config.convertToOnline({ ...request, bytes });+ }+ if (online.type !== officeType) {+ throw new Error('OLE online Unit type mismatch');+ }+ online = this._onlineReference(online);+ if (!controller.signal.aborted) {+ this._onlineResults.set(key(drawing), { attachmentId: objectId!, online });+ }+ }+ if (controller.signal.aborted || attachmentId(this._getDrawing(drawing)) !== objectId) {+ return;+ }+ progress.update('saving');+ try {+ const editable = host.isEditable?.(drawing) ?? host.drawingService?.getDrawingEditable() ?? this._drawings.getDrawingEditable();+ if (!editable || !await host.saveOnlineUnit(drawing, online)) {+ throw new Error('Link persistence rejected');+ }+ } catch {+ throw new OleLinkSaveError('OLE online link could not be saved');+ }+ if (controller.signal.aborted || attachmentId(this._getDrawing(drawing)) !== objectId) {+ return;+ }+ progress.dispose();+ this._showOnlineComplete(this._fileName(drawing), online);+ } catch (error) {+ if (!controller.signal.aborted) {+ throw error;+ }+ } finally {+ controller.signal.removeEventListener('abort', cancelProgress);+ progress.dispose();+ }+ }++ async download(drawing: IDrawingSearch): Promise<void> {+ const { file, bytes } = await this._file(drawing);+ const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: file.mimeType }));+ const link = document.createElement('a');+ link.href = url;+ link.download = file.name;+ link.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+ }++ async preview(drawing: IDrawingSearch): Promise<void> {+ const resource = this._oleService.getResource(drawing.unitId);+ const objectId = attachmentId(this._getDrawing(drawing));+ const record = objectId ? resource?.objects[objectId] : undefined;+ if (record?.external || !record?.fileId || !resource?.files[record.fileId]) {+ this._messages.show({ type: MessageType.Info, content: this._locale.t<LocaleKey>(record?.external ? 'drawing-ui.ole.externalHint' : 'drawing-ui.ole.missingHint') });+ return;+ }+ if (!this._canPreview(resource.files[record.fileId].mimeType)) {+ this._messages.show({ type: MessageType.Info, content: this._locale.t<LocaleKey>('drawing-ui.ole.unsupported') });+ return;+ }+ // The existing dialog service must capture a stable opener when the OLE toolbar unmounts.+ const focusOwner = document.activeElement?.closest<HTMLElement>('[role="dialog"]');+ const previewKey = key(drawing);+ this._previews.get(previewKey)?.abort();+ const controller = new AbortController();+ this._previews.set(previewKey, controller);+ const { id, file, bytes } = await this._file(drawing, controller.signal);+ if (file.mimeType === 'application/pdf' || ['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(file.mimeType)) {+ const url = URL.createObjectURL(new Blob([bytes as Uint8Array<ArrayBuffer>], { type: file.mimeType }));+ const dialogId = `ole-preview-${previewKey}`;+ const close = () => {+ controller.abort();+ URL.revokeObjectURL(url);+ this._dialogs.close(dialogId);+ this._previews.delete(previewKey);+ };+ controller.signal.addEventListener('abort', () => URL.revokeObjectURL(url), { once: true });+ focusOwner?.focus({ preventScroll: true });+ this._dialogs.open({ id: dialogId, title: { title: file.name }, children: { label: OLE_PREVIEW_COMPONENT, value: JSON.stringify({ url, mimeType: file.mimeType, name: file.name }) }, width: '80vw', onClose: close });+ } else if (this._oleConfig().previewOffice) {+ await this._oleConfig().previewOffice!({ unitId: drawing.unitId, attachmentId: id, bytes, name: file.name, mimeType: file.mimeType, signal: controller.signal });+ } else if (this._oleConfig().convertOffice && getOleOfficeType(file.mimeType) != null) {+ const view = await this._oleConfig().convertOffice!({ unitId: drawing.unitId, attachmentId: id, bytes, name: file.name, mimeType: file.mimeType, signal: controller.signal });+ if (controller.signal.aborted || attachmentId(this._getDrawing(drawing)) !== id) {+ return;+ }+ if (!this._previewFactory(view.type)) {+ throw new Error('Office preview renderer is unavailable');+ }+ this._officeViews.set(previewKey, view);+ const dialogId = `ole-preview-${previewKey}`;+ const close = () => {+ controller.abort();+ this._dialogs.close(dialogId);+ this._officeViews.delete(previewKey);+ this._previews.delete(previewKey);+ };+ focusOwner?.focus({ preventScroll: true });+ this._dialogs.open({+ id: dialogId,+ title: { title: file.name },+ children: { label: OLE_OFFICE_PREVIEW_COMPONENT, value: previewKey },+ width: '90vw',+ // Fixed canvas popups use viewport coordinates, so their modal must not create a transformed containing block.+ style: { top: 0, right: 0, bottom: 0, left: 0, margin: 'auto', height: 'max-content', transform: 'none', animation: 'none' },+ onClose: close,+ });+ } else {+ this._messages.show({ type: MessageType.Info, content: this._locale.t<LocaleKey>('drawing-ui.ole.unsupported') });+ this._previews.delete(previewKey);+ }+ }++ private _canPreview(mimeType: string): boolean {+ if (mimeType === 'application/pdf' || ['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(mimeType)) {+ return true;+ }+ const config = this._oleConfig();+ if (config.previewOffice) {+ return true;+ }+ const type = getOleOfficeType(mimeType);+ return !!config.convertOffice && type != null && !!this._previewFactory(type);+ }++ private _previewFactory(type: UniverInstanceType): IOleConfig['createOfficePreview'] {+ const configured = this._oleConfig().createOfficePreview;+ if (configured) {+ return configured;+ }+ const renderer = getOlePreviewRenderer(type);+ return renderer ? async (container, view) => renderer({ container, ...view, config: this._config, locale: this._locale, theme: this._theme }) : undefined;+ }++ mountOfficePreview(id: string, container: HTMLElement): IDisposable | undefined {+ const view = this._officeViews.get(id);+ if (!view) {+ return;+ }+ const factory = this._previewFactory(view.type);+ if (!factory) {+ return;+ }+ let disposed = false;+ let renderer: IDisposable | undefined;+ void factory(container, view).then((value) => {+ if (disposed) {+ value.dispose();+ } else {+ renderer = value;+ }+ }).catch(() => {+ if (!disposed) {+ this._messages.show({ type: MessageType.Error, content: this._locale.t<LocaleKey>('drawing-ui.ole.failed') });+ }+ });+ return { dispose: () => {+ disposed = true;+ renderer?.dispose();+ } };+ }++ override dispose(): void {+ this._closePopup();+ this._closeName();+ for (const pending of this._onlinePending.values()) {+ pending.controller.abort();+ }+ this._reportedUnits.clear();+ this._onlinePending.clear();+ this._onlineResults.clear();+ for (const binding of this._bindings.values()) {+ binding.dispose();+ }+ for (const preview of this._previews.values()) {+ preview.abort();+ }+ this._bindings.clear();+ this._previews.clear();+ this._officeViews.clear();+ super.dispose();+ }+}diff --git a/packages/drawing-ui/src/views/ole/OleConversionProgress.tsx b/packages/drawing-ui/src/views/ole/OleConversionProgress.tsxnew file mode 100644index 0000000000..1bdcae25ca--- /dev/null+++ b/packages/drawing-ui/src/views/ole/OleConversionProgress.tsx@@ -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 { IDisposable, LocaleService } from '@univerjs/core';+import type { OleConversionStage } from '@univerjs/drawing';+import type { INotificationService } from '@univerjs/ui';+import type { LocaleKey } from '../../locale/types';+import { useObservable } from '@univerjs/ui';+import { createElement } from 'react';+import { BehaviorSubject } from 'rxjs';++const STAGE_KEYS: Record<OleConversionStage, LocaleKey> = {+ reading: 'drawing-ui.ole.progressReading',+ uploading: 'drawing-ui.ole.progressUploading',+ converting: 'drawing-ui.ole.converting',+ creating: 'drawing-ui.ole.progressCreating',+ saving: 'drawing-ui.ole.progressSaving',+};++function OleConversionProgress({ stage$, locale, name }: {+ stage$: BehaviorSubject<OleConversionStage>;+ locale: LocaleService;+ name: string;+}) {+ const stage = useObservable(stage$) ?? 'reading';+ return (+ <div className="univer-flex univer-w-60 univer-min-w-0 univer-flex-col univer-gap-2" role="status">+ <span className="univer-truncate">{name}</span>+ <span>{locale.t<LocaleKey>(STAGE_KEYS[stage])}</span>+ <progress className="univer-h-1 univer-w-full" aria-label={locale.t<LocaleKey>(STAGE_KEYS[stage])} />+ </div>+ );+}++/** Keep progress on the source page even when the drawing menu closes. */+export function createOleConversionProgress(+ notifications: INotificationService,+ locale: LocaleService,+ name: string+): IDisposable & { update: (stage: OleConversionStage) => void } {+ const stage$ = new BehaviorSubject<OleConversionStage>('reading');+ const notification = notifications.show({+ title: createElement(OleConversionProgress, { stage$, locale, name }),+ position: 'bottom-right',+ duration: Infinity,+ closable: false,+ dismissible: false,+ });+ let disposed = false;+ const update = (stage: OleConversionStage): void => {+ if (disposed) return;+ stage$.next(stage);+ };+ update('reading');+ return { update, dispose: () => {+ if (disposed) return;+ disposed = true;+ notification.dispose();+ stage$.complete();+ } };+}diff --git a/packages/drawing-ui/src/views/ole/OleName.tsx b/packages/drawing-ui/src/views/ole/OleName.tsxnew file mode 100644index 0000000000..29840d048d--- /dev/null+++ b/packages/drawing-ui/src/views/ole/OleName.tsx@@ -0,0 +1,94 @@+/**+ * 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 { LocaleKey } from '../../locale/types';+import { LocaleService } from '@univerjs/core';+import { Button, Input, Tooltip } from '@univerjs/design';+import { CheckMarkIcon, CloseIcon } from '@univerjs/icons';+import { useDependency } from '@univerjs/ui';+import { useRef, useState } from 'react';++interface IOleNameProps {+ fileName: string;+ close: () => void;+ save: (baseName: string) => Promise<string | undefined>;+}++export function OleName({ popup }: { popup: { extraProps: IOleNameProps } }) {+ const locale = useDependency(LocaleService);+ const { fileName, close, save } = popup.extraProps;+ const dot = fileName.lastIndexOf('.');+ const extension = dot > 0 ? fileName.slice(dot) : '';+ const [value, setValue] = useState(extension ? fileName.slice(0, dot) : fileName);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string>();+ const savingRef = useRef(false);+ const confirm = async () => {+ if (savingRef.current) return;+ savingRef.current = true;+ setBusy(true);+ try {+ setError(await save(value));+ } finally {+ savingRef.current = false;+ setBusy(false);+ }+ };+ return (+ <div+ role="dialog"+ aria-label={locale.t<LocaleKey>('drawing-ui.ole.rename')}+ aria-busy={busy}+ className="+ univer-box-border univer-w-80 univer-max-w-full univer-rounded-lg univer-border univer-border-solid+ univer-border-gray-200 univer-bg-gray-0 univer-p-2 univer-font-sans univer-text-sm univer-text-gray-900+ univer-shadow-md+ dark:univer-border-gray-600 dark:univer-bg-gray-800 dark:univer-text-gray-0+ "+ onPointerDown={(event) => event.stopPropagation()}+ onKeyDown={async (event) => {+ event.stopPropagation();+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;+ if (event.key === 'Escape' && !savingRef.current) close();+ if (event.key === 'Enter') {+ event.preventDefault();+ await confirm();+ }+ }}+ >+ <div className="univer-flex univer-items-center univer-gap-1">+ <Input+ autoFocus+ aria-label={locale.t<LocaleKey>('drawing-ui.ole.rename')}+ value={value}+ disabled={busy}+ onChange={setValue}+ onFocus={(event) => event.target.select()}+ />+ {extension && <span className="univer-shrink-0 univer-text-gray-500">{extension}</span>}+ <Tooltip title={locale.t<LocaleKey>('drawing-ui.ole.saveName')} placement="top">+ <Button size="icon" variant="ghost" disabled={busy} aria-label={locale.t<LocaleKey>('drawing-ui.ole.saveName')} onClick={confirm}>+ <CheckMarkIcon />+ </Button>+ </Tooltip>+ <Tooltip title={locale.t<LocaleKey>('drawing-ui.ole.cancel')} placement="top">+ <Button size="icon" variant="ghost" disabled={busy} aria-label={locale.t<LocaleKey>('drawing-ui.ole.cancel')} onClick={close}><CloseIcon /></Button>+ </Tooltip>+ </div>+ {error && <div role="alert" className="univer-mt-1 univer-text-red-600">{error}</div>}+ </div>+ );+}diff --git a/packages/drawing-ui/src/views/ole/OlePopup.tsx b/packages/drawing-ui/src/views/ole/OlePopup.tsxnew file mode 100644index 0000000000..4d6ba4ab66--- /dev/null+++ b/packages/drawing-ui/src/views/ole/OlePopup.tsx@@ -0,0 +1,203 @@+/**+ * 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 { ReactNode } from 'react';+import { LocaleService, UniverInstanceType } from '@univerjs/core';+import { Button, clsx, Separator, Tooltip } from '@univerjs/design';+import { ConvertIcon, DeleteIcon, DownloadIcon, EyeIcon, LinkIcon, RenameIcon, WarningIcon } from '@univerjs/icons';+import { useDependency } from '@univerjs/ui';+import { useEffect, useRef, useState } from 'react';+import type { LocaleKey } from '../../locale/types';+import { OleUIService } from '../../services/ole-ui.service';++interface IOlePopupActions {+ fileName?: string;+ officeType?: UniverInstanceType;+ showConvert?: boolean;+ hasOnlineUnit?: boolean;+ converting?: boolean;+ convert?: () => Promise<void>;+ available: boolean;+ previewAvailable: boolean;+ status: string;+ editable: boolean;+ onEnter: () => void;+ onLeave: () => void;+ download: () => Promise<void>;+ preview: () => Promise<void>;+ remove: () => Promise<void>;+ rename?: () => void;+}++function OleActionButton({ title, disabled, danger = false, children, onClick }: { title: string; disabled: boolean; danger?: boolean; children: ReactNode; onClick: () => void }) {+ return (+ <Tooltip title={title} placement="top" className="univer-font-sans">+ <span className="univer-inline-flex">+ <Button+ type="button"+ size="icon"+ variant="ghost"+ aria-label={title}+ disabled={disabled}+ onClick={onClick}+ className={clsx(+ `+ univer-shrink-0 !univer-text-gray-600+ dark:!univer-text-gray-200+ `,+ `+ focus-visible:univer-outline focus-visible:univer-outline-2+ focus-visible:univer-outline-primary-500+ `,+ danger && `+ hover:!univer-bg-red-50 hover:!univer-text-red-600+ focus-visible:!univer-text-red-600+ dark:hover:!univer-bg-red-900 dark:hover:!univer-text-red-300+ `+ )}+ >+ {children}+ </Button>+ </span>+ </Tooltip>+ );+}++export function OlePopup({ popup }: { popup: { extraProps: IOlePopupActions } }) {+ const locale = useDependency(LocaleService);+ const [busy, setBusy] = useState<'action' | 'convert'>();+ const actions = popup.extraProps;+ const run = async (action: () => Promise<void>, isConversion = false) => {+ setBusy(isConversion ? 'convert' : 'action');+ try {+ await action();+ } finally {+ setBusy(undefined);+ }+ };+ let convertKey: LocaleKey = 'drawing-ui.ole.convertDoc';+ let openKey: LocaleKey = 'drawing-ui.ole.openDoc';+ if (actions.officeType === UniverInstanceType.UNIVER_SHEET) {+ convertKey = 'drawing-ui.ole.convertSheet';+ openKey = 'drawing-ui.ole.openSheet';+ } else if (actions.officeType === UniverInstanceType.UNIVER_SLIDE) {+ convertKey = 'drawing-ui.ole.convertSlide';+ openKey = 'drawing-ui.ole.openSlide';+ }+ const converting = actions.converting === true || busy === 'convert';+ let convertActionKey: LocaleKey = actions.hasOnlineUnit ? openKey : convertKey;+ if (converting) {+ convertActionKey = 'drawing-ui.ole.converting';+ }+ let convertIcon = actions.hasOnlineUnit ? <LinkIcon /> : <ConvertIcon />;+ if (converting) {+ convertIcon = (+ <span+ aria-hidden="true"+ className="+ univer-size-4 univer-animate-spin univer-rounded-full univer-border-2 univer-border-solid+ univer-border-current univer-border-t-transparent+ "+ />+ );+ }+ const disabled = busy != null || converting;+ return (+ <div+ role="toolbar"+ aria-label={actions.fileName ?? locale.t<LocaleKey>('drawing-ui.ole.actions')}+ aria-busy={busy != null || converting}+ className="+ univer-box-border univer-flex univer-h-10 univer-w-max univer-flex-nowrap univer-items-center univer-gap-1+ univer-rounded-lg univer-border univer-border-solid univer-border-gray-200 univer-bg-gray-0 univer-px-1+ univer-shadow-sm+ dark:univer-border-gray-600 dark:univer-bg-gray-800+ "+ onMouseEnter={actions.onEnter}+ onMouseLeave={actions.onLeave}+ onFocus={actions.onEnter}+ onBlur={actions.onLeave}+ >+ {actions.available+ ? (+ <>+ <OleActionButton title={locale.t<LocaleKey>(actions.previewAvailable ? 'drawing-ui.ole.preview' : 'drawing-ui.ole.unsupported')} disabled={disabled || !actions.previewAvailable} onClick={() => run(actions.preview)}><EyeIcon /></OleActionButton>+ <OleActionButton title={locale.t<LocaleKey>('drawing-ui.ole.download')} disabled={disabled} onClick={() => run(actions.download)}><DownloadIcon /></OleActionButton>+ </>+ )+ : (+ <Tooltip+ title={actions.status}+ placement="top"+ className="!univer-pointer-events-none univer-max-w-80 univer-font-sans"+ >+ <span+ role="img"+ aria-label={actions.status}+ tabIndex={0}+ className="+ univer-inline-flex univer-size-8 univer-shrink-0 univer-items-center univer-justify-center+ univer-rounded-md univer-text-yellow-600+ focus-visible:univer-outline focus-visible:univer-outline-2+ focus-visible:univer-outline-primary-500+ dark:univer-text-yellow-400+ "+ >+ <WarningIcon />+ </span>+ </Tooltip>+ )}+ {actions.available && actions.showConvert && actions.convert && (+ <OleActionButton title={locale.t<LocaleKey>(convertActionKey)} disabled={disabled || !actions.available || (!actions.hasOnlineUnit && !actions.editable)} onClick={() => run(actions.convert!, true)}>+ {convertIcon}+ </OleActionButton>+ )}+ {actions.available && actions.editable && actions.rename && <OleActionButton title={locale.t<LocaleKey>('drawing-ui.ole.rename')} disabled={disabled} onClick={actions.rename}><RenameIcon /></OleActionButton>}+ {actions.editable && (+ <>+ <Separator orientation="vertical" className="univer-mx-0.5 !univer-h-4" />+ <OleActionButton danger title={locale.t<LocaleKey>('drawing-ui.ole.remove')} disabled={disabled} onClick={() => run(actions.remove)}><DeleteIcon /></OleActionButton>+ </>+ )}+ </div>+ );+}++export function OlePreview({ value }: { value: string }) {+ const locale = useDependency(LocaleService);+ const { url, mimeType, name } = JSON.parse(value) as { url: string; mimeType: string; name: string };+ return mimeType === 'application/pdf'+ ? (+ <div>+ <iframe title={name} src={url} style={{ height: '70vh', width: '100%', border: 0 }} />+ <div className="univer-flex univer-items-center univer-gap-2 univer-p-2 univer-text-sm">+ <span>{locale.t<LocaleKey>('drawing-ui.ole.nativePreviewHint')}</span>+ <a href={url} download={name} className="univer-text-primary-600">{locale.t<LocaleKey>('drawing-ui.ole.download')}</a>+ </div>+ </div>+ )+ : <img alt={name} src={url} style={{ maxHeight: '70vh', maxWidth: '100%', objectFit: 'contain' }} />;+}++export function OleOfficePreview({ value }: { value: string }) {+ const service = useDependency(OleUIService);+ const containerRef = useRef<HTMLDivElement>(null);+ useEffect(() => {+ const viewer = containerRef.current ? service.mountOfficePreview(value, containerRef.current) : undefined;+ return () => queueMicrotask(() => viewer?.dispose());+ }, [service, value]);+ return <div ref={containerRef} style={{ height: '70vh', width: '100%' }} />;+}diff --git a/packages/drawing-ui/src/views/ole/__tests__/OleName.spec.tsx b/packages/drawing-ui/src/views/ole/__tests__/OleName.spec.tsxnew file mode 100644index 0000000000..9d22c2a0fc--- /dev/null+++ b/packages/drawing-ui/src/views/ole/__tests__/OleName.spec.tsx@@ -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 { Injector, LocaleService, LocaleType } from '@univerjs/core';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import enUS from '../../../locale/en-US';+import { OleName } from '../OleName';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const cleanups: Array<() => void> = [];++function renderName() {+ const injector = new Injector([[LocaleService]]);+ const locale = injector.get(LocaleService);+ locale.load({ [LocaleType.EN_US]: enUS });+ locale.setLocale(LocaleType.EN_US);+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root = createRoot(container);+ const actions = { fileName: '原始名称.docx', close: vi.fn(), save: vi.fn(async (_value: string): Promise<string | undefined> => undefined) };+ act(() => root.render(<RediContext.Provider value={{ injector }}><OleName popup={{ extraProps: actions }} /></RediContext.Provider>));+ cleanups.push(() => {+ act(() => root.unmount());+ container.remove();+ injector.dispose();+ });+ const key = async (value: string, isComposing = false) => act(async () => {+ container.querySelector('[role="dialog"]')!.dispatchEvent(new KeyboardEvent('keydown', { key: value, isComposing, bubbles: true }));+ });+ return { container, actions, key };+}++afterEach(() => cleanups.splice(0).forEach((cleanup) => cleanup()));++describe('OLE name editing', () => {+ it('edits the basename and leaves the fixed extension visible', async () => {+ const h = renderName();+ expect(h.container.querySelector('input')?.value).toBe('原始名称');+ expect(h.container.textContent).toContain('.docx');+ await h.key('Enter', true);+ expect(h.actions.save).not.toHaveBeenCalled();+ await h.key('Enter');+ expect(h.actions.save).toHaveBeenCalledWith('原始名称');+ });++ it('cancels without saving and shows rejected saves inline', async () => {+ const h = renderName();+ await h.key('Escape');+ expect(h.actions.close).toHaveBeenCalledOnce();+ expect(h.actions.save).not.toHaveBeenCalled();+ h.actions.save.mockResolvedValue('Unable to save');+ await h.key('Enter');+ expect(h.container.querySelector('[role="alert"]')?.textContent).toBe('Unable to save');+ expect(h.container.querySelector('input')?.disabled).toBe(false);+ });++ it('provides only rename controls without a separate name viewer or copy action', () => {+ const h = renderName();+ expect(h.container.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe('Rename');+ expect(h.container.querySelector('input')).not.toBeNull();+ expect(h.container.querySelectorAll('button')).toHaveLength(2);+ expect(h.container.querySelector('[aria-label="Save name"]')).not.toBeNull();+ expect(h.container.querySelector('[aria-label="Copy name"]')).toBeNull();+ });+});diff --git a/packages/drawing-ui/src/views/ole/__tests__/OlePopup.spec.tsx b/packages/drawing-ui/src/views/ole/__tests__/OlePopup.spec.tsxnew file mode 100644index 0000000000..edae67eec3--- /dev/null+++ b/packages/drawing-ui/src/views/ole/__tests__/OlePopup.spec.tsx@@ -0,0 +1,148 @@+/**+ * 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 { Root } from 'react-dom/client';+import { Injector, LocaleService, LocaleType, UniverInstanceType } from '@univerjs/core';+import { RediContext } from '@univerjs/ui';+import { act } from 'react';+import { createRoot } from 'react-dom/client';+import { afterEach, describe, expect, it, vi } from 'vitest';+import enUS from '../../../locale/en-US';+import { OlePopup } from '../OlePopup';++(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+const cleanups: Array<() => void> = [];++function renderPopup() {+ const injector = new Injector([[LocaleService]]);+ const locale = injector.get(LocaleService);+ locale.load({ [LocaleType.EN_US]: enUS });+ locale.setLocale(LocaleType.EN_US);+ locale.setDirection('ltr');+ const container = document.createElement('div');+ document.body.appendChild(container);+ const root: Root = createRoot(container);+ const actions = {+ fileName: 'A very long filename that should never make the toolbar wider 文档.docx',+ officeType: UniverInstanceType.UNIVER_DOC,+ showConvert: true,+ hasOnlineUnit: false,+ converting: false,+ available: true,+ previewAvailable: true,+ status: '',+ editable: true,+ onEnter: vi.fn(),+ onLeave: vi.fn(),+ download: vi.fn(async () => {}),+ preview: vi.fn(async () => {}),+ convert: vi.fn(async () => {}),+ rename: vi.fn(),+ remove: vi.fn(async () => {}),+ };+ const render = () => act(() => {+ root.render(<RediContext.Provider value={{ injector }}><OlePopup popup={{ extraProps: actions }} /></RediContext.Provider>);+ });+ render();+ cleanups.push(() => {+ act(() => root.unmount());+ container.remove();+ injector.dispose();+ });+ const toolbar = () => container.querySelector('[role="toolbar"]')!;+ const button = (label: string) => container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);+ return { actions, render, toolbar, button };+}++afterEach(() => cleanups.splice(0).forEach((cleanup) => cleanup()));++describe('compact OLE toolbar', () => {+ it('disables unsupported preview without blocking download', () => {+ const h = renderPopup();+ h.actions.previewAvailable = false;+ h.render();+ expect(h.button('Preview')).toBeNull();+ expect(h.toolbar().querySelector<HTMLButtonElement>('button:disabled')).not.toBeNull();+ expect(h.button('Download')?.disabled).toBe(false);+ });++ it('shows a focusable reason instead of unavailable actions, with Delete only for editors', () => {+ const h = renderPopup();+ h.actions.available = false;+ h.actions.status = 'The original file is not embedded in this document.';+ h.render();+ const reason = h.toolbar().querySelector('[role="img"]');+ expect(reason?.getAttribute('aria-label')).toBe(h.actions.status);+ expect(reason?.getAttribute('tabindex')).toBe('0');+ act(() => reason?.parentElement?.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })));+ expect(document.querySelector('[role="tooltip"]')?.className).toContain('!univer-pointer-events-none');+ expect(h.toolbar().textContent).toBe('');+ expect(h.toolbar().querySelectorAll('button')).toHaveLength(1);+ expect(h.button('Delete')).not.toBeNull();+ for (const label of ['Preview', 'Download', 'Rename', 'Convert to online document']) {+ expect(h.button(label)).toBeNull();+ }+ h.actions.editable = false;+ h.render();+ expect(h.toolbar().querySelectorAll('button')).toHaveLength(0);+ expect(h.toolbar().querySelector('[role="img"]')?.getAttribute('aria-label')).toBe(h.actions.status);+ });++ it('keeps filenames out of the visible toolbar while preserving the accessible name', () => {+ const h = renderPopup();+ expect(h.toolbar().textContent).toBe('');+ expect(h.toolbar().getAttribute('aria-label')).toBe(h.actions.fileName);+ expect(h.toolbar().querySelectorAll('button')).toHaveLength(5);+ h.actions.fileName = `${'x'.repeat(300)}.docx`;+ h.render();+ expect(h.toolbar().textContent).toBe('');+ expect(h.toolbar().querySelectorAll('button')).toHaveLength(5);+ });++ it('shows conversion progress immediately and restores controls when the import completes', async () => {+ const h = renderPopup();+ let finish!: () => void;+ h.actions.convert.mockImplementation(() => new Promise<void>((resolve) => {+ finish = resolve;+ }));+ await act(async () => h.button('Convert to online document')!.click());+ expect(h.toolbar().getAttribute('aria-busy')).toBe('true');+ expect(h.button('Converting…')?.disabled).toBe(true);+ expect(h.toolbar().querySelector('.univer-animate-spin')).not.toBeNull();+ await act(async () => finish());+ h.actions.hasOnlineUnit = true;+ h.render();+ expect(h.toolbar().getAttribute('aria-busy')).toBe('false');+ expect(h.button('Open online document in new tab')?.disabled).toBe(false);+ expect(h.toolbar().querySelector('.univer-animate-spin')).toBeNull();+ });++ it('hides online conversion for local mode and permits opening an existing link in read-only mode', () => {+ const h = renderPopup();+ h.actions.showConvert = false;+ h.render();+ expect(h.toolbar().querySelectorAll('button')).toHaveLength(4);+ h.actions.showConvert = true;+ h.actions.editable = false;+ h.render();+ expect(h.button('Convert to online document')?.disabled).toBe(true);+ h.actions.hasOnlineUnit = true;+ h.render();+ expect(h.button('Open online document in new tab')?.disabled).toBe(false);+ expect(h.button('Delete')).toBeNull();+ expect(h.button('Rename')).toBeNull();+ });+});diff --git a/packages/drawing-ui/src/views/ole/__tests__/ole-canvas-renderer.spec.ts b/packages/drawing-ui/src/views/ole/__tests__/ole-canvas-renderer.spec.tsnew file mode 100644index 0000000000..f0f7e6e490--- /dev/null+++ b/packages/drawing-ui/src/views/ole/__tests__/ole-canvas-renderer.spec.ts@@ -0,0 +1,164 @@+/**+ * 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 { UniverRenderingContext } from '@univerjs/engine-render';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { OleCanvasRenderer } from '../ole-canvas-renderer';++class TestPath2D {+ constructor(readonly data: string) {}+}++function context() {+ vi.stubGlobal('Path2D', TestPath2D);+ return {+ _context: { fillStyle: '', strokeStyle: '' },+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ rect: vi.fn(),+ clip: vi.fn(),+ translate: vi.fn(),+ scale: vi.fn(),+ fill: vi.fn(),+ stroke: vi.fn(),+ fillText: vi.fn(),+ fillRect: vi.fn(),+ drawImage: vi.fn(),+ measureText: vi.fn((text: string) => ({ width: Array.from(text).length * 6 })),+ fillStyle: '',+ font: '',+ textAlign: '',+ textBaseline: '',+ };+}++afterEach(() => vi.unstubAllGlobals());++describe('OLE vector canvas content', () => {+ it('paints a vector warning badge and explicit status below the filename without a bitmap or background', () => {+ const ctx = context();+ const renderer = new OleCanvasRenderer('linked.pdf', 'application/pdf', () => '#112233', undefined, { label: 'Link unavailable', color: () => '#AA6600' });+ renderer.draw(ctx as unknown as UniverRenderingContext, 192, 128);+ expect(ctx.fillText.mock.calls.map(([text]) => text)).toEqual(['linked.pdf', 'Link unavailable']);+ expect(ctx.fillStyle).toBe('#AA6600');+ expect(ctx.fill.mock.calls.some(([path]) => (path as TestPath2D).data === 'M8 1L15 14H1Z')).toBe(true);+ expect(ctx.font).toMatch(/^12px /);+ expect(ctx.rect).toHaveBeenCalledWith(0, 0, 192, 128);+ expect(ctx.fillRect).not.toHaveBeenCalled();+ expect(ctx.drawImage).not.toHaveBeenCalled();+ });++ it('prioritizes the unavailable status within small native object bounds', () => {+ const ctx = context();+ new OleCanvasRenderer('filename.pdf', 'application/pdf', () => '#112233', undefined, { label: 'Unavailable', color: () => '#AA6600' })+ .draw(ctx as unknown as UniverRenderingContext, 96, 48);+ expect(ctx.fillText).toHaveBeenCalledOnce();+ expect(ctx.fillText.mock.lastCall![0]).toBe('Unavailable');+ expect(ctx.fillStyle).toBe('#AA6600');+ expect(ctx.rect).toHaveBeenCalledWith(0, 0, 96, 48);+ expect(ctx.drawImage).not.toHaveBeenCalled();+ });++ it('reserves space for the glyph in small native Office objects', () => {+ const ctx = context();+ new OleCanvasRenderer('Microsoft_Word_Document.docx', 'application/msword', () => '#112233')+ .draw(ctx as unknown as UniverRenderingContext, 76, 48);+ expect(ctx.fillText).toHaveBeenCalledOnce();+ expect(ctx.fillText.mock.lastCall![0]).toMatch(/\.docx$/);+ expect((ctx.scale.mock.lastCall![0] as number) * 16).toBeGreaterThan(24);+ });++ it('grows the vector glyph with the object and keeps a fixed logical font size', () => {+ const ctx = context();+ const renderer = new OleCanvasRenderer('report.docx', 'application/msword', () => '#112233');+ renderer.draw(ctx as unknown as UniverRenderingContext, 96, 64);+ const firstScale = ctx.scale.mock.lastCall![0] as number;+ const firstFont = ctx.font;+ renderer.draw(ctx as unknown as UniverRenderingContext, 192, 128);+ const enlargedScale = ctx.scale.mock.lastCall![0] as number;+ expect(enlargedScale).toBeGreaterThan(firstScale);+ expect(enlargedScale * 16).toBeGreaterThan(32);+ expect(ctx.font).toBe(firstFont);+ renderer.draw(ctx as unknown as UniverRenderingContext, 76, 48);+ expect(ctx.font).toBe(firstFont);+ expect(ctx.drawImage).not.toHaveBeenCalled();+ expect(ctx.scale.mock.lastCall![0]).toBeLessThan(enlargedScale);+ });++ it('updates occurrence captions without changing artwork', () => {+ const ctx = context();+ let name = 'original.docx';+ const renderer = new OleCanvasRenderer(name, 'application/msword', () => '#112233', () => name);+ renderer.draw(ctx as unknown as UniverRenderingContext, 96, 80);+ name = '预算.docx';+ renderer.draw(ctx as unknown as UniverRenderingContext, 96, 80);+ expect(ctx.fillText).toHaveBeenLastCalledWith(name, 48, expect.any(Number));+ });++ it('draws transparent vector artwork and real text on every paint, including after zoom', () => {+ const ctx = context();+ const renderer = new OleCanvasRenderer('report.docx', 'application/msword', () => '#112233');+ renderer.draw(ctx as unknown as UniverRenderingContext, 552, 100);+ const measurements = ctx.measureText.mock.calls.length;+ renderer.draw(ctx as unknown as UniverRenderingContext, 552, 100);+ expect(ctx.fillText).toHaveBeenCalledTimes(2);+ expect(ctx.fillText.mock.calls[0][0]).toBe('report.docx');+ expect(ctx.fill).toHaveBeenCalled();+ expect(ctx.fill.mock.calls[0][0]).toBeInstanceOf(TestPath2D);+ const iconScale = ctx.scale.mock.lastCall![0] as number;+ expect(iconScale).toBeGreaterThan(2);+ expect(ctx.scale).toHaveBeenCalledWith(iconScale, iconScale);+ expect(ctx.measureText).toHaveBeenCalledTimes(measurements);+ expect(ctx.fillStyle).toBe('#112233');+ expect(ctx.fillRect).not.toHaveBeenCalled();+ expect(ctx.drawImage).not.toHaveBeenCalled();+ });++ it('remeasures resized objects, wraps Unicode filenames and keeps a complete extension', () => {+ const ctx = context();+ const renderer = new OleCanvasRenderer('季度 Budget 2026 financial report.xlsx', 'application/vnd.ms-excel', () => '#112233');+ renderer.draw(ctx as unknown as UniverRenderingContext, 96, 64);+ const lines = ctx.fillText.mock.calls.map(([text]) => text as string);+ expect(lines).toHaveLength(2);+ expect(lines[1]).toMatch(/\.xlsx$/);+ const measurements = ctx.measureText.mock.calls.length;+ renderer.draw(ctx as unknown as UniverRenderingContext, 192, 64);+ expect(ctx.measureText.mock.calls.length).toBeGreaterThan(measurements);+ expect(ctx.fillRect).not.toHaveBeenCalled();+ });++ it('clips fixed-size captions to tiny objects and does not distort the glyph', () => {+ const ctx = context();+ const renderer = new OleCanvasRenderer('report.docx', 'application/msword', () => '#112233');+ renderer.draw(ctx as unknown as UniverRenderingContext, 40, 20);+ expect(ctx.font).toMatch(/^12px /);+ expect(ctx.rect).toHaveBeenCalledWith(0, 0, 40, 20);+ expect(ctx.clip).toHaveBeenCalledOnce();+ const [x, y] = ctx.scale.mock.lastCall!;+ expect(x).toBe(y);+ expect(x).toBeGreaterThanOrEqual(0);+ expect(ctx.drawImage).not.toHaveBeenCalled();+ });++ it.each(['application/pdf', 'application/zip', 'image/png', 'application/octet-stream'])('keeps %s as vector artwork', (mimeType) => {+ const ctx = context();+ new OleCanvasRenderer('attachment.bin', mimeType, () => '#112233').draw(ctx as unknown as UniverRenderingContext, 96, 64);+ expect(ctx.fill).toHaveBeenCalled();+ expect(ctx.fillText).toHaveBeenCalled();+ expect(ctx.drawImage).not.toHaveBeenCalled();+ });+});diff --git a/packages/drawing-ui/src/views/ole/__tests__/ole-object.spec.ts b/packages/drawing-ui/src/views/ole/__tests__/ole-object.spec.tsnew file mode 100644index 0000000000..75f5a1a08c--- /dev/null+++ b/packages/drawing-ui/src/views/ole/__tests__/ole-object.spec.ts@@ -0,0 +1,84 @@+/**+ * 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 { UniverRenderingContext } from '@univerjs/engine-render';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { OleCanvasRenderer } from '../ole-canvas-renderer';+import { OleObject } from '../ole-object';++function context() {+ vi.stubGlobal('Path2D', class {});+ return {+ _context: { fillStyle: '', strokeStyle: '' },+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ rect: vi.fn(),+ clip: vi.fn(),+ translate: vi.fn(),+ scale: vi.fn(),+ transform: vi.fn(),+ fill: vi.fn(),+ stroke: vi.fn(),+ fillText: vi.fn(),+ drawImage: vi.fn(),+ measureText: (text: string) => ({ width: text.length * 6 }),+ font: '',+ fillStyle: '',+ textAlign: '',+ textBaseline: '',+ globalAlpha: 1,+ };+}++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('OLE canvas object', () => {+ it('redraws vector content and sharp captions at the current size without loading a bitmap', () => {+ const ctx = context();+ const createElement = vi.spyOn(document, 'createElement');+ const object = new OleObject('ole', { width: 96, height: 64, url: 'https://example.test/unused.png' });+ object.setRenderer(new OleCanvasRenderer('report.docx', 'application/msword', () => '#112233'));+ expect(object.getNative()).toBeUndefined();+ expect(createElement).not.toHaveBeenCalled();+ object.render(ctx as unknown as UniverRenderingContext);+ const firstScale = ctx.scale.mock.lastCall![0];+ object.transformByState({ width: 192, height: 128 });+ object.render(ctx as unknown as UniverRenderingContext);+ expect(ctx.scale.mock.lastCall![0]).toBeGreaterThan(firstScale);+ expect(ctx.fillText).toHaveBeenCalledWith('report.docx', 96, expect.any(Number));+ expect(ctx.font).toMatch(/^12px /);+ expect(ctx.drawImage).not.toHaveBeenCalled();+ expect(object.transformerConfig?.rotateEnabled).toBe(false);+ object.dispose();+ });++ it('retains native bounds, opacity and viewport clipping for document pages', () => {+ const ctx = context();+ const object = new OleObject('clipped', { left: 20, top: 30, width: 96, height: 64, opacity: 0.5, clipBounds: { left: 10, top: 20, width: 80, height: 60 } });+ object.setRenderer(new OleCanvasRenderer('file.pdf', 'application/pdf', () => '#112233'));+ object.render(ctx as unknown as UniverRenderingContext);+ expect(ctx.rect).toHaveBeenCalledWith(10, 20, 80, 60);+ expect(ctx.transform).toHaveBeenCalledWith(1, 0, 0, 1, 68, 62);+ expect(ctx.globalAlpha).toBe(0.5);+ expect(object.getRealBound()).toMatchObject({ left: 20, top: 30, width: 96, height: 64 });+ expect(ctx.drawImage).not.toHaveBeenCalled();+ object.dispose();+ });+});diff --git a/packages/drawing-ui/src/views/ole/ole-canvas-renderer.ts b/packages/drawing-ui/src/views/ole/ole-canvas-renderer.tsnew file mode 100644index 0000000000..d682170238--- /dev/null+++ b/packages/drawing-ui/src/views/ole/ole-canvas-renderer.ts@@ -0,0 +1,317 @@+/**+ * 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 { UniverRenderingContext } from '@univerjs/engine-render';+import { UniverInstanceType } from '@univerjs/core';+import { getOleOfficeType } from '@univerjs/drawing';++interface IOleGlyphPath {+ d: string;+ fill?: string;+ stroke?: string;+ strokeWidth?: number;+ fillRule?: CanvasFillRule;+}++const GLYPHS: Record<string, IOleGlyphPath[]> = {+ sheet: [+ {+ d: 'M3.4535 1.12549C2.7002 1.12549 2.08954 1.73615 2.08954 2.48945V13.5104C2.08954 14.2637 2.7002 14.8744 3.4535 14.8744H12.5465C13.2998 14.8744 13.9105 14.2637 13.9105 13.5104V5.0992L10.0091 1.12549H3.4535Z',+ fill: '#35BD4B',+ },+ {+ d: 'M10.0075 1.12549L13.9104 5.09842H10.6742C10.306 5.09842 10.0075 4.79994 10.0075 4.43175V1.12549Z',+ fill: '#32A846',+ },+ {+ d: 'M4.7 7.05H11.1V12.05H4.7V7.05ZM5.5 7.85V9.2H7.35V7.85H5.5ZM8.15 7.85V9.2H10.3V7.85H8.15ZM5.5 10V11.25H7.35V10H5.5ZM8.15 10V11.25H10.3V10H8.15Z',+ fill: 'white',+ fillRule: 'evenodd',+ },+ ],+ doc: [+ {+ d: 'M3.4535 1.12549C2.7002 1.12549 2.08954 1.73615 2.08954 2.48945V13.5104C2.08954 14.2637 2.7002 14.8744 3.4535 14.8744H12.5465C13.2998 14.8744 13.9105 14.2637 13.9105 13.5104V5.0992L10.0091 1.12549H3.4535Z',+ fill: '#4B7DFF',+ },+ {+ d: 'M10.0075 1.12549L13.9104 5.09842H10.6742C10.306 5.09842 10.0075 4.79994 10.0075 4.43175V1.12549Z',+ fill: '#305CFA',+ },+ {+ d: 'M4.57245 7.27962C4.57245 7.09553 4.72169 6.94629 4.90578 6.94629H10.2391C10.4232 6.94629 10.5724 7.09553 10.5724 7.27962C10.5724 7.46372 10.4232 7.61296 10.2391 7.61296H4.90578C4.72169 7.61296 4.57245 7.46372 4.57245 7.27962Z',+ fill: 'white',+ },+ {+ d: 'M4.57245 9.62638C4.57245 9.44229 4.72169 9.29305 4.90578 9.29305H10.2391C10.4232 9.29305 10.5724 9.44229 10.5724 9.62638C10.5724 9.81048 10.4232 9.95972 10.2391 9.95972H4.90578C4.72169 9.95972 4.57245 9.81048 4.57245 9.62638Z',+ fill: 'white',+ },+ {+ d: 'M4.90578 11.6398C4.72169 11.6398 4.57245 11.789 4.57245 11.9731C4.57245 12.1572 4.72169 12.3065 4.90578 12.3065H7.57245C7.75654 12.3065 7.90578 12.1572 7.90578 11.9731C7.90578 11.789 7.75654 11.6398 7.57245 11.6398H4.90578Z',+ fill: 'white',+ },+ ],+ slide: [+ {+ d: 'M3.4535 1.12549C2.7002 1.12549 2.08954 1.73615 2.08954 2.48945V13.5104C2.08954 14.2637 2.7002 14.8744 3.4535 14.8744H12.5465C13.2998 14.8744 13.9105 14.2637 13.9105 13.5104V5.0992L10.0091 1.12549H3.4535Z',+ fill: '#FF6B4B',+ },+ {+ d: 'M10.0075 1.12549L13.9104 5.09842H10.6742C10.306 5.09842 10.0075 4.79994 10.0075 4.43175V1.12549Z',+ fill: '#EC4F2D',+ },+ {+ d: 'M7.76493 7.24535C7.76493 7.07967 7.63024 6.94371 7.46548 6.96123C7.01146 7.00953 6.57426 7.16714 6.19216 7.42245C5.72662 7.73351 5.36378 8.17564 5.14951 8.69292C4.93525 9.2102 4.87918 9.77941 4.98842 10.3285C5.09765 10.8777 5.36727 11.3821 5.76318 11.778C6.15909 12.1739 6.66351 12.4436 7.21265 12.5528C7.76179 12.662 8.33099 12.606 8.84828 12.3917C9.36556 12.1774 9.80769 11.8146 10.1188 11.349C10.3741 10.9669 10.5317 10.5297 10.58 10.0757C10.5975 9.91096 10.4615 9.77627 10.2958 9.77627L8.06493 9.77627C7.89925 9.77627 7.76493 9.64195 7.76493 9.47627L7.76493 7.24535Z',+ fill: 'white',+ },+ {+ d: 'M10.4097 9.35206C10.5753 9.35206 10.7115 9.21728 10.6918 9.05277C10.6645 8.82511 10.6062 8.60178 10.5181 8.38909C10.3917 8.08379 10.2063 7.80639 9.97264 7.57272C9.73897 7.33905 9.46157 7.1537 9.15627 7.02724C8.94358 6.93914 8.72024 6.88083 8.49259 6.85356C8.32808 6.83385 8.1933 6.97001 8.1933 7.13569V9.05206C8.1933 9.21774 8.32761 9.35206 8.4933 9.35206H10.4097Z',+ fill: 'white',+ },+ ],+ pdf: [+ {+ d: 'M3.4535 1.12549C2.7002 1.12549 2.08954 1.73615 2.08954 2.48945V13.5104C2.08954 14.2637 2.7002 14.8744 3.4535 14.8744H12.5465C13.2998 14.8744 13.9105 14.2637 13.9105 13.5104V5.0992L10.0091 1.12549H3.4535Z',+ fill: '#E5484D',+ },+ {+ d: 'M10.0075 1.12549L13.9104 5.09842H10.6742C10.306 5.09842 10.0075 4.79994 10.0075 4.43175V1.12549Z',+ fill: '#C62F35',+ },+ {+ d: 'M4.75 6.45H9.3L11.25 8.4V12.35H4.75V6.45Z',+ fill: 'white',+ },+ {+ d: 'M9.3 6.45V8.4H11.25L9.3 6.45Z',+ fill: '#F7C7C9',+ },+ {+ d: 'M4.15 8.65H11.75V11.35H4.15V8.65Z',+ fill: '#B9252D',+ },+ {+ d: 'M5.05 10.62V9.38H5.45C5.76 9.38 5.94 9.57 5.94 9.82C5.94 10.08 5.76 10.25 5.45 10.25H5.05M6.43 9.38V10.62H6.78C7.16 10.62 7.38 10.38 7.38 10C7.38 9.62 7.16 9.38 6.78 9.38H6.43ZM7.88 10.62V9.38H8.85M7.88 9.99H8.62',+ stroke: 'white',+ strokeWidth: 0.42,+ },+ ],+ image: [+ {+ d: 'M3 1.5h6l4 4v9H3z',+ fill: '#8E51FF',+ },+ {+ d: 'M9 1.5v4h4',+ fill: '#6E35D1',+ },+ {+ d: 'M5.0 8.0a1.0 1.0 0 1 0 2.0 0a1.0 1.0 0 1 0 -2.0 0',+ fill: 'white',+ },+ {+ d: 'M4.5 12.5l2.3-2.5 1.5 1.4 1.7-2.2 2 3.3z',+ fill: 'white',+ },+ ],+ zip: [+ {+ d: 'M3 1.5h6l4 4v9H3z',+ fill: '#E5A000',+ },+ {+ d: 'M9 1.5v4h4',+ fill: '#BD8200',+ },+ {+ d: 'M6 2h1v1H6zm1 1h1v1H7zM6 4h1v1H6zm1 1h1v1H7zM6 6h1v1H6zm1 1h1v1H7zM6 8h1v1H6zM6 10h2v2H6z',+ fill: 'white',+ },+ ],+ unknown: [+ {+ d: 'M3 1.5h6l4 4v9H3z',+ fill: '#F3F4F6',+ stroke: '#9CA3AF',+ },+ {+ d: 'M9 1.5v4h4M5 9h6M5 11h4',+ stroke: '#9CA3AF',+ },+ ],+};+const paths = new Map<IOleGlyphPath, Path2D>();+const warningShape: IOleGlyphPath = { d: 'M8 1L15 14H1Z' };+const warningMark: IOleGlyphPath = { d: 'M7.25 5H8.75V9.5H7.25ZM7.25 11H8.75V12.5H7.25Z' };++interface IOleCanvasWarning {+ label: string;+ color: () => string;+}++function glyphType(mimeType: string): string {+ switch (getOleOfficeType(mimeType)) {+ case UniverInstanceType.UNIVER_SHEET: return 'sheet';+ case UniverInstanceType.UNIVER_DOC: return 'doc';+ case UniverInstanceType.UNIVER_SLIDE: return 'slide';+ }+ if (mimeType === 'application/pdf') {+ return 'pdf';+ }+ if (mimeType.startsWith('image/')) {+ return 'image';+ }+ if (mimeType === 'application/zip' || mimeType === 'application/x-zip-compressed') {+ return 'zip';+ }+ return 'unknown';+}++function fittingPrefix(value: string, width: number, measure: (text: string) => number): string {+ const points = Array.from(value);+ let low = 0;+ let high = points.length;+ while (low < high) {+ const middle = Math.ceil((low + high) / 2);+ if (measure(points.slice(0, middle).join('')) <= width) {+ low = middle;+ } else {+ high = middle - 1;+ }+ }+ return points.slice(0, low).join('');+}++function ellipsize(value: string, width: number, measure: (text: string) => number): string {+ if (measure(value) <= width) {+ return value;+ }+ const dot = value.lastIndexOf('.');+ const suffix = dot > 0 && value.length - dot <= 12 ? value.slice(dot) : '';+ if (measure(`…${suffix}`) > width) {+ return measure('…') <= width ? '…' : '';+ }+ return `${fittingPrefix(suffix ? value.slice(0, dot) : value, width - measure(`…${suffix}`), measure)}…${suffix}`;+}++function caption(value: string, width: number, maxLines: number, measure: (text: string) => number): string[] {+ if (measure(value) <= width || maxLines === 1) {+ return [ellipsize(value, width, measure)];+ }+ let first = fittingPrefix(value, width, measure);+ const dot = value.lastIndexOf('.');+ if (dot > 0 && dot < first.length && value.length - dot <= 12) {+ first = value.slice(0, dot);+ }+ const split = Math.max(first.lastIndexOf(' '), first.lastIndexOf('_'), first.lastIndexOf('-'));+ if (split > first.length / 2) {+ first = first.slice(0, split + 1);+ }+ if (!first) {+ return [ellipsize(value, width, measure)];+ }+ return [first.trimEnd(), ellipsize(value.slice(first.length).trimStart(), width, measure)];+}++/** Rasterize paths and text directly into the current canvas, at its current zoom and pixel ratio. */+export class OleCanvasRenderer {+ private _name: string;+ private readonly _glyph: IOleGlyphPath[];+ private _layout?: { width: number; height: number; font: number; lines: string[]; icon: number; top: number };++ constructor(name: string, mimeType: string, private readonly _textColor: () => string, private readonly _getName?: () => string, private readonly _warning?: IOleCanvasWarning) {+ this._name = name.slice(0, 2048).replace(/[\u0000-\u001F\u007F]/g, '');+ this._glyph = GLYPHS[glyphType(mimeType)];+ }++ draw = (ctx: UniverRenderingContext, width: number, height: number): void => {+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {+ return;+ }+ const name = (this._getName?.() ?? this._name).slice(0, 2048).replace(/[\u0000-\u001F\u007F]/g, '');+ if (name !== this._name) {+ this._name = name;+ this._layout = undefined;+ }+ ctx.save();+ ctx.translate(-width / 2, -height / 2);+ ctx.beginPath();+ ctx.rect(0, 0, width, height);+ ctx.clip();+ const font = 12;+ ctx.font = `${font}px Arial, "Microsoft YaHei", sans-serif`;+ let layout = this._layout;+ if (!layout || layout.width !== width || layout.height !== height) {+ const textWidth = Math.max(0, Math.min(240, width - 8));+ const measure = (text: string) => ctx.measureText(text).width;+ let lines = caption(this._name, textWidth, height < 64 ? 1 : 2, measure);+ if (this._warning) {+ lines = height < 64+ ? [ellipsize(this._warning.label, textWidth, measure)]+ : [ellipsize(this._name, textWidth, measure), ellipsize(this._warning.label, textWidth, measure)];+ }+ const icon = Math.max(0, Math.min(width - 4, height - lines.length * font * 1.2 - 4));+ layout = { width, height, font, lines, icon, top: Math.max(0, (height - icon - lines.length * font * 1.2 - 4) / 2) };+ this._layout = layout;+ }+ ctx.save();+ ctx.translate((width - layout.icon) / 2, layout.top);+ ctx.scale(layout.icon / 16, layout.icon / 16);+ for (const part of this._glyph) {+ let path = paths.get(part);+ if (!path) {+ path = new Path2D(part.d);+ paths.set(part, path);+ }+ // File-brand colors are intrinsic artwork, like a native image; do not invert them in dark mode.+ if (part.fill) {+ ctx._context.fillStyle = part.fill;+ ctx.fill(path, part.fillRule ?? 'nonzero');+ }+ if (part.stroke) {+ ctx._context.strokeStyle = part.stroke;+ ctx.lineWidth = part.strokeWidth ?? 1;+ ctx.lineCap = 'round';+ ctx.lineJoin = 'round';+ ctx.stroke(path);+ }+ }+ ctx.restore();+ if (this._warning && layout.icon >= 12) {+ ctx.save();+ const size = Math.min(16, layout.icon / 2);+ ctx.translate((width + layout.icon) / 2 - size, layout.top + layout.icon - size);+ ctx.scale(size / 16, size / 16);+ for (const part of [warningShape, warningMark]) {+ let path = paths.get(part);+ if (!path) {+ path = new Path2D(part.d);+ paths.set(part, path);+ }+ ctx._context.fillStyle = part === warningShape ? this._warning.color() : '#FFFFFF';+ ctx.fill(path);+ }+ ctx.restore();+ }+ ctx.textAlign = 'center';+ ctx.textBaseline = 'alphabetic';+ layout.lines.forEach((line, index) => {+ ctx.fillStyle = this._warning && index === layout.lines.length - 1 ? this._warning.color() : this._textColor();+ ctx.fillText(line, width / 2, layout.top + layout.icon + 4 + layout.font + index * layout.font * 1.2);+ });+ ctx.restore();+ };+}diff --git a/packages/drawing-ui/src/views/ole/ole-object.ts b/packages/drawing-ui/src/views/ole/ole-object.tsnew file mode 100644index 0000000000..5edbabb49c--- /dev/null+++ b/packages/drawing-ui/src/views/ole/ole-object.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 { IImageProps, IViewportInfo, UniverRenderingContext } from '@univerjs/engine-render';+import { Image } from '@univerjs/engine-render';+import type { OleCanvasRenderer } from './ole-canvas-renderer';++/** OLE content is drawn as paths and text; Image supplies only geometry, clipping and hit testing. */+export class OleObject extends Image {+ private _renderer?: OleCanvasRenderer;++ constructor(id: string, config: IImageProps) {+ super(id, { ...config, image: undefined, url: undefined });+ this.transformerConfig = { ...this.transformerConfig, rotateEnabled: false };+ }++ setRenderer(renderer: OleCanvasRenderer): void {+ this._renderer = renderer;+ this.makeDirty(true);+ }++ protected override _draw(ctx: UniverRenderingContext, _bounds?: IViewportInfo, renderWidth?: number, renderHeight?: number): void {+ this._renderer?.draw(ctx, renderWidth ?? this.width, renderHeight ?? this.height);+ }++ override dispose(): void {+ this._renderer = undefined;+ super.dispose();+ }+}diff --git a/packages/drawing/README.md b/packages/drawing/README.mdindex db764405c9..8a4f26edce 100644--- a/packages/drawing/README.md+++ b/packages/drawing/README.md@@ -30,6 +30,12 @@ import { UniverDrawingPlugin } from '@univerjs/drawing';univer.registerPlugin(UniverDrawingPlugin);```+## OLE online references++An OLE drawing retains its `oleAttachmentId`, which identifies the original attachment's resource record. After explicit online conversion, `oleOnlineUnit` stores only the new Unit's `unitId` and `type`; it does not store a URL or embed the converted Unit's snapshot.++Configure `ole.getLink(unitId, type)` on `UniverDrawingPlugin` to resolve the application's current URL on each explicit Open action. There is no default application route. The existing Pro `UniverExchangeClientPlugin` supplies conversion callbacks without adding a separate OLE plugin or owning navigation. Legacy stored `url` fields remain unchanged and are ignored when opening. See the [OLE integration guide](./docs/ole-attachments.md) for configuration and transport boundaries.+## Resources- [Documentation](https://docs.univer.ai)diff --git a/packages/drawing/docs/ole-attachments.md b/packages/drawing/docs/ole-attachments.mdnew file mode 100644index 0000000000..f856024bb2--- /dev/null+++ b/packages/drawing/docs/ole-attachments.md@@ -0,0 +1,82 @@+# OLE attachment resources++OLE drawings use `DrawingTypeEnum.DRAWING_OLE` and the versioned `UNIVER_OLE_ATTACHMENT_PLUGIN` resource. Each occurrence has its own object identity; files are addressed by SHA-256. The resource preserves the original Office part, a losslessly extracted independent file when available, presentation parts and relationships. The host converter does not execute or automatically import the attachment.++`UniverDrawingPlugin` registers the resource for Sheets, Docs and Slides, including headless runtimes. The respective drawing UI plugins expose icon buttons for Preview, Download, Rename and Delete, with localized tooltips. The menu opens above the drawing by default. Compact drawing captions may wrap or ellipsize while retaining the extension; captions do not open a separate popup. The drawing supports position and size changes through the existing mutation and undo pipeline. Imported rotation is retained; direct rotation, flipping and cropping are not offered by the OLE toolbar. Preview state belongs to the local UI.++## JSON and online Unit transport++```ts+import { prepareOleSnapshot } from '@univerjs/drawing';++// JSON is portable: original bytes and presentation resources remain in the snapshot.+const portable = await prepareOleSnapshot(snapshot, 'json', undefined, attachmentIo);++// Upload every retained binary through the existing attachment contract before saving the Unit.+const online = await prepareOleSnapshot(snapshot, 'unit', targetUnitId, attachmentIo);+await saveUnitSnapshot(online);++// Resolve online attachments to a portable model before passing it to the Office exporter.+const exportSnapshot = await prepareOleSnapshot(online, 'json', undefined, attachmentIo);+```++`attachmentIo.upload(file, targetUnitId)` returns the existing `IBaseAttachment` with a stable UUID source and matching size. `attachmentIo.read(attachment, signal)` uses the application's authenticated attachment reader and renews signed URLs as needed. The helper accepts UnitData or the native exchange JSON envelope; it updates encoded slide metadata too. It clones the input and publishes no partially rewritten snapshot after an upload failure. Uploads are sequential. The application owns Unit save/load and attachment retention; deleting one occurrence does not immediately delete shared or historical binaries.++Inline JSON requires no upload service. Online mode stores attachment identities rather than signed URLs. Use the helper at the import/export transport boundary; regular Unit saves retain these references. Office export requires all referenced files to be resolved; missing or corrupt bytes cause an explicit error. The version 1 resource has a 50 MiB limit including JSON/Base64 overhead.++### Server creation and export boundaries++The server must use the OLE-capable drawing model and native exchange implementation together. Upgrading the browser alone does not preserve OLE across server materialization or Office export. Register the drawing model plugin in headless runtimes so resource save/checkpoint operations retain attachment records.++When importing an Office file to an online Unit, allocate its final Unit ID first, transfer retained binaries through the application's attachment storage, then create the Unit from the prepared data. A server-side storage adapter can assign these files during creation, as it does for embedded images. Browser attachment endpoints that require an existing Unit must keep that validation; do not relax it to make a pre-creation upload succeed. Do not expose the new Unit until preparation and creation succeed. Upload failures may leave unreferenced files for the application's normal attachment cleanup, but must not publish a partially prepared model.++Before Office export, materialize the Unit through the Server SDK and call `prepareOleSnapshot(..., 'json', undefined, attachmentIo)` to resolve every UUID to validated bytes. Passing a snapshot containing unresolved UUIDs directly to the native exporter is not a complete export integration. JSON import/export keeps bytes inline and needs no attachment uploader. Native SDK envelopes may contain `Uint8Array` metadata, sheet blocks or UTF-8 resource data; the helper preserves those representations and copies their buffers without changing the caller's data. It does not reassign Unit identities.++## Preview integration++The Pro collaboration client supplies an adapter using the existing attachment upload/sign/read requests. It passes the explicit target Unit to the shared attachment uploader, independently of the currently focused Unit. Configure navigation on the existing drawing plugin, and register the existing exchange client with the application's exchange endpoints:++```ts+import { UniverDrawingPlugin } from '@univerjs/drawing';+import { UniverExchangeClientPlugin } from '@univerjs-pro/exchange-client';++univer.registerPlugin(UniverDrawingPlugin, {+ ole: {+ getLink: (unitId, type) => `/viewer?unit=${encodeURIComponent(unitId)}&type=${type}`,+ },+});+univer.registerPlugin(UniverExchangeClientPlugin, exchangeEndpoints);+```++The example's `/viewer` route belongs to the application; replace it with the application's official Unit Viewer route. Configure `getLink` once for all three hosts. It must synchronously return a relative or absolute HTTP(S) URL; use its second `type` argument when Sheet, Doc and Slide routes differ. There is no default application route. Without a resolver, online actions stay hidden; preview and download follow their own capabilities.++The existing exchange client installs lazy `ole.convertOffice` and `ole.convertToOnline` callbacks and an exact-Unit `ole.isCollaborative(unitId)` check, preserving application overrides. It contains transport and conversion logic without importing UI or DOM packages, so its normal entry remains usable in Node.js. There is no additional OLE exchange package or plugin registration. An online attachment submits its stable file ID and source Unit ID to the existing import/task endpoint; the browser does not read or upload its bytes. Inline JSON bytes are uploaded once. The server must authorize the persistent attachment reference and can use `UniverAttachmentImportService` with its normal attachment and Unit creation adapters. The JSON preview endpoint never creates a persisted Unit.++Common Drawing UI owns attachment actions, dialogs and the isolated temporary viewer lifecycle. Existing product UI modules provide stateless read-only renderers:++| Target attachment | Required renderer module |+| --- | --- |+| XLS/XLSX | `@univerjs/sheets-drawing-ui` |+| DOC/DOCX | `@univerjs/docs-drawing-ui` |+| PPT/PPTX | `@univerjs-pro/slides-ui` |++Load the corresponding existing product UI module with its normal styles and locale resources to enable cross-type preview. For example, a Sheet application needs Doc UI loaded to preview a Word attachment. Loading the module makes its renderer available before any target-type Unit exists; there is no additional OLE plugin registration. The temporary viewer registers that product's normal plugins when it opens. Applications may supply `ole.previewOffice` or `ole.createOfficePreview` instead. If the renderer is absent, Preview is disabled with a localized explanation before attachment reads or conversion requests. Download and online conversion retain their independent capability checks. PDF and supported image previews use the existing native preview dialog.++Only supported Office attachments in a collaborative host show Convert to online spreadsheet/document/slides. PDF, unknown binaries and unavailable local links are retained as attachments. A read-only host cannot create an online Unit reference. Existing references can still be opened, subject to normal destination authentication and permissions.++After a successful import, the host drawing command saves only `oleOnlineUnit: { unitId, type }` alongside `oleAttachmentId`. Slides store this field on the OLE page element. These fields travel through the existing drawing mutations, collaboration and undo/redo. Snapshot transport preserves the metadata in both modes. URLs are not persisted: every explicit Open action calls the current `getLink(unitId, type)`, including the completion notification. Legacy stored `url` fields remain untouched and are ignored, with no fallback to their old addresses. The retained original file is unchanged; Office export continues to embed that original file rather than the online document's later edits. The Unit reference does not contain a portable copy of the converted document.++Conversion keeps progress on the source page and never pre-opens a tab or navigates automatically. After the Unit reference is saved, a persistent completion notification offers Open. Clicking it or the drawing toolbar's Open action resolves the current URL and opens a new tab without importing again. If saving the reference fails after the server creates a Unit, the same UI session retains that result and retries persistence without another import. Deleting the OLE drawing or closing its host stops local waiting; it does not delete an already created independent online Unit. If a browser blocks the new tab, the reference remains available through the Open action.++Office preview remains an isolated read-only temporary Univer instance. It explicitly disables online conversion even when its parent is collaborative. All OLE action tooltips and error messages are defined in the 19 drawing UI locales.+++## Compact attachment toolbar++The shared OLE toolbar is one row of icon buttons: Preview, Download, optional Convert/Open online, Rename, then a separator and Delete. Rename and Delete are hidden for read-only hosts. Attachment filenames remain in the Canvas caption and the toolbar's accessible name; they do not participate in toolbar layout. There is no filename hover tooltip. Clicking a caption selects the object and uses the same toolbar; it never opens a separate name viewer. Action tooltips remain above their buttons. The editable local toolbar is 159 × 40 CSS pixels; the collaborative Office toolbar is 195 × 40 CSS pixels.++Sheet, Doc and Slide hosts use the shared `OleObject` canvas component from `@univerjs/drawing-ui`. It reuses existing engine image geometry, clipping and hit testing, while its OLE render path skips native bitmap loading and caching. File-type glyphs use built-in static vector paths and captions use Canvas text at the current zoom and device pixel ratio. Neither has a background panel. User-supplied SVG is never parsed by this renderer. Imported object geometry is retained; the glyph keeps its aspect ratio inside that geometry. Static artwork and captions remain on Canvas; only the explicit rename editor and action controls use temporary UI overlays.++Rename replaces the toolbar with an input above the object, with a fixed extension and explicit Save/Cancel buttons. Enter saves, Escape cancels, and composition Enter is ignored. Clipboard actions inside the input remain native text operations; they do not paste into the Slide canvas. Names must be nonempty, at most 255 Unicode characters including the extension, and cannot contain control/path characters or end in a dot. The per-occurrence `oleFileName` field overrides the displayed and default download name. The original file record, SHA-256 and bytes are unchanged, so other occurrences sharing those bytes retain their own names. Drawing commands persist the name through the normal mutations and undo/redo; both JSON and Unit snapshot transport retain it. Rename does not change an already converted online Unit's title. Office export retains original OLE binary and presentation parts; rewriting their native caption metadata to match the override is not implemented.++Online conversion keeps an indeterminate progress bar and localized reading/uploading, converting, creating and saving stages visible in a source-page notification. Closing a Unit or deleting its drawing immediately clears this UI and stops waiting; committed server work is not rolled back. Configure the existing exchange task timeout for large documents. Delete uses the danger hover color; normal, focus and dark colors use the existing theme tokens. All three product adapters position the toolbar above its attachment with an 8 px gap.diff --git a/packages/drawing/package.json b/packages/drawing/package.jsonindex 1e2d3dcf94..b1c54fbfe9 100644--- a/packages/drawing/package.json+++ b/packages/drawing/package.json@@ -67,6 +67,7 @@"rxjs": ">=7.0.0"},"dependencies": {+ "@noble/hashes": "1.8.0","@univerjs/core": "workspace:*"},"devDependencies": {diff --git a/packages/drawing/src/config/config.ts b/packages/drawing/src/config/config.tsindex 1c909b1f21..186f364f3d 100644--- a/packages/drawing/src/config/config.ts+++ b/packages/drawing/src/config/config.ts@@ -15,12 +15,14 @@*/import type { DependencyOverride } from '@univerjs/core';+import type { IOleConfig } from '../models/ole-model';export const DRAWING_PLUGIN_CONFIG_KEY = 'drawing.config';export const configSymbol = Symbol(DRAWING_PLUGIN_CONFIG_KEY);export interface IUniverDrawingConfig {+ ole?: IOleConfig;override?: DependencyOverride;/*** The maximum allowed size of uploaded images in bytes.diff --git a/packages/drawing/src/index.ts b/packages/drawing/src/index.tsindex 8804643c81..c3433d88cc 100644--- a/packages/drawing/src/index.ts+++ b/packages/drawing/src/index.ts@@ -18,6 +18,8 @@ export { DRAWING_IMAGE_ALLOW_IMAGE_LIST, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGexport { SetDrawingSelectedOperation } from './commands/operations/set-drawing-selected.operation';export type { IUniverDrawingConfig } from './config/config';export type { IDocFloatDomData, IDocFloatDomDataBase, IImageData } from './models/image-model-interface';+export type { IOleAttachmentIo, IOleConfig, IOleDrawing, IOleOnlineConversionRequest, IOleOnlineUnit, IOlePreviewRequest, IOleResource, OleConversionStage } from './models/ole-model';+export { getOleOfficeType, OLE_RESOURCE_NAME, prepareOleSnapshot, readOleFile } from './models/ole-model';export { UniverDrawingPlugin } from './plugin';export { DrawingManagerService, UnitDrawingService } from './services/drawing-manager-impl.service';export type { IDrawingJson1Type, IDrawingJsonUndo1 } from './services/drawing-manager-impl.service';@@ -34,6 +36,7 @@ export type {} from './services/drawing-manager.service';export { IDrawingManagerService } from './services/drawing-manager.service';export { ImageIoService } from './services/image-io-impl.service';+export { OleService } from './services/ole.service';export { URLImageService } from './services/url-image.service';export { createDrawingCopyPlan, DRAWING_COPY_CONTEXT_KEY, getOrCreateDrawingCopyPlan } from './utils/drawing-copy-plan';export type { ICreateDrawingCopyPlanOptions, IDrawingCopyPlan } from './utils/drawing-copy-plan';diff --git a/packages/drawing/src/models/__tests__/ole-model.spec.ts b/packages/drawing/src/models/__tests__/ole-model.spec.tsnew file mode 100644index 0000000000..716dd26eba--- /dev/null+++ b/packages/drawing/src/models/__tests__/ole-model.spec.ts@@ -0,0 +1,167 @@+/**+ * 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 { IOleAttachmentIo, IOleResource } from '../ole-model';+import { Buffer } from 'node:buffer';+import { createHash } from 'node:crypto';+import { describe, expect, it, vi } from 'vitest';+import { parseOleResource, prepareOleResource, prepareOleSnapshot, readOleFile } from '../ole-model';++const bytes = new TextEncoder().encode('%PDF-1.7 original attachment');+const sha256 = createHash('sha256').update(bytes).digest('hex');++function resource(): IOleResource {+ return {+ version: 1,+ files: { [sha256]: { name: 'original.pdf', mimeType: 'application/pdf', size: bytes.length, sha256, data: Buffer.from(bytes).toString('base64') } },+ objects: Object.fromEntries(['ole-1', 'ole-2'].map((id) => [id, {+ id,+ hostPart: 'xl/worksheets/sheet1.xml',+ subUnitId: 'sheet1',+ drawingId: id,+ shapeId: id,+ progId: '',+ relationshipId: 'r1',+ external: false,+ status: 'ready',+ rawFileId: sha256,+ fileId: sha256,+ xml: '<oleObject/>',+ relationships: [],+ parts: { 'xl/embeddings/object.bin': sha256 },+ }])),+ };+}++function adapter(): IOleAttachmentIo {+ return {+ upload: vi.fn(async (file, unitId) => ({ id: `${unitId}-file`, name: file.name, mimeType: file.type, size: file.size, source: `${unitId}-file`, sourceType: 'UUID' as never })),+ read: vi.fn(async () => bytes.slice()),+ };+}++describe('durable OLE attachments', () => {+ it('verifies original bytes on HTTP origins without Web Crypto', async () => {+ vi.stubGlobal('crypto', {});+ expect(await readOleFile(resource().files[sha256])).toEqual(bytes);+ const corrupt = resource().files[sha256];+ corrupt.data = Buffer.from('different bytes').toString('base64');+ corrupt.size = Buffer.from('different bytes').length;+ await expect(readOleFile(corrupt)).rejects.toThrow('integrity mismatch');+ });++ it('JSON save and reopen is self-contained and never calls attachment IO', async () => {+ const io = adapter();+ const json = await prepareOleResource(resource(), 'json', undefined, io);+ expect(await readOleFile(parseOleResource(JSON.stringify(json)).files[sha256])).toEqual(bytes);+ expect(io.upload).not.toHaveBeenCalled();+ expect(io.read).not.toHaveBeenCalled();+ expect(Object.keys(json.objects)).toEqual(['ole-1', 'ole-2']);+ });++ it('Unit upload binds the explicit host and stores a stable attachment identity', async () => {+ const input = resource();+ const io = adapter();+ const online = await prepareOleResource(input, 'unit', 'target-host', io);+ expect(io.upload).toHaveBeenCalledTimes(1);+ expect(io.upload).toHaveBeenCalledWith(expect.any(File), 'target-host');+ expect(online.files[sha256].data).toBeUndefined();+ expect(online.files[sha256].attachment?.source).toBe('target-host-file');+ expect(input.files[sha256].data).toBeDefined();+ expect(await readOleFile(online.files[sha256], io)).toEqual(bytes);+ const portable = await prepareOleResource(online, 'json', undefined, io);+ expect(portable.files[sha256].attachment).toBeUndefined();+ expect(await readOleFile(portable.files[sha256])).toEqual(bytes);+ });++ it('upload failure never partially rewrites the source model', async () => {+ const input = resource();+ const original = JSON.stringify(input);+ const io = adapter();+ io.upload = vi.fn(async () => {+ throw new Error('upload failed');+ });+ await expect(prepareOleResource(input, 'unit', 'host', io)).rejects.toThrow('upload failed');+ expect(JSON.stringify(input)).toBe(original);+ await expect(prepareOleResource(input, 'unit', undefined, io)).rejects.toThrow('target Unit');+ });++ it('rejects corrupt, missing and oversized resources instead of returning partial files', async () => {+ const value = resource();+ value.files[sha256].data = Buffer.from(new Uint8Array(bytes.length)).toString('base64');+ await expect(readOleFile(value.files[sha256])).rejects.toThrow('integrity');+ value.files[sha256].size = 100 * 1024 * 1024;+ expect(() => parseOleResource(JSON.stringify(value))).toThrow('size limit');+ const missing = resource();+ missing.objects['ole-1'].fileId = 'constructor';+ expect(() => parseOleResource(JSON.stringify(missing))).toThrow('Missing OLE');+ });++ it('cancellation prevents a late attachment response from opening a preview', async () => {+ const io = adapter();+ const online = await prepareOleResource(resource(), 'unit', 'host', io);+ const controller = new AbortController();+ io.read = async () => {+ controller.abort();+ return bytes;+ };+ await expect(readOleFile(online.files[sha256], io, controller.signal)).rejects.toThrow('aborted');+ });+});++describe.each(['workbook', 'doc', 'slide'])('OLE snapshot transport: %s', (host) => {+ it('preserves SDK binary metadata and UTF-8 resources during attachment transfer', async () => {+ const opaque = new Uint8Array([0, 255, 128]);+ const model = { resources: [{ name: 'UNIVER_OLE_ATTACHMENT_PLUGIN', data: JSON.stringify(resource()) }] };+ const meta = new TextEncoder().encode(JSON.stringify(model));+ const input = { snapshot: { [host]: host === 'slide'+ ? { originalMeta: meta }+ : {+ ...model,+ originalMeta: opaque,+ resources: [{ ...model.resources[0], data: new TextEncoder().encode(model.resources[0].data) }],+ } }, sheetBlocks: [{ data: opaque }] };+ const online = await prepareOleSnapshot(input, 'unit', 'target-host', adapter());+ expect(online.sheetBlocks[0].data).toEqual(opaque);+ expect(online.sheetBlocks[0].data).not.toBe(opaque);+ const raw = online.snapshot[host];+ const converted = host === 'slide' ? JSON.parse(new TextDecoder().decode(raw.originalMeta)) : raw;+ const entry = converted.resources[0].data;+ const attached = parseOleResource(typeof entry === 'string' ? entry : new TextDecoder().decode(entry));+ expect(attached.files[sha256].data).toBeUndefined();+ expect(attached.files[sha256].attachment?.source).toBe('target-host-file');+ expect(input.snapshot[host].originalMeta).toEqual(host === 'slide' ? meta : opaque);+ });++ it('roundtrips JSON → Unit → JSON without changing the original snapshot', async () => {+ const onlineUnit = { unitId: 'child', type: 1 };+ const model = { drawings: { 'ole-1': { oleAttachmentId: 'ole-1', oleOnlineUnit: onlineUnit, oleFileName: '预算.pdf' } }, resources: [{ name: 'UNIVER_OLE_ATTACHMENT_PLUGIN', data: JSON.stringify(resource()) }] };+ const snapshot = { snapshot: { [host]: host === 'slide' ? { originalMeta: Buffer.from(JSON.stringify(model)).toString('base64') } : model } };+ const saved = JSON.stringify(snapshot);+ const io = adapter();+ const online = await prepareOleSnapshot(snapshot, 'unit', 'target-host', io);+ expect(io.upload).toHaveBeenCalledTimes(1);+ expect(JSON.stringify(snapshot)).toBe(saved);+ const portable = await prepareOleSnapshot(online, 'json', undefined, io);+ const raw = portable.snapshot[host];+ const data = host === 'slide' ? JSON.parse(Buffer.from((raw as { originalMeta: string }).originalMeta, 'base64').toString()) : raw;+ expect(data.drawings['ole-1'].oleOnlineUnit).toEqual(onlineUnit);+ expect(data.drawings['ole-1'].oleFileName).toBe('预算.pdf');+ expect(parseOleResource(data.resources[0].data).files[sha256].name).toBe('original.pdf');+ expect(await readOleFile(parseOleResource(data.resources[0].data).files[sha256])).toEqual(bytes);+ expect(Object.keys(parseOleResource(data.resources[0].data).objects)).toHaveLength(2);+ });+});diff --git a/packages/drawing/src/models/ole-model.ts b/packages/drawing/src/models/ole-model.tsnew file mode 100644index 0000000000..364526ccd1--- /dev/null+++ b/packages/drawing/src/models/ole-model.ts@@ -0,0 +1,269 @@+/**+ * 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 { IBaseAttachment, IDisposable } from '@univerjs/core';+import type { IImageData } from './image-model-interface';+import { UniverInstanceType } from '@univerjs/core';++export const OLE_RESOURCE_NAME = 'UNIVER_OLE_ATTACHMENT_PLUGIN';+export const OLE_MAX_RESOURCE_BYTES = 50 * 1024 * 1024;++export interface IOleDrawing extends IImageData {+ oleAttachmentId: string;+ /** Per-occurrence display and download name; original attachment metadata stays intact. */+ oleFileName?: string;+ oleOnlineUnit?: IOleOnlineUnit;+}++export interface IOleOnlineUnit {+ unitId: string;+ type: UniverInstanceType;+}++export function getOleOfficeType(mimeType: string): UniverInstanceType | undefined {+ switch (mimeType) {+ case 'application/vnd.ms-excel':+ case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':+ return UniverInstanceType.UNIVER_SHEET;+ case 'application/msword':+ case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':+ return UniverInstanceType.UNIVER_DOC;+ case 'application/vnd.ms-powerpoint':+ case 'application/vnd.openxmlformats-officedocument.presentationml.presentation':+ return UniverInstanceType.UNIVER_SLIDE;+ default:+ return undefined;+ }+}++export interface IOleFile {+ name: string;+ mimeType: string;+ size: number;+ sha256: string;+ data?: string;+ attachment?: IBaseAttachment;+}++export interface IOleRelationship {+ id: string;+ relationshipType: string;+ target: string;+ external: boolean;+}++export interface IOleObject {+ id: string;+ hostPart: string;+ fileName?: string;+ subUnitId: string;+ drawingId: string;+ initialGeometry?: object;+ shapeId: string;+ progId: string;+ relationshipId: string;+ external: boolean;+ status: 'ready' | 'opaque' | 'missing' | 'external-unavailable';+ rawFileId: string | null;+ fileId: string | null;+ xml: string;+ relationships: IOleRelationship[];+ parts: Record<string, string>;+ legacy?: {+ hostPart: string;+ xml: string;+ shapeTypes: string[];+ relationships: IOleRelationship[];+ };+}++export interface IOleResource {+ version: 1;+ files: Record<string, IOleFile>;+ objects: Record<string, IOleObject>;+}++/** The online adapter follows the application's existing attachment upload/read contract. */+export interface IOleAttachmentIo {+ upload: (file: File, targetUnitId: string) => Promise<IBaseAttachment>;+ read: (attachment: IBaseAttachment, signal?: AbortSignal) => Promise<Uint8Array>;+}++export interface IOlePreviewRequest {+ unitId: string;+ attachmentId: string;+ name: string;+ mimeType: string;+ bytes: Uint8Array;+ signal: AbortSignal;+}++export type OleConversionStage = 'reading' | 'uploading' | 'converting' | 'creating' | 'saving';++/** Existing Unit attachments are converted by reference. JSON attachments upload their bytes once. */+export type IOleOnlineConversionRequest = Omit<IOlePreviewRequest, 'bytes'> & {+ onProgress?: (stage: OleConversionStage) => void;+} & ({ fileId: string; bytes?: never } | { bytes: Uint8Array; fileId?: never });++export interface IOleConfig {+ /** Whether this exact host Unit is backed by the collaboration server. */+ isCollaborative?: (unitId: string) => boolean;+ /** Resolve the current application URL on each Open action; URLs are never persisted. */+ getLink?: (unitId: string, type: UniverInstanceType) => string;+ /** Explicitly create an independent online Unit and return its durable identity. */+ convertToOnline?: (request: IOleOnlineConversionRequest) => Promise<IOleOnlineUnit>;+ attachmentIo?: IOleAttachmentIo;+ /** Open a temporary read-only Office preview. The handler must not create a persisted child Unit. */+ previewOffice?: (request: IOlePreviewRequest) => Promise<void>;+ /** Convert on demand to UnitData, using JSON output without persisting a child Unit. */+ createOfficePreview?: (container: HTMLElement, view: { type: UniverInstanceType; data: object }) => Promise<IDisposable>;+ convertOffice?: (request: IOlePreviewRequest) => Promise<{ type: UniverInstanceType; data: object }>;+}++export function parseOleResource(json: string): IOleResource {+ if (new TextEncoder().encode(json).byteLength > OLE_MAX_RESOURCE_BYTES) {+ throw new Error('OLE resource exceeds size limit');+ }+ const value = JSON.parse(json) as IOleResource;+ if (value?.version !== 1 || !value.files || !value.objects || Array.isArray(value.files) || Array.isArray(value.objects)) {+ throw new Error('Invalid OLE resource');+ }+ let total = 0;+ for (const [id, file] of Object.entries(value.files)) {+ if (!/^[a-f0-9]{64}$/.test(id) || id !== file.sha256 || !Number.isSafeInteger(file.size) || file.size < 0 || typeof file.name !== 'string' || typeof file.mimeType !== 'string') {+ throw new Error('Invalid OLE file record');+ }+ total += file.size;+ if (total > OLE_MAX_RESOURCE_BYTES || (file.data != null && (typeof file.data !== 'string' || file.data.length > Math.ceil(file.size / 3) * 4))) {+ throw new Error('OLE files exceed size limit');+ }+ if (file.data == null && (!file.attachment?.source || file.attachment.sourceType !== 'UUID')) {+ throw new Error('Missing OLE attachment source');+ }+ }+ for (const [id, object] of Object.entries(value.objects)) {+ if (object.id !== id || typeof object.drawingId !== 'string' || typeof object.subUnitId !== 'string' || (object.fileName != null && typeof object.fileName !== 'string')) {+ throw new Error('Invalid OLE object identity');+ }+ for (const fileId of [object.fileId, object.rawFileId, ...Object.values(object.parts)]) {+ if (fileId != null && !Object.prototype.hasOwnProperty.call(value.files, fileId)) {+ throw new Error('Missing OLE file record');+ }+ }+ }+ return value;+}++export async function readOleFile(file: IOleFile, io?: IOleAttachmentIo, signal?: AbortSignal): Promise<Uint8Array> {+ if (signal?.aborted) {+ throw new Error('OLE request aborted');+ }+ let bytes: Uint8Array;+ if (file.data != null) {+ const binary = atob(file.data);+ bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));+ } else if (file.attachment && io) {+ bytes = await io.read(file.attachment, signal);+ } else {+ throw new Error('OLE attachment reader is unavailable');+ }+ if (signal?.aborted) {+ throw new Error('OLE request aborted');+ }+ if (bytes.byteLength !== file.size || bytes.byteLength > OLE_MAX_RESOURCE_BYTES) {+ throw new Error('OLE attachment size mismatch');+ }+ const hash = globalThis.crypto?.subtle+ ? new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', bytes as Uint8Array<ArrayBuffer>))+ : (await import('@noble/hashes/sha256')).sha256(bytes);+ if (signal?.aborted) {+ throw new Error('OLE request aborted');+ }+ const digest = Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('');+ if (digest !== file.sha256) {+ throw new Error('OLE attachment integrity mismatch');+ }+ return bytes;+}++/** Atomic model conversion: failures leave the caller's resource unchanged. */+export async function prepareOleResource(resource: IOleResource, mode: 'json' | 'unit', targetUnitId?: string, io?: IOleAttachmentIo): Promise<IOleResource> {+ const candidate = parseOleResource(JSON.stringify(resource));+ if (mode === 'unit' && (!targetUnitId || !io)) {+ throw new Error('OLE online import requires a target Unit and attachment IO');+ }+ // Upload sequentially to bound memory and follow the existing endpoint's rate limits.+ for (const file of Object.values(candidate.files)) {+ const bytes = await readOleFile(file, io);+ if (mode === 'unit') {+ const attachment = await io!.upload(new File([bytes as Uint8Array<ArrayBuffer>], file.name, { type: file.mimeType }), targetUnitId!);+ if (!attachment.source || attachment.sourceType !== 'UUID' || attachment.size !== file.size) {+ throw new Error('Invalid persisted OLE attachment response');+ }+ file.attachment = attachment;+ delete file.data;+ } else {+ // Avoid spreading a large binary into a function call's argument list.+ let binary = '';+ for (let offset = 0; offset < bytes.length; offset += 8192) {+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));+ }+ file.data = btoa(binary);+ delete file.attachment;+ }+ }+ return parseOleResource(JSON.stringify(candidate));+}++/** Prepare a UnitData model or a native exchange JSON envelope without changing the caller's model. */+export async function prepareOleSnapshot<T extends object>(snapshot: T, mode: 'json' | 'unit', targetUnitId?: string, io?: IOleAttachmentIo): Promise<T> {+ interface IResourceHost { resources?: Array<{ name: string; data: string | Uint8Array }>; originalMeta?: string | Uint8Array }+ interface IEnvelope extends IResourceHost { snapshot?: IEnvelope; workbook?: IResourceHost; doc?: IResourceHost; slide?: IResourceHost }+ const clone = (value: unknown): unknown => {+ if (value instanceof Uint8Array) return Uint8Array.from(value);+ if (Array.isArray(value)) return value.map(clone);+ if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clone(item)]));+ return value;+ };+ const candidate = clone(snapshot) as T & IEnvelope;+ const envelope = candidate.snapshot ?? candidate;+ const host = envelope.workbook ?? envelope.doc ?? envelope.slide ?? envelope;+ let model = host;+ let encoded = false;+ if (envelope.slide && host.originalMeta != null) {+ const bytes = typeof host.originalMeta === 'string'+ ? Uint8Array.from(atob(host.originalMeta), (character) => character.charCodeAt(0))+ : host.originalMeta;+ model = JSON.parse(new TextDecoder().decode(bytes)) as IResourceHost;+ encoded = true;+ }+ for (const entry of model.resources ?? []) {+ if (entry.name === OLE_RESOURCE_NAME) {+ const text = typeof entry.data === 'string' ? entry.data : new TextDecoder().decode(entry.data);+ const prepared = JSON.stringify(await prepareOleResource(parseOleResource(text), mode, targetUnitId, io));+ entry.data = typeof entry.data === 'string' ? prepared : new TextEncoder().encode(prepared);+ }+ }+ if (encoded) {+ const bytes = new TextEncoder().encode(JSON.stringify(model));+ let binary = '';+ for (let offset = 0; offset < bytes.length; offset += 8192) {+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192));+ }+ host.originalMeta = typeof host.originalMeta === 'string' ? btoa(binary) : bytes;+ }+ return candidate;+}diff --git a/packages/drawing/src/plugin.ts b/packages/drawing/src/plugin.tsindex 586541dfed..37fc0da76d 100644--- a/packages/drawing/src/plugin.ts+++ b/packages/drawing/src/plugin.ts@@ -16,7 +16,17 @@import type { Dependency } from '@univerjs/core';import type { IUniverDrawingConfig } from './config/config';-import { ICommandService, IConfigService, IImageIoService, Inject, Injector, IURLImageService, merge, mergeOverrideWithDependencies, Plugin } from '@univerjs/core';+import {+ ICommandService,+ IConfigService,+ IImageIoService,+ Inject,+ Injector,+ IURLImageService,+ merge,+ mergeOverrideWithDependencies,+ Plugin,+} from '@univerjs/core';import pkg from '../package.json';import { setDrawingImageAllowSize } from './basics/config';import { SetDrawingSelectedOperation } from './commands/operations/set-drawing-selected.operation';@@ -24,6 +34,7 @@ import { defaultPluginConfig, DRAWING_PLUGIN_CONFIG_KEY } from './config/config'import { DrawingManagerService } from './services/drawing-manager-impl.service';import { IDrawingManagerService } from './services/drawing-manager.service';import { ImageIoService } from './services/image-io-impl.service';+import { OleService } from './services/ole.service';import { URLImageService } from './services/url-image.service';export class UniverDrawingPlugin extends Plugin {@@ -55,6 +66,7 @@ export class UniverDrawingPlugin extends Plugin {override onStarting(): void {this._initCommands();this._initDependencies();+ this._injector.get(OleService);}private _initDependencies(): void {@@ -62,6 +74,7 @@ export class UniverDrawingPlugin extends Plugin {[IImageIoService, { useClass: ImageIoService }],[IURLImageService, { useClass: URLImageService }],[IDrawingManagerService, { useClass: DrawingManagerService }],+ [OleService],];const dependency = mergeOverrideWithDependencies(dependencies, this._config?.override);diff --git a/packages/drawing/src/services/__tests__/ole.service.spec.ts b/packages/drawing/src/services/__tests__/ole.service.spec.tsnew file mode 100644index 0000000000..f2df8a570b--- /dev/null+++ b/packages/drawing/src/services/__tests__/ole.service.spec.ts@@ -0,0 +1,49 @@+/**+ * 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 {+ DesktopLogService,+ ILogService,+ Injector,+ IResourceManagerService,+ ResourceManagerService,+ UniverInstanceType,+} from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import { OLE_RESOURCE_NAME } from '../../models/ole-model';+import { OleService } from '../ole.service';++describe('headless OLE resource lifecycle', () => {+ it.each([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC, UniverInstanceType.UNIVER_SLIDE])('preserves resources across save and reload for host %s without UI', (type) => {+ const injector = new Injector([+ [ILogService, { useClass: DesktopLogService }],+ [IResourceManagerService, { useClass: ResourceManagerService }],+ [OleService],+ ]);+ const service = injector.get(OleService);+ const resources = injector.get(IResourceManagerService);+ const json = JSON.stringify({ version: 1, files: {}, objects: {} });+ resources.loadResources('first-host', [{ name: OLE_RESOURCE_NAME, data: json }]);+ const saved = resources.getResources('first-host', type);+ expect(saved).toEqual([{ name: OLE_RESOURCE_NAME, data: json }]);+ resources.loadResources('reopened-host', saved);+ expect(service.getResource('reopened-host')).toEqual({ version: 1, files: {}, objects: {} });+ resources.unloadResources('first-host', type);+ expect(service.getResource('first-host')).toBeUndefined();+ expect(service.getResource('reopened-host')).toBeDefined();+ injector.dispose();+ });+});diff --git a/packages/drawing/src/services/ole.service.ts b/packages/drawing/src/services/ole.service.tsnew file mode 100644index 0000000000..73049804c7--- /dev/null+++ b/packages/drawing/src/services/ole.service.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 { IOleResource } from '../models/ole-model';+import { Disposable, IResourceManagerService, UniverInstanceType } from '@univerjs/core';+import { OLE_RESOURCE_NAME, parseOleResource } from '../models/ole-model';++/** Registered by the model plugin so headless save/export preserves original files too. */+export class OleService extends Disposable {+ private readonly _resources = new Map<string, IOleResource>();++ constructor(@IResourceManagerService resourceManager: IResourceManagerService) {+ super();+ this.disposeWithMe(resourceManager.registerPluginResource<IOleResource>({+ pluginName: OLE_RESOURCE_NAME,+ businesses: [UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_DOC, UniverInstanceType.UNIVER_SLIDE],+ onLoad: (unitId, resource) => this._resources.set(unitId, resource),+ onUnLoad: (unitId) => this._resources.delete(unitId),+ toJson: (unitId) => JSON.stringify(this._resources.get(unitId) ?? { version: 1, files: {}, objects: {} }),+ parseJson: parseOleResource,+ }));+ }++ getResource(unitId: string): IOleResource | undefined {+ return this._resources.get(unitId);+ }++ override dispose(): void {+ this._resources.clear();+ super.dispose();+ }+}diff --git a/packages/drawing/src/utils/rotate-enabled.ts b/packages/drawing/src/utils/rotate-enabled.tsindex d525942360..85924acad2 100644--- a/packages/drawing/src/utils/rotate-enabled.ts+++ b/packages/drawing/src/utils/rotate-enabled.ts@@ -38,6 +38,9 @@ export function resolveDrawingRotateEnabled(options: IDrawingRotateEnabledResolverOptions = {},visiting = new Set<string>()): boolean {+ if (drawing.drawingType === DrawingTypeEnum.DRAWING_OLE) {+ return false;+ }const drawingKey = getDrawingKey(drawing);if (visiting.has(drawingKey)) {return true;diff --git a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.tsindex 0ebb29c898..4062accaa5 100644--- a/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts+++ b/packages/sheets-drawing-ui/src/commands/commands/__tests__/drawing-commands.spec.ts@@ -15,11 +15,21 @@*/import type { ISheetDrawing } from '@univerjs/sheets-drawing';-import { Direction, DrawingTypeEnum, ImageSourceType } from '@univerjs/core';+import { Direction, DrawingTypeEnum, ImageSourceType, IUndoRedoService } from '@univerjs/core';import { getDrawingShapeKeyByDrawingSearch, IDrawingManagerService } from '@univerjs/drawing';import { insertGroupObject } from '@univerjs/drawing-ui';-import { DrawingGroupObject, Engine, Image, IRenderManagerService, MAIN_VIEW_PORT_KEY, Rect, Scene, Vector2, Viewport } from '@univerjs/engine-render';-import { InsertSheetDrawingCommand, ISheetDrawingService } from '@univerjs/sheets-drawing';+import {+ DrawingGroupObject,+ Engine,+ Image,+ IRenderManagerService,+ MAIN_VIEW_PORT_KEY,+ Rect,+ Scene,+ Vector2,+ Viewport,+} from '@univerjs/engine-render';+import { InsertSheetDrawingCommand, ISheetDrawingService, SetSheetDrawingCommand } from '@univerjs/sheets-drawing';import { afterEach, describe, expect, it, vi } from 'vitest';import { createSheetsDrawingUiTestBed } from '../../../__tests__/create-sheets-drawing-ui-test-bed';import { FlipSheetDrawingCommand } from '../flip-drawings.command';@@ -152,11 +162,29 @@ describe('sheet drawing UI commands', () => {// each test disposes its own univer instance});- it('moves focused drawings by one pixel in the selected direction', async () => {+ it('persists an online OLE link with symmetric drawing mutations', async () => {+ const testBed = createSheetsDrawingUiTestBed();+ const service = testBed.get(ISheetDrawingService);+ const drawing = { ...createSheetDrawing('ole-1', 10, 20), drawingType: DrawingTypeEnum.DRAWING_OLE, oleAttachmentId: 'retained' };+ await insertDrawings(testBed, [drawing]);+ const online = { unitId: 'child', type: 1 };+ expect(await testBed.commandService.executeCommand(SetSheetDrawingCommand.id, { unitId: testBed.unitId, drawings: [{ ...drawing, oleOnlineUnit: online, oleFileName: '预算.xlsx' }] })).toBe(true);+ expect(JSON.parse(JSON.stringify(service.getDrawingByParam(drawing)))).toMatchObject({ oleAttachmentId: 'retained', oleOnlineUnit: online, oleFileName: '预算.xlsx' });+ const history = testBed.get(IUndoRedoService).pitchTopUndoElement()!;+ for (const mutation of history.undoMutations) testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);+ expect(service.getDrawingByParam(drawing)).not.toHaveProperty('oleOnlineUnit');+ expect(service.getDrawingByParam(drawing)).not.toHaveProperty('oleFileName');+ for (const mutation of history.redoMutations) testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);+ expect(service.getDrawingByParam(drawing)).toMatchObject({ oleOnlineUnit: online, oleFileName: '预算.xlsx' });+ testBed.univer.dispose();+ });++ it.each([DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_OLE])('moves drawing type %s and replays geometry through undo and redo', async (drawingType) => {const testBed = createSheetsDrawingUiTestBed();const sheetDrawingService = testBed.get(ISheetDrawingService);testBed.commandService.registerCommand(MoveDrawingsCommand);- await insertDrawings(testBed, [createSheetDrawing('drawing-1', 10, 20)]);+ const drawing = { ...createSheetDrawing('drawing-1', 10, 20), drawingType, oleAttachmentId: 'retained-attachment' };+ await insertDrawings(testBed, [drawing]);sheetDrawingService.focusDrawing([{unitId: testBed.unitId,subUnitId: testBed.subUnitId,@@ -174,6 +202,17 @@ describe('sheet drawing UI commands', () => {top: 20,});+ const param = { unitId: testBed.unitId, subUnitId: testBed.subUnitId, drawingId: 'drawing-1' };+ const history = testBed.get(IUndoRedoService).pitchTopUndoElement()!;+ for (const mutation of history.undoMutations) {+ testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);+ }+ expect(sheetDrawingService.getDrawingByParam(param)).toMatchObject({ drawingType, oleAttachmentId: 'retained-attachment', transform: { left: 10, top: 20 } });+ for (const mutation of history.redoMutations) {+ testBed.commandService.syncExecuteCommand(mutation.id, mutation.params);+ }+ expect(sheetDrawingService.getDrawingByParam(param)).toMatchObject({ drawingType, oleAttachmentId: 'retained-attachment', transform: { left: 11, top: 20 } });+testBed.univer.dispose();});diff --git a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.ts b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.tsindex 75224f2e82..55c64fe022 100644--- a/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.ts+++ b/packages/sheets-drawing-ui/src/controllers/__tests__/sheet-drawing-printing.controller.spec.ts@@ -23,7 +23,7 @@ vi.mock('../../views/PrintingFloatDom', () => ({mountPrintingFloatDom: vi.fn(() => vi.fn()),}));-function createController(options?: { hasDrawingData?: boolean }) {+function createController(options?: { hasDrawingData?: boolean; drawingType?: DrawingTypeEnum }) {const interceptors = new Map<string, any>();const points = {PRINTING_COMPONENT_COLLECT: 'PRINTING_COMPONENT_COLLECT',@@ -39,7 +39,7 @@ function createController(options?: { hasDrawingData?: boolean }) {unitId: 'unit-1',subUnitId: 'sheet-1',drawingId: 'image-1',- drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ drawingType: options?.drawingType ?? DrawingTypeEnum.DRAWING_IMAGE,transform: { left: 20, top: 30, width: 120, height: 60 },},'chart-1': {@@ -130,8 +130,8 @@ function createController(options?: { hasDrawingData?: boolean }) {}describe('SheetDrawingPrintingController', () => {- it('renders printable images while excluding charts and floating DOM drawings', () => {- const { controller, interceptors, points } = createController();+ it.each([DrawingTypeEnum.DRAWING_IMAGE, DrawingTypeEnum.DRAWING_OLE])('prints images and OLE without editor interaction (type: %s)', (drawingType) => {+ const { controller, interceptors, points } = createController({ drawingType });const scene = {};const resourceCollector = { add: vi.fn() };const next = vi.fn(() => 'next-result');@@ -144,8 +144,8 @@ describe('SheetDrawingPrintingController', () => {}, next);expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledTimes(2);- expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'image-1' }), scene, { allowInactiveSheet: true });- expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'grouped-image' }), scene, { allowInactiveSheet: true });+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'image-1' }), scene, { allowInactiveSheet: true, interactive: false });+ expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'grouped-image' }), scene, { allowInactiveSheet: true, interactive: false });expect(resourceCollector.add).toHaveBeenCalledTimes(2);expect(result).toBe('next-result');diff --git a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.tsindex 998750a682..8683f3fdd6 100644--- a/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts+++ b/packages/sheets-drawing-ui/src/controllers/sheet-drawing-printing.controller.ts@@ -59,7 +59,7 @@ export class SheetDrawingPrintingController extends Disposable {drawing.drawingType !== DrawingTypeEnum.DRAWING_DOM &&drawing.drawingType !== DrawingTypeEnum.DRAWING_BLOCK) {- const resource = this._drawingRenderService.renderDrawing(drawing, scene, { allowInactiveSheet: true });+ const resource = this._drawingRenderService.renderDrawing(drawing, scene, { allowInactiveSheet: true, interactive: false });if (resource) {resourceCollector.add(Promise.resolve(resource));}diff --git a/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts b/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.tsindex 049593f98c..e30c0d83eb 100644--- a/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts+++ b/packages/sheets-drawing-ui/src/menu/__tests__/drawing-popup-menu.controller.spec.ts@@ -21,11 +21,13 @@ import {IContextService,IImageIoService,Injector,+ IPermissionService,IUniverInstanceService,LocaleService,toDisposable,} from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';+import { OleUIService } from '@univerjs/drawing-ui';import { IRenderManagerService } from '@univerjs/engine-render';import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';import { IDialogService, IMenuManagerService, IMessageService, MenuItemType } from '@univerjs/ui';@@ -35,6 +37,8 @@ import { DrawingPopupMenuController } from '../drawing-popup-menu.controller';function createControllerHarness(initialDrawingType: DrawingTypeEnum) {const injector = new Injector();+ injector.add([IPermissionService, { useValue: { getPermissionPoint: () => undefined } as never }]);+ injector.add([OleUIService, { useValue: { registerHost: () => toDisposable(() => undefined) } as never }]);const createControl$ = new Subject<void>();const clearControl$ = new Subject<void>();const changing$ = new Subject<void>();diff --git a/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts b/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.tsindex dc4309187b..675a754a00 100644--- a/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts+++ b/packages/sheets-drawing-ui/src/menu/drawing-popup-menu.controller.ts@@ -16,9 +16,9 @@import type { IDisposable, Nullable, Workbook } from '@univerjs/core';import type { ImageIoService } from '@univerjs/drawing';+import type { IOlePreviewContext } from '@univerjs/drawing-ui';import type { BaseObject, Scene } from '@univerjs/engine-render';import type { ISheetFloatDom } from '@univerjs/sheets-drawing';-import type { LocaleKey } from '../locale/types';import {DrawingTypeEnum,FOCUSING_COMMON_DRAWINGS,@@ -26,6 +26,7 @@ import {IContextService,IImageIoService,Inject,+ IPermissionService,IUniverInstanceService,LocaleService,RxDisposable,@@ -35,21 +36,27 @@ import { MessageType } from '@univerjs/design';import { IDrawingManagerService, SetDrawingSelectedOperation } from '@univerjs/drawing';import {COMPONENT_IMAGE_POPUP_MENU,+ createOlePreviewViewer,ImageCropperObject,ImageResetSizeOperation,+ OleUIService,OpenImageCropOperation,+ registerOlePreviewRenderer,} from '@univerjs/drawing-ui';import { IRenderManagerService } from '@univerjs/engine-render';-import { RemoveSheetDrawingCommand } from '@univerjs/sheets-drawing';-import { SheetCanvasPopManagerService } from '@univerjs/sheets-ui';+import { UniverSheetsPlugin, WorkbookEditablePermission, WorkbookRenameSheetPermission } from '@univerjs/sheets';+import { RemoveSheetDrawingCommand, SetSheetDrawingCommand, UniverSheetsDrawingPlugin } from '@univerjs/sheets-drawing';+import { SheetCanvasPopManagerService, UniverSheetsUIPlugin } from '@univerjs/sheets-ui';import {FloatingObjectToolbarPosition,IMenuManagerService,IMessageService,MenuItemType,} from '@univerjs/ui';+import type { LocaleKey } from '../locale/types';import { FlipSheetDrawingCommand } from '../commands/commands/flip-drawings.command';import { EditSheetDrawingOperation } from '../commands/operations/edit-sheet-drawing.operation';+import { UniverSheetsDrawingUIPlugin } from '../plugin';export class DrawingPopupMenuController extends RxDisposable {private _initImagePopupMenu = new Set<string>();@@ -64,10 +71,20 @@ export class DrawingPopupMenuController extends RxDisposable {@IMenuManagerService private readonly _menuManagerService: IMenuManagerService,@IContextService protected readonly _contextService: IContextService,@IImageIoService private readonly _ioService: ImageIoService,- @ICommandService protected readonly _commandService: ICommandService+ @ICommandService protected readonly _commandService: ICommandService,+ @Inject(OleUIService) private readonly _oleUI: OleUIService,+ @IPermissionService private readonly _permissionService: IPermissionService) {super();+ this.disposeWithMe(this._oleUI.registerHost(UniverInstanceType.UNIVER_SHEET, {+ isEditable: (drawing) => this._drawingManagerService.getDrawingEditable() && this._permissionService.getPermissionPoint(new WorkbookEditablePermission(drawing.unitId).id)?.value !== false,+ attach: (object, componentKey, extraProps, _drawing, direction = 'top-center') => this._canvasPopManagerService.attachPopupToObject(object, { componentKey, extraProps, direction, portal: true, offset: direction === 'top-center' ? [0, 8] : [0, 0] }),+ rename: (drawing, name) => this._commandService.executeCommand(SetSheetDrawingCommand.id, { unitId: drawing.unitId, drawings: [{ ...drawing, oleFileName: name }] }),+ saveOnlineUnit: (drawing, online) => this._commandService.executeCommand(SetSheetDrawingCommand.id, { unitId: drawing.unitId, drawings: [{ ...drawing, oleOnlineUnit: online }] }),+ remove: (drawing) => this._commandService.executeCommand(RemoveSheetDrawingCommand.id, { unitId: drawing.unitId, drawings: [drawing] }),+ }));+this._init();}@@ -184,7 +201,7 @@ export class DrawingPopupMenuController extends RxDisposable {}const drawingParam = this._drawingManagerService.getDrawingOKey(object.oKey);- if (!drawingParam || drawingParam.drawingType === DrawingTypeEnum.DRAWING_SHAPE) {+ if (!drawingParam || drawingParam.drawingType === DrawingTypeEnum.DRAWING_SHAPE || drawingParam.drawingType === DrawingTypeEnum.DRAWING_OLE) {return;}@@ -276,3 +293,21 @@ export class DrawingPopupMenuController extends RxDisposable {});}}++function createSheetOlePreview(context: IOlePreviewContext): IDisposable {+ return createOlePreviewViewer({ ...context, setReadonly: (permissions, unitId) => {+ for (const point of [new WorkbookEditablePermission(unitId), new WorkbookRenameSheetPermission(unitId)]) {+ if (!permissions.getPermissionPoint(point.id)) {+ permissions.addPermissionPoint(point);+ }+ permissions.updatePermissionPoint(point.id, false);+ }+ }, register: (viewer) => {+ viewer.registerPlugin(UniverSheetsPlugin);+ viewer.registerPlugin(UniverSheetsUIPlugin, { disableEdit: true });+ viewer.registerPlugin(UniverSheetsDrawingPlugin);+ viewer.registerPlugin(UniverSheetsDrawingUIPlugin);+ } });+}++registerOlePreviewRenderer(UniverInstanceType.UNIVER_SHEET, createSheetOlePreview);diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c9200be2a1..30cd97dcbd 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -246,7 +246,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))common/debugger:dependencies:@@ -358,7 +358,7 @@ importers:version: 7.2.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))devDependencies:'@univerjs/icons':specifier: 1.47.0@@ -562,7 +562,7 @@ importers:version: 8.3.0(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/action-recorder:dependencies:@@ -605,7 +605,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/core:dependencies:@@ -657,7 +657,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/data-validation:dependencies:@@ -682,7 +682,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/design:dependencies:@@ -752,7 +752,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs:dependencies:@@ -780,7 +780,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-drawing:dependencies:@@ -805,7 +805,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-drawing-ui:dependencies:@@ -836,6 +836,9 @@ importers:'@univerjs/icons':specifier: 1.47.0+ '@univerjs/protocol':+ specifier: workspace:*+ version: link:../protocol'@univerjs/ui':specifier: workspace:*version: link:../ui@@ -846,9 +849,6 @@ importers:'@univerjs-infra/shared':specifier: workspace:*version: link:../../common/shared- '@univerjs/protocol':- specifier: workspace:*- version: link:../protocolpostcss:specifier: ^8.5.32version: 8.5.32@@ -866,7 +866,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-find-replace:dependencies:@@ -903,7 +903,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-hyper-link:dependencies:@@ -919,7 +919,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-hyper-link-ui:dependencies:@@ -971,7 +971,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-thread-comment:dependencies:@@ -996,7 +996,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-thread-comment-ui:dependencies:@@ -1054,7 +1054,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-toc:dependencies:@@ -1079,7 +1079,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-toc-ui:dependencies:@@ -1131,7 +1131,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/docs-ui:dependencies:@@ -1171,7 +1171,7 @@ importers:version: 2.5.8jsdom:specifier: ^29.1.1- version: 29.1.1+ version: 29.1.1(@noble/[email protected])postcss:specifier: ^8.5.32version: 8.5.32@@ -1189,10 +1189,13 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/drawing:dependencies:+ '@noble/hashes':+ specifier: 1.8.0+ version: 1.8.0'@univerjs/core':specifier: workspace:*version: link:../core@@ -1208,7 +1211,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/drawing-ui:dependencies:@@ -1251,7 +1254,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/engine-formula:dependencies:@@ -1279,7 +1282,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/engine-render:dependencies:@@ -1316,7 +1319,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/find-replace:dependencies:@@ -1356,7 +1359,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/network:dependencies:@@ -1375,7 +1378,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/protocol:dependencies:@@ -1394,7 +1397,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/rpc:dependencies:@@ -1413,7 +1416,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/rpc-node:dependencies:@@ -1435,7 +1438,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets:dependencies:@@ -1469,7 +1472,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-conditional-formatting:dependencies:@@ -1503,7 +1506,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-conditional-formatting-ui:dependencies:@@ -1561,7 +1564,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-crosshair-highlight:dependencies:@@ -1607,7 +1610,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-data-validation:dependencies:@@ -1641,7 +1644,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-data-validation-ui:dependencies:@@ -1708,7 +1711,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-drawing:dependencies:@@ -1733,7 +1736,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-drawing-ui:dependencies:@@ -1794,7 +1797,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-filter:dependencies:@@ -1825,7 +1828,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-filter-ui:dependencies:@@ -1877,7 +1880,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-find-replace:dependencies:@@ -1908,7 +1911,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-formula:dependencies:@@ -1942,7 +1945,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-formula-ui:dependencies:@@ -2003,7 +2006,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-hyper-link:dependencies:@@ -2031,7 +2034,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-hyper-link-ui:dependencies:@@ -2095,7 +2098,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-note:dependencies:@@ -2126,7 +2129,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-note-ui:dependencies:@@ -2175,7 +2178,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-numfmt:dependencies:@@ -2200,7 +2203,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-numfmt-ui:dependencies:@@ -2252,7 +2255,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-sort:dependencies:@@ -2274,7 +2277,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-sort-ui:dependencies:@@ -2326,7 +2329,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-table:dependencies:@@ -2357,7 +2360,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-table-ui:dependencies:@@ -2418,7 +2421,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-thread-comment:dependencies:@@ -2446,7 +2449,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-thread-comment-ui:dependencies:@@ -2504,7 +2507,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/sheets-ui:dependencies:@@ -2565,7 +2568,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/slides:dependencies:@@ -2587,7 +2590,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/slides-ui:dependencies:@@ -2639,7 +2642,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/telemetry:dependencies:@@ -2655,7 +2658,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/themes:devDependencies:@@ -2680,7 +2683,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/thread-comment-ui:dependencies:@@ -2726,7 +2729,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/ui:dependencies:@@ -2781,7 +2784,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/ui-adapter-vue3:dependencies:@@ -2800,7 +2803,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vue:specifier: ^3.5.42version: 3.5.42([email protected])@@ -2822,7 +2825,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages/watermark:dependencies:@@ -2844,7 +2847,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))presets:dependencies:@@ -3455,7 +3458,7 @@ importers:version: 6.0.3vitest:specifier: ^5.0.5- version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))packages:@@ -4868,6 +4871,10 @@ packages:'@neoconfetti/[email protected]':resolution: {integrity: sha512-klcSooChXXOzIm+SE5IISIAn3bYzYfPjbX7D7HoqZL84oAfgREeSg5vSIaSFH+DaGzzvImTyWe1OyrJ67vik4A==}+ '@noble/[email protected]':+ resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}+ engines: {node: ^14.21.3 || >=16}+'@nodelib/[email protected]':resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}engines: {node: '>= 8'}@@ -12626,7 +12633,9 @@ snapshots:'@eslint/core': 1.2.1levn: 0.4.1- '@exodus/[email protected]': {}+ '@exodus/[email protected](@noble/[email protected])':+ optionalDependencies:+ '@noble/hashes': 1.8.0'@flatten-js/[email protected]': {}@@ -12787,6 +12796,8 @@ snapshots:'@neoconfetti/[email protected]': {}+ '@noble/[email protected]': {}+'@nodelib/[email protected]':dependencies:'@nodelib/fs.stat': 2.0.5@@ -13947,7 +13958,7 @@ snapshots:picocolors: 1.1.1redent: 3.0.0optionalDependencies:- vitest: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@testing-library/[email protected](@testing-library/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':dependencies:@@ -14314,7 +14325,7 @@ snapshots:magicast: 0.5.5obug: 3.0.0tinyrainbow: 3.2.0- vitest: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@vitest/[email protected](@typescript-eslint/[email protected](@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])':dependencies:@@ -14324,7 +14335,7 @@ snapshots:optionalDependencies:'@typescript-eslint/eslint-plugin': 8.65.0(@typescript-eslint/[email protected]([email protected]([email protected])([email protected]))([email protected])([email protected]))([email protected]([email protected])([email protected]))([email protected])([email protected])typescript: 6.0.3- vitest: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ vitest: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))transitivePeerDependencies:- supports-color@@ -15207,10 +15218,10 @@ snapshots:+ [email protected](@noble/[email protected]):dependencies:whatwg-mimetype: 5.0.0- whatwg-url: 16.0.1+ whatwg-url: 16.0.1(@noble/[email protected])transitivePeerDependencies:- '@noble/hashes'@@ -16357,9 +16368,9 @@ snapshots:+ [email protected](@noble/[email protected]):dependencies:- '@exodus/bytes': 1.15.1+ '@exodus/bytes': 1.15.1(@noble/[email protected])transitivePeerDependencies:- '@noble/hashes'@@ -16709,17 +16720,17 @@ snapshots:+ [email protected](@noble/[email protected]):dependencies:'@asamuzakjp/css-color': 5.1.11'@asamuzakjp/dom-selector': 7.1.1'@bramus/specificity': 2.4.2'@csstools/css-syntax-patches-for-csstree': 1.1.6([email protected])- '@exodus/bytes': 1.15.1+ '@exodus/bytes': 1.15.1(@noble/[email protected])css-tree: 3.2.1- data-urls: 7.0.0+ data-urls: 7.0.0(@noble/[email protected])decimal.js: 10.6.0- html-encoding-sniffer: 6.0.0+ html-encoding-sniffer: 6.0.0(@noble/[email protected])is-potential-custom-element-name: 1.0.1lru-cache: 11.5.2parse5: 8.0.1@@ -16730,7 +16741,7 @@ snapshots:w3c-xmlserializer: 5.0.0webidl-conversions: 8.0.1whatwg-mimetype: 5.0.0- whatwg-url: 16.0.1+ whatwg-url: 16.0.1(@noble/[email protected])xml-name-validator: 5.0.0transitivePeerDependencies:- '@noble/hashes'@@ -19282,7 +19293,7 @@ snapshots:tsx: 4.23.13yaml: 2.9.0- [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@types/chai': 5.2.3'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -19302,11 +19313,11 @@ snapshots:'@types/node': 26.1.2'@vitest/coverage-istanbul': 5.0.5([email protected])happy-dom: 20.14.5- jsdom: 29.1.1+ jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw- [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@types/chai': 5.2.3'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -19326,11 +19337,11 @@ snapshots:'@types/node': 26.2.0'@vitest/coverage-istanbul': 5.0.5([email protected])happy-dom: 20.14.5- jsdom: 29.1.1+ jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw- [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected](@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@noble/[email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@types/chai': 5.2.3'@vitest/mocker': 5.0.5([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -19350,7 +19361,7 @@ snapshots:'@types/node': 26.5.1'@vitest/coverage-istanbul': 5.0.5([email protected])happy-dom: 20.14.5- jsdom: 29.1.1+ jsdom: 29.1.1(@noble/[email protected])transitivePeerDependencies:- msw@@ -19452,9 +19463,9 @@ snapshots:+ [email protected](@noble/[email protected]):dependencies:- '@exodus/bytes': 1.15.1+ '@exodus/bytes': 1.15.1(@noble/[email protected])tr46: 6.0.0webidl-conversions: 8.0.1transitivePeerDependencies: