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(docs): stabilize table rendering and paragraph menu state (#7080)
Univer3b6ea01d0f97
diff --git a/packages/docs-ui/src/components/paragraph-menu/component-keys.ts b/packages/docs-ui/src/components/paragraph-menu/component-keys.tsnew file mode 100644index 0000000000..71154323a0--- /dev/null+++ b/packages/docs-ui/src/components/paragraph-menu/component-keys.ts@@ -0,0 +1,18 @@+/**+ * 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.+ */++export const DOC_PARAGRAPH_MENU_COMPONENT_KEY = 'doc.paragraph.menu';+export const DOC_TABLE_BLOCK_MENU_COMPONENT_KEY = 'doc.table-block.menu';diff --git a/packages/docs-ui/src/components/paragraph-menu/index.tsx b/packages/docs-ui/src/components/paragraph-menu/index.tsxindex 51c8502007..8b262a610b 100644--- a/packages/docs-ui/src/components/paragraph-menu/index.tsx+++ b/packages/docs-ui/src/components/paragraph-menu/index.tsx@@ -54,6 +54,8 @@ import { IDocClipboardService } from '../../services/clipboard/clipboard.serviceimport { DocEventManagerService } from '../../services/doc-event-manager.service';import { DocParagraphMenuService } from '../../services/doc-paragraph-menu.service';+export { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY } from './component-keys';+export function getParagraphMenuIconSizeClass(iconKey: string): string {return iconKey === 'TextTypeIcon' ? 'univer-size-3' : 'univer-size-4';}@@ -588,7 +590,7 @@ function getBlockSelectionRange(target: IDocBlockMenuTarget | null | undefined,};}-export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {+function ParagraphMenuBase({ popup, tableBlockOnly = false }: { popup: IPopup; tableBlockOnly?: boolean }) {const [visible, setVisible] = useState(false);const [openMode, setOpenMode] = useState<ParagraphMenuOpenMode>('pointer');const [anchorRect, setAnchorRect] = useState<{ left: number; right: number; top: number; bottom: number } | null>(null);@@ -621,7 +623,10 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {const slashMenuRequest = useObservable(docParagraphMenuService?.slashMenuRequest$);const paragraph = useObservable(docEventManagerService?.hoverParagraph$);const paragraphLeft = useObservable(docEventManagerService?.hoverParagraphLeft$);- const currentActiveTarget = activeTarget ?? docParagraphMenuService?.activeTarget;+ const rawActiveTarget = activeTarget ?? docParagraphMenuService?.activeTarget;+ const currentActiveTarget = tableBlockOnly+ ? rawActiveTarget?.kind === 'table' ? rawActiveTarget : null+ : rawActiveTarget?.kind === 'table' ? null : rawActiveTarget;const activeParagraphBound = currentActiveTarget?.paragraph ?? docParagraphMenuService?.activeParagraph ?? paragraph ?? paragraphLeft;const startIndex = activeParagraphBound?.startIndex;const dataStream = doc?.getBody()?.dataStream ?? '';@@ -939,6 +944,10 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {handleOpenSlashMenu(slashMenuRequest);}, [slashMenuRequest]);+ if (!currentActiveTarget) {+ return null;+ }+return (<><div@@ -1190,7 +1199,15 @@ export const ParagraphMenu = ({ popup }: { popup: IPopup }) => {)}</>);-};+}++export const ParagraphMenu = ({ popup }: { popup: IPopup }) => (+ <ParagraphMenuBase popup={popup} />+);++export const TableBlockMenu = ({ popup }: { popup: IPopup }) => (+ <ParagraphMenuBase popup={popup} tableBlockOnly />+);export function shouldUseInsertBelowRange(commandId: string, params: IValueOption): boolean {if (params.id === INSERT_BELLOW_MENU_ID) {diff --git a/packages/docs-ui/src/controllers/doc-ui.controller.ts b/packages/docs-ui/src/controllers/doc-ui.controller.tsindex 271eab9c4c..d727401ee1 100644--- a/packages/docs-ui/src/controllers/doc-ui.controller.ts+++ b/packages/docs-ui/src/controllers/doc-ui.controller.ts@@ -29,7 +29,7 @@ import { BuiltInUIPart, ComponentManager, connectInjector, ILayoutService, IMenuimport { CoreHeaderFooterCommand, OpenHeaderFooterPanelCommand } from '../commands/commands/doc-header-footer.command';import { SidebarDocHeaderFooterPanelOperation } from '../commands/operations/doc-header-footer-panel.operation';import { BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker, ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker } from '../components/list-type-picker';-import { ParagraphMenu } from '../components/paragraph-menu';+import { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, ParagraphMenu, TableBlockMenu } from '../components/paragraph-menu';import { floatToolbarMenuSchema, menuSchema } from '../menu/schema';import { DocSelectionRenderService } from '../services/selection/doc-selection-render.service';import { TabShortCut } from '../shortcuts/format.shortcut';@@ -73,7 +73,8 @@ export class DocUIController extends Disposable {[BULLET_LIST_TYPE_COMPONENT, BulletListTypePicker],[ORDER_LIST_TYPE_COMPONENT, OrderListTypePicker],['TodoListDoubleIcon', TodoListDoubleIcon],- ['doc.paragraph.menu', ParagraphMenu],+ [DOC_PARAGRAPH_MENU_COMPONENT_KEY, ParagraphMenu],+ [DOC_TABLE_BLOCK_MENU_COMPONENT_KEY, TableBlockMenu],['DeleteIcon', DeleteIcon],[PAGE_SETTING_COMPONENT_ID, PageSettings],['DocumentSettingIcon', DocSettingIcon],diff --git a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.tsindex 1fb69fdd85..907896155b 100644--- a/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts+++ b/packages/docs-ui/src/services/__tests__/doc-paragraph-menu.service.spec.ts@@ -15,10 +15,11 @@*/import type { IMutiPageParagraphBound } from '../doc-event-manager.service';-import { DataStreamTreeTokenType, DocumentBlockRangeType, PresetListType } from '@univerjs/core';+import { DataStreamTreeTokenType, DOC_RANGE_TYPE, DocumentBlockRangeType, PresetListType } from '@univerjs/core';import { DocumentEditArea } from '@univerjs/engine-render';import { BehaviorSubject, Subject } from 'rxjs';import { describe, expect, it, vi } from 'vitest';+import { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY } from '../../components/paragraph-menu';import { getPreferredParagraphBoundsInRange, getTableBlockMenuHoverRect, getTableHorizontalViewportGeometry } from '../doc-event-manager.service';import { DocParagraphMenuService } from '../doc-paragraph-menu.service';@@ -156,7 +157,8 @@ describe('DocParagraphMenuService', () => {tableId: 'table-1',});- const [anchor, options] = attachPopupToRect.mock.calls[0] as unknown as [() => { bottom: number; left: number; right: number; top: number }, { direction: string }];+ const [anchor, options] = attachPopupToRect.mock.calls[0] as unknown as [() => { bottom: number; left: number; right: number; top: number }, { componentKey: string; direction: string }];+ expect(options.componentKey).toBe(DOC_TABLE_BLOCK_MENU_COMPONENT_KEY);expect(options.direction).toBe('top-right');expect(anchor()).toEqual({bottom: 76,@@ -184,6 +186,9 @@ describe('DocParagraphMenuService', () => {expect(service.activeTarget?.kind).toBe('paragraph');expect(service.activeTarget?.draggable).toBe(true);expect(service.activeTarget?.cellRange).toEqual({ startOffset: 2, endOffset: 8 });++ const [, options] = attachPopupToRect.mock.calls[0] as unknown as [unknown, { componentKey: string }];+ expect(options.componentKey).toBe(DOC_PARAGRAPH_MENU_COMPONENT_KEY);});it('does not let the same table hover target steal back a cell paragraph menu', () => {@@ -310,6 +315,171 @@ describe('DocParagraphMenuService', () => {});});+ it('does not move the document cursor when the paragraph menu is hovered', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const replaceDocRanges = vi.fn();+ const service = createService({+ attachPopupToRect,+ dataStream: 'Body\r',+ replaceDocRanges,+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 4,+ startIndex: 4,+ }));+ service.setParagraphMenuActive(true);++ expect(replaceDocRanges).not.toHaveBeenCalled();+ });++ it('does not show paragraph menus while a table rect selection is active', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Body\r',+ docRanges: [{+ startOffset: 3,+ endOffset: 12,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ }],+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 4,+ startIndex: 4,+ }));++ expect(attachPopupToRect).not.toHaveBeenCalled();+ expect(service.activeTarget).toBeNull();+ });++ it('shows paragraph menus again after the table rect selection is cleared', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const docRanges: Array<{ collapsed: boolean; endOffset: number; rangeType: DOC_RANGE_TYPE; startOffset: number }> = [{+ startOffset: 3,+ endOffset: 12,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ }];+ const service = createService({+ attachPopupToRect,+ dataStream: 'Body\r',+ getDocRanges: () => docRanges,+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 4,+ startIndex: 4,+ }));+ docRanges.length = 0;+ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 4,+ startIndex: 4,+ }));++ expect(attachPopupToRect).toHaveBeenCalledTimes(1);+ expect(service.activeTarget?.kind).toBe('paragraph');+ });++ it('hides an already visible paragraph menu when a table rect selection becomes active', () => {+ const dispose = vi.fn();+ const textSelection$ = new Subject();+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));+ const service = createService({+ attachPopupToRect,+ dataStream: 'Body\r',+ textSelection$,+ });++ service.showParagraphMenu(createParagraphBound({+ paragraphStart: 0,+ paragraphEnd: 4,+ startIndex: 4,+ }));+ textSelection$.next({+ textRanges: [],+ rectRanges: [{+ startOffset: 3,+ endOffset: 12,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ }],+ });++ expect(dispose).toHaveBeenCalledTimes(1);+ expect(service.activeTarget).toBeNull();+ });++ it('still shows the table menu while a table rect selection is active', () => {+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));+ const service = createService({+ attachPopupToRect,+ dataStream: '',+ docRanges: [{+ startOffset: 10,+ endOffset: 30,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ }],+ tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],+ });++ service.showTableMenu({+ pageIndex: 0,+ rect: {+ bottom: 170,+ left: 100,+ right: 400,+ top: 80,+ },+ tableId: 'table-1',+ });++ expect(attachPopupToRect).toHaveBeenCalledTimes(1);+ expect(service.activeTarget?.kind).toBe('table');+ });++ it('keeps an already visible table menu when a table rect selection becomes active', () => {+ const dispose = vi.fn();+ const textSelection$ = new Subject();+ const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose }));+ const service = createService({+ attachPopupToRect,+ dataStream: '',+ tables: [{ tableId: 'table-1', startIndex: 10, endIndex: 30 }],+ textSelection$,+ });++ service.showTableMenu({+ pageIndex: 0,+ rect: {+ bottom: 170,+ left: 100,+ right: 400,+ top: 80,+ },+ tableId: 'table-1',+ });+ textSelection$.next({+ textRanges: [],+ rectRanges: [{+ startOffset: 10,+ endOffset: 30,+ collapsed: false,+ rangeType: DOC_RANGE_TYPE.RECT,+ }],+ });++ expect(dispose).not.toHaveBeenCalled();+ expect(service.activeTarget?.kind).toBe('table');+ });+it('uses list icons for list paragraph menus', () => {const attachPopupToRect = vi.fn(() => ({ canDispose: () => true, dispose: vi.fn() }));const service = createService({@@ -693,10 +863,14 @@ function createService(options: {blockRanges?: Array<{ blockId: string; blockType: string; endIndex: number; startIndex: number }>;dataStream: string;findParagraphBoundByIndex?: (index: number) => unknown;+ docRanges?: Array<{ collapsed?: boolean; endOffset?: number; rangeType?: DOC_RANGE_TYPE | string; startOffset?: number }>;+ getDocRanges?: () => Array<{ collapsed?: boolean; endOffset?: number; rangeType?: DOC_RANGE_TYPE | string; startOffset?: number }>;paragraphs?: Array<{ bullet?: { listType?: PresetListType }; startIndex: number }>;paragraphBounds?: Map<number, IMutiPageParagraphBound>;inputBefore$?: Subject<unknown>;keydown$?: Subject<unknown>;+ replaceDocRanges?: ReturnType<typeof vi.fn>;+ textSelection$?: Subject<unknown>;tableCellBounds?: Map<string, Array<{ colIndex: number; pageIndex: number; rect: { bottom: number; left: number; right: number; top: number }; rowIndex: number; tableId: string }>>;tables?: Array<{ endIndex: number; startIndex: number; tableId: string }>;viewportScrollY?: number;@@ -730,8 +904,9 @@ function createService(options: {} as never,{getActiveTextRange: () => null,- replaceDocRanges: vi.fn(),- textSelection$: new Subject(),+ getDocRanges: options.getDocRanges ?? vi.fn(() => options.docRanges ?? []),+ replaceDocRanges: options.replaceDocRanges ?? vi.fn(),+ textSelection$: options.textSelection$ ?? new Subject(),} as never,{hoverParagraphRealTime$: new BehaviorSubject(null),diff --git a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts b/packages/docs-ui/src/services/doc-paragraph-menu.service.tsindex 87a4e801d0..5136a7534b 100644--- a/packages/docs-ui/src/services/doc-paragraph-menu.service.ts+++ b/packages/docs-ui/src/services/doc-paragraph-menu.service.ts@@ -18,11 +18,12 @@ import type { DocumentDataModel, ICustomBlock, ICustomTable, IDocumentBlockRangeimport type { IBoundRectNoAngle, IRenderContext, IRenderModule, ITextRangeWithStyle } from '@univerjs/engine-render';import type { IMutiPageParagraphBound, ITableBound, ITableParagraphBound } from './doc-event-manager.service';import type { IEditorInputConfig } from './selection/doc-selection-render.service';-import { BlockType, DataStreamTreeTokenType, Disposable, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';+import { BlockType, DataStreamTreeTokenType, Disposable, DOC_RANGE_TYPE, Inject, isInternalEditorID, PresetListType } from '@univerjs/core';import { DocSelectionManagerService, DocSkeletonManagerService } from '@univerjs/docs';import { DocumentEditArea } from '@univerjs/engine-render';import { BehaviorSubject, combineLatest, first, throttleTime } from 'rxjs';import { VIEWPORT_KEY } from '../basics/docs-view-key';+import { DOC_PARAGRAPH_MENU_COMPONENT_KEY, DOC_TABLE_BLOCK_MENU_COMPONENT_KEY } from '../components/paragraph-menu/component-keys';import { DocEventManagerService } from './doc-event-manager.service';import { calcDocRangePositions, DocCanvasPopManagerService, transformBound2OffsetBound, transformOffset2Bound } from './doc-popup-manager.service';import { DocFloatMenuService } from './float-menu.service';@@ -99,6 +100,18 @@ const LIST_ICON_MAP: Partial<Record<PresetListType, string>> = {[PresetListType.CHECK_LIST_CHECKED]: 'TodoListDoubleIcon',};+interface IDocSelectionRangeLike {+ collapsed?: boolean;+ endOffset?: number;+ rangeType?: string;+ startOffset?: number;+}++interface IDocExpandedSelectionState {+ hasExpandedTextRange: boolean;+ hasRectRange: boolean;+}+export class DocParagraphMenuService extends Disposable implements IRenderModule {private _paragrahMenu: {paragraph: IMutiPageParagraphBound;@@ -171,15 +184,48 @@ export class DocParagraphMenuService extends Disposable implements IRenderModulereturn true;}+ private _getExpandedSelectionState(ranges: readonly IDocSelectionRangeLike[]): IDocExpandedSelectionState {+ return ranges.reduce<IDocExpandedSelectionState>((state, range) => {+ if (range.rangeType === DOC_RANGE_TYPE.RECT) {+ state.hasRectRange = true;+ return state;+ }++ if (range.collapsed === false) {+ state.hasExpandedTextRange = true;+ return state;+ }++ if (typeof range.startOffset === 'number' &&+ typeof range.endOffset === 'number' &&+ range.endOffset > range.startOffset &&+ range.collapsed !== true) {+ state.hasExpandedTextRange = true;+ }++ return state;+ }, {+ hasExpandedTextRange: false,+ hasRectRange: false,+ });+ }++ private _hasExpandedSelectionRanges(ranges: readonly IDocSelectionRangeLike[]) {+ const state = this._getExpandedSelectionState(ranges);+ return state.hasExpandedTextRange || state.hasRectRange;+ }++ private _hasExpandedTextSelection() {+ return this._getExpandedSelectionState(this._docSelectionManagerService.getDocRanges()).hasExpandedTextRange;+ }++ private _hasExpandedSelection() {+ return this._hasExpandedSelectionRanges(this._docSelectionManagerService.getDocRanges());+ }+setParagraphMenuActive(active: boolean) {if (this._paragrahMenu) {this._paragrahMenu.active = active;- if (!this._isCursorInActiveParagraph()) {- this._docSelectionManagerService.replaceDocRanges([{- startOffset: this._paragrahMenu.paragraph.paragraphStart,- endOffset: this._paragrahMenu.paragraph.paragraphStart,- }]);- }}}@@ -189,6 +235,26 @@ export class DocParagraphMenuService extends Disposable implements IRenderModulereturn;}+ const selectionState = this._getExpandedSelectionState(this._docSelectionManagerService.getDocRanges());+ if (selectionState.hasExpandedTextRange) {+ this.hideParagraphMenu(true);+ return;+ }++ if (selectionState.hasRectRange) {+ if (tableBound) {+ this.showTableMenu(tableBound);+ return;+ }++ if (this._paragrahMenu?.target.kind === 'table') {+ return;+ }++ this.hideParagraphMenu(true);+ return;+ }+const viewModel = this._docSkeletonManagerService.getViewModel();if (viewModel.getEditArea() === DocumentEditArea.BODY &&@@ -226,6 +292,13 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule}));+ this.disposeWithMe(this._docSelectionManagerService.textSelection$.subscribe(({ textRanges, rectRanges }) => {+ const selectionState = this._getExpandedSelectionState([...textRanges, ...rectRanges]);+ if (selectionState.hasExpandedTextRange || (selectionState.hasRectRange && this._paragrahMenu?.target.kind !== 'table')) {+ this.hideParagraphMenu(true);+ }+ }));+let lastScrollY = 0;this.disposeWithMe(this._context.scene.getViewport(VIEWPORT_KEY.VIEW_MAIN)!.onScrollAfter$.subscribeEvent((e) => {if (lastScrollY === e.scrollY) {@@ -386,6 +459,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule}showParagraphMenu(paragraph: IMutiPageParagraphBound) {+ if (this._hasExpandedSelection()) {+ this.hideParagraphMenu(true);+ return;+ }+const target = this._buildParagraphMenuTarget(paragraph);if (!target) {this.hideParagraphMenu(true);@@ -416,7 +494,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModuleconst disposable = this._docPopupManagerService.attachPopupToRect(getFirstLine,{- componentKey: 'doc.paragraph.menu',+ componentKey: DOC_PARAGRAPH_MENU_COMPONENT_KEY,direction: 'left-center',onClickOutside: () => {if (this._isSlashMenuActive) {@@ -446,6 +524,11 @@ export class DocParagraphMenuService extends Disposable implements IRenderModule}showTableMenu(tableBound: ITableBound) {+ if (this._hasExpandedTextSelection()) {+ this.hideParagraphMenu(true);+ return;+ }+const body = this._context.unit.getBody();const table = body?.tables?.find((item) => item.tableId === tableBound.tableId);if (!table) {@@ -494,7 +577,7 @@ export class DocParagraphMenuService extends Disposable implements IRenderModuleconst disposable = this._docPopupManagerService.attachPopupToRect(getFirstLine,{- componentKey: 'doc.paragraph.menu',+ componentKey: DOC_TABLE_BLOCK_MENU_COMPONENT_KEY,direction: 'top-right',onClickOutside: () => {this.hideParagraphMenu(true);diff --git a/packages/engine-render/src/components/docs/__tests__/document.spec.ts b/packages/engine-render/src/components/docs/__tests__/document.spec.tsindex 635538ca65..a935bfd826 100644--- a/packages/engine-render/src/components/docs/__tests__/document.spec.ts+++ b/packages/engine-render/src/components/docs/__tests__/document.spec.ts@@ -339,6 +339,59 @@ describe('documents render', () => {documents.dispose();});+ it('aligns table cell background to precise start and end edges', () => {+ const skeleton = { getSkeletonData: () => ({ pages: [] }) } as any;+ const documents = new Documents('docs-background-precision', skeleton, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });+ const cell = createPage(DocumentSkeletonPageType.CELL, 'cell-background-precision');+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 10.25;+ cell.pageHeight = 6.25;+ const noBorder = { color: { rgb: 'transparent' }, width: { v: 0 } };+ const row = {+ cells: [cell],+ rowSource: {+ tableCells: [{+ backgroundColor: { rgb: '#bf125d' },+ borderTop: noBorder,+ borderBottom: noBorder,+ borderLeft: noBorder,+ borderRight: noBorder,+ }],+ },+ } as any;+ cell.parent = row;+ (documents as any)._drawLiquid = { x: 0.25, y: 0.25 };++ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 2, scaleY: 2 })),+ fillRect: vi.fn(),+ fillRectByPrecision: vi.fn(),+ setLineWidthByPrecision: vi.fn(),+ beginPath: vi.fn(),+ moveToByPrecision: vi.fn(),+ lineToByPrecision: vi.fn(),+ setLineDash: vi.fn(),+ stroke: vi.fn(),+ closePathByEnv: vi.fn(),+ set fillStyle(_value: string) {},+ set strokeStyle(_value: string) {},+ } as any;++ (documents as any)._drawTableCellBordersAndBg(ctx, { marginLeft: 0, marginTop: 0 }, cell);++ expect(ctx.fillRect).toHaveBeenCalledWith(0.5, 0.5, 10, 6);+ expect(ctx.fillRectByPrecision).not.toHaveBeenCalled();++ documents.dispose();+ });+it('draws a docs workspace background behind traditional pages', () => {const page = createPage(DocumentSkeletonPageType.BODY, '');const skeleton = {@@ -702,6 +755,109 @@ describe('documents render', () => {documents.dispose();});+ it('batches adjacent table cell backgrounds into a shared path', () => {+ const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');+ bodyPage.marginLeft = 0;+ bodyPage.marginTop = 0;+ const cells = Array.from({ length: 2 }, (_, index) => {+ const cell = createPage(DocumentSkeletonPageType.CELL, `background-batch-cell-${index}`);+ cell.marginLeft = 0;+ cell.marginTop = 0;+ cell.pageWidth = 10.25;+ cell.pageHeight = 6.25;+ cell.left = index * 10.25;+ return cell;+ });+ const noBorder = { color: { rgb: 'transparent' }, width: { v: 0 } };+ const row = {+ cells,+ index: 0,+ height: 6.25,+ top: 0,+ rowSource: {+ tableCells: [+ {+ backgroundColor: { rgb: '#000000' },+ borderTop: noBorder,+ borderBottom: noBorder,+ borderLeft: noBorder,+ borderRight: noBorder,+ },+ {+ backgroundColor: { rgb: '#000000' },+ borderTop: noBorder,+ borderBottom: noBorder,+ borderLeft: noBorder,+ borderRight: noBorder,+ },+ ],+ },+ } as any;+ const table = {+ rows: [row],+ width: 20.5,+ height: 6.25,+ top: 0.25,+ left: 0.25,+ tableId: 'table-background-batch',+ tableSource: {},+ parent: bodyPage,+ } as any;+ row.parent = table;+ cells.forEach((cell) => {+ cell.parent = row;+ });+ bodyPage.skeTables.set('table-background-batch', table);++ const documents = new Documents('docs-background-batch', {+ getSkeletonData: () => ({ pages: [bodyPage] }),+ } as any, {+ pageLayoutType: PageLayoutType.VERTICAL,+ pageMarginLeft: 0,+ pageMarginTop: 0,+ });++ const rects: Array<[number, number, number, number]> = [];+ const fillStyles: string[] = [];+ const ctx = {+ save: vi.fn(),+ restore: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 2, scaleY: 2 })),+ beginPath: vi.fn(),+ rect: vi.fn((x: number, y: number, width: number, height: number) => rects.push([x, y, width, height])),+ fill: vi.fn(),+ closePath: vi.fn(),+ set fillStyle(value: string) {+ fillStyles.push(value);+ },+ } as any;++ vi.spyOn(documents as any, '_drawTableCell').mockImplementation(() => {});++ (documents as any)._drawTable(+ ctx,+ bodyPage,+ bodyPage.skeTables,+ [],+ null,+ [],+ {} as any,+ 0,+ 0,+ {},+ { scaleX: 1, scaleY: 1 }+ );++ expect(fillStyles).toEqual(['#000000']);+ expect(ctx.fill).toHaveBeenCalledTimes(1);+ expect(rects).toEqual([+ [0.5, 0.5, 10, 6],+ [10.5, 0.5, 10.5, 6],+ ]);++ documents.dispose();+ });+it('uses the document unit id to apply table horizontal viewport while drawing', () => {const bodyPage = createPage(DocumentSkeletonPageType.BODY, '');attachTable(bodyPage);@@ -737,10 +893,14 @@ describe('documents render', () => {const ctx = {save: vi.fn(),restore: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),beginPath: vi.fn(),+ rect: vi.fn(),+ fill: vi.fn(),rectByPrecision: vi.fn(),closePath: vi.fn(),clip: vi.fn(),+ set fillStyle(_value: string) {},} as any;const translateCalls: Array<[number | undefined, number | undefined]> = [];@@ -792,10 +952,14 @@ describe('documents render', () => {const ctx = {save: vi.fn(),restore: vi.fn(),+ getScale: vi.fn(() => ({ scaleX: 1, scaleY: 1 })),beginPath: vi.fn(),+ rect: vi.fn(),+ fill: vi.fn(),rectByPrecision: vi.fn(),closePath: vi.fn(),clip: vi.fn(),+ set fillStyle(_value: string) {},} as any;vi.spyOn(documents as any, '_drawTableCell').mockImplementation(() => {});diff --git a/packages/engine-render/src/components/docs/document.ts b/packages/engine-render/src/components/docs/document.tsindex 84537ad1d6..973c047430 100644--- a/packages/engine-render/src/components/docs/document.ts+++ b/packages/engine-render/src/components/docs/document.ts@@ -31,7 +31,7 @@ import { BORDER_TYPE as BORDER_LTRB, drawLineByBorderType } from '../../basics';import { calculateRectRotate, getRotateOffsetAndFarthestHypotenuse } from '../../basics/draw';import { LineType } from '../../basics/i-document-skeleton-cached';import { VERTICAL_ROTATE_ANGLE } from '../../basics/text-rotation';-import { degToRad } from '../../basics/tools';+import { degToRad, fixLineWidthByScale } from '../../basics/tools';import { Vector2 } from '../../basics/vector2';import { DocumentsSpanAndLineExtensionRegistry } from '../extension';import { DocComponent } from './doc-component';@@ -534,6 +534,8 @@ export class Documents extends DocComponent {drawLiquid.translate(-viewport.scrollLeft, 0);}+ this._drawTableCellBackgrounds(ctx, page, tableSkeleton);+for (const row of rows) {const { top: rowTop, cells } = row;drawLiquid.translateSave();@@ -576,6 +578,59 @@ export class Documents extends DocComponent {}}+ private _drawTableCellBackgrounds(+ ctx: UniverRenderingContext,+ page: IDocumentSkeletonPage,+ tableSkeleton: IDocumentSkeletonTable+ ) {+ if (this._drawLiquid == null) {+ return;+ }++ const backgrounds = new Map<string, Array<{ x: number; y: number; width: number; height: number }>>();+ const tableX = this._drawLiquid.x + page.marginLeft;+ const tableY = this._drawLiquid.y + page.marginTop;++ for (const row of tableSkeleton.rows) {+ row.cells.forEach((cell, index) => {+ if ((cell as IDocumentSkeletonPage & { isMergedCellCovered?: boolean }).isMergedCellCovered) {+ return;+ }++ const cellSource = row.rowSource.tableCells[index];+ if (!cellSource || cellSource.rowSpan === 0 || cellSource.columnSpan === 0) {+ return;+ }++ const color = cellSource.backgroundColor?.rgb;+ if (!color) {+ return;+ }++ const rects = backgrounds.get(color) ?? [];+ rects.push({+ x: tableX + cell.left,+ y: tableY + row.top,+ width: cell.pageWidth,+ height: cell.pageHeight,+ });+ backgrounds.set(color, rects);+ });+ }++ backgrounds.forEach((rects, color) => {+ ctx.save();+ ctx.fillStyle = color;+ ctx.beginPath();+ rects.forEach(({ x, y, width, height }) => {+ rectByPrecisionBounds(ctx, x, y, width, height);+ });+ ctx.fill();+ ctx.closePath();+ ctx.restore();+ });+ }+private _getTableViewport(page: IDocumentSkeletonPage,tableSkeleton: IDocumentSkeletonTable,@@ -701,7 +756,7 @@ export class Documents extends DocComponent {if (this._drawLiquid == null) {return;}- this._drawTableCellBordersAndBg(ctx, page, cell);+ this._drawTableCellBordersAndBg(ctx, page, cell, false);const { sections, marginLeft, marginTop } = cell;// eslint-disable-next-line no-param-reassign@@ -845,7 +900,8 @@ export class Documents extends DocComponent {private _drawTableCellBordersAndBg(ctx: UniverRenderingContext,page: IDocumentSkeletonPage,- cell: IDocumentSkeletonPage+ cell: IDocumentSkeletonPage,+ drawBackground = true) {const { marginLeft, marginTop } = page;const { pageWidth, pageHeight } = cell;@@ -874,10 +930,10 @@ export class Documents extends DocComponent {y += marginTop;// Draw cell bg.- if (cellSource.backgroundColor?.rgb) {+ if (drawBackground && cellSource.backgroundColor?.rgb) {ctx.save();ctx.fillStyle = cellSource.backgroundColor.rgb;- ctx.fillRectByPrecision(x, y, pageWidth, pageHeight);+ fillRectByPrecisionBounds(ctx, x, y, pageWidth, pageHeight);ctx.restore();}@@ -1212,3 +1268,35 @@ function setTableCellBorderDash(ctx: UniverRenderingContext, dashStyle?: DashStyctx.setLineDash([0]);}++function fillRectByPrecisionBounds(+ ctx: UniverRenderingContext,+ x: number,+ y: number,+ width: number,+ height: number+) {+ const { scaleX, scaleY } = ctx.getScale();+ const startX = fixLineWidthByScale(x, scaleX);+ const startY = fixLineWidthByScale(y, scaleY);+ const endX = fixLineWidthByScale(x + width, scaleX);+ const endY = fixLineWidthByScale(y + height, scaleY);++ ctx.fillRect(startX, startY, endX - startX, endY - startY);+}++function rectByPrecisionBounds(+ ctx: UniverRenderingContext,+ x: number,+ y: number,+ width: number,+ height: number+) {+ const { scaleX, scaleY } = ctx.getScale();+ const startX = fixLineWidthByScale(x, scaleX);+ const startY = fixLineWidthByScale(y, scaleY);+ const endX = fixLineWidthByScale(x + width, scaleX);+ const endY = fixLineWidthByScale(y + height, scaleY);++ ctx.rect(startX, startY, endX - startX, endY - startY);+}