Skip to content

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.

fix(sheets): keep whole column and row range types through structural edits (#8170)

wpxp123456f2c9b6263b59
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts
index 4b8fac80e0..f3198c7fd7 100644
--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import { Injector } from '@univerjs/core';
+import { Injector, RANGE_TYPE } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { ConditionalFormattingRangeTransformService } from '../conditional-formatting-range-transform.service';
@@ -90,4 +90,50 @@ describe('ConditionalFormattingRangeTransformService', () => {
{ startRow: 1, startColumn: 0, endRow: 1, endColumn: 1 },
]));
});
+
+ it('keeps a whole column type when a delta only rewrites cells inside the range', () => {
+ const service = createService();
+
+ const ranges = service.applyRangeDelta(
+ [{ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }],
+ [{ startRow: 0, endRow: 16, startColumn: 0, endColumn: 0 }],
+ [{ startRow: 0, endRow: 16, startColumn: 0, endColumn: 0 }]
+ );
+
+ expect(ranges).toEqual([{ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }]);
+ });
+
+ it('keeps a whole column range whole when the added range is already covered', () => {
+ const service = createService();
+
+ const ranges = service.addRanges(
+ [{ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }],
+ [{ startRow: 10, endRow: 20, startColumn: 0, endColumn: 0 }]
+ );
+
+ expect(ranges).toEqual([{ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }]);
+ });
+
+ it('does not keep a whole column type once only part of the range is left', () => {
+ const service = createService();
+
+ const ranges = service.subtractRanges(
+ [{ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }],
+ [{ startRow: 0, endRow: 49, startColumn: 0, endColumn: 0 }]
+ );
+
+ expect(ranges).toEqual([{ startRow: 50, endRow: 99, startColumn: 0, endColumn: 0 }]);
+ });
+
+ it('does not keep a whole column type on a projected copy', () => {
+ const service = createService();
+
+ const ranges = service.copyIntersectingRanges(
+ [{ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }],
+ { startRow: 0, endRow: 99, startColumn: 0, endColumn: 0 },
+ { row: 0, col: 1 }
+ );
+
+ expect(ranges).toEqual([{ startRow: 0, endRow: 99, startColumn: 1, endColumn: 1 }]);
+ });
});
diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts
index c8f5ac5d9f..5bf144e055 100644
--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts
@@ -24,21 +24,32 @@ export interface IRangeAnchor {
export class ConditionalFormattingRangeTransformService {
subtractRanges(sourceRanges: IRange[], rangesToSubtract: IRange[]) {
- return Rectangle.mergeRanges(Rectangle.subtractMulti(sourceRanges, rangesToSubtract));
+ return this._keepCoveredRangeType(
+ Rectangle.mergeRanges(Rectangle.subtractMulti(sourceRanges, rangesToSubtract)),
+ sourceRanges
+ );
}
addRanges(sourceRanges: IRange[], rangesToAdd: IRange[]) {
- return Rectangle.mergeRanges([...sourceRanges, ...rangesToAdd]);
+ return this._keepCoveredRangeType(
+ Rectangle.mergeRanges([...sourceRanges, ...rangesToAdd]),
+ sourceRanges
+ );
}
applyRangeDelta(sourceRanges: IRange[], rangesToSubtract: IRange[], rangesToAdd: IRange[]) {
const ranges = rangesToSubtract.length
- ? this.subtractRanges(sourceRanges, rangesToSubtract)
+ ? Rectangle.mergeRanges(Rectangle.subtractMulti(sourceRanges, rangesToSubtract))
: sourceRanges;
- return rangesToAdd.length
- ? this.addRanges(ranges, rangesToAdd)
+ const merged = rangesToAdd.length
+ ? Rectangle.mergeRanges([...ranges, ...rangesToAdd])
: ranges;
+
+ // the delta is applied to the original ranges: when the net coverage is unchanged (auto fill
+ // or paste back into the same cells) the whole column/row type has to survive, even though
+ // the intermediate subtract/add results are plain coordinates
+ return this._keepCoveredRangeType(merged, sourceRanges);
}
copyIntersectingRanges(sourceRanges: IRange[], sourceRange: IRange, targetAnchor: IRangeAnchor) {
@@ -67,4 +78,22 @@ export class ConditionalFormattingRangeTransformService {
endColumn: range.endColumn + offset.col,
};
}
+
+ /**
+ * Rebuilding ranges from coordinates drops `rangeType`. A result range that still covers exactly
+ * the same cells as a whole column/row source has to keep that type, otherwise a rule that was
+ * not actually changed (for example adding an already covered range) degrades to concrete rows.
+ * Results that no longer match a source range are genuine partial coverage and stay concrete.
+ */
+ private _keepCoveredRangeType(ranges: IRange[], sourceRanges: IRange[]) {
+ return ranges.map((range) => {
+ const source = sourceRanges.find((item) => item.rangeType
+ && item.startRow === range.startRow
+ && item.endRow === range.endRow
+ && item.startColumn === range.startColumn
+ && item.endColumn === range.endColumn);
+
+ return source ? { ...range, rangeType: source.rangeType } : range;
+ });
+ }
}
diff --git a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts
index 200f61a28b..79343449d1 100644
--- a/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts
+++ b/packages/sheets-data-validation-ui/src/controllers/__tests__/dv-auto-fill.controller.spec.ts
@@ -15,7 +15,7 @@
*/
import type { ISheetAutoFillHook } from '@univerjs/sheets';
-import { DataValidationType, Direction, Range } from '@univerjs/core';
+import { DataValidationType, Direction, Range, RANGE_TYPE } from '@univerjs/core';
import { AddDataValidationMutation } from '@univerjs/data-validation';
import { AUTO_FILL_APPLY_TYPE } from '@univerjs/sheets';
import { DATA_VALIDATION_PLUGIN_NAME } from '@univerjs/sheets-data-validation';
@@ -132,4 +132,37 @@ describe('DataValidationAutoFillController', () => {
expect(testBed.dataValidationModel.getRuleByLocation(testBed.unitId, testBed.subUnitId, 0, 0)?.uid).toBe('decimal-rule');
expect(testBed.dataValidationModel.getRuleByLocation(testBed.unitId, testBed.subUnitId, 1, 0)).toBeUndefined();
});
+
+ it('keeps a whole column rule whole when data is filled inside it', async () => {
+ await testBed.commandService.executeCommand(AddDataValidationMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule: {
+ uid: 'whole-column-rule',
+ type: DataValidationType.DECIMAL,
+ formula1: '1',
+ ranges: [{ startRow: 0, endRow: 199_999, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN }],
+ },
+ });
+ const location = {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ source: { rows: [0], cols: [0] },
+ target: { rows: [1], cols: [0] },
+ };
+
+ // auto fill first clears the target and then copies the source range back: the net coverage
+ // of the rule is unchanged, so a whole column rule must stay a whole column rule
+ const result = hook.onFillData?.(location, Direction.DOWN, AUTO_FILL_APPLY_TYPE.COPY);
+ if (!result) {
+ throw new Error('Data validation autofill did not return mutations');
+ }
+ for (const mutation of result.redos) {
+ await testBed.commandService.executeCommand(mutation.id, mutation.params);
+ }
+
+ expect(testBed.dataValidationModel.getRuleById(testBed.unitId, testBed.subUnitId, 'whole-column-rule')?.ranges).toEqual([
+ { startRow: 0, endRow: 199_999, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN },
+ ]);
+ });
});
diff --git a/packages/sheets-data-validation/src/controllers/__tests__/dv-ref-range.spec.ts b/packages/sheets-data-validation/src/controllers/__tests__/dv-ref-range.spec.ts
new file mode 100644
index 0000000000..61898ceb07
--- /dev/null
+++ b/packages/sheets-data-validation/src/controllers/__tests__/dv-ref-range.spec.ts
@@ -0,0 +1,299 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IAccessor, Injector, IRange, IWorkbookData } from '@univerjs/core';
+import type { FUniver } from '@univerjs/core/facade';
+import { DataValidationType, Direction, ICommandService, LocaleType, RANGE_TYPE } from '@univerjs/core';
+import { DataValidatorRegistryService } from '@univerjs/data-validation';
+import { serializeRange } from '@univerjs/engine-formula';
+import { InsertColByRangeCommand, InsertColMutation, InsertRowByRangeCommand, InsertRowMutation, SetSelectionsOperation, SheetsSelectionsService } from '@univerjs/sheets';
+import { FormulaRefRangeService } from '@univerjs/sheets-formula';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { AddSheetDataValidationCommand, ClearRangeDataValidationCommand, UpdateSheetDataValidationRangeCommand } from '../../commands/commands/data-validation.command';
+import { createFacadeTestBed } from '../../facade/__tests__/create-test-bed';
+import { createDefaultNewRule } from '../../utils/create';
+import { DataValidationFormulaRefRangeController } from '../dv-formula-ref-range.controller';
+import { DataValidationRefRangeController } from '../dv-ref-range.controller';
+
+function createWorkbookData(): IWorkbookData {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: ['sheet1'],
+ styles: {},
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ name: 'sheet1',
+ rowCount: 100,
+ columnCount: 26,
+ cellData: {},
+ },
+ },
+ };
+}
+
+describe('data validation ref range on row and column insertion', () => {
+ let get: Injector['get'];
+ let univerAPI: FUniver;
+ let univer: ReturnType<typeof createFacadeTestBed>['univer'];
+
+ beforeEach(() => {
+ // a number rule is handled by the formula based ref-range controller, which transforms
+ // the rule ranges together with its formulas
+ const testBed = createFacadeTestBed(createWorkbookData(), [
+ [DataValidationFormulaRefRangeController],
+ [DataValidationRefRangeController],
+ [FormulaRefRangeService],
+ [DataValidatorRegistryService],
+ ]);
+ univer = testBed.univer;
+ get = testBed.get;
+ univerAPI = testBed.univerAPI;
+
+ const commandService = get(ICommandService);
+ [
+ AddSheetDataValidationCommand,
+ ClearRangeDataValidationCommand,
+ UpdateSheetDataValidationRangeCommand,
+ InsertRowByRangeCommand,
+ InsertRowMutation,
+ InsertColByRangeCommand,
+ InsertColMutation,
+ SetSelectionsOperation,
+ ].forEach((command) => commandService.registerCommand(command));
+
+ // instantiate the controllers before rules are added, so that they subscribe to rule changes
+ get(DataValidationFormulaRefRangeController);
+ get(DataValidationRefRangeController);
+ });
+
+ afterEach(() => {
+ univer.dispose();
+ });
+
+ function insertRows(startRow: number, direction: Direction.UP | Direction.DOWN) {
+ expect(get(ICommandService).syncExecuteCommand(InsertRowByRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction,
+ range: { startRow, endRow: startRow, startColumn: 0, endColumn: 25 },
+ })).toBeTruthy();
+ }
+
+ function insertColumns(startColumn: number, direction: Direction.LEFT | Direction.RIGHT) {
+ expect(get(ICommandService).syncExecuteCommand(InsertColByRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ direction,
+ range: { startRow: 0, endRow: 99, startColumn, endColumn: startColumn },
+ })).toBeTruthy();
+ }
+
+ function setUpRule(rangeA1: string) {
+ const workbook = univerAPI.getActiveWorkbook()!;
+ const worksheet = workbook.getActiveSheet();
+ worksheet.getRange(rangeA1).setDataValidation(
+ univerAPI.newDataValidation().requireNumberBetween(0, 100).build()
+ );
+
+ const ruleRanges = () => worksheet.getDataValidations().flatMap((rule) => rule.rule.ranges);
+ const ruleA1Notations = () => worksheet.getDataValidations()
+ .flatMap((rule) => rule.getRanges().map((range) => range.getA1Notation()));
+
+ return { worksheet, ruleRanges, ruleA1Notations };
+ }
+
+ it('shifts the rule when a row is inserted right above the rule range', () => {
+ const { ruleA1Notations } = setUpRule('A2:A10');
+
+ // the UP entry creates the new row 2
+ insertRows(1, Direction.UP);
+ expect(ruleA1Notations()).toEqual(['A3:A11']);
+ });
+
+ it('shifts the rule identically when the same row is inserted through the DOWN entry', () => {
+ const { ruleA1Notations } = setUpRule('A2:A10');
+
+ // the DOWN entry creates the same new row 2
+ insertRows(1, Direction.DOWN);
+ expect(ruleA1Notations()).toEqual(['A3:A11']);
+ });
+
+ it('keeps the rule untouched when the row is inserted right below the rule range', () => {
+ const { ruleA1Notations } = setUpRule('A2:A10');
+
+ insertRows(10, Direction.UP);
+ expect(ruleA1Notations()).toEqual(['A2:A10']);
+ });
+
+ it('keeps the rule untouched when the row below is inserted through the DOWN entry', () => {
+ const { ruleA1Notations } = setUpRule('A2:A10');
+
+ insertRows(10, Direction.DOWN);
+ expect(ruleA1Notations()).toEqual(['A2:A10']);
+ });
+
+ it('keeps the inserted row covered when it is inserted inside the rule range', () => {
+ const { ruleA1Notations } = setUpRule('A2:A10');
+
+ insertRows(5, Direction.UP);
+ expect(ruleA1Notations()).toEqual(['A2:A11']);
+ });
+
+ it('keeps a whole column rule whole when rows are inserted', () => {
+ const { ruleRanges, ruleA1Notations } = setUpRule('A:A');
+ expect(ruleA1Notations()).toEqual(['A:A']);
+
+ // rows are inserted above and inside the rule range
+ insertRows(0, Direction.UP);
+ insertRows(5, Direction.UP);
+
+ expect(ruleRanges()).toMatchObject([{ startRow: 0, rangeType: RANGE_TYPE.COLUMN }]);
+ expect(ruleRanges()[0].endRow).toBe(101);
+ expect(ruleA1Notations()).toEqual(['A:A']);
+ });
+
+ it('keeps a whole row rule whole when columns are inserted', () => {
+ const { ruleRanges, ruleA1Notations } = setUpRule('1:1');
+ expect(ruleA1Notations()).toEqual(['1:1']);
+
+ insertColumns(0, Direction.LEFT);
+ insertColumns(3, Direction.LEFT);
+
+ expect(ruleRanges()).toMatchObject([{ startColumn: 0, rangeType: RANGE_TYPE.ROW }]);
+ expect(ruleRanges()[0].endColumn).toBe(27);
+ expect(ruleA1Notations()).toEqual(['1:1']);
+ });
+
+ it('drops the whole column type when only part of the rule is cleared', () => {
+ const { worksheet } = setUpRule('A:A');
+
+ get(ICommandService).syncExecuteCommand(ClearRangeDataValidationCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ranges: [{ startRow: 0, endRow: 49, startColumn: 0, endColumn: 0 }],
+ });
+
+ const rules = worksheet.getDataValidations();
+ expect(rules.map((rule) => rule.rule.ranges)).toMatchObject([[{ startRow: 50, endRow: 99 }]]);
+ expect(rules[0].rule.ranges[0].rangeType).toBeUndefined();
+ });
+
+ it('keeps a whole column rule created from a column selection', () => {
+ // this is what the UI produces when the user picks a whole column through the column header
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ get(ICommandService).syncExecuteCommand(AddSheetDataValidationCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ rule: {
+ uid: 'column-rule',
+ type: DataValidationType.DECIMAL,
+ operator: 0,
+ formula1: '0',
+ formula2: '100',
+ ranges: [{
+ startRow: 0,
+ endRow: 99,
+ startColumn: 0,
+ endColumn: 0,
+ rangeType: RANGE_TYPE.COLUMN,
+ }],
+ },
+ });
+
+ insertRows(0, Direction.UP);
+
+ const rules = worksheet.getDataValidations();
+ expect(rules.map((rule) => rule.rule.ranges)).toMatchObject([[{ startRow: 0, endRow: 100, rangeType: RANGE_TYPE.COLUMN }]]);
+ expect(rules.flatMap((rule) => rule.getRanges().map((range) => range.getA1Notation()))).toEqual(['A:A']);
+ });
+
+ it('keeps the range type when the panel rewrites the rule range', () => {
+ const { worksheet } = setUpRule('A:A');
+
+ // the range selector of the panel emits a whole column range with empty row bounds
+ get(ICommandService).syncExecuteCommand(UpdateSheetDataValidationRangeCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ ruleId: worksheet.getDataValidations()[0].rule.uid,
+ ranges: [{
+ startRow: null,
+ endRow: null,
+ startColumn: 0,
+ endColumn: 0,
+ rangeType: RANGE_TYPE.COLUMN,
+ } as unknown as IRange],
+ });
+
+ const rules = worksheet.getDataValidations();
+ expect(rules.map((rule) => rule.rule.ranges)).toMatchObject([[{ startRow: 0, endRow: 99, rangeType: RANGE_TYPE.COLUMN }]]);
+ expect(rules.flatMap((rule) => rule.getRanges().map((range) => range.getA1Notation()))).toEqual(['A:A']);
+ });
+
+ it('keeps a whole column list rule whole when rows are inserted', () => {
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ worksheet.getRange('A:A').setDataValidation(
+ univerAPI.newDataValidation().requireValueInList(['Yes', 'No']).build()
+ );
+
+ insertRows(0, Direction.UP);
+
+ const rules = worksheet.getDataValidations();
+ expect(rules.map((rule) => rule.rule.ranges)).toMatchObject([[{ startRow: 0, endRow: 100, rangeType: RANGE_TYPE.COLUMN }]]);
+ expect(rules.flatMap((rule) => rule.getRanges().map((range) => range.getA1Notation()))).toEqual(['A:A']);
+ });
+
+ it('creates a whole column rule from a column selection, like the panel new rule button does', () => {
+ // the panel takes the current selection as the rule range
+ get(SheetsSelectionsService).setSelections('test', 'sheet1', [{
+ range: { startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN },
+ primary: {
+ startRow: 0,
+ endRow: 0,
+ startColumn: 0,
+ endColumn: 0,
+ actualRow: 0,
+ actualColumn: 0,
+ isMerged: false,
+ isMergedMainCell: false,
+ },
+ style: null,
+ }]);
+
+ const rule = createDefaultNewRule({ get } as unknown as IAccessor);
+ expect(rule.ranges[0]).toMatchObject({ startRow: 0, endRow: 99, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN });
+ // the panel renders the rule range with serializeRange
+ expect(serializeRange(rule.ranges[0])).toBe('A:A');
+
+ const worksheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+ get(ICommandService).syncExecuteCommand(AddSheetDataValidationCommand.id, {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ rule,
+ });
+
+ expect(worksheet.getDataValidations().flatMap((item) => item.getRanges().map((range) => range.getA1Notation()))).toEqual(['A:A']);
+ expect(serializeRange(worksheet.getDataValidations()[0].rule.ranges[0])).toBe('A:A');
+
+ insertRows(0, Direction.UP);
+
+ expect(worksheet.getDataValidations().flatMap((item) => item.getRanges().map((range) => range.getA1Notation()))).toEqual(['A:A']);
+ expect(serializeRange(worksheet.getDataValidations()[0].rule.ranges[0])).toBe('A:A');
+ });
+});
diff --git a/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.ts b/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.ts
index 5db6fc485b..5088e2e500 100644
--- a/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.ts
+++ b/packages/sheets-data-validation/src/models/__tests__/rule-matrix.spec.ts
@@ -15,6 +15,7 @@
*/
import type { IRange, ISheetDataValidationRule, IUniverInstanceService, Workbook, Worksheet } from '@univerjs/core';
+import { RANGE_TYPE } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { RuleMatrix } from '../rule-matrix';
@@ -54,6 +55,35 @@ describe('RuleMatrix', () => {
expect(matrix.getValue(5, 5)).toBeUndefined();
});
+ it('keeps a whole column range type when an already covered range is added', () => {
+ const wholeColumn = { startRow: 0, endRow: 19, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN };
+ const rule = createRule('rule-1', [wholeColumn]);
+ const matrix = createMatrix(new Map([['rule-1', [wholeColumn]]]));
+
+ // auto fill or copy/paste adds a range that the rule already covers
+ matrix.addRangeRules([{ id: 'rule-1', ranges: [{ startRow: 0, endRow: 4, startColumn: 0, endColumn: 0 }] }]);
+
+ expect(matrix.diff([rule])).toEqual([]);
+ });
+
+ it('drops the whole column type when the added range extends the rule', () => {
+ const wholeColumn = { startRow: 0, endRow: 9, startColumn: 0, endColumn: 0, rangeType: RANGE_TYPE.COLUMN };
+ const rule = createRule('rule-1', [wholeColumn]);
+ const matrix = createMatrix(new Map([['rule-1', [wholeColumn]]]));
+
+ matrix.addRangeRules([{ id: 'rule-1', ranges: [{ startRow: 0, endRow: 19, startColumn: 0, endColumn: 0 }] }]);
+
+ expect(matrix.diff([rule])).toEqual([
+ {
+ type: 'update',
+ ruleId: 'rule-1',
+ oldRanges: [wholeColumn],
+ newRanges: [{ startRow: 0, endRow: 19, startColumn: 0, endColumn: 0 }],
+ rule,
+ },
+ ]);
+ });
+
it('updates, removes, and merges rule ranges correctly', () => {
const matrix = createMatrix(new Map([
['rule-1', [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]],
diff --git a/packages/sheets-data-validation/src/models/rule-matrix.ts b/packages/sheets-data-validation/src/models/rule-matrix.ts
index 6976537343..9df57a73dc 100644
--- a/packages/sheets-data-validation/src/models/rule-matrix.ts
+++ b/packages/sheets-data-validation/src/models/rule-matrix.ts
@@ -86,6 +86,7 @@ export class RuleMatrix {
}
const ranges = Rectangle.mergeRanges(_ranges.map((range) => Range.transformRange(range, this._worksheet!)));
+ const ruleRanges = this._withInputRangeType(ranges, _ranges);
this._map.forEach((value, key) => {
const newRanges = Rectangle.subtractMulti(value, ranges);
@@ -97,7 +98,7 @@ export class RuleMatrix {
});
this._dirty = true;
- this._map.set(ruleId, ranges);
+ this._map.set(ruleId, ruleRanges);
this._debonceBuildTree();
}
@@ -141,6 +142,38 @@ export class RuleMatrix {
this._addRule(ruleId, _newRanges);
}
+ /**
+ * The matrix stores concrete coordinates, while the rule keeps its semantic range type (a whole
+ * column/row). `Range.transformRange` and `Rectangle.mergeRanges` rebuild ranges from bounds only,
+ * so the type of the ranges handed to the matrix has to be carried over explicitly.
+ */
+ private _withInputRangeType(ranges: IRange[], inputRanges: IRange[]): IRange[] {
+ const rangeType = inputRanges[0]?.rangeType;
+ if (!rangeType || !inputRanges.every((range) => range.rangeType === rangeType)) {
+ return ranges;
+ }
+
+ return ranges.map((range) => ({ ...range, rangeType }));
+ }
+
+ /**
+ * A rule range that the matrix rebuilt from coordinates keeps its type when the rebuilt range
+ * still covers exactly the same cells as the rule's own range. This is what makes an auto fill
+ * or a paste that only rewrites cells inside the rule a no-op instead of a downgrade: the
+ * intermediate subtract/add steps drop the type, but the net coverage is unchanged.
+ */
+ private _keepRuleRangeType(ranges: IRange[], ruleRanges: IRange[]): IRange[] {
+ return ranges.map((range) => {
+ const source = ruleRanges.find((item) => item.rangeType
+ && item.startRow === range.startRow
+ && item.endRow === range.endRow
+ && item.startColumn === range.startColumn
+ && item.endColumn === range.endColumn);
+
+ return source ? { ...range, rangeType: source.rangeType } : range;
+ });
+ }
+
addRangeRules(rules: { id: string; ranges: IRange[] }[]) {
rules.forEach(({ id: ruleId, ranges }) => {
if (!ranges.length) {
@@ -176,7 +209,7 @@ export class RuleMatrix {
const mutations: RangeMutation[] = [];
let deleteIndex = 0;
rules.forEach((rule, index) => {
- const newRanges = this._map.get(rule.uid) ?? [];
+ const newRanges = this._keepRuleRangeType(this._map.get(rule.uid) ?? [], rule.ranges);
const oldRanges = rule.ranges;
if (newRanges.length !== 0 && (newRanges.length !== oldRanges.length || newRanges.some((range, i) => !Rectangle.equals(range, oldRanges[i])))) {
@@ -206,7 +239,7 @@ export class RuleMatrix {
const mutations: RangeMutation[] = [];
let deleteIndex = 0;
rules.forEach((rule, index) => {
- const newRanges = this._map.get(rule.uid) ?? [];
+ const newRanges = this._keepRuleRangeType(this._map.get(rule.uid) ?? [], rule.ranges);
const oldRanges = rule.ranges;
if (newRanges.length !== 0 && (newRanges.length !== oldRanges.length || newRanges.some((range, i) => !Rectangle.equals(range, oldRanges[i])))) {
@@ -230,7 +263,7 @@ export class RuleMatrix {
});
Array.from(additionRules).forEach((rule) => {
- const newRanges = this._map.get(rule.uid) ?? [];
+ const newRanges = this._keepRuleRangeType(this._map.get(rule.uid) ?? [], rule.ranges);
mutations.push({
type: 'add',
rule: {
diff --git a/packages/sheets-formula/src/services/__tests__/formula-ref.spec.ts b/packages/sheets-formula/src/services/__tests__/formula-ref.spec.ts
index e52b6f5bad..a0e14fd9fd 100644
--- a/packages/sheets-formula/src/services/__tests__/formula-ref.spec.ts
+++ b/packages/sheets-formula/src/services/__tests__/formula-ref.spec.ts
@@ -15,10 +15,10 @@
*/
import type { IRange, IWorkbookData } from '@univerjs/core';
-import type { ITestBed } from './util';
-import { Direction, ICommandService, LocaleType } from '@univerjs/core';
+import { Direction, ICommandService, LocaleType, RANGE_TYPE } from '@univerjs/core';
import { InsertColCommand, MoveRangeCommand, RemoveColCommand } from '@univerjs/sheets';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import type { ITestBed } from './util';
import { FormulaRefRangeService } from '../formula-ref-range.service';
import { createCommandTestBed } from './util';
@@ -396,6 +396,115 @@ describe('FormulaRefRangeService', () => {
);
});
+ it('keeps the inserted column covered when it is inserted inside the range', async () => {
+ const formulaRefRangeService = testBed.get(FormulaRefRangeService);
+
+ let newFormulas: {
+ formulas: string[];
+ ranges: IRange[];
+ }[] = [];
+
+ formulaRefRangeService.registerRangeFormula(
+ 'test',
+ 'sheet1',
+ [{
+ startRow: 5,
+ endRow: 10,
+ startColumn: 5,
+ endColumn: 10,
+ }],
+ ['=A1'],
+ (res) => {
+ newFormulas = res;
+ return {
+ redos: [],
+ undos: [],
+ };
+ }
+ );
+
+ await testBed.get(ICommandService).executeCommand(
+ InsertColCommand.id,
+ {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: {
+ startColumn: 7,
+ endColumn: 7,
+ startRow: 0,
+ endRow: 9999,
+ },
+ direction: Direction.LEFT,
+ }
+ );
+
+ expect(newFormulas).toEqual(
+ [
+ {
+ formulas: ['=C1'],
+ ranges: [{ startRow: 5, endRow: 10, startColumn: 8, endColumn: 11 }],
+ },
+ {
+ formulas: ['=A1'],
+ ranges: [{ startRow: 5, endRow: 10, startColumn: 5, endColumn: 7 }],
+ },
+ ]
+ );
+ });
+
+ it('keeps a whole row range whole and unsplit when a column is inserted', async () => {
+ const formulaRefRangeService = testBed.get(FormulaRefRangeService);
+
+ let newFormulas: {
+ formulas: string[];
+ ranges: IRange[];
+ }[] = [];
+
+ formulaRefRangeService.registerRangeFormula(
+ 'test',
+ 'sheet1',
+ [{
+ startRow: 2,
+ endRow: 2,
+ startColumn: 0,
+ endColumn: 9,
+ rangeType: RANGE_TYPE.ROW,
+ }],
+ ['=A1'],
+ (res) => {
+ newFormulas = res;
+ return {
+ redos: [],
+ undos: [],
+ };
+ }
+ );
+
+ await testBed.get(ICommandService).executeCommand(
+ InsertColCommand.id,
+ {
+ unitId: 'test',
+ subUnitId: 'sheet1',
+ range: {
+ startColumn: 3,
+ endColumn: 3,
+ startRow: 0,
+ endRow: 9999,
+ },
+ direction: Direction.LEFT,
+ }
+ );
+
+ expect(newFormulas).toEqual(
+ [
+ {
+ formulas: ['=A1'],
+ ranges: [{ startRow: 2, endRow: 2, startColumn: 0, endColumn: 10, rangeType: RANGE_TYPE.ROW }],
+ },
+ ]
+ );
+ });
+
it('stops listening for range changes after registerFormula is disposed', async () => {
const formulaRefRangeService = testBed.get(FormulaRefRangeService);
const updatedFormulas: string[] = [];
diff --git a/packages/sheets-formula/src/services/formula-ref-range.service.ts b/packages/sheets-formula/src/services/formula-ref-range.service.ts
index b7ac611963..1be69959b4 100644
--- a/packages/sheets-formula/src/services/formula-ref-range.service.ts
+++ b/packages/sheets-formula/src/services/formula-ref-range.service.ts
@@ -15,10 +15,10 @@
*/
import type { IDisposable, IMutationInfo, IRange, Workbook } from '@univerjs/core';
-import type { EffectRefRangeParams } from '@univerjs/sheets';
-import { AbsoluteRefType, Disposable, DisposableCollection, getIntersectRange, Inject, Injector, isFormulaString, IUniverInstanceService, moveRangeByOffset, Rectangle, UniverInstanceType } from '@univerjs/core';
+import type { EffectRefRangeParams, IInsertColCommandParams, IInsertRowCommandParams } from '@univerjs/sheets';
+import { AbsoluteRefType, Disposable, DisposableCollection, getIntersectRange, Inject, Injector, isFormulaString, IUniverInstanceService, moveRangeByOffset, RANGE_TYPE, Rectangle, UniverInstanceType } from '@univerjs/core';
import { deserializeRangeWithSheetWithCache, ErrorType, generateStringWithSequence, LexerTreeBuilder, sequenceNodeType, serializeRange, serializeRangeWithSheet, serializeRangeWithSpreadsheet } from '@univerjs/engine-formula';
-import { getSeparateEffectedRangesOnCommand, handleCommonDefaultRangeChangeWithEffectRefCommands, handleDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';
+import { EffectRefRangId, getSeparateEffectedRangesOnCommand, handleCommonDefaultRangeChangeWithEffectRefCommands, handleDefaultRangeChangeWithEffectRefCommands, RefRangeService } from '@univerjs/sheets';
export type FormulaChangeMap = Record<string, Record<string, Record<string, string>>>;
@@ -32,6 +32,53 @@ export type RangeFormulaChangeCallback = (infos: { formulas: string[]; ranges: I
undos: IMutationInfo[];
};
+interface IRangeFormulaItem {
+ formulas: { newFormula: string; orginFormula: string }[];
+ ranges: IRange[];
+ key: string;
+}
+
+/**
+ * An inserted row or column that lands inside a registered range stays part of that range, the
+ * same way {@link handleCommonDefaultRangeChangeWithEffectRefCommands} expands a range when the
+ * insertion happens inside it. `registerRangeFormula` splits a range into the segments that are
+ * affected by a command, and an inserted block is not part of any segment, so it has to be
+ * collected separately, otherwise the inserted cells would silently drop out of the range.
+ */
+function getInsertedBlocks(command: EffectRefRangeParams, ranges: IRange[]): IRange[] {
+ const params = command.params as IInsertRowCommandParams | IInsertColCommandParams | undefined;
+ if (!params?.range) {
+ return [];
+ }
+
+ switch (command.id) {
+ case EffectRefRangId.InsertRowCommandId: {
+ const { startRow, endRow } = params.range;
+ return ranges
+ .filter((range) => startRow > range.startRow && startRow <= range.endRow)
+ .map((range) => ({
+ startRow,
+ endRow,
+ startColumn: range.startColumn,
+ endColumn: range.endColumn,
+ }));
+ }
+ case EffectRefRangId.InsertColCommandId: {
+ const { startColumn, endColumn } = params.range;
+ return ranges
+ .filter((range) => startColumn > range.startColumn && startColumn <= range.endColumn)
+ .map((range) => ({
+ startRow: range.startRow,
+ endRow: range.endRow,
+ startColumn,
+ endColumn,
+ }));
+ }
+ default:
+ return [];
+ }
+}
+
function getFormulaKeyOffset(lexerTreeBuilder: LexerTreeBuilder, formulaString: string, refOffsetX: number, refOffsetY: number) {
const sequenceNodes = lexerTreeBuilder.sequenceNodesBuilder(formulaString);
@@ -252,6 +299,11 @@ export class FormulaRefRangeService extends Disposable {
const formulaDeps = formulas.map((formula) => this._getFormulaDependcy(unitId, subUnitId, formula, oldRanges));
// eslint-disable-next-line max-lines-per-function
const handleRangeChange = (commandInfo: EffectRefRangeParams) => {
+ const wholeRangeResult = this._transformWholeRangeFormulas(unitId, subUnitId, oldRanges, formulas, commandInfo);
+ if (wholeRangeResult) {
+ return callback(wholeRangeResult);
+ }
+
const effectedRanges = getSeparateEffectedRangesOnCommand(this._injector, commandInfo);
if (!effectedRanges) {
return {
@@ -307,7 +359,7 @@ export class FormulaRefRangeService extends Disposable {
noEffectRanges.sort((a, b) => a.startRow - b.startRow || a.startColumn - b.startColumn);
// 3. calculate every effected range to get new range and new formula
- const keyMap = new Map<string, { formulas: { newFormula: string }[]; ranges: IRange[] }[]>();
+ const keyMap = new Map<string, IRangeFormulaItem[]>();
for (let i = 0; i < ranges.length; i++) {
const range = ranges[i];
const currentRow = range.startRow;
@@ -379,6 +431,10 @@ export class FormulaRefRangeService extends Disposable {
}
}
+ // 4.1 the inserted row/column block itself is not part of any segment but stays
+ // covered by the range it was inserted into
+ this._appendInsertedBlockItems(keyMap, commandInfo, oldRanges, formulas, oldRanges[0], originKey);
+
// 5. merge effected ranges and get new formula,
// if origin formula was same, means these ranges can use same formula
const res = [];
@@ -422,4 +478,63 @@ export class FormulaRefRangeService extends Disposable {
return disposableCollection;
}
+
+ /**
+ * A whole column/row/sheet range keeps its anchor, so it is adjusted as a single range:
+ * segmenting it would both split the rule and drop the range type.
+ *
+ * @returns the single rule range to apply, or `undefined` when the regular segmentation applies
+ */
+ private _transformWholeRangeFormulas(
+ unitId: string,
+ subUnitId: string,
+ oldRanges: IRange[],
+ formulas: string[],
+ commandInfo: EffectRefRangeParams
+ ): { formulas: string[]; ranges: IRange[] }[] | undefined {
+ const ruleRangeType = oldRanges[0]?.rangeType ?? RANGE_TYPE.NORMAL;
+ if (ruleRangeType === RANGE_TYPE.NORMAL || !oldRanges.every((range) => range.rangeType === ruleRangeType)) {
+ return undefined;
+ }
+
+ const ranges = handleCommonDefaultRangeChangeWithEffectRefCommands(oldRanges[0], commandInfo);
+ if (!ranges.length) {
+ return [];
+ }
+
+ return [{
+ formulas: formulas.map((formula) => (isFormulaString(formula) ? this.transformFormulaByEffectCommand(unitId, subUnitId, formula, commandInfo) : formula)),
+ ranges,
+ }];
+ }
+
+ private _appendInsertedBlockItems(
+ keyMap: Map<string, IRangeFormulaItem[]>,
+ commandInfo: EffectRefRangeParams,
+ oldRanges: IRange[],
+ formulas: string[],
+ origin: IRange,
+ originKey: string
+ ) {
+ for (const block of getInsertedBlocks(commandInfo, oldRanges)) {
+ const offsetRow = block.startRow - origin.startRow;
+ const offsetColumn = block.startColumn - origin.startColumn;
+ const blockFormulas = formulas.map((formula) => ({
+ newFormula: isFormulaString(formula) ? this._lexerTreeBuilder.moveFormulaRefOffset(formula, offsetColumn, offsetRow) : formula,
+ orginFormula: formula,
+ }));
+ const item: IRangeFormulaItem = {
+ formulas: blockFormulas,
+ ranges: [block],
+ key: originKey,
+ };
+ const items = keyMap.get(item.key);
+
+ if (items) {
+ items.push(item);
+ } else {
+ keyMap.set(item.key, [item]);
+ }
+ }
+ }
}
diff --git a/packages/sheets/src/facade/f-worksheet.ts b/packages/sheets/src/facade/f-worksheet.ts
index b5e7f92987..aacc1aa270 100644
--- a/packages/sheets/src/facade/f-worksheet.ts
+++ b/packages/sheets/src/facade/f-worksheet.ts
@@ -37,8 +37,6 @@ import type {
ISetTextWrapCommandParams,
IToggleGridlinesCommandParams,
} from '@univerjs/sheets';
-import type { FDefinedName } from './f-defined-name';
-import type { FWorkbook } from './f-workbook';
import {
BooleanNumber,
covertCellValue,
@@ -91,6 +89,8 @@ import {
SheetsSelectionsService,
ToggleGridlinesCommand,
} from '@univerjs/sheets';
+import type { FDefinedName } from './f-defined-name';
+import type { FWorkbook } from './f-workbook';
import { SHEETS_CUSTOM_FIELD_WARNING_MESSAGE } from './const';
import { FDefinedNameBuilder } from './f-defined-name';
import { FRange } from './f-range';
@@ -499,8 +499,8 @@ export class FWorksheet extends FBaseInitialable {
unitId: this._workbook.getUnitId(),
sheetId: sheet.getSheetId(),
// Use the current range instead of the future actual range to match Apps Script behavior.
- // Users can create the latest range in real time when needed.
- rangeType: RANGE_TYPE.NORMAL,
+ // Users can create the latest range in real time when needed. The range type is kept so
+ // that a whole column/row range keeps behaving like one.
startRow: parsedRange.rangeType === RANGE_TYPE.COLUMN ? 0 : parsedRange.startRow,
endRow: parsedRange.rangeType === RANGE_TYPE.COLUMN ? sheet.getMaxRows() - 1 : parsedRange.endRow,
startColumn: parsedRange.rangeType === RANGE_TYPE.ROW ? 0 : parsedRange.startColumn,
diff --git a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts
index 4ff05bbdc5..95d3444e15 100644
--- a/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts
+++ b/packages/sheets/src/services/permission/range-permission/__tests__/range-protection.ref-range.spec.ts
@@ -15,10 +15,11 @@
*/
import type { Injector, IRange, Univer, Workbook } from '@univerjs/core';
-import type { IRangeProtectionRule } from '../../../../models/range-protection-rule.model';
-import { ICommandService, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, IUniverInstanceService, RANGE_TYPE, UniverInstanceType } from '@univerjs/core';
import { UnitObject } from '@univerjs/protocol';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IRangeProtectionRule } from '../../../../models/range-protection-rule.model';
+import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../../__tests__/util';
import { RemoveSheetCommand } from '../../../../commands/commands/remove-sheet.command';
import { AddRangeProtectionMutation } from '../../../../commands/mutations/add-range-protection.mutation';
import { DeleteRangeProtectionMutation } from '../../../../commands/mutations/delete-range-protection.mutation';
@@ -29,7 +30,6 @@ import { SetRangeProtectionMutation } from '../../../../commands/mutations/set-r
import { RangeProtectionRenderModel } from '../../../../models/range-protection-render.model';
import { EditStateEnum, RangeProtectionRuleModel, ViewStateEnum } from '../../../../models/range-protection-rule.model';
import { RangeProtectionCache } from '../../../../models/range-protection.cache';
-import { createTestBase, TEST_WORKBOOK_DATA_DEMO } from '../../../__tests__/util';
import { RefRangeService } from '../../../ref-range/ref-range.service';
import { SheetsSelectionsService } from '../../../selections/selection.service';
import { SheetInterceptorService } from '../../../sheet-interceptor/sheet-interceptor.service';
@@ -305,6 +305,79 @@ describe('RangeProtectionRefRangeService', () => {
expect(ruleModel.getRule(unitId, subUnitId, colRule.id)?.ranges[0]).toMatchObject({ startColumn: 3, endColumn: 4 });
});
+ it('keeps a whole column protected range whole through row edits', async () => {
+ const rule = createRule({
+ ranges: [{ startRow: 0, endRow: 9, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.COLUMN }],
+ });
+ ruleModel.addRule(unitId, subUnitId, rule);
+
+ await commandService.executeCommand(InsertRowMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 0, endRow: 0, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 0, endRow: 10, rangeType: RANGE_TYPE.COLUMN });
+
+ await commandService.executeCommand(RemoveRowMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 2, endRow: 3, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 0, endRow: 8, rangeType: RANGE_TYPE.COLUMN });
+
+ // moving rows along the covered axis leaves a whole column protection range untouched
+ await commandService.executeCommand(MoveRowsMutation.id, {
+ unitId,
+ subUnitId,
+ sourceRange: { startRow: 1, endRow: 2, startColumn: 0, endColumn: 10 },
+ targetRange: { startRow: 8, endRow: 9, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 0, endRow: 8, rangeType: RANGE_TYPE.COLUMN });
+ });
+
+ it('round trips a whole column protected range through an inserted row and its removal', async () => {
+ const rule = createRule({
+ ranges: [{ startRow: 0, endRow: 9, startColumn: 1, endColumn: 1, rangeType: RANGE_TYPE.COLUMN }],
+ });
+ ruleModel.addRule(unitId, subUnitId, rule);
+
+ await commandService.executeCommand(InsertRowMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 0, endRow: 10, rangeType: RANGE_TYPE.COLUMN });
+
+ // undoing an insertion replays the inverse mutation, which has to shrink the range back
+ await commandService.executeCommand(RemoveRowMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 2, endRow: 2, startColumn: 0, endColumn: 10 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startRow: 0, endRow: 9, rangeType: RANGE_TYPE.COLUMN });
+ });
+
+ it('keeps a whole row protected range whole through column edits', async () => {
+ const rule = createRule({
+ ranges: [{ startRow: 1, endRow: 1, startColumn: 0, endColumn: 9, rangeType: RANGE_TYPE.ROW }],
+ });
+ ruleModel.addRule(unitId, subUnitId, rule);
+
+ await commandService.executeCommand(InsertColMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 0, endRow: 10, startColumn: 0, endColumn: 0 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startColumn: 0, endColumn: 10, rangeType: RANGE_TYPE.ROW });
+
+ await commandService.executeCommand(RemoveColMutation.id, {
+ unitId,
+ subUnitId,
+ range: { startRow: 0, endRow: 10, startColumn: 2, endColumn: 3 },
+ });
+ expect(ruleModel.getRule(unitId, subUnitId, rule.id)?.ranges[0]).toMatchObject({ startColumn: 0, endColumn: 8, rangeType: RANGE_TYPE.ROW });
+ });
+
it('should register ref ranges after range protection mutation', async () => {
const registerSpy = vi.spyOn(refRangeService, 'registerRefRange');
const rule = createRule({
diff --git a/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts b/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts
index edcb83e1b4..af33d28bd8 100644
--- a/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts
+++ b/packages/sheets/src/services/permission/range-permission/range-protection.ref-range.ts
@@ -15,6 +15,7 @@
*/
import type { ICommandInfo, IMutationInfo, IRange, Workbook } from '@univerjs/core';
+import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, RANGE_TYPE, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
import type { IInsertColMutationParams } from '../../../basics/interfaces/mutation-interface';
import type { IInsertColCommandParams, IInsertRowCommandParams } from '../../../commands/commands/insert-row-col.command';
import type { IMoveColsCommandParams, IMoveRowsCommandParams } from '../../../commands/commands/move-rows-cols.command';
@@ -26,7 +27,6 @@ import type { IMoveRowsMutationParams } from '../../../commands/mutations/move-r
import type { ISetRangeProtectionMutationParams } from '../../../commands/mutations/set-range-protection.mutation';
import type { IRangeProtectionRule } from '../../../models/range-protection-rule.model';
import type { EffectRefRangeParams } from '../../ref-range/type';
-import { Disposable, DisposableCollection, ICommandService, Inject, IUniverInstanceService, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
import { InsertColCommand, InsertRowCommand } from '../../../commands/commands/insert-row-col.command';
import { MoveColsCommand, MoveRowsCommand } from '../../../commands/commands/move-rows-cols.command';
import { RemoveColCommand, RemoveRowCommand } from '../../../commands/commands/remove-row-col.command';
@@ -149,7 +149,7 @@ export class RangeProtectionRefRangeService extends Disposable {
private _getRefRangeMutationsByDeleteCols(params: IRemoveRowColCommandParams, unitId: string, subUnitId: string) {
const permissionRangeLapRules = this._selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((range) => {
- return Rectangle.intersects(range, params.range);
+ return !this._coversAllColumns(range) && Rectangle.intersects(range, params.range);
});
});
@@ -160,6 +160,10 @@ export class RangeProtectionRefRangeService extends Disposable {
permissionRangeLapRules.forEach((rule) => {
const cloneRule = Tools.deepClone(rule);
const rangesByRemove = cloneRule.ranges.reduce((p, c) => {
+ if (this._coversAllColumns(c)) {
+ p.push(c);
+ return p;
+ }
if (Rectangle.intersects(c, removeRange)) {
const cloneRange = Tools.deepClone(c);
const { startColumn, endColumn } = removeRange;
@@ -197,7 +201,7 @@ export class RangeProtectionRefRangeService extends Disposable {
private _getRefRangeMutationsByDeleteRows(params: IRemoveRowColCommandParams, unitId: string, subUnitId: string) {
const permissionRangeLapRules = this._selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((range) => {
- return Rectangle.intersects(range, params.range);
+ return !this._coversAllRows(range) && Rectangle.intersects(range, params.range);
});
});
@@ -208,6 +212,10 @@ export class RangeProtectionRefRangeService extends Disposable {
permissionRangeLapRules.forEach((rule) => {
const cloneRule = Tools.deepClone(rule);
const rangesByRemove = cloneRule.ranges.reduce((p, c) => {
+ if (this._coversAllRows(c)) {
+ p.push(c);
+ return p;
+ }
if (Rectangle.intersects(c, removeRange)) {
const cloneRange = Tools.deepClone(c);
const { startRow, endRow } = removeRange;
@@ -243,7 +251,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const permissionRangeLapRules = this._selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((range) => {
- return insertStart > range.startColumn && insertStart <= range.endColumn;
+ return !this._coversAllColumns(range) && insertStart > range.startColumn && insertStart <= range.endColumn;
});
});
@@ -254,7 +262,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const cloneRule = Tools.deepClone(rule);
let hasLap = false;
cloneRule.ranges.forEach((range) => {
- if (insertStart > range.startColumn && insertStart <= range.endColumn) {
+ if (!this._coversAllColumns(range) && insertStart > range.startColumn && insertStart <= range.endColumn) {
range.endColumn += insertLength;
hasLap = true;
}
@@ -276,7 +284,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const permissionRangeLapRules = this._selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((range) => {
- return insertStart > range.startRow && insertStart <= range.endRow;
+ return !this._coversAllRows(range) && insertStart > range.startRow && insertStart <= range.endRow;
});
});
@@ -287,7 +295,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const cloneRule = Tools.deepClone(rule);
let hasLap = false;
cloneRule.ranges.forEach((range) => {
- if (insertStart > range.startRow && insertStart <= range.endRow) {
+ if (!this._coversAllRows(range) && insertStart > range.startRow && insertStart <= range.endRow) {
range.endRow += insertLength;
hasLap = true;
}
@@ -310,7 +318,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const permissionRangeLapRules = this._selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((range) => {
- return moveToStartRow > range.startRow && moveToStartRow <= range.endRow;
+ return !this._coversAllRows(range) && moveToStartRow > range.startRow && moveToStartRow <= range.endRow;
});
});
@@ -323,7 +331,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const moveFromStartRow = fromRange.startRow;
let hasLap = false;
cloneRule.ranges.forEach((range) => {
- if (moveToStartRow > range.startRow && moveToStartRow <= range.endRow) {
+ if (!this._coversAllRows(range) && moveToStartRow > range.startRow && moveToStartRow <= range.endRow) {
if (moveFromStartRow < range.startRow) {
range.startRow = range.startRow - moveLength;
range.endRow = range.endRow - moveLength;
@@ -351,7 +359,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const permissionRangeLapRules = this._selectionProtectionRuleModel.getSubunitRuleList(unitId, subUnitId).filter((rule) => {
return rule.ranges.some((range) => {
- return moveToStartCol > range.startColumn && moveToStartCol <= range.endColumn;
+ return !this._coversAllColumns(range) && moveToStartCol > range.startColumn && moveToStartCol <= range.endColumn;
});
});
@@ -364,7 +372,7 @@ export class RangeProtectionRefRangeService extends Disposable {
const moveFromStartCol = fromRange.startColumn;
let hasLap = false;
cloneRule.ranges.forEach((range) => {
- if (moveToStartCol > range.startColumn && moveToStartCol <= range.endColumn) {
+ if (!this._coversAllColumns(range) && moveToStartCol > range.startColumn && moveToStartCol <= range.endColumn) {
if (moveFromStartCol < range.startColumn) {
range.startColumn = range.startColumn - moveLength;
range.endColumn = range.endColumn - moveLength;
@@ -405,6 +413,11 @@ export class RangeProtectionRefRangeService extends Disposable {
permissionListRule.forEach((rule) => {
const ranges = rule.ranges;
ranges.forEach((range) => {
+ // moving cells along an axis a whole range already covers keeps it unchanged
+ if ((isRowMove && this._coversAllRows(range)) || (!isRowMove && this._coversAllColumns(range))) {
+ return;
+ }
+
let { startRow, endRow, startColumn, endColumn } = range;
if (!Rectangle.intersects(range, sourceRange)) {
@@ -476,6 +489,12 @@ export class RangeProtectionRefRangeService extends Disposable {
permissionListRule.forEach((rule) => {
const ranges = rule.ranges;
ranges.forEach((range) => {
+ // a whole column/row protection range always covers that axis, so structural
+ // edits there only move its end instead of shifting it
+ if (this._adjustWholeRangeForStructuralChange(range, isRowOperation, isAddOperation, operationStart, operationEnd, operationCount)) {
+ return;
+ }
+
let { startRow, endRow, startColumn, endColumn } = range;
if (isAddOperation) {
@@ -536,6 +555,48 @@ export class RangeProtectionRefRangeService extends Disposable {
return range.startRow <= range.endRow && range.startColumn <= range.endColumn;
}
+ private _coversAllRows(range: IRange) {
+ return range.rangeType === RANGE_TYPE.COLUMN || range.rangeType === RANGE_TYPE.ALL;
+ }
+
+ private _coversAllColumns(range: IRange) {
+ return range.rangeType === RANGE_TYPE.ROW || range.rangeType === RANGE_TYPE.ALL;
+ }
+
+ /**
+ * A whole column/row/sheet protection range always covers that axis, so inserting or removing
+ * rows/columns there only moves its end instead of shifting it.
+ *
+ * @returns `true` when the range was adjusted as a whole range
+ */
+ private _adjustWholeRangeForStructuralChange(
+ range: IRange,
+ isRowOperation: boolean,
+ isAddOperation: boolean,
+ operationStart: number,
+ operationEnd: number,
+ operationCount: number
+ ) {
+ const coversAll = isRowOperation ? this._coversAllRows(range) : this._coversAllColumns(range);
+ if (!coversAll) {
+ return false;
+ }
+
+ const startKey = isRowOperation ? 'startRow' : 'startColumn';
+ const endKey = isRowOperation ? 'endRow' : 'endColumn';
+
+ if (isAddOperation) {
+ range[startKey] = 0;
+ range[endKey] += operationCount;
+ return true;
+ }
+
+ const removed = Math.min(operationEnd, range[endKey]) - Math.max(operationStart, 0) + 1;
+ range[startKey] = 0;
+ range[endKey] = Math.max(0, range[endKey] - Math.max(0, removed));
+ return true;
+ }
+
private _initReBuildCache() {
this.disposeWithMe(this._commandService.onCommandExecuted((command: ICommandInfo) => {
if (mutationIdByRowCol.includes(command.id) || mutationIdArrByMove.includes(command.id)) {
diff --git a/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts b/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts
index f437c07261..f2557baa8d 100644
--- a/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts
+++ b/packages/sheets/src/services/ref-range/__tests__/util-behavior.spec.ts
@@ -15,6 +15,8 @@
*/
import type { IAccessor, ICommandInfo, IRange } from '@univerjs/core';
+import { Direction, IUniverInstanceService, MAX_COLUMN_COUNT, MAX_ROW_COUNT, Range, RANGE_TYPE } from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type {
IInsertColMutationParams,
IInsertRowMutationParams,
@@ -23,8 +25,6 @@ import type {
} from '../../../basics';
import type { IMoveRangeMutationParams } from '../../../commands/mutations/move-range.mutation';
import type { IMoveColumnsMutationParams } from '../../../commands/mutations/move-rows-cols.mutation';
-import { Direction, IUniverInstanceService, MAX_COLUMN_COUNT, MAX_ROW_COUNT, Range, RANGE_TYPE } from '@univerjs/core';
-import { afterEach, describe, expect, it, vi } from 'vitest';
import { InsertColMutation, InsertRowMutation } from '../../../commands/mutations/insert-row-col.mutation';
import { MoveRangeMutation } from '../../../commands/mutations/move-range.mutation';
import { MoveColsMutation } from '../../../commands/mutations/move-rows-cols.mutation';
@@ -257,7 +257,7 @@ describe('ref range util behavior coverage', () => {
]));
});
- it('handles row/column insertion direction at the right and bottom boundaries', () => {
+ it('expands when the insertion starts at the last row and leaves ranges below it untouched', () => {
expect(handleInsertRowCommon({
id: EffectRefRangId.InsertRowCommandId,
params: { unitId: 'unit', subUnitId: 'sheet', range: r(9, 10, 0, 10), direction: Direction.DOWN },
@@ -279,6 +279,83 @@ describe('ref range util behavior coverage', () => {
}, r(2, 4, 5, 8))).toEqual([r(2, 4, 5, 10)]);
});
+ it('returns the same range for both insertion entries at one position', () => {
+ // A2:A10 as a row ref range
+ const rowTarget = r(1, 9, 2, 4);
+ const insertRow = (startRow: number, direction: Direction.UP | Direction.DOWN) => handleInsertRowCommon({
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(startRow, startRow, 0, 10), direction },
+ }, rowTarget);
+
+ // insertRowsBefore(1) and insertRowsAfter(0) create the same new row 2
+ expect(insertRow(1, Direction.UP)).toEqual(insertRow(1, Direction.DOWN));
+ expect(insertRow(1, Direction.UP)).toEqual([r(2, 10, 2, 4)]);
+
+ // insertRowsBefore(10) and insertRowsAfter(9) create the same new row 11
+ expect(insertRow(10, Direction.UP)).toEqual(insertRow(10, Direction.DOWN));
+ expect(insertRow(10, Direction.UP)).toEqual([rowTarget]);
+
+ // insertRowsBefore(5) and insertRowsAfter(4) both insert inside the range
+ expect(insertRow(5, Direction.UP)).toEqual(insertRow(5, Direction.DOWN));
+ expect(insertRow(5, Direction.UP)).toEqual([r(1, 10, 2, 4)]);
+
+ // B20:F20 as a column ref range
+ const colTarget = r(19, 19, 1, 5);
+ const insertColumn = (startColumn: number, direction: Direction.LEFT | Direction.RIGHT) => handleInsertColCommon({
+ id: EffectRefRangId.InsertColCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, startColumn, startColumn), direction },
+ }, colTarget);
+
+ // insertColumnsBefore(1) and insertColumnsAfter(0) create the same new column B
+ expect(insertColumn(1, Direction.LEFT)).toEqual(insertColumn(1, Direction.RIGHT));
+ expect(insertColumn(1, Direction.LEFT)).toEqual([r(19, 19, 2, 6)]);
+
+ // insertColumnsBefore(6) and insertColumnsAfter(5) create the same new column G
+ expect(insertColumn(6, Direction.LEFT)).toEqual(insertColumn(6, Direction.RIGHT));
+ expect(insertColumn(6, Direction.LEFT)).toEqual([colTarget]);
+
+ // insertColumnsBefore(3) and insertColumnsAfter(2) both insert inside the range
+ expect(insertColumn(3, Direction.LEFT)).toEqual(insertColumn(3, Direction.RIGHT));
+ expect(insertColumn(3, Direction.LEFT)).toEqual([r(19, 19, 1, 6)]);
+ });
+
+ it('keeps whole column and whole row ranges covering their axis', () => {
+ const wholeColumn = r(0, 9, 2, 3, RANGE_TYPE.COLUMN);
+ const insertRows = (startRow: number) => handleCommonDefaultRangeChangeWithEffectRefCommands(wholeColumn, {
+ id: EffectRefRangId.InsertRowCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(startRow, startRow, 0, 10), direction: Direction.UP },
+ });
+
+ // rows may be inserted anywhere: a whole column range covers every one of them
+ expect(insertRows(0)).toEqual([r(0, 10, 2, 3, RANGE_TYPE.COLUMN)]);
+ expect(insertRows(5)).toEqual([r(0, 10, 2, 3, RANGE_TYPE.COLUMN)]);
+
+ // columns are concrete coordinates, so the regular rules still apply
+ expect(handleCommonDefaultRangeChangeWithEffectRefCommands(wholeColumn, {
+ id: EffectRefRangId.InsertColCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 3, 3), direction: Direction.LEFT },
+ })).toEqual([r(0, 9, 2, 4, RANGE_TYPE.COLUMN)]);
+
+ // removing rows shrinks the range instead of deleting the rule
+ expect(handleCommonDefaultRangeChangeWithEffectRefCommands(wholeColumn, {
+ id: EffectRefRangId.RemoveRowCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(2, 3, 0, 10) },
+ })).toEqual([r(0, 7, 2, 3, RANGE_TYPE.COLUMN)]);
+
+ // moving rows keeps a whole column range untouched
+ expect(handleCommonDefaultRangeChangeWithEffectRefCommands(wholeColumn, {
+ id: EffectRefRangId.MoveRowsCommandId,
+ params: { fromRange: r(1, 2, 0, 10), toRange: r(6, 7, 0, 10) },
+ })).toEqual([wholeColumn]);
+
+ // and the transposed case
+ const wholeRow = r(2, 3, 0, 9, RANGE_TYPE.ROW);
+ expect(handleCommonDefaultRangeChangeWithEffectRefCommands(wholeRow, {
+ id: EffectRefRangId.InsertColCommandId,
+ params: { unitId: 'unit', subUnitId: 'sheet', range: r(0, 10, 4, 4), direction: Direction.LEFT },
+ })).toEqual([r(2, 3, 0, 10, RANGE_TYPE.ROW)]);
+ });
+
it('skips filtered rows when removing a row range', () => {
const targetRange = r(3, 8, 0, 3);
const operators = handleIRemoveRow({
diff --git a/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts b/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts
index c066e31434..4fc3681758 100644
--- a/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts
+++ b/packages/sheets/src/services/ref-range/__tests__/utils.spec.ts
@@ -15,13 +15,13 @@
*/
import type { ICommandInfo, IMutationInfo, IRange } from '@univerjs/core';
+import { Direction, RANGE_TYPE } from '@univerjs/core';
+import { beforeEach, describe, expect, it } from 'vitest';
import type { IRemoveSheetMutationParams } from '../../../basics';
import type { IInsertColCommandParams, IInsertRowCommandParams } from '../../../commands/commands/insert-row-col.command';
import type { IRemoveRowColCommandInterceptParams } from '../../../commands/commands/remove-row-col.command';
import type { IMoveRowsMutationParams } from '../../../commands/mutations/move-rows-cols.mutation';
import type { IRemoveRowColCommand } from '../type';
-import { Direction, RANGE_TYPE } from '@univerjs/core';
-import { beforeEach, describe, expect, it } from 'vitest';
import { InsertColMutation, InsertRowMutation } from '../../../commands/mutations/insert-row-col.mutation';
import { MoveColsMutation, MoveRowsMutation } from '../../../commands/mutations/move-rows-cols.mutation';
import { RemoveColMutation, RemoveRowMutation } from '../../../commands/mutations/remove-row-col.mutation';
@@ -1276,7 +1276,7 @@ describe('test ref-range move', () => {
}]);
});
- it('should handle insertion at the start of the range', () => {
+ it('should shift the range down when insertion is at the first row of the range', () => {
const info: ICommandInfo<IInsertRowCommandParams> = {
params: {
range: { startRow: 5, endRow: 7, startColumn: 0, endColumn: 5 },
@@ -1291,7 +1291,7 @@ describe('test ref-range move', () => {
const result = handleInsertRowCommon(info, targetRange);
expect(result).toEqual([{
- startRow: 5,
+ startRow: 8, // 5 + (7 - 5 + 1): inserting above the range shifts it
endRow: 13, // 10 + (7 - 5 + 1)
startColumn: 2,
endColumn: 8,
@@ -1404,7 +1404,7 @@ describe('test ref-range move', () => {
}]);
});
- it('should handle insertion at the start of the range', () => {
+ it('should shift the range right when insertion is at the first column of the range', () => {
const info: ICommandInfo<IInsertColCommandParams> = {
params: {
range: { startRow: 0, endRow: 5, startColumn: 5, endColumn: 7 },
@@ -1421,7 +1421,7 @@ describe('test ref-range move', () => {
expect(result).toEqual([{
startRow: 2,
endRow: 8,
- startColumn: 5,
+ startColumn: 8, // 5 + (7 - 5 + 1): inserting to the left of the range shifts it
endColumn: 13, // 10 + (7 - 5 + 1)
}]);
});
diff --git a/packages/sheets/src/services/ref-range/util.ts b/packages/sheets/src/services/ref-range/util.ts
index 1bee97aa68..d4471b9710 100644
--- a/packages/sheets/src/services/ref-range/util.ts
+++ b/packages/sheets/src/services/ref-range/util.ts
@@ -15,6 +15,7 @@
*/
import type { IAccessor, ICommandInfo, IMutationInfo, IRange, Nullable } from '@univerjs/core';
+import { getIntersectRange, IUniverInstanceService, MAX_COLUMN_COUNT, MAX_ROW_COUNT, mergeIntervals, ObjectMatrix, RANGE_TYPE, Rectangle } from '@univerjs/core';
import type { IInsertColMutationParams, IInsertRowMutationParams, IRemoveColMutationParams, IRemoveRowsMutationParams, IRemoveSheetMutationParams } from '../../basics';
import type { IDeleteRangeMoveLeftCommandParams } from '../../commands/commands/delete-range-move-left.command';
import type { IDeleteRangeMoveUpCommandParams } from '../../commands/commands/delete-range-move-up.command';
@@ -44,7 +45,6 @@ import type {
IRemoveRowColCommand,
IReorderRangeCommand,
} from './type';
-import { Direction, getIntersectRange, IUniverInstanceService, MAX_COLUMN_COUNT, MAX_ROW_COUNT, mergeIntervals, ObjectMatrix, RANGE_TYPE, Rectangle } from '@univerjs/core';
import { DeleteRangeMoveLeftCommand } from '../../commands/commands/delete-range-move-left.command';
import { DeleteRangeMoveUpCommand } from '../../commands/commands/delete-range-move-up.command';
import { InsertRangeMoveDownCommand } from '../../commands/commands/insert-range-move-down.command';
@@ -967,78 +967,57 @@ export const handleRemoveRowCommon = (param: IRemoveRowColCommandInterceptParams
];
};
+/**
+ * A ref range follows the data it covers, whichever command entry produced the insertion:
+ * inserting above the range shifts it down, inserting inside the range expands it, and
+ * inserting below the range leaves it untouched.
+ *
+ * `direction` only decides which row the inserted cells inherit styles and height from, so it
+ * is deliberately ignored here: two entry points that insert a row at the same position must
+ * return the same range. This matches `handleBaseInsertRange`, which serves the mutation based
+ * ref-range paths, and the collaboration transform algorithms, which cannot supply a direction
+ * at all.
+ */
export const handleInsertRowCommon = (info: ICommandInfo<IInsertRowCommandParams>, targetRange: IRange) => {
const param = info.params!;
const insertRow = param.range.startRow;
const insertCount = param.range.endRow - param.range.startRow + 1;
- const direction = param.direction;
-
- if (direction === Direction.UP) {
- if (insertRow < targetRange.startRow) {
- return [{
- ...targetRange,
- startRow: targetRange.startRow + insertCount,
- endRow: targetRange.endRow + insertCount,
- }];
- } else if (insertRow <= targetRange.endRow) {
- return [{
- ...targetRange,
- endRow: targetRange.endRow + insertCount,
- }];
- }
- } else {
- if (insertRow <= targetRange.startRow) {
- return [{
- ...targetRange,
- startRow: targetRange.startRow + insertCount,
- endRow: targetRange.endRow + insertCount,
- }];
- } else if (insertRow <= targetRange.endRow + 1) {
- return [{
- ...targetRange,
- endRow: targetRange.endRow + insertCount,
- }];
- }
+ // an endpoint moves only when the insertion point is at or above it
+ const startOffset = insertRow <= targetRange.startRow ? insertCount : 0;
+ const endOffset = insertRow <= targetRange.endRow ? insertCount : 0;
+
+ if (!startOffset && !endOffset) {
+ return [targetRange];
}
- return [targetRange];
+ return [{
+ ...targetRange,
+ startRow: targetRange.startRow + startOffset,
+ endRow: targetRange.endRow + endOffset,
+ }];
};
+/**
+ * Column counterpart of {@link handleInsertRowCommon}: a ref range follows the data it covers,
+ * so `direction` is deliberately ignored here as well.
+ */
export const handleInsertColCommon = (info: ICommandInfo<IInsertColCommandParams>, targetRange: IRange) => {
const param = info.params!;
const insertColumn = param.range.startColumn;
const insertCount = param.range.endColumn - param.range.startColumn + 1;
- const direction = param.direction;
-
- if (direction === Direction.LEFT) {
- if (insertColumn < targetRange.startColumn) {
- return [{
- ...targetRange,
- startColumn: targetRange.startColumn + insertCount,
- endColumn: targetRange.endColumn + insertCount,
- }];
- } else if (insertColumn <= targetRange.endColumn) {
- return [{
- ...targetRange,
- endColumn: targetRange.endColumn + insertCount,
- }];
- }
- } else {
- if (insertColumn <= targetRange.startColumn) {
- return [{
- ...targetRange,
- startColumn: targetRange.startColumn + insertCount,
- endColumn: targetRange.endColumn + insertCount,
- }];
- } else if (insertColumn <= targetRange.endColumn + 1) {
- return [{
- ...targetRange,
- endColumn: targetRange.endColumn + insertCount,
- }];
- }
+ // an endpoint moves only when the insertion point is at or above it
+ const startOffset = insertColumn <= targetRange.startColumn ? insertCount : 0;
+ const endOffset = insertColumn <= targetRange.endColumn ? insertCount : 0;
+
+ if (!startOffset && !endOffset) {
+ return [targetRange];
}
- return [targetRange];
+ return [{
+ ...targetRange,
+ startColumn: targetRange.startColumn + startOffset,
+ endColumn: targetRange.endColumn + endOffset,
+ }];
};
export const runRefRangeMutations = (operators: IOperator[], range: IRange) => {
@@ -1161,7 +1140,94 @@ export type MutationsAffectRange =
| IInsertRowMutationParams
| IMoveRangeMutationParams;
+const ROW_AXIS_COMMANDS: string[] = [
+ EffectRefRangId.InsertRowCommandId,
+ EffectRefRangId.RemoveRowCommandId,
+ EffectRefRangId.MoveRowsCommandId,
+ EffectRefRangId.InsertRangeMoveDownCommandId,
+ EffectRefRangId.DeleteRangeMoveUpCommandId,
+];
+
+const COLUMN_AXIS_COMMANDS: string[] = [
+ EffectRefRangId.InsertColCommandId,
+ EffectRefRangId.RemoveColCommandId,
+ EffectRefRangId.MoveColsCommandId,
+ EffectRefRangId.InsertRangeMoveRightCommandId,
+ EffectRefRangId.DeleteRangeMoveLeftCommandId,
+];
+
+/**
+ * A whole column/row/sheet range always covers the whole axis, so it does not follow concrete
+ * coordinates on that axis: structural edits there keep the range anchored at 0 and only move its
+ * end. Edits on the opposite axis still go through the regular coordinate based rules.
+ *
+ * @returns the adjusted ranges, or `undefined` when the regular logic should handle the command
+ */
+function handleWholeRangeCommand(targetRange: IRange, commandInfo: ICommandInfo): IRange[] | undefined {
+ const coversAllRows = targetRange.rangeType === RANGE_TYPE.COLUMN || targetRange.rangeType === RANGE_TYPE.ALL;
+ const coversAllColumns = targetRange.rangeType === RANGE_TYPE.ROW || targetRange.rangeType === RANGE_TYPE.ALL;
+ if (!coversAllRows && !coversAllColumns) {
+ return undefined;
+ }
+ // a typed range that still carries stale coordinates cannot be tracked reliably
+ if ((coversAllRows && !Number.isFinite(targetRange.endRow)) || (coversAllColumns && !Number.isFinite(targetRange.endColumn))) {
+ return undefined;
+ }
+
+ if (ROW_AXIS_COMMANDS.includes(commandInfo.id)) {
+ return coversAllRows ? [adjustWholeRange(targetRange, true, commandInfo)] : undefined;
+ }
+ if (COLUMN_AXIS_COMMANDS.includes(commandInfo.id)) {
+ return coversAllColumns ? [adjustWholeRange(targetRange, false, commandInfo)] : undefined;
+ }
+ if (commandInfo.id === EffectRefRangId.MoveRangeCommandId || commandInfo.id === EffectRefRangId.ReorderRangeCommandId) {
+ // moving cells around never changes how much of an axis a whole range covers
+ return [targetRange];
+ }
+ return undefined;
+}
+
+function adjustWholeRange(targetRange: IRange, isRow: boolean, commandInfo: ICommandInfo): IRange {
+ const currentEnd = isRow ? targetRange.endRow : targetRange.endColumn;
+
+ switch (commandInfo.id) {
+ case EffectRefRangId.InsertRowCommandId:
+ case EffectRefRangId.InsertColCommandId: {
+ const params = commandInfo.params as IInsertRowCommandParams | IInsertColCommandParams;
+ const count = isRow
+ ? params.range.endRow - params.range.startRow + 1
+ : params.range.endColumn - params.range.startColumn + 1;
+
+ return isRow
+ ? { ...targetRange, startRow: 0, endRow: currentEnd + count }
+ : { ...targetRange, startColumn: 0, endColumn: currentEnd + count };
+ }
+ case EffectRefRangId.RemoveRowCommandId:
+ case EffectRefRangId.RemoveColCommandId: {
+ const params = commandInfo.params as IRemoveRowColCommandInterceptParams;
+ const removedRanges = params.ranges ?? (params.range ? [params.range] : []);
+ const intervals: [number, number][] = removedRanges.map((range) => (isRow ? [range.startRow, range.endRow] : [range.startColumn, range.endColumn]));
+ const removedCount = mergeIntervals(intervals).reduce((total, [start, end]) => {
+ const overlap = Math.min(end, currentEnd) - Math.max(start, 0) + 1;
+ return total + Math.max(0, overlap);
+ }, 0);
+
+ return isRow
+ ? { ...targetRange, startRow: 0, endRow: Math.max(0, currentEnd - removedCount) }
+ : { ...targetRange, startColumn: 0, endColumn: Math.max(0, currentEnd - removedCount) };
+ }
+ default:
+ // shifting cells along the axis keeps the whole axis covered
+ return targetRange;
+ }
+}
+
export const handleCommonDefaultRangeChangeWithEffectRefCommands = (range: IRange, commandInfo: ICommandInfo): IRange[] => {
+ const wholeRangeResult = handleWholeRangeCommand(range, commandInfo);
+ if (wholeRangeResult) {
+ return wholeRangeResult;
+ }
+
let operator: IOperator[] = [];
switch (commandInfo.id) {
case EffectRefRangId.DeleteRangeMoveLeftCommandId: {