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
fix(sheets): fix printing issues (#7248)
wpxp123456656de76ee422
diff --git a/packages/core/src/types/const/const.ts b/packages/core/src/types/const/const.tsindex 065e733d81..120056a5fb 100644--- a/packages/core/src/types/const/const.ts+++ b/packages/core/src/types/const/const.ts@@ -257,6 +257,4 @@ export const NAMED_STYLE_SPACE_MAP: Record<NamedStyleType, Nullable<IParagraphSt[NamedStyleType.NAMED_STYLE_TYPE_UNSPECIFIED]: null,};-export const PRINT_CHART_COMPONENT_KEY = 'univer-sheets-chart-print-chart';-export const DOC_DRAWING_PRINTING_COMPONENT_KEY = 'univer-docs-drawing-printing';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 2e9a6422ff..98ed274ce0 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@@ -311,6 +311,15 @@ describe('DrawingRenderService', () => {expect(await inactiveSheetCase.service.renderImages(imageParam(), inactiveSheetCase.scene as unknown as Scene)).toBeUndefined();expect(inactiveSheetCase.scene.getObjectKeys).toEqual([]);+ const inactivePrintingSheetCase = createHarness();+ inactivePrintingSheetCase.univerInstanceService.unitType = UniverInstanceType.UNIVER_SHEET;+ inactivePrintingSheetCase.univerInstanceService.activeSheetId = 'sheet-2';+ expect(await inactivePrintingSheetCase.service.renderImages(+ imageParam(),+ inactivePrintingSheetCase.scene as unknown as Scene,+ { allowInactiveSheet: true }+ )).toHaveLength(1);+const noTransformCase = createHarness();expect(await noTransformCase.service.renderImages(imageParam({ transform: null }), noTransformCase.scene as unknown as Scene)).toBeUndefined();expect(noTransformCase.scene.getObjectKeys).toEqual([]);diff --git a/packages/drawing-ui/src/services/drawing-render.service.ts b/packages/drawing-ui/src/services/drawing-render.service.tsindex a35b5a1929..16f1e42b17 100644--- a/packages/drawing-ui/src/services/drawing-render.service.ts+++ b/packages/drawing-ui/src/services/drawing-render.service.ts@@ -84,7 +84,7 @@ export class DrawingRenderService {) { }// eslint-disable-next-line max-lines-per-function, complexity- async renderImages(imageParam: IImageData, scene: Scene) {+ async renderImages(imageParam: IImageData, scene: Scene, options?: { allowInactiveSheet?: boolean }) {const {transform: singleTransform,drawingType,@@ -114,7 +114,8 @@ export class DrawingRenderService {return;}- if (this._univerInstanceService.getUnitType(unitId) === UniverInstanceType.UNIVER_SHEET && subUnitId !== this._getActiveSheetId()) {+ // Isolated print scenes may target a worksheet that is not active in the editor.+ if (!options?.allowInactiveSheet && this._univerInstanceService.getUnitType(unitId) === UniverInstanceType.UNIVER_SHEET && subUnitId !== this._getActiveSheetId()) {return;}@@ -284,7 +285,7 @@ export class DrawingRenderService {return rects;}- renderDrawing(param: IDrawingSearch, scene: Scene) {+ renderDrawing(param: IDrawingSearch, scene: Scene, options?: { allowInactiveSheet?: boolean }) {const drawingParam = this._drawingManagerService.getDrawingByParam(param);if (drawingParam == null) {return;@@ -292,7 +293,7 @@ export class DrawingRenderService {switch (drawingParam.drawingType) {case DrawingTypeEnum.DRAWING_IMAGE:- return this.renderImages(drawingParam as IImageData, scene);+ return this.renderImages(drawingParam as IImageData, scene, options);default:}}diff --git a/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.tsindex a802181bda..ed9bc78230 100644--- a/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts+++ b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.integration.spec.ts@@ -306,6 +306,46 @@ describe('spreadsheet integration', () => {expect(skeleton.stylesCache.fontMatrix.getSizeOf()).toBe(0);});+ it('keeps the last printing row and column when the viewport ends on their exact boundaries', () => {+ const { skeleton, scene, cacheCanvas } = fixture;+ const endRow = 3;+ const endColumn = 3;+ const cacheBound = createBound(+ skeleton.rowHeaderWidthAndMarginLeft,+ skeleton.columnHeaderHeightAndMarginTop,+ skeleton.rowHeaderWidthAndMarginLeft + skeleton.columnWidthAccumulation[endColumn],+ skeleton.columnHeaderHeightAndMarginTop + skeleton.rowHeightAccumulation[endRow]+ );+ const vpInfo = createViewportInfo(scene, cacheCanvas, { cacheBound });++ expect(skeleton.getCacheRangeByViewport(vpInfo, true)).toEqual({+ startRow: 0,+ endRow,+ startColumn: 0,+ endColumn,+ });+ });++ it('does not include the next printing row or column for a one-pixel viewport overlap', () => {+ const { skeleton, scene, cacheCanvas } = fixture;+ const endRow = 3;+ const endColumn = 3;+ const cacheBound = createBound(+ skeleton.rowHeaderWidthAndMarginLeft,+ skeleton.columnHeaderHeightAndMarginTop,+ skeleton.rowHeaderWidthAndMarginLeft + skeleton.columnWidthAccumulation[endColumn] + 1,+ skeleton.columnHeaderHeightAndMarginTop + skeleton.rowHeightAccumulation[endRow] + 1+ );+ const vpInfo = createViewportInfo(scene, cacheCanvas, { cacheBound });++ expect(skeleton.getCacheRangeByViewport(vpInfo, true)).toEqual({+ startRow: 0,+ endRow,+ startColumn: 0,+ endColumn,+ });+ });+it('builds border cache for row-wise merged cells on the selection left edge', () => {const workbookData = workbookDataFactory();workbookData.id = 'sheet-render-border-workbook';diff --git a/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts b/packages/engine-render/src/components/sheets/extensions/sheet-extension.tsindex 14f13ac723..e94b61cc20 100644--- a/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts+++ b/packages/engine-render/src/components/sheets/extensions/sheet-extension.ts@@ -31,6 +31,14 @@ export const SHEET_EXTENSION_PREFIX = 'sheet-ext-';export class SheetExtension extends ComponentExtension<SpreadsheetSkeleton, SHEET_EXTENSION_TYPE, IRange[]> {override type = SHEET_EXTENSION_TYPE.GRID;+ /**+ * Return an isolated instance when this extension is safe to render in a print scene.+ * Editor-only extensions remain excluded by default.+ */+ copyForPrinting(): SheetExtension | null {+ return null;+ }+isRenderDiffRangesByCell(rangeP: IRange, diffRanges?: IRange[]) {if (diffRanges == null || diffRanges.length === 0) {return true;diff --git a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts b/packages/engine-render/src/components/sheets/sheet.render-skeleton.tsindex 5e8d80a867..0666ec640c 100644--- a/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts+++ b/packages/engine-render/src/components/sheets/sheet.render-skeleton.ts@@ -1410,7 +1410,8 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const endY = Math.round(viewBound.bottom) - this.columnHeaderHeightAndMarginTop;let endRow = searchArray(rowHeightAccumulation, endY);// If the endY is exactly on the boundary, need to minus 1 to get the correct endRow.- if (endRow < lenOfRowData && rowHeightAccumulation[endRow - 1] === endY) {+ const isEndYOnBoundary = endRow < lenOfRowData && rowHeightAccumulation[endRow - 1] === endY;+ if (isEndYOnBoundary) {endRow -= 1;}@@ -1419,17 +1420,19 @@ export class SpreadsheetSkeleton extends SheetSkeleton {const endX = Math.round(viewBound.right) - this.rowHeaderWidthAndMarginLeft;let endColumn = searchArray(columnWidthAccumulation, endX);// If the endX is exactly on the boundary, need to minus 1 to get the correct endColumn.- if (endColumn < lenOfColData && columnWidthAccumulation[endColumn - 1] === endX) {+ const isEndXOnBoundary = endColumn < lenOfColData && columnWidthAccumulation[endColumn - 1] === endX;+ if (isEndXOnBoundary) {endColumn -= 1;}- // If the get range is used for visible range, the endRow and endColumn need to minus 1.+ // Printing excludes a row or column reached only by a small viewport overlap.+ // An exact boundary was already adjusted above and must not be decremented twice.if (isPrinting) {return {startRow,- endRow: endRow === lenOfRowData - 1 ? endRow : endRow - 1,+ endRow: endRow === lenOfRowData - 1 || isEndYOnBoundary ? endRow : endRow - 1,startColumn,- endColumn: endColumn === lenOfColData - 1 ? endColumn : endColumn - 1,+ endColumn: endColumn === lenOfColData - 1 || isEndXOnBoundary ? endColumn : endColumn - 1,};}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 7cf56c8916..57e1a0bb4f 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@@ -14,7 +14,7 @@* limitations under the License.*/-import { DrawingTypeEnum, PRINT_CHART_COMPONENT_KEY } from '@univerjs/core';+import { DrawingTypeEnum } from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';import { mountPrintingFloatDom } from '../../views/PrintingFloatDom';import { SheetDrawingPrintingController } from '../sheet-drawing-printing.controller';@@ -23,7 +23,7 @@ vi.mock('../../views/PrintingFloatDom', () => ({mountPrintingFloatDom: vi.fn(() => vi.fn()),}));-function createController() {+function createController(options?: { hasDrawingData?: boolean }) {const interceptors = new Map<string, any>();const points = {PRINTING_COMPONENT_COLLECT: 'PRINTING_COMPONENT_COLLECT',@@ -33,7 +33,7 @@ function createController() {const drawingData = {'unit-1': {'sheet-1': {- order: ['image-1', 'chart-1', 'dom-1', 'grouped-image'],+ order: ['image-1', 'chart-1', 'dom-1', 'block-1', 'grouped-image', 'hidden-image', 'hidden-chart'],data: {'image-1': {unitId: 'unit-1',@@ -57,6 +57,14 @@ function createController() {componentKey: 'custom-dom',transform: { left: 80, top: 90, width: 40, height: 20 },},+ 'block-1': {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ drawingId: 'block-1',+ drawingType: DrawingTypeEnum.DRAWING_BLOCK,+ componentKey: 'custom-block',+ transform: { left: 80, top: 80, width: 20, height: 20 },+ },'grouped-image': {unitId: 'unit-1',subUnitId: 'sheet-1',@@ -65,6 +73,22 @@ function createController() {groupId: 'group-1',transform: { left: -100, top: -100, width: 20, height: 20 },},+ 'hidden-image': {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ drawingId: 'hidden-image',+ drawingType: DrawingTypeEnum.DRAWING_IMAGE,+ hidden: true,+ transform: { left: 1000, top: 1000, width: 500, height: 500 },+ },+ 'hidden-chart': {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ drawingId: 'hidden-chart',+ drawingType: DrawingTypeEnum.DRAWING_CHART,+ hidden: true,+ transform: { left: 1000, top: 1000, width: 500, height: 500 },+ },},},},@@ -93,14 +117,11 @@ function createController() {}),},} as never,- { renderDrawing: vi.fn() } as never,- { getDrawingDataForUnit: vi.fn(() => drawingData['unit-1']) } as never,+ { renderDrawing: vi.fn(() => Promise.resolve()) } as never,+ { getDrawingDataForUnit: vi.fn(() => options?.hasDrawingData === false ? undefined : drawingData['unit-1']) } as never,{ getRenderById: vi.fn(() => render) } as never,{- get: vi.fn((key: string) => {- if (key === PRINT_CHART_COMPONENT_KEY) return 'ChartPrintingComponent';- return `${key}-Component`;- }),+ get: vi.fn((key: string) => `${key}-Component`),} as never,{} as never);@@ -109,20 +130,23 @@ function createController() {}describe('SheetDrawingPrintingController', () => {- it('renders printable image drawings into the print scene while leaving chart/dom to float dom printing', () => {+ it('renders printable images while excluding charts and floating DOM drawings', () => {const { controller, interceptors, points } = createController();const scene = {};+ const resourceCollector = { add: vi.fn() };const next = vi.fn(() => 'next-result');const result = interceptors.get(points.PRINTING_COMPONENT_COLLECT).handler(null, {unitId: 'unit-1',subUnitId: 'sheet-1',scene,+ resourceCollector,}, next);expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledTimes(2);- expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'image-1' }), scene);- expect((controller as any)._drawingRenderService.renderDrawing).toHaveBeenCalledWith(expect.objectContaining({ drawingId: 'grouped-image' }), scene);+ 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(resourceCollector.add).toHaveBeenCalledTimes(2);expect(result).toBe('next-result');controller.dispose();@@ -148,13 +172,16 @@ describe('SheetDrawingPrintingController', () => {controller.dispose();});- it('mounts chart and dom float components for printing and registers cleanup', () => {+ it('defers React root cleanup when replacing printed float components', async () => {const { controller, interceptors, points } = createController();const unmount = vi.fn();vi.mocked(mountPrintingFloatDom).mockReturnValueOnce(unmount);- const add = vi.fn((dispose: () => void) => dispose());+ const disposers: Array<() => void> = [];+ const add = vi.fn((dispose: () => void) => disposers.push(dispose));const disposableCollection = { add };+ const resourceCollector = { add: vi.fn() };const next = vi.fn((value) => value);+ const root = document.createElement('div');const result = interceptors.get(points.PRINTING_DOM_COLLECT).handler(disposableCollection, {unitId: 'unit-1',@@ -162,26 +189,56 @@ describe('SheetDrawingPrintingController', () => {scene: 'scene',skeleton: 'skeleton',worksheet: 'worksheet',- root: 'root',+ root,+ resourceCollector,}, next);expect(mountPrintingFloatDom).toHaveBeenCalledWith({floatDomInfos: [- expect.objectContaining({ drawingId: 'chart-1', componentKey: 'ChartPrintingComponent' }),expect.objectContaining({ drawingId: 'dom-1', componentKey: 'custom-dom-print-Component' }),+ expect.objectContaining({ drawingId: 'block-1', componentKey: 'custom-block-print-Component' }),],scene: 'scene',skeleton: 'skeleton',worksheet: 'worksheet',},- 'root',+ expect.any(HTMLElement),expect.any(Object));+ const printingRoot = vi.mocked(mountPrintingFloatDom).mock.calls[0][1];+ expect(printingRoot).not.toBe(root);+ expect(printingRoot.parentElement).toBe(root);expect(add).toHaveBeenCalled();- expect(unmount).toHaveBeenCalled();+ expect(resourceCollector.add).not.toHaveBeenCalled();+ expect(unmount).not.toHaveBeenCalled();expect(result).toBe(disposableCollection);+ disposers.forEach((dispose) => dispose());+ expect(unmount).not.toHaveBeenCalled();+ expect(printingRoot.parentElement).toBeNull();++ await Promise.resolve();+ expect(unmount).toHaveBeenCalledOnce();++ controller.dispose();+ });++ it('continues DOM collection when the sheet has no drawing data', () => {+ const { controller, interceptors, points } = createController({ hasDrawingData: false });+ const disposableCollection = { add: vi.fn() };+ const next = vi.fn(() => 'next-result');+ const mountCallCount = vi.mocked(mountPrintingFloatDom).mock.calls.length;++ const result = interceptors.get(points.PRINTING_DOM_COLLECT).handler(disposableCollection, {+ unitId: 'unit-1',+ subUnitId: 'sheet-1',+ }, next);++ expect(next).toHaveBeenCalledWith(disposableCollection);+ expect(result).toBe('next-result');+ expect(mountPrintingFloatDom).toHaveBeenCalledTimes(mountCallCount);+controller.dispose();});});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 c692dafb63..1732ba3e89 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@@ -16,7 +16,7 @@import type { IRange } from '@univerjs/core';import type { IFloatDomData } from '@univerjs/sheets-drawing';-import { Disposable, DrawingTypeEnum, Inject, Injector, PRINT_CHART_COMPONENT_KEY, Tools } from '@univerjs/core';+import { Disposable, DrawingTypeEnum, Inject, Injector, Tools } from '@univerjs/core';import { IDrawingManagerService } from '@univerjs/drawing';import { DrawingRenderService } from '@univerjs/drawing-ui';import { IRenderManagerService } from '@univerjs/engine-render';@@ -45,14 +45,24 @@ export class SheetDrawingPrintingController extends Disposable {this._sheetPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_COMPONENT_COLLECT,{handler: (_param, pos, next) => {- const { unitId, scene, subUnitId } = pos;+ const { unitId, scene, subUnitId, resourceCollector } = pos;const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);const subUnitData = unitData?.[subUnitId];if (subUnitData) {subUnitData.order.forEach((id) => {const drawing = subUnitData.data[id];- if (drawing.drawingType !== DrawingTypeEnum.DRAWING_CHART && drawing.drawingType !== DrawingTypeEnum.DRAWING_DOM) {- this._drawingRenderService.renderDrawing(drawing, scene);+ if (drawing.hidden) {+ return;+ }+ if (+ drawing.drawingType !== DrawingTypeEnum.DRAWING_CHART &&+ drawing.drawingType !== DrawingTypeEnum.DRAWING_DOM &&+ drawing.drawingType !== DrawingTypeEnum.DRAWING_BLOCK+ ) {+ const resource = this._drawingRenderService.renderDrawing(drawing, scene, { allowInactiveSheet: true });+ if (resource) {+ resourceCollector.add(Promise.resolve(resource));+ }}});}@@ -89,7 +99,7 @@ export class SheetDrawingPrintingController extends Disposable {const data = subUnitData.order.map((key) => subUnitData.data[key]);if (data.length) {data.forEach((param) => {- if (!param.groupId && param.transform && Tools.isDefine(param.transform.left) && Tools.isDefine(param.transform.top) && Tools.isDefine(param.transform.width) && Tools.isDefine(param.transform.height)) {+ if (!param.hidden && !param.groupId && param.transform && Tools.isDefine(param.transform.left) && Tools.isDefine(param.transform.top) && Tools.isDefine(param.transform.width) && Tools.isDefine(param.transform.height)) {const start = skeleton.skeleton.getCellIndexByOffset(param.transform.left, param.transform.top, scaleX, scaleY, { x: 0, y: 0 });const end = skeleton.skeleton.getCellIndexByOffset(param.transform.left + param.transform.width, param.transform.top + param.transform.height, scaleX, scaleY, { x: 0, y: 0 });if (start.column < newRange.startColumn) {@@ -131,14 +141,10 @@ export class SheetDrawingPrintingController extends Disposable {if (subUnitData) {const floatDomInfos = subUnitData.order.map((id) => {const drawing = subUnitData.data[id] as IFloatDomData;- if (drawing.drawingType === DrawingTypeEnum.DRAWING_CHART) {- return {- ...drawing,- componentKey: this._componetManager.get(PRINT_CHART_COMPONENT_KEY) as any,- };+ if (drawing.hidden) {+ return null;}-- if (drawing.drawingType === DrawingTypeEnum.DRAWING_DOM) {+ if (drawing.drawingType === DrawingTypeEnum.DRAWING_DOM || drawing.drawingType === DrawingTypeEnum.DRAWING_BLOCK) {const printingComponentKey = this._sheetPrintInterceptorService.getPrintComponent(drawing.componentKey);return {...drawing,@@ -148,6 +154,13 @@ export class SheetDrawingPrintingController extends Disposable {return null;}).filter(Boolean) as IFloatDomData[];+ // Each prepare cycle gets its own React container. Removing the old+ // container immediately and unmounting it later prevents its cleanup+ // from racing with a new render mounted into the persistent page root.+ const printingRoot = document.createElement('div');+ printingRoot.style.position = 'absolute';+ printingRoot.style.inset = '0';+ pos.root.appendChild(printingRoot);const unmountPrintingFloatDom = mountPrintingFloatDom({floatDomInfos,@@ -155,16 +168,20 @@ export class SheetDrawingPrintingController extends Disposable {skeleton: pos.skeleton,worksheet: pos.worksheet,},- pos.root,+ printingRoot,this._injector);disposableCollection?.add(() => {- unmountPrintingFloatDom();+ printingRoot.remove();+ queueMicrotask(unmountPrintingFloatDom);});return next(disposableCollection);}++ // Do not terminate the interceptor chain on sheets without drawings.+ return next(disposableCollection);},})diff --git a/packages/sheets-drawing-ui/src/index.ts b/packages/sheets-drawing-ui/src/index.tsindex a6abbc63c1..f4fe8c1338 100644--- a/packages/sheets-drawing-ui/src/index.ts+++ b/packages/sheets-drawing-ui/src/index.ts@@ -42,6 +42,7 @@ export {export type { ICanvasFloatDom, ICanvasFloatDomInfo, IDOMAnchor } from './services/canvas-float-dom-manager.service';export { DrawingContextMenuService, IDrawingContextMenuService } from './services/drawing-context-menu.service';export type { IDrawingContextMenuProvider, IDrawingContextMenuProviderContext } from './services/drawing-context-menu.service';+export { SHEET_CHART_RENDER_OBJECT_CONFIG } from './services/sheet-chart-render-object.config';export { SheetDrawingHitTestService } from './services/sheet-drawing-hit-test.service';export type { ISheetDrawingDoubleClickEvent, ISheetDrawingHitTestResult } from './services/sheet-drawing-hit-test.service';export { SheetDrawingAnchor } from './views/sheet-image-panel/SheetDrawingAnchor';diff --git a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.tsindex 294233b577..45c59baa4a 100644--- a/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts+++ b/packages/sheets-drawing-ui/src/services/canvas-float-dom-manager.service.ts@@ -98,6 +98,7 @@ import {} from '@univerjs/sheets-ui';import { CanvasFloatDomPreviewService, CanvasFloatDomService } from '@univerjs/ui';import { BehaviorSubject, filter, map, of, Subject, switchMap, take } from 'rxjs';+import { SHEET_CHART_RENDER_OBJECT_CONFIG } from './sheet-chart-render-object.config';export interface ICanvasFloatDom {/**@@ -1259,7 +1260,6 @@ export class SheetCanvasFloatDomManagerService extends Disposable {};const isChart = drawingType === DrawingTypeEnum.DRAWING_CHART;- imageConfig.rotateEnabled = false;if (isChart) {const backgroundColor = this._getChartDataBackground(data);@@ -1270,9 +1270,9 @@ export class SheetCanvasFloatDomManagerService extends Disposable {if (data && (data as Record<string, string>).border) {imageConfig.stroke = (data as Record<string, string>).border;}- imageConfig.paintFirst = 'stroke';- imageConfig.strokeWidth = 1;- imageConfig.radius = 8;+ Object.assign(imageConfig, SHEET_CHART_RENDER_OBJECT_CONFIG);+ } else {+ imageConfig.rotateEnabled = false;}const rect = rectShape ?? this._createRenderObject({diff --git a/packages/sheets-drawing-ui/src/services/sheet-chart-render-object.config.ts b/packages/sheets-drawing-ui/src/services/sheet-chart-render-object.config.tsnew file mode 100644index 0000000000..5269914912--- /dev/null+++ b/packages/sheets-drawing-ui/src/services/sheet-chart-render-object.config.ts@@ -0,0 +1,31 @@+/**+ * 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 { IRectProps } from '@univerjs/engine-render';++type SheetChartRenderObjectConfig = Pick<+ IRectProps,+ 'borderEnabled' | 'paintFirst' | 'radius' | 'rotateEnabled' | 'strokeWidth'+>;++/** Shared Chart frame config for editor and isolated print Scene objects. */+export const SHEET_CHART_RENDER_OBJECT_CONFIG = Object.freeze({+ borderEnabled: false,+ paintFirst: 'stroke',+ radius: 8,+ rotateEnabled: false,+ strokeWidth: 1,+} satisfies SheetChartRenderObjectConfig);diff --git a/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsx b/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsxindex a48aa23666..f54f5478ea 100644--- a/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsx+++ b/packages/sheets-drawing-ui/src/views/PrintingFloatDom.tsx@@ -32,51 +32,64 @@ export interface IPrintingFloatDomProps {worksheet: Worksheet;};-export const PrintingFloatDom = (props: IPrintingFloatDomProps) => {- const { floatDomInfos, scene, skeleton, worksheet } = props;- const floatDomParams = useMemo(() => floatDomInfos.map((info) => {- const { width, height, angle, left, top } = info.transform!;- const offsetBound = transformBound2DOMBound(- {- left: left ?? 0,- right: (left ?? 0) + (width ?? 0),- top: top ?? 0,- bottom: (top ?? 0) + (height ?? 0),- },- scene,- skeleton,- worksheet,- undefined,- true- );- const { scaleX, scaleY } = scene.getAncestorScale();+export function createPrintingFloatDom(+ info: IFloatDomData,+ scene: Scene,+ skeleton: SpreadsheetSkeleton,+ worksheet: Worksheet+) {+ const { width, height, angle, left, top } = info.transform!;+ // The print root starts at the sheet content origin and does not include row/column headers.+ const offsetBound = transformBound2DOMBound(+ {+ left: left ?? 0,+ right: (left ?? 0) + (width ?? 0),+ top: top ?? 0,+ bottom: (top ?? 0) + (height ?? 0),+ },+ scene,+ skeleton,+ worksheet,+ undefined,+ true+ );+ const { scaleX, scaleY } = scene.getAncestorScale();++ const domPos: IFloatDomLayout = {+ startX: offsetBound.left,+ endX: offsetBound.right,+ startY: offsetBound.top,+ endY: offsetBound.bottom,+ rotate: angle!,+ width: width! * scaleX,+ height: height! * scaleY,+ absolute: offsetBound.absolute,+ };- const domPos: IFloatDomLayout = {- startX: offsetBound.left,- endX: offsetBound.right,- startY: offsetBound.top,- endY: offsetBound.bottom,- rotate: angle!,- width: width! * scaleX,- height: height! * scaleY,- absolute: offsetBound.absolute,- };+ const floatDom: IFloatDom & { position: IFloatDomLayout } = {+ position$: new BehaviorSubject<IFloatDomLayout>(domPos),+ position: domPos,+ id: info.drawingId,+ componentKey: info.componentKey,+ onPointerMove: () => { },+ onPointerDown: () => { },+ onPointerUp: () => { },+ onWheel: () => { },+ unitId: info.unitId,+ data: info.data,+ // Preserve props required by custom printable floating DOM components.+ props: (info as IFloatDomData & { props?: Record<string, unknown> }).props,+ };- const floatDom: IFloatDom & { position: IFloatDomLayout } = {- position$: new BehaviorSubject<IFloatDomLayout>(domPos),- position: domPos,- id: info.drawingId,- componentKey: info.componentKey,- onPointerMove: () => { },- onPointerDown: () => { },- onPointerUp: () => { },- onWheel: () => { },- unitId: info.unitId,- data: info.data,- };+ return [info.drawingId, floatDom] as const;+}- return [info.drawingId, floatDom] as const;- }), [floatDomInfos, scene, skeleton, worksheet]);+export const PrintingFloatDom = (props: IPrintingFloatDomProps) => {+ const { floatDomInfos, scene, skeleton, worksheet } = props;+ const floatDomParams = useMemo(+ () => floatDomInfos.map((info) => createPrintingFloatDom(info, scene, skeleton, worksheet)),+ [floatDomInfos, scene, skeleton, worksheet]+ );return (<div style={{ position: 'absolute', top: 0, left: 0 }}>diff --git a/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsx b/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsxindex c6c88f113e..e4679615f6 100644--- a/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsx+++ b/packages/sheets-drawing-ui/src/views/__tests__/PrintingFloatDom.spec.tsx@@ -23,7 +23,7 @@ import { ComponentManager } from '@univerjs/ui';import { act } from 'react';import { afterEach, describe, expect, it } from 'vitest';import { createSheetsDrawingUiTestBed } from '../../__tests__/create-sheets-drawing-ui-test-bed';-import { mountPrintingFloatDom } from '../PrintingFloatDom';+import { createPrintingFloatDom, mountPrintingFloatDom } from '../PrintingFloatDom';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -74,8 +74,8 @@ class TestPrintingWorksheet {}}-function PrintingContent(props: { data?: { label?: string } }) {- return <span data-testid="printed-content">{props.data?.label}</span>;+function PrintingContent(props: { data?: { label?: string }; printingLabel?: string }) {+ return <span data-testid="printed-content">{props.printingLabel ?? props.data?.label}</span>;}function createFloatDomInfo(drawingId = 'printed-float-dom', label = 'printing'): IFloatDomData {@@ -183,4 +183,20 @@ describe('PrintingFloatDom', () => {expect(root.textContent).toContain('First printed label');expect(root.textContent).toContain('Second printed label');});++ it('forwards printing-only component props', () => {+ const info = {+ ...createFloatDomInfo(),+ props: { printingLabel: 'Ready callback props' },+ } as IFloatDomData;++ const [, floatDom] = createPrintingFloatDom(+ info,+ new TestPrintingScene() as unknown as Scene,+ new TestPrintingSkeleton() as unknown as SpreadsheetSkeleton,+ new TestPrintingWorksheet() as unknown as Worksheet+ );++ expect(floatDom.props).toEqual({ printingLabel: 'Ready callback props' });+ });});diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.tsindex 1fe7fb3ddb..38ba5ca391 100644--- a/packages/sheets-ui/src/index.ts+++ b/packages/sheets-ui/src/index.ts@@ -234,7 +234,7 @@ export { IMarkSelectionService, MarkSelectionService } from './services/mark-selexport { SheetPermissionRenderManagerService } from './services/permission/sheet-permission-render-manager.service';export type { ProtectedRangeShadowStrategy } from './services/permission/sheet-permission-render-manager.service';export { SheetPermissionUserManagerService } from './services/permission/sheet-permission-user-list.service';-export { SheetPrintInterceptorService } from './services/print-interceptor.service';+export { SheetPrintingResourceCollector, SheetPrintInterceptorService } from './services/print-interceptor.service';export { IRepeatLastActionService, RepeatLastActionPermission } from './services/repeat-last-action.service';export type { RepeatableCommandHandler } from './services/repeat-last-action.service';export { SheetScrollManagerService } from './services/scroll-manager.service';diff --git a/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts b/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.tsindex c9c3af1854..7779f6571b 100644--- a/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts+++ b/packages/sheets-ui/src/services/__tests__/print-interceptor.service.spec.ts@@ -16,7 +16,7 @@import { Injector } from '@univerjs/core';import { beforeEach, describe, expect, it } from 'vitest';-import { SheetPrintInterceptorService } from '../print-interceptor.service';+import { SheetPrintingResourceCollector, SheetPrintInterceptorService } from '../print-interceptor.service';describe('SheetPrintInterceptorService', () => {let service: SheetPrintInterceptorService;@@ -40,3 +40,25 @@ describe('SheetPrintInterceptorService', () => {expect(service.interceptor.fetchThroughInterceptors(interceptPoints.PRINTING_DOM_COLLECT)(domCollection as never, {} as never)).toBe(domCollection);});});++describe('SheetPrintingResourceCollector', () => {+ it('waits for registered printing resources', async () => {+ const collector = new SheetPrintingResourceCollector();+ let resolveResource!: () => void;+ const resource = new Promise<void>((resolve) => {+ resolveResource = resolve;+ });+ collector.add(resource);+ let ready = false;+ const waiting = collector.wait().then(() => {+ ready = true;+ });++ await Promise.resolve();+ expect(ready).toBe(false);++ resolveResource();+ await waiting;+ expect(ready).toBe(true);+ });+});diff --git a/packages/sheets-ui/src/services/print-interceptor.service.ts b/packages/sheets-ui/src/services/print-interceptor.service.tsindex 4ae49c9877..438a1fdbca 100644--- a/packages/sheets-ui/src/services/print-interceptor.service.ts+++ b/packages/sheets-ui/src/services/print-interceptor.service.ts@@ -18,6 +18,41 @@ import type { DisposableCollection, IRange, Worksheet } from '@univerjs/core';import type { Engine, Scene, Spreadsheet, SpreadsheetSkeleton } from '@univerjs/engine-render';import { createInterceptorKey, Disposable, InterceptorManager } from '@univerjs/core';+/** Tracks asynchronous resources registered by all interceptors for one print page. */+export class SheetPrintingResourceCollector {+ private readonly _pending = new Set<Promise<unknown>>();++ add(resource: Promise<unknown>): void {+ const tracked = Promise.resolve(resource)+ .catch(() => undefined)+ .finally(() => this._pending.delete(tracked));+ this._pending.add(tracked);+ }++ async wait(timeout = 10_000): Promise<void> {+ const deadline = Date.now() + timeout;+ // A completed resource may synchronously register another resource, so keep+ // draining until the set is empty rather than snapshotting it only once.+ while (this._pending.size > 0) {+ const remaining = deadline - Date.now();+ if (remaining <= 0) {+ return;+ }++ let timeoutId: ReturnType<typeof setTimeout> | undefined;+ await Promise.race([+ Promise.allSettled(Array.from(this._pending)),+ new Promise<void>((resolve) => {+ timeoutId = setTimeout(resolve, remaining);+ }),+ ]);+ if (timeoutId !== undefined) {+ clearTimeout(timeoutId);+ }+ }+ }+}+interface ISheetPrintContext {unitId: string;subUnitId: string;@@ -26,6 +61,8 @@ interface ISheetPrintContext {root: HTMLElement;worksheet: Worksheet;skeleton: SpreadsheetSkeleton;+ range: IRange;+ resourceCollector: SheetPrintingResourceCollector;offset: {offsetX: number;offsetY: number;