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.

feat(facade): add sheet-data-validation facade api (#3050)

zhangw9ce3f8d88c7e
diff --git a/packages/facade/package.json b/packages/facade/package.json
index a399aa9720..b0a7c3b363 100644
--- a/packages/facade/package.json
+++ b/packages/facade/package.json
@@ -66,6 +66,7 @@
"@univerjs/engine-render": "workspace:*",
"@univerjs/network": "workspace:*",
"@univerjs/sheets": "workspace:*",
+ "@univerjs/sheets-data-validation": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
@@ -73,6 +74,7 @@
},
"devDependencies": {
"@univerjs/core": "workspace:*",
+ "@univerjs/data-validation": "workspace:*",
"@univerjs/docs": "workspace:*",
"@univerjs/docs-ui": "workspace:*",
"@univerjs/engine-formula": "workspace:*",
@@ -81,6 +83,7 @@
"@univerjs/shared": "workspace:*",
"@univerjs/sheets": "workspace:*",
"@univerjs/sheets-conditional-formatting": "workspace:*",
+ "@univerjs/sheets-data-validation": "workspace:*",
"@univerjs/sheets-formula": "workspace:*",
"@univerjs/sheets-numfmt": "workspace:*",
"@univerjs/sheets-ui": "workspace:*",
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index 25f470e6c8..9e29814e08 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -40,6 +40,7 @@ import {
IDescriptionService,
IRegisterFunctionService,
RegisterFunctionService,
+ RegisterOtherFormulaService,
} from '@univerjs/sheets-formula';
import enUS from '@univerjs/sheets-formula/locale/en-US';
import zhCN from '@univerjs/sheets-formula/locale/zh-CN';
@@ -48,7 +49,9 @@ import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService }
import { ISheetSelectionRenderService, SheetRenderController, SheetSelectionRenderService, SheetSkeletonManagerService, SheetsRenderService } from '@univerjs/sheets-ui';
import { IPlatformService, IShortcutService, PlatformService, ShortcutService } from '@univerjs/ui';
import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
-
+import { UniverDataValidationPlugin } from '@univerjs/data-validation';
+import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, DataValidationModel, SheetDataValidationManager, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
+import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '@univerjs/engine-formula/services/active-dirty-manager.service.js';
import { FUniver } from '../facade';
function getTestWorkbookDataDemo(): IWorkbookData {
@@ -162,6 +165,13 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
[ConditionalFormattingFormulaService],
[ConditionalFormattingRuleModel],
[ConditionalFormattingViewModel],
+
+ [DataValidationCacheService],
+ [DataValidationFormulaService],
+ [DataValidationCustomFormulaService],
+ [RegisterOtherFormulaService],
+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
+ [SheetsDataValidationValidatorService],
] as Dependency[]).forEach((d) => {
injector.add(d);
});
@@ -178,6 +188,8 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
});
univer.registerPlugin(TestPlugin);
+ univer.registerPlugin(UniverDataValidationPlugin);
+
const sheet = univer.createUnit(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());
const univerInstanceService = injector.get(IUniverInstanceService);
@@ -187,6 +199,15 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
logService.setLogLevel(LogLevel.SILENT); // change this to `LogLevel.VERBOSE` to debug tests via logs
const univerAPI = FUniver.newAPI(injector);
+ const createSheetDataValidationManager = (unitId: string, subUnitId: string) => {
+ return new SheetDataValidationManager(
+ unitId,
+ subUnitId,
+ injector
+ );
+ };
+ const dataValidationModel = injector.get(DataValidationModel);
+ dataValidationModel.setManagerCreator(createSheetDataValidationManager);
return {
univer,
diff --git a/packages/facade/src/apis/__tests__/facade.spec.ts b/packages/facade/src/apis/__tests__/facade.spec.ts
index a776549972..f9001c2591 100644
--- a/packages/facade/src/apis/__tests__/facade.spec.ts
+++ b/packages/facade/src/apis/__tests__/facade.spec.ts
@@ -288,6 +288,10 @@ describe('Test FUniver', () => {
name: 'SHEET_CONDITIONAL_FORMATTING_PLUGIN',
data: '{"sheet-0011":[{"cfId":"AEGZdW8C","ranges":[{"startRow":2,"startColumn":1,"endRow":11,"endColumn":5,"startAbsoluteRefType":0,"endAbsoluteRefType":0,"rangeType":0}],"rule":{"type":"highlightCell","subType":"text","operator":"containsText","style":{"cl":{"rgb":"#2f56ef"},"bg":{"rgb":"#e8ecfc"}},"value":""},"stopIfTrue":false},{"cfId":"4ICEXdJj","ranges":[{"startRow":2,"startColumn":1,"endRow":11,"endColumn":5,"startAbsoluteRefType":0,"endAbsoluteRefType":0,"rangeType":0}],"rule":{"type":"highlightCell","subType":"text","operator":"containsText","style":{"cl":{"rgb":"#2f56ef"},"bg":{"rgb":"#e8ecfc"}},"value":""},"stopIfTrue":false},{"cfId":"geCv018z","ranges":[{"startRow":2,"startColumn":1,"endRow":11,"endColumn":5,"startAbsoluteRefType":0,"endAbsoluteRefType":0,"rangeType":0}],"rule":{"type":"highlightCell","subType":"text","operator":"containsText","style":{"cl":{"rgb":"#2f56ef"},"bg":{"rgb":"#e8ecfc"}},"value":""},"stopIfTrue":false}]}',
},
+ {
+ data: '{}',
+ name: 'SHEET_DATA_VALIDATION_PLUGIN',
+ },
]);
});
diff --git a/packages/facade/src/apis/facade.ts b/packages/facade/src/apis/facade.ts
index afb9260d56..7d7953ed8b 100644
--- a/packages/facade/src/apis/facade.ts
+++ b/packages/facade/src/apis/facade.ts
@@ -56,6 +56,7 @@ import { FDocument } from './docs/f-document';
import { FWorkbook } from './sheets/f-workbook';
import { FSheetHooks } from './sheets/f-sheet-hooks';
import { FHooks } from './f-hooks';
+import { FDataValidationBuilder } from './sheets/f-data-validation-builder';
export class FUniver {
static BorderStyle = BorderStyleTypes;
@@ -127,6 +128,10 @@ export class FUniver {
return injector.createInstance(FUniver);
}
+ static newDataValidation(): FDataValidationBuilder {
+ return new FDataValidationBuilder();
+ }
+
/**
* registerFunction may be executed multiple times, triggering multiple formula forced refreshes
*/
diff --git a/packages/facade/src/apis/sheets/__tests__/f-data-validation-builder.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-data-validation-builder.spec.ts
new file mode 100644
index 0000000000..1bb693a3f5
--- /dev/null
+++ b/packages/facade/src/apis/sheets/__tests__/f-data-validation-builder.spec.ts
@@ -0,0 +1,224 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { beforeEach, describe, expect, it } from 'vitest';
+import type { Injector } from '@univerjs/core';
+import { DataValidationOperator, DataValidationType, ICommandService } from '@univerjs/core';
+import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
+import { FDataValidationBuilder } from '../f-data-validation-builder';
+import { createFacadeTestBed } from '../../__tests__/create-test-bed';
+import type { FUniver } from '../../facade';
+
+describe('Test FDataValidationBuilder', () => {
+ let get: Injector['get'];
+ let commandService: ICommandService;
+ let univerAPI: FUniver;
+
+ beforeEach(() => {
+ const testBed = createFacadeTestBed();
+ get = testBed.get;
+
+ univerAPI = testBed.univerAPI;
+
+ commandService = get(ICommandService);
+ commandService.registerCommand(SetRangeValuesCommand);
+ commandService.registerCommand(SetRangeValuesMutation);
+ commandService.registerCommand(SetStyleCommand);
+ commandService.registerCommand(SetVerticalTextAlignCommand);
+ commandService.registerCommand(SetHorizontalTextAlignCommand);
+ commandService.registerCommand(SetTextWrapCommand);
+ });
+
+ it('should build checkbox', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireCheckbox('1', '2');
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.CHECKBOX);
+ expect(builder.getCriteriaValues()).toEqual([undefined, '1', '2']);
+ });
+
+ it('should build number equal', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberEqualTo(1);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.EQUAL, '1', undefined]);
+ });
+
+ it('should build number greater than', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberGreaterThan(1);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN, '1', undefined]);
+ });
+
+ it('should build number greater than or equal', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberGreaterThanOrEqualTo(1);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN_OR_EQUAL, '1', undefined]);
+ });
+
+ it('should build number less than', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberLessThan(1);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.LESS_THAN, '1', undefined]);
+ });
+
+ it('should build number less than or equal to', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberLessThanOrEqualTo(1);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.LESS_THAN_OR_EQUAL, '1', undefined]);
+ });
+
+ it('should build number between', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberBetween(1, 2);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.BETWEEN, '1', '2']);
+ });
+
+ it('should build number not between', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberNotBetween(1, 2);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DECIMAL);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.NOT_BETWEEN, '1', '2']);
+ });
+
+ it('should build int equal', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberEqualTo(1, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.EQUAL, '1', undefined]);
+ });
+
+ it('should build int greater than', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberGreaterThan(1, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN, '1', undefined]);
+ });
+
+ it('should build int greater than or equal', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberGreaterThanOrEqualTo(1, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN_OR_EQUAL, '1', undefined]);
+ });
+
+ it('should build int less than', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberLessThan(1, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.LESS_THAN, '1', undefined]);
+ });
+
+ it('should build int less than or equal to', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberLessThanOrEqualTo(1, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.LESS_THAN_OR_EQUAL, '1', undefined]);
+ });
+
+ it('should build int between', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberBetween(1, 2, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.BETWEEN, '1', '2']);
+ });
+
+ it('should build int not between', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireNumberNotBetween(1, 2, true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.WHOLE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.NOT_BETWEEN, '1', '2']);
+ });
+
+ it('should build date equal', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateEqualTo(new Date('2020-01-01'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.EQUAL, new Date('2020-01-01').toLocaleDateString(), undefined]);
+ });
+
+ it('should build date after', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateAfter(new Date('2020-01-01'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN, new Date('2020-01-01').toLocaleDateString(), undefined]);
+ });
+
+ it('should build date before', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateBefore(new Date('2020-01-01'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.LESS_THAN, new Date('2020-01-01').toLocaleDateString(), undefined]);
+ });
+
+ it('should build date on or after', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateOnOrAfter(new Date('2020-01-01'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.GREATER_THAN_OR_EQUAL, new Date('2020-01-01').toLocaleDateString(), undefined]);
+ });
+
+ it('should build date on or before', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateOnOrBefore(new Date('2020-01-01'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.LESS_THAN_OR_EQUAL, new Date('2020-01-01').toLocaleDateString(), undefined]);
+ });
+
+ it('should build date between', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateBetween(new Date('2020-01-01'), new Date('2020-01-02'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.BETWEEN, new Date('2020-01-01').toLocaleDateString(), new Date('2020-01-02').toLocaleDateString()]);
+ });
+
+ it('should build date not between', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireDateNotBetween(new Date('2020-01-01'), new Date('2020-01-02'));
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.DATE);
+ expect(builder.getCriteriaValues()).toEqual([DataValidationOperator.NOT_BETWEEN, new Date('2020-01-01').toLocaleDateString(), new Date('2020-01-02').toLocaleDateString()]);
+ });
+
+ it('should build value in list', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireValueInList(['1', '2', '3']);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.LIST);
+ expect(builder.getCriteriaValues()).toEqual([undefined, '1,2,3', undefined]);
+ });
+
+ it('should build value in list-multiple', () => {
+ const builder = new FDataValidationBuilder();
+ builder.requireValueInList(['1', '2', '3'], true);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.LIST_MULTIPLE);
+ expect(builder.getCriteriaValues()).toEqual([undefined, '1,2,3', undefined]);
+ });
+
+ it('should build value in range', () => {
+ const activeSheet = univerAPI.getActiveWorkbook()!.getActiveSheet();
+
+ // // A1 sets the number
+ const range1 = activeSheet!.getRange(0, 0, 1, 1)!;
+
+ const builder = new FDataValidationBuilder();
+ builder.requireValueInRange(range1);
+ expect(builder.build().getCriteriaType()).toEqual(DataValidationType.LIST);
+ expect(builder.getCriteriaValues()).toEqual([undefined, '=[test]sheet1!A1', undefined]);
+ });
+});
diff --git a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
index f842dc0c6a..4dd0fd56fd 100644
--- a/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
+++ b/packages/facade/src/apis/sheets/__tests__/f-range.spec.ts
@@ -15,12 +15,13 @@
*/
import type { ICellData, Injector, IStyleData, Nullable } from '@univerjs/core';
-import { HorizontalAlign, ICommandService, IUniverInstanceService, VerticalAlign, WrapStrategy } from '@univerjs/core';
+import { DataValidationType, HorizontalAlign, ICommandService, IUniverInstanceService, VerticalAlign, WrapStrategy } from '@univerjs/core';
import { SetHorizontalTextAlignCommand, SetRangeValuesCommand, SetRangeValuesMutation, SetStyleCommand, SetTextWrapCommand, SetVerticalTextAlignCommand } from '@univerjs/sheets';
import { beforeEach, describe, expect, it } from 'vitest';
import { FormulaDataModel } from '@univerjs/engine-formula';
-import type { FUniver } from '../../facade';
+import { AddSheetDataValidationCommand } from '@univerjs/sheets-data-validation';
+import { FUniver } from '../../facade';
import { createFacadeTestBed } from '../../__tests__/create-test-bed';
describe('Test FRange', () => {
@@ -53,6 +54,7 @@ describe('Test FRange', () => {
commandService.registerCommand(SetVerticalTextAlignCommand);
commandService.registerCommand(SetHorizontalTextAlignCommand);
commandService.registerCommand(SetTextWrapCommand);
+ commandService.registerCommand(AddSheetDataValidationCommand);
getValueByPosition = (
startRow: number,
@@ -552,4 +554,26 @@ describe('Test FRange', () => {
await range!.setWrapStrategy(WrapStrategy.CLIP);
expect(getStyleByPosition(0, 0, 0, 0)?.tb).toBe(WrapStrategy.CLIP);
});
+
+ it('Range set data validation', async () => {
+ const activeSheet = univerAPI.getActiveWorkbook()?.getActiveSheet();
+ const range = activeSheet?.getRange(0, 0, 10, 10)!;
+ const range2 = activeSheet?.getRange(11, 11, 2, 2);
+ await range.setDataValidation(FUniver.newDataValidation().requireCheckbox().build());
+ await range2?.setDataValidation(FUniver.newDataValidation().requireNumberEqualTo(1).build());
+ const range3 = activeSheet?.getRange(0, 0, 100, 100);
+
+ expect(range.getDataValidation()).toBeTruthy();
+ expect(range.getDataValidation()?.rule.ranges).toEqual([{
+ startRow: 0,
+ endRow: 9,
+ startColumn: 0,
+ endColumn: 9,
+ }]);
+ expect(range.getDataValidation()?.getCriteriaType()).toEqual(DataValidationType.CHECKBOX);
+ expect(range.getDataValidations().length).toEqual(1);
+ expect(range3?.getDataValidations().length).toEqual(2);
+
+ expect(activeSheet?.getDataValidations().length).toEqual(2);
+ });
});
diff --git a/packages/facade/src/apis/sheets/f-data-validation-builder.ts b/packages/facade/src/apis/sheets/f-data-validation-builder.ts
new file mode 100644
index 0000000000..35ae82b4cb
--- /dev/null
+++ b/packages/facade/src/apis/sheets/f-data-validation-builder.ts
@@ -0,0 +1,448 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { IDataValidationRule } from '@univerjs/core';
+import { DataValidationErrorStyle, DataValidationOperator, DataValidationType, generateRandomId } from '@univerjs/core';
+import { serializeRangeToRefString } from '@univerjs/engine-formula';
+import type { FRange } from './f-range';
+import { FDataValidation } from './f-data-validation';
+
+ /**
+ * Builder for data validation rules.
+ *
+ * Set the data validation for cell A1 to require a value from B1:B10.
+ * var rule = FUniver.newDataValidation().requireValueInRange(range).build();
+ * cell.setDataValidation(rule);
+ */
+export class FDataValidationBuilder {
+ private _rule: IDataValidationRule;
+
+ constructor(rule?: IDataValidationRule) {
+ this._rule = rule ?? {
+ uid: generateRandomId(),
+ ranges: undefined,
+ type: DataValidationType.CUSTOM,
+ };
+ }
+
+ /**
+ * Builds an FDataValidation instance based on the _rule property of the current class
+ *
+ * @returns {FDataValidation} A new instance of the FDataValidation class
+ */
+ build(): FDataValidation {
+ return new FDataValidation(this._rule);
+ }
+
+ /**
+ * Creates a duplicate of the current DataValidationBuilder object
+ *
+ * @return {FDataValidationBuilder} A new instance of the DataValidationBuilder class
+ */
+ copy(): FDataValidationBuilder {
+ return new FDataValidationBuilder({
+ ...this._rule,
+ uid: generateRandomId(),
+ });
+ }
+
+ /**
+ * Determines whether invalid data is allowed
+ *
+ * @returns {boolean} True if invalid data is allowed, False otherwise
+ */
+ getAllowInvalid(): boolean {
+ return this._rule.errorStyle !== DataValidationErrorStyle.STOP;
+ }
+
+ /**
+ * Gets the data validation type of the rule
+ *
+ * @returns {DataValidationType} The data validation type
+ */
+ getCriteriaType(): DataValidationType {
+ return this._rule.type;
+ }
+
+ /**
+ * Gets the values used for criteria evaluation
+ *
+ * @returns {any[]} An array containing the operator, formula1, and formula2 values
+ */
+ getCriteriaValues(): any[] {
+ return [this._rule.operator, this._rule.formula1, this._rule.formula2];
+ }
+
+ /**
+ * Gets the help text information, which is used to provide users with guidance and support
+ *
+ * @returns {string | undefined} Returns the help text information. If there is no error message, it returns an undefined value.
+ */
+ getHelpText(): string | undefined {
+ return this._rule.error;
+ }
+
+ /**
+ * Sets the data validation type to CHECKBOX and sets the checked and unchecked values
+ *
+ * @param checkedValue The value when the checkbox is checked (Optional)
+ * @param uncheckedValue The value when the checkbox is unchecked (Optional)
+ * @returns The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireCheckbox(checkedValue?: string, uncheckedValue?: string): FDataValidationBuilder {
+ this._rule.type = DataValidationType.CHECKBOX;
+ this._rule.formula1 = checkedValue;
+ this._rule.formula2 = uncheckedValue;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be after a specific date
+ *
+ * @param date The date to compare against. The formatted date string will be set as formula1
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateAfter(date: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = date.toLocaleDateString();
+ this._rule.operator = DataValidationOperator.GREATER_THAN;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be before a specific date
+ *
+ * @param date The date to compare against. The formatted date string will be set as formula1
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateBefore(date: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = date.toLocaleDateString();
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.LESS_THAN;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be within a specific date range
+ *
+ * @param start The starting date of the range. The formatted date string will be set as formula1
+ * @param end The ending date of the range. The formatted date string will be set as formula2
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateBetween(start: Date, end: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = start.toLocaleDateString();
+ this._rule.formula2 = end.toLocaleDateString();
+ this._rule.operator = DataValidationOperator.BETWEEN;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be equal to a specific date
+ *
+ * @param date The date to compare against. The formatted date string will be set as formula1
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateEqualTo(date: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = date.toLocaleDateString();
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.EQUAL;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be not within a specific date range
+ *
+ * @param start The starting date of the date range
+ * @param end The ending date of the date range
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateNotBetween(start: Date, end: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = start.toLocaleDateString();
+ this._rule.formula2 = end.toLocaleDateString();
+ this._rule.operator = DataValidationOperator.NOT_BETWEEN;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be on or after a specific date
+ *
+ * @param date The date to compare against. The formatted date string will be set as formula1
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateOnOrAfter(date: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = date.toLocaleDateString();
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.GREATER_THAN_OR_EQUAL;
+
+ return this;
+ }
+
+ /**
+ * Set the data validation type to DATE and configure the validation rules to be on or before a specific date
+ *
+ * @param date The date to compare against. The formatted date string will be set as formula1
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireDateOnOrBefore(date: Date): FDataValidationBuilder {
+ this._rule.type = DataValidationType.DATE;
+ this._rule.formula1 = date.toLocaleDateString();
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.LESS_THAN_OR_EQUAL;
+
+ return this;
+ }
+
+ /**
+ * Requires that a custom formula be satisfied.
+ * Sets the data validation type to CUSTOM and configures the validation rule based on the provided formula string.
+ *
+ * @param formula The formula string that needs to be satisfied.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireFormulaSatisfied(formula: string): FDataValidationBuilder {
+ this._rule.type = DataValidationType.CUSTOM;
+ this._rule.formula1 = formula;
+ this._rule.formula2 = undefined;
+ return this;
+ }
+
+ /**
+ * Requires the user to enter a number within a specific range, which can be integer or decimal.
+ * Sets the data validation type based on the isInteger parameter and configures the validation rules for the specified number range.
+ *
+ * @param start The starting value of the number range.
+ * @param end The ending value of the number range.
+ * @param isInteger Indicates whether the required number is an integer. Default is undefined, meaning it can be an integer or decimal.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireNumberBetween(start: number, end: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${start}`;
+ this._rule.formula2 = `${end}`;
+ this._rule.operator = DataValidationOperator.BETWEEN;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+
+ return this;
+ }
+
+ /**
+ * Requires the user to enter a number that is equal to a specific value, which can be an integer or a decimal.
+ * Sets the data validation type based on the isInteger parameter and configures the validation rules for the specified number.
+ *
+ * @param num The number to which the entered number should be equal.
+ * @param isInteger Indicates whether the required number is an integer. Default is undefined, meaning it can be an integer or a decimal.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireNumberEqualTo(num: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${num}`;
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.EQUAL;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+ return this;
+ }
+
+ /**
+ * Requires the user to enter a number that is greater than a specific value, which can be an integer or a decimal.
+ * Sets the data validation type based on the isInteger parameter and configures the validation rules for the specified number.
+ *
+ * @param num The number to which the entered number should be greater.
+ * @param isInteger Indicates whether the required number is an integer. Default is undefined, meaning it can be an integer or a decimal.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireNumberGreaterThan(num: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${num}`;
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.GREATER_THAN;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+ return this;
+ }
+
+ /**
+ * Requires the user to enter a number that is greater than or equal to a specific value, which can be an integer or a decimal.
+ * Sets the data validation type based on the isInteger parameter and configures the validation rules for the specified number.
+ *
+ * @param num The number to which the entered number should be greater than or equal.
+ * @param isInteger Indicates whether the required number is an integer. Default is undefined, meaning it can be an integer or a decimal.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireNumberGreaterThanOrEqualTo(num: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${num}`;
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.GREATER_THAN_OR_EQUAL;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+ return this;
+ }
+
+ /**
+ * Requires the user to enter a number that is less than a specific value, which can be an integer or a decimal.
+ * Sets the data validation type based on the isInteger parameter and configures the validation rules for the specified number.
+ *
+ * @param num The number to which the entered number should be less.
+ * @param isInteger Indicates whether the required number is an integer. Default is undefined, meaning it can be an integer or a decimal.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireNumberLessThan(num: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${num}`;
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.LESS_THAN;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+ return this;
+ }
+
+ /**
+ * Sets the data validation rule to require a number less than or equal to a specified value
+ * The specified value can be an integer or a decimal
+ *
+ * @param num The number to which the entered number should be less than or equal
+ * @param isInteger Indicates whether the required number is an integer
+ * @return The current instance of the DataValidationBuilder class, allowing for method chaining
+ */
+ requireNumberLessThanOrEqualTo(num: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${num}`;
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.LESS_THAN_OR_EQUAL;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+ return this;
+ }
+
+ /**
+ * Sets a data validation rule that requires the user to enter a number outside a specified range
+ * The specified range includes all integers and decimals
+ *
+ * @param start The starting point of the specified range
+ * @param end The end point of the specified range
+ * @param isInteger Optional parameter, indicating whether the number to be verified is an integer. Default value is false
+ * @return An instance of the FDataValidationBuilder class, allowing for method chaining
+ */
+ requireNumberNotBetween(start: number, end: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${start}`;
+ this._rule.formula2 = `${end}`;
+ this._rule.operator = DataValidationOperator.NOT_BETWEEN;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+
+ return this;
+ }
+
+ /**
+ * Creates a data validation rule that requires the user to enter a number that is not equal to a specific value
+ * The specific value can be an integer or a decimal
+ *
+ * @param num The number to which the entered number should not be equal
+ * @param isInteger Indicates whether the required number is an integer. Default is undefined, meaning it can be an integer or a decimal
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining
+ */
+ requireNumberNotEqualTo(num: number, isInteger?: boolean): FDataValidationBuilder {
+ this._rule.formula1 = `${num}`;
+ this._rule.formula2 = undefined;
+ this._rule.operator = DataValidationOperator.NOT_EQUAL;
+ this._rule.type = isInteger ? DataValidationType.WHOLE : DataValidationType.DECIMAL;
+ return this;
+ }
+
+ /**
+ * Sets a data validation rule that requires the user to enter a value from a list of specific values.
+ * The list can be displayed in a dropdown, and the user can choose multiple values according to the settings.
+ *
+ * @param values An array containing the specific values that the user can enter.
+ * @param multiple Optional parameter indicating whether the user can select multiple values. Default is false, meaning only one value can be selected.
+ * @param showDropdown Optional parameter indicating whether to display the list in a dropdown. Default is true, meaning the list will be displayed as a dropdown.
+ * @return An instance of the FDataValidationBuilder class, allowing for method chaining.
+ */
+ requireValueInList(values: string[], multiple?: boolean, showDropdown?: boolean): FDataValidationBuilder {
+ this._rule.type = multiple ? DataValidationType.LIST_MULTIPLE : DataValidationType.LIST;
+ this._rule.formula1 = values.join(',');
+ this._rule.formula2 = undefined;
+ this._rule.showDropDown = showDropdown ?? true;
+
+ return this;
+ }
+
+ /**
+ * Sets a data validation rule that requires the user to enter a value within a specific range.
+ * The range is defined by an FRange object, which contains the unit ID, sheet name, and cell range.
+ *
+ * @param range An FRange object representing the range of values that the user can enter.
+ * @param multiple Optional parameter indicating whether the user can select multiple values. Default is false, meaning only one value can be selected.
+ * @param showDropdown Optional parameter indicating whether to display the list in a dropdown. Default is true, meaning the list will be displayed as a dropdown.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ requireValueInRange(range: FRange, multiple?: boolean, showDropdown?: boolean): FDataValidationBuilder {
+ this._rule.type = multiple ? DataValidationType.LIST_MULTIPLE : DataValidationType.LIST;
+ this._rule.formula1 = `=${serializeRangeToRefString({
+ unitId: range.getUnitId(),
+ sheetName: range.getSheetName(),
+ range: range.getRange(),
+ })}`;
+ this._rule.formula2 = undefined;
+ this._rule.showDropDown = showDropdown ?? true;
+
+ return this;
+ }
+
+ /**
+ * Sets whether to allow invalid data and configures the error style for data validation.
+ * If invalid data is not allowed, the error style will be set to STOP, indicating that data entry must stop upon encountering an error.
+ * If invalid data is allowed, the error style will be set to WARNING, indicating that a warning will be displayed when invalid data is entered, but data entry can continue.
+ *
+ * @param allowInvalidData A boolean value indicating whether to allow invalid data.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ setAllowInvalid(allowInvalidData: boolean): FDataValidationBuilder {
+ this._rule.errorStyle = !allowInvalidData ? DataValidationErrorStyle.STOP : DataValidationErrorStyle.WARNING;
+ return this;
+ }
+
+ /**
+ * Sets the help text and enables the display of error messages for data validation.
+ * This method allows you to set a custom help text that will be displayed when the user enters invalid data.
+ *
+ * @param helpText The text to display as help information.
+ * @return The current instance of the FDataValidationBuilder class to allow for method chaining.
+ */
+ setHelpText(helpText: string): FDataValidationBuilder {
+ this._rule.error = helpText;
+ this._rule.showErrorMessage = true;
+ return this;
+ }
+
+ /**
+ * Sets the criteria values for data validation.
+ * This method is used to configure the validation rules based on specific criteria values.
+ *
+ * @param type The type of data validation.
+ * @param values An array containing the criteria values.
+ * The array should have three elements: [operator, formula1, formula2].
+ * operator is a DataValidationOperator enum value, formula1 is the first formula, and formula2 is the second formula.
+ * @return The current instance of the FDataValidationBuilder class, allowing for method chaining.
+ */
+ withCriteriaValues(type: DataValidationType, values: [DataValidationOperator, string, string]) {
+ this._rule.type = type;
+ this._rule.operator = values[0];
+ this._rule.formula1 = values[1];
+ this._rule.formula2 = values[2];
+ return this;
+ }
+}
diff --git a/packages/facade/src/apis/sheets/f-data-validation.ts b/packages/facade/src/apis/sheets/f-data-validation.ts
new file mode 100644
index 0000000000..8500b6c598
--- /dev/null
+++ b/packages/facade/src/apis/sheets/f-data-validation.ts
@@ -0,0 +1,71 @@
+/**
+ * Copyright 2023-present DreamNum Inc.
+ *
+ * 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 { DataValidationErrorStyle, type IDataValidationRule } from '@univerjs/core';
+import { FDataValidationBuilder } from './f-data-validation-builder';
+
+export class FDataValidation {
+ rule: IDataValidationRule;
+ constructor(rule: IDataValidationRule) {
+ this.rule = rule;
+ }
+
+ /**
+ * Gets whether invalid data is allowed based on the error style value.
+ *
+ * @return true if invalid data is allowed, false otherwise.
+ */
+ getAllowInvalid() {
+ return this.rule.errorStyle !== DataValidationErrorStyle.STOP;
+ };
+
+ /**
+ * Gets the data validation type of the rule
+ *
+ * @returns {DataValidationType} The data validation type
+ */
+ getCriteriaType() {
+ return this.rule.type;
+ };
+
+ /**
+ * Gets the values used for criteria evaluation
+ *
+ * @returns {any[]} An array containing the operator, formula1, and formula2 values
+ */
+ getCriteriaValues() {
+ return [this.rule.operator, this.rule.formula1, this.rule.formula2];
+ }
+
+ /**
+ * Gets the help text information, which is used to provide users with guidance and support
+ *
+ * @returns {string | undefined} Returns the help text information. If there is no error message, it returns an undefined value.
+ */
+ getHelpText() {
+ return this.rule.error;
+ };
+
+ /**
+ * Creates a new instance of FDataValidationBuilder using the current rule object.
+ * This method is useful for copying an existing data validation rule configuration.
+ *
+ * @return A new FDataValidationBuilder instance with the same rule configuration.
+ */
+ copy() {
+ return new FDataValidationBuilder(this.rule);
+ }
+}
diff --git a/packages/facade/src/apis/sheets/f-range.ts b/packages/facade/src/apis/sheets/f-range.ts
index 7d2bc961ec..35548ab81b 100644
--- a/packages/facade/src/apis/sheets/f-range.ts
+++ b/packages/facade/src/apis/sheets/f-range.ts
@@ -23,6 +23,7 @@ import type {
ISelectionCellWithMergeInfo,
IStyleData,
ITextDecoration,
+ Nullable,
Workbook,
Worksheet,
} from '@univerjs/core';
@@ -47,8 +48,11 @@ import { SetNumfmtCommand } from '@univerjs/sheets-numfmt';
import { FormulaDataModel } from '@univerjs/engine-formula';
import { ISheetClipboardService, SheetSkeletonManagerService } from '@univerjs/sheets-ui';
import { IRenderManagerService } from '@univerjs/engine-render';
+import type { IAddSheetDataValidationCommandParams, IClearRangeDataValidationCommandParams } from '@univerjs/sheets-data-validation';
+import { AddSheetDataValidationCommand, ClearRangeDataValidationCommand, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
import type { FHorizontalAlignment, FVerticalAlignment } from './utils';
-import { covertCellValue,
+import {
+ covertCellValue,
covertCellValues,
isCellMerged,
transformCoreHorizontalAlignment,
@@ -56,6 +60,7 @@ import { covertCellValue,
transformFacadeHorizontalAlignment,
transformFacadeVerticalAlignment,
} from './utils';
+import { FDataValidation } from './f-data-validation';
export type FontLine = 'none' | 'underline' | 'line-through';
export type FontStyle = 'normal' | 'italic';
@@ -74,18 +79,65 @@ export class FRange {
// empty
}
+ /**
+ * Get the unit ID of the current workbook
+ *
+ * @return The unit ID of the workbook
+ */
+ getUnitId() {
+ return this._workbook.getUnitId();
+ }
+
+ /**
+ * Gets the name of the worksheet
+ *
+ * @return The name of the worksheet
+ */
+ getSheetName() {
+ return this._worksheet.getName();
+ }
+
+ /**
+ * Gets the area where the statement is applied
+ *
+ * @return The area where the statement is applied
+ */
+ getRange() {
+ return this._range;
+ }
+
+ /**
+ * Gets the starting row number of the applied area
+ *
+ * @return The starting row number of the area
+ */
getRow(): number {
return this._range.startRow;
}
+ /**
+ * Gets the starting column number of the applied area
+ *
+ * @return The starting column number of the area
+ */
getColumn(): number {
return this._range.startColumn;
}
+ /**
+ * Gets the width of the applied area
+ *
+ * @return The width of the area
+ */
getWidth(): number {
return this._range.endColumn - this._range.startColumn + 1;
}
+ /**
+ * Gets the height of the applied area
+ *
+ * @return The height of the area
+ */
getHeight(): number {
return this._range.endRow - this._range.startRow + 1;
}
@@ -533,4 +585,77 @@ export class FRange {
return copyContent?.html ?? '';
}
+
+ /**
+ * set a data validation rule to current range
+ * @param rule data validation rule, build by `FUniver.newDataValidation`
+ * @returns current range
+ */
+ async setDataValidation(rule: Nullable<FDataValidation>) {
+ if (!rule) {
+ this._commandService.executeCommand(ClearRangeDataValidationCommand.id, {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ ranges: [this._range],
+ } as IClearRangeDataValidationCommandParams);
+ return this;
+ }
+
+ const params: IAddSheetDataValidationCommandParams = {
+ unitId: this._workbook.getUnitId(),
+ subUnitId: this._worksheet.getSheetId(),
+ rule: {
+ ...rule.rule,
+ ranges: [this._range],
+ },
+ };
+
+ await this._commandService.executeCommand(AddSheetDataValidationCommand.id, params);
+ return this;
+ }
+
+ /**
+ * get first data validation rule in current range
+ * @returns data validation rule
+ */
+ getDataValidation(): Nullable<FDataValidation> {
+ const validatorService = this._injector.get(SheetsDataValidationValidatorService);
+ const rule = validatorService.getDataValidation(
+ this._workbook.getUnitId(),
+ this._worksheet.getSheetId(),
+ [this._range]
+ );
+
+ if (rule) {
+ return new FDataValidation(rule);
+ }
+
+ return rule;
+ }
+
+ /**
+ * get all data validation rules in current range
+ * @returns {FDataValidation[]} all data validation rules
+ */
+ getDataValidations() {
+ const validatorService = this._injector.get(SheetsDataValidationValidatorService);
+ return validatorService.getDataValidations(
+ this._workbook.getUnitId(),
+ this._worksheet.getSheetId(),
+ [this._range]
+ ).map((rule) => new FDataValidation(rule));
+ }
+
+ /**
+ * get data validation validator status for current range
+ * @returns matrix of validator status
+ */
+ async getValidatorStatus() {
+ const validatorService = this._injector.get(SheetsDataValidationValidatorService);
+ return validatorService.validatorRanges(
+ this._workbook.getUnitId(),
+ this._worksheet.getSheetId(),
+ [this._range]
+ );
+ }
}
diff --git a/packages/facade/src/apis/sheets/f-workbook.ts b/packages/facade/src/apis/sheets/f-workbook.ts
index 0599bcc3aa..ae6445d1ed 100644
--- a/packages/facade/src/apis/sheets/f-workbook.ts
+++ b/packages/facade/src/apis/sheets/f-workbook.ts
@@ -33,6 +33,7 @@ import type {
} from '@univerjs/sheets';
import { InsertSheetCommand, RemoveSheetCommand, SetWorksheetActiveOperation, SheetsSelectionsService, WorkbookEditablePermission } from '@univerjs/sheets';
+import { SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
import { FWorksheet } from './f-worksheet';
export class FWorkbook {
@@ -276,4 +277,15 @@ export class FWorkbook {
}
// #region callbacks
+
+ /**
+ * get data validation validator status for current workbook
+ * @returns matrix of validator status
+ */
+ getValidatorStatus() {
+ const validatorService = this._injector.get(SheetsDataValidationValidatorService);
+ return validatorService.validatorWorkbook(
+ this._workbook.getUnitId()
+ );
+ }
}
diff --git a/packages/facade/src/apis/sheets/f-worksheet.ts b/packages/facade/src/apis/sheets/f-worksheet.ts
index 8687531c53..5c3029ab40 100644
--- a/packages/facade/src/apis/sheets/f-worksheet.ts
+++ b/packages/facade/src/apis/sheets/f-worksheet.ts
@@ -19,8 +19,10 @@ import type { ISetWorksheetColWidthMutationParams, ISetWorksheetRowHeightMutatio
import { SetWorksheetColWidthMutation, SetWorksheetRowHeightMutation, SheetsSelectionsService } from '@univerjs/sheets';
import { Inject, Injector } from '@univerjs/core';
+import { DataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
import { FRange } from './f-range';
import { FSelection } from './f-selection';
+import { FDataValidation } from './f-data-validation';
export class FWorksheet {
constructor(
@@ -116,4 +118,25 @@ export class FWorksheet {
getMaxRows() {
return this._worksheet.getMaxRows();
}
+
+ /**
+ * get all data validation rules in current sheet
+ * @returns {FDataValidation[]} all data validation rules
+ */
+ getDataValidations() {
+ const dataValidationModel = this._injector.get(DataValidationModel);
+ return dataValidationModel.getRules(this._workbook.getUnitId(), this._worksheet.getSheetId()).map((rule) => new FDataValidation(rule));
+ }
+
+ /**
+ * get data validation validator status for current sheet
+ * @returns matrix of validator status
+ */
+ getValidatorStatus() {
+ const validatorService = this._injector.get(SheetsDataValidationValidatorService);
+ return validatorService.validatorWorksheet(
+ this._workbook.getUnitId(),
+ this._worksheet.getSheetId()
+ );
+ }
}
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.ts
index 46915a03d4..8a92271dc1 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
@@ -501,3 +501,20 @@ export const UpdateSheetDataValidationOptionsCommand: ICommand<IUpdateSheetDataV
},
};
+export interface IClearRangeDataValidationCommandParams {
+ unitId: string;
+ subUnitId: string;
+ ranges: IRange[];
+}
+
+export const ClearRangeDataValidationCommand: ICommand<IClearRangeDataValidationCommandParams> = {
+ type: CommandType.COMMAND,
+ id: 'sheets.command.clear-range-data-validation',
+ handler(accessor, params) {
+ if (!params) {
+ return false;
+ }
+ const commandService = accessor.get(ICommandService);
+ return true;
+ },
+};
diff --git a/packages/sheets-data-validation/src/index.ts b/packages/sheets-data-validation/src/index.ts
index 99a92c71ce..adf8c81544 100644
--- a/packages/sheets-data-validation/src/index.ts
+++ b/packages/sheets-data-validation/src/index.ts
@@ -21,6 +21,8 @@ export { DataValidationFormulaService } from './services/dv-formula.service';
export { DataValidationCustomFormulaService } from './services/dv-custom-formula.service';
export { DATA_VALIDATION_PLUGIN_NAME } from './common/const';
export { SheetsDataValidationValidatorService } from './services/dv-validator-service';
+export { DataValidationModel } from '@univerjs/data-validation';
+export { SheetDataValidationManager } from './models/sheet-data-validation-manager';
// #region - all commands
export {
@@ -33,10 +35,12 @@ export {
UpdateSheetDataValidationSettingCommand,
AddSheetDataValidationCommand,
AddSheetDataValidationAndOpenCommand,
+ ClearRangeDataValidationCommand,
type IAddSheetDataValidationCommandParams,
type IUpdateSheetDataValidationRangeCommandParams,
type IUpdateSheetDataValidationOptionsCommandParams,
type IUpdateSheetDataValidationSettingCommandParams,
+ type IClearRangeDataValidationCommandParams,
} from './commands/commands/data-validation.command';
export {
diff --git a/packages/sheets-data-validation/src/services/dv-validator-service.ts b/packages/sheets-data-validation/src/services/dv-validator-service.ts
index f164c6a4c3..e7ffadbc37 100644
--- a/packages/sheets-data-validation/src/services/dv-validator-service.ts
+++ b/packages/sheets-data-validation/src/services/dv-validator-service.ts
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-import type { Nullable, ObjectMatrix, Workbook } from '@univerjs/core';
+import type { IDataValidationRule, IRange, Nullable, ObjectMatrix, Workbook } from '@univerjs/core';
import { DataValidationStatus, Inject, IUniverInstanceService, Range, UniverInstanceType } from '@univerjs/core';
import { DataValidationModel } from '@univerjs/data-validation';
import type { SheetDataValidationManager } from '../models/sheet-data-validation-manager';
@@ -54,6 +54,16 @@ export class SheetsDataValidationValidatorService {
});
}
+ validatorRanges(unitId: string, subUnitId: string, ranges: IRange[]) {
+ return Promise.all(ranges.map((range) => {
+ const promises: Promise<DataValidationStatus>[] = [];
+ Range.foreach(range, (row, col) => {
+ promises.push(this.validatorCell(unitId, subUnitId, row, col));
+ });
+ return promises;
+ }));
+ }
+
async validatorWorksheet(unitId: string, subUnitId: string) {
const manager = this._dataValidationModel.ensureManager(unitId, subUnitId) as SheetDataValidationManager;
const rules = manager.getDataValidations();
@@ -82,4 +92,25 @@ export class SheetsDataValidationValidatorService {
return map;
}
+
+ getDataValidations(unitId: string, subUnitId: string, ranges: IRange[]): IDataValidationRule[] {
+ const manager = this._dataValidationModel.ensureManager(unitId, subUnitId) as SheetDataValidationManager;
+ const ruleMatrix = manager.getRuleObjectMatrix();
+ const ruleIdSet = new Set<string>();
+ ranges.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ const ruleId = ruleMatrix.getValue(row, col);
+ if (ruleId) {
+ ruleIdSet.add(ruleId);
+ }
+ });
+ });
+
+ const rules = Array.from(ruleIdSet).map((id) => manager.getRuleById(id)).filter(Boolean) as IDataValidationRule[];
+ return rules;
+ }
+
+ getDataValidation(unitId: string, subUnitId: string, ranges: IRange[]): Nullable<IDataValidationRule> {
+ return this.getDataValidations(unitId, subUnitId, ranges)[0];
+ }
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 330bde2aef..e407a5ea7a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -10,7 +10,7 @@ importers:
devDependencies:
'@antfu/eslint-config':
specifier: 2.25.0
'@commitlint/cli':
specifier: ^19.4.0
version: 19.4.0(@types/[email protected])([email protected])
@@ -31,7 +31,7 @@ importers:
'@storybook/react':
specifier: 8.2.8
'@types/node':
specifier: ^22.1.0
version: 22.1.0
@@ -133,7 +133,7 @@ importers:
'@storybook/addon-interactions':
specifier: 8.2.8
'@storybook/addon-links':
specifier: 8.2.8
@@ -151,7 +151,7 @@ importers:
'@storybook/react':
specifier: 8.2.8
'@storybook/react-webpack5':
specifier: 8.2.8
@@ -175,7 +175,7 @@ importers:
storybook:
specifier: 8.2.8
- version: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ version: 8.2.8(@babel/[email protected])
storybook-addon-swc:
specifier: ^1.2.0
@@ -1504,6 +1504,9 @@ importers:
'@univerjs/core':
specifier: workspace:*
version: link:../core
+ '@univerjs/data-validation':
+ specifier: workspace:*
+ version: link:../data-validation
'@univerjs/docs':
specifier: workspace:*
version: link:../docs
@@ -1528,6 +1531,9 @@ importers:
'@univerjs/sheets-conditional-formatting':
specifier: workspace:*
version: link:../sheets-conditional-formatting
+ '@univerjs/sheets-data-validation':
+ specifier: workspace:*
+ version: link:../sheets-data-validation
'@univerjs/sheets-formula':
specifier: workspace:*
version: link:../sheets-formula
@@ -11017,7 +11023,7 @@ snapshots:
dependencies:
'@babel/runtime': 7.25.0
dependencies:
'@antfu/install-pkg': 0.3.3
'@clack/prompts': 0.7.0
@@ -11042,7 +11048,7 @@ snapshots:
eslint-plugin-toml: 0.11.1([email protected]([email protected]))
eslint-plugin-unicorn: 55.0.0([email protected]([email protected]))
eslint-plugin-vue: 9.27.0([email protected]([email protected]))
eslint-plugin-yml: 1.14.0([email protected]([email protected]))
eslint-processor-vue-blocks: 0.1.2(@vue/[email protected])([email protected]([email protected]))
@@ -12953,21 +12959,21 @@ snapshots:
'@types/uuid': 9.0.8
dequal: 2.0.3
polished: 4.3.1
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
uuid: 9.0.1
dependencies:
'@storybook/global': 5.0.0
memoizerific: 1.11.3
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
dependencies:
dequal: 2.0.3
lodash: 4.17.21
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
@@ -12977,14 +12983,14 @@ snapshots:
'@storybook/csf-plugin': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
'@storybook/global': 5.0.0
'@types/react': 18.3.3
fs-extra: 11.2.0
react: 18.3.1
react-dom: 18.3.1([email protected])
rehype-external-links: 3.0.0
rehype-slug: 6.0.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
transitivePeerDependencies:
- supports-color
@@ -13000,7 +13006,7 @@ snapshots:
'@storybook/addon-outline': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
'@storybook/addon-toolbars': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
'@storybook/addon-viewport': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
transitivePeerDependencies:
- supports-color
@@ -13008,15 +13014,15 @@ snapshots:
dependencies:
'@storybook/global': 5.0.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
'@storybook/global': 5.0.0
'@storybook/instrumenter': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
polished: 4.3.1
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
transitivePeerDependencies:
- '@jest/globals'
@@ -13029,7 +13035,7 @@ snapshots:
dependencies:
'@storybook/csf': 0.1.11
'@storybook/global': 5.0.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
optionalDependencies:
react: 18.3.1
@@ -13037,13 +13043,13 @@ snapshots:
dependencies:
'@storybook/global': 5.0.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
tiny-invariant: 1.3.3
dependencies:
'@storybook/global': 5.0.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
@@ -13053,12 +13059,12 @@ snapshots:
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
memoizerific: 1.11.3
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
@@ -13081,7 +13087,7 @@ snapshots:
memoizerific: 1.11.3
polished: 4.3.1
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
telejson: 7.2.0
ts-dedent: 2.2.0
util-deprecate: 1.0.2
@@ -13108,7 +13114,7 @@ snapshots:
path-browserify: 1.0.1
process: 0.11.10
semver: 7.6.3
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
@@ -13139,7 +13145,7 @@ snapshots:
'@types/cross-spawn': 6.0.6
cross-spawn: 7.0.3
globby: 14.0.2
- jscodeshift: 0.15.2(@babel/[email protected](@babel/[email protected]))
+ jscodeshift: 0.15.2(@babel/[email protected])
lodash: 4.17.21
prettier: 3.3.3
recast: 0.23.9
@@ -13149,14 +13155,14 @@ snapshots:
- supports-color
- utf-8-validate
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
'@types/node': 18.19.44
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
'@storybook/[email protected]':
@@ -13179,7 +13185,7 @@ snapshots:
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
unplugin: 1.12.1
'@storybook/[email protected]':
@@ -13197,19 +13203,19 @@ snapshots:
dependencies:
'@storybook/global': 5.0.0
'@vitest/utils': 1.6.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
util: 0.12.5
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
'@storybook/[email protected]': {}
dependencies:
'@storybook/core-webpack': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
'@storybook/react-docgen-typescript-plugin': 1.0.6--canary.9.0c3f3b7.0([email protected])([email protected](@swc/[email protected])([email protected]))
'@types/node': 18.19.44
'@types/semver': 7.5.8
@@ -13221,7 +13227,7 @@ snapshots:
react-dom: 18.3.1([email protected])
resolve: 1.22.8
semver: 7.6.3
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
tsconfig-paths: 4.2.0
webpack: 5.93.0(@swc/[email protected])([email protected])
optionalDependencies:
@@ -13233,9 +13239,9 @@ snapshots:
- uglify-js
- webpack-cli
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
@@ -13251,21 +13257,21 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
'@types/node': 18.19.44
react: 18.3.1
react-dom: 18.3.1([email protected])
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
optionalDependencies:
typescript: 5.5.4
transitivePeerDependencies:
@@ -13276,14 +13282,14 @@ snapshots:
- uglify-js
- webpack-cli
dependencies:
- '@storybook/components': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
+ '@storybook/components': 8.2.8([email protected](@babel/[email protected]))
'@storybook/global': 5.0.0
- '@storybook/manager-api': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
- '@storybook/preview-api': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
- '@storybook/theming': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
+ '@storybook/manager-api': 8.2.8([email protected](@babel/[email protected]))
+ '@storybook/preview-api': 8.2.8([email protected](@babel/[email protected]))
+ '@storybook/theming': 8.2.8([email protected](@babel/[email protected]))
'@types/escodegen': 0.0.6
'@types/estree': 0.0.51
'@types/node': 18.19.44
@@ -13298,23 +13304,23 @@ snapshots:
react-dom: 18.3.1([email protected])
react-element-to-jsx-string: 15.0.0([email protected]([email protected]))([email protected])
semver: 7.6.3
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
ts-dedent: 2.2.0
type-fest: 2.19.0
util-deprecate: 1.0.2
optionalDependencies:
typescript: 5.5.4
dependencies:
'@storybook/csf': 0.1.11
'@storybook/instrumenter': 8.2.8([email protected](@babel/[email protected](@babel/[email protected])))
'@testing-library/dom': 10.1.0
'@testing-library/user-event': 14.5.2(@testing-library/[email protected])
'@vitest/expect': 1.6.0
'@vitest/spy': 1.6.0
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
util: 0.12.5
transitivePeerDependencies:
- '@jest/globals'
@@ -13323,13 +13329,13 @@ snapshots:
- jest
- vitest
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
- storybook: 8.2.8(@babel/[email protected](@babel/[email protected]))
+ storybook: 8.2.8(@babel/[email protected])
dependencies:
@@ -13445,7 +13451,7 @@ snapshots:
lz-string: 1.5.0
pretty-format: 27.5.1
dependencies:
'@adobe/css-tools': 4.4.0
'@babel/runtime': 7.25.0
@@ -13456,7 +13462,7 @@ snapshots:
lodash: 4.17.21
redent: 3.0.0
optionalDependencies:
dependencies:
@@ -15908,13 +15914,13 @@ snapshots:
optionalDependencies:
dependencies:
'@typescript-eslint/utils': 7.18.0([email protected]([email protected]))([email protected])
eslint: 9.9.0([email protected])
optionalDependencies:
transitivePeerDependencies:
- supports-color
- typescript
@@ -17048,7 +17054,7 @@ snapshots:
dependencies:
'@babel/core': 7.25.2
'@babel/parser': 7.25.3
@@ -19132,7 +19138,7 @@ snapshots:
webpack: 5.93.0(@swc/[email protected])([email protected])
dependencies:
'@babel/core': 7.25.2
'@babel/types': 7.25.2
@@ -19152,7 +19158,7 @@ snapshots:
fs-extra: 11.2.0
giget: 1.2.3
globby: 14.0.2
- jscodeshift: 0.15.2(@babel/[email protected](@babel/[email protected]))
+ jscodeshift: 0.15.2(@babel/[email protected])
leven: 3.1.0
ora: 5.4.1
prettier: 3.3.3
@@ -19804,7 +19810,7 @@ snapshots:
sass: 1.77.5
terser: 5.31.5
dependencies:
'@ampproject/remapping': 2.3.0
'@vitest/expect': 2.0.5
@@ -19827,8 +19833,6 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.1.0
- happy-dom: 14.12.3
- jsdom: 24.1.0
transitivePeerDependencies:
- less
- lightningcss