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): clamp validation ranges to sheet bounds (#7692)
wpxp123456d139c3ddec10
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.spec.tsindex 86197e16ec..07c76fe683 100644--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.spec.ts+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/utils-extra.spec.ts@@ -52,8 +52,10 @@ describe('conditional formatting calculate utilities', () => {expect(filterRange([{ startRow: 0, startColumn: 0, endRow: 10, endColumn: 10 },{ startRow: 100, startColumn: 0, endRow: 101, endColumn: 1 },+ { startRow: -2, startColumn: -3, endRow: 1, endColumn: 2 },], 5, 6)).toEqual([{ startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 },+ { startRow: 0, startColumn: 0, endRow: 1, endColumn: 2 },]);});@@ -149,6 +151,10 @@ describe('conditional formatting calculate utilities', () => {};},},+ worksheet: {+ getMaxRows: () => 2,+ getMaxColumns: () => 2,+ },} as any);expect(matrix.getValue(0, 0)).toBe('hit');expect(matrix.getValue(1, 1)).toBeUndefined();diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.tsindex bc49ffb015..a796efc951 100644--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.ts+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.ts@@ -21,6 +21,7 @@ import { BooleanNumber, CellValueType, ColorKit, DateSystem, excelSerialToDateTiimport { BooleanValue, FormulaResultStatus } from '@univerjs/engine-formula';import { CFNumberOperator, CFValueType } from '../../base/const';import { ConditionalFormattingFormulaService } from '../../services/conditional-formatting-formula.service';+import { getRangesInWorksheet } from '../../utils/range';import { ConditionalFormattingViewModel } from '../conditional-formatting-view-model';export function isFloatsEqual(a: number, b: number) {@@ -143,7 +144,7 @@ export const getCacheStyleMatrix = <S = any>(unitId: string, subUnitId: string,const { accessor } = context;const conditionalFormattingViewModel = accessor.get(ConditionalFormattingViewModel);const matrix = new ObjectMatrix<S>();- rule.ranges.forEach((range) => {+ getRangesInWorksheet(rule.ranges, context.worksheet).forEach((range) => {Range.foreach(range, (row, col) => {const cellCfItem = conditionalFormattingViewModel.getCellCfs(unitId, subUnitId, row, col);if (cellCfItem) {@@ -262,12 +263,17 @@ export const getColorScaleFromValue = (colorList: { color: ColorKit; value: numbexport const filterRange = (ranges: IRange[], maxRow: number, maxCol: number): IRange[] => {return ranges.map((range) => {- if (range.startColumn > maxCol || range.startRow > maxRow) {+ if (range.startColumn > maxCol || range.startRow > maxRow || range.endColumn < 0 || range.endRow < 0) {return null as unknown as IRange;}const _range = { ...range };+ _range.startRow = Math.max(_range.startRow, 0);+ _range.startColumn = Math.max(_range.startColumn, 0);_range.endRow = Math.min(_range.endRow, maxRow);_range.endColumn = Math.min(_range.endColumn, maxCol);+ if (_range.startRow > _range.endRow || _range.startColumn > _range.endColumn) {+ return null as unknown as IRange;+ }return _range;}).filter((range) => !!range);};diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.tsindex 6feb06b3aa..a9e5737fb9 100644--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-formula.service.spec.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { CellValueType, Injector } from '@univerjs/core';+import { CellValueType, Injector, IUniverInstanceService } from '@univerjs/core';import { FormulaResultStatus, RegisterOtherFormulaService } from '@univerjs/engine-formula';import { Subject } from 'rxjs';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -41,6 +41,19 @@ describe('ConditionalFormattingFormulaService', () => {$ruleChange = ruleChange$;}+ class TestUniverInstanceService {+ getUnit() {+ return {+ getSheetBySheetId() {+ return {+ getMaxRows: () => 20,+ getMaxColumns: () => 10,+ };+ },+ };+ }+ }+beforeEach(() => {formulaResults = new Map();registerFormulaWithRange = vi.fn(() => 'formula-1');@@ -50,6 +63,7 @@ describe('ConditionalFormattingFormulaService', () => {const injector = new Injector();injector.add([RegisterOtherFormulaService, { useClass: TestRegisterOtherFormulaService as never }]);injector.add([ConditionalFormattingRuleModel, { useClass: TestConditionalFormattingRuleModel as never }]);+ injector.add([IUniverInstanceService, { useClass: TestUniverInstanceService as never }]);injector.add([ConditionalFormattingFormulaService]);service = injector.get(ConditionalFormattingFormulaService);});@@ -74,6 +88,26 @@ describe('ConditionalFormattingFormulaService', () => {);});+ it('clips formula ranges to the worksheet and skips ranges outside it', () => {+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0', [+ { startRow: 0, endRow: 1048575, startColumn: 0, endColumn: 16383 },+ ]);+ service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-2', '=A1>0', [+ { startRow: 20, endRow: 30, startColumn: 10, endColumn: 20 },+ ]);++ expect(registerFormulaWithRange).toHaveBeenCalledTimes(1);+ expect(registerFormulaWithRange).toHaveBeenCalledWith(+ 'book-1',+ 'sheet-1',+ '=A1>0',+ [{ startRow: 0, endRow: 19, startColumn: 0, endColumn: 9 }],+ undefined,+ expect.any(String),+ 'cf-1'+ );+ });+it('returns boolean formula results as business booleans for conditional checks', () => {service.registerFormulaWithRange('book-1', 'sheet-1', 'cf-1', '=A1>0');formulaResults.set('formula-1', {diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.tsindex 4d3ce3f5b6..82fae0c17d 100644--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting-formula.service.ts@@ -14,14 +14,15 @@* limitations under the License.*/-import type { ICellData, IRange, Nullable } from '@univerjs/core';+import type { ICellData, IRange, Nullable, Workbook } from '@univerjs/core';import type { IOtherFormulaResult } from '@univerjs/engine-formula';import type { IConditionalFormattingRuleConfig, IConditionFormattingRule } from '../models/type';-import { BooleanNumber, CellValueType, Disposable, Inject, ObjectMatrix, RefAlias } from '@univerjs/core';+import { BooleanNumber, CellValueType, Disposable, Inject, IUniverInstanceService, ObjectMatrix, RefAlias, UniverInstanceType } from '@univerjs/core';import { FormulaResultStatus, OtherFormulaBizType, RegisterOtherFormulaService } from '@univerjs/engine-formula';import { Subject } from 'rxjs';import { CFRuleType, CFSubRuleType, CFValueType } from '../base/const';import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';+import { getRangesInWorksheet } from '../utils/range';// eslint-disable-next-line ts/consistent-type-definitionstype IFormulaItem = {@@ -43,7 +44,8 @@ export class ConditionalFormattingFormulaService extends Disposable {constructor(@Inject(RegisterOtherFormulaService) private _registerOtherFormulaService: RegisterOtherFormulaService,- @Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel+ @Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,+ @IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService) {super();this._initFormulaResultChange();@@ -152,9 +154,19 @@ export class ConditionalFormattingFormulaService extends Disposable {if (formulaMap.getValue(cfFormulaId, ['id'])) {return;}+ const worksheet = this._univerInstanceService+ .getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ return;+ }+ const effectiveRanges = getRangesInWorksheet(ranges, worksheet);+ if (!effectiveRanges.length) {+ return;+ }// Always sort ranges by top-left so the formula engine uses a consistent anchor (ranges[0])// regardless of the call path (e.g. rule-add event vs preComputing).- const sortedRanges = [...ranges].sort((a, b) =>+ const sortedRanges = effectiveRanges.sort((a, b) =>a.startRow !== b.startRow ? a.startRow - b.startRow : a.startColumn - b.startColumn);const formulaId = this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formulaText, sortedRanges, undefined, OtherFormulaBizType.CONDITIONAL_FORMATTING, cfId);diff --git a/packages/sheets-conditional-formatting/src/utils/range.ts b/packages/sheets-conditional-formatting/src/utils/range.tsnew file mode 100644index 0000000000..e472a7207f--- /dev/null+++ b/packages/sheets-conditional-formatting/src/utils/range.ts@@ -0,0 +1,55 @@+/**+ * 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 { IRange, Nullable, Worksheet } from '@univerjs/core';+import { getIntersectRange, Range } from '@univerjs/core';++export function getRangeInWorksheet(range: IRange, worksheet: Worksheet): Nullable<IRange> {+ const maxRows = worksheet.getMaxRows();+ const maxColumns = worksheet.getMaxColumns();+ if (maxRows <= 0 || maxColumns <= 0) {+ return null;+ }++ const effectiveRange = getIntersectRange(Range.transformRange(range, worksheet), {+ startRow: 0,+ endRow: maxRows - 1,+ startColumn: 0,+ endColumn: maxColumns - 1,+ });+ if (!effectiveRange) {+ return null;+ }++ return {+ startRow: effectiveRange.startRow,+ endRow: effectiveRange.endRow,+ startColumn: effectiveRange.startColumn,+ endColumn: effectiveRange.endColumn,+ };+}++export function getRangesInWorksheet(ranges: IRange[], worksheet: Worksheet): IRange[] {+ const effectiveRanges: IRange[] = [];+ ranges.forEach((range) => {+ const effectiveRange = getRangeInWorksheet(range, worksheet);+ if (effectiveRange) {+ effectiveRanges.push(effectiveRange);+ }+ });++ return effectiveRanges;+}diff --git a/packages/sheets-data-validation/src/commands/commands/data-validation.command.ts b/packages/sheets-data-validation/src/commands/commands/data-validation.command.tsindex 30b34ae569..c707285d8b 100644--- a/packages/sheets-data-validation/src/commands/commands/data-validation.command.ts+++ b/packages/sheets-data-validation/src/commands/commands/data-validation.command.ts@@ -63,6 +63,7 @@ import { getSheetCommandTarget, SetRangeValuesMutation, SetRangeValuesUndoMutatiimport { SheetDataValidationModel } from '../../models/sheet-data-validation-model';import { shouldOffsetFormulaByRange } from '../../utils/formula';import { getStringCellValue } from '../../utils/get-cell-data-origin';+import { getRangesInWorksheet } from '../../utils/range';import { CHECKBOX_FORMULA_1, CHECKBOX_FORMULA_2 } from '../../validators';export interface IUpdateSheetDataValidationRangeCommandParams {@@ -114,7 +115,7 @@ export function getDataValidationDiffMutations(if (!fillDefaultValue) {return;}- ranges.forEach((range) => {+ getRangesInWorksheet(ranges, worksheet).forEach((range) => {Range.foreach(range, (row, column) => {const cellData = worksheet.getCellRaw(row, column);const value = getStringCellValue(cellData);@@ -486,7 +487,7 @@ export const UpdateSheetDataValidationSettingCommand: ICommand<IUpdateSheetDataVconst { formula2: oldFormula2 = CHECKBOX_FORMULA_2, formula1: oldFormula1 = CHECKBOX_FORMULA_1 } = rule;const { formula2 = CHECKBOX_FORMULA_2, formula1 = CHECKBOX_FORMULA_1 } = setting;let setted = false;- ranges.forEach((range) => {+ getRangesInWorksheet(ranges, worksheet).forEach((range) => {Range.foreach(range, (row, column) => {const cellData = worksheet.getCellRaw(row, column);const value = getStringCellValue(cellData);diff --git a/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts b/packages/sheets-data-validation/src/controllers/dv-formula.controller.tsindex d2afecaa95..6026417d3e 100644--- a/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts+++ b/packages/sheets-data-validation/src/controllers/dv-formula.controller.ts@@ -20,6 +20,7 @@ import { Disposable, Inject, IPermissionService, IUniverInstanceService, UniverIimport { deserializeRangeWithSheetWithCache, LexerTreeBuilder } from '@univerjs/engine-formula';import { UnitAction } from '@univerjs/protocol';import { WorksheetViewPermission } from '@univerjs/sheets';+import { getRangeInWorksheet } from '../utils/range';export class DataValidationFormulaController extends Disposable {constructor(@@ -57,7 +58,11 @@ export class DataValidationFormulaController extends Disposable {if (!targetSheet) {return false;}- const { startRow, endRow, startColumn, endColumn } = sequenceGrid.range;+ const range = getRangeInWorksheet(sequenceGrid.range, targetSheet);+ if (!range) {+ continue;+ }+ const { startRow, endRow, startColumn, endColumn } = range;for (let i = startRow; i <= endRow; i++) {for (let j = startColumn; j <= endColumn; j++) {const permission = (targetSheet.getCell(i, j) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0];diff --git a/packages/sheets-data-validation/src/facade/f-range.ts b/packages/sheets-data-validation/src/facade/f-range.tsindex 3719786242..0ad1269595 100644--- a/packages/sheets-data-validation/src/facade/f-range.ts+++ b/packages/sheets-data-validation/src/facade/f-range.ts@@ -18,7 +18,13 @@ import type { IDataValidationRule, IRange, Nullable } from '@univerjs/core';import type { IAddSheetDataValidationCommandParams, IClearRangeDataValidationCommandParams } from '@univerjs/sheets-data-validation';import type { IDataValidationError } from './f-workbook';import { DataValidationStatus } from '@univerjs/core';-import { AddSheetDataValidationCommand, ClearRangeDataValidationCommand, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';+import {+ AddSheetDataValidationCommand,+ ClearRangeDataValidationCommand,+ getRangesInWorksheet,+ SheetDataValidationModel,+ SheetsDataValidationValidatorService,+} from '@univerjs/sheets-data-validation';import { FRange } from '@univerjs/sheets/facade';import { FDataValidation } from './f-data-validation';@@ -246,7 +252,7 @@ export class FRangeSheetsDataValidationMixin extends FRange implements IFRangeShconst sheetName = worksheet.getName();const errors: IDataValidationError[] = [];- for (const range of ranges) {+ for (const range of getRangesInWorksheet(ranges, worksheet)) {const promises: Promise<void>[] = [];for (let row = range.startRow; row <= range.endRow; row++) {diff --git a/packages/sheets-data-validation/src/facade/f-workbook.ts b/packages/sheets-data-validation/src/facade/f-workbook.tsindex 2b2e17a77e..970b31be85 100644--- a/packages/sheets-data-validation/src/facade/f-workbook.ts+++ b/packages/sheets-data-validation/src/facade/f-workbook.ts@@ -16,7 +16,11 @@import type { IDataValidationRule, IRange, Nullable, ObjectMatrix } from '@univerjs/core';import { DataValidationStatus } from '@univerjs/core';-import { SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';+import {+ getRangesInWorksheet,+ SheetDataValidationModel,+ SheetsDataValidationValidatorService,+} from '@univerjs/sheets-data-validation';import { FWorkbook } from '@univerjs/sheets/facade';export interface IDataValidationError {@@ -124,7 +128,7 @@ export class FWorkbookSheetsDataValidationMixin extends FWorkbook implements IFWconst sheetName = worksheet.getName();const errors: IDataValidationError[] = [];- for (const range of ranges) {+ for (const range of getRangesInWorksheet(ranges, worksheet)) {const promises: Promise<void>[] = [];for (let row = range.startRow; row <= range.endRow; row++) {diff --git a/packages/sheets-data-validation/src/facade/f-worksheet.ts b/packages/sheets-data-validation/src/facade/f-worksheet.tsindex cddc8c72b5..d71f18fd34 100644--- a/packages/sheets-data-validation/src/facade/f-worksheet.ts+++ b/packages/sheets-data-validation/src/facade/f-worksheet.ts@@ -18,7 +18,11 @@ import type { IDataValidationRule, IRange, Nullable, ObjectMatrix } from '@univeimport type { IDataValidationError } from './f-workbook';import { DataValidationStatus } from '@univerjs/core';import { DataValidationModel } from '@univerjs/data-validation';-import { SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';+import {+ getRangesInWorksheet,+ SheetDataValidationModel,+ SheetsDataValidationValidatorService,+} from '@univerjs/sheets-data-validation';import { FWorksheet } from '@univerjs/sheets/facade';import { FDataValidation } from './f-data-validation';@@ -138,7 +142,7 @@ export class FWorksheetDataValidationMixin extends FWorksheet implements IFWorksconst sheetName = worksheet.getName();const errors: IDataValidationError[] = [];- for (const range of ranges) {+ for (const range of getRangesInWorksheet(ranges, worksheet)) {const promises: Promise<void>[] = [];for (let row = range.startRow; row <= range.endRow; row++) {diff --git a/packages/sheets-data-validation/src/index.ts b/packages/sheets-data-validation/src/index.tsindex fe3690233a..6b5a963022 100644--- a/packages/sheets-data-validation/src/index.ts+++ b/packages/sheets-data-validation/src/index.ts@@ -49,6 +49,7 @@ export { createDefaultNewRule } from './utils/create';export { getFormulaCellData, getFormulaResult } from './utils/formula';export { isLegalFormulaResult } from './utils/formula';export { getCellValueOrigin } from './utils/get-cell-data-origin';+export { getRangesInWorksheet } from './utils/range';export {CHECKBOX_FORMULA_1,CHECKBOX_FORMULA_2,diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.tsindex f298fd8e62..464a779252 100644--- a/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.ts+++ b/packages/sheets-data-validation/src/services/__tests__/dv-cache.service.spec.ts@@ -36,6 +36,14 @@ function createService(ruleRanges: IRange[] = [{ startRow: 1, endRow: 2, startCo} as unknown as ICommandService;const univerInstanceService = {unitDisposed$,+ getUnit: vi.fn(() => ({+ getSheetBySheetId: vi.fn((subUnitId: string) => subUnitId === 'sheet-1'+ ? {+ getMaxRows: () => 3,+ getMaxColumns: () => 3,+ }+ : null),+ })),} as unknown as IUniverInstanceService;const dataValidationModel = {getRules: vi.fn(() => [createRule(ruleRanges)]),@@ -131,4 +139,47 @@ describe('DataValidationCacheService', () => {service.dispose();});++ it('limits oversized ranges to the worksheet bounds', () => {+ const { service } = createService();+ const cache = service.ensureCache('unit-1', 'sheet-1');+ const oversizedRange = [{+ startRow: 0,+ endRow: 1048575,+ startColumn: 0,+ endColumn: 16383,+ }];++ cache.setValue(0, 0, 1 as never);+ cache.setValue(2, 2, 2 as never);+ cache.setValue(3, 3, 3 as never);++ service.markRangeDirty('unit-1', 'sheet-1', oversizedRange);++ expect(service.getValue('unit-1', 'sheet-1', 0, 0)).toBeUndefined();+ expect(service.getValue('unit-1', 'sheet-1', 2, 2)).toBeUndefined();+ expect(service.getValue('unit-1', 'sheet-1', 3, 3)).toBe(3);++ service.removeRule('unit-1', 'sheet-1', createRule(oversizedRange));++ expect(cache.getMatrix()[0]).toBeUndefined();+ expect(cache.getMatrix()[2]).toBeUndefined();+ expect(service.getValue('unit-1', 'sheet-1', 3, 3)).toBe(3);++ service.dispose();+ });++ it('skips cached cells when rule ranges are completely outside the worksheet', () => {+ const { service } = createService();+ const cache = service.ensureCache('unit-1', 'sheet-1');+ const outsideRange = [{ startRow: 3, endRow: 10, startColumn: 3, endColumn: 10 }];++ cache.setValue(0, 0, 1 as never);+ service.markRangeDirty('unit-1', 'sheet-1', outsideRange);+ service.removeRule('unit-1', 'sheet-1', createRule(outsideRange));++ expect(service.getValue('unit-1', 'sheet-1', 0, 0)).toBe(1);++ service.dispose();+ });});diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.tsindex d50348b8c1..21b0d6984d 100644--- a/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.ts+++ b/packages/sheets-data-validation/src/services/__tests__/dv-custom-formula.service.spec.ts@@ -52,7 +52,15 @@ describe('DataValidationCustomFormulaService', () => {markRangeDirty: vi.fn(),} as unknown as DataValidationCacheService;const service = new DataValidationCustomFormulaService(- { getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET) } as unknown as IUniverInstanceService,+ {+ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET),+ getUnit: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => ({+ getMaxRows: () => 20,+ getMaxColumns: () => 20,+ })),+ })),+ } as unknown as IUniverInstanceService,registerOtherFormulaService,dataValidationModel,cacheService,@@ -100,6 +108,64 @@ describe('DataValidationCustomFormulaService', () => {service.dispose();});+ it('clips formula registration ranges to the worksheet and skips ranges outside it', () => {+ const registerFormulaWithRange = vi.fn(() => 'formula-1');+ const service = new DataValidationCustomFormulaService(+ {+ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_SHEET),+ getUnit: vi.fn(() => ({+ getSheetBySheetId: vi.fn(() => ({+ getMaxRows: () => 20,+ getMaxColumns: () => 10,+ })),+ })),+ } as unknown as IUniverInstanceService,+ {+ formulaResult$: new Subject<any>(),+ registerFormulaWithRange,+ deleteFormula: vi.fn(),+ getFormulaValue: vi.fn(),+ getFormulaValueSync: vi.fn(),+ markFormulaDirty: vi.fn(),+ } as unknown as RegisterOtherFormulaService,+ {+ getRuleById: vi.fn(),+ getRules: vi.fn(() => []),+ } as unknown as DataValidationModel,+ {+ dirtyRanges$: new Subject<any>(),+ markRangeDirty: vi.fn(),+ } as unknown as DataValidationCacheService,+ { getValidatorItem: vi.fn(() => ({ offsetFormulaByRange: true })) } as unknown as DataValidatorRegistryService+ );++ service.addRule('unit-1', 'sheet-1', {+ uid: 'rule-1',+ type: DataValidationType.DATE,+ formula1: '=A1',+ ranges: [{ startRow: 0, endRow: 1048575, startColumn: 0, endColumn: 16383 }],+ } as any);+ service.addRule('unit-1', 'sheet-1', {+ uid: 'rule-2',+ type: DataValidationType.DATE,+ formula1: '=A1',+ ranges: [{ startRow: 20, endRow: 30, startColumn: 10, endColumn: 20 }],+ } as any);++ expect(registerFormulaWithRange).toHaveBeenCalledTimes(1);+ expect(registerFormulaWithRange).toHaveBeenCalledWith(+ 'unit-1',+ 'sheet-1',+ '=A1',+ [{ startRow: 0, endRow: 19, startColumn: 0, endColumn: 9 }],+ { ruleId: 'rule-1' },+ OtherFormulaBizType.DATA_VALIDATION_CUSTOM,+ 'rule-1'+ );++ service.dispose();+ });+it('skips non-offset rules and returns undefined for missing formulas', async () => {const service = new DataValidationCustomFormulaService({ getUnitType: vi.fn(() => UniverInstanceType.UNIVER_DOC) } as unknown as IUniverInstanceService,diff --git a/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.tsindex 9fed34efc1..98f8d82b6a 100644--- a/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts+++ b/packages/sheets-data-validation/src/services/__tests__/dv-validator.service.spec.ts@@ -191,4 +191,28 @@ describe('SheetsDataValidationValidatorService', () => {service.dispose();});++ it('limits validation and rule lookup to the worksheet bounds', async () => {+ const { service, model } = createService();+ const oversizedRange = { startRow: 0, endRow: 1048575, startColumn: 0, endColumn: 16383 };+ const getValue = vi.fn(() => undefined);+ model.getRules = vi.fn(() => [createRule('rule-1', [oversizedRange])]);+ model.getRuleObjectMatrix = vi.fn(() => ({ getValue }) as never);++ await service.validatorRanges('unit-1', 'sheet-1', [oversizedRange]);+ expect(model.validator).toHaveBeenCalledTimes(400);++ model.validator = vi.fn((_rule: IDataValidationRule, _pos: ISheetLocation, onComplete?: (status: DataValidationStatus, changed: boolean) => void) => {+ onComplete?.(DataValidationStatus.INVALID, true);+ return DataValidationStatus.INVALID;+ });+ await service.validatorWorksheet('unit-1', 'sheet-1');+ expect(model.validator).toHaveBeenCalledTimes(400);++ service.getDataValidations('unit-1', 'sheet-1', [oversizedRange]);+ expect(getValue).toHaveBeenCalledTimes(400);++ await expect(service.validatorRanges('unit-1', 'sheet-1', [{ startRow: 20, endRow: 30, startColumn: 20, endColumn: 30 }])).resolves.toEqual([]);+ service.dispose();+ });});diff --git a/packages/sheets-data-validation/src/services/dv-cache.service.ts b/packages/sheets-data-validation/src/services/dv-cache.service.tsindex e37d13fe8b..f9b665c586 100644--- a/packages/sheets-data-validation/src/services/dv-cache.service.ts+++ b/packages/sheets-data-validation/src/services/dv-cache.service.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import type { DataValidationStatus, IRange, ISheetDataValidationRule, Nullable } from '@univerjs/core';+import type { DataValidationStatus, IRange, ISheetDataValidationRule, Nullable, Workbook } from '@univerjs/core';import type { IRemoveSheetMutationParams, ISetRangeValuesMutationParams } from '@univerjs/sheets';import {Disposable,@@ -29,6 +29,7 @@ import {import { DataValidationModel } from '@univerjs/data-validation';import { RemoveSheetMutation, SetRangeValuesMutation } from '@univerjs/sheets';import { Subject } from 'rxjs';+import { getRangesInWorksheet } from '../utils/range';export class DataValidationCacheService extends Disposable {private _cacheMatrix: Map<string, Map<string, ObjectMatrix<Nullable<DataValidationStatus>>>> = new Map();@@ -119,9 +120,21 @@ export class DataValidationCacheService extends Disposable {this._deleteRange(unitId, subUnitId, rule.ranges);}+ private _getEffectiveRanges(unitId: string, subUnitId: string, ranges: IRange[]) {+ const worksheet = this._univerInstanceService+ .getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ return [];+ }++ return getRangesInWorksheet(ranges, worksheet);+ }+markRangeDirty(unitId: string, subUnitId: string, ranges: IRange[], isSetRange?: boolean) {const cache = this._ensureCache(unitId, subUnitId);- ranges.forEach((range) => {+ const effectiveRanges = this._getEffectiveRanges(unitId, subUnitId, ranges);+ effectiveRanges.forEach((range) => {Range.foreach(range, (row, col) => {if (cache.getValue(row, col) !== undefined) {cache.setValue(row, col, undefined);@@ -134,7 +147,8 @@ export class DataValidationCacheService extends Disposable {private _deleteRange(unitId: string, subUnitId: string, ranges: IRange[]) {const cache = this._ensureCache(unitId, subUnitId);- ranges.forEach((range) => {+ const effectiveRanges = this._getEffectiveRanges(unitId, subUnitId, ranges);+ effectiveRanges.forEach((range) => {Range.foreach(range, (row, col) => {cache.realDeleteValue(row, col);});diff --git a/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts b/packages/sheets-data-validation/src/services/dv-custom-formula.service.tsindex 98b2e6f8b9..7bda929b26 100644--- a/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts+++ b/packages/sheets-data-validation/src/services/dv-custom-formula.service.ts@@ -14,11 +14,12 @@* limitations under the License.*/-import type { IRange, ISheetDataValidationRule } from '@univerjs/core';+import type { IRange, ISheetDataValidationRule, Workbook } from '@univerjs/core';import { Disposable, Inject, isFormulaString, IUniverInstanceService, Rectangle, UniverInstanceType } from '@univerjs/core';import { DataValidationModel, DataValidatorRegistryService } from '@univerjs/data-validation';import { OtherFormulaBizType, RegisterOtherFormulaService } from '@univerjs/engine-formula';import { getFormulaCellData, shouldOffsetFormulaByRange } from '../utils/formula';+import { getRangesInWorksheet } from '../utils/range';import { DataValidationCacheService } from './dv-cache.service';interface IFormulaData {@@ -157,12 +158,22 @@ export class DataValidationCustomFormulaService extends Disposable {private _addFormulaByRange(unitId: string, subUnitId: string, ruleId: string, formula: string | undefined, formula2: string | undefined, ranges: IRange[]) {const { ruleFormulaMap, ruleFormulaMap2 } = this._ensureMaps(unitId, subUnitId);+ const worksheet = this._instanceSrv+ .getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ return;+ }+ const effectiveRanges = getRangesInWorksheet(ranges, worksheet);+ if (!effectiveRanges.length) {+ return;+ }- const originRow = ranges[0].startRow;- const originCol = ranges[0].startColumn;+ const originRow = effectiveRanges[0].startRow;+ const originCol = effectiveRanges[0].startColumn;if (formula && isFormulaString(formula)) {- const formulaId = this._registerFormula(unitId, subUnitId, ruleId, formula, ranges);+ const formulaId = this._registerFormula(unitId, subUnitId, ruleId, formula, effectiveRanges);ruleFormulaMap.set(ruleId, {formula,originCol,@@ -172,7 +183,7 @@ export class DataValidationCustomFormulaService extends Disposable {}if (formula2 && isFormulaString(formula2)) {- const formulaId2 = this._registerFormula(unitId, subUnitId, ruleId, formula2, ranges);+ const formulaId2 = this._registerFormula(unitId, subUnitId, ruleId, formula2, effectiveRanges);ruleFormulaMap2.set(ruleId, {formula: formula2,originCol,diff --git a/packages/sheets-data-validation/src/services/dv-validator.service.ts b/packages/sheets-data-validation/src/services/dv-validator.service.tsindex bfd56e232d..f228b6ef88 100644--- a/packages/sheets-data-validation/src/services/dv-validator.service.ts+++ b/packages/sheets-data-validation/src/services/dv-validator.service.ts@@ -18,6 +18,7 @@ import type { IDataValidationRule, IRange, Nullable, ObjectMatrix, Workbook, Worimport { bufferDebounceTime, DataValidationStatus, Disposable, getIntersectRange, Inject, IUniverInstanceService, LifecycleService, LifecycleStages, Range, Tools, UniverInstanceType } from '@univerjs/core';import { bufferWhen, filter, skip } from 'rxjs';import { SheetDataValidationModel } from '../models/sheet-data-validation-model';+import { getRangesInWorksheet } from '../utils/range';import { DataValidationCacheService } from './dv-cache.service';export class SheetsDataValidationValidatorService extends Disposable {@@ -54,7 +55,7 @@ export class SheetsDataValidationValidatorService extends Disposable {if (!worksheet) {return;}- map[range.unitId][range.subUnitId].push(...range.ranges.map((range) => Range.transformRange(range, worksheet)));+ map[range.unitId][range.subUnitId].push(...getRangesInWorksheet(range.ranges, worksheet));});Object.entries(map).forEach(([unitId, subUnitMap]) => {@@ -131,14 +132,14 @@ export class SheetsDataValidationValidatorService extends Disposable {throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);}- const allRules = this._sheetDataValidationModel.getRules(unitId, subUnitId);- const ruleRanges: IRange[] = [];- for (const rule of allRules) {- ruleRanges.push(...rule.ranges);- }+ const effectiveRanges = getRangesInWorksheet(ranges, worksheet);+ const ruleRanges = getRangesInWorksheet(+ this._sheetDataValidationModel.getRules(unitId, subUnitId).flatMap((rule) => rule.ranges),+ worksheet+ );const intersectRanges: IRange[] = [];- for (const range of ranges) {+ for (const range of effectiveRanges) {for (const ruleRange of ruleRanges) {const intersect = getIntersectRange(range, ruleRange);if (intersect) {@@ -201,18 +202,17 @@ export class SheetsDataValidationValidatorService extends Disposable {if (!worksheet) {throw new Error(`cannot find current worksheet, sheetId: ${subUnitId}`);}- const rules = this._sheetDataValidationModel.getRules(unitId, subUnitId);+ const ranges = getRangesInWorksheet(+ this._sheetDataValidationModel.getRules(unitId, subUnitId).flatMap((rule) => rule.ranges),+ worksheet+ );await Promise.all(- rules.map((rule) => {- return Promise.all(- rule.ranges.map((range) => {- const promises: Promise<DataValidationStatus>[] = [];- Range.foreach(range, (row, col) => {- promises.push(this._validatorByCell(workbook, worksheet, row, col));- });- return Promise.all(promises);- })- );+ ranges.map((range) => {+ const promises: Promise<DataValidationStatus>[] = [];+ Range.foreach(range, (row, col) => {+ promises.push(this._validatorByCell(workbook, worksheet, row, col));+ });+ return Promise.all(promises);}));@@ -233,9 +233,16 @@ export class SheetsDataValidationValidatorService extends Disposable {}getDataValidations(unitId: string, subUnitId: string, ranges: IRange[]): IDataValidationRule[] {+ const worksheet = this._univerInstanceService+ .getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET)+ ?.getSheetBySheetId(subUnitId);+ if (!worksheet) {+ return [];+ }+const ruleMatrix = this._sheetDataValidationModel.getRuleObjectMatrix(unitId, subUnitId);const ruleIdSet = new Set<string>();- ranges.forEach((range) => {+ getRangesInWorksheet(ranges, worksheet).forEach((range) => {Range.foreach(range, (row, col) => {const ruleId = ruleMatrix.getValue(row, col);if (ruleId) {diff --git a/packages/sheets-data-validation/src/utils/range.ts b/packages/sheets-data-validation/src/utils/range.tsnew file mode 100644index 0000000000..e472a7207f--- /dev/null+++ b/packages/sheets-data-validation/src/utils/range.ts@@ -0,0 +1,55 @@+/**+ * 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 { IRange, Nullable, Worksheet } from '@univerjs/core';+import { getIntersectRange, Range } from '@univerjs/core';++export function getRangeInWorksheet(range: IRange, worksheet: Worksheet): Nullable<IRange> {+ const maxRows = worksheet.getMaxRows();+ const maxColumns = worksheet.getMaxColumns();+ if (maxRows <= 0 || maxColumns <= 0) {+ return null;+ }++ const effectiveRange = getIntersectRange(Range.transformRange(range, worksheet), {+ startRow: 0,+ endRow: maxRows - 1,+ startColumn: 0,+ endColumn: maxColumns - 1,+ });+ if (!effectiveRange) {+ return null;+ }++ return {+ startRow: effectiveRange.startRow,+ endRow: effectiveRange.endRow,+ startColumn: effectiveRange.startColumn,+ endColumn: effectiveRange.endColumn,+ };+}++export function getRangesInWorksheet(ranges: IRange[], worksheet: Worksheet): IRange[] {+ const effectiveRanges: IRange[] = [];+ ranges.forEach((range) => {+ const effectiveRange = getRangeInWorksheet(range, worksheet);+ if (effectiveRange) {+ effectiveRanges.push(effectiveRange);+ }+ });++ return effectiveRanges;+}diff --git a/packages/sheets-data-validation/src/validators/util.ts b/packages/sheets-data-validation/src/validators/util.tsindex e6ad8c0206..924e6be418 100644--- a/packages/sheets-data-validation/src/validators/util.ts+++ b/packages/sheets-data-validation/src/validators/util.ts@@ -20,14 +20,25 @@ import type { ISheetLocationBase } from '@univerjs/sheets';import { isFormulaString, Range, UniverInstanceType } from '@univerjs/core';import { deserializeListOptions } from '@univerjs/sheets';import { getCellValueOrigin } from '../utils/get-cell-data-origin';+import { getRangeInWorksheet } from '../utils/range';export function getSheetRangeValueSet(grid: IUnitRangeName, univerInstanceService: IUniverInstanceService, currUnitId: string, currSubUnitId: string) {const set = new Set<string>();const unitId = grid.unitId || currUnitId;- const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET) ?? univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const workbook = univerInstanceService.getUnit<Workbook>(unitId, UniverInstanceType.UNIVER_SHEET) ?? univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ if (!workbook) {+ return [];+ }const worksheet = workbook.getSheetBySheetName(grid.sheetName) ?? workbook.getSheetBySheetId(currSubUnitId) ?? workbook.getActiveSheet();- Range.foreach(grid.range, (row, col) => {- const data = worksheet?.getCellRaw(row, col);+ if (!worksheet) {+ return [];+ }+ const range = getRangeInWorksheet(grid.range, worksheet);+ if (!range) {+ return [];+ }+ Range.foreach(range, (row, col) => {+ const data = worksheet.getCellRaw(row, col);if (!data) {return;}