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): harden row structure updates (#7395)
Univeradaa459b2a4f
diff --git a/e2e/ref-range/ref-range-features.spec.ts b/e2e/ref-range/ref-range-features.spec.tsnew file mode 100644index 0000000000..2b7fc2014a--- /dev/null+++ b/e2e/ref-range/ref-range-features.spec.ts@@ -0,0 +1,156 @@+import type { Page } from '@playwright/test';+import { expect, test } from '@playwright/test';+import * as RefRangeE2EProtocol from '../../examples/src/sheets/ref-range-e2e.protocol';++interface IStructuralCase {+ name: string;+ axis: RefRangeE2EProtocol.FixtureAxis;+ operation: RefRangeE2EProtocol.FixtureOperation;+ index: number;+}++interface IFixtureRequestArguments {+ eventName: string;+ request: RefRangeE2EProtocol.RefRangeE2ERequest;+}++const STRUCTURAL_CASES: IStructuralCase[] = [+ { name: 'insert row', axis: 'row', operation: 'insert', index: 0 },+ { name: 'delete row', axis: 'row', operation: 'delete', index: 0 },+ { name: 'insert column', axis: 'column', operation: 'insert', index: 0 },+ { name: 'delete column', axis: 'column', operation: 'delete', index: 0 },+];++const POPUP_STRUCTURAL_CASES: IStructuralCase[] = [+ { name: 'insert row before popup', axis: 'row', operation: 'insert', index: 0 },+ { name: 'delete row before popup', axis: 'row', operation: 'delete', index: 0 },+ { name: 'insert column before popup', axis: 'column', operation: 'insert', index: 0 },+ { name: 'delete column before popup', axis: 'column', operation: 'delete', index: 0 },+];++const RANGE_FEATURES = [+ 'merge',+ 'protection',+ 'filter',+ 'dataValidation',+ 'conditionalFormatting',+] as const;++const POINT_FEATURES = ['hyperlink', 'note', 'comment'] as const;++function executeFixture<T>(page: Page, request: RefRangeE2EProtocol.RefRangeE2ERequest): Promise<T> {+ return page.evaluate<T, IFixtureRequestArguments>(({ eventName, request: fixtureRequest }) => new Promise((resolve, reject) => {+ window.dispatchEvent(new CustomEvent(eventName, {+ detail: { request: fixtureRequest, resolve, reject },+ }));+ }), {+ eventName: RefRangeE2EProtocol.REF_RANGE_E2E_EVENT,+ request,+ });+}++function snapshot(page: Page): Promise<RefRangeE2EProtocol.IFixtureSnapshot> {+ return executeFixture(page, { action: 'snapshot' });+}++function modelSnapshot(value: RefRangeE2EProtocol.IFixtureSnapshot): Omit<RefRangeE2EProtocol.IFixtureSnapshot, 'popupRect'> {+ return {+ merge: value.merge,+ protection: value.protection,+ filter: value.filter,+ dataValidation: value.dataValidation,+ conditionalFormatting: value.conditionalFormatting,+ hyperlink: value.hyperlink,+ note: value.note,+ comment: value.comment,+ dataValidationFormula: value.dataValidationFormula,+ conditionalFormattingRule: value.conditionalFormattingRule,+ hyperlinkUrl: value.hyperlinkUrl,+ };+}++function expectRangeShift(+ before: RefRangeE2EProtocol.IRangeRecord,+ after: RefRangeE2EProtocol.IRangeRecord,+ testCase: IStructuralCase,+ feature: string+): void {+ const offset = testCase.operation === 'insert' ? 1 : -1;+ if (testCase.axis === 'row') {+ expect(after.startRow, `${testCase.name} ${feature} start row`).toBe(before.startRow + offset);+ expect(after.endRow, `${testCase.name} ${feature} end row`).toBe(before.endRow + offset);+ expect(after.startColumn, `${testCase.name} ${feature} start column`).toBe(before.startColumn);+ expect(after.endColumn, `${testCase.name} ${feature} end column`).toBe(before.endColumn);+ } else {+ expect(after.startColumn, `${testCase.name} ${feature} start column`).toBe(before.startColumn + offset);+ expect(after.endColumn, `${testCase.name} ${feature} end column`).toBe(before.endColumn + offset);+ expect(after.startRow, `${testCase.name} ${feature} start row`).toBe(before.startRow);+ expect(after.endRow, `${testCase.name} ${feature} end row`).toBe(before.endRow);+ }+}++function expectPointShift(+ before: RefRangeE2EProtocol.IPointRecord,+ after: RefRangeE2EProtocol.IPointRecord,+ testCase: IStructuralCase,+ feature: string+): void {+ const offset = testCase.operation === 'insert' ? 1 : -1;+ expect(after.row, `${testCase.name} ${feature} row`).toBe(before.row + (testCase.axis === 'row' ? offset : 0));+ expect(after.column, `${testCase.name} ${feature} column`).toBe(before.column + (testCase.axis === 'column' ? offset : 0));+}++function expectPopupMove(+ before: RefRangeE2EProtocol.IRectRecord,+ after: RefRangeE2EProtocol.IRectRecord,+ testCase: IStructuralCase+): void {+ const primaryPosition = testCase.axis === 'row' ? 'top' : 'left';+ const secondaryPosition = testCase.axis === 'row' ? 'left' : 'top';+ const direction = testCase.operation === 'insert' ? 1 : -1;+ expect(Math.sign(after[primaryPosition] - before[primaryPosition]), `${testCase.name} popup direction`).toBe(direction);+ expect(after[secondaryPosition], `${testCase.name} popup orthogonal position`).toBe(before[secondaryPosition]);+ expect(after.width, `${testCase.name} popup width`).toBe(before.width);+ expect(after.height, `${testCase.name} popup height`).toBe(before.height);+}++test('RefRange consumers stay aligned across row and column edits', async ({ page }) => {+ const pageErrors: string[] = [];+ page.on('pageerror', (error) => pageErrors.push(error.stack ?? error.message));++ await page.setViewportSize({ width: 1600, height: 1200 });+ await page.goto('/sheets/?ref-range-e2e');+ await page.locator(`html[${RefRangeE2EProtocol.REF_RANGE_E2E_READY_ATTRIBUTE}="true"]`).waitFor();+ const initial = await executeFixture<RefRangeE2EProtocol.IFixtureSnapshot>(page, { action: 'setup' });++ for (const testCase of STRUCTURAL_CASES) {+ const before = await snapshot(page);+ await executeFixture<null>(page, { action: 'apply', ...testCase });+ const after = await snapshot(page);++ for (const feature of RANGE_FEATURES) expectRangeShift(before[feature], after[feature], testCase, feature);+ for (const feature of POINT_FEATURES) expectPointShift(before[feature], after[feature], testCase, feature);+ expect(after.dataValidationFormula, `${testCase.name} data validation formula`).not.toBe(before.dataValidationFormula);+ expect(after.conditionalFormattingRule, `${testCase.name} conditional formatting formula`).not.toBe(before.conditionalFormattingRule);+ expect(after.hyperlinkUrl, `${testCase.name} hyperlink target`).not.toBe(before.hyperlinkUrl);+ expect(await executeFixture<boolean>(page, { action: 'undo' })).toBe(true);+ await expect.poll(async () => modelSnapshot(await snapshot(page))).toEqual(modelSnapshot(before));+ }++ await expect.poll(async () => {+ const current = await snapshot(page);+ return current.popupRect.left > 0 && current.popupRect.top > 0;+ }).toBe(true);+ for (const testCase of POPUP_STRUCTURAL_CASES) {+ const before = await snapshot(page);+ await executeFixture<null>(page, { action: 'apply', ...testCase });+ const after = await snapshot(page);+ expectPopupMove(before.popupRect, after.popupRect, testCase);++ expect(await executeFixture<boolean>(page, { action: 'undo' })).toBe(true);+ await expect.poll(() => snapshot(page), { message: `${testCase.name} undo` }).toEqual(before);+ }++ expect(modelSnapshot(await snapshot(page))).toEqual(modelSnapshot(initial));+ expect(pageErrors).toEqual([]);+});diff --git a/examples/src/sheets/main.ts b/examples/src/sheets/main.tsindex 351cb6a04a..9f3a0246e2 100644--- a/examples/src/sheets/main.ts+++ b/examples/src/sheets/main.ts@@ -40,6 +40,7 @@ import '@univerjs/engine-formula/facade';import '@univerjs/sheets-filter/facade';import '@univerjs/sheets-formula/facade';import '@univerjs/sheets-numfmt/facade';+import '@univerjs/sheets-hyper-link/facade';import '@univerjs/sheets-hyper-link-ui/facade';import '@univerjs/sheets-thread-comment/facade';import '@univerjs/sheets-conditional-formatting/facade';@@ -163,16 +164,22 @@ function createNewInstance() {});window.univer = univer;- window.univerAPI = FUniver.newAPI(univer);+ const univerAPI = FUniver.newAPI(univer);+ window.univerAPI = univerAPI;+ if (IS_E2E && new URLSearchParams(window.location.search).has('ref-range-e2e')) {+ import('./ref-range-e2e').then(({ installRefRangeE2EFixture }) => {+ installRefRangeE2EFixture(univer, univerAPI);+ });+ }// window.univerAPI.addFonts([// { value: 'PingFang SC', label: '苹方(简)', category: 'sans-serif' },// { value: 'Helvetica Neue', label: 'Helvetica Neue', category: 'sans-serif' },// ]);- customRegisterEvent(univer, window.univerAPI!);+ customRegisterEvent(univer, univerAPI);// customRangePopups(univer, window.univerAPI!);- simpleRangePopupDemo(univer, window.univerAPI!);- insertFloatDom(univer, window.univerAPI!);+ simpleRangePopupDemo(univer, univerAPI);+ insertFloatDom(univer, univerAPI);}createNewInstance();diff --git a/examples/src/sheets/ref-range-e2e.protocol.ts b/examples/src/sheets/ref-range-e2e.protocol.tsnew file mode 100644index 0000000000..435933899d--- /dev/null+++ b/examples/src/sheets/ref-range-e2e.protocol.ts@@ -0,0 +1,51 @@+export const REF_RANGE_E2E_EVENT = 'univer-ref-range-feature-e2e-request';+export const REF_RANGE_E2E_READY_ATTRIBUTE = 'data-univer-ref-range-feature-e2e-ready';++export type FixtureAxis = 'row' | 'column';+export type FixtureOperation = 'insert' | 'delete';++export interface IRangeRecord {+ startRow: number;+ endRow: number;+ startColumn: number;+ endColumn: number;+}++export interface IPointRecord {+ row: number;+ column: number;+}++export interface IRectRecord {+ left: number;+ top: number;+ width: number;+ height: number;+}++export interface IFixtureSnapshot {+ merge: IRangeRecord;+ protection: IRangeRecord;+ filter: IRangeRecord;+ dataValidation: IRangeRecord;+ conditionalFormatting: IRangeRecord;+ hyperlink: IPointRecord;+ note: IPointRecord;+ comment: IPointRecord;+ dataValidationFormula: string | undefined;+ conditionalFormattingRule: string;+ hyperlinkUrl: string;+ popupRect: IRectRecord;+}++export type RefRangeE2ERequest =+ | { action: 'setup' }+ | { action: 'snapshot' }+ | { action: 'apply'; axis: FixtureAxis; operation: FixtureOperation; index: number }+ | { action: 'undo' };++export interface IRefRangeE2ERequestDetail {+ request: RefRangeE2ERequest;+ resolve: (value: unknown) => void;+ reject: (reason: unknown) => void;+}diff --git a/examples/src/sheets/ref-range-e2e.tsx b/examples/src/sheets/ref-range-e2e.tsxnew file mode 100644index 0000000000..a28da0f54b--- /dev/null+++ b/examples/src/sheets/ref-range-e2e.tsx@@ -0,0 +1,259 @@+import type { IRange, IWorkbookData, Univer } from '@univerjs/core';+import type { FUniver } from '@univerjs/core/facade';+import type { FWorksheet } from '@univerjs/sheets/facade';+import { LocaleType, UndoCommand, UniverInstanceType } from '@univerjs/core';+import { ICanvasPopupService } from '@univerjs/ui';+import * as RefRangeE2EProtocol from './ref-range-e2e.protocol';++const FIXTURE_COMPONENT_KEY = 'RefRangeFeaturePopupProbe';+const FIXTURE_UNIT_ID = 'ref-range-feature-e2e-unit';+const FIXTURE_SHEET_ID = 'ref-range-feature-e2e-sheet';++function RefRangeFeaturePopupProbe() {+ return (+ <div+ data-ref-range-feature-popup="true"+ style={{ width: 80, height: 32 }}+ />+ );+}++function createWorkbookData(): IWorkbookData {+ return {+ id: FIXTURE_UNIT_ID,+ appVersion: '3.0.0-alpha',+ locale: LocaleType.EN_US,+ name: 'RefRange Feature E2E',+ sheetOrder: [FIXTURE_SHEET_ID],+ styles: {},+ sheets: {+ [FIXTURE_SHEET_ID]: {+ id: FIXTURE_SHEET_ID,+ name: 'Feature Matrix',+ rowCount: 120,+ columnCount: 30,+ cellData: {+ 1: { 1: { v: 1 } },+ 15: { 3: { v: 'Region' }, 4: { v: 'Sales' }, 5: { v: 'Enabled' } },+ 16: { 3: { v: 'East' }, 4: { v: 20 }, 5: { v: true } },+ 17: { 3: { v: 'West' }, 4: { v: 30 }, 5: { v: true } },+ },+ },+ },+ };+}++function waitForRender(): Promise<void> {+ return new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));+}++function rangeRecord(range: IRange): RefRangeE2EProtocol.IRangeRecord {+ return {+ startRow: range.startRow,+ endRow: range.endRow,+ startColumn: range.startColumn,+ endColumn: range.endColumn,+ };+}++function isRequestDetail(value: unknown): value is RefRangeE2EProtocol.IRefRangeE2ERequestDetail {+ return typeof value === 'object' && value !== null &&+ 'request' in value &&+ 'resolve' in value && typeof value.resolve === 'function' &&+ 'reject' in value && typeof value.reject === 'function';+}++function requireSingle<T>(values: T[], feature: string): T {+ if (values.length !== 1) throw new Error(`Expected one ${feature}, received ${values.length}`);+ return values[0];+}++class RefRangeE2EFixture {+ private _isSetup = false;++ constructor(+ private readonly _univer: Univer,+ private readonly _univerAPI: FUniver,+ private readonly _canvasPopupService: ICanvasPopupService+ ) {}++ install(): void {+ this._univerAPI.registerComponent(FIXTURE_COMPONENT_KEY, RefRangeFeaturePopupProbe);+ window.addEventListener(RefRangeE2EProtocol.REF_RANGE_E2E_EVENT, this._onRequest);+ document.documentElement.setAttribute(RefRangeE2EProtocol.REF_RANGE_E2E_READY_ATTRIBUTE, 'true');+ }++ private readonly _onRequest = (event: Event): void => {+ if (!(event instanceof CustomEvent) || !isRequestDetail(event.detail)) return;+ this._execute(event.detail.request).then(event.detail.resolve, event.detail.reject);+ };++ private async _execute(request: RefRangeE2EProtocol.RefRangeE2ERequest): Promise<unknown> {+ switch (request.action) {+ case 'setup':+ return this._setup();+ case 'snapshot':+ return this._snapshot();+ case 'apply':+ await this._apply(request.axis, request.operation, request.index);+ return null;+ case 'undo':+ return Boolean(await this._univerAPI.executeCommand(UndoCommand.id));+ }+ }++ private async _setup(): Promise<RefRangeE2EProtocol.IFixtureSnapshot> {+ if (this._isSetup) return this._snapshot();++ await new Promise((resolve) => setTimeout(resolve, 500));+ this._univer.createUnit(UniverInstanceType.UNIVER_SHEET, createWorkbookData());+ await waitForRender();+ await new Promise((resolve) => setTimeout(resolve, 200));+ const sheet = this._requireSheet();++ sheet.getRange('D10:E11').merge();+ await sheet.getRange('G10:H11').getRangePermission().protect({ name: 'RefRange E2E protection' });+ if (!sheet.getRange('D16:F22').createFilter()) throw new Error('Failed to create E2E filter');++ const dataValidation = this._univerAPI.newDataValidation()+ .requireFormulaSatisfied('=B2>0')+ .build();+ sheet.getRange('D26:E27').setDataValidation(dataValidation);++ const conditionalFormatting = sheet.newConditionalFormattingRule()+ .whenFormulaSatisfied('=B2>0')+ .setBackground('#fef3c7')+ .setRanges([sheet.getRange('G26:H27').getRange()])+ .build();+ sheet.addConditionalFormattingRule(conditionalFormatting);++ await sheet.getRange('D32').setHyperLink(sheet.getRange('G32:H33').getUrl(), 'Target range');+ sheet.getRange('D36').createOrUpdateNote({+ note: 'RefRange E2E note',+ width: 160,+ height: 80,+ show: false,+ });+ const comment = this._univerAPI.newTheadComment()+ .setId('ref-range-e2e-comment')+ .setContent(this._univerAPI.newRichText().insertText('RefRange E2E comment'));+ if (!await sheet.getRange('G36').addCommentAsync(comment)) throw new Error('Failed to create E2E comment');++ await this._waitForCellRect(sheet);+ const popup = sheet.getRange('D4:E5').attachRangePopup({+ componentKey: FIXTURE_COMPONENT_KEY,+ direction: 'bottom-center',+ });+ if (!popup) throw new Error('Failed to attach E2E range popup');+ this._univerAPI.getActiveWorkbook()?.setActiveRange(sheet.getRange('D4:E5'));++ this._isSetup = true;+ await waitForRender();+ return this._snapshot();+ }++ private async _snapshot(): Promise<RefRangeE2EProtocol.IFixtureSnapshot> {+ const sheet = this._requireSheet();+ const merge = requireSingle(sheet.getMergedRanges(), 'merged range');+ const protection = requireSingle(+ await sheet.getWorksheetPermission().listRangeProtectionRules({ ignoreCollaborators: true }),+ 'range protection'+ );+ const filter = sheet.getFilter();+ if (!filter) throw new Error('E2E filter is missing');+ const dataValidation = requireSingle(sheet.getDataValidations(), 'data validation');+ const conditionalFormatting = requireSingle(sheet.getConditionalFormattingRules(), 'conditional formatting rule');+ const hyperlink = requireSingle(sheet.getRange('A1:Z60').getHyperLinks(), 'hyperlink');+ const note = requireSingle(sheet.getNotes(), 'note');+ const comment = this._findComment(sheet);+ const popupRect = this._getPopupRect();++ return {+ merge: rangeRecord(merge.getRange()),+ protection: rangeRecord(requireSingle(protection.ranges, 'protected range').getRange()),+ filter: rangeRecord(filter.getRange().getRange()),+ dataValidation: rangeRecord(requireSingle(dataValidation.rule.ranges, 'data validation range')),+ conditionalFormatting: rangeRecord(requireSingle(conditionalFormatting.ranges, 'conditional formatting range')),+ hyperlink: { row: hyperlink.row, column: hyperlink.column },+ note: { row: note.row, column: note.col },+ comment,+ dataValidationFormula: dataValidation.getCriteriaValues()[1],+ conditionalFormattingRule: JSON.stringify(conditionalFormatting.rule),+ hyperlinkUrl: hyperlink.url,+ popupRect: {+ ...popupRect,+ },+ };+ }++ private async _apply(+ axis: RefRangeE2EProtocol.FixtureAxis,+ operation: RefRangeE2EProtocol.FixtureOperation,+ index: number+ ): Promise<void> {+ const sheet = this._requireSheet();+ if (axis === 'row') {+ if (operation === 'insert') sheet.insertRowBefore(index);+ else sheet.deleteRow(index);+ } else if (operation === 'insert') {+ sheet.insertColumnBefore(index);+ } else {+ sheet.deleteColumn(index);+ }+ await waitForRender();+ }++ private _getPopupRect(): RefRangeE2EProtocol.IRectRecord {+ const popup = requireSingle(+ this._canvasPopupService.popups+ .map(([, item]) => item)+ .filter((item) => item.componentKey === FIXTURE_COMPONENT_KEY),+ 'range popup'+ );+ let popupAnchor = popup.anchorRect;+ const popupSubscription = popup.anchorRect$.subscribe((anchor) => {+ popupAnchor = anchor;+ });+ popupSubscription.unsubscribe();+ if (!popupAnchor) throw new Error('E2E popup anchor is missing');+ return {+ left: popupAnchor.left,+ top: popupAnchor.top,+ width: popupAnchor.right - popupAnchor.left,+ height: popupAnchor.bottom - popupAnchor.top,+ };+ }++ private async _waitForCellRect(sheet: FWorksheet): Promise<void> {+ const deadline = Date.now() + 2_000;+ while (Date.now() < deadline) {+ const rect = sheet.getRange('D4').getCellRect();+ if (rect.left > 0 && rect.top > 0 && rect.width > 0 && rect.height > 0) return;+ await new Promise((resolve) => setTimeout(resolve, 20));+ }+ throw new Error('Timed out waiting for E2E sheet skeleton');+ }++ private _findComment(sheet: FWorksheet): RefRangeE2EProtocol.IPointRecord {+ for (let row = 30; row < 45; row++) {+ for (let column = 0; column < 10; column++) {+ if (sheet.getRange(row, column).getComment()?.getCommentData().id === 'ref-range-e2e-comment') {+ return { row, column };+ }+ }+ }+ throw new Error('E2E comment is missing');+ }++ private _requireSheet(): FWorksheet {+ const sheet = this._univerAPI.getActiveWorkbook()?.getActiveSheet();+ if (!sheet) throw new Error('RefRange E2E sheet is not active');+ return sheet;+ }+}++export function installRefRangeE2EFixture(univer: Univer, univerAPI: FUniver): void {+ const injector = univer.__getInjector();+ const canvasPopupService = injector.get(ICanvasPopupService);+ new RefRangeE2EFixture(univer, univerAPI, canvasPopupService).install();+}diff --git a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts b/packages/sheets/src/facade/__tests__/f-worksheet.spec.tsindex 58b77c687d..6e17826608 100644--- a/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts+++ b/packages/sheets/src/facade/__tests__/f-worksheet.spec.ts@@ -320,6 +320,42 @@ describe('Test FWorksheet', () => {expect(sheet?.getMaxRows()).toBe(102);});+ it('Worksheet inserts rows after the last valid row index', () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getSheetByName('sheet1')!;+ const rowCount = activeSheet.getMaxRows();++ activeSheet.insertRowsAfter(rowCount - 1, 30);++ expect(activeSheet.getMaxRows()).toBe(rowCount + 30);+ });++ it('Worksheet rejects invalid row insertion indexes with actionable errors', () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getSheetByName('sheet1')!;+ const rowCount = activeSheet.getMaxRows();+ const executeCommand = vi.spyOn(commandService, 'syncExecuteCommand');++ expect(() => activeSheet.insertRows(rowCount, 30)).toThrowError(+ `insertRows(): row index ${rowCount} is out of bounds. ` ++ `The worksheet has ${rowCount} rows; expected an integer from 0 to ${rowCount - 1}. ` ++ `To insert 30 row(s) at the bottom, use insertRowsAfter(${rowCount - 1}, 30). ` ++ `To resize the worksheet directly, use setRowCount(${rowCount + 30}).`+ );+ expect(() => activeSheet.insertRowsAfter(-1, 1)).toThrowError(/expected an integer from 0 to 99/);+ expect(() => activeSheet.insertRowAfter(rowCount)).toThrowError(/insertRowsAfter\(\): row index 100/);+ expect(() => activeSheet.insertRowBefore(-1)).toThrowError(/insertRowsBefore\(\): row index -1/);+ expect(executeCommand).not.toHaveBeenCalled();+ });++ it('Worksheet rejects invalid row insertion counts', () => {+ const activeSheet = univerAPI.getActiveWorkbook()!.getSheetByName('sheet1')!;+ const executeCommand = vi.spyOn(commandService, 'syncExecuteCommand');++ expect(() => activeSheet.insertRows(0, 0)).toThrowError('insertRows(): row count 0 must be a positive integer.');+ expect(() => activeSheet.insertRowsBefore(0, -1)).toThrowError('insertRowsBefore(): row count -1 must be a positive integer.');+ expect(() => activeSheet.insertRowsAfter(0, 1.5)).toThrowError('insertRowsAfter(): row count 1.5 must be a positive integer.');+ expect(executeCommand).not.toHaveBeenCalled();+ });+it('Worksheet deleteRow', async () => {const activeSheet = univerAPI.getActiveWorkbook()?.getSheetByName('sheet1');@@ -629,10 +665,17 @@ describe('Test FWorksheet', () => {it('Worksheet appends rows and updates sheet dimensions through facade APIs', () => {const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();+ const initialMaxRows = activeSheet.getMaxRows();const initialLastRow = activeSheet.getLastRow();activeSheet.appendRow(['North', 100, true]);expect(activeSheet.getRange(initialLastRow + 1, 0, 1, 3).getValues()).toEqual([['North', 100, 1]]);expect(activeSheet.getDataRange().getA1Notation()).toBe(`A1:C${initialLastRow + 2}`);+ expect(activeSheet.getMaxRows()).toBe(initialMaxRows);++ activeSheet.getRange(initialMaxRows - 1, 0).setValue('at capacity');+ activeSheet.appendRow(['expanded']);+ expect(activeSheet.getMaxRows()).toBe(initialMaxRows + 1);+ expect(activeSheet.getRange(initialMaxRows, 0).getValue()).toBe('expanded');activeSheet.setRowCount(120);activeSheet.setColumnCount(80);diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.tsindex 278ae1df5e..98b08721a4 100644--- a/packages/sheets/src/facade/f-worksheet.ts+++ b/packages/sheets/src/facade/f-worksheet.ts@@ -97,6 +97,22 @@ import { FSelection } from './f-selection';import { FWorksheetPermission } from './permission/f-worksheet-permission';import { covertToColRange, covertToRowRange } from './utils';+function assertValidRowInsertion(methodName: string, rowIndex: number, rowCount: number, howMany: number): void {+ if (!Number.isInteger(howMany) || howMany <= 0) {+ throw new RangeError(`${methodName}(): row count ${howMany} must be a positive integer.`);+ }++ const lastRowIndex = rowCount - 1;+ if (!Number.isInteger(rowIndex) || rowIndex < 0 || rowIndex > lastRowIndex) {+ throw new RangeError(+ `${methodName}(): row index ${rowIndex} is out of bounds. ` ++ `The worksheet has ${rowCount} rows; expected an integer from 0 to ${lastRowIndex}. ` ++ `To insert ${howMany} row(s) at the bottom, use insertRowsAfter(${lastRowIndex}, ${howMany}). ` ++ `To resize the worksheet directly, use setRowCount(${rowCount + howMany}).`+ );+ }+}+export interface IFacadeClearOptions {contentsOnly?: boolean;formatOnly?: boolean;@@ -536,7 +552,7 @@ export class FWorksheet extends FBaseInitialable {/*** Inserts a row after the given row position.- * @param {number} afterPosition - The row after which the new row should be added, starting at 0 for the first row.+ * @param {number} afterPosition - The existing row after which the new row should be added. The index is zero-based and must be between 0 and `getMaxRows() - 1`.* @returns {FWorksheet} This sheet, for chaining.* @example* ```typescript@@ -554,7 +570,7 @@ export class FWorksheet extends FBaseInitialable {/*** Inserts a row before the given row position.- * @param {number} beforePosition - The row before which the new row should be added, starting at 0 for the first row.+ * @param {number} beforePosition - The existing row before which the new row should be added. The index is zero-based and must be between 0 and `getMaxRows() - 1`.* @returns {FWorksheet} This sheet, for chaining.* @example* ```typescript@@ -572,8 +588,8 @@ export class FWorksheet extends FBaseInitialable {/*** Inserts one or more consecutive blank rows in a sheet starting at the specified location.- * @param {number} rowIndex - The index indicating where to insert a row, starting at 0 for the first row.- * @param {number} numRows - The number of rows to insert.+ * @param {number} rowIndex - The existing row before which rows are inserted. The index is zero-based and must be between 0 and `getMaxRows() - 1`.+ * @param {number} numRows - The positive number of rows to insert.* @returns {FWorksheet} This sheet, for chaining.* @example* ```typescript@@ -586,13 +602,14 @@ export class FWorksheet extends FBaseInitialable {* ```*/insertRows(rowIndex: number, numRows: number = 1): FWorksheet {+ assertValidRowInsertion('insertRows', rowIndex, this.getMaxRows(), numRows);return this.insertRowsBefore(rowIndex, numRows);}/*** Inserts a number of rows after the given row position.- * @param {number} afterPosition - The row after which the new rows should be added, starting at 0 for the first row.- * @param {number} howMany - The number of rows to insert.+ * @param {number} afterPosition - The existing row after which the new rows should be added. The index is zero-based and must be between 0 and `getMaxRows() - 1`.+ * @param {number} howMany - The positive number of rows to insert.* @returns {FWorksheet} This sheet, for chaining.* @example* ```typescript@@ -605,6 +622,8 @@ export class FWorksheet extends FBaseInitialable {* ```*/insertRowsAfter(afterPosition: number, howMany: number): FWorksheet {+ assertValidRowInsertion('insertRowsAfter', afterPosition, this.getMaxRows(), howMany);+const unitId = this._workbook.getUnitId();const subUnitId = this._worksheet.getSheetId();const direction = Direction.DOWN;@@ -635,8 +654,8 @@ export class FWorksheet extends FBaseInitialable {/*** Inserts a number of rows before the given row position.- * @param {number} beforePosition - The row before which the new rows should be added, starting at 0 for the first row.- * @param {number} howMany - The number of rows to insert.+ * @param {number} beforePosition - The existing row before which the new rows should be added. The index is zero-based and must be between 0 and `getMaxRows() - 1`.+ * @param {number} howMany - The positive number of rows to insert.* @returns {FWorksheet} This sheet, for chaining.* @example* ```typescript@@ -649,6 +668,8 @@ export class FWorksheet extends FBaseInitialable {* ```*/insertRowsBefore(beforePosition: number, howMany: number): FWorksheet {+ assertValidRowInsertion('insertRowsBefore', beforePosition, this.getMaxRows(), howMany);+const unitId = this._workbook.getUnitId();const subUnitId = this._worksheet.getSheetId();const direction = Direction.UP;@@ -2650,7 +2671,8 @@ export class FWorksheet extends FBaseInitialable {}/**- * Appends a row to the bottom of the current data region in the sheet. If a cell's content begins with =, it's interpreted as a formula.+ * Appends a row to the bottom of the current data region in the sheet. If the destination row is already within the worksheet capacity,+ * this method writes into that row without increasing `getMaxRows()`. If a cell's content begins with =, it's interpreted as a formula.* @param {CellValue[]} rowContents - An array of values for the new row.* @returns {FWorksheet} Returns the current worksheet instance for method chaining.* @examplediff --git a/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts b/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.tsindex cb30dfc4b5..800ad26438 100644--- a/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts+++ b/packages/sheets/src/services/ref-range/__tests__/ref-range.service.spec.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import type { Dependency, ICommand, IRange, IWorkbookData, Nullable, Workbook } from '@univerjs/core';+import type { Dependency, ICommand, IDisposable, IRange, IWorkbookData, Nullable, Workbook } from '@univerjs/core';import type { IInsertColMutationParams } from '../../../basics';import { ICommandService, ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { InsertColMutation } from '../../../commands/mutations/insert-row-col.mutation';import { SheetsSelectionsService } from '../../selections/selection.service';import { SheetInterceptorService } from '../../sheet-interceptor/sheet-interceptor.service';@@ -162,5 +162,135 @@ describe('test "RefRangeService"', () => {expect(beforeRange).toBeNull();expect(afterRange).toBeNull();});++ it('should keep one command listener after watchers are disposed out of registration order', () => {+ const watchedRange: IRange = { startRow: 0, startColumn: 1, endColumn: 3, endRow: 0 };++ for (let i = 0; i < 3; i++) {+ const first = refRangeService.watchRange('test', 'sheet1', watchedRange, () => {});+ const second = refRangeService.watchRange('test', 'sheet1', watchedRange, () => {});+ first.dispose();+ second.dispose();+ }++ const callback = vi.fn();+ refRangeService.watchRange('test', 'sheet1', watchedRange, callback);++ expect(commandService.syncExecuteCommand(InsertColMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 2 },+ })).toBeTruthy();+ expect(callback).toHaveBeenCalledOnce();+ expect(callback).toHaveBeenCalledWith(watchedRange, {+ startRow: 0,+ startColumn: 1,+ endColumn: 4,+ endRow: 0,+ });+ });++ it('should not notify a replacement watcher for the mutation that registered it', () => {+ const watchedRange: IRange = { startRow: 0, startColumn: 1, endColumn: 3, endRow: 0 };+ const replacementCallback = vi.fn();+ let primaryDisposable: IDisposable;+ let replacementDisposable: IDisposable | undefined;+ const primaryCallback = vi.fn((_before: IRange, after: Nullable<IRange>) => {+ if (!after) {+ throw new Error('Expected the watched range to survive column insertion');+ }+ replacementDisposable = refRangeService.watchRange('test', 'sheet1', after, replacementCallback);+ primaryDisposable.dispose();+ });+ primaryDisposable = refRangeService.watchRange('test', 'sheet1', watchedRange, primaryCallback);+ const insertParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 2 },+ };++ expect(commandService.syncExecuteCommand(InsertColMutation.id, insertParams)).toBeTruthy();+ expect(primaryCallback).toHaveBeenCalledOnce();+ expect(replacementCallback).not.toHaveBeenCalled();++ expect(commandService.syncExecuteCommand(InsertColMutation.id, insertParams)).toBeTruthy();+ expect(primaryCallback).toHaveBeenCalledOnce();+ expect(replacementCallback).toHaveBeenCalledOnce();+ replacementDisposable?.dispose();+ });++ it('should not notify a pending watcher after another callback disposes it', () => {+ const watchedRange: IRange = { startRow: 0, startColumn: 1, endColumn: 3, endRow: 0 };+ let pendingDisposable: IDisposable;+ const firstCallback = vi.fn(() => pendingDisposable.dispose());+ const pendingCallback = vi.fn();+ refRangeService.watchRange('test', 'sheet1', watchedRange, firstCallback);+ pendingDisposable = refRangeService.watchRange('test', 'sheet1', watchedRange, pendingCallback);++ expect(commandService.syncExecuteCommand(InsertColMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 2 },+ })).toBeTruthy();+ expect(firstCallback).toHaveBeenCalledOnce();+ expect(pendingCallback).not.toHaveBeenCalled();+ });++ it('should keep chart-like rebinders and stable float watchers bounded during structural churn', () => {+ const rebindWatcherCount = 64;+ const stableWatcherCount = 64;+ const mutationCount = 200;+ const watchedRange: IRange = { startRow: 0, startColumn: 1, endColumn: 3, endRow: 0 };+ const activeRebinders: IDisposable[] = [];+ const stableWatchers: IDisposable[] = [];+ let rebindCallbackCount = 0;+ let rebindCallbacksInCurrentMutation = 0;+ let stableCallbackCount = 0;++ const bindRebindingWatcher = (index: number, range: IRange): IDisposable => {+ const currentDisposable = refRangeService.watchRange('test', 'sheet1', range, (_before, after) => {+ if (!after) {+ throw new Error('Expected the watched range to survive column insertion');+ }+ rebindCallbackCount++;+ rebindCallbacksInCurrentMutation++;+ if (rebindCallbacksInCurrentMutation > rebindWatcherCount) {+ throw new Error('A structural mutation notified replacement watchers registered during the same mutation');+ }+ const replacement = bindRebindingWatcher(index, after);+ currentDisposable.dispose();+ activeRebinders[index] = replacement;+ });+ return currentDisposable;+ };++ for (let i = 0; i < rebindWatcherCount; i++) {+ activeRebinders.push(bindRebindingWatcher(i, watchedRange));+ }+ for (let i = 0; i < stableWatcherCount; i++) {+ stableWatchers.push(refRangeService.watchRange('test', 'sheet1', watchedRange, () => {+ stableCallbackCount++;+ }));+ }++ const insertParams = {+ unitId: 'test',+ subUnitId: 'sheet1',+ range: { startRow: 0, endRow: 9, startColumn: 2, endColumn: 2 },+ };+ for (let i = 0; i < mutationCount; i++) {+ rebindCallbacksInCurrentMutation = 0;+ expect(commandService.syncExecuteCommand(InsertColMutation.id, insertParams)).toBeTruthy();+ }++ expect(rebindCallbackCount).toBe(rebindWatcherCount * mutationCount);+ expect(stableCallbackCount).toBe(stableWatcherCount * mutationCount);++ activeRebinders.forEach((disposable) => disposable.dispose());+ stableWatchers.forEach((disposable) => disposable.dispose());+ expect(commandService.syncExecuteCommand(InsertColMutation.id, insertParams)).toBeTruthy();+ expect(rebindCallbackCount).toBe(rebindWatcherCount * mutationCount);+ expect(stableCallbackCount).toBe(stableWatcherCount * mutationCount);+ });});});diff --git a/packages/sheets/src/services/ref-range/ref-range.service.ts b/packages/sheets/src/services/ref-range/ref-range.service.tsindex 82b84bf1e0..fbc7f222bf 100644--- a/packages/sheets/src/services/ref-range/ref-range.service.ts+++ b/packages/sheets/src/services/ref-range/ref-range.service.ts@@ -62,6 +62,7 @@ const MERGE_UNDO = createInterceptorKey<IMutationInfo[], null>('MERGE_UNDO');class WatchRange extends Disposable {constructor(+ readonly revision: number,private readonly _unitId: string,private readonly _subUnitId: string,private _range: Nullable<IRange>,@@ -117,6 +118,8 @@ export class RefRangeService extends Disposable {interceptor = new InterceptorManager({ MERGE_REDO, MERGE_UNDO });private _watchRanges = new Set<WatchRange>();+ private _watchRangesListener: Nullable<IDisposable> = null;+ private _watchRangeRevision = 0;constructor(@ICommandService private readonly _commandService: ICommandService,@@ -137,25 +140,28 @@ export class RefRangeService extends Disposable {}watchRange(unitId: string, subUnitId: string, range: IRange, callback: WatchRangeCallback, skipIntersects?: boolean): IDisposable {- let watchRangesListener: Nullable<IDisposable>;- if (this._watchRanges.size === 0) {- watchRangesListener = this._commandService.onCommandExecuted((command) => {+ if (!this._watchRangesListener) {+ this._watchRangesListener = this.disposeWithMe(this._commandService.onCommandExecuted((command) => {if (command.type !== CommandType.MUTATION) return false;++ // A callback may synchronously replace its watcher. The replacement starts with the next mutation.+ const revision = this._watchRangeRevision;for (const watchRange of this._watchRanges) {+ if (watchRange.revision > revision) continue;watchRange.onMutation(command as IMutationInfo<ISheetCommandSharedParams>);}- });+ }));}- const watchRange = new WatchRange(unitId, subUnitId, range, callback, skipIntersects);+ const watchRange = new WatchRange(++this._watchRangeRevision, unitId, subUnitId, range, callback, skipIntersects);this._watchRanges.add(watchRange);const teardownWatching = toDisposable(() => {this._watchRanges.delete(watchRange);if (this._watchRanges.size === 0) {- watchRangesListener?.dispose();- watchRangesListener = null;+ this._watchRangesListener?.dispose();+ this._watchRangesListener = null;}});