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.

refactor(conditional-formatting): init (#4164)

Gpound.liu66188858051a
diff --git a/packages/facade/src/apis/__tests__/create-test-bed.ts b/packages/facade/src/apis/__tests__/create-test-bed.ts
index 189d200806..31949a7526 100644
--- a/packages/facade/src/apis/__tests__/create-test-bed.ts
+++ b/packages/facade/src/apis/__tests__/create-test-bed.ts
@@ -45,7 +45,7 @@ import {
WorksheetProtectionPointModel,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
-import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
+import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModelV2 } from '@univerjs/sheets-conditional-formatting';
import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
import {
@@ -182,7 +182,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
[ConditionalFormattingService],
[ConditionalFormattingFormulaService],
[ConditionalFormattingRuleModel],
- [ConditionalFormattingViewModel],
+ [ConditionalFormattingViewModelV2],
// data validation
[DataValidationCacheService],
diff --git a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts
index 2fd756ddeb..81bb4d061e 100644
--- a/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts
+++ b/packages/facade/src/apis/sheets/__tests__/create-worksheet-test-bed.ts
@@ -45,7 +45,7 @@ import {
WorksheetProtectionPointModel,
WorksheetProtectionRuleModel,
} from '@univerjs/sheets';
-import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
+import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModelV2 } from '@univerjs/sheets-conditional-formatting';
import { DataValidationCacheService, DataValidationCustomFormulaService, DataValidationFormulaService, SheetDataValidationModel, SheetsDataValidationValidatorService } from '@univerjs/sheets-data-validation';
import { UniverSheetsFilterPlugin } from '@univerjs/sheets-filter';
@@ -179,7 +179,7 @@ export function createWorksheetTestBed(workbookData?: IWorkbookData, dependencie
[ConditionalFormattingService],
[ConditionalFormattingFormulaService],
[ConditionalFormattingRuleModel],
- [ConditionalFormattingViewModel],
+ [ConditionalFormattingViewModelV2],
// data validation
[DataValidationCacheService],
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts
index e8094b4369..c0222ce5a2 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.auto-fill.controller.ts
@@ -19,7 +19,7 @@ import type { IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationP
import type { IDiscreteRange, ISheetAutoFillHook } from '@univerjs/sheets-ui';
import { Disposable, Inject, Injector, IUniverInstanceService, ObjectMatrix, Range, Rectangle, UniverInstanceType } from '@univerjs/core';
import { createTopMatrixFromMatrix, findAllRectangle } from '@univerjs/sheets';
-import { ConditionalFormattingRuleModel, ConditionalFormattingViewModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
+import { ConditionalFormattingRuleModel, ConditionalFormattingViewModelV2, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
import { APPLY_TYPE, getAutoFillRepeatRange, IAutoFillService, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
export class ConditionalFormattingAutoFillController extends Disposable {
@@ -28,7 +28,7 @@ export class ConditionalFormattingAutoFillController extends Disposable {
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(IAutoFillService) private _autoFillService: IAutoFillService,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel
+ @Inject(ConditionalFormattingViewModelV2) private _conditionalFormattingViewModel: ConditionalFormattingViewModelV2
) {
super();
@@ -85,21 +85,21 @@ export class ConditionalFormattingAutoFillController extends Disposable {
targetRange
);
const { row: sourceRow, col: sourceCol } = mapFunc(sourcePositionRange.startRow, sourcePositionRange.startColumn);
- const sourceCellCf = this._conditionalFormattingViewModel.getCellCf(
+ const sourceCellCf = this._conditionalFormattingViewModel.getCellCfs(
unitId,
subUnitId,
sourceRow,
sourceCol
);
const { row: targetRow, col: targetCol } = mapFunc(targetPositionRange.startRow, targetPositionRange.startColumn);
- const targetCellCf = this._conditionalFormattingViewModel.getCellCf(
+ const targetCellCf = this._conditionalFormattingViewModel.getCellCfs(
unitId,
subUnitId,
targetRow,
targetCol
);
if (targetCellCf) {
- targetCellCf.cfList.forEach((cf) => {
+ targetCellCf.forEach((cf) => {
let matrix = matrixMap.get(cf.cfId);
if (!matrixMap.get(cf.cfId)) {
const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cf.cfId);
@@ -119,7 +119,7 @@ export class ConditionalFormattingAutoFillController extends Disposable {
}
if (sourceCellCf) {
- sourceCellCf.cfList.forEach((cf) => {
+ sourceCellCf.forEach((cf) => {
let matrix = matrixMap.get(cf.cfId);
if (!matrixMap.get(cf.cfId)) {
const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cf.cfId);
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts
index 693f6c001b..b5c78c6656 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.copy-paste.controller.ts
@@ -31,7 +31,7 @@ import {
import {
createTopMatrixFromMatrix, findAllRectangle,
} from '@univerjs/sheets';
-import { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory, ConditionalFormattingRuleModel, ConditionalFormattingViewModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
+import { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory, ConditionalFormattingRuleModel, ConditionalFormattingViewModelV2, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
import { COPY_TYPE, getRepeatRange, ISheetClipboardService, PREDEFINED_HOOK_NAME, rangeToDiscreteRange, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
export class ConditionalFormattingCopyPasteController extends Disposable {
@@ -48,7 +48,7 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
@Inject(ISheetClipboardService) private _sheetClipboardService: ISheetClipboardService,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
@Inject(Injector) private _injector: Injector,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
+ @Inject(ConditionalFormattingViewModelV2) private _conditionalFormattingViewModel: ConditionalFormattingViewModelV2,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService
) {
@@ -82,10 +82,6 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
cfMap,
},
};
- const model = this._conditionalFormattingViewModel.getMatrix(unitId, subUnitId);
- if (!model) {
- return;
- }
const discreteRange = this._injector.invoke((accessor) => {
return rangeToDiscreteRange(range, accessor, unitId, subUnitId);
@@ -97,12 +93,12 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
const cfIdSet: Set<string> = new Set();
rows.forEach((row, rowIndex) => {
cols.forEach((col, colIndex) => {
- const cellCfList = this._conditionalFormattingViewModel.getCellCf(unitId, subUnitId, row, col, model);
+ const cellCfList = this._conditionalFormattingViewModel.getCellCfs(unitId, subUnitId, row, col);
if (!cellCfList) {
return;
}
- cellCfList.cfList.forEach((item) => cfIdSet.add(item.cfId));
- matrix.setValue(rowIndex, colIndex, cellCfList.cfList.map((item) => item.cfId));
+ cellCfList.forEach((item) => cfIdSet.add(item.cfId));
+ matrix.setValue(rowIndex, colIndex, cellCfList.map((item) => item.cfId));
});
});
cfIdSet.forEach((cfId) => {
@@ -149,13 +145,12 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
const { ranges: [vCopyRange, vPastedRange], mapFunc } = virtualizeDiscreteRanges([copyInfo.copyRange, pastedRange]);
const repeatRange = getRepeatRange(vCopyRange, vPastedRange, true);
- const model = this._conditionalFormattingViewModel.getMatrix(unitId, subUnitId);
const effectedConditionalFormattingRuleMatrix: Record<string, ObjectMatrix<1>> = {};
Range.foreach(vPastedRange, (row, col) => {
const { row: realRow, col: realCol } = mapFunc(row, col);
- const cellCfList = this._conditionalFormattingViewModel.getCellCf(unitId, subUnitId, realRow, realCol, model!);
+ const cellCfList = this._conditionalFormattingViewModel.getCellCfs(unitId, subUnitId, realRow, realCol);
if (cellCfList) {
- cellCfList.cfList.forEach((item) => {
+ cellCfList.forEach((item) => {
if (!effectedConditionalFormattingRuleMatrix[item.cfId]) {
const ruleMatrix = new ObjectMatrix<1>();
effectedConditionalFormattingRuleMatrix[item.cfId] = ruleMatrix;
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.painter.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.painter.controller.ts
index 0a098c37a2..ad1c9553b4 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.painter.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.painter.controller.ts
@@ -19,7 +19,7 @@ import type { IAddConditionalRuleMutationParams, IDeleteConditionalRuleMutationP
import type { IFormatPainterHook } from '@univerjs/sheets-ui';
import { Disposable, Inject, Injector, IUniverInstanceService, ObjectMatrix, Range, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
import { createTopMatrixFromMatrix, findAllRectangle, SheetsSelectionsService } from '@univerjs/sheets';
-import { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory, ConditionalFormattingRuleModel, ConditionalFormattingViewModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
+import { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory, ConditionalFormattingRuleModel, ConditionalFormattingViewModelV2, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
import { FormatPainterStatus, IFormatPainterService } from '@univerjs/sheets-ui';
const repeatByRange = (sourceRange: IRange, targetRange: IRange) => {
@@ -82,7 +82,7 @@ export class ConditionalFormattingPainterController extends Disposable {
@Inject(SheetsSelectionsService) private _sheetsSelectionsService: SheetsSelectionsService,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel
+ @Inject(ConditionalFormattingViewModelV2) private _conditionalFormattingViewModel: ConditionalFormattingViewModelV2
) {
super();
@@ -140,14 +140,14 @@ export class ConditionalFormattingPainterController extends Disposable {
targetRange
);
- const sourceCellCf = this._conditionalFormattingViewModel.getCellCf(
+ const sourceCellCf = this._conditionalFormattingViewModel.getCellCfs(
sourceUnitId,
sourceSubUnitId,
sourcePositionRange.startRow,
sourcePositionRange.startColumn
);
- const targetCellCf = this._conditionalFormattingViewModel.getCellCf(
+ const targetCellCf = this._conditionalFormattingViewModel.getCellCfs(
targetUnitId,
targetSubUnitId,
targetPositionRange.startRow,
@@ -155,7 +155,7 @@ export class ConditionalFormattingPainterController extends Disposable {
);
if (targetCellCf) {
- targetCellCf.cfList.forEach((cf) => {
+ targetCellCf.forEach((cf) => {
let matrix = matrixMap.get(cf.cfId);
if (!matrixMap.get(cf.cfId)) {
const rule = this._conditionalFormattingRuleModel.getRule(targetUnitId, targetSubUnitId, cf.cfId);
@@ -175,7 +175,7 @@ export class ConditionalFormattingPainterController extends Disposable {
}
if (sourceCellCf) {
- sourceCellCf.cfList.forEach((cf) => {
+ sourceCellCf.forEach((cf) => {
const matrix = matrixMap.get(cf.cfId);
matrix && matrix.setValue(targetPositionRange.startRow, targetPositionRange.startColumn, 1);
});
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
index 69a0073fbf..698587e36a 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts
@@ -16,11 +16,12 @@
import type { ICellDataForSheetInterceptor, Workbook } from '@univerjs/core';
import type { IConditionalFormattingCellData, IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
-import { Disposable, Inject, InterceptorEffectEnum, IUniverInstanceService, Range, UniverInstanceType } from '@univerjs/core';
+import { Disposable, Inject, InterceptorEffectEnum, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
import { IRenderManagerService } from '@univerjs/engine-render';
import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';
-import { ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel, DEFAULT_PADDING, DEFAULT_WIDTH } from '@univerjs/sheets-conditional-formatting';
+import { ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModelV2, DEFAULT_PADDING, DEFAULT_WIDTH } from '@univerjs/sheets-conditional-formatting';
import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+import { merge } from 'rxjs';
import { bufferTime, filter } from 'rxjs/operators';
export class SheetsCfRenderController extends Disposable {
@@ -33,196 +34,39 @@ export class SheetsCfRenderController extends Disposable {
@Inject(ConditionalFormattingService) private _conditionalFormattingService: ConditionalFormattingService,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(IRenderManagerService) private _renderManagerService: IRenderManagerService,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
+ @Inject(ConditionalFormattingViewModelV2) private _conditionalFormattingViewModel: ConditionalFormattingViewModelV2,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel
) {
super();
this._initViewModelInterceptor();
- this._initViewModel();
this._initSkeleton();
- this._initVmEffectByRule();
this.disposeWithMe(() => {
this._ruleChangeCacheMap.clear();
});
}
- public markDirtySkeleton() {
+ private _markDirtySkeleton() {
const unitId = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
this._renderManagerService.getRenderById(unitId)?.with(SheetSkeletonManagerService).reCalculate();
this._renderManagerService.getRenderById(unitId)?.mainComponent?.makeDirty();
}
private _initSkeleton() {
- // After the conditional formatting is marked dirty to drive a rendering, to trigger the window within the conditional formatting recalculation
- this.disposeWithMe(this._conditionalFormattingViewModel.markDirty$.pipe(bufferTime(16), filter((v) => {
- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return false;
-
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return false;
-
- return v.filter((item) => item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
- })).subscribe(() => this.markDirtySkeleton()));
-
- // Sort and delete does not mark dirty.
- this.disposeWithMe(this._conditionalFormattingRuleModel.$ruleChange.pipe(bufferTime(16), filter((v) => {
- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return false;
-
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return false;
-
- return v.filter((item) => ['sort', 'delete'].includes(item.type) && item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
- })).subscribe(() => this.markDirtySkeleton()));
-
- // Once the calculation is complete, a view update is triggered
- // This rendering does not trigger conditional formatting recalculation,because the rule is not mark dirty
- this.disposeWithMe(this._conditionalFormattingService.ruleComputeStatus$.pipe(bufferTime(16), filter((v) => {
- const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- if (!workbook) return false;
-
- const worksheet = workbook.getActiveSheet();
- if (!worksheet) return false;
-
- return v.filter((item) => item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
- })).subscribe(() => this.markDirtySkeleton()));
- }
-
- private _initVmEffectByRule() {
- this.disposeWithMe(
- this._conditionalFormattingRuleModel.$ruleChange.subscribe((config) => {
- const { rule, unitId, subUnitId } = config;
- switch (config.type) {
- case 'add': {
- this._handleRuleAdd(unitId, subUnitId, rule);
- return;
- }
- case 'delete': {
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this._conditionalFormattingViewModel.deleteCellCf(unitId, subUnitId, row, col, rule.cfId);
- });
- });
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- return;
- }
- case 'set': {
- this._handleRuleChange(unitId, subUnitId, rule, config.oldRule!);
- return;
- }
- case 'sort': {
- const list = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)!;
- const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {
- map.set(cur, index);
- return map;
- }, new Map<string, number>());
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);
- });
- });
- }
- }
- }));
- }
-
- private _initViewModel() {
- let isNeedMark = false;
- const workbookList = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
- workbookList.forEach((workbook) => {
- const unitId = workbook.getUnitId();
- const subRuleMap = this._conditionalFormattingRuleModel.getUnitRules(unitId);
- if (subRuleMap) {
- [...subRuleMap.keys()].forEach((subUnitId) => {
- const ruleList = subRuleMap.get(subUnitId)!;
- ruleList.forEach((rule) => {
- this._handleRuleAdd(unitId, subUnitId, rule);
- isNeedMark = true;
- });
- });
- }
- });
- isNeedMark && this.markDirtySkeleton();
- }
-
- private _handleRuleAdd(
- unitId: string,
- subUnitId: string,
- rule: IConditionFormattingRule) {
- const list = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)!;
- const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {
- map.set(cur, index);
- return map;
- }, new Map<string, number>());
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, rule.cfId);
- this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);
- });
- });
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- }
-
- private _handleRuleChange(
- unitId: string,
- subUnitId: string,
- rule: IConditionFormattingRule,
- oldRule: IConditionFormattingRule
- ) {
- const list = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)!;
- const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {
- map.set(cur, index);
- return map;
- }, new Map<string, number>());
-
- // After each setting, the cache needs to be cleared,
- // and this cleanup is deferred until the end of the calculation.
- // Otherwise the render will flash once
- const handleChange = (oldRule: IConditionFormattingRule, newRule: IConditionFormattingRule) => {
- oldRule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this._conditionalFormattingViewModel.deleteCellCf(unitId, subUnitId, row, col, oldRule.cfId);
- });
- });
- newRule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, oldRule.cfId);
- this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);
- });
- });
- };
- const dispose = this._conditionalFormattingService.interceptorManager.intercept(this._conditionalFormattingService.interceptorManager.getInterceptPoints().beforeUpdateRuleResult, {
- handler: (config, _, next) => {
- if (unitId === config?.unitId && subUnitId === config.subUnitId && oldRule.cfId === config.cfId) {
- const list = this._ruleChangeCacheMap.get(config.cfId) || [];
- list.forEach((config) => {
- handleChange(config.oldRule, config.rule);
- config.dispose();
- });
- this._ruleChangeCacheMap.delete(config.cfId);
- return;
- }
- next(config);
- },
- });
-
- if (oldRule.cfId === rule.cfId) {
- let list = this._ruleChangeCacheMap.get(oldRule.cfId);
- if (!list) {
- list = [];
- this._ruleChangeCacheMap.set(oldRule.cfId, list);
- }
- list.push({ oldRule, rule, dispose });
- }
-
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, oldRule.cfId);
- });
- });
-
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
+ this.disposeWithMe(merge(this._conditionalFormattingRuleModel.$ruleChange, this._conditionalFormattingViewModel.markDirty$)
+ .pipe(
+ bufferTime(16),
+ filter((v) => !!v.length),
+ filter((v) => {
+ const workbook = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ if (!workbook) return false;
+
+ const worksheet = workbook.getActiveSheet();
+ if (!worksheet) return false;
+
+ return v.filter((item) => item.unitId === workbook.getUnitId() && item.subUnitId === worksheet.getSheetId()).length > 0;
+ })
+ ).subscribe(() => this._markDirtySkeleton()));
}
private _initViewModelInterceptor() {
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.viewport.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.viewport.controller.ts
new file mode 100644
index 0000000000..f7cd77a0dd
--- /dev/null
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.viewport.controller.ts
@@ -0,0 +1,63 @@
+/**
+ * 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 { Workbook } from '@univerjs/core';
+import { Disposable, Inject, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { IRenderManagerService } from '@univerjs/engine-render';
+import { CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH, ConditionalFormattingViewModelV2 } from '@univerjs/sheets-conditional-formatting';
+import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';
+
+export class ConditionalFormattingViewportController extends Disposable {
+ constructor(
+ @Inject(ConditionalFormattingViewModelV2) private _conditionalFormattingViewModel: ConditionalFormattingViewModelV2,
+ @IUniverInstanceService private _univerInstanceService: IUniverInstanceService,
+ @IRenderManagerService private _renderManagerService: IRenderManagerService) {
+ super();
+ this._init();
+ }
+
+ private _init() {
+ const unit = this._univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);
+ const bindUnit = (unit: Workbook) => {
+ const unitId = unit.getUnitId();
+ const render = this._renderManagerService.getRenderById(unitId);
+ if (!render) {
+ return;
+ }
+ const sheetSkeletonManagerService = render.with(SheetSkeletonManagerService);
+ this.disposeWithMe(sheetSkeletonManagerService.currentSkeleton$.subscribe((s) => {
+ if (s) {
+ const range = s.skeleton.rowColumnSegment;
+ const col = range.endColumn - range.startColumn + 1;
+ const row = range.endRow - range.startRow + 1;
+ const length = row * col * 9;
+ const result = Math.max(CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH, length);
+ this._conditionalFormattingViewModel.setCacheLength(result);
+ }
+ }));
+ };
+
+ if (unit) {
+ bindUnit(unit);
+ }
+ this._univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET).subscribe((unit) => {
+ if (!unit) {
+ return;
+ }
+ bindUnit(unit);
+ });
+ }
+}
diff --git a/packages/sheets-conditional-formatting-ui/src/plugin.ts b/packages/sheets-conditional-formatting-ui/src/plugin.ts
index 57ee086d81..99f9f901df 100644
--- a/packages/sheets-conditional-formatting-ui/src/plugin.ts
+++ b/packages/sheets-conditional-formatting-ui/src/plugin.ts
@@ -55,6 +55,7 @@ import { ConditionalFormattingPanelController } from './controllers/cf.panel.con
import { ConditionalFormattingPermissionController } from './controllers/cf.permission.controller';
import { SheetsCfRefRangeController } from './controllers/cf.ref-range.controller';
import { SheetsCfRenderController } from './controllers/cf.render.controller';
+import { ConditionalFormattingViewportController } from './controllers/cf.viewport.controller';
import { defaultPluginConfig, PLUGIN_CONFIG_KEY } from './controllers/config.schema';
@DependentOn(UniverSheetsConditionalFormattingPlugin)
@@ -93,6 +94,7 @@ export class UniverSheetsConditionalFormattingUIPlugin extends Plugin {
[ConditionalFormattingEditorController],
[ConditionalFormattingClearController],
[ConditionalFormattingPainterController],
+ [ConditionalFormattingViewportController],
]);
touchDependencies(this._injector, [
@@ -117,6 +119,7 @@ export class UniverSheetsConditionalFormattingUIPlugin extends Plugin {
[ConditionalFormattingPainterController],
[ConditionalFormattingPermissionController],
[SheetsCfRefRangeController],
+ [ConditionalFormattingViewportController],
]);
}
diff --git a/packages/sheets-conditional-formatting/src/index.ts b/packages/sheets-conditional-formatting/src/index.ts
index f53f4a2b9c..cfdee4e0f8 100644
--- a/packages/sheets-conditional-formatting/src/index.ts
+++ b/packages/sheets-conditional-formatting/src/index.ts
@@ -16,18 +16,16 @@
export * from './base/const';
export * from './models/conditional-formatting-rule-model';
-export * from './models/conditional-formatting-view-model';
+export * from './models/conditional-formatting-view-model-v2';
export * from './models/icon-map';
export * from './models/type';
export { UniverSheetsConditionalFormattingPlugin } from './plugin';
export * from './render/data-bar.render';
export * from './render/icon.render';
export * from './render/type';
-export * from './services/calculate-unit/type';
-export * from './services/calculate-unit/utils';
export * from './services/conditional-formatting.service';
export * from './services/conditional-formatting-formula.service';
-
+export * from './models/calculate-unit-v2/utils';
export * from './utils/anchor';
export * from './utils/create-cf-id';
export * from './utils/is-ranges-equal';
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/base-calculate.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/base-calculate.spec.ts
new file mode 100644
index 0000000000..4ed45d2ac0
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/base-calculate.spec.ts
@@ -0,0 +1,65 @@
+/**
+ * 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 { IColorScale } from '../../type';
+import { CellValueType } from '@univerjs/core';
+import { describe, expect, it, vi } from 'vitest';
+import { CFRuleType, CFValueType } from '../../../base/const';
+import { ColorScaleCalculateUnit } from '../color-scale-calculate-unit';
+
+describe('test-color-scale', () => {
+ it('test-sync-computing', () => {
+ const colorScaleUnit = new ColorScaleCalculateUnit({
+ unitId: '',
+ subUnitId: '',
+ workbook: null as any,
+ worksheet: null as any,
+ rule: {
+ cfId: '123',
+ ranges: [],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.colorScale,
+ config: [{ index: 0, value: { type: CFValueType.num, value: 10 }, color: 'red' },
+ { index: 1, value: { type: CFValueType.num, value: 20 }, color: 'white' },
+ { index: 2, value: { type: CFValueType.num, value: 30 }, color: 'green' },
+ ],
+ } as IColorScale,
+ },
+ limit: 1000,
+ accessor: null as any,
+ getCellValue: (row, col) => ({ v: row + col, t: CellValueType.NUMBER }),
+ });
+ const count = vi.spyOn(colorScaleUnit, 'getCellResult' as any);
+
+ const color1 = colorScaleUnit.getCell(1, 1);
+ const color2 = colorScaleUnit.getCell(2, 12);
+ const color3 = colorScaleUnit.getCell(5, 20);
+ const color4 = colorScaleUnit.getCell(11, 20);
+ expect(color1).toBe('rgb(255,0,0)');
+ expect(color2).toBe('rgb(255,102,102)');
+ expect(color3).toBe('rgb(128,192,128)');
+ expect(color4).toBe('rgb(0,128,0)');
+ // 测试缓存
+ colorScaleUnit.getCell(1, 1);
+ // 之前已经 colorScaleUnit.getCell(1, 1) 后,会缓存,而跳过执行一次计算.
+ expect(count.mock.calls.length).toBe(4);
+ colorScaleUnit.clearCache();
+ colorScaleUnit.getCell(1, 1);
+ // 清除缓存后,会重新计算一次。
+ expect(count.mock.calls.length).toBe(5);
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.color.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.color.spec.ts
new file mode 100644
index 0000000000..95cd37bb81
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.color.spec.ts
@@ -0,0 +1,175 @@
+/**
+ * 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 { IColorScale, IConditionFormattingRule } from '../../../models/type';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { CFRuleType, CFValueType } from '../../../base/const';
+import { createTestBed } from './test.util';
+
+describe('Test colorScale', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+
+ beforeEach(() => {
+ testBed && testBed.univer.dispose();
+ testBed = createTestBed();
+ testBed.getConditionalFormattingViewModel();
+ });
+
+ it('colorScale normal test', () => {
+ const params: IConditionFormattingRule<IColorScale> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.colorScale,
+ config: [{
+ index: 0,
+ color: '#d0d9fb',
+ value: {
+ type: CFValueType.min,
+ },
+ },
+ {
+ index: 1,
+ color: '#2e55ef',
+ value: {
+ type: CFValueType.max,
+ },
+ }],
+ },
+
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ const one = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ const two = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const three = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);
+ const four = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 3);
+ const five = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 4);
+ expect(one).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(208,217,251)',
+ },
+ },
+ });
+ expect(two).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(181,195,249)',
+ },
+ },
+ });
+ expect(three).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(154,173,247)',
+ },
+ },
+ });
+ expect(four).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(127,151,245)',
+ },
+ },
+ });
+ expect(five).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(100,129,243)',
+ },
+ },
+ });
+ });
+ it('The colors are consistent, but the values are interchangeable', () => {
+ const params: IConditionFormattingRule<IColorScale> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.colorScale,
+ config: [{
+ index: 0,
+ color: '#d0d9fb',
+ value: {
+ type: CFValueType.num,
+ value: 1,
+ },
+ },
+ {
+ index: 1,
+ color: '#2e55ef',
+ value: {
+ type: CFValueType.num,
+ value: -5,
+ },
+ },
+ {
+ index: 2,
+ color: 'rgb(231, 37, 143)',
+ value: {
+ type: CFValueType.num,
+ value: 3,
+ },
+ },
+ ],
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ const one = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0); // 1
+ const two = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1); // 2
+ const three = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);// 3
+ const four = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 3); // 4
+ const five = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 6); // is same as 3
+ expect(one).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(46,85,239)',
+ },
+ },
+ });
+ expect(two).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(139,61,191)',
+ },
+ },
+ });
+ expect(three).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(231,37,143)',
+ },
+ },
+ });
+ expect(four).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(231,37,143)',
+ },
+ },
+ });
+ expect(five).toEqual({
+ style: {
+ bg: {
+ rgb: 'rgb(231,37,143)',
+ },
+ },
+ });
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.databar.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.databar.spec.ts
new file mode 100644
index 0000000000..43820e4577
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.databar.spec.ts
@@ -0,0 +1,132 @@
+/**
+ * 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 { IConditionFormattingRule, IDataBar } from '../../../models/type';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { CFRuleType, CFValueType } from '../../../base/const';
+import { createTestBed } from './test.util';
+
+describe('Test conditional formatting data bar', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+
+ beforeEach(() => {
+ testBed && testBed.univer.dispose();
+ testBed = createTestBed();
+ testBed.getConditionalFormattingViewModel();
+ });
+
+ it('The maximum and minimum values of the data bar are corrected automatically when minimum is greater than maximum.', () => {
+ const params: IConditionFormattingRule<IDataBar> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 0, endColumn: 6 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.dataBar,
+ isShowValue: false,
+ config: {
+ // The minimum is greater than the maximum
+ min: { type: CFValueType.num, value: 7 },
+ max: { type: CFValueType.num, value: 1 },
+ isGradient: false,
+ positiveColor: '#abd91a',
+ nativeColor: '#ffbe38',
+ },
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+
+ const start = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 0, 0);
+ const end = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 0, 6);
+
+ expect(start).toEqual({});
+
+ expect(end).toEqual({
+ dataBar: {
+ color: '#abd91a',
+ startPoint: 0,
+ value: 100,
+ isGradient: false,
+ isShowValue: false,
+ },
+ isShowValue: false,
+ });
+ });
+
+ it('test data bar normal', () => {
+ const params: IConditionFormattingRule<IDataBar> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 6, endColumn: 6 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.dataBar,
+ isShowValue: true,
+ config: {
+ min: { value: 2, type: CFValueType.num },
+ max: { value: 5, type: CFValueType.num },
+ isGradient: true,
+ positiveColor: '#abd91a',
+ nativeColor: '#ffbe38',
+ },
+ },
+
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const one = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ const two = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const three = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);
+ const four = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 3);
+ const five = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 4);
+ const six = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 6, 0);
+
+ // If less than the minimum value,do not render the data bar.
+ expect(one).toEqual({});
+ expect(two).toEqual({});
+ expect(three).toEqual({
+ dataBar: {
+ color: '#abd91a',
+ startPoint: 0,
+ value: 33.333333333333336,
+ isGradient: true,
+ isShowValue: true,
+ },
+ isShowValue: true,
+
+ });
+
+ expect(four).toEqual({
+ dataBar: {
+ color: '#abd91a',
+ startPoint: 0,
+ value: 66.66666666666667,
+ isGradient: true,
+ isShowValue: true,
+ },
+ isShowValue: true,
+
+ });
+ expect(five).toEqual({
+ dataBar: {
+ color: '#abd91a',
+ startPoint: 0,
+ value: 100,
+ isGradient: true,
+ isShowValue: true,
+ },
+ isShowValue: true,
+ });
+ expect(six).toEqual({});
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.highlight.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.highlight.spec.ts
new file mode 100644
index 0000000000..a477d514fa
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/calculate.highlight.spec.ts
@@ -0,0 +1,606 @@
+/**
+ * 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 { IAverageHighlightCell, IConditionFormattingRule, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell } from '../../../models/type';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { CFNumberOperator, CFRuleType, CFSubRuleType, CFTextOperator } from '../../../base/const';
+import { createTestBed } from './test.util';
+
+describe('Test conditional formatting highlight', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+
+ beforeEach(() => {
+ testBed && testBed.univer.dispose();
+ testBed = createTestBed();
+ testBed.getConditionalFormattingViewModel();
+ });
+
+ describe('Test Number', async () => {
+ it('Is CFNumberOperator.between', async () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.between,
+ value: [0, 10],
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+
+ it('Is not CFNumberOperator.between', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.between,
+ value: [5, 10],
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('Is CFNumberOperator.equal', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.equal,
+ value: 2,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('Is not CFNumberOperator.equal', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.equal,
+ value: 2,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);
+ expect(result).toEqual({ style: {} });
+ });
+ it('Is CFNumberOperator.greaterThan', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value: 0,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('Is not CFNumberOperator.greaterThan', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value: 2,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('Is CFNumberOperator.greaterThanOrEqual', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThanOrEqual,
+ value: 0,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('Is not CFNumberOperator.greaterThanOrEqual', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThanOrEqual,
+ value: 3,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('Is CFNumberOperator.lessThan', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.lessThan,
+ value: 3,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it(`Is not ${CFNumberOperator.lessThan}`, () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.lessThan,
+ value: 0,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it(`Is ${CFNumberOperator.lessThanOrEqual}`, () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.lessThanOrEqual,
+ value: 3,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('Is not CFNumberOperator.lessThanOrEqual', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.lessThanOrEqual,
+ value: 0,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('Is CFNumberOperator.notBetween', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.notBetween,
+ value: [5, 7],
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('Is not CFNumberOperator.notBetween', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.notBetween,
+ value: [0, 3],
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('Is CFNumberOperator.notEqual', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.notEqual,
+ value: 11,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('Is not CFNumberOperator.notEqual', () => {
+ const params: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.notEqual,
+ value: 2,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ });
+ describe('Test Text', () => {
+ it('is CFTextOperator.beginsWith', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.beginsWith,
+ value: '2',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is not CFTextOperator.beginsWith', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.beginsWith,
+ value: '11',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+
+ it('is CFTextOperator.endsWith', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.endsWith,
+ value: '2',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is not CFTextOperator.endsWith', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.endsWith,
+ value: '11',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+
+ it('is CFTextOperator.containsText', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.containsText,
+ value: '2',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is not CFTextOperator.containsText', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.containsText,
+ value: '11',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('is CFTextOperator.equal', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.containsText,
+ value: '2',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is not CFTextOperator.equal', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.containsText,
+ value: '11',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('is CFTextOperator.notEqual', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notEqual,
+ value: '22',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is not CFTextOperator.notEqual', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notEqual,
+ value: '2',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ it('is CFTextOperator.notContainsText', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notEqual,
+ value: '11',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is not CFTextOperator.notContainsText', () => {
+ const params: IConditionFormattingRule<ITextHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.notEqual,
+ value: '2',
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: {} });
+ });
+ });
+ describe('Test average', () => {
+ it(`is ${CFNumberOperator.greaterThanOrEqual} average`, () => {
+ const params: IConditionFormattingRule<IAverageHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.average,
+ operator: CFNumberOperator.greaterThanOrEqual,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it(`is ${CFNumberOperator.lessThanOrEqual} average`, () => {
+ const params: IConditionFormattingRule<IAverageHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.average,
+ operator: CFNumberOperator.lessThanOrEqual,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ });
+ describe('Test rank', () => {
+ it('is bottom 2', () => {
+ const params: IConditionFormattingRule<IRankHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 4, endColumn: 4 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.rank,
+ isBottom: true,
+ isPercent: false,
+ value: 2,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ it('is bottom 6', () => {
+ const params: IConditionFormattingRule<IRankHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 4, endColumn: 4 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: false,
+ rule: {
+ style: { bg: { rgb: '#2AEAEA' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.rank,
+ isBottom: true,
+ isPercent: false,
+ value: 6,
+ },
+ };
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
+ testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/services/__test__/test.util.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
similarity index 80%
rename from packages/sheets-conditional-formatting/src/services/__test__/test.util.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
index c442123d2f..576a77039b 100644
--- a/packages/sheets-conditional-formatting/src/services/__test__/test.util.ts
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
@@ -16,20 +16,21 @@
import type { Dependency, IWorkbookData } from '@univerjs/core';
import { ICommandService, Inject, Injector, IUniverInstanceService, LocaleType, Plugin, Univer, UniverInstanceType } from '@univerjs/core';
+import { IActiveDirtyManagerService } from '@univerjs/engine-formula';
import {
SheetInterceptorService,
} from '@univerjs/sheets';
+import { AddConditionalRuleMutation } from '../../../commands/mutations/add-conditional-rule.mutation';
+import { DeleteConditionalRuleMutation } from '../../../commands/mutations/delete-conditional-rule.mutation';
+import { ConditionalFormattingFormulaMarkDirty } from '../../../commands/mutations/formula-mark-dirty.mutation';
+import { MoveConditionalRuleMutation } from '../../../commands/mutations/move-conditional-rule.mutation';
+import { SetConditionalRuleMutation } from '../../../commands/mutations/set-conditional-rule.mutation';
-import { IActiveDirtyManagerService } from '@univerjs/engine-formula';
-import { ConditionalFormattingService } from '../conditional-formatting.service';
-import { ConditionalFormattingFormulaService } from '../conditional-formatting-formula.service';
-import { ConditionalFormattingRuleModel } from '../../models/conditional-formatting-rule-model';
-import { ConditionalFormattingViewModel } from '../../models/conditional-formatting-view-model';
-import { AddConditionalRuleMutation } from '../../commands/mutations/add-conditional-rule.mutation';
-import { DeleteConditionalRuleMutation } from '../../commands/mutations/delete-conditional-rule.mutation';
-import { ConditionalFormattingFormulaMarkDirty } from '../../commands/mutations/formula-mark-dirty.mutation';
-import { MoveConditionalRuleMutation } from '../../commands/mutations/move-conditional-rule.mutation';
-import { SetConditionalRuleMutation } from '../../commands/mutations/set-conditional-rule.mutation';
+import { ConditionalFormattingRuleModel } from '../../../models/conditional-formatting-rule-model';
+import { ConditionalFormattingViewModelV2 } from '../../../models/conditional-formatting-view-model-v2';
+
+import { ConditionalFormattingFormulaService } from '../../../services/conditional-formatting-formula.service';
+import { ConditionalFormattingService } from '../../../services/conditional-formatting.service';
const TEST_WORKBOOK_DATA_DEMO: () => IWorkbookData = () => ({
id: 'test',
@@ -44,6 +45,7 @@ const TEST_WORKBOOK_DATA_DEMO: () => IWorkbookData = () => ({
3: { 0: { v: 1, t: 2 }, 1: { v: 2, t: 2 }, 2: { v: 3, t: 2 }, 3: { v: 4, t: 2 }, 4: { v: 5, t: 2 }, 5: { v: 6, t: 2 }, 6: { v: 7, t: 2 } },
4: { 0: { v: 1, t: 2 }, 1: { v: 2, t: 2 }, 2: { v: 3, t: 2 }, 3: { v: 4, t: 2 }, 4: { v: 5, t: 2 }, 5: { v: 6, t: 2 }, 6: { v: 7, t: 2 } },
5: { 0: { v: 1, t: 2 }, 1: { v: 2, t: 2 }, 2: { v: 3, t: 2 }, 3: { v: 4, t: 2 }, 4: { v: 5, t: 2 }, 5: { v: 6, t: 2 }, 6: { v: 7, t: 2 } },
+ 6: { 0: { v: 0, t: 2 } },
},
rowCount: 6,
columnCount: 8,
@@ -70,20 +72,16 @@ export const createTestBed = (dependencies?: Dependency[]) => {
@Inject(Injector) override readonly _injector: Injector
) {
super();
- }
-
- override onStarting(): void {
this._injector.add([SheetInterceptorService]);
- dependencies?.forEach((d) => this._injector.add(d));
- }
-
- override onReady(): void {
this._injector.add([ConditionalFormattingService]);
this._injector.add([ConditionalFormattingFormulaService]);
this._injector.add([ConditionalFormattingRuleModel]);
- this._injector.add([ConditionalFormattingViewModel]);
+ this._injector.add([ConditionalFormattingViewModelV2]);
this._injector.add([IActiveDirtyManagerService, { useFactory: () => ({ register: () => { /* empty */ } } as any) }]);
- this._injector.get(ConditionalFormattingService);
+ }
+
+ override onStarting(): void {
+ dependencies?.forEach((d) => this._injector.add(d));
}
}
@@ -94,6 +92,7 @@ export const createTestBed = (dependencies?: Dependency[]) => {
const univerInstanceService = injector.get(IUniverInstanceService);
const commandService = injector.get(ICommandService);
+
[
AddConditionalRuleMutation,
DeleteConditionalRuleMutation,
@@ -103,13 +102,17 @@ export const createTestBed = (dependencies?: Dependency[]) => {
].forEach((commandInfo) => {
commandService.registerCommand(commandInfo);
});
+
const unitId = workbookJson.id;
const subUnitId = workbookJson.sheets.sheet1.id!;
+
univerInstanceService.focusUnit('test');
univerInstanceService.setCurrentUnitForType(unitId);
+
const getConditionalFormattingRuleModel = () => injector.get(ConditionalFormattingRuleModel);
- const getConditionalFormattingViewModel = () => injector.get(ConditionalFormattingViewModel);
+ const getConditionalFormattingViewModel = () => injector.get(ConditionalFormattingViewModelV2);
const getConditionalFormattingService = () => injector.get(ConditionalFormattingService);
+
return {
univer,
get,
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/base-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/base-calculate-unit.ts
new file mode 100644
index 0000000000..18cb70488d
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/base-calculate-unit.ts
@@ -0,0 +1,149 @@
+/**
+ * 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 { IAccessor, ICellData, Nullable, Workbook, Worksheet } from '@univerjs/core';
+import type { IConditionFormattingRule } from '../type';
+import { LRUMap } from '@univerjs/core';
+import { BehaviorSubject } from 'rxjs';
+import { distinctUntilChanged } from 'rxjs/operators';
+
+export enum CalculateEmitStatus {
+
+ preComputingStart = 'preComputingStart',
+ preComputing = 'preComputing',
+ preComputingEnd = 'preComputingEnd',
+ preComputingError = 'preComputingError',
+
+}
+export interface IContext {
+ unitId: string;
+ subUnitId: string;
+ workbook: Workbook;
+ worksheet: Worksheet;
+ accessor: IAccessor;
+ rule: IConditionFormattingRule;
+ getCellValue: (row: number, col: number,) => ICellData;
+ limit: number;
+}
+/**
+ * Processing Main Path Calculation Logic
+ */
+export abstract class BaseCalculateUnit<C = any, S = any> {
+ /**
+ * 3nd-level cache
+ */
+ private _cache: LRUMap<string, Nullable<S>>;
+
+ protected _preComputingStatus$ = new BehaviorSubject<CalculateEmitStatus>(CalculateEmitStatus.preComputingStart);
+ public preComputingStatus$ = this._preComputingStatus$.asObservable().pipe(distinctUntilChanged());
+ /**
+ * 2nd-level cache
+ */
+ private _preComputingCache: Nullable<C>;
+ private _rule: IConditionFormattingRule;
+
+ constructor(private _context: IContext) {
+ this._cache = new LRUMap(_context.limit);
+ this._rule = _context.rule;
+ this._preComputingCache = null;
+ this._initClearCacheListener();
+ }
+
+ public setCacheLength(length: number) {
+ this._cache.limit = length;
+ }
+
+ public clearCache() {
+ this._cache.clear();
+ }
+
+ public resetPreComputingCache() {
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingStart);
+ this._preComputingCache = null;
+ }
+
+ public updateRule(rule: IConditionFormattingRule) {
+ this._rule = rule;
+ this.resetPreComputingCache();
+ }
+
+ public getCell(row: number, col: number) {
+ const key = this._createKey(row, col);
+
+ if (this._preComputingStatus$.getValue() === CalculateEmitStatus.preComputing) {
+ // If the pre-calculation is not yet complete, return the previous result directly.
+ return this._cache.get(key);
+ }
+ let preComputingResult = this.getPreComputingResult(row, col);
+ if (preComputingResult === null) {
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingStart);
+ this.preComputing(row, col, this._getContext());
+ preComputingResult = this.getPreComputingResult(row, col);
+
+ if (preComputingResult === null) {
+ // If the calculation is not yet complete, return the previous cache.
+ return this._cache.get(key);
+ }
+ }
+
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
+
+ if (this._cache.has(key)) {
+ return this._cache.get(key);
+ }
+ const result = this.getCellResult(row, col, preComputingResult, this._getContext());
+ if (result !== null) {
+ this._setCache(row, col, result);
+ }
+ return result;
+ }
+ // If a null value is set, it indicates that caching is not required.
+ abstract preComputing(row: number, col: number, context: IContext): void;
+
+ /**
+ * If a null value is returned, it indicates that caching is not required.
+ */
+ protected abstract getCellResult(row: number, col: number, preComputingResult: Nullable<C>, context: IContext): Nullable<S>;
+
+ protected setPreComputingCache(v: C) {
+ this._preComputingCache = v;
+ }
+
+ protected getPreComputingResult(_row: number, _col: number) {
+ return this._preComputingCache;
+ }
+
+ private _createKey(row: number, col: number) {
+ return `${row}_${col}`;
+ }
+
+ private _setCache(row: number, col: number, v: Nullable<S>) {
+ const key = this._createKey(row, col);
+ this._cache.set(key, v);
+ }
+
+ private _getContext() {
+ return { ...this._context, rule: this._rule };
+ }
+
+ private _initClearCacheListener() {
+ this.preComputingStatus$.subscribe((e) => {
+ if (e === CalculateEmitStatus.preComputingEnd) {
+ this.clearCache();
+ }
+ });
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/color-scale-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/color-scale-calculate-unit.ts
new file mode 100644
index 0000000000..fc12839bc1
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/color-scale-calculate-unit.ts
@@ -0,0 +1,92 @@
+/**
+ * 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 { IColorScale, IConditionFormattingRule } from '../type';
+import type { IContext } from './base-calculate-unit';
+import { CellValueType, ColorKit, ObjectMatrix, Range } from '@univerjs/core';
+import { isObject } from '@univerjs/engine-render';
+import { CFValueType } from '../../base/const';
+import { FormulaResultStatus } from '../../services/conditional-formatting-formula.service';
+import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';
+import { filterRange, getColorScaleFromValue, getValueByType, isNullable } from './utils';
+
+interface IConfigItem {
+ value: number;
+ color: ColorKit;
+}
+
+export class ColorScaleCalculateUnit extends BaseCalculateUnit<IConfigItem[], string> {
+ override preComputing(_row: number, _col: number, context: IContext): void {
+ const rule = context.rule as IConditionFormattingRule<IColorScale>;
+ const worksheet = context.worksheet;
+ const matrix = new ObjectMatrix<number>();
+ const isNeedMatrix = !rule.rule.config.every((item) => item.value.type === CFValueType.num);
+ if (isNeedMatrix) {
+ const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
+ ranges.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ const cell = context.getCellValue(row, col);
+ const v = cell && cell.v;
+ if (!isNullable(v) && cell?.t === CellValueType.NUMBER) {
+ const _value = Number(v);
+ !Number.isNaN(_value) && matrix.setValue(row, col, _value);
+ }
+ });
+ });
+ }
+ const _configList = [...rule.rule.config].sort((a, b) => a.index - b.index).map((config) => {
+ return {
+ value: getValueByType(config.value, matrix, {
+ ...context,
+ cfId: rule.cfId,
+ }), color: new ColorKit(config.color),
+ };
+ });
+ const isAllFinished = !_configList.some((item) => isObject(item.value) ? item.value.status !== FormulaResultStatus.SUCCESS : false);
+
+ if (isAllFinished) {
+ const colorList = _configList
+ .map((item) => item.color)
+ .reduce((result, color, index) => {
+ result.result.push({ color, value: result.sortValue[index] });
+ return result;
+ }, {
+ result: [] as { value: number; color: ColorKit }[],
+ sortValue: _configList.map((item) => item.value.result as number).sort((a, b) => a - b),
+ })
+ .result;
+ this.setPreComputingCache(colorList);
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
+ return;
+ }
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputing);
+ }
+
+ protected override getCellResult(row: number, col: number, preComputingResult: IConfigItem[], context: IContext) {
+ if (!preComputingResult) {
+ return null;
+ }
+ const value = context.getCellValue(row, col);
+ if (value.t === CellValueType.NUMBER) {
+ const v = Number(value.v);
+ if (!Number.isNaN(v)) {
+ const color = getColorScaleFromValue(preComputingResult, v);
+ return color;
+ }
+ }
+ return undefined;
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/data-bar-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/data-bar-calculate-unit.ts
new file mode 100644
index 0000000000..2e2b83f373
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/data-bar-calculate-unit.ts
@@ -0,0 +1,147 @@
+/**
+ * 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 { ICellData } from '@univerjs/core';
+import type { IConditionFormattingRule, IDataBar } from '../type';
+import type { IContext } from './base-calculate-unit';
+import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
+import { CFValueType } from '../../base/const';
+import { defaultDataBarNativeColor, defaultDataBarPositiveColor, defaultPlaceholderColor } from '../../render/data-bar.render';
+import { FormulaResultStatus } from '../../services/conditional-formatting-formula.service';
+import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';
+import { filterRange, getValueByType, isNullable } from './utils';
+
+const getSafeValue = (v: number) => Math.max(Math.min(100, v), 0);
+
+const getValue = (row: number, col: number, getCell: (row: number, col: number) => ICellData) => {
+ const cell = getCell(row, col);
+ if (cell && cell.t === CellValueType.NUMBER) {
+ const value = Number(cell.v);
+ return Number.isNaN(value) ? null : value;
+ }
+ return null;
+};
+interface IConfig {
+ min: number;
+ max: number;
+ startPoint: number;
+}
+export class DataBarCalculateUnit extends BaseCalculateUnit<IConfig> {
+ override preComputing(row: number, col: number, context: IContext): void {
+ const rule = context.rule as IConditionFormattingRule<IDataBar>;
+ const ruleConfig = rule.rule;
+ const worksheet = context.worksheet;
+ const matrix = new ObjectMatrix<number>();
+ const isNeedMatrix = ![rule.rule.config.max, rule.rule.config.min].every((e) => e.type === CFValueType.num);
+ if (isNeedMatrix) {
+ const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
+ ranges.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ const cell = context.getCellValue(row, col);
+ const v = cell && cell.v;
+ if (!isNullable(v) && cell?.t === CellValueType.NUMBER) {
+ const _value = Number(v);
+ !Number.isNaN(_value) && matrix.setValue(row, col, _value);
+ }
+ });
+ });
+ }
+ const _min = getValueByType(ruleConfig.config.min, matrix, { ...context, cfId: rule.cfId });
+ const _max = getValueByType(ruleConfig.config.max, matrix, { ...context, cfId: rule.cfId });
+ let min = 0;
+ let max = 0;
+
+ // If the formula triggers the calculation, wait for the result,
+ // and use the previous style cache until the result comes out。
+ if (_min.status === FormulaResultStatus.SUCCESS) {
+ const v = Number(_min.result); // Get the minimum value
+ min = Number.isNaN(v) ? 0 : v;
+ } else {
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputing);
+ return;
+ }
+
+ if (_max.status === FormulaResultStatus.SUCCESS) {
+ const maxResult = Number(_max.result); // Get the maximum value
+ const v = Number.isNaN(maxResult) ? 0 : maxResult;
+ max = Math.max(v, min);
+ min = Math.min(v, min);
+ let startPoint = 50;
+ if (min < 0 && max <= 0) {
+ startPoint = 100;
+ } else if (min < 0 && max > 0) {
+ const length = Math.abs(max) + Math.abs(min);
+ startPoint = Math.abs(min) / length * 100;
+ } else if (min >= 0 && max > 0) {
+ startPoint = 0;
+ }
+ this.setPreComputingCache({ min, max, startPoint });
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
+ return;
+ }
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputing);
+ }
+
+ // eslint-disable-next-line complexity
+ protected override getCellResult(row: number, col: number, preComputingResult: IConfig, context: IContext) {
+ const { min, max, startPoint } = preComputingResult;
+ const rule = context.rule as IConditionFormattingRule<IDataBar>;
+ const ruleConfig = rule.rule;
+ const isShowValue = ruleConfig.isShowValue;
+ const isGradient = ruleConfig.config.isGradient;
+ const value = getValue(row, col, context.getCellValue);
+ if (value === null || value < min || (min === max || max < min)) {
+ return undefined;
+ }
+
+ if (value === 0) {
+ // Renders a placeholder if the current value is 0
+ return { color: defaultPlaceholderColor, startPoint, value: 0, isGradient, isShowValue };
+ }
+ if (min < 0 && max <= 0) {
+ const length = max - min;
+
+ const v = getSafeValue((max - value) / length * 100);
+ if (v === 0) {
+ // Renders noting if the result value is 0
+ return undefined;
+ }
+ return { color: ruleConfig.config.nativeColor || defaultDataBarNativeColor, startPoint, value: -v, isGradient, isShowValue };
+ } else if (min < 0 && max > 0) {
+ if (value > 0) {
+ const v = getSafeValue(Math.min(value / max, 1) * 100);
+ if (v === 0) {
+ return undefined;
+ }
+ return { color: ruleConfig.config.positiveColor || defaultDataBarPositiveColor, startPoint, value: v, isGradient, isShowValue };
+ } else {
+ const v = getSafeValue(Math.min(Math.abs(value) / Math.abs(min), 1) * 100);
+ if (v === 0) {
+ return undefined;
+ }
+ return { color: ruleConfig.config.nativeColor || defaultDataBarNativeColor, startPoint, value: -v, isGradient, isShowValue };
+ }
+ } else if (min >= 0 && max > 0) {
+ const length = max - min;
+ const startPoint = 0;
+ const v = getSafeValue((1 - (max - value) / length) * 100);
+ if (v === 0) {
+ return undefined;
+ }
+ return { color: ruleConfig.config.positiveColor || defaultDataBarPositiveColor, startPoint, value: v, isGradient, isShowValue };
+ }
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
similarity index 71%
rename from packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
index 239afd3e4e..2963224a23 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/highlight-cell.ts
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
@@ -14,26 +14,26 @@
* limitations under the License.
*/
-/* eslint-disable max-lines-per-function */
-
-import type { IStyleBase } from '@univerjs/core';
-import type { IAverageHighlightCell, IConditionFormattingRule, IFormulaHighlightCell, IHighlightCell, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell, ITimePeriodHighlightCell } from '../../models/type';
-import type { ICalculateUnit } from './type';
-import { CellValueType, dayjs, ObjectMatrix, Range } from '@univerjs/core';
+import type { IStyleData, Nullable } from '@univerjs/core';
+import type { IAverageHighlightCell, IFormulaHighlightCell, IHighlightCell, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell, ITimePeriodHighlightCell } from '../type';
+import type { IContext } from './base-calculate-unit';
+import { CellValueType, dayjs, Range } from '@univerjs/core';
import { ERROR_TYPE_SET } from '@univerjs/engine-formula';
-import { CFNumberOperator, CFRuleType, CFSubRuleType, CFTextOperator, CFTimePeriodOperator } from '../../base/const';
-import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
-import { EMPTY_STYLE } from './type';
-import { compareWithNumber, filterRange, getCellValue, isFloatsEqual, isNullable, serialTimeToTimestamp } from './utils';
-
-export const highlightCellCalculateUnit: ICalculateUnit = {
- type: CFRuleType.highlightCell,
- handle: async (rule: IConditionFormattingRule, context) => {
- const ruleConfig = rule.rule as IHighlightCell;
-
- const { worksheet, unitId, subUnitId } = context;
- const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
+import { CFNumberOperator, CFSubRuleType, CFTextOperator, CFTimePeriodOperator } from '../../base/const';
+import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../../services/conditional-formatting-formula.service';
+import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';
+import { compareWithNumber, getCellValue, isFloatsEqual, isNullable, serialTimeToTimestamp } from './utils';
+interface IConfig {
+ value: any;
+ type: CFSubRuleType;
+}
+export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConfig>, Nullable<IStyleData>> {
+ // eslint-disable-next-line max-lines-per-function
+ override preComputing(row: number, col: number, context: IContext): void {
+ const ruleConfig = context.rule.rule as IHighlightCell;
+ const ranges = context.rule.ranges;
+ // eslint-disable-next-line max-lines-per-function, complexity
const getCache = () => {
switch (ruleConfig.subType) {
case CFSubRuleType.average: {
@@ -41,7 +41,7 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
let count = 0;
ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
- const cell = worksheet?.getCellRaw(row, col);
+ const cell = context.getCellValue(row, col);
const v = getCellValue(cell || undefined);
if (cell && cell.t === CellValueType.NUMBER && v !== undefined) {
sum += Number(v) || 0;
@@ -49,14 +49,14 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
}
});
});
- return { average: sum / count };
+ return { value: sum / count, type: ruleConfig.subType };
}
case CFSubRuleType.uniqueValues:
case CFSubRuleType.duplicateValues: {
const cacheMap: Map<any, number> = new Map();
ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
- const cell = worksheet?.getCellRaw(row, col);
+ const cell = context.getCellValue(row, col);
const v = getCellValue(cell || undefined);
if (v !== undefined) {
const cache = cacheMap.get(v);
@@ -68,13 +68,13 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
}
});
});
- return { count: cacheMap };
+ return { value: cacheMap, type: ruleConfig.subType };
}
case CFSubRuleType.rank: {
const allValue: number[] = [];
ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
- const cell = worksheet?.getCellRaw(row, col);
+ const cell = context.getCellValue(row, col);
const v = getCellValue(cell || undefined);
if (cell && cell.t === CellValueType.NUMBER && v !== undefined) {
allValue.push(Number(v) || 0);
@@ -82,119 +82,144 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
});
});
allValue.sort((a, b) => b - a);
- const configRule = rule.rule as IRankHighlightCell;
+ const configRule = context.rule.rule as IRankHighlightCell;
const targetIndex = configRule.isPercent
? Math.floor(Math.max(Math.min(configRule.value, 100), 0) / 100 * allValue.length)
: Math.floor(Math.max(Math.min(configRule.isBottom ? (configRule.value - 1) : configRule.value, allValue.length), 0));
if (configRule.isBottom) {
- return { rank: allValue[allValue.length - targetIndex - 1] };
+ return { value: allValue[allValue.length - targetIndex - 1], type: ruleConfig.subType };
} else {
- return { rank: allValue[Math.max(targetIndex - 1, 0)] };
+ return { value: allValue[Math.max(targetIndex - 1, 0)], type: ruleConfig.subType };
}
}
case CFSubRuleType.formula: {
const _ruleConfig = ruleConfig as IFormulaHighlightCell;
const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
- conditionalFormattingFormulaService.registerFormulaWithRange(context.unitId, context.subUnitId, rule.cfId, _ruleConfig.value, rule.ranges);
- break;
+ conditionalFormattingFormulaService.registerFormulaWithRange(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value, context.rule.ranges);
+ const result = conditionalFormattingFormulaService.getFormulaMatrix(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value);
+ if (result && result.status === FormulaResultStatus.SUCCESS) {
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
+ return {
+ value: result.result,
+ type: ruleConfig.subType,
+ };
+ } else {
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputing);
+ }
+ return null;
}
case CFSubRuleType.timePeriod: {
const subRuleConfig = ruleConfig as ITimePeriodHighlightCell;
switch (subRuleConfig.operator) {
case CFTimePeriodOperator.last7Days: {
return {
- timePeriod: {
+ value: {
start: dayjs().subtract(7, 'day').valueOf(),
end: dayjs().valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.lastMonth: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('month').subtract(1, 'month').valueOf(),
end: dayjs().endOf('month').subtract(1, 'month').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.lastWeek: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('week').subtract(1, 'week').valueOf(),
end: dayjs().endOf('week').subtract(1, 'week').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.nextMonth: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('month').add(1, 'month').valueOf(),
end: dayjs().endOf('month').add(1, 'month').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.nextWeek: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('week').add(1, 'week').valueOf(),
end: dayjs().endOf('week').add(1, 'week').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.thisMonth: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('month').valueOf(),
end: dayjs().endOf('month').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.thisWeek: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('week').valueOf(),
end: dayjs().endOf('week').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.today: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('day').valueOf(),
end: dayjs().endOf('day').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.tomorrow: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('day').add(1, 'day').valueOf(),
end: dayjs().endOf('day').add(1, 'day').valueOf(),
},
+ type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.yesterday: {
return {
- timePeriod: {
+ value: {
start: dayjs().startOf('day').subtract(1, 'day').valueOf(),
end: dayjs().endOf('day').subtract(1, 'day').valueOf(),
},
+ type: ruleConfig.subType,
};
}
}
}
}
};
- const cache = getCache();
+ const result = getCache();
+ this.setPreComputingCache(result);
+ }
- // eslint-disable-next-line complexity
- const check = (row: number, col: number) => {
- const cellValue = worksheet?.getCellRaw(row, col);
+ // eslint-disable-next-line max-lines-per-function
+ protected override getCellResult(row: number, col: number, preComputingResult: Nullable<IConfig>, context: IContext) {
+ const cellValue = context.getCellValue(row, col);
+ const ruleConfig = context.rule.rule as IHighlightCell;
+ // eslint-disable-next-line max-lines-per-function, complexity
+ const run = () => {
switch (ruleConfig.subType) {
case CFSubRuleType.number: {
const v = cellValue && Number(cellValue.v);
if (isNullable(v) || Number.isNaN(v) || cellValue?.t !== CellValueType.NUMBER) {
- return false;
+ return;
}
const subRuleConfig = ruleConfig as INumberHighlightCell;
return compareWithNumber({ operator: subRuleConfig.operator, value: subRuleConfig.value || 0 }, v || 0);
@@ -242,21 +267,21 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
}
case CFSubRuleType.timePeriod: {
const value = getCellValue(cellValue!);
- if (isNullable(value) || Number.isNaN(Number(value)) || cellValue?.t !== CellValueType.NUMBER) {
- return false;
+ if (isNullable(value) || Number.isNaN(Number(value)) || cellValue?.t !== CellValueType.NUMBER || !preComputingResult) {
+ return;
}
const v = serialTimeToTimestamp(Number(value));
- const { start, end } = cache!.timePeriod!;
+ const { start, end } = preComputingResult.value!;
return v >= start && v <= end;
}
case CFSubRuleType.average: {
const value = cellValue && cellValue.v;
const v = Number(value);
- if (isNullable(value) || Number.isNaN(v) || cellValue?.t !== CellValueType.NUMBER) {
+ if (isNullable(value) || Number.isNaN(v) || cellValue?.t !== CellValueType.NUMBER || !preComputingResult) {
return false;
}
const subRuleConfig = ruleConfig as IAverageHighlightCell;
- const average = cache?.average!;
+ const average = preComputingResult.value;
switch (subRuleConfig.operator) {
case CFNumberOperator.greaterThan: {
@@ -287,11 +312,11 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
const v = Number(value);
- if (isNullable(value) || Number.isNaN(v) || cellValue?.t !== CellValueType.NUMBER) {
+ if (isNullable(value) || Number.isNaN(v) || cellValue?.t !== CellValueType.NUMBER || !preComputingResult) {
return false;
}
- const targetValue = cache!.rank!;
+ const targetValue = preComputingResult.value;
const subRuleConfig = ruleConfig as IRankHighlightCell;
if (subRuleConfig.isBottom) {
return v <= targetValue;
@@ -302,53 +327,33 @@ export const highlightCellCalculateUnit: ICalculateUnit = {
case CFSubRuleType.uniqueValues: {
const value = getCellValue(cellValue!);
- if (isNullable(value)) {
+ if (isNullable(value) || !preComputingResult) {
return false;
}
- const uniqueCache = cache!.count!;
+ const uniqueCache = preComputingResult.value;
return uniqueCache.get(value) === 1;
}
case CFSubRuleType.duplicateValues: {
const value = getCellValue(cellValue!);
- if (isNullable(value)) {
+ if (isNullable(value) || !preComputingResult) {
return false;
}
- const uniqueCache = cache!.count!;
+ const uniqueCache = preComputingResult.value;
return uniqueCache.get(value) !== 1;
}
case CFSubRuleType.formula: {
- const _ruleConfig = ruleConfig as IFormulaHighlightCell;
- const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
- const result = conditionalFormattingFormulaService.getFormulaResult(unitId, subUnitId, rule.cfId, _ruleConfig.value, row, col);
- if (result && result.status === FormulaResultStatus.SUCCESS) {
- return result.result === true;
+ // const _ruleConfig = ruleConfig as IFormulaHighlightCell;
+ const cache = preComputingResult?.value;
+ if (cache) {
+ const value = cache.getValue(row, col);
+ return value === true;
}
return false;
}
}
};
- const computeResult = new ObjectMatrix<IStyleBase>();
- if (ruleConfig.subType === CFSubRuleType.formula) {
- const _ruleConfig = ruleConfig as IFormulaHighlightCell;
- const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
- const aliasItemMap = conditionalFormattingFormulaService.getSubUnitFormulaMap(unitId, subUnitId);
- const item = aliasItemMap?.getValue(conditionalFormattingFormulaService.createCFormulaId(rule.cfId, _ruleConfig.value), ['id']);
- if (!item || (item.status !== FormulaResultStatus.SUCCESS)) {
- return conditionalFormattingFormulaService.getCache(unitId, subUnitId, rule.cfId) || computeResult;
- }
- }
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- if (check(row, col)) {
- computeResult.setValue(row, col, ruleConfig.style);
- } else {
- // Returns an empty property indicating that it has been processed.
- computeResult.setValue(row, col, EMPTY_STYLE as IStyleBase);
- }
- });
- });
- return computeResult;
- },
-};
-
+ const result = run();
+ return result ? ruleConfig.style : {};
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/icon-set-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/icon-set-calculate-unit.ts
new file mode 100644
index 0000000000..a23b66463b
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/icon-set-calculate-unit.ts
@@ -0,0 +1,119 @@
+/**
+ * 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 { ICellData, Nullable } from '@univerjs/core';
+import type { CFNumberOperator } from '../../base/const';
+import type { IIconSet } from '../type';
+import type { IContext } from './base-calculate-unit';
+import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
+import { CFValueType } from '../../base/const';
+import { FormulaResultStatus } from '../../services/conditional-formatting-formula.service';
+import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';
+import { compareWithNumber, filterRange, getOppositeOperator, getValueByType, isNullable } from './utils';
+
+const getValue = (row: number, col: number, getCell: (row: number, col: number) => ICellData) => {
+ const cell = getCell(row, col);
+ if (cell && cell.t === CellValueType.NUMBER) {
+ const value = Number(cell.v);
+ return Number.isNaN(value) ? null : value;
+ }
+ return null;
+};
+interface IConfigItem {
+ operator: CFNumberOperator;
+ value: number;
+ iconType: string;
+ iconId: string;
+}
+export class IconSetCalculateUnit extends BaseCalculateUnit<IConfigItem[]> {
+ override preComputing(_row: number, _col: number, context: IContext): void {
+ const ruleConfig = context.rule.rule as IIconSet;
+ const worksheet = context.worksheet;
+ const matrix = new ObjectMatrix<number>();
+ const isNeedMatrix = !ruleConfig.config.every((e) => e.value.type === CFValueType.num);
+ if (isNeedMatrix) {
+ const ranges = filterRange(context.rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
+ ranges.forEach((range) => {
+ Range.foreach(range, (row, col) => {
+ const cell = context.getCellValue(row, col);
+ const v = cell && cell.v;
+ if (!isNullable(v) && cell?.t === CellValueType.NUMBER) {
+ const _value = Number(v);
+ !Number.isNaN(_value) && matrix.setValue(row, col, _value);
+ }
+ });
+ });
+ }
+ const splitValueResult = ruleConfig.config.map((v) => getValueByType(v.value, matrix, { ...context, cfId: context.rule.cfId }));
+ const isAllFinished = !splitValueResult.some((item) => item.status !== FormulaResultStatus.SUCCESS);
+ if (isAllFinished) {
+ const splitValue = splitValueResult.map((item, index) => ({
+ operator: ruleConfig.config[index].operator,
+ value: Number(item.result) || 0,
+ })).reduce((result, cur, index, list) => {
+ const item = ruleConfig.config[index];
+ if (!index || index === list.length - 1) {
+ result.push({ ...cur, iconId: item.iconId, iconType: item.iconType });
+ } else {
+ const pre = list[index - 1];
+ if (!compareWithNumber(pre, cur.value)) {
+ result.push({ ...cur, iconId: item.iconId, iconType: item.iconType });
+ }
+ }
+ return result;
+ }, [] as { operator: CFNumberOperator; value: number; iconType: string; iconId: string }[]);
+ this.setPreComputingCache(splitValue);
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
+ return;
+ }
+ this._preComputingStatus$.next(CalculateEmitStatus.preComputing);
+ }
+
+ protected override getCellResult(row: number, col: number, preComputingResult: Nullable<IConfigItem[]>, context: IContext) {
+ if (!preComputingResult) {
+ return null;
+ }
+ const value = getValue(row, col, context.getCellValue);
+
+ if (value === null) {
+ return;
+ }
+ const ruleConfig = context.rule.rule as IIconSet;
+
+ const isShowValue = ruleConfig.isShowValue === undefined ? true : !!ruleConfig.isShowValue;
+
+ for (let index = 0; index < preComputingResult.length; index++) {
+ const item = preComputingResult[index];
+ const start = { ...item };
+ const end = { ...item };
+ const { iconId, iconType } = item;
+ if (index === 0) {
+ if (compareWithNumber(item, value)) {
+ return { iconId, iconType, isShowValue };
+ }
+ } else if (index === preComputingResult.length - 1) {
+ return { iconId, iconType, isShowValue };
+ } else {
+ const pre = preComputingResult[index - 1];
+ end.operator = getOppositeOperator(pre.operator);
+ end.value = pre.value;
+ if (compareWithNumber(start, value) && compareWithNumber(end, value)) {
+ return { iconId, iconType, isShowValue };
+ }
+ }
+ }
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.ts
similarity index 95%
rename from packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts
rename to packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.ts
index 61fb492454..644c8c0c60 100644
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/utils.ts
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/utils.ts
@@ -16,12 +16,12 @@
import type { CellValue, ICellData, IObjectMatrixPrimitiveType, IRange, Nullable } from '@univerjs/core';
import type { IConditionFormattingRule, IValueConfig } from '../../models/type';
-import type { IContext } from './type';
+import type { IContext } from './base-calculate-unit';
import { BooleanNumber, CellValueType, ColorKit, dayjs, ObjectMatrix, Range } from '@univerjs/core';
import { BooleanValue } from '@univerjs/engine-formula';
import { CFNumberOperator, CFValueType } from '../../base/const';
-import { ConditionalFormattingViewModel } from '../../models/conditional-formatting-view-model';
-import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
+import { ConditionalFormattingViewModelV2 } from '../../models/conditional-formatting-view-model-v2';
+import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../../services/conditional-formatting-formula.service';
export function isFloatsEqual(a: number, b: number) {
return Math.abs(a - b) < Number.EPSILON;
@@ -158,7 +158,7 @@ export const getValueByType = (value: IValueConfig, matrix: ObjectMatrix<number>
const formulaText = String(value.value);
const conditionalFormattingFormulaService = accessor.get(ConditionalFormattingFormulaService);
conditionalFormattingFormulaService.registerFormulaWithRange(unitId, subUnitId, cfId, formulaText);
- const result = conditionalFormattingFormulaService.getFormulaResult(unitId, subUnitId, cfId, formulaText);
+ const result = conditionalFormattingFormulaService.getFormulaResultWithCoords(unitId, subUnitId, cfId, formulaText);
return result;
}
case CFValueType.num: {
@@ -173,14 +173,14 @@ export const getValueByType = (value: IValueConfig, matrix: ObjectMatrix<number>
export const getCacheStyleMatrix = <S = any>(unitId: string, subUnitId: string, rule: IConditionFormattingRule, context: IContext) => {
const { accessor } = context;
- const conditionalFormattingViewModel = accessor.get(ConditionalFormattingViewModel);
+ const conditionalFormattingViewModel = accessor.get(ConditionalFormattingViewModelV2);
const matrix = new ObjectMatrix<S>();
rule.ranges.forEach((range) => {
Range.foreach(range, (row, col) => {
- const cellCfItem = conditionalFormattingViewModel.getCellCf(unitId, subUnitId, row, col);
+ const cellCfItem = conditionalFormattingViewModel.getCellCfs(unitId, subUnitId, row, col);
if (cellCfItem) {
- const item = cellCfItem.cfList.find((item) => item.cfId === rule.cfId);
- item?.ruleCache && matrix.setValue(row, col, item.ruleCache as any);
+ const item = cellCfItem.find((item) => item.cfId === rule.cfId);
+ item?.result && matrix.setValue(row, col, item.result);
}
});
});
diff --git a/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts b/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts
index d1cfcf3116..af0483a9f8 100644
--- a/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts
+++ b/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts
@@ -14,14 +14,13 @@
* limitations under the License.
*/
-import { Inject, Injector, Tools } from '@univerjs/core';
-import { Observable, Subject } from 'rxjs';
-import { bufferTime, filter } from 'rxjs/operators';
-import { createCfId } from '../utils/create-cf-id';
import type { IAnchor } from '../utils/anchor';
+import type { IConditionFormattingRule, IRuleModel } from './type';
+import { Tools } from '@univerjs/core';
+import { Subject } from 'rxjs';
import { findIndexByAnchor, moveByAnchor } from '../utils/anchor';
-import type { IConditionFormattingRule, IRuleModel } from './type';
+import { createCfId } from '../utils/create-cf-id';
type RuleOperatorType = 'delete' | 'set' | 'add' | 'sort';
@@ -29,83 +28,7 @@ export class ConditionalFormattingRuleModel {
// Map<unitID ,<sheetId ,IConditionFormattingRule[]>>
private _model: IRuleModel = new Map();
private _ruleChange$ = new Subject<{ rule: IConditionFormattingRule; oldRule?: IConditionFormattingRule; unitId: string; subUnitId: string; type: RuleOperatorType }>();
- $ruleChange = this._ruleChange$.asObservable().pipe(
- bufferTime(16),
- filter((list) => !!list.length),
- // Operations for aggregated conditional formatting
- // Adding and then deleting the same conditional format for multiple times will not result in any changes being propagated externally
- // When multiple settings are applied to the same conditional format, only the last setting will be propagated externally.
- (source) => new Observable<{ rule: IConditionFormattingRule; oldRule?: IConditionFormattingRule; unitId: string; subUnitId: string; type: RuleOperatorType }>((observer) => {
- source.subscribe({
- next: (ruleList) => {
- type Item = (typeof ruleList)[0];
- const createKey = (item: Item) => `${item.unitId}_${item.subUnitId}_${item.rule.cfId}`;
- // Adding and then deleting the same conditional format for multiple times will not result in any changes being propagated externally
- const handleCreateAndDelete = (list: Item[]) => {
- //Between the operation can be nullified, do not have to carry out.
- const createIndex = list.findIndex((rule) => rule.type === 'add');
- const deleteIndex = list.findIndex((rule) => rule.type === 'delete');
- if (createIndex !== -1 && deleteIndex !== -1 && deleteIndex > createIndex) {
- list.splice(createIndex, deleteIndex - createIndex + 1);
- }
- };
- // When multiple settings are applied to the same conditional format, only the last setting will be propagated externally.
- const handleSetAndSet = (list: Item[]) => {
- const setList = list.filter((item) => item.type === 'set');
- if (setList.length < 2) {
- return;
- }
- const theLast = setList[setList.length - 1];
- let index = list.length - 1;
- while (index >= 0) {
- const item = list[index];
- if (item.type === 'set' && item !== theLast) {
- list.splice(index, 1);
- }
- index--;
- }
- };
-
- const result = ruleList.reduce((a, b, index) => {
- const key = createKey(b);
- if (!a[key]) {
- a[key] = [];
- }
- const list = a[key];
- list.push({ ...b, _index: index });
- return a;
- }, {} as Record<string, (Item & { _index: number })[]>);
-
- for (const key in result) {
- const list = result[key];
- if (list.length >= 2) {
- handleCreateAndDelete(list);
- // handleSetAndSet(list)
- }
- }
-
- const resultList = Object.keys(result).reduce((a, key) => {
- const list = result[key];
- a.push(...list);
- return a;
- }, [] as (Item & { _index: number })[]).sort((a, b) => a._index - b._index).map((item) => {
- return item;
- });
-
- resultList.forEach((item) => {
- observer.next(item);
- });
- },
- error: (err) => observer.error(err),
- complete: () => observer.complete(),
- });
- }));
-
- constructor(
- @Inject(Injector) private _injector: Injector
- ) {
- // empty
- }
+ public $ruleChange = this._ruleChange$.asObservable();
private _ensureList(unitId: string, subUnitId: string) {
let list = this.getSubunitRules(unitId, subUnitId);
diff --git a/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model-v2.ts b/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model-v2.ts
new file mode 100644
index 0000000000..9cfa4b4572
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model-v2.ts
@@ -0,0 +1,284 @@
+/**
+ * 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 { Workbook } from '@univerjs/core';
+import type { BaseCalculateUnit, IContext } from './calculate-unit-v2/base-calculate-unit';
+import type { IConditionFormattingRule } from './type';
+import { Disposable, Inject, Injector, IUniverInstanceService, LRUMap, RTree } from '@univerjs/core';
+import { Subject } from 'rxjs';
+import { bufferTime, filter, map } from 'rxjs/operators';
+import { CFRuleType, CFSubRuleType } from '../base/const';
+import { ConditionalFormattingFormulaService } from '../services/conditional-formatting-formula.service';
+import { ColorScaleCalculateUnit } from './calculate-unit-v2/color-scale-calculate-unit';
+import { DataBarCalculateUnit } from './calculate-unit-v2/data-bar-calculate-unit';
+import { HighlightCellCalculateUnit } from './calculate-unit-v2/highlight-cell-calculate-unit';
+import { IconSetCalculateUnit } from './calculate-unit-v2/icon-set-calculate-unit';
+import { ConditionalFormattingRuleModel } from './conditional-formatting-rule-model';
+
+// The default is a 50-row,20-column viewable area.
+export const CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH = 50 * 20 * 3 * 3;
+export class ConditionalFormattingViewModelV2 extends Disposable {
+ // Map<unitID ,<sheetId ,ObjectMatrix>>
+ private _calculateUnitManagers: Map<string, Map<string, Map<string, BaseCalculateUnit>>> = new Map();
+ private _rTreeManager: RTree = new RTree();
+
+ /**
+ * 1nd-level cache
+ */
+ private _cellCache = new LRUMap<string, { cfId: string; result: any; priority: number }[]>(CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH);
+
+ private _markDirty$ = new Subject<{ cfId: string; unitId: string; subUnitId: string; isImmediately?: boolean }>();
+ /**
+ * The rendering layer listens to this variable to determine whether a reRender is necessary.
+ * @memberof ConditionalFormattingViewModelV2
+ */
+ public markDirty$ = this._markDirty$.asObservable();
+ constructor(
+ @Inject(Injector) private _injector: Injector,
+ @Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
+ @Inject(ConditionalFormattingFormulaService) private _conditionalFormattingFormulaService: ConditionalFormattingFormulaService,
+ @IUniverInstanceService private _univerInstanceService: IUniverInstanceService) {
+ super();
+ this._initRuleListener();
+ this._handleCustomFormulasSeparately();
+ this._initCFFormulaListener();
+ }
+
+ private _initCFFormulaListener() {
+ // If a conditional format depends on multiple formula results,removing the 2nd level cache when a single result is returned can cause screen flickering.
+ // It is necessary to wait until all results are ready before removing the cache.
+ this.disposeWithMe(
+ this._conditionalFormattingFormulaService.result$.subscribe(({ unitId, subUnitId, cfId, isAllFinished }) => {
+ if (isAllFinished) {
+ this._markRuleDirtyAtOnce(unitId, subUnitId, cfId, isAllFinished);
+ }
+ }));
+ }
+
+ public getCellCfs(unitId: string, subUnitId: string, row: number, col: number) {
+ const key = this._createCacheKey(unitId, subUnitId, row, col);
+ if (this._cellCache.has(key)) {
+ return this._cellCache.get(key);
+ }
+ const result = this._getCellCfs(unitId, subUnitId, row, col);
+ if (result.length) {
+ this._cellCache.set(key, result);
+ }
+ return result;
+ }
+
+ private _getCellCfs(unitId: string, subUnitId: string, row: number, col: number) {
+ const subunitRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId) ?? [];
+ const _calculateUnitManagers = this._ensureCalculateUnitManager(unitId, subUnitId);
+ const list = this._rTreeManager.bulkSearch([{ unitId, sheetId: subUnitId, range: { startColumn: col, endColumn: col, startRow: row, endRow: row } }]);
+ const rules = subunitRules.filter((rule) => list.has(rule.cfId));
+ if (!rules.length) {
+ return [];
+ }
+ const result = rules.map((rule) => {
+ const calculateUnit = _calculateUnitManagers.get(rule.cfId);
+ if (!calculateUnit) {
+ return null;
+ }
+ return {
+ cfId: rule.cfId,
+ result: calculateUnit.getCell(row, col),
+ };
+ }).filter((e) => !!e).map((e, index) => ({ ...e, priority: index }));
+ return result;
+ }
+
+ /**
+ `isNeedResetPreComputingCache` indicates whether it is necessary to remove the 2nd-level cache for each rule individually.
+ Generally, when the logic of a rule calculation is modified, the cache for that rule needs to be removed.
+ Changes in style/priority do not require the clearing of the 2nd-level cache.
+ Rule changes/region changes require the removal of the 2nd-level cache.
+ There is also a situation where preComputing is asynchronously calculated.
+ After the calculation is finished, it is only for marking as dirty, and the 2nd-level cache need to be cleared.
+ * @param {boolean} [isNeedResetPreComputingCache]
+ */
+ private _markRuleDirtyAtOnce = (unitId: string, subUnitId: string, cfId: string, isNeedResetPreComputingCache: boolean = true) => {
+ this._cellCache.clear();
+ if (isNeedResetPreComputingCache) {
+ const _calculateUnitManagers = this._ensureCalculateUnitManager(unitId, subUnitId);
+ const calculateUnit = _calculateUnitManagers.get(cfId);
+ if (calculateUnit) {
+ calculateUnit.resetPreComputingCache();
+ }
+ }
+
+ this._markDirty$.next({
+ unitId, subUnitId, cfId,
+ });
+ };
+
+ /**
+ * For the same condition format being marked dirty multiple times at the same time,
+ * it will cause the style cache to be cleared, thereby causing the screen to flicker.
+ * Here,multiple dirties are merged into one..
+ */
+ public markRuleDirty = (() => {
+ const rxItem = new Subject<{ unitId: string; subUnitId: string; cfId: string; isNeedResetPreComputingCache: boolean }>();
+ rxItem.pipe(bufferTime(100), filter((e) => !!e.length), map((list) => {
+ const set = new Set();
+ const result: typeof list = [];
+ list.forEach((item) => {
+ const kye = `${item.unitId}_${item.subUnitId}_${item.cfId}`;
+ if (set.has(kye)) {
+ if (item.isNeedResetPreComputingCache) {
+ const i = result.find((e) => e.cfId === item.cfId)!;
+ i.isNeedResetPreComputingCache = true;
+ }
+ return;
+ }
+ set.add(kye);
+ result.push({ ...item });
+ });
+ return result;
+ })).subscribe((list) => {
+ list.forEach((item) => {
+ this._markRuleDirtyAtOnce(item.unitId, item.subUnitId, item.cfId, item.isNeedResetPreComputingCache);
+ });
+ });
+ return (unitId: string, subUnitId: string, cfId: string, isNeedResetPreComputingCache: boolean = true) => {
+ rxItem.next({ unitId, subUnitId, cfId, isNeedResetPreComputingCache });
+ };
+ })();
+
+ private _handleCustomFormulasSeparately() {
+ this.disposeWithMe(
+ this._conditionalFormattingRuleModel.$ruleChange.subscribe((e) => {
+ if (e.type === 'set') {
+ const { unitId, subUnitId } = e;
+ const oldRule = e.oldRule!;
+ // If the range of a custom formula is modified,then the cached formulas must be cleared and recalculated.
+ if (oldRule.rule.type === CFRuleType.highlightCell && oldRule.rule.subType === CFSubRuleType.formula) {
+ this._conditionalFormattingFormulaService.deleteCache(unitId, subUnitId, oldRule.cfId);
+ }
+ }
+ }));
+ }
+
+ private _initRuleListener() {
+ this.disposeWithMe(
+ this._conditionalFormattingRuleModel.$ruleChange.subscribe((e) => {
+ const { unitId, subUnitId, rule } = e;
+ const { cfId, ranges } = rule;
+ const calculateUnitManager = this._ensureCalculateUnitManager(unitId, subUnitId);
+ this.markRuleDirty(unitId, subUnitId, cfId);
+ switch (e.type) {
+ case 'add': {
+ this._rTreeManager.bulkInsert(ranges.map((r) => ({ unitId, sheetId: subUnitId, id: cfId, range: r })));
+ const instance = this._createRuleCalculateUnitInstance(unitId, subUnitId, rule);
+ if (!instance) {
+ return;
+ }
+ calculateUnitManager.set(rule.cfId, instance);
+ break;
+ }
+ case 'delete': {
+ this._rTreeManager.bulkRemove(ranges.map((r) => ({ unitId, sheetId: subUnitId, id: cfId, range: r })));
+ calculateUnitManager.delete(rule.cfId);
+ break;
+ }
+ case 'set': {
+ const oldRule = e.oldRule!;
+
+ this._rTreeManager.bulkRemove(oldRule.ranges.map((r) => ({ unitId, sheetId: subUnitId, id: oldRule.cfId, range: r })));
+ this._rTreeManager.bulkInsert(ranges.map((r) => ({ unitId, sheetId: subUnitId, id: cfId, range: r })));
+ if (oldRule.rule.type !== rule.rule.type) {
+ const instance = this._createRuleCalculateUnitInstance(unitId, subUnitId, rule);
+ if (!instance) {
+ return;
+ }
+ calculateUnitManager.delete(oldRule.cfId);
+ calculateUnitManager.set(rule.cfId, instance);
+ } else {
+ const instance = calculateUnitManager.get(oldRule.cfId);
+ if (!instance) {
+ return;
+ }
+ instance.updateRule(rule);
+ }
+ }
+ }
+ }));
+ }
+
+ private _ensureCalculateUnitManager(unitId: string, subUnitId: string) {
+ let unitMap = this._calculateUnitManagers.get(unitId);
+ if (!unitMap) {
+ unitMap = new Map();
+ this._calculateUnitManagers.set(unitId, unitMap);
+ }
+ let subUnitMap = unitMap.get(subUnitId);
+ if (!subUnitMap) {
+ subUnitMap = new Map();
+ unitMap.set(subUnitId, subUnitMap);
+ }
+ return subUnitMap;
+ }
+
+ private _createRuleCalculateUnitInstance(unitId: string, subUnitId: string, rule: IConditionFormattingRule) {
+ const workbook = this._univerInstanceService.getUnit<Workbook>(unitId);
+ const worksheet = workbook?.getSheetBySheetId(subUnitId);
+ if (!workbook || !worksheet) {
+ return;
+ }
+ const context: IContext = {
+ workbook,
+ worksheet,
+ unitId,
+ subUnitId,
+ accessor: this._injector,
+ rule,
+ limit: CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH,
+ getCellValue: (row: number, col: number) => worksheet.getCellRaw(row, col) || {},
+ };
+ switch (rule.rule.type) {
+ case CFRuleType.colorScale: {
+ return new ColorScaleCalculateUnit(context);
+ }
+ case CFRuleType.dataBar: {
+ return new DataBarCalculateUnit(context);
+ }
+ case CFRuleType.highlightCell: {
+ return new HighlightCellCalculateUnit(context);
+ }
+ case CFRuleType.iconSet: {
+ return new IconSetCalculateUnit(context);
+ }
+ }
+ }
+
+ private _createCacheKey(unitId: string, subUnitId: string, row: number, col: number) {
+ return `${unitId}_${subUnitId}_${row}_${col}`;
+ }
+
+ public setCacheLength(length: number = CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH) {
+ if (this._cellCache.limit === length) {
+ return;
+ }
+ this._cellCache.limit = length;
+ this._calculateUnitManagers.forEach((subunitMap) => {
+ subunitMap.forEach((unitMap) => {
+ unitMap.forEach((unit) => {
+ unit.setCacheLength(length);
+ });
+ });
+ });
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model.ts b/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model.ts
deleted file mode 100644
index b23d52a5a9..0000000000
--- a/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * 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 { ObjectMatrix, Range } from '@univerjs/core';
-import { Subject } from 'rxjs';
-import type { IDataBarRenderParams } from '../render/type';
-import type { IConditionFormattingRule, IHighlightCell } from './type';
-
-interface ICacheItem { cfId: string; ruleCache?: IHighlightCell['style'] | IDataBarRenderParams; isDirty: boolean }
-interface ICellItem {
- cfList: ICacheItem[];
-}
-
-export class ConditionalFormattingViewModel {
- // Map<unitID ,<sheetId ,ObjectMatrix>>
- private _model: Map<string, Map<string, ObjectMatrix<ICellItem>>> = new Map();
-
- private _markDirty$ = new Subject<{ rule: IConditionFormattingRule; unitId: string; subUnitId: string }>();
- public markDirty$ = this._markDirty$.asObservable();
-
- private _ensureMatrix(unitId: string, subUnitId: string) {
- let _matrix = this.getMatrix(unitId, subUnitId);
- if (!_matrix) {
- _matrix = new ObjectMatrix<ICellItem>();
- let unitModel = this._model.get(unitId);
- if (!unitModel) {
- unitModel = new Map<string, ObjectMatrix<ICellItem>>();
- this._model.set(unitId, unitModel);
- }
- unitModel.set(subUnitId, _matrix);
- }
- return _matrix;
- }
-
- public getMatrix(unitId: string, subUnitId: string) {
- return this._model.get(unitId)?.get(subUnitId);
- }
-
- public getCellCf(unitId: string, subUnitId: string, row: number, col: number, matrix?: ObjectMatrix<ICellItem>) {
- const _matrix = matrix ?? this.getMatrix(unitId, subUnitId);
- if (!_matrix) {
- return null;
- }
- const value = _matrix.getValue(row, col);
- return value;
- }
-
- public setCellCfRuleCache(unitId: string, subUnitId: string, row: number, col: number, cfId: string, value: any) {
- const matrix = this._ensureMatrix(unitId, subUnitId);
- const cell = matrix.getValue(row, col);
- const item = cell?.cfList.find((e) => e.cfId === cfId);
- if (item) {
- item.ruleCache = value;
- item.isDirty = false;
- }
- }
-
- public deleteCellCf(
- unitId: string,
- subUnitId: string,
- row: number,
- col: number,
- cfId: string,
- matrix?: ObjectMatrix<ICellItem>) {
- const _matrix = matrix ?? this.getMatrix(unitId, subUnitId);
- if (_matrix) {
- const cellItem = _matrix.getValue(row, col);
- if (cellItem) {
- const cfList = cellItem.cfList;
- const index = cfList.findIndex((item) => item.cfId === cfId);
- if (index > -1) {
- cfList.splice(index, 1);
- }
- if (!cfList.length) {
- _matrix.realDeleteValue(row, col);
- }
- }
- }
- }
-
- public pushCellCf(
- unitId: string,
- subUnitId: string,
- row: number,
- col: number,
- cfId: string
- ) {
- const _matrix = this._ensureMatrix(unitId, subUnitId);
- let cellValue = _matrix.getValue(row, col);
- if (!cellValue) {
- cellValue = { cfList: [{ cfId, isDirty: true }] };
- } else {
- const cfIdList = cellValue.cfList;
- const index = cfIdList.findIndex((item) => item.cfId === cfId);
- if (index > -1) {
- return;
- }
- cfIdList.push({ cfId, isDirty: true });
- }
- _matrix.setValue(row, col, cellValue);
- }
-
- public sortCellCf(
- unitId: string,
- subUnitId: string,
- row: number,
- col: number,
- cfPriorityMap: Map<string, number>) {
- const cell = this.getCellCf(unitId, subUnitId, row, col);
- if (cell) {
- const sortResult = cell.cfList.map((cf) => {
- const priority = cfPriorityMap.get(cf.cfId);
- if (priority === undefined) {
- return null;
- }
- return { ...cf, priority };
- })
- .filter((item) => !!item)
- .sort((a, b) => a!.priority - b!.priority) as ICellItem['cfList'];
- // The smaller the priority, the higher
- cell.cfList = sortResult;
- }
- }
-
- public markRuleDirty(
- unitId: string,
- subUnitId: string,
- rule: IConditionFormattingRule,
- row?: number,
- col?: number
- ) {
- const handleCell = (row: number, col: number) => {
- const cell = this.getCellCf(unitId, subUnitId, row, col);
- if (cell) {
- const ruleItem = cell.cfList.find((item) => item.cfId === rule.cfId);
- if (ruleItem) {
- ruleItem.isDirty = true;
- }
- }
- };
- if (row !== undefined && col !== undefined) {
- handleCell(row, col);
- this._markDirty$.next({ rule, unitId, subUnitId });
- } else {
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- handleCell(row, col);
- });
- });
- this._markDirty$.next({ rule, unitId, subUnitId });
- }
- }
-}
diff --git a/packages/sheets-conditional-formatting/src/plugin.ts b/packages/sheets-conditional-formatting/src/plugin.ts
index 18a4187b2c..04372deee2 100644
--- a/packages/sheets-conditional-formatting/src/plugin.ts
+++ b/packages/sheets-conditional-formatting/src/plugin.ts
@@ -16,7 +16,7 @@
import type { Dependency } from '@univerjs/core';
import type { IUniverSheetsConditionalFormattingConfig } from './controllers/config.schema';
-import { ICommandService, IConfigService, Inject, Injector, Plugin, UniverInstanceType } from '@univerjs/core';
+import { ICommandService, IConfigService, Inject, Injector, Plugin, touchDependencies, UniverInstanceType } from '@univerjs/core';
import { SHEET_CONDITIONAL_FORMATTING_PLUGIN } from './base/const';
import { AddConditionalRuleMutation } from './commands/mutations/add-conditional-rule.mutation';
import { DeleteConditionalRuleMutation } from './commands/mutations/delete-conditional-rule.mutation';
@@ -28,7 +28,7 @@ import {
PLUGIN_CONFIG_KEY,
} from './controllers/config.schema';
import { ConditionalFormattingRuleModel } from './models/conditional-formatting-rule-model';
-import { ConditionalFormattingViewModel } from './models/conditional-formatting-view-model';
+import { ConditionalFormattingViewModelV2 } from './models/conditional-formatting-view-model-v2';
import { ConditionalFormattingService } from './services/conditional-formatting.service';
import { ConditionalFormattingFormulaService } from './services/conditional-formatting-formula.service';
@@ -52,7 +52,7 @@ export class UniverSheetsConditionalFormattingPlugin extends Plugin {
[ConditionalFormattingService],
[ConditionalFormattingFormulaService],
[ConditionalFormattingRuleModel],
- [ConditionalFormattingViewModel],
+ [ConditionalFormattingViewModelV2],
] as Dependency[]).forEach((dependency) => {
this._injector.add(dependency);
});
@@ -70,5 +70,6 @@ export class UniverSheetsConditionalFormattingPlugin extends Plugin {
override onStarting(): void {
this._injector.get(ConditionalFormattingService);
+ touchDependencies(this._injector, [[ConditionalFormattingService], [ConditionalFormattingViewModelV2]]);
}
}
diff --git a/packages/sheets-conditional-formatting/src/render/data-bar.render.ts b/packages/sheets-conditional-formatting/src/render/data-bar.render.ts
index d2221534d0..b3f6cbe967 100644
--- a/packages/sheets-conditional-formatting/src/render/data-bar.render.ts
+++ b/packages/sheets-conditional-formatting/src/render/data-bar.render.ts
@@ -24,6 +24,8 @@ export const dataBarUKey = 'sheet-conditional-rule-data-bar';
export const defaultDataBarPositiveColor = '#ffbe38';
export const defaultDataBarNativeColor = '#abd91a';
+export const defaultPlaceholderColor = '#000';
+
const EXTENSION_Z_INDEX = 34;
export class DataBar extends SheetExtension {
diff --git a/packages/sheets-conditional-formatting/src/services/__test__/calculate.databar.spec.ts b/packages/sheets-conditional-formatting/src/services/__test__/calculate.databar.spec.ts
deleted file mode 100644
index 40d7217b9a..0000000000
--- a/packages/sheets-conditional-formatting/src/services/__test__/calculate.databar.spec.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * 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 { Range } from '@univerjs/core';
-import type { IConditionFormattingRule, IDataBar } from '../../models/type';
-import { CFRuleType, CFValueType } from '../../base/const';
-import { createTestBed } from './test.util';
-
-describe('Test conditional formatting data bar', () => {
- let testBed: ReturnType<typeof createTestBed>;
-
- beforeEach(() => {
- testBed && testBed.univer.dispose();
- testBed = createTestBed();
- (testBed.getConditionalFormattingService() as any)._calculateUnit$.subscribe((config: any) => {
- (testBed.getConditionalFormattingService() as any)._handleCalculateUnit(config.unitId, config.subUnitId, config.rule);
- });
- (testBed.getConditionalFormattingRuleModel() as any)._ruleChange$.subscribe((config: any) => {
- config.rule.ranges.forEach((range: any) => {
- const viewModel = testBed.getConditionalFormattingViewModel();
- Range.foreach(range, (row, col) => {
- viewModel.pushCellCf(config.unitId, config.subUnitId, row, col, config.rule.cfId);
- });
- });
- });
- });
-
- it('The maximum and minimum values of the data bar are corrected automatically when minimum is greater than maximum.', () => {
- const params: IConditionFormattingRule<IDataBar> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 0, endColumn: 6 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- type: CFRuleType.dataBar,
- isShowValue: false,
- config: {
- // The minimum is greater than the maximum
- min: { type: CFValueType.num, value: 7 },
- max: { type: CFValueType.num, value: 1 },
- isGradient: false,
- positiveColor: '#abd91a',
- nativeColor: '#ffbe38',
- },
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
-
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const start = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 0, 0);
- const end = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 0, 6);
-
- expect(start).toEqual({
- dataBar: {
- color: '#abd91a',
- startPoint: 0,
- value: 0,
- isGradient: false,
- isShowValue: false,
- },
- isShowValue: false,
- });
-
- expect(end).toEqual({
- dataBar: {
- color: '#abd91a',
- startPoint: 0,
- value: 100,
- isGradient: false,
- isShowValue: false,
- },
- isShowValue: false,
- });
- });
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 0, 1);
- });
-});
diff --git a/packages/sheets-conditional-formatting/src/services/__test__/cf.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__test__/cf.service.spec.ts
deleted file mode 100644
index 14050d364b..0000000000
--- a/packages/sheets-conditional-formatting/src/services/__test__/cf.service.spec.ts
+++ /dev/null
@@ -1,957 +0,0 @@
-/**
- * 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 { Range } from '@univerjs/core';
-import type { IAverageHighlightCell, IColorScale, IConditionFormattingRule, IDataBar, INumberHighlightCell, IRankHighlightCell, ITextHighlightCell } from '../../models/type';
-import { CFNumberOperator, CFRuleType, CFSubRuleType, CFTextOperator, CFValueType } from '../../base/const';
-import { EMPTY_STYLE } from '../calculate-unit/type';
-import { createTestBed } from './test.util';
-
-describe('Test conditional formatting service', () => {
- let testBed: ReturnType<typeof createTestBed>;
-
- beforeEach(() => {
- testBed && testBed.univer.dispose();
- testBed = createTestBed();
- (testBed.getConditionalFormattingService() as any)._calculateUnit$.subscribe((config: any) => {
- (testBed.getConditionalFormattingService() as any)._handleCalculateUnit(config.unitId, config.subUnitId, config.rule);
- });
- (testBed.getConditionalFormattingRuleModel() as any)._ruleChange$.subscribe((config: any) => {
- config.rule.ranges.forEach((range: any) => {
- const viewModel = testBed.getConditionalFormattingViewModel();
- Range.foreach(range, (row, col) => {
- viewModel.pushCellCf(config.unitId, config.subUnitId, row, col, config.rule.cfId);
- });
- });
- });
- });
-
- describe('Test highlight', () => {
- describe('Test Number', () => {
- it(`Is ${CFNumberOperator.between}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.between,
- value: [0, 10],
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.between}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.between,
- value: [5, 10],
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.equal}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.equal,
- value: 2,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.equal}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.equal,
- value: 2,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.greaterThan}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.greaterThan,
- value: 0,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.greaterThan}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.greaterThan,
- value: 2,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.greaterThanOrEqual}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.greaterThanOrEqual,
- value: 0,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.greaterThanOrEqual}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.greaterThanOrEqual,
- value: 3,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.lessThan}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.lessThan,
- value: 3,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.lessThan}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.lessThan,
- value: 0,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.lessThanOrEqual}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.lessThanOrEqual,
- value: 3,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.lessThanOrEqual}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.lessThanOrEqual,
- value: 0,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.notBetween}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.notBetween,
- value: [5, 7],
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.notBetween}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.notBetween,
- value: [0, 3],
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`Is ${CFNumberOperator.notEqual}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.notEqual,
- value: 11,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`Is not ${CFNumberOperator.notEqual}`, () => {
- const params: IConditionFormattingRule<INumberHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.number,
- operator: CFNumberOperator.notEqual,
- value: 2,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- });
- describe('Test Text', () => {
- it(`is ${CFTextOperator.beginsWith}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.beginsWith,
- value: '2',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is not ${CFTextOperator.beginsWith}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.beginsWith,
- value: '11',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
-
- it(`is ${CFTextOperator.endsWith}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.endsWith,
- value: '2',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is not ${CFTextOperator.endsWith}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.endsWith,
- value: '11',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
-
- it(`is ${CFTextOperator.containsText}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.containsText,
- value: '2',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is not ${CFTextOperator.containsText}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.containsText,
- value: '11',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`is ${CFTextOperator.equal}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.containsText,
- value: '2',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is not ${CFTextOperator.equal}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.containsText,
- value: '11',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`is ${CFTextOperator.notEqual}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.notEqual,
- value: '22',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is not ${CFTextOperator.notEqual}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.notEqual,
- value: '2',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- it(`is ${CFTextOperator.notContainsText}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.notEqual,
- value: '11',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is not ${CFTextOperator.notContainsText}`, () => {
- const params: IConditionFormattingRule<ITextHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.text,
- operator: CFTextOperator.notEqual,
- value: '2',
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: EMPTY_STYLE });
- });
- });
- });
- describe('Test average', () => {
- it(`is ${CFNumberOperator.greaterThanOrEqual} average`, () => {
- const params: IConditionFormattingRule<IAverageHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.average,
- operator: CFNumberOperator.greaterThanOrEqual,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it(`is ${CFNumberOperator.lessThanOrEqual} average`, () => {
- const params: IConditionFormattingRule<IAverageHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.average,
- operator: CFNumberOperator.lessThanOrEqual,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- });
- describe('Test rank', () => {
- it('is bottom 2', () => {
- const params: IConditionFormattingRule<IRankHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 4, endColumn: 4 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.rank,
- isBottom: true,
- isPercent: false,
- value: 2,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- it('is bottom 6', () => {
- const params: IConditionFormattingRule<IRankHighlightCell> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 4, endColumn: 4 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- style: { bg: { rgb: '#2AEAEA' } },
- type: CFRuleType.highlightCell,
- subType: CFSubRuleType.rank,
- isBottom: true,
- isPercent: false,
- value: 6,
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
- });
- });
- });
- // describe('Test timePeriod', () => {
- // // wait
- // });
- describe('Test dataBar', () => {
- it('dataBar', () => {
- const params: IConditionFormattingRule<IDataBar> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- type: CFRuleType.dataBar,
- isShowValue: true,
- config: {
- min: { value: 2, type: CFValueType.num },
- max: { value: 5, type: CFValueType.num },
- isGradient: true,
- positiveColor: '#abd91a',
- nativeColor: '#ffbe38',
- },
- },
-
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const one = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- const two = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const three = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);
- const four = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 3);
- const five = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 4);
- expect(one).toEqual(EMPTY_STYLE);
- expect(two).toEqual({
- dataBar: {
- color: '#abd91a',
- startPoint: 0,
- value: 0,
- isGradient: true,
- isShowValue: true,
- },
- isShowValue: true,
- });
- expect(three).toEqual({
- dataBar: {
- color: '#abd91a',
- startPoint: 0,
- value: 33.333333333333336,
- isGradient: true,
- isShowValue: true,
- },
- isShowValue: true,
-
- });
-
- expect(four).toEqual({
- dataBar: {
- color: '#abd91a',
- startPoint: 0,
- value: 66.66666666666667,
- isGradient: true,
- isShowValue: true,
- },
- isShowValue: true,
-
- });
- expect(five).toEqual({
- dataBar: {
- color: '#abd91a',
- startPoint: 0,
- value: 100,
- isGradient: true,
- isShowValue: true,
- },
- isShowValue: true,
- });
- });
- });
- });
- describe('Test colorScale', () => {
- it('colorScale', () => {
- const params: IConditionFormattingRule<IColorScale> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- type: CFRuleType.colorScale,
- config: [{
- index: 0,
- color: '#d0d9fb',
- value: {
- type: CFValueType.min,
- },
- },
- {
- index: 1,
- color: '#2e55ef',
- value: {
- type: CFValueType.max,
- },
- }],
- },
-
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const one = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- const two = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
- const three = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);
- const four = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 3);
- const five = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 4);
- expect(one).toEqual({
- style: {
- bg: {
- rgb: 'rgb(208,217,251)',
- },
- },
- });
- expect(two).toEqual({
- style: {
- bg: {
- rgb: 'rgb(181,195,249)',
- },
- },
- });
- expect(three).toEqual({
- style: {
- bg: {
- rgb: 'rgb(154,173,247)',
- },
- },
- });
- expect(four).toEqual({
- style: {
- bg: {
- rgb: 'rgb(127,151,245)',
- },
- },
- });
- expect(five).toEqual({
- style: {
- bg: {
- rgb: 'rgb(100,129,243)',
- },
- },
- });
- });
- });
- it('The colors are consistent, but the values are interchangeable', () => {
- const params: IConditionFormattingRule<IColorScale> = {
- ranges: [{ startRow: 0, startColumn: 0, endRow: 5, endColumn: 6 }],
- cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
- stopIfTrue: false,
- rule: {
- type: CFRuleType.colorScale,
- config: [{
- index: 0,
- color: '#d0d9fb',
- value: {
- type: CFValueType.num,
- value: 1,
- },
- },
- {
- index: 1,
- color: '#2e55ef',
- value: {
- type: CFValueType.num,
- value: -5,
- },
- },
- {
- index: 2,
- color: 'rgb(231, 37, 143)',
- value: {
- type: CFValueType.num,
- value: 3,
- },
- },
- ],
- },
- };
- testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, params);
- testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0);
- const dispose = testBed.getConditionalFormattingService().ruleComputeStatus$.subscribe(() => {
- dispose.unsubscribe();
- const one = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 0); // 1
- const two = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1); // 2
- const three = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 2);// 3
- const four = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 3); // 4
- const five = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 6); // is same as 3
- expect(one).toEqual({
- style: {
- bg: {
- rgb: 'rgb(46,85,239)',
- },
- },
- });
- expect(two).toEqual({
- style: {
- bg: {
- rgb: 'rgb(139,61,191)',
- },
- },
- });
- expect(three).toEqual({
- style: {
- bg: {
- rgb: 'rgb(231,37,143)',
- },
- },
- });
- expect(four).toEqual({
- style: {
- bg: {
- rgb: 'rgb(231,37,143)',
- },
- },
- });
- expect(five).toEqual({
- style: {
- bg: {
- rgb: 'rgb(231,37,143)',
- },
- },
- });
- });
- });
- });
- });
-});
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts
deleted file mode 100644
index e559717ced..0000000000
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/color-scale.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * 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 { IColorScale, IConditionFormattingRule } from '../../models/type';
-import type { ICalculateUnit } from './type';
-import { CellValueType, ColorKit, ObjectMatrix, Range } from '@univerjs/core';
-import { isObject } from '@univerjs/engine-render';
-import { CFRuleType } from '../../base/const';
-import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
-import { filterRange, getColorScaleFromValue, getValueByType, isNullable } from './utils';
-
-const emptyStyle = '';
-export const colorScaleCellCalculateUnit: ICalculateUnit = {
- type: CFRuleType.colorScale,
- handle: async (rule: IConditionFormattingRule, context) => {
- const ruleConfig = rule.rule as IColorScale;
- const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
- const { worksheet } = context;
- const matrix = new ObjectMatrix<number>();
- const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const cell = worksheet?.getCellRaw(row, col);
- const v = cell && cell.v;
- if (!isNullable(v) && cell?.t === CellValueType.NUMBER) {
- const _value = Number(v);
- !Number.isNaN(_value) && matrix.setValue(row, col, _value);
- }
- });
- });
-
- const computeResult = new ObjectMatrix<string>();
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- computeResult.setValue(row, col, emptyStyle);
- });
- });
-
- const _configList = [...ruleConfig.config].sort((a, b) => a.index - b.index).map((config) => {
- return {
- value: getValueByType(config.value, matrix, { ...context, cfId: rule.cfId }), color: new ColorKit(config.color),
- };
- });
- // If the formula triggers the calculation, wait for the result,
- // and use the previous style cache until the result comes out
- const isFormulaWithoutSuccess = _configList.some((item) => isObject(item.value) ? item.value.status !== FormulaResultStatus.SUCCESS : false);
- if (isFormulaWithoutSuccess) {
- return conditionalFormattingFormulaService.getCache(context.unitId, context.subUnitId, rule.cfId) ?? computeResult;
- }
-
- const colorList = _configList
- .map((item) => item.color)
- .reduce((result, color, index) => {
- result.result.push({ color, value: result.sortValue[index] });
- return result;
- }, {
- result: [] as { value: number; color: ColorKit }[],
- sortValue: _configList.map((item) => item.value.result as number).sort((a, b) => a - b),
- })
- .result;
-
- if (colorList.length <= 1) {
- return computeResult;
- }
-
- matrix.forValue((row, col, value) => {
- const color = getColorScaleFromValue(colorList, value);
- color && computeResult.setValue(row, col, color);
- });
- return computeResult;
- },
-
-};
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts
deleted file mode 100644
index 5a925db026..0000000000
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * 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 { IConditionFormattingRule, IDataBar } from '../../models/type';
-import type { IDataBarRenderParams } from '../../render/type';
-import type { ICalculateUnit } from './type';
-import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
-import { CFRuleType } from '../../base/const';
-import { defaultDataBarNativeColor, defaultDataBarPositiveColor } from '../../render/data-bar.render';
-import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
-import { EMPTY_STYLE } from './type';
-import { filterRange, getValueByType, isNullable } from './utils';
-
-export const dataBarCellCalculateUnit: ICalculateUnit = {
- type: CFRuleType.dataBar,
- // eslint-disable-next-line max-lines-per-function
- handle: async (rule: IConditionFormattingRule, context) => {
- const ruleConfig = rule.rule as IDataBar;
- const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
-
- const { worksheet } = context;
- const matrix = new ObjectMatrix<number>();
- const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const cell = worksheet?.getCellRaw(row, col);
- const v = cell && cell.v;
- if (!isNullable(v) && cell?.t === CellValueType.NUMBER) {
- const _value = Number(v);
- !Number.isNaN(_value) && matrix.setValue(row, col, _value);
- }
- });
- });
-
- const computeResult = new ObjectMatrix<IDataBarRenderParams>();
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- computeResult.setValue(row, col, EMPTY_STYLE as IDataBarRenderParams);
- });
- });
-
- const _min = getValueByType(ruleConfig.config.min, matrix, { ...context, cfId: rule.cfId });
- const _max = getValueByType(ruleConfig.config.max, matrix, { ...context, cfId: rule.cfId });
- let min = 0;
- let max = 0;
-
- // If the formula triggers the calculation, wait for the result,
- // and use the previous style cache until the result comes out。
- if (_min.status === FormulaResultStatus.WAIT) {
- return conditionalFormattingFormulaService.getCache(context.unitId, context.subUnitId, rule.cfId) || computeResult;
- } else if (_min.status === FormulaResultStatus.SUCCESS) {
- const v = Number(_min.result); // Get the minimum value
- min = Number.isNaN(v) ? 0 : v;
- } else {
- return computeResult;
- }
- if (_max.status === FormulaResultStatus.WAIT) {
- return conditionalFormattingFormulaService.getCache(context.unitId, context.subUnitId, rule.cfId) || computeResult;
- } else if (_max.status === FormulaResultStatus.SUCCESS) {
- const maxResult = Number(_max.result); // Get the maximum value
- const v = Number.isNaN(maxResult) ? 0 : maxResult;
- max = Math.max(v, min);
- min = Math.min(v, min);
- } else {
- return computeResult;
- }
-
- const isGradient = ruleConfig.config.isGradient;
- const isShowValue = ruleConfig.isShowValue;
-
- const getSafeValue = (v: number) => Math.max(Math.min(100, v), 0);
-
- if (min === max || max < min) {
- // do nothing,don't know how it work.
- } else if (min < 0 && max <= 0) {
- const length = max - min;
- const startPoint = 100;
- matrix.forValue((row, col, value) => {
- if (value > max) {
- return;
- }
- const v = getSafeValue((max - value) / length * 100);
- computeResult.setValue(row, col, { color: ruleConfig.config.nativeColor || defaultDataBarNativeColor, startPoint, value: -v, isGradient, isShowValue });
- });
- } else if (min < 0 && max > 0) {
- const length = Math.abs(max) + Math.abs(min);
- const startPoint = Math.abs(min) / length * 100;
- matrix.forValue((row, col, value) => {
- if (!value) {
- return;
- }
- if (value > 0) {
- const v = getSafeValue(Math.min(value / max, 1) * 100);
- computeResult.setValue(row, col, { color: ruleConfig.config.positiveColor || defaultDataBarPositiveColor, startPoint, value: v, isGradient, isShowValue });
- } else {
- const v = getSafeValue(Math.min(Math.abs(value) / Math.abs(min), 1) * 100);
- computeResult.setValue(row, col, { color: ruleConfig.config.nativeColor || defaultDataBarNativeColor, startPoint, value: -v, isGradient, isShowValue });
- }
- });
- } else if (min >= 0 && max > 0) {
- const length = max - min;
- const startPoint = 0;
- matrix.forValue((row, col, value) => {
- if (value < min) {
- return;
- }
- const v = getSafeValue((1 - (max - value) / length) * 100);
- computeResult.setValue(row, col, { color: ruleConfig.config.positiveColor || defaultDataBarPositiveColor, startPoint, value: v, isGradient, isShowValue });
- });
- }
- return computeResult;
- },
-
-};
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts
deleted file mode 100644
index ced9d49176..0000000000
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/icon-set.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * 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 { CFNumberOperator } from '../../base/const';
-import type { IConditionFormattingRule, IIconSet } from '../../models/type';
-import type { IIconSetRenderParams } from '../../render/type';
-
-import type { ICalculateUnit } from './type';
-import { CellValueType, ObjectMatrix, Range } from '@univerjs/core';
-import { CFRuleType } from '../../base/const';
-import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';
-import { EMPTY_STYLE } from './type';
-import { compareWithNumber, filterRange, getOppositeOperator, getValueByType, isNullable } from './utils';
-
-export const iconSetCalculateUnit: ICalculateUnit = {
- type: CFRuleType.iconSet,
- handle: async (rule: IConditionFormattingRule, context) => {
- const ruleConfig = rule.rule as IIconSet;
- const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
-
- const { worksheet } = context;
- const matrix = new ObjectMatrix<number>();
- const ranges = filterRange(rule.ranges, worksheet.getMaxRows() - 1, worksheet.getMaxColumns() - 1);
-
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- const cell = worksheet?.getCellRaw(row, col);
- const v = cell && cell.v;
- if (!isNullable(v) && cell?.t === CellValueType.NUMBER) {
- const _value = Number(v);
- !Number.isNaN(_value) && matrix.setValue(row, col, _value);
- }
- });
- });
-
- const computeResult = new ObjectMatrix<IIconSetRenderParams>();
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- computeResult.setValue(row, col, EMPTY_STYLE as IIconSetRenderParams);
- });
- });
-
- const splitValueResult = ruleConfig.config.map((v) => getValueByType(v.value, matrix, { ...context, cfId: rule.cfId }));
-
- const isFormulaWithoutSuccess = splitValueResult.some((item) => item.status !== FormulaResultStatus.SUCCESS);
- if (isFormulaWithoutSuccess) {
- return conditionalFormattingFormulaService.getCache(context.unitId, context.subUnitId, rule.cfId) ?? computeResult;
- }
-
- const splitValue = splitValueResult.map((item, index) => ({
- operator: ruleConfig.config[index].operator,
- value: Number(item.result) || 0,
- })).reduce((result, cur, index, list) => {
- const item = ruleConfig.config[index];
- if (!index || index === list.length - 1) {
- result.push({ ...cur, iconId: item.iconId, iconType: item.iconType });
- } else {
- const pre = list[index - 1];
- if (!compareWithNumber(pre, cur.value)) {
- result.push({ ...cur, iconId: item.iconId, iconType: item.iconType });
- }
- }
- return result;
- }, [] as { operator: CFNumberOperator; value: number; iconType: string; iconId: string }[]);
-
- const isShowValue = ruleConfig.isShowValue === undefined ? true : !!ruleConfig.isShowValue;
- matrix.forValue((row, col, value) => {
- for (let index = 0; index < splitValue.length; index++) {
- const item = splitValue[index];
- const start = { ...item };
- const end = { ...item };
- const { iconId, iconType } = item;
- if (index === 0) {
- if (compareWithNumber(item, value)) {
- computeResult.setValue(row, col, { iconId, iconType, isShowValue });
- return;
- }
- } else if (index === splitValue.length - 1) {
- computeResult.setValue(row, col, { iconId, iconType, isShowValue });
- return;
- } else {
- const pre = splitValue[index - 1];
- end.operator = getOppositeOperator(pre.operator);
- end.value = pre.value;
- if (compareWithNumber(start, value) && compareWithNumber(end, value)) {
- computeResult.setValue(row, col, { iconId, iconType, isShowValue });
- return;
- }
- }
- }
- });
-
- return computeResult;
- },
-
-};
diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/type.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/type.ts
deleted file mode 100644
index eeff816d4e..0000000000
--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/type.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * 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 { IAccessor, ObjectMatrix, Workbook, Worksheet } from '@univerjs/core';
-import type { CFRuleType } from '../../base/const';
-import type { IConditionFormattingRule } from '../../models/type';
-
-export interface IContext {
- accessor: IAccessor;
- unitId: string;
- subUnitId: string;
- workbook: Workbook;
- worksheet: Worksheet;
-};
-export interface ICalculateUnit<R = any> {
- type: CFRuleType;
- handle: (rule: IConditionFormattingRule, context: IContext) => Promise<ObjectMatrix<R>>;
-}
-
-export const EMPTY_STYLE = {} as unknown;
-Object.freeze(EMPTY_STYLE);
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.ts
index add712f7b6..255dc7ea1d 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
@@ -19,24 +19,26 @@ import type { IRemoveOtherFormulaMutationParams, ISetFormulaCalculationResultMut
import type { IConditionalFormattingFormulaMarkDirtyParams } from '../commands/mutations/formula-mark-dirty.mutation';
import type { IConditionalFormattingRuleConfig } from '../models/type';
-import { BooleanNumber, CellValueType, Disposable, ICommandService, Inject, Injector, ObjectMatrix, RefAlias, toDisposable, Tools } from '@univerjs/core';
-import {
- IActiveDirtyManagerService,
+import { BooleanNumber, CellValueType, Disposable, ICommandService, Inject, ObjectMatrix, RefAlias, Tools } from '@univerjs/core';
+import { IActiveDirtyManagerService,
RemoveOtherFormulaMutation,
SetFormulaCalculationResultMutation,
SetOtherFormulaMutation,
} from '@univerjs/engine-formula';
-import { CFRuleType, CFSubRuleType, CFValueType } from '../base/const';
+import { Subject } from 'rxjs';
+
+import { CFRuleType, CFValueType } from '../base/const';
+
import { ConditionalFormattingFormulaMarkDirty } from '../commands/mutations/formula-mark-dirty.mutation';
import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';
-import { ConditionalFormattingViewModel } from '../models/conditional-formatting-view-model';
-import { ConditionalFormattingService } from './conditional-formatting.service';
// eslint-disable-next-line ts/consistent-type-definitions
type IFormulaItem = {
formulaText: string;
cfId: string;
id: string;
+ unitId: string;
+ subUnitId: string;
ranges: IRange[];
status: FormulaResultStatus;
formulaId: string;
@@ -62,42 +64,18 @@ export class ConditionalFormattingFormulaService extends Disposable {
// Cache Formula ID and formula mapping.
private _formulaMap: Map<string, Map<string, RefAlias<IFormulaItem, 'id' | 'formulaId'>>> = new Map();
- // Cache style results, style replacement needs to wait until the formula has been calculated, then replace.
- private _cache: Map<string, Map<string, Map<string, ObjectMatrix<unknown>>>> = new Map();
+ private _result$ = new Subject<IFormulaItem & { isAllFinished: boolean }>();
+ public result$ = this._result$.asObservable();
constructor(
@Inject(ICommandService) private _commandService: ICommandService,
- @Inject(Injector) private _injector: Injector,
@Inject(IActiveDirtyManagerService) private _activeDirtyManagerService: IActiveDirtyManagerService,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel
) {
super();
this._initFormulaCalculationResultChange();
this._initRuleChange();
- this._initCache();
- this.disposeWithMe(toDisposable(() => {
- this._cache.clear();
- this._formulaMap.clear();
- }));
- }
-
- private _initCache() {
- const _conditionalFormattingService = this._injector.get(ConditionalFormattingService);
- this.disposeWithMe(_conditionalFormattingService.ruleComputeStatus$.subscribe((option) => {
- const { unitId, subUnitId, status, result, cfId } = option;
- if (status === 'end' && result) {
- const cacheMap = this._ensureCacheMap(unitId, subUnitId);
- cacheMap.set(cfId, result);
- }
- }));
- this.disposeWithMe(this._conditionalFormattingRuleModel.$ruleChange.subscribe((option) => {
- if (option.type === 'delete') {
- const { unitId, subUnitId, rule } = option;
- this._deleteCache(unitId, subUnitId, rule.cfId);
- }
- }));
}
private _initRuleChange() {
@@ -106,13 +84,9 @@ export class ConditionalFormattingFormulaService extends Disposable {
case CFRuleType.colorScale: {
return rule.config.some((item) => item.value.type === CFValueType.formula);
}
- case CFRuleType.highlightCell: {
- return rule.subType === CFSubRuleType.formula;
- }
case CFRuleType.dataBar: {
return [rule.config.max, rule.config.min].some((item) => item.type === CFValueType.formula);
}
-
case CFRuleType.iconSet: {
return rule.config.some((item) => item.value.type === CFValueType.formula);
}
@@ -138,7 +112,6 @@ export class ConditionalFormattingFormulaService extends Disposable {
const params = commandInfo.params as ISetFormulaCalculationResultMutation;
for (const unitId in params.unitOtherData) {
for (const subUnitId in params.unitOtherData[unitId]) {
- const cfIdsSet = new Set<string>();
for (const formulaId in params.unitOtherData[unitId]![subUnitId]) {
const resultMatrix = new ObjectMatrix(params.unitOtherData[unitId][subUnitId][formulaId]);
const formulaMapAlias = this._ensureSubunitFormulaMap(unitId, subUnitId).getValue(formulaId, ['formulaId']);
@@ -161,11 +134,9 @@ export class ConditionalFormattingFormulaService extends Disposable {
});
formulaMapAlias.status = FormulaResultStatus.SUCCESS;
- cfIdsSet.add(formulaMapAlias.cfId);
- }
- for (const cfId of cfIdsSet) {
- const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId);
- rule && this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
+ const allFormulaMapAlias = this._getAllFormulaResultByCfId(unitId, subUnitId, formulaMapAlias.cfId);
+ const isAllFinished = allFormulaMapAlias.every((item) => item.status === FormulaResultStatus.SUCCESS);
+ this._result$.next({ ...formulaMapAlias, isAllFinished });
}
}
}
@@ -199,53 +170,23 @@ export class ConditionalFormattingFormulaService extends Disposable {
return subUnitMap;
}
- private _ensureCacheMap(unitId: string, subUnitId: string) {
- let unitMap = this._cache.get(unitId);
- if (!unitMap) {
- unitMap = new Map<string, Map<string, ObjectMatrix<any>>>();
- this._cache.set(unitId, unitMap);
- }
- let subUnitMap = unitMap.get(subUnitId);
- if (!subUnitMap) {
- subUnitMap = new Map();
- unitMap.set(subUnitId, subUnitMap);
- }
- return subUnitMap;
- }
-
- private _deleteCache(unitId: string, subUnitId: string, cfId?: string) {
- const unitCache = this._cache.get(unitId);
- if (unitCache) {
- const subUnitCache = unitCache.get(subUnitId);
- if (subUnitCache) {
- if (cfId) {
- subUnitCache.delete(cfId);
- } else {
- subUnitCache.clear();
- }
- }
- }
- }
-
- public getCache(unitId: string, subUnitId: string, cfId: string) {
- const map = this._ensureCacheMap(unitId, subUnitId);
- return map.get(cfId);
- }
-
public getSubUnitFormulaMap(unitId: string, subUnitId: string) {
return this._formulaMap.get(unitId)?.get(subUnitId);
}
public registerFormulaWithRange(unitId: string, subUnitId: string, cfId: string, formulaText: string, ranges: IRange[] = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }]) {
const formulaMap = this._ensureSubunitFormulaMap(unitId, subUnitId);
- if (formulaMap.getValue(this.createCFormulaId(cfId, formulaText), ['id'])) {
+ const cfFormulaId = this.createCFormulaId(cfId, formulaText);
+ if (formulaMap.getValue(cfFormulaId, ['id'])) {
return;
}
const formulaId = this._createFormulaId(unitId, subUnitId);
formulaMap.addValue({
formulaText,
+ unitId,
+ subUnitId,
cfId,
- id: this.createCFormulaId(cfId, formulaText),
+ id: cfFormulaId,
ranges,
formulaId,
status: FormulaResultStatus.WAIT,
@@ -269,17 +210,12 @@ export class ConditionalFormattingFormulaService extends Disposable {
}
private _removeFormulaByCfId(unitId: string, subUnitId: string, cfId: string) {
- const subUnitFormulaMap = this._ensureSubunitFormulaMap(unitId, subUnitId);
- subUnitFormulaMap.deleteValue(cfId);
- const values = subUnitFormulaMap.getValues().filter((item) => item.cfId === cfId);
- values.forEach((v) => {
- subUnitFormulaMap.deleteValue(v.id, ['id']);
- });
+ const values = this.deleteCache(unitId, subUnitId, cfId);
const formulaIdList = values.map((item) => item.formulaId);
this._commandService.executeCommand(RemoveOtherFormulaMutation.id, { unitId, subUnitId, formulaIdList } as IRemoveOtherFormulaMutationParams);
}
- public getFormulaResult(unitId: string, subUnitId: string, cfId: string, formulaText: string, row: number = 0, col: number = 0) {
+ public getFormulaResultWithCoords(unitId: string, subUnitId: string, cfId: string, formulaText: string, row: number = 0, col: number = 0) {
const map = this.getSubUnitFormulaMap(unitId, subUnitId);
if (!map) {
return { status: FormulaResultStatus.NOT_REGISTER };
@@ -300,10 +236,61 @@ export class ConditionalFormattingFormulaService extends Disposable {
return { status: FormulaResultStatus.ERROR };
}
+ public getFormulaMatrix(unitId: string, subUnitId: string, cfId: string, formulaText: string) {
+ const map = this.getSubUnitFormulaMap(unitId, subUnitId);
+ if (!map) {
+ return { status: FormulaResultStatus.NOT_REGISTER };
+ }
+ const item = map.getValue(this.createCFormulaId(cfId, formulaText), ['id']);
+ if (!item) {
+ return { status: FormulaResultStatus.NOT_REGISTER };
+ }
+ if (FormulaResultStatus.SUCCESS === item.status && item.result) {
+ const result = item.result;
+ return { result, status: FormulaResultStatus.SUCCESS };
+ }
+ }
+
+ /**
+ * If `formulaText` is not provided, then all caches related to `cfId` will be deleted.
+ */
+ public deleteCache(unitId: string, subUnitId: string, cfId: string, formulaText?: string) {
+ const map = this.getSubUnitFormulaMap(unitId, subUnitId);
+ if (!map) {
+ return [];
+ }
+ if (formulaText) {
+ const key = this.createCFormulaId(cfId, formulaText);
+ map.deleteValue(key, ['id']);
+ return [];
+ } else {
+ const values = map.getValues().filter((v) => v.cfId === cfId);
+ values.forEach((e) => {
+ map.deleteValue(e.formulaId, ['formulaId']);
+ });
+ return values;
+ }
+ }
+
+ private _getAllFormulaResultByCfId(unitId: string, subUnitId: string, cfId: string) {
+ const map = this.getSubUnitFormulaMap(unitId, subUnitId);
+ if (!map) {
+ return [];
+ }
+ const values = map.getValues().filter((v) => v.cfId === cfId);
+ return values;
+ }
+
+ /**
+ * The external environment is not aware of`formulaId`;it communicates internally with the formula engine.
+ */
private _createFormulaId(unitId: string, subUnitId: string) {
return `sheet.cf_${unitId}_${subUnitId}_${Tools.generateRandomId(8)}`;
}
+ /**
+ * A conditional formatting may have multiple formulas;if the formulas are identical,then the results will be consistent.
+ */
public createCFormulaId(cfId: string, formulaText: string) {
return `${cfId}_${formulaText}`;
}
diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
index 8208aac073..6bc875d65d 100644
--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
@@ -19,44 +19,21 @@ import type { IInsertColMutationParams, IMoveColumnsMutationParams, IMoveRangeMu
import type { IDeleteConditionalRuleMutationParams } from '../commands/mutations/delete-conditional-rule.mutation';
import type { IConditionFormattingRule, IHighlightCell, IRuleModelJson } from '../models/type';
import type { IDataBarCellData, IDataBarRenderParams, IIconSetCellData, IIconSetRenderParams } from '../render/type';
-import type { ICalculateUnit, IContext } from './calculate-unit/type';
-import { createInterceptorKey, Disposable, ICommandService, Inject, Injector, InterceptorManager, IResourceManagerService, IUniverInstanceService, ObjectMatrix, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
+import { Disposable, ICommandService, Inject, Injector, IResourceManagerService, IUniverInstanceService, ObjectMatrix, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
import { InsertColMutation, InsertRowMutation, MoveColsMutation, MoveRangeMutation, MoveRowsMutation, RemoveColMutation, RemoveRowMutation, RemoveSheetCommand, ReorderRangeMutation, SetRangeValuesMutation, SheetInterceptorService } from '@univerjs/sheets';
-import { Subject } from 'rxjs';
-import { bufferTime, filter, map } from 'rxjs/operators';
import { CFRuleType, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '../base/const';
import { DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory } from '../commands/mutations/delete-conditional-rule.mutation';
import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';
-import { ConditionalFormattingViewModel } from '../models/conditional-formatting-view-model';
-import { colorScaleCellCalculateUnit } from './calculate-unit/color-scale';
-import { dataBarCellCalculateUnit } from './calculate-unit/data-bar';
-import { highlightCellCalculateUnit } from './calculate-unit/highlight-cell';
-import { iconSetCalculateUnit } from './calculate-unit/icon-set';
-import { EMPTY_STYLE } from './calculate-unit/type';
-
-type ComputeStatus = 'computing' | 'end' | 'error';
-
-interface IComputeCache { status: ComputeStatus };
-
-const beforeUpdateRuleResult = createInterceptorKey<{ subUnitId: string; unitId: string; cfId: string }, undefined>('conditional-formatting-before-update-rule-result');
+import { ConditionalFormattingViewModelV2 } from '../models/conditional-formatting-view-model-v2';
export class ConditionalFormattingService extends Disposable {
- // <unitId,<subUnitId,<cfId,IComputeCache>>>
- private _ruleCacheMap: Map<string, Map<string, Map<string, IComputeCache>>> = new Map();
-
- private _calculateUnit$ = new Subject<{ unitId: string; subUnitId: string; rule: IConditionFormattingRule }>();
-
- private _ruleComputeStatus$: Subject<{ status: ComputeStatus; result?: ObjectMatrix<any>; unitId: string; subUnitId: string; cfId: string }> = new Subject();
- public ruleComputeStatus$ = this._ruleComputeStatus$.asObservable();
-
- public interceptorManager = new InterceptorManager({ beforeUpdateRuleResult });
-
- private _calculationUnitMap: Map<IConditionFormattingRule['rule']['type'], ICalculateUnit> = new Map();
+ get _conditionalFormattingViewModelV2() {
+ return this._injector.get(ConditionalFormattingViewModelV2);
+ }
constructor(
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
@Inject(Injector) private _injector: Injector,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(IResourceManagerService) private _resourceManagerService: IResourceManagerService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@@ -64,71 +41,41 @@ export class ConditionalFormattingService extends Disposable {
) {
super();
this._initCellChange();
- this._initCacheManager();
- this._initRemoteCalculate();
this._initSnapshot();
this._initSheetChange();
- this._registerCalculationUnit(dataBarCellCalculateUnit);
- this._registerCalculationUnit(colorScaleCellCalculateUnit);
- this._registerCalculationUnit(highlightCellCalculateUnit);
- this._registerCalculationUnit(iconSetCalculateUnit);
- this._calculateUnit$.pipe(bufferTime(100), filter((list) => !!list.length), map((list) => {
- const createKey = (config: typeof list[0]) => `${config.unitId}_${config.subUnitId}_${config.rule.cfId}`;
- const result = list.reduce((a, b) => {
- const key = createKey(b);
- if (!a.map[key]) {
- a.map[key] = b;
- a.list.push(b);
- }
- return a;
- }, {
- map: {} as Record<string, typeof list[0]>,
- list: [] as typeof list,
- });
- return result.list;
- })).subscribe((configList) => {
- configList.forEach((config) => {
- this._handleCalculateUnit(config.unitId, config.subUnitId, config.rule);
- });
- });
-
- this.disposeWithMe(() => {
- this.interceptorManager.dispose();
- });
}
public composeStyle(unitId: string, subUnitId: string, row: number, col: number) {
- const cell = this._conditionalFormattingViewModel.getCellCf(unitId, subUnitId, row, col);
- if (cell) {
+ const cellCfs = this._conditionalFormattingViewModelV2.getCellCfs(unitId, subUnitId, row, col);
+
+ if (cellCfs && cellCfs?.length) {
// High priority should be applied at the back, overwriting the previous results.
// reverse is a side-effect function that changes the original array.
- const ruleList = cell.cfList.map((item) => this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, item.cfId)!).filter((rule) => !!rule).reverse();
+ const ruleList = cellCfs.map((item) => this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, item.cfId)!).filter((rule) => !!rule).reverse();
const endIndex = ruleList.findIndex((rule) => rule?.stopIfTrue);
if (endIndex > -1) {
ruleList.splice(endIndex + 1);
}
const result = ruleList.reduce((pre, rule) => {
const type = rule.rule.type;
- const ruleCacheItem = cell.cfList.find((cache) => cache.cfId === rule.cfId);
- if (ruleCacheItem?.isDirty) {
- this._calculateUnit$.next({ unitId, subUnitId, rule });
- }
+ const ruleCacheItem = cellCfs.find((cache) => cache.cfId === rule.cfId);
+
if (type === CFRuleType.highlightCell) {
- ruleCacheItem!.ruleCache && Tools.deepMerge(pre, { style: ruleCacheItem!.ruleCache });
+ ruleCacheItem!.result && Tools.deepMerge(pre, { style: ruleCacheItem!.result });
} else if (type === CFRuleType.colorScale) {
- const ruleCache = ruleCacheItem?.ruleCache;
+ const ruleCache = ruleCacheItem?.result;
if (ruleCache && typeof ruleCache === 'string') {
pre.style = { ...(pre.style ?? {}), bg: { rgb: ruleCache } };
}
} else if (type === CFRuleType.dataBar) {
- const ruleCache = ruleCacheItem?.ruleCache as IDataBarRenderParams;
- if (ruleCache && ruleCache !== EMPTY_STYLE) {
+ const ruleCache = ruleCacheItem?.result as IDataBarRenderParams;
+ if (ruleCache) {
pre.dataBar = ruleCache;
pre.isShowValue = ruleCache.isShowValue;
}
} else if (type === CFRuleType.iconSet) {
- const ruleCache = ruleCacheItem?.ruleCache as IIconSetRenderParams;
- if (ruleCache && ruleCache !== EMPTY_STYLE) {
+ const ruleCache = ruleCacheItem?.result as IIconSetRenderParams;
+ if (ruleCache) {
pre.iconSet = ruleCache;
pre.isShowValue = ruleCache.isShowValue;
}
@@ -226,59 +173,16 @@ export class ConditionalFormattingService extends Disposable {
);
}
- private _registerCalculationUnit(unit: ICalculateUnit) {
- this._calculationUnitMap.set(unit.type, unit);
- }
-
- private _getComputedCache(unitId: string, subUnitId: string, cfId: string) {
- return this._ruleCacheMap.get(unitId)?.get(subUnitId)?.get(cfId);
- }
-
- private _setComputedCache(unitId: string, subUnitId: string, cfId: string, value: IComputeCache) {
- let unitMap = this._ruleCacheMap.get(unitId);
- if (!unitMap) {
- unitMap = new Map();
- this._ruleCacheMap.set(unitId, unitMap);
- }
- let subUnitMap = unitMap.get(subUnitId);
- if (!subUnitMap) {
- subUnitMap = new Map();
- unitMap.set(subUnitId, subUnitMap);
- }
- subUnitMap.set(cfId, value);
- }
-
- private _deleteComputeCache(unitId: string, subUnitId: string, cfId: string) {
- const unitCache = this._ruleCacheMap.get(unitId);
- const subUnitCache = unitCache?.get(subUnitId);
- if (subUnitCache) {
- subUnitCache.delete(cfId);
- const size = subUnitCache.size;
- if (!size) {
- unitCache?.delete(subUnitId);
- }
- }
- }
-
- private _initCacheManager() {
- this.disposeWithMe(this._conditionalFormattingViewModel.markDirty$.subscribe((item) => {
- this._deleteComputeCache(item.unitId, item.subUnitId, item.rule.cfId);
- }));
-
- this.disposeWithMe(this._conditionalFormattingRuleModel.$ruleChange.pipe(filter((item) => item.type !== 'sort')).subscribe((item) => {
- const { unitId, subUnitId, rule } = item;
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
- }));
- }
-
+ // eslint-disable-next-line max-lines-per-function
private _initCellChange() {
this.disposeWithMe(
+ // eslint-disable-next-line max-lines-per-function
this._commandService.onCommandExecuted((commandInfo) => {
const collectRule = (unitId: string, subUnitId: string, cellData: [number, number][]) => {
const ruleIds: Set<string> = new Set();
cellData.forEach(([row, col]) => {
- const ruleItem = this._conditionalFormattingViewModel.getCellCf(unitId, subUnitId, row, col);
- ruleItem?.cfList.forEach((item) => ruleIds.add(item.cfId));
+ const ruleItem = this._conditionalFormattingViewModelV2.getCellCfs(unitId, subUnitId, row, col);
+ ruleItem?.forEach((item) => ruleIds.add(item.cfId));
});
return [...ruleIds].map((cfId) => this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId) as IConditionFormattingRule).filter((rule) => !!rule);
};
@@ -297,8 +201,7 @@ export class ConditionalFormattingService extends Disposable {
});
const rules = collectRule(unitId, subUnitId, cellMatrix);
rules.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
break;
}
@@ -310,8 +213,7 @@ export class ConditionalFormattingService extends Disposable {
if (allRules) {
const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
effectRule.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
}
break;
@@ -324,8 +226,7 @@ export class ConditionalFormattingService extends Disposable {
if (allRules) {
const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
effectRule.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
}
break;
@@ -342,8 +243,7 @@ export class ConditionalFormattingService extends Disposable {
if (allRules) {
const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
effectRule.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
}
break;
@@ -360,8 +260,7 @@ export class ConditionalFormattingService extends Disposable {
if (allRules) {
const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
effectRule.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
}
break;
@@ -375,8 +274,7 @@ export class ConditionalFormattingService extends Disposable {
});
const rules = collectRule(unitId, value.subUnitId, cellMatrix);
rules.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, value.subUnitId, rule);
- this._deleteComputeCache(unitId, value.subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, value.subUnitId, rule.cfId);
});
};
handleSubUnit(to);
@@ -389,8 +287,7 @@ export class ConditionalFormattingService extends Disposable {
if (allRules) {
const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, range)));
effectRule.forEach((rule) => {
- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);
- this._deleteComputeCache(unitId, subUnitId, rule.cfId);
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
}
break;
@@ -398,46 +295,6 @@ export class ConditionalFormattingService extends Disposable {
}
}));
}
-
- private _initRemoteCalculate() {
- this.disposeWithMe(this._ruleComputeStatus$.subscribe(({ status, subUnitId, unitId, cfId, result }) => {
- const cache = this._getComputedCache(unitId, subUnitId, cfId) || {} as IComputeCache;
- cache.status = status;
- this._setComputedCache(unitId, subUnitId, cfId, cache);
- if (status === 'end' && result) {
- this.interceptorManager.fetchThroughInterceptors(this.interceptorManager.getInterceptPoints().beforeUpdateRuleResult)({
- subUnitId, unitId, cfId,
- }, undefined);
- result.forValue((row, col, value) => {
- this._conditionalFormattingViewModel.setCellCfRuleCache(unitId, subUnitId, row, col, cfId, value);
- });
- }
- }));
- }
-
- private async _handleCalculateUnit(unitId: string, subUnitId: string, rule: IConditionFormattingRule) {
- // We need to perform a secondary verification, as the rule may have been deleted after initApply.
- if (!this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, rule.cfId)) {
- return;
- }
- const workbook = this._univerInstanceService.getUnit<Workbook>(unitId);
- const worksheet = workbook?.getSheetBySheetId(subUnitId);
- let cache = this._getComputedCache(unitId, subUnitId, rule.cfId);
- if (cache && ['computing', 'end'].includes(cache.status)) {
- return;
- }
- if (!cache) {
- cache = { status: 'computing' };
- this._setComputedCache(unitId, subUnitId, rule.cfId, cache);
- }
- const unit = this._calculationUnitMap.get(rule.rule.type);
- if (!unit || !worksheet) {
- return;
- }
- const context: IContext = { unitId, subUnitId, accessor: this._injector, workbook: workbook!, worksheet };
- const result = await unit.handle(rule, context);
- this._ruleComputeStatus$.next({ status: 'end', unitId, subUnitId, cfId: rule.cfId, result });
- }
}
const getUnitId = (u: IUniverInstanceService) => u.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();