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(sheet): row col gap render (#6776)
Univerd6a9675d0450
diff --git a/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts b/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.tsindex 66bdd0ff99..366bfdaffa 100644--- a/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts+++ b/packages/core/src/sheets/__tests__/sheet-skeleton.integration.spec.ts@@ -21,6 +21,8 @@ import { afterEach, describe, expect, it } from 'vitest';import { IConfigService } from '../../services/config/config.service';import { IContextService } from '../../services/context/context.service';import { LocaleService } from '../../services/locale/locale.service';+import { ThemeService } from '../../services/theme/theme.service';+import { ColorKit } from '../../shared';import { BooleanNumber, HorizontalAlign } from '../../types/enum';import { LocaleType } from '../../types/enum/locale-type';import { SheetSkeleton } from '../sheet-skeleton';@@ -303,4 +305,107 @@ describe('SheetSkeleton integration', () => {expect(() => skeleton.getCellWithCoordByIndex(0, 0)).not.toThrow();});++ it('should fill gap default colors from theme and include gap sizes in accumulation arrays', () => {+ const testBed = createCoreTestBed(workbookDataFactory());+ const injector = testBed.univer.__getInjector();+ const worksheet = testBed.sheet.getActiveSheet()!;+ const skeleton = new SheetSkeleton(+ worksheet,+ testBed.sheet.getStyles(),+ injector.get(LocaleService),+ injector.get(IContextService),+ injector.get(IConfigService),+ injector as Injector+ ).calculate()!;++ disposables.push(() => testBed.univer.dispose());++ skeleton.setGapConfig({+ rowGaps: {+ 1: { size: 5 },+ },+ colGaps: {+ 2: { size: 7 },+ },+ });++ const themeService = injector.get(ThemeService);+ const baseColor = themeService.getColorFromTheme('primary.500');+ const { r, g, b } = new ColorKit(baseColor).toRgb();++ expect(skeleton.gapConfig.defaultBackgroundColor).toBe(`rgba(${r}, ${g}, ${b}, 0.08)`);+ expect(skeleton.gapConfig.defaultStripeColor).toBe(`rgba(${r}, ${g}, ${b}, 0.25)`);+ expect(skeleton.getRowGapSize(1)).toBe(5);+ expect(skeleton.getColGapSize(2)).toBe(7);++ // Gap sizes are included in cumulative arrays.+ expect(skeleton.rowHeightAccumulation).toEqual([28, 57, 81, 105, 105, 129, 153, 177]);+ expect(skeleton.columnWidthAccumulation).toEqual([72, 192, 271, 343, 343, 415]);++ // Position queries should detect gap hit ranges.+ expect(skeleton.getRowGapAtPosition(30)).toBe(1);+ expect(skeleton.getRowGapAtPosition(10)).toBe(-1);+ expect(skeleton.getColGapAtPosition(195)).toBe(2);+ expect(skeleton.getColGapAtPosition(100)).toBe(-1);+ });++ it('should keep provided gap default colors and return no-gap helpers when row/col gaps are absent', () => {+ const testBed = createCoreTestBed(workbookDataFactory());+ const injector = testBed.univer.__getInjector();+ const worksheet = testBed.sheet.getActiveSheet()!;+ const skeleton = new SheetSkeleton(+ worksheet,+ testBed.sheet.getStyles(),+ injector.get(LocaleService),+ injector.get(IContextService),+ injector.get(IConfigService),+ injector as Injector+ ).calculate()!;++ disposables.push(() => testBed.univer.dispose());++ skeleton.setGapConfig({+ defaultBackgroundColor: '#112233',+ defaultStripeColor: '#445566',+ });++ expect(skeleton.gapConfig.defaultBackgroundColor).toBe('#112233');+ expect(skeleton.gapConfig.defaultStripeColor).toBe('#445566');+ expect(skeleton.getGapSizeGetter()).toBeUndefined();+ expect(skeleton.getRowGapAtPosition(20)).toBe(-1);+ expect(skeleton.getColGapAtPosition(20)).toBe(-1);+ });++ it('should preserve provided one-sided gap color and fill the missing side from theme', () => {+ const testBed = createCoreTestBed(workbookDataFactory());+ const injector = testBed.univer.__getInjector();+ const worksheet = testBed.sheet.getActiveSheet()!;+ const skeleton = new SheetSkeleton(+ worksheet,+ testBed.sheet.getStyles(),+ injector.get(LocaleService),+ injector.get(IContextService),+ injector.get(IConfigService),+ injector as Injector+ ).calculate()!;++ disposables.push(() => testBed.univer.dispose());++ const themeService = injector.get(ThemeService);+ const baseColor = themeService.getColorFromTheme('primary.500');+ const { r, g, b } = new ColorKit(baseColor).toRgb();++ skeleton.setGapConfig({+ defaultBackgroundColor: '#abcdef',+ });+ expect(skeleton.gapConfig.defaultBackgroundColor).toBe('#abcdef');+ expect(skeleton.gapConfig.defaultStripeColor).toBe(`rgba(${r}, ${g}, ${b}, 0.25)`);++ skeleton.setGapConfig({+ defaultStripeColor: '#fedcba',+ });+ expect(skeleton.gapConfig.defaultStripeColor).toBe('#fedcba');+ expect(skeleton.gapConfig.defaultBackgroundColor).toBe(`rgba(${r}, ${g}, ${b}, 0.08)`);+ });});diff --git a/packages/core/src/sheets/sheet-skeleton.ts b/packages/core/src/sheets/sheet-skeleton.tsindex 661db0d565..6d6523dc5c 100644--- a/packages/core/src/sheets/sheet-skeleton.ts+++ b/packages/core/src/sheets/sheet-skeleton.ts@@ -40,12 +40,50 @@ import { DocumentDataModel } from '../docs/data-model/document-data-model';import { IConfigService } from '../services/config/config.service';import { IContextService } from '../services/context/context.service';import { LocaleService } from '../services/locale/locale.service';-import { isCellCoverable, ObjectMatrix, Rectangle, searchArray, Tools } from '../shared';+import { ThemeService } from '../services/theme/theme.service';+import { ColorKit, isCellCoverable, ObjectMatrix, Rectangle, searchArray, Tools } from '../shared';import { ImageCacheMap } from '../shared/cache/image-cache';import { getIntersectRange } from '../shared/range';import { Skeleton } from '../skeleton';import { BooleanNumber, HorizontalAlign } from '../types/enum';+/**+ * Configuration for a single gap (visual separator between rows or columns).+ * The gap area is rendered with a background color and diagonal stripes.+ */+export interface IGapItem {+ /** Gap size in pixels */+ size: number;+ /** Background color of the gap area. Falls back to ISheetGapConfig.defaultBackgroundColor. */+ color?: string;+ /** Diagonal stripe color. Falls back to ISheetGapConfig.defaultStripeColor. */+ stripeColor?: string;+}++/**+ * Configuration for row/column gaps in a sheet.+ * Gaps are visual-only separators that do not affect the data model.+ * They are stored as runtime configuration and are not persisted.+ */+export interface ISheetGapConfig {+ /** Row gaps. Key is the row index; gap appears BEFORE that row. */+ rowGaps?: IObjectArrayPrimitiveType<IGapItem>;+ /** Column gaps. Key is the column index; gap appears BEFORE that column. */+ colGaps?: IObjectArrayPrimitiveType<IGapItem>;+ /** Default diagonal stripe color (theme primary). Used when gap items don't specify stripeColor. */+ defaultStripeColor?: string;+ /** Default background color (lighter primary). Used when gap items don't specify color. */+ defaultBackgroundColor?: string;+}++/**+ * Optional gap size getter for coordinate calculation functions.+ */+export interface IGapSizeGetter {+ row: (r: number) => number;+ col: (c: number) => number;+}+export interface IGetRowColByPosOptions {closeFirst?: boolean;@@ -119,6 +157,12 @@ export class SheetSkeleton extends Skeleton {private _columnWidthAccumulation: number[] = [];private _marginTop: number = 0;private _marginLeft: number = 0;++ /**+ * Runtime gap configuration for visual row/column separators.+ */+ private _gapConfig: ISheetGapConfig = {};+/** Scale of Scene */protected _scaleX: number = 1;protected _scaleY: number = 1;@@ -213,6 +257,112 @@ export class SheetSkeleton extends Skeleton {return this._imageCacheMap;}+ // #region Gap Config++ get gapConfig(): ISheetGapConfig {+ return this._gapConfig;+ }++ /**+ * Set runtime gap configuration for visual row/column separators.+ * This triggers a recalculation of the layout (accumulation arrays, etc.).+ */+ setGapConfig(config: ISheetGapConfig): void {+ this._gapConfig = this._fillDefaultGapThemeColors(config);+ this.makeDirty(true);+ this._updateLayout();+ }++ private _fillDefaultGapThemeColors(config: ISheetGapConfig): ISheetGapConfig {+ if (config.defaultBackgroundColor && config.defaultStripeColor) {+ return config;+ }++ const themeService = this._injector.get(ThemeService);+ const baseColor = themeService.getColorFromTheme('primary.500');++ const { r, g, b } = new ColorKit(baseColor).toRgb();++ return {+ ...config,+ defaultBackgroundColor: config.defaultBackgroundColor ?? `rgba(${r}, ${g}, ${b}, 0.08)`,+ defaultStripeColor: config.defaultStripeColor ?? `rgba(${r}, ${g}, ${b}, 0.25)`,+ };+ }++ /**+ * Get the gap size (in px) BEFORE the given row.+ */+ getRowGapSize(row: number): number {+ return this._gapConfig.rowGaps?.[row]?.size ?? 0;+ }++ /**+ * Get the gap size (in px) BEFORE the given column.+ */+ getColGapSize(col: number): number {+ return this._gapConfig.colGaps?.[col]?.size ?? 0;+ }++ /**+ * Returns a gap size getter object for use with coordinate utility functions.+ */+ getGapSizeGetter(): IGapSizeGetter | undefined {+ if (!this._gapConfig.rowGaps && !this._gapConfig.colGaps) {+ return undefined;+ }+ return {+ row: (r: number) => this.getRowGapSize(r),+ col: (c: number) => this.getColGapSize(c),+ };+ }++ /**+ * Check if a Y position (in sheet content coordinates) falls within a row gap.+ * @returns The row index that the gap precedes, or -1 if not in a gap.+ */+ getRowGapAtPosition(y: number): number {+ const { rowGaps } = this._gapConfig;+ if (!rowGaps) return -1;++ for (const rowStr of Object.keys(rowGaps)) {+ const row = Number(rowStr);+ const gapSize = rowGaps[row]?.size ?? 0;+ if (gapSize <= 0) continue;++ const gapStart = this._rowHeightAccumulation[row - 1] ?? 0;+ const gapEnd = gapStart + gapSize;+ if (y >= gapStart && y < gapEnd) {+ return row;+ }+ }+ return -1;+ }++ /**+ * Check if an X position (in sheet content coordinates) falls within a column gap.+ * @returns The column index that the gap precedes, or -1 if not in a gap.+ */+ getColGapAtPosition(x: number): number {+ const { colGaps } = this._gapConfig;+ if (!colGaps) return -1;++ for (const colStr of Object.keys(colGaps)) {+ const col = Number(colStr);+ const gapSize = colGaps[col]?.size ?? 0;+ if (gapSize <= 0) continue;++ const gapStart = this._columnWidthAccumulation[col - 1] ?? 0;+ const gapEnd = gapStart + gapSize;+ if (x >= gapStart && x < gapEnd) {+ return col;+ }+ }+ return -1;+ }++ // #endregion+private _generateRowMatrixCache(rowCount: number,rowData: IObjectArrayPrimitiveType<Partial<IRowData>>,@@ -247,6 +397,10 @@ export class SheetSkeleton extends Skeleton {}}+ // Add gap BEFORE this row (gap appears between row r-1 and row r)+ const gapSize = this._gapConfig.rowGaps?.[r]?.size ?? 0;+ rowTotalHeight += gapSize;+rowTotalHeight += rowHeight;rowHeightAccumulation.push(rowTotalHeight);@@ -289,6 +443,10 @@ export class SheetSkeleton extends Skeleton {}}+ // Add gap BEFORE this column (gap appears between column c-1 and column c)+ const gapSize = this._gapConfig.colGaps?.[c]?.size ?? 0;+ columnTotalWidth += gapSize;+columnTotalWidth += columnWidth;columnWidthAccumulation.push(columnTotalWidth);}@@ -331,7 +489,9 @@ export class SheetSkeleton extends Skeleton {row,column,this.rowHeightAccumulation,- this.columnWidthAccumulation+ this.columnWidthAccumulation,+ undefined,+ this.getGapSizeGetter());// For center alignment, the current cell's width needs to be divided in half for comparison.@@ -367,7 +527,9 @@ export class SheetSkeleton extends Skeleton {row,column,this.rowHeightAccumulation,- this.columnWidthAccumulation+ this.columnWidthAccumulation,+ undefined,+ this.getGapSizeGetter());if (@@ -602,7 +764,9 @@ export class SheetSkeleton extends Skeleton {rowIndex,columnIndex,rowHeightAccumulation,- columnWidthAccumulation+ columnWidthAccumulation,+ undefined,+ this.getGapSizeGetter());if (header) {@@ -778,7 +942,8 @@ export class SheetSkeleton extends Skeleton {column,rowHeightAccumulation,columnWidthAccumulation,- this.worksheet?.getCellInfoInMergeData(row, column)+ this.worksheet?.getCellInfoInMergeData(row, column),+ this.getGapSizeGetter());const { isMerged, isMergedMainCell } = primary;let { startY, endY, startX, endX, mergeInfo } = primary;@@ -1028,24 +1193,30 @@ export class SheetSkeleton extends Skeleton {* @param column* @param rowHeightAccumulation* @param columnWidthAccumulation+ * @param rowGapSize Gap size (px) BEFORE this row. The cell startY is shifted by this amount.+ * @param colGapSize Gap size (px) BEFORE this column. The cell startX is shifted by this amount.*/export function getCellCoordByIndexSimple(row: number,column: number,rowHeightAccumulation: number[],- columnWidthAccumulation: number[]+ columnWidthAccumulation: number[],+ rowGapSize: number = 0,+ colGapSize: number = 0): IPosition {const startRow = row - 1;const startColumn = column - 1;- const startY = rowHeightAccumulation[startRow] || 0;+ // Gap is included in the accumulation before the cell's height.+ // So startY (bottom of prev row) + gap = actual cell top.+ const startY = (rowHeightAccumulation[startRow] || 0) + rowGapSize;let endY = rowHeightAccumulation[row];if (endY == null) {endY = rowHeightAccumulation[rowHeightAccumulation.length - 1];}- const startX = columnWidthAccumulation[startColumn] || 0;+ const startX = (columnWidthAccumulation[startColumn] || 0) + colGapSize;let endX = columnWidthAccumulation[column];if (endX == null) {@@ -1066,7 +1237,8 @@ export function getCellCoordByIndexSimple(* @param {number} column The column index of the cell* @param {number[]} rowHeightAccumulation The accumulated height of each row* @param {number[]} columnWidthAccumulation The accumulated width of each column- * @param {ICellInfo} mergeData The merge information of the cell+ * @param {ICellInfo} mergeDataInfo The merge information of the cell+ * @param {IGapSizeGetter} gapSizeGetter Optional getter for gap sizes before specific rows/columns* @returns {ICellWithCoord} The cell position information of the specified row and column, including the position information of the cell and the merge information of the cell*/// eslint-disable-next-line max-lines-per-function@@ -1075,7 +1247,8 @@ export function getCellWithCoordByIndexCore(column: number,rowHeightAccumulation: number[],columnWidthAccumulation: number[],- mergeDataInfo: Nullable<ICellInfo>+ mergeDataInfo: Nullable<ICellInfo>,+ gapSizeGetter?: IGapSizeGetter): ICellWithCoord {row = Tools.clamp(row, 0, rowHeightAccumulation.length - 1);column = Tools.clamp(column, 0, columnWidthAccumulation.length - 1);@@ -1084,7 +1257,9 @@ export function getCellWithCoordByIndexCore(row,column,rowHeightAccumulation,- columnWidthAccumulation+ columnWidthAccumulation,+ gapSizeGetter?.row(row) ?? 0,+ gapSizeGetter?.col(column) ?? 0);if (!mergeDataInfo) {@@ -1134,12 +1309,14 @@ export function getCellWithCoordByIndexCore(const columnAccumulationCount = columnWidthAccumulation.length - 1;if (isMerged && startRow !== -1 && startColumn !== -1) {- const mergeStartY = rowHeightAccumulation[startRow - 1] || 0;+ const mergeRowGapSize = gapSizeGetter?.row(startRow) ?? 0;+ const mergeColGapSize = gapSizeGetter?.col(startColumn) ?? 0;+ const mergeStartY = (rowHeightAccumulation[startRow - 1] || 0) + mergeRowGapSize;const mergeEndY =rowHeightAccumulation[endRow] ||rowHeightAccumulation[rowAccumulationCount];- const mergeStartX = columnWidthAccumulation[startColumn - 1] || 0;+ const mergeStartX = (columnWidthAccumulation[startColumn - 1] || 0) + mergeColGapSize;const mergeEndX =columnWidthAccumulation[endColumn] ||columnWidthAccumulation[columnAccumulationCount];diff --git a/packages/engine-render/src/components/sheets/__tests__/spreadsheet.gap.spec.ts b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.gap.spec.tsnew file mode 100644index 0000000000..bcb93f5278--- /dev/null+++ b/packages/engine-render/src/components/sheets/__tests__/spreadsheet.gap.spec.ts@@ -0,0 +1,250 @@+/**+ * 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 { describe, expect, it, vi } from 'vitest';+import { Spreadsheet } from '../spreadsheet';++interface IGapMockContext {+ clearRectByPrecision: ReturnType<typeof vi.fn>;+ save: ReturnType<typeof vi.fn>;+ restore: ReturnType<typeof vi.fn>;+ beginPath: ReturnType<typeof vi.fn>;+ rectByPrecision: ReturnType<typeof vi.fn>;+ clip: ReturnType<typeof vi.fn>;+ moveTo: ReturnType<typeof vi.fn>;+ lineTo: ReturnType<typeof vi.fn>;+ stroke: ReturnType<typeof vi.fn>;+ fillRectByPrecision: ReturnType<typeof vi.fn>;+ fillStyle: string;+ strokeStyle: string;+ lineWidth: number;+}++interface IGapConfigShape {+ defaultBackgroundColor?: string;+ defaultStripeColor?: string;+ rowGaps?: Record<number, { size: number; color?: string; stripeColor?: string }>;+ colGaps?: Record<number, { size: number; color?: string; stripeColor?: string }>;+}++interface IGapSkeletonShape {+ gapConfig?: IGapConfigShape;+ rowHeightAccumulation: number[];+ columnWidthAccumulation: number[];+}++interface ISpreadsheetPrivateMethods {+ _drawSingleGapRect: (+ ctx: IGapMockContext,+ gapItem: { size: number; color?: string; stripeColor?: string },+ x: number,+ y: number,+ w: number,+ h: number,+ defaultBg: string,+ defaultStripe: string+ ) => void;+ _drawGapAreas: (+ ctx: IGapMockContext,+ spreadsheetSkeleton: IGapSkeletonShape,+ rowStart: number,+ rowEnd: number,+ columnStart: number,+ columnEnd: number,+ viewStartX: number,+ viewEndX: number,+ viewStartY: number,+ viewEndY: number+ ) => void;+}++function createCtx() {+ return {+ clearRectByPrecision: vi.fn(),+ save: vi.fn(),+ restore: vi.fn(),+ beginPath: vi.fn(),+ rectByPrecision: vi.fn(),+ clip: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),+ stroke: vi.fn(),+ fillRectByPrecision: vi.fn(),+ fillStyle: '',+ strokeStyle: '',+ lineWidth: 0,+ } as IGapMockContext;+}++describe('spreadsheet gap drawing', () => {+ it('draws a single gap with item colors', () => {+ const spreadsheet = new Spreadsheet('sheet-gap-test');+ const spreadsheetPrivate = spreadsheet as unknown as ISpreadsheetPrivateMethods;+ const ctx = createCtx();+ const fillStyles: string[] = [];+ const strokeStyles: string[] = [];++ ctx.fillRectByPrecision = vi.fn(() => {+ fillStyles.push(ctx.fillStyle);+ });+ ctx.stroke = vi.fn(() => {+ strokeStyles.push(ctx.strokeStyle);+ });++ spreadsheetPrivate._drawSingleGapRect(+ ctx,+ { size: 6, color: 'rgba(1,2,3,0.2)', stripeColor: 'rgba(4,5,6,0.4)' },+ 10,+ 20,+ 30,+ 40,+ 'rgba(100,100,100,0.08)',+ 'rgba(100,100,100,0.25)'+ );++ expect(ctx.clearRectByPrecision).toHaveBeenCalledWith(10, 20, 30, 40);+ expect(fillStyles).toContain('rgba(1,2,3,0.2)');+ expect(strokeStyles).toContain('rgba(4,5,6,0.4)');+ expect(ctx.moveTo).toHaveBeenCalled();+ expect(ctx.lineTo).toHaveBeenCalled();++ spreadsheet.dispose();+ });++ it('draws a single gap with default colors when item colors are missing', () => {+ const spreadsheet = new Spreadsheet('sheet-gap-test-default');+ const spreadsheetPrivate = spreadsheet as unknown as ISpreadsheetPrivateMethods;+ const ctx = createCtx();+ const fillStyles: string[] = [];+ const strokeStyles: string[] = [];++ ctx.fillRectByPrecision = vi.fn(() => {+ fillStyles.push(ctx.fillStyle);+ });+ ctx.stroke = vi.fn(() => {+ strokeStyles.push(ctx.strokeStyle);+ });++ spreadsheetPrivate._drawSingleGapRect(+ ctx,+ { size: 4 },+ 0,+ 0,+ 20,+ 10,+ 'rgba(11,22,33,0.08)',+ 'rgba(11,22,33,0.25)'+ );++ expect(fillStyles).toContain('rgba(11,22,33,0.08)');+ expect(strokeStyles).toContain('rgba(11,22,33,0.25)');++ spreadsheet.dispose();+ });++ it('draws row and column gaps and skips non-positive gaps', () => {+ const spreadsheet = new Spreadsheet('sheet-gap-area-test');+ const spreadsheetPrivate = spreadsheet as unknown as ISpreadsheetPrivateMethods;+ const ctx = createCtx();+ const drawSpy = vi.spyOn(spreadsheetPrivate, '_drawSingleGapRect').mockImplementation(() => {});++ const skeleton: IGapSkeletonShape = {+ gapConfig: {+ defaultBackgroundColor: 'rgba(11,22,33,0.08)',+ defaultStripeColor: 'rgba(11,22,33,0.25)',+ rowGaps: {+ 0: { size: 0 },+ 1: { size: 6 },+ },+ colGaps: {+ 1: { size: 0 },+ 2: { size: 5 },+ },+ },+ rowHeightAccumulation: [20, 46, 70],+ columnWidthAccumulation: [30, 60, 95],+ };++ spreadsheetPrivate._drawGapAreas(+ ctx,+ skeleton,+ 0,+ 2,+ 0,+ 2,+ 0,+ 200,+ 0,+ 120+ );++ // row gap r=1 and col gap c=2 should be drawn; size=0 entries should be skipped.+ expect(drawSpy).toHaveBeenCalledTimes(2);+ expect(drawSpy).toHaveBeenCalledWith(+ ctx,+ { size: 6 },+ 0,+ 20,+ 200,+ 6,+ 'rgba(11,22,33,0.08)',+ 'rgba(11,22,33,0.25)'+ );+ expect(drawSpy).toHaveBeenCalledWith(+ ctx,+ { size: 5 },+ 60,+ 0,+ 5,+ 120,+ 'rgba(11,22,33,0.08)',+ 'rgba(11,22,33,0.25)'+ );++ spreadsheet.dispose();+ });++ it('does nothing when gap config has no row/column gaps', () => {+ const spreadsheet = new Spreadsheet('sheet-gap-empty-test');+ const spreadsheetPrivate = spreadsheet as unknown as ISpreadsheetPrivateMethods;+ const ctx = createCtx();+ const drawSpy = vi.spyOn(spreadsheetPrivate, '_drawSingleGapRect').mockImplementation(() => {});++ spreadsheetPrivate._drawGapAreas(+ ctx,+ {+ gapConfig: {+ defaultBackgroundColor: 'rgba(11,22,33,0.08)',+ defaultStripeColor: 'rgba(11,22,33,0.25)',+ },+ rowHeightAccumulation: [20],+ columnWidthAccumulation: [30],+ },+ 0,+ 0,+ 0,+ 0,+ 0,+ 100,+ 0,+ 100+ );++ expect(drawSpy).not.toHaveBeenCalled();++ spreadsheet.dispose();+ });+});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 6f7d119e17..d2deacf1f8 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@@ -422,4 +422,71 @@ describe('spreadsheet integration', () => {});noSkeletonSpreadsheet.dispose();});++ it('draws row and column gap areas using defaults from gapConfig', () => {+ const { spreadsheet, skeleton, mainCanvas } = fixture;+ const context = mainCanvas.getContext() as any;++ skeleton.setGapConfig({+ defaultBackgroundColor: 'rgba(11, 22, 33, 0.08)',+ defaultStripeColor: 'rgba(11, 22, 33, 0.25)',+ rowGaps: {+ 1: { size: 6 },+ },+ colGaps: {+ 1: { size: 5 },+ },+ });++ const drawSingleGapRectSpy = vi.spyOn(spreadsheet as any, '_drawSingleGapRect');++ (spreadsheet as any)._drawGapAreas(+ context,+ skeleton,+ 0,+ 3,+ 0,+ 3,+ 0,+ 400,+ 0,+ 240+ );++ expect(drawSingleGapRectSpy).toHaveBeenCalled();+ expect(drawSingleGapRectSpy).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ size: 6 }),+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ 6,+ 'rgba(11, 22, 33, 0.08)',+ 'rgba(11, 22, 33, 0.25)'+ );+ expect(drawSingleGapRectSpy).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ size: 5 }),+ expect.any(Number),+ expect.any(Number),+ 5,+ expect.any(Number),+ 'rgba(11, 22, 33, 0.08)',+ 'rgba(11, 22, 33, 0.25)'+ );++ // Cover fallback branch in _drawSingleGapRect: use default colors when item colors are absent.+ expect(() => {+ (spreadsheet as any)._drawSingleGapRect(+ context,+ { size: 3 },+ 1,+ 2,+ 30,+ 12,+ 'rgba(11, 22, 33, 0.08)',+ 'rgba(11, 22, 33, 0.25)'+ );+ }).not.toThrow();+ });});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.tsindex 7e52100796..500192e566 100644--- a/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.ts+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/column-header-layout.spec.ts@@ -22,6 +22,8 @@ function createCtx() {save: vi.fn(),restore: vi.fn(),beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),moveToByPrecision: vi.fn(),lineToByPrecision: vi.fn(),stroke: vi.fn(),@@ -116,4 +118,80 @@ describe('column header layout extension', () => {expect(ctx.stroke).toHaveBeenCalled();expect(ctx.fillText).toHaveBeenCalled();});++ it('uses gapConfig default colors when drawing column gaps', () => {+ const layout = new ColumnHeaderLayout();+ const ctx = createCtx();+ const fillStyles: string[] = [];+ const strokeStyles: string[] = [];++ ctx.fillRectByPrecision = vi.fn(() => {+ fillStyles.push(ctx.fillStyle);+ });+ ctx.stroke = vi.fn(() => {+ strokeStyles.push(ctx.strokeStyle);+ });++ const skeleton = {+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ columnHeaderHeight: 20,+ rowHeightAccumulation: [20],+ columnWidthAccumulation: [60],+ columnTotalWidth: 60,+ rowTotalHeight: 20,+ gapConfig: {+ defaultBackgroundColor: 'rgba(1, 2, 3, 0.08)',+ defaultStripeColor: 'rgba(4, 5, 6, 0.25)',+ colGaps: {+ 0: { size: 6 },+ },+ },+ worksheet: {+ getSheetId: vi.fn(() => 'sheet-main'),+ },+ } as any;++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton);++ expect(fillStyles).toContain('rgba(1, 2, 3, 0.08)');+ expect(strokeStyles).toContain('rgba(4, 5, 6, 0.25)');+ });++ it('uses gap item custom colors before default colors in column gaps', () => {+ const layout = new ColumnHeaderLayout();+ const ctx = createCtx();+ const fillStyles: string[] = [];+ const strokeStyles: string[] = [];++ ctx.fillRectByPrecision = vi.fn(() => {+ fillStyles.push(ctx.fillStyle);+ });+ ctx.stroke = vi.fn(() => {+ strokeStyles.push(ctx.strokeStyle);+ });++ const skeleton = {+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ columnHeaderHeight: 20,+ rowHeightAccumulation: [20],+ columnWidthAccumulation: [60],+ columnTotalWidth: 60,+ rowTotalHeight: 20,+ gapConfig: {+ defaultBackgroundColor: 'rgba(1, 2, 3, 0.08)',+ defaultStripeColor: 'rgba(4, 5, 6, 0.25)',+ colGaps: {+ 0: { size: 6, color: '#112233', stripeColor: '#334455' },+ },+ },+ worksheet: {+ getSheetId: vi.fn(() => 'sheet-main'),+ },+ } as any;++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton);++ expect(fillStyles).toContain('#112233');+ expect(strokeStyles).toContain('#334455');+ });});diff --git a/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.ts b/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.tsindex 5feaf59e77..cfc17fadac 100644--- a/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.ts+++ b/packages/engine-render/src/components/sheets/extensions/__tests__/row-header-layout.spec.ts@@ -22,6 +22,8 @@ function createCtx() {save: vi.fn(),restore: vi.fn(),beginPath: vi.fn(),+ moveTo: vi.fn(),+ lineTo: vi.fn(),moveToByPrecision: vi.fn(),lineToByPrecision: vi.fn(),stroke: vi.fn(),@@ -116,4 +118,80 @@ describe('row header layout extension', () => {expect(ctx.stroke).toHaveBeenCalled();expect(ctx.fillText).toHaveBeenCalled();});++ it('uses gapConfig default colors when drawing row gaps', () => {+ const layout = new RowHeaderLayout();+ const ctx = createCtx();+ const fillStyles: string[] = [];+ const strokeStyles: string[] = [];++ ctx.fillRectByPrecision = vi.fn(() => {+ fillStyles.push(ctx.fillStyle);+ });+ ctx.stroke = vi.fn(() => {+ strokeStyles.push(ctx.strokeStyle);+ });++ const skeleton = {+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ rowHeaderWidth: 30,+ rowHeightAccumulation: [40],+ columnWidthAccumulation: [30],+ columnTotalWidth: 30,+ rowTotalHeight: 40,+ gapConfig: {+ defaultBackgroundColor: 'rgba(10, 20, 30, 0.08)',+ defaultStripeColor: 'rgba(10, 20, 30, 0.25)',+ rowGaps: {+ 0: { size: 8 },+ },+ },+ worksheet: {+ getSheetId: vi.fn(() => 'sheet-main'),+ },+ } as any;++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton);++ expect(fillStyles).toContain('rgba(10, 20, 30, 0.08)');+ expect(strokeStyles).toContain('rgba(10, 20, 30, 0.25)');+ });++ it('uses gap item custom colors before default colors in row gaps', () => {+ const layout = new RowHeaderLayout();+ const ctx = createCtx();+ const fillStyles: string[] = [];+ const strokeStyles: string[] = [];++ ctx.fillRectByPrecision = vi.fn(() => {+ fillStyles.push(ctx.fillStyle);+ });+ ctx.stroke = vi.fn(() => {+ strokeStyles.push(ctx.strokeStyle);+ });++ const skeleton = {+ rowColumnSegment: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 },+ rowHeaderWidth: 30,+ rowHeightAccumulation: [40],+ columnWidthAccumulation: [30],+ columnTotalWidth: 30,+ rowTotalHeight: 40,+ gapConfig: {+ defaultBackgroundColor: 'rgba(10, 20, 30, 0.08)',+ defaultStripeColor: 'rgba(10, 20, 30, 0.25)',+ rowGaps: {+ 0: { size: 8, color: '#223344', stripeColor: '#556677' },+ },+ },+ worksheet: {+ getSheetId: vi.fn(() => 'sheet-main'),+ },+ } as any;++ layout.draw(ctx, { scaleX: 1, scaleY: 1 } as any, skeleton);++ expect(fillStyles).toContain('#223344');+ expect(strokeStyles).toContain('#556677');+ });});diff --git a/packages/engine-render/src/components/sheets/extensions/column-header-layout.ts b/packages/engine-render/src/components/sheets/extensions/column-header-layout.tsindex d64e63b655..afa050da15 100644--- a/packages/engine-render/src/components/sheets/extensions/column-header-layout.ts+++ b/packages/engine-render/src/components/sheets/extensions/column-header-layout.ts@@ -141,6 +141,7 @@ export class ColumnHeaderLayout extends SheetExtension {ctx.setLineWidthByPrecision(1);ctx.translateWithPrecisionRatio(FIX_ONE_PIXEL_BLUR_OFFSET, FIX_ONE_PIXEL_BLUR_OFFSET);let preColumnPosition = 0;+ const colGaps = spreadsheetSkeleton.gapConfig?.colGaps;// draw each column headerfor (let c = startColumn - 1; c <= endColumn; c++) {@@ -152,6 +153,49 @@ export class ColumnHeaderLayout extends SheetExtension {if (preColumnPosition === columnEndPosition) {continue;// Skip hidden columns}++ // Draw gap area in column header if a gap is configured before this column+ const gapSize = colGaps?.[c]?.size ?? 0;+ if (gapSize > 0) {+ const gapItem = colGaps![c];+ const gapLeft = preColumnPosition;+ const gapRight = preColumnPosition + gapSize;+ // defaultBackgroundColor and defaultStripeColor are guaranteed by SheetSkeleton._fillDefaultGapThemeColors+ const { defaultBackgroundColor = '', defaultStripeColor = '' } = spreadsheetSkeleton.gapConfig || {};+ const defaultBg = defaultBackgroundColor;+ const defaultStripe = defaultStripeColor;++ // Fill gap background+ ctx.save();+ ctx.fillStyle = gapItem.color ?? defaultBg;+ ctx.fillRectByPrecision(gapLeft, 0, gapSize, columnHeaderHeight);+ ctx.restore();++ // Draw diagonal stripes+ ctx.save();+ ctx.beginPath();+ ctx.rectByPrecision(gapLeft, 0, gapSize, columnHeaderHeight);+ ctx.clip();+ ctx.strokeStyle = gapItem.stripeColor ?? defaultStripe;+ ctx.lineWidth = 1;+ ctx.beginPath();+ const spacing = 6;+ for (let d = -columnHeaderHeight; d < gapSize; d += spacing) {+ ctx.moveTo(gapLeft + d, columnHeaderHeight);+ ctx.lineTo(gapLeft + d + columnHeaderHeight, 0);+ }+ ctx.stroke();+ ctx.restore();++ preColumnPosition = gapRight;+ }++ // After gap, the column itself may still be hidden (width = 0)+ if (preColumnPosition >= columnEndPosition) {+ preColumnPosition = columnEndPosition;+ continue;+ }+const cellBound = { left: preColumnPosition, top: 0, right: columnEndPosition, bottom: columnHeaderHeight, width: columnEndPosition - preColumnPosition, height: columnHeaderHeight };const [curColumnCfg, specStyle] = this.getCfgOfCurrentColumn(columnsCfg, headerStyle, c);diff --git a/packages/engine-render/src/components/sheets/extensions/row-header-layout.ts b/packages/engine-render/src/components/sheets/extensions/row-header-layout.tsindex 1e8c12a99f..da7837565d 100644--- a/packages/engine-render/src/components/sheets/extensions/row-header-layout.ts+++ b/packages/engine-render/src/components/sheets/extensions/row-header-layout.ts@@ -140,6 +140,7 @@ export class RowHeaderLayout extends SheetExtension {let preRowPosition = 0;const rowHeightAccumulationLength = rowHeightAccumulation.length;+ const rowGaps = spreadsheetSkeleton.gapConfig?.rowGaps;for (let r = startRow - 1; r <= endRow; r++) {if (r < 0 || r > rowHeightAccumulationLength - 1) {continue;@@ -148,6 +149,49 @@ export class RowHeaderLayout extends SheetExtension {if (preRowPosition === rowEndPosition) {continue; // Skip hidden rows}++ // Draw gap area in row header if a gap is configured before this row+ const gapSize = rowGaps?.[r]?.size ?? 0;+ if (gapSize > 0) {+ const gapItem = rowGaps![r];+ const gapTop = preRowPosition;+ const gapBottom = preRowPosition + gapSize;+ // defaultBackgroundColor and defaultStripeColor are guaranteed by SheetSkeleton._fillDefaultGapThemeColors+ const { defaultBackgroundColor = '', defaultStripeColor = '' } = spreadsheetSkeleton.gapConfig || {};+ const defaultBg = defaultBackgroundColor;+ const defaultStripe = defaultStripeColor;++ // Fill gap background+ ctx.save();+ ctx.fillStyle = gapItem.color ?? defaultBg;+ ctx.fillRectByPrecision(0, gapTop, rowHeaderWidth, gapSize);+ ctx.restore();++ // Draw diagonal stripes+ ctx.save();+ ctx.beginPath();+ ctx.rectByPrecision(0, gapTop, rowHeaderWidth, gapSize);+ ctx.clip();+ ctx.strokeStyle = gapItem.stripeColor ?? defaultStripe;+ ctx.lineWidth = 1;+ ctx.beginPath();+ const spacing = 6;+ for (let d = -gapSize; d < rowHeaderWidth; d += spacing) {+ ctx.moveTo(d, gapBottom);+ ctx.lineTo(d + gapSize, gapTop);+ }+ ctx.stroke();+ ctx.restore();++ preRowPosition = gapBottom;+ }++ // After gap, the row itself may still be hidden (height = 0)+ if (preRowPosition >= rowEndPosition) {+ preRowPosition = rowEndPosition;+ continue;+ }+const cellBound = {left: 0,top: preRowPosition,diff --git a/packages/engine-render/src/components/sheets/spreadsheet.ts b/packages/engine-render/src/components/sheets/spreadsheet.tsindex 94243a5298..84af524495 100644--- a/packages/engine-render/src/components/sheets/spreadsheet.ts+++ b/packages/engine-render/src/components/sheets/spreadsheet.ts@@ -525,7 +525,7 @@ export class Spreadsheet extends SheetComponent {* draw gridlines* @param ctx*/- // eslint-disable-next-line max-lines-per-function+ // eslint-disable-next-line max-lines-per-function, complexityprivate _drawAuxiliary(ctx: UniverRenderingContext2D) {const spreadsheetSkeleton = this.getSkeleton();if (spreadsheetSkeleton == null) {@@ -645,6 +645,9 @@ export class Spreadsheet extends SheetComponent {// clear line of overflow cellthis._clearRectangle(ctx, rowHeightAccumulation, columnWidthAccumulation, overflowCache.toNativeArray());+ // Draw gap areas AFTER merge/overflow clearing so gap visuals are always on top+ this._drawGapAreas(ctx, spreadsheetSkeleton, rowStart, rowEnd, columnStart, columnEnd, startX, endX, startY, endY);+ctx.restore();}@@ -684,6 +687,89 @@ export class Spreadsheet extends SheetComponent {}}+ /**+ * Draw gap areas for row and column gaps.+ * Clears gridlines in gap regions and fills with gap style.+ */+ private _drawGapAreas(+ ctx: UniverRenderingContext2D,+ spreadsheetSkeleton: SpreadsheetSkeleton,+ rowStart: number,+ rowEnd: number,+ columnStart: number,+ columnEnd: number,+ viewStartX: number,+ viewEndX: number,+ viewStartY: number,+ viewEndY: number+ ): void {+ const { gapConfig, rowHeightAccumulation, columnWidthAccumulation } = spreadsheetSkeleton;+ const rowGaps = gapConfig?.rowGaps;+ const colGaps = gapConfig?.colGaps;+ // defaultBackgroundColor and defaultStripeColor are guaranteed to be filled by _fillDefaultGapThemeColors in SheetSkeleton+ const { defaultBackgroundColor = '', defaultStripeColor = '' } = gapConfig || {};+ const defaultBg = defaultBackgroundColor;+ const defaultStripe = defaultStripeColor;++ if (rowGaps) {+ for (let r = rowStart; r <= rowEnd; r++) {+ const gapSize = rowGaps[r]?.size ?? 0;+ if (gapSize <= 0) continue;+ const gapTop = rowHeightAccumulation[r - 1] ?? 0;+ this._drawSingleGapRect(ctx, rowGaps[r], viewStartX, gapTop, viewEndX - viewStartX, gapSize, defaultBg, defaultStripe);+ }+ }++ if (colGaps) {+ for (let c = columnStart; c <= columnEnd; c++) {+ const gapSize = colGaps[c]?.size ?? 0;+ if (gapSize <= 0) continue;+ const gapLeft = columnWidthAccumulation[c - 1] ?? 0;+ this._drawSingleGapRect(ctx, colGaps[c], gapLeft, viewStartY, gapSize, viewEndY - viewStartY, defaultBg, defaultStripe);+ }+ }+ }++ /**+ * Render a single gap rectangle: clear gridlines, fill background, draw diagonal stripes.+ */+ private _drawSingleGapRect(+ ctx: UniverRenderingContext2D,+ gapItem: { size: number; color?: string; stripeColor?: string },+ x: number,+ y: number,+ w: number,+ h: number,+ defaultBg: string,+ defaultStripe: string+ ): void {+ ctx.clearRectByPrecision(x, y, w, h);++ // Fill background+ ctx.save();+ ctx.fillStyle = gapItem.color ?? defaultBg;+ ctx.fillRectByPrecision(x, y, w, h);+ ctx.restore();++ // Draw diagonal stripes+ const stripeColor = gapItem.stripeColor ?? defaultStripe;+ ctx.save();+ ctx.beginPath();+ ctx.rectByPrecision(x, y, w, h);+ ctx.clip();++ ctx.strokeStyle = stripeColor;+ ctx.lineWidth = 1;+ ctx.beginPath();+ const spacing = 6;+ for (let d = -h; d < w; d += spacing) {+ ctx.moveTo(x + d, y + h);+ ctx.lineTo(x + d + h, y);+ }+ ctx.stroke();+ ctx.restore();+ }+testShowRuler(cacheCtx: UniverRenderingContext2D, viewportInfo: IViewportInfo): void {const { cacheBound } = viewportInfo;const spreadsheetSkeleton = this.getSkeleton()!;diff --git a/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts b/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.tsindex 1da34e28c5..3969a3383d 100644--- a/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts+++ b/packages/sheets-ui/src/facade/__tests__/f-workbook-worksheet.spec.ts@@ -83,8 +83,8 @@ describe('Test FWorkbook/FWorksheet UI mixin', () => {it('workbook and worksheet render facade methods should use render services and command ids consistently', async () => {const sheetSize = 100;- const rowHeader = { setCustomHeader: vi.fn() };- const columnHeader = { setCustomHeader: vi.fn() };+ const rowHeader = { setCustomHeader: vi.fn(), makeDirty: vi.fn() };+ const columnHeader = { setCustomHeader: vi.fn(), makeDirty: vi.fn() };const mainComponent = { makeDirty: vi.fn() };const visibleRange = { startRow: 1, endRow: 4, startColumn: 2, endColumn: 6 };const visibleRanges = new Map([[SHEET_VIEWPORT_KEY.VIEW_MAIN, visibleRange]]);@@ -124,9 +124,10 @@ describe('Test FWorkbook/FWorksheet UI mixin', () => {showSelection: vi.fn(),};const render = {- components: new Map([+ components: new Map<SHEET_VIEW_KEY, unknown>([[SHEET_VIEW_KEY.ROW, rowHeader],[SHEET_VIEW_KEY.COLUMN, columnHeader],+ [SHEET_VIEW_KEY.MAIN, mainComponent],]),mainComponent,with: vi.fn((service: unknown) => {diff --git a/packages/sheets-ui/src/facade/f-worksheet.ts b/packages/sheets-ui/src/facade/f-worksheet.tsindex 852c5b6177..3e6cde00e1 100644--- a/packages/sheets-ui/src/facade/f-worksheet.ts+++ b/packages/sheets-ui/src/facade/f-worksheet.ts@@ -334,13 +334,9 @@ export class FWorksheetUIMixin extends FWorksheet implements IFWorksheetUIMixinrender.with(SheetSkeletonManagerService).reCalculate();- const mainComponent = render.mainComponent;-- if (!mainComponent) {- throw new Error('Main component not found');- }-- mainComponent.makeDirty();+ render.components.forEach((component) => {+ component.makeDirty?.();+ });return this;}