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(sheets-conditional-formatting): index rule ranges and batch range transforms (#7030)

白熱cf16c10e2d96
diff --git a/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts b/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts
index 330a2a9136..bd5d49c0ee 100644
--- a/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts
+++ b/packages/sheets-conditional-formatting-ui/src/__tests__/create-cf-ui-test-bed.ts
@@ -54,6 +54,8 @@ import {
ClearRangeCfCommand,
ClearWorksheetCfCommand,
ConditionalFormattingFormulaService,
+ ConditionalFormattingRangeIndexModel,
+ ConditionalFormattingRangeTransformService,
ConditionalFormattingRuleModel,
ConditionalFormattingViewModel,
DeleteConditionalRuleMutation,
@@ -204,7 +206,9 @@ export function createCfUiTestBed() {
} as unknown as IActiveDirtyManagerService,
}]);
injector.add([ConditionalFormattingRuleModel]);
+ injector.add([ConditionalFormattingRangeIndexModel]);
injector.add([ConditionalFormattingFormulaService]);
+ injector.add([ConditionalFormattingRangeTransformService]);
injector.add([ConditionalFormattingViewModel]);
injector.add([ComponentManager, { useValue: componentManager as unknown as ComponentManager }]);
injector.add([ISidebarService, { useValue: sidebarService as unknown as ISidebarService }]);
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 4a3fd37541..350670cf2b 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
@@ -17,18 +17,33 @@
import type { IMutationInfo, IRange, Workbook } from '@univerjs/core';
import type { IDiscreteRange, ISheetAutoFillHook } from '@univerjs/sheets';
import type { IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
-import { Disposable, Inject, Injector, IUniverInstanceService, ObjectMatrix, Range, Rectangle, UniverInstanceType } from '@univerjs/core';
-import { AUTO_FILL_APPLY_TYPE, AutoFillTools, createTopMatrixFromMatrix, findAllRectangle, IAutoFillService } from '@univerjs/sheets';
-import { ConditionalFormattingRuleModel, ConditionalFormattingViewModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
+import { Disposable, Inject, Injector, IUniverInstanceService, Range, Rectangle, UniverInstanceType } from '@univerjs/core';
+import { AUTO_FILL_APPLY_TYPE, AutoFillTools, IAutoFillService } from '@univerjs/sheets';
+import {
+ ConditionalFormattingRangeTransformService,
+ ConditionalFormattingRuleModel,
+ ConditionalFormattingViewModel,
+ DeleteConditionalRuleMutation,
+ DeleteConditionalRuleMutationUndoFactory,
+ SetConditionalRuleMutation,
+ setConditionalRuleMutationUndoFactory,
+ SHEET_CONDITIONAL_FORMATTING_PLUGIN,
+} from '@univerjs/sheets-conditional-formatting';
import { virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
+interface IRangeDelta {
+ add: IRange[];
+ remove: IRange[];
+}
+
export class ConditionalFormattingAutoFillController extends Disposable {
constructor(
@Inject(Injector) private _injector: Injector,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(IAutoFillService) private _autoFillService: IAutoFillService,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel
+ @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
+ @Inject(ConditionalFormattingRangeTransformService) private _conditionalFormattingRangeTransformService: ConditionalFormattingRangeTransformService
) {
super();
@@ -43,7 +58,8 @@ export class ConditionalFormattingAutoFillController extends Disposable {
sourceStartCell: { row: number; col: number },
targetStartCell: { row: number; col: number },
relativeRange: IRange,
- matrixMap: Map<string, ObjectMatrix<1>>,
+ rangeMap: Map<string, IRange[]>,
+ rangeDeltaMap: Map<string, IRangeDelta>,
mapFunc: (row: number, col: number) => ({ row: number; col: number })
) => {
const unitId = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();
@@ -52,6 +68,27 @@ export class ConditionalFormattingAutoFillController extends Disposable {
return;
}
+ const getRangeDelta = (cfId: string) => {
+ let rangeDelta = rangeDeltaMap.get(cfId);
+ if (!rangeDelta) {
+ rangeDelta = { add: [], remove: [] };
+ rangeDeltaMap.set(cfId, rangeDelta);
+ }
+ return rangeDelta;
+ };
+ const ensureRuleRanges = (cfId: string) => {
+ if (rangeMap.has(cfId)) {
+ return true;
+ }
+
+ const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId);
+ if (!rule) {
+ return false;
+ }
+
+ rangeMap.set(cfId, rule.ranges);
+ return true;
+ };
const sourceRange = {
startRow: sourceStartCell.row,
startColumn: sourceStartCell.col,
@@ -100,41 +137,29 @@ export class ConditionalFormattingAutoFillController extends Disposable {
);
if (targetCellCf) {
targetCellCf.forEach((cf) => {
- let matrix = matrixMap.get(cf.cfId);
- if (!matrixMap.get(cf.cfId)) {
- const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cf.cfId);
- if (!rule) {
- return;
- }
- matrix = new ObjectMatrix();
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- matrix!.setValue(row, col, 1);
- });
- });
- matrixMap.set(cf.cfId, matrix);
+ if (!ensureRuleRanges(cf.cfId)) {
+ return;
}
- matrix!.realDeleteValue(targetRow, targetCol);
+ getRangeDelta(cf.cfId).remove.push({
+ startRow: targetRow,
+ endRow: targetRow,
+ startColumn: targetCol,
+ endColumn: targetCol,
+ });
});
}
if (sourceCellCf) {
sourceCellCf.forEach((cf) => {
- let matrix = matrixMap.get(cf.cfId);
- if (!matrixMap.get(cf.cfId)) {
- const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cf.cfId);
- if (!rule) {
- return;
- }
- matrix = new ObjectMatrix();
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- matrix!.setValue(row, col, 1);
- });
- });
- matrixMap.set(cf.cfId, matrix);
+ if (!ensureRuleRanges(cf.cfId)) {
+ return;
}
- matrix!.setValue(targetRow, targetCol, 1);
+ getRangeDelta(cf.cfId).add.push({
+ startRow: targetRow,
+ endRow: targetRow,
+ startColumn: targetCol,
+ endColumn: targetCol,
+ });
});
}
});
@@ -143,7 +168,8 @@ export class ConditionalFormattingAutoFillController extends Disposable {
const generalApplyFunc = (sourceRange: IDiscreteRange, targetRange: IDiscreteRange) => {
const unitId = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getUnitId();
const subUnitId = this._univerInstanceService.getCurrentUnitOfType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getActiveSheet()?.getSheetId();
- const matrixMap: Map<string, ObjectMatrix<1>> = new Map();
+ const rangeMap: Map<string, IRange[]> = new Map();
+ const rangeDeltaMap: Map<string, IRangeDelta> = new Map();
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
@@ -162,14 +188,25 @@ export class ConditionalFormattingAutoFillController extends Disposable {
const repeats = AutoFillTools.getAutoFillRepeatRange(vSourceRange, vTargetRange);
repeats.forEach((repeat) => {
- loopFunc(sourceStartCell, repeat.repeatStartCell, repeat.relativeRange, matrixMap, mapFunc);
+ loopFunc(sourceStartCell, repeat.repeatStartCell, repeat.relativeRange, rangeMap, rangeDeltaMap, mapFunc);
+ });
+ rangeDeltaMap.forEach((rangeDelta, cfId) => {
+ const ranges = rangeMap.get(cfId);
+ if (!ranges) {
+ return;
+ }
+
+ rangeMap.set(cfId, this._conditionalFormattingRangeTransformService.applyRangeDelta(
+ ranges,
+ rangeDelta.remove,
+ rangeDelta.add
+ ));
});
- matrixMap.forEach((item, cfId) => {
+ rangeMap.forEach((ranges, cfId) => {
const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId);
if (!rule) {
return;
}
- const ranges = findAllRectangle(createTopMatrixFromMatrix(item));
if (ranges.length) {
const params: ISetConditionalRuleMutationParams = {
unitId,
diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts
index e5d1e72f4f..244be9b8ce 100644
--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts
+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.clear.controller.ts
@@ -15,10 +15,22 @@
*/
import type { IMutationInfo, IRange, Workbook } from '@univerjs/core';
-import type { IConditionalFormattingRuleConfig, IConditionFormattingRule, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
-import { Disposable, Inject, Injector, IUniverInstanceService, Rectangle, UniverInstanceType } from '@univerjs/core';
-import { ClearSelectionAllCommand, ClearSelectionFormatCommand, RangeMergeUtil, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
-import { ConditionalFormattingRuleModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from '@univerjs/sheets-conditional-formatting';
+import type {
+ IConditionalFormattingRuleConfig,
+ IConditionFormattingRule,
+ IDeleteConditionalRuleMutationParams,
+ ISetConditionalRuleMutationParams,
+} from '@univerjs/sheets-conditional-formatting';
+import { Disposable, Inject, Injector, IUniverInstanceService, UniverInstanceType } from '@univerjs/core';
+import { ClearSelectionAllCommand, ClearSelectionFormatCommand, SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ ConditionalFormattingRangeIndexModel,
+ ConditionalFormattingRangeTransformService,
+ DeleteConditionalRuleMutation,
+ DeleteConditionalRuleMutationUndoFactory,
+ SetConditionalRuleMutation,
+ setConditionalRuleMutationUndoFactory,
+} from '@univerjs/sheets-conditional-formatting';
export class ConditionalFormattingClearController extends Disposable {
constructor(
@@ -26,7 +38,7 @@ export class ConditionalFormattingClearController extends Disposable {
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,
@Inject(SheetsSelectionsService) private _selectionManagerService: SheetsSelectionsService,
- @Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel
+ @Inject(ConditionalFormattingRangeIndexModel) private _conditionalFormattingRangeIndexModel: ConditionalFormattingRangeIndexModel
) {
super();
@@ -53,7 +65,7 @@ export class ConditionalFormattingClearController extends Disposable {
const unitId = workbook.getUnitId();
const subUnitId = worksheet.getSheetId();
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
+ const allRules = this._conditionalFormattingRangeIndexModel.getRulesByRanges(unitId, subUnitId, ranges);
if (!allRules || !allRules.length) {
return defaultV;
}
@@ -73,7 +85,7 @@ export class ConditionalFormattingClearController extends Disposable {
if (!ranges || !ranges.length) {
return emptyInterceptorArr;
}
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
+ const allRules = this._conditionalFormattingRangeIndexModel.getRulesByRanges(unitId, subUnitId, ranges);
if (!allRules || !allRules.length) {
return emptyInterceptorArr;
}
@@ -90,11 +102,9 @@ export class ConditionalFormattingClearController extends Disposable {
export function generateClearCfMutations(injector: Injector, allRules: IConditionFormattingRule<IConditionalFormattingRuleConfig>[], ranges: IRange[], unitId: string, subUnitId: string) {
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
- allRules.filter((rule) => {
- return ranges.some((range) => rule.ranges.some((ruleRange) => Rectangle.getIntersects(ruleRange, range)));
- }).forEach((rule) => {
- const mergeUtil = new RangeMergeUtil();
- const mergeRanges = mergeUtil.add(...rule.ranges).subtract(...ranges).merge();
+ const rangeTransformService = injector.get(ConditionalFormattingRangeTransformService);
+ allRules.forEach((rule) => {
+ const mergeRanges = rangeTransformService.subtractRanges(rule.ranges, ranges);
if (mergeRanges.length) {
const redo: IMutationInfo<ISetConditionalRuleMutationParams> = {
id: SetConditionalRuleMutation.id,
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 65dcbc33cb..f396be8cc9 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
@@ -15,7 +15,13 @@
*/
import type { IRange, Nullable } from '@univerjs/core';
-import type { IAddConditionalRuleMutationParams, IConditionalFormattingRuleConfig, IConditionFormattingRule, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
+import type {
+ IAddConditionalRuleMutationParams,
+ IConditionalFormattingRuleConfig,
+ IConditionFormattingRule,
+ IDeleteConditionalRuleMutationParams,
+ ISetConditionalRuleMutationParams,
+} from '@univerjs/sheets-conditional-formatting';
import type { ICopyPastePayload, IPasteHookValueType, ISheetDiscreteRangeLocation } from '@univerjs/sheets-ui';
import {
Disposable,
@@ -28,12 +34,21 @@ import {
Tools,
} from '@univerjs/core';
import {
- createTopMatrixFromMatrix,
- findAllRectangle,
getSheetCommandTarget,
rangeToDiscreteRange,
} from '@univerjs/sheets';
-import { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory, ConditionalFormattingRuleModel, ConditionalFormattingViewModel, DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory, SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';
+import {
+ AddConditionalRuleMutation,
+ AddConditionalRuleMutationUndoFactory,
+ ConditionalFormattingRangeTransformService,
+ ConditionalFormattingRuleModel,
+ ConditionalFormattingViewModel,
+ DeleteConditionalRuleMutation,
+ DeleteConditionalRuleMutationUndoFactory,
+ SetConditionalRuleMutation,
+ setConditionalRuleMutationUndoFactory,
+ SHEET_CONDITIONAL_FORMATTING_PLUGIN,
+} from '@univerjs/sheets-conditional-formatting';
import { COPY_TYPE, getRepeatRange, ISheetClipboardService, PREDEFINED_HOOK_NAME_PASTE, virtualizeDiscreteRanges } from '@univerjs/sheets-ui';
interface ICopyInfoType {
@@ -59,7 +74,8 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
@Inject(Injector) private _injector: Injector,
@Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
- @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService
+ @Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
+ @Inject(ConditionalFormattingRangeTransformService) private _conditionalFormattingRangeTransformService: ConditionalFormattingRangeTransformService
) {
super();
this._initClipboardHook();
@@ -138,10 +154,12 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
const { ranges: [vCopyRange, vPastedRange], mapFunc } = virtualizeDiscreteRanges([copyRange, pastedRange]);
const repeatRange = getRepeatRange(vCopyRange, vPastedRange, true);
- const effectedConditionalFormattingRuleMatrix: Record<string, {
+ const effectedConditionalFormattingRuleRanges: Record<string, {
unitId: string;
subUnitId: string;
- ruleMatrix: ObjectMatrix<1>;
+ ranges: IRange[];
+ add: IRange[];
+ remove: IRange[];
}> = {};
// 1. delete the conditional formatting rules in the pasted range.
@@ -150,21 +168,26 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
const cellCfList = this._conditionalFormattingViewModel.getCellCfs(pastedUnitId, pastedSubUnitId, realRow, realCol);
if (cellCfList) {
cellCfList.forEach((item) => {
- if (!effectedConditionalFormattingRuleMatrix[item.cfId]) {
- const ruleMatrix = new ObjectMatrix<1>();
- effectedConditionalFormattingRuleMatrix[item.cfId] = {
+ if (!effectedConditionalFormattingRuleRanges[item.cfId]) {
+ const rule = this._conditionalFormattingRuleModel.getRule(pastedUnitId, pastedSubUnitId, item.cfId);
+ if (!rule) {
+ return;
+ }
+ effectedConditionalFormattingRuleRanges[item.cfId] = {
unitId: pastedUnitId,
subUnitId: pastedSubUnitId,
- ruleMatrix,
+ ranges: rule.ranges,
+ add: [],
+ remove: [],
};
- const rule = this._conditionalFormattingRuleModel.getRule(pastedUnitId, pastedSubUnitId, item.cfId);
- rule?.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- ruleMatrix.setValue(row, col, 1);
- });
- });
}
- effectedConditionalFormattingRuleMatrix[item.cfId].ruleMatrix.realDeleteValue(realRow, realCol);
+ const current = effectedConditionalFormattingRuleRanges[item.cfId];
+ current.remove.push({
+ startRow: realRow,
+ endRow: realRow,
+ startColumn: realCol,
+ endColumn: realCol,
+ });
});
}
});
@@ -176,21 +199,26 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
const cellCfList = this._conditionalFormattingViewModel.getCellCfs(copyUnitId, copySubUnitId, realRow, realCol);
if (cellCfList) {
cellCfList.forEach((item) => {
- if (!effectedConditionalFormattingRuleMatrix[item.cfId]) {
- const ruleMatrix = new ObjectMatrix<1>();
- effectedConditionalFormattingRuleMatrix[item.cfId] = {
+ if (!effectedConditionalFormattingRuleRanges[item.cfId]) {
+ const rule = this._conditionalFormattingRuleModel.getRule(copyUnitId, copySubUnitId, item.cfId);
+ if (!rule) {
+ return;
+ }
+ effectedConditionalFormattingRuleRanges[item.cfId] = {
unitId: copyUnitId,
subUnitId: copySubUnitId,
- ruleMatrix,
+ ranges: rule.ranges,
+ add: [],
+ remove: [],
};
- const rule = this._conditionalFormattingRuleModel.getRule(copyUnitId, copySubUnitId, item.cfId);
- rule?.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- ruleMatrix.setValue(row, col, 1);
- });
- });
}
- effectedConditionalFormattingRuleMatrix[item.cfId].ruleMatrix.realDeleteValue(realRow, realCol);
+ const current = effectedConditionalFormattingRuleRanges[item.cfId];
+ current.remove.push({
+ startRow: realRow,
+ endRow: realRow,
+ startColumn: realCol,
+ endColumn: realCol,
+ });
});
}
});
@@ -240,20 +268,22 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
copyRangeCfIdList.forEach((cfId) => {
const rule = cacheCfIdMap[cfId] || getCurrentSheetCfRule(cfId);
- if (!effectedConditionalFormattingRuleMatrix[rule.cfId]) {
- const ruleMatrix = new ObjectMatrix<1>();
- effectedConditionalFormattingRuleMatrix[rule.cfId] = {
+ if (!effectedConditionalFormattingRuleRanges[rule.cfId]) {
+ effectedConditionalFormattingRuleRanges[rule.cfId] = {
unitId: pastedUnitId,
subUnitId: pastedSubUnitId,
- ruleMatrix,
+ ranges: rule.ranges,
+ add: [],
+ remove: [],
};
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- ruleMatrix.setValue(row, col, 1);
- });
- });
}
- effectedConditionalFormattingRuleMatrix[rule.cfId].ruleMatrix.setValue(_row, _col, 1);
+ const current = effectedConditionalFormattingRuleRanges[rule.cfId];
+ current.add.push({
+ startRow: _row,
+ endRow: _row,
+ startColumn: _col,
+ endColumn: _col,
+ });
});
});
});
@@ -261,9 +291,9 @@ export class ConditionalFormattingCopyPasteController extends Disposable {
const redos = [];
const undos = [];
- for (const cfId in effectedConditionalFormattingRuleMatrix) {
- const { unitId, subUnitId, ruleMatrix } = effectedConditionalFormattingRuleMatrix[cfId];
- const ranges = findAllRectangle(createTopMatrixFromMatrix(ruleMatrix));
+ for (const cfId in effectedConditionalFormattingRuleRanges) {
+ const { unitId, subUnitId, ranges: sourceRanges, add, remove } = effectedConditionalFormattingRuleRanges[cfId];
+ const ranges = this._conditionalFormattingRangeTransformService.applyRangeDelta(sourceRanges, remove, add);
if (!ranges.length) {
const deleteParams: IDeleteConditionalRuleMutationParams = {
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 2d1d3c4b48..3525754d66 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
@@ -15,13 +15,33 @@
*/
import type { IMutationInfo, IRange, Nullable, Workbook } from '@univerjs/core';
-import type { IAddConditionalRuleMutationParams, IDeleteConditionalRuleMutationParams, ISetConditionalRuleMutationParams } from '@univerjs/sheets-conditional-formatting';
+import type {
+ IAddConditionalRuleMutationParams,
+ IDeleteConditionalRuleMutationParams,
+ ISetConditionalRuleMutationParams,
+} from '@univerjs/sheets-conditional-formatting';
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 { Disposable, Inject, Injector, IUniverInstanceService, Range, Rectangle, Tools, UniverInstanceType } from '@univerjs/core';
+import { SheetsSelectionsService } from '@univerjs/sheets';
+import {
+ AddConditionalRuleMutation,
+ AddConditionalRuleMutationUndoFactory,
+ ConditionalFormattingRangeTransformService,
+ ConditionalFormattingRuleModel,
+ ConditionalFormattingViewModel,
+ DeleteConditionalRuleMutation,
+ DeleteConditionalRuleMutationUndoFactory,
+ SetConditionalRuleMutation,
+ setConditionalRuleMutationUndoFactory,
+ SHEET_CONDITIONAL_FORMATTING_PLUGIN,
+} from '@univerjs/sheets-conditional-formatting';
import { FormatPainterStatus, IFormatPainterService } from '@univerjs/sheets-ui';
+interface IRangeDelta {
+ add: IRange[];
+ remove: IRange[];
+}
+
const repeatByRange = (sourceRange: IRange, targetRange: IRange) => {
const getRowLength = (range: IRange) => range.endRow - range.startRow + 1;
const getColLength = (range: IRange) => range.endColumn - range.startColumn + 1;
@@ -81,8 +101,8 @@ export class ConditionalFormattingPainterController extends Disposable {
@Inject(IFormatPainterService) private _formatPainterService: IFormatPainterService,
@Inject(SheetsSelectionsService) private _sheetsSelectionsService: SheetsSelectionsService,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
-
- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel
+ @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,
+ @Inject(ConditionalFormattingRangeTransformService) private _conditionalFormattingRangeTransformService: ConditionalFormattingRangeTransformService
) {
super();
@@ -98,7 +118,8 @@ export class ConditionalFormattingPainterController extends Disposable {
sourceStartCell: { row: number; col: number },
targetStartCell: { row: number; col: number },
relativeRange: IRange,
- matrixMap: Map<string, ObjectMatrix<1>>,
+ rangeMap: Map<string, IRange[]>,
+ rangeDeltaMap: Map<string, IRangeDelta>,
config: {
targetUnitId: string;
targetSubUnitId: string;
@@ -107,6 +128,14 @@ export class ConditionalFormattingPainterController extends Disposable {
const { unitId: sourceUnitId, subUnitId: sourceSubUnitId } = this._painterConfig!;
const { targetUnitId, targetSubUnitId } = config;
+ const getRangeDelta = (cfId: string) => {
+ let rangeDelta = rangeDeltaMap.get(cfId);
+ if (!rangeDelta) {
+ rangeDelta = { add: [], remove: [] };
+ rangeDeltaMap.set(cfId, rangeDelta);
+ }
+ return rangeDelta;
+ };
const sourceRange = {
startRow: sourceStartCell.row,
startColumn: sourceStartCell.col,
@@ -156,28 +185,33 @@ export class ConditionalFormattingPainterController extends Disposable {
if (targetCellCf) {
targetCellCf.forEach((cf) => {
- let matrix = matrixMap.get(cf.cfId);
- if (!matrixMap.get(cf.cfId)) {
+ if (!rangeMap.has(cf.cfId)) {
const rule = this._conditionalFormattingRuleModel.getRule(targetUnitId, targetSubUnitId, cf.cfId);
if (!rule) {
return;
}
- matrix = new ObjectMatrix();
- rule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- matrix!.setValue(row, col, 1);
- });
- });
- matrixMap.set(cf.cfId, matrix);
+ rangeMap.set(cf.cfId, rule.ranges);
}
- matrix!.realDeleteValue(targetPositionRange.startRow, targetPositionRange.startColumn);
+ getRangeDelta(cf.cfId).remove.push({
+ startRow: targetPositionRange.startRow,
+ endRow: targetPositionRange.startRow,
+ startColumn: targetPositionRange.startColumn,
+ endColumn: targetPositionRange.startColumn,
+ });
});
}
if (sourceCellCf) {
sourceCellCf.forEach((cf) => {
- const matrix = matrixMap.get(cf.cfId);
- matrix && matrix.setValue(targetPositionRange.startRow, targetPositionRange.startColumn, 1);
+ if (!rangeMap.has(cf.cfId)) {
+ return;
+ }
+ getRangeDelta(cf.cfId).add.push({
+ startRow: targetPositionRange.startRow,
+ endRow: targetPositionRange.startRow,
+ startColumn: targetPositionRange.startColumn,
+ endColumn: targetPositionRange.startColumn,
+ });
});
}
});
@@ -186,7 +220,8 @@ export class ConditionalFormattingPainterController extends Disposable {
const generalApplyFunc = (targetUnitId: string, targetSubUnitId: string, targetRange: IRange) => {
const { range: sourceRange, unitId: sourceUnitId, subUnitId: sourceSubUnitId } = this._painterConfig!;
const isSkipSheet = targetUnitId !== sourceUnitId || sourceSubUnitId !== targetSubUnitId;
- const matrixMap: Map<string, ObjectMatrix<1>> = new Map();
+ const rangeMap: Map<string, IRange[]> = new Map();
+ const rangeDeltaMap: Map<string, IRangeDelta> = new Map();
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
@@ -197,15 +232,7 @@ export class ConditionalFormattingPainterController extends Disposable {
ruleList?.forEach((rule) => {
const { ranges, cfId } = rule;
if (ranges.some((range) => Rectangle.intersects(sourceRange, range))) {
- const matrix = new ObjectMatrix<1>();
- if (!isSkipSheet) {
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- matrix.setValue(row, col, 1);
- });
- });
- }
- matrixMap.set(cfId, matrix);
+ rangeMap.set(cfId, isSkipSheet ? [] : ranges);
}
});
@@ -217,16 +244,27 @@ export class ConditionalFormattingPainterController extends Disposable {
const repeats = repeatByRange(sourceRange, targetRange);
repeats.forEach((repeat) => {
- loopFunc(sourceStartCell, { row: repeat.startRange.startRow, col: repeat.startRange.startColumn }, repeat.repeatRelativeRange, matrixMap, { targetUnitId, targetSubUnitId });
+ loopFunc(sourceStartCell, { row: repeat.startRange.startRow, col: repeat.startRange.startColumn }, repeat.repeatRelativeRange, rangeMap, rangeDeltaMap, { targetUnitId, targetSubUnitId });
+ });
+ rangeDeltaMap.forEach((rangeDelta, cfId) => {
+ const ranges = rangeMap.get(cfId);
+ if (!ranges) {
+ return;
+ }
+
+ rangeMap.set(cfId, this._conditionalFormattingRangeTransformService.applyRangeDelta(
+ ranges,
+ rangeDelta.remove,
+ rangeDelta.add
+ ));
});
- matrixMap.forEach((item, cfId) => {
+ rangeMap.forEach((ranges, cfId) => {
if (!isSkipSheet) {
const rule = this._conditionalFormattingRuleModel.getRule(sourceUnitId, sourceSubUnitId, cfId);
if (!rule) {
return;
}
- const ranges = findAllRectangle(createTopMatrixFromMatrix(item));
if (ranges.length) {
const params: ISetConditionalRuleMutationParams = {
unitId: sourceUnitId,
@@ -246,7 +284,6 @@ export class ConditionalFormattingPainterController extends Disposable {
}
} else {
const rule = this._conditionalFormattingRuleModel.getRule(targetUnitId, targetSubUnitId, cfId);
- const ranges = findAllRectangle(createTopMatrixFromMatrix(item));
if (!rule) {
if (ranges.length) {
const sourceRule = this._conditionalFormattingRuleModel.getRule(sourceUnitId, sourceSubUnitId, cfId);
diff --git a/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts b/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
index da7fd524b3..2a0e37d5cd 100644
--- a/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
+++ b/packages/sheets-conditional-formatting/src/commands/commands/__tests__/clear-cf.command.spec.ts
@@ -18,7 +18,9 @@ import type { IAccessor } from '@univerjs/core';
import { ICommandService, IUndoRedoService, IUniverInstanceService } from '@univerjs/core';
import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
import { describe, expect, it, vi } from 'vitest';
+import { ConditionalFormattingRangeIndexModel } from '../../../models/conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from '../../../models/conditional-formatting-rule-model';
+import { ConditionalFormattingRangeTransformService } from '../../../services/conditional-formatting-range-transform.service';
import { DeleteConditionalRuleMutation } from '../../mutations/delete-conditional-rule.mutation';
import { SetConditionalRuleMutation } from '../../mutations/set-conditional-rule.mutation';
import { ClearRangeCfCommand } from '../clear-range-cf.command';
@@ -68,6 +70,8 @@ function createRuleModel() {
}
function createAccessor(ruleModel: ConditionalFormattingRuleModel) {
+ const rangeIndexModel = new ConditionalFormattingRangeIndexModel(ruleModel);
+ const rangeTransformService = new ConditionalFormattingRangeTransformService();
const commandService = {
syncExecuteCommand: vi.fn(() => true),
};
@@ -87,6 +91,14 @@ function createAccessor(ruleModel: ConditionalFormattingRuleModel) {
return ruleModel;
}
+ if (token === ConditionalFormattingRangeIndexModel) {
+ return rangeIndexModel;
+ }
+
+ if (token === ConditionalFormattingRangeTransformService) {
+ return rangeTransformService;
+ }
+
if (token === ICommandService) {
return commandService;
}
diff --git a/packages/sheets-conditional-formatting/src/commands/commands/clear-range-cf.command.ts b/packages/sheets-conditional-formatting/src/commands/commands/clear-range-cf.command.ts
index b3a03e42ec..291b3492ce 100644
--- a/packages/sheets-conditional-formatting/src/commands/commands/clear-range-cf.command.ts
+++ b/packages/sheets-conditional-formatting/src/commands/commands/clear-range-cf.command.ts
@@ -23,12 +23,11 @@ import {
ICommandService,
IUndoRedoService,
IUniverInstanceService,
- ObjectMatrix,
- Range,
sequenceExecute,
} from '@univerjs/core';
-import { createTopMatrixFromMatrix, findAllRectangle, getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
-import { ConditionalFormattingRuleModel } from '../../models/conditional-formatting-rule-model';
+import { getSheetCommandTarget, SheetsSelectionsService } from '@univerjs/sheets';
+import { ConditionalFormattingRangeIndexModel } from '../../models/conditional-formatting-range-index-model';
+import { ConditionalFormattingRangeTransformService } from '../../services/conditional-formatting-range-transform.service';
import { DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory } from '../mutations/delete-conditional-rule.mutation';
import { SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from '../mutations/set-conditional-rule.mutation';
@@ -44,7 +43,8 @@ export const ClearRangeCfCommand: ICommand<IClearRangeCfParams> = {
if (!params) {
return false;
}
- const conditionalFormattingRuleModel = accessor.get(ConditionalFormattingRuleModel);
+ const conditionalFormattingRangeIndexModel = accessor.get(ConditionalFormattingRangeIndexModel);
+ const conditionalFormattingRangeTransformService = accessor.get(ConditionalFormattingRangeTransformService);
const univerInstanceService = accessor.get(IUniverInstanceService);
const commandService = accessor.get(ICommandService);
const undoRedoService = accessor.get(IUndoRedoService);
@@ -54,8 +54,8 @@ export const ClearRangeCfCommand: ICommand<IClearRangeCfParams> = {
if (!target) return false;
const { unitId, subUnitId } = target;
- const ranges = selectionManagerService.getCurrentSelections()?.map((selection) => selection.range) || [];
- const allRuleList = conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
+ const ranges = params.ranges ?? selectionManagerService.getCurrentSelections()?.map((selection) => selection.range) ?? [];
+ const allRuleList = conditionalFormattingRangeIndexModel.getRulesByRanges(unitId, subUnitId, ranges);
if (!allRuleList?.length || !ranges.length) {
return false;
}
@@ -63,18 +63,7 @@ export const ClearRangeCfCommand: ICommand<IClearRangeCfParams> = {
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
allRuleList.forEach((oldRule) => {
- const matrix = new ObjectMatrix<1>();
- oldRule.ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- matrix.setValue(row, col, 1);
- });
- });
- ranges.forEach((range) => {
- Range.foreach(range, (row, col) => {
- matrix.realDeleteValue(row, col);
- });
- });
- const newRanges = findAllRectangle(createTopMatrixFromMatrix(matrix));
+ const newRanges = conditionalFormattingRangeTransformService.subtractRanges(oldRule.ranges, ranges);
if (newRanges.length) {
const rule: IConditionFormattingRule = { ...oldRule, ranges: newRanges };
const params = { unitId, subUnitId, rule } as ISetConditionalRuleMutationParams;
diff --git a/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts b/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts
index f10176f8d7..5068e3f591 100644
--- a/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts
+++ b/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts
@@ -33,7 +33,21 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { FUniver } from '@univerjs/core/facade';
-import { ActiveDirtyManagerService, DefinedNamesService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IFunctionService, ISheetRowFilteredService, ISuperTableService, LexerTreeBuilder, RegisterOtherFormulaService, SheetRowFilteredService, SuperTableService } from '@univerjs/engine-formula';
+import {
+ ActiveDirtyManagerService,
+ DefinedNamesService,
+ FormulaDataModel,
+ FunctionService,
+ IActiveDirtyManagerService,
+ IDefinedNamesService,
+ IFunctionService,
+ ISheetRowFilteredService,
+ ISuperTableService,
+ LexerTreeBuilder,
+ RegisterOtherFormulaService,
+ SheetRowFilteredService,
+ SuperTableService,
+} from '@univerjs/engine-formula';
import { Engine, IRenderingEngine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';
import {
RefRangeService,
@@ -41,8 +55,23 @@ import {
SheetSkeletonService,
SheetsSelectionsService,
} from '@univerjs/sheets';
-import { ConditionalFormattingFormulaService, ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel } from '@univerjs/sheets-conditional-formatting';
-import { DescriptionService, FormulaCalculationSessionController, FormulaCalculationSessionService, IDescriptionService, IRegisterFunctionService, RegisterFunctionService } from '@univerjs/sheets-formula';
+import {
+ ConditionalFormattingFormulaService,
+ ConditionalFormattingRangeIndexModel,
+ ConditionalFormattingRangeTransformService,
+ ConditionalFormattingRuleModel,
+ ConditionalFormattingService,
+ ConditionalFormattingStyleComposer,
+ ConditionalFormattingViewModel,
+} from '@univerjs/sheets-conditional-formatting';
+import {
+ DescriptionService,
+ FormulaCalculationSessionController,
+ FormulaCalculationSessionService,
+ IDescriptionService,
+ IRegisterFunctionService,
+ RegisterFunctionService,
+} from '@univerjs/sheets-formula';
import enUS from '@univerjs/sheets/locale/en-US';
import zhCN from '@univerjs/sheets/locale/zh-CN';
@@ -155,7 +184,10 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:
// conditional formatting
[ConditionalFormattingService],
[ConditionalFormattingFormulaService],
+ [ConditionalFormattingRangeTransformService],
+ [ConditionalFormattingStyleComposer],
[ConditionalFormattingRuleModel],
+ [ConditionalFormattingRangeIndexModel],
[ConditionalFormattingViewModel],
[RegisterOtherFormulaService],
[IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],
diff --git a/packages/sheets-conditional-formatting/src/index.ts b/packages/sheets-conditional-formatting/src/index.ts
index a2a92112ad..e6f333ef54 100644
--- a/packages/sheets-conditional-formatting/src/index.ts
+++ b/packages/sheets-conditional-formatting/src/index.ts
@@ -40,6 +40,7 @@ export type { ISetConditionalRuleMutationParams } from './commands/mutations/set
export { SetConditionalRuleMutation, setConditionalRuleMutationUndoFactory } from './commands/mutations/set-conditional-rule.mutation';
export type { IUniverSheetsConditionalFormattingConfig } from './config/config';
export * from './models/calculate-unit-v2/utils';
+export * from './models/conditional-formatting-range-index-model';
export * from './models/conditional-formatting-rule-model';
export * from './models/conditional-formatting-view-model';
export * from './models/icon-map';
@@ -49,6 +50,8 @@ export * from './render/data-bar.render';
export * from './render/icon.render';
export * from './render/type';
export * from './services/conditional-formatting-formula.service';
+export * from './services/conditional-formatting-range-transform.service';
+export * from './services/conditional-formatting-style-composer.service';
export * from './services/conditional-formatting.service';
export * from './utils/anchor';
export * from './utils/create-cf-id';
diff --git a/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts b/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts
new file mode 100644
index 0000000000..e9f5e738e2
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/__tests__/conditional-formatting-range-index-model.spec.ts
@@ -0,0 +1,98 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IConditionFormattingRule } from '../type';
+import { describe, expect, it } from 'vitest';
+import { CFRuleType, CFSubRuleType, CFTextOperator } from '../../base/const';
+import { ConditionalFormattingRangeIndexModel } from '../conditional-formatting-range-index-model';
+import { ConditionalFormattingRuleModel } from '../conditional-formatting-rule-model';
+
+function createRule(cfId: string, startRow: number, endRow: number, startColumn: number, endColumn: number): IConditionFormattingRule {
+ return {
+ cfId,
+ ranges: [{ startRow, endRow, startColumn, endColumn }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.text,
+ operator: CFTextOperator.containsText,
+ value: 'x',
+ style: { bg: { rgb: '#fff' } },
+ },
+ };
+}
+
+describe('ConditionalFormattingRangeIndexModel', () => {
+ it('queries rule ids by cell and range through rule model changes', () => {
+ const ruleModel = new ConditionalFormattingRuleModel();
+ const rangeIndex = new ConditionalFormattingRangeIndexModel(ruleModel);
+ const unitId = 'unit';
+ const subUnitId = 'sheet';
+
+ ruleModel.addRule(unitId, subUnitId, createRule('a', 0, 2, 0, 2));
+ ruleModel.addRule(unitId, subUnitId, createRule('b', 10, 12, 10, 12));
+
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 1, 1)).toEqual(new Set(['a']));
+ expect(rangeIndex.getRuleIdsByRanges(unitId, subUnitId, [{
+ startRow: 1,
+ endRow: 11,
+ startColumn: 1,
+ endColumn: 11,
+ }])).toEqual(new Set(['a', 'b']));
+
+ ruleModel.setRule(unitId, subUnitId, createRule('a', 20, 21, 20, 21), 'a');
+
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 1, 1)).toEqual(new Set());
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 20, 20)).toEqual(new Set(['a']));
+
+ ruleModel.deleteRule(unitId, subUnitId, 'a');
+
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 20, 20)).toEqual(new Set());
+
+ rangeIndex.dispose();
+ });
+
+ it('indexes rules that already exist before construction', () => {
+ const ruleModel = new ConditionalFormattingRuleModel();
+ const unitId = 'unit';
+ const subUnitId = 'sheet';
+
+ ruleModel.addRule(unitId, subUnitId, createRule('a', 0, 2, 0, 2));
+
+ const rangeIndex = new ConditionalFormattingRangeIndexModel(ruleModel);
+
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 1, 1)).toEqual(new Set(['a']));
+
+ rangeIndex.dispose();
+ });
+
+ it('can rebuild after unit rules are removed without rule change events', () => {
+ const ruleModel = new ConditionalFormattingRuleModel();
+ const rangeIndex = new ConditionalFormattingRangeIndexModel(ruleModel);
+ const unitId = 'unit';
+ const subUnitId = 'sheet';
+
+ ruleModel.addRule(unitId, subUnitId, createRule('a', 0, 2, 0, 2));
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 1, 1)).toEqual(new Set(['a']));
+
+ ruleModel.deleteUnitId(unitId);
+ rangeIndex.rebuild();
+
+ expect(rangeIndex.getRuleIdsByCell(unitId, subUnitId, 1, 1)).toEqual(new Set());
+
+ rangeIndex.dispose();
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
index 8aa3b9a6e1..562b65d28a 100644
--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__test__/test.util.ts
@@ -23,7 +23,10 @@ import { DeleteConditionalRuleMutation } from '../../../commands/mutations/delet
import { MoveConditionalRuleMutation } from '../../../commands/mutations/move-conditional-rule.mutation';
import { SetConditionalRuleMutation } from '../../../commands/mutations/set-conditional-rule.mutation';
import { ConditionalFormattingFormulaService } from '../../../services/conditional-formatting-formula.service';
+import { ConditionalFormattingRangeTransformService } from '../../../services/conditional-formatting-range-transform.service';
+import { ConditionalFormattingStyleComposer } from '../../../services/conditional-formatting-style-composer.service';
import { ConditionalFormattingService } from '../../../services/conditional-formatting.service';
+import { ConditionalFormattingRangeIndexModel } from '../../conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from '../../conditional-formatting-rule-model';
import { ConditionalFormattingViewModel } from '../../conditional-formatting-view-model';
@@ -72,7 +75,10 @@ export const createTestBed = (dependencies?: Dependency[]) => {
this._injector.add([ConditionalFormattingService]);
this._injector.add([RegisterOtherFormulaService]);
this._injector.add([ConditionalFormattingFormulaService]);
+ this._injector.add([ConditionalFormattingRangeTransformService]);
+ this._injector.add([ConditionalFormattingStyleComposer]);
this._injector.add([ConditionalFormattingRuleModel]);
+ this._injector.add([ConditionalFormattingRangeIndexModel]);
this._injector.add([ConditionalFormattingViewModel]);
this._injector.add([IActiveDirtyManagerService, { useFactory: () => ({ register: () => { /* empty */ } } as any) }]);
}
diff --git a/packages/sheets-conditional-formatting/src/models/conditional-formatting-range-index-model.ts b/packages/sheets-conditional-formatting/src/models/conditional-formatting-range-index-model.ts
new file mode 100644
index 0000000000..f6f5473066
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/conditional-formatting-range-index-model.ts
@@ -0,0 +1,115 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRange } from '@univerjs/core';
+import { Disposable, Inject, RTree } from '@univerjs/core';
+import { ConditionalFormattingRuleModel } from './conditional-formatting-rule-model';
+
+export class ConditionalFormattingRangeIndexModel extends Disposable {
+ private _rTreeManager: RTree = new RTree();
+
+ constructor(
+ @Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel
+ ) {
+ super();
+
+ this.rebuild();
+ this._initRuleListener();
+ }
+
+ getRuleIdsByCell(unitId: string, subUnitId: string, row: number, col: number) {
+ return this.getRuleIdsByRanges(unitId, subUnitId, [{
+ startRow: row,
+ endRow: row,
+ startColumn: col,
+ endColumn: col,
+ }]);
+ }
+
+ getRuleIdsByRanges(unitId: string, subUnitId: string, ranges: IRange[]) {
+ if (!ranges.length) {
+ return new Set<string>();
+ }
+
+ const ids = this._rTreeManager.bulkSearch(ranges.map((range) => ({
+ unitId,
+ sheetId: subUnitId,
+ range,
+ })));
+
+ return new Set(Array.from(ids).map((id) => String(id)));
+ }
+
+ getRulesByRanges(unitId: string, subUnitId: string, ranges: IRange[]) {
+ const ids = this.getRuleIdsByRanges(unitId, subUnitId, ranges);
+ const ruleList = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId) ?? [];
+ return ruleList.filter((rule) => ids.has(rule.cfId));
+ }
+
+ override dispose(): void {
+ this.clear();
+ super.dispose();
+ }
+
+ clear() {
+ this._rTreeManager.clear();
+ }
+
+ rebuild() {
+ this.clear();
+ this._conditionalFormattingRuleModel.getAll().forEach((subUnitMap, unitId) => {
+ subUnitMap.forEach((rules, subUnitId) => {
+ rules.forEach((rule) => {
+ this._insert(unitId, subUnitId, rule.cfId, rule.ranges);
+ });
+ });
+ });
+ }
+
+ private _initRuleListener() {
+ this.disposeWithMe(
+ this._conditionalFormattingRuleModel.$ruleChange.subscribe((e) => {
+ const { unitId, subUnitId, rule } = e;
+ const { cfId, ranges } = rule;
+
+ switch (e.type) {
+ case 'add': {
+ this._insert(unitId, subUnitId, cfId, ranges);
+ break;
+ }
+ case 'delete': {
+ this._remove(unitId, subUnitId, cfId, ranges);
+ break;
+ }
+ case 'set': {
+ const oldRule = e.oldRule!;
+ this._remove(unitId, subUnitId, oldRule.cfId, oldRule.ranges);
+ this._insert(unitId, subUnitId, cfId, ranges);
+ break;
+ }
+ }
+ })
+ );
+ }
+
+ private _insert(unitId: string, subUnitId: string, cfId: string, ranges: IRange[]) {
+ this._rTreeManager.bulkInsert(ranges.map((range) => ({ unitId, sheetId: subUnitId, id: cfId, range })));
+ }
+
+ private _remove(unitId: string, subUnitId: string, cfId: string, ranges: IRange[]) {
+ this._rTreeManager.bulkRemove(ranges.map((range) => ({ unitId, sheetId: subUnitId, id: cfId, range })));
+ }
+}
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
index 98d678e56b..b5db16d804 100644
--- a/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model.ts
+++ b/packages/sheets-conditional-formatting/src/models/conditional-formatting-view-model.ts
@@ -17,7 +17,7 @@
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 { Disposable, Inject, Injector, IUniverInstanceService, LRUMap } from '@univerjs/core';
import { Subject } from 'rxjs';
import { bufferTime, filter, map } from 'rxjs/operators';
import { CFRuleType, CFSubRuleType } from '../base/const';
@@ -26,6 +26,7 @@ import { ColorScaleCalculateUnit } from './calculate-unit-v2/color-scale-calcula
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 { ConditionalFormattingRangeIndexModel } from './conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from './conditional-formatting-rule-model';
// The default is a 50-row,20-column viewable area.
@@ -33,7 +34,6 @@ export const CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH = 50 * 20 * 3 * 3;
export class ConditionalFormattingViewModel 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
@@ -49,6 +49,7 @@ export class ConditionalFormattingViewModel extends Disposable {
constructor(
@Inject(Injector) private _injector: Injector,
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
+ @Inject(ConditionalFormattingRangeIndexModel) private _conditionalFormattingRangeIndexModel: ConditionalFormattingRangeIndexModel,
@Inject(ConditionalFormattingFormulaService) private _conditionalFormattingFormulaService: ConditionalFormattingFormulaService,
@IUniverInstanceService private _univerInstanceService: IUniverInstanceService
) {
@@ -85,7 +86,7 @@ export class ConditionalFormattingViewModel extends Disposable {
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 list = this._conditionalFormattingRangeIndexModel.getRuleIdsByCell(unitId, subUnitId, row, col);
const rules = subunitRules.filter((rule) => list.has(rule.cfId));
if (!rules.length) {
return [];
@@ -170,7 +171,6 @@ export class ConditionalFormattingViewModel extends Disposable {
clearCache() {
this._calculateUnitManagers.clear();
this._cellCache.clear();
- this._rTreeManager.clear();
}
private _handleCustomFormulasSeparately() {
@@ -197,7 +197,6 @@ export class ConditionalFormattingViewModel extends Disposable {
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;
@@ -206,15 +205,12 @@ export class ConditionalFormattingViewModel extends Disposable {
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) {
diff --git a/packages/sheets-conditional-formatting/src/plugin.ts b/packages/sheets-conditional-formatting/src/plugin.ts
index 7d673891f5..97b73f2988 100644
--- a/packages/sheets-conditional-formatting/src/plugin.ts
+++ b/packages/sheets-conditional-formatting/src/plugin.ts
@@ -34,9 +34,12 @@ import {
defaultPluginConfig,
SHEETS_CONDITIONAL_FORMATTING_PLUGIN_CONFIG_KEY,
} from './config/config';
+import { ConditionalFormattingRangeIndexModel } from './models/conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from './models/conditional-formatting-rule-model';
import { ConditionalFormattingViewModel } from './models/conditional-formatting-view-model';
import { ConditionalFormattingFormulaService } from './services/conditional-formatting-formula.service';
+import { ConditionalFormattingRangeTransformService } from './services/conditional-formatting-range-transform.service';
+import { ConditionalFormattingStyleComposer } from './services/conditional-formatting-style-composer.service';
import { ConditionalFormattingService } from './services/conditional-formatting.service';
@DependentOn(UniverFormulaEnginePlugin)
@@ -65,7 +68,10 @@ export class UniverSheetsConditionalFormattingPlugin extends Plugin {
([
[ConditionalFormattingService],
[ConditionalFormattingFormulaService],
+ [ConditionalFormattingRangeTransformService],
+ [ConditionalFormattingStyleComposer],
[ConditionalFormattingRuleModel],
+ [ConditionalFormattingRangeIndexModel],
[ConditionalFormattingViewModel],
] as Dependency[]).forEach((dependency) => {
this._injector.add(dependency);
@@ -91,6 +97,7 @@ export class UniverSheetsConditionalFormattingPlugin extends Plugin {
this._injector.get(ConditionalFormattingService);
touchDependencies(this._injector, [
[ConditionalFormattingService],
+ [ConditionalFormattingRangeIndexModel],
[ConditionalFormattingViewModel],
]);
}
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts
new file mode 100644
index 0000000000..00cbb9fe87
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-range-transform.service.spec.ts
@@ -0,0 +1,86 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { ConditionalFormattingRangeTransformService } from '../conditional-formatting-range-transform.service';
+
+const sortRanges = <T extends { startRow: number; startColumn: number; endRow: number; endColumn: number }>(ranges: T[]) => {
+ return [...ranges].sort((a, b) =>
+ a.startRow - b.startRow ||
+ a.startColumn - b.startColumn ||
+ a.endRow - b.endRow ||
+ a.endColumn - b.endColumn
+ );
+};
+
+describe('ConditionalFormattingRangeTransformService', () => {
+ it('subtracts ranges without expanding to a cell matrix', () => {
+ const service = new ConditionalFormattingRangeTransformService();
+
+ const ranges = service.subtractRanges(
+ [{ startRow: 0, endRow: 4, startColumn: 0, endColumn: 4 }],
+ [{ startRow: 1, endRow: 3, startColumn: 1, endColumn: 3 }]
+ );
+
+ expect(sortRanges(ranges)).toEqual(sortRanges([
+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 4 },
+ { startRow: 4, startColumn: 0, endRow: 4, endColumn: 4 },
+ { startRow: 1, startColumn: 0, endRow: 3, endColumn: 0 },
+ { startRow: 1, startColumn: 4, endRow: 3, endColumn: 4 },
+ ]));
+ });
+
+ it('intersects source ranges and translates them to a target anchor', () => {
+ const service = new ConditionalFormattingRangeTransformService();
+
+ const ranges = service.copyIntersectingRanges(
+ [{ startRow: 0, endRow: 2, startColumn: 0, endColumn: 2 }],
+ { startRow: 1, endRow: 1, startColumn: 1, endColumn: 2 },
+ { row: 10, col: 20 }
+ );
+
+ expect(ranges).toEqual([
+ { startRow: 10, endRow: 10, startColumn: 20, endColumn: 21 },
+ ]);
+ });
+
+ it('adds and merges translated ranges', () => {
+ const service = new ConditionalFormattingRangeTransformService();
+
+ const ranges = service.addRanges(
+ [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 0 }],
+ [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }]
+ );
+
+ expect(ranges).toEqual([{ startRow: 0, startColumn: 0, endRow: 0, endColumn: 1 }]);
+ });
+
+ it('applies batched subtract and add operations once per rule', () => {
+ const service = new ConditionalFormattingRangeTransformService();
+
+ const ranges = service.applyRangeDelta(
+ [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }],
+ [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }],
+ [{ startRow: 1, endRow: 1, startColumn: 0, endColumn: 1 }]
+ );
+
+ expect(sortRanges(ranges)).toEqual(sortRanges([
+ { startRow: 0, startColumn: 0, endRow: 0, endColumn: 0 },
+ { startRow: 0, startColumn: 2, endRow: 0, endColumn: 2 },
+ { startRow: 1, startColumn: 0, endRow: 1, endColumn: 1 },
+ ]));
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts
new file mode 100644
index 0000000000..20f1c1e6e7
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting-range-transform.service.ts
@@ -0,0 +1,70 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IRange } from '@univerjs/core';
+import { Rectangle } from '@univerjs/core';
+
+export interface IRangeAnchor {
+ row: number;
+ col: number;
+}
+
+export class ConditionalFormattingRangeTransformService {
+ subtractRanges(sourceRanges: IRange[], rangesToSubtract: IRange[]) {
+ return Rectangle.mergeRanges(Rectangle.subtractMulti(sourceRanges, rangesToSubtract));
+ }
+
+ addRanges(sourceRanges: IRange[], rangesToAdd: IRange[]) {
+ return Rectangle.mergeRanges([...sourceRanges, ...rangesToAdd]);
+ }
+
+ applyRangeDelta(sourceRanges: IRange[], rangesToSubtract: IRange[], rangesToAdd: IRange[]) {
+ const ranges = rangesToSubtract.length
+ ? this.subtractRanges(sourceRanges, rangesToSubtract)
+ : sourceRanges;
+
+ return rangesToAdd.length
+ ? this.addRanges(ranges, rangesToAdd)
+ : ranges;
+ }
+
+ copyIntersectingRanges(sourceRanges: IRange[], sourceRange: IRange, targetAnchor: IRangeAnchor) {
+ const fragments: IRange[] = [];
+
+ sourceRanges.forEach((range) => {
+ const intersect = Rectangle.getIntersects(range, sourceRange);
+ if (!intersect) {
+ return;
+ }
+
+ fragments.push(this.translateRange(intersect, {
+ row: targetAnchor.row - sourceRange.startRow,
+ col: targetAnchor.col - sourceRange.startColumn,
+ }));
+ });
+
+ return Rectangle.mergeRanges(fragments);
+ }
+
+ translateRange(range: IRange, offset: IRangeAnchor): IRange {
+ return {
+ startRow: range.startRow + offset.row,
+ endRow: range.endRow + offset.row,
+ startColumn: range.startColumn + offset.col,
+ endColumn: range.endColumn + offset.col,
+ };
+ }
+}
diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting-style-composer.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting-style-composer.service.ts
new file mode 100644
index 0000000000..19d931dccb
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting-style-composer.service.ts
@@ -0,0 +1,123 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { IConditionFormattingRule, IHighlightCell } from '../models/type';
+import type { IDataBarCellData, IDataBarRenderParams, IIconSetCellData, IIconSetRenderParams } from '../render/type';
+import { Inject, merge } from '@univerjs/core';
+import { CFRuleType } from '../base/const';
+import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';
+import { ConditionalFormattingViewModel } from '../models/conditional-formatting-view-model';
+
+export class ConditionalFormattingStyleComposer {
+ constructor(
+ @Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
+ @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel
+ ) {
+ // empty
+ }
+
+ // Conditional formats need to be evaluated in priority order.
+ // Evaluation of subsequent rules stops only if the current rule is matched and stopIfTrue=true.
+ composeStyle(unitId: string, subUnitId: string, row: number, col: number) {
+ const cellCfs = this._conditionalFormattingViewModel.getCellCfs(unitId, subUnitId, row, col);
+
+ if (!cellCfs?.length) {
+ return null;
+ }
+
+ const matchedRules: Array<{
+ rule: IConditionFormattingRule;
+ cacheItem: (typeof cellCfs)[number];
+ }> = [];
+
+ let stopIfTrueIndex = -1;
+ for (const cacheItem of cellCfs) {
+ const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cacheItem.cfId);
+ if (!rule) {
+ continue;
+ }
+
+ matchedRules.push({ rule, cacheItem });
+
+ if (stopIfTrueIndex === -1 && rule.stopIfTrue && this._isRuleMatched(rule, cacheItem.result)) {
+ stopIfTrueIndex = matchedRules.length - 1;
+ }
+ }
+
+ if (!matchedRules.length) {
+ return null;
+ }
+
+ const effectiveRules = stopIfTrueIndex > -1
+ ? matchedRules.slice(0, stopIfTrueIndex + 1)
+ : matchedRules;
+
+ const result = {} as { style?: IHighlightCell['style'] } & IDataBarCellData & IIconSetCellData & { isShowValue: boolean };
+
+ for (let i = effectiveRules.length - 1; i >= 0; i--) {
+ const { rule, cacheItem } = effectiveRules[i];
+ this._mergeComposeResult(result, rule, cacheItem.result);
+ }
+
+ return result;
+ }
+
+ private _mergeComposeResult(
+ result: { style?: IHighlightCell['style'] } & IDataBarCellData & IIconSetCellData & { isShowValue: boolean },
+ rule: IConditionFormattingRule,
+ ruleResult: unknown
+ ) {
+ const type = rule.rule.type;
+
+ if (type === CFRuleType.highlightCell) {
+ ruleResult && merge(result, { style: ruleResult });
+ return;
+ }
+
+ if (type === CFRuleType.colorScale) {
+ if (ruleResult && typeof ruleResult === 'string') {
+ const preStyle = result.style || {};
+ result.style = { ...preStyle, bg: { rgb: ruleResult } };
+ }
+ return;
+ }
+
+ if (type === CFRuleType.dataBar) {
+ const ruleCache = ruleResult as IDataBarRenderParams;
+ if (ruleCache) {
+ result.dataBar = ruleCache;
+ result.isShowValue = ruleCache.isShowValue;
+ }
+ return;
+ }
+
+ if (type === CFRuleType.iconSet) {
+ const ruleCache = ruleResult as IIconSetRenderParams;
+ if (ruleCache) {
+ result.iconSet = ruleCache;
+ result.isShowValue = ruleCache.isShowValue;
+ }
+ }
+ }
+
+ private _isRuleMatched(rule: IConditionFormattingRule, ruleResult: unknown) {
+ if (rule.rule.type === CFRuleType.highlightCell) {
+ return !!ruleResult && typeof ruleResult === 'object' && Object.keys(ruleResult as object).length > 0;
+ }
+
+ return !!ruleResult;
+ }
+}
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 5307ced72a..0ab9a7b8db 100644
--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
@@ -30,8 +30,7 @@ import type {
} from '@univerjs/sheets';
import type { IAddConditionalRuleMutationParams } from '../commands/mutations/add-conditional-rule.mutation';
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 { IRuleModelJson } from '../models/type';
import {
Disposable,
ICommandService,
@@ -40,9 +39,7 @@ import {
IResourceManagerService,
isInternalEditorID,
IUniverInstanceService,
- merge,
ObjectMatrix,
- Rectangle,
UniverInstanceType,
} from '@univerjs/core';
import {
@@ -60,57 +57,23 @@ import {
SetRangeValuesMutation,
SheetInterceptorService,
} from '@univerjs/sheets';
-import { CFRuleType, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '../base/const';
+import { SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '../base/const';
import { AddConditionalRuleMutation, AddConditionalRuleMutationUndoFactory } from '../commands/mutations/add-conditional-rule.mutation';
import { DeleteConditionalRuleMutation, DeleteConditionalRuleMutationUndoFactory } from '../commands/mutations/delete-conditional-rule.mutation';
+import { ConditionalFormattingRangeIndexModel } from '../models/conditional-formatting-range-index-model';
import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';
import { ConditionalFormattingViewModel } from '../models/conditional-formatting-view-model';
+import { ConditionalFormattingStyleComposer } from './conditional-formatting-style-composer.service';
export class ConditionalFormattingService extends Disposable {
get _conditionalFormattingViewModelV2() {
return this._injector.get(ConditionalFormattingViewModel);
}
- private _mergeComposeResult(
- result: { style?: IHighlightCell['style'] } & IDataBarCellData & IIconSetCellData & { isShowValue: boolean },
- rule: IConditionFormattingRule,
- ruleResult: unknown
- ) {
- const type = rule.rule.type;
-
- if (type === CFRuleType.highlightCell) {
- ruleResult && merge(result, { style: ruleResult });
- return;
- }
-
- if (type === CFRuleType.colorScale) {
- if (ruleResult && typeof ruleResult === 'string') {
- const preStyle = result.style || {};
- result.style = { ...preStyle, bg: { rgb: ruleResult } };
- }
- return;
- }
-
- if (type === CFRuleType.dataBar) {
- const ruleCache = ruleResult as IDataBarRenderParams;
- if (ruleCache) {
- result.dataBar = ruleCache;
- result.isShowValue = ruleCache.isShowValue;
- }
- return;
- }
-
- if (type === CFRuleType.iconSet) {
- const ruleCache = ruleResult as IIconSetRenderParams;
- if (ruleCache) {
- result.iconSet = ruleCache;
- result.isShowValue = ruleCache.isShowValue;
- }
- }
- }
-
constructor(
@Inject(ConditionalFormattingRuleModel) private _conditionalFormattingRuleModel: ConditionalFormattingRuleModel,
+ @Inject(ConditionalFormattingRangeIndexModel) private _conditionalFormattingRangeIndexModel: ConditionalFormattingRangeIndexModel,
+ @Inject(ConditionalFormattingStyleComposer) private _conditionalFormattingStyleComposer: ConditionalFormattingStyleComposer,
@Inject(Injector) private _injector: Injector,
@Inject(IUniverInstanceService) private _univerInstanceService: IUniverInstanceService,
@Inject(IResourceManagerService) private _resourceManagerService: IResourceManagerService,
@@ -123,61 +86,8 @@ export class ConditionalFormattingService extends Disposable {
this._initSheetChange();
}
- //Conditional formats need to be evaluated in priority order
- // (in this implementation, this is equivalent to evaluating higher-priority rules first,
- // which generally corresponds to a smaller order value coming first).
- // Evaluation of subsequent rules shall stop only if the current rule is matched and stopIfTrue=true.
- // A stopIfTrue rule that is not matched must not terminate the evaluation of subsequent rules.
public composeStyle(unitId: string, subUnitId: string, row: number, col: number) {
- const cellCfs = this._conditionalFormattingViewModelV2.getCellCfs(unitId, subUnitId, row, col);
-
- if (!cellCfs?.length) {
- return null;
- }
-
- const matchedRules: Array<{
- rule: IConditionFormattingRule;
- cacheItem: (typeof cellCfs)[number];
- }> = [];
-
- let stopIfTrueIndex = -1;
- for (const cacheItem of cellCfs) {
- const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cacheItem.cfId);
- if (!rule) {
- continue;
- }
-
- matchedRules.push({ rule, cacheItem });
-
- if (stopIfTrueIndex === -1 && rule.stopIfTrue && this._isRuleMatched(rule, cacheItem.result)) {
- stopIfTrueIndex = matchedRules.length - 1;
- }
- }
-
- if (!matchedRules.length) {
- return null;
- }
-
- const effectiveRules = stopIfTrueIndex > -1
- ? matchedRules.slice(0, stopIfTrueIndex + 1)
- : matchedRules;
-
- const result = {} as { style?: IHighlightCell['style'] } & IDataBarCellData & IIconSetCellData & { isShowValue: boolean };
-
- for (let i = effectiveRules.length - 1; i >= 0; i--) {
- const { rule, cacheItem } = effectiveRules[i];
- this._mergeComposeResult(result, rule, cacheItem.result);
- }
-
- return result;
- }
-
- private _isRuleMatched(rule: IConditionFormattingRule, ruleResult: unknown) {
- if (rule.rule.type === CFRuleType.highlightCell) {
- return !!ruleResult && typeof ruleResult === 'object' && Object.keys(ruleResult as object).length > 0;
- }
-
- return !!ruleResult;
+ return this._conditionalFormattingStyleComposer.composeStyle(unitId, subUnitId, row, col);
}
private _initSnapshot() {
@@ -210,6 +120,7 @@ export class ConditionalFormattingService extends Disposable {
parseJson: (json) => parseJson(json),
onUnLoad: (unitID) => {
this._conditionalFormattingRuleModel.deleteUnitId(unitID);
+ this._conditionalFormattingRangeIndexModel.rebuild();
if (isInternalEditorID(unitID)) return;
this._conditionalFormattingViewModelV2.clearCache();
},
@@ -307,38 +218,26 @@ export class ConditionalFormattingService extends Disposable {
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._conditionalFormattingViewModelV2.getCellCfs(unitId, subUnitId, row, col);
- ruleItem?.forEach((item) => ruleIds.add(item.cfId));
+ const markRulesDirtyByRanges = (unitId: string, subUnitId: string, ranges: IRange[]) => {
+ const rules = this._conditionalFormattingRangeIndexModel.getRulesByRanges(unitId, subUnitId, ranges);
+ rules.forEach((rule) => {
+ this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
});
- const rules: IConditionFormattingRule[] = [];
- for (const cfId of ruleIds) {
- const rule = this._conditionalFormattingRuleModel.getRule(unitId, subUnitId, cfId);
- if (rule) {
- rules.push(rule);
- }
- }
- return rules;
};
switch (commandInfo.id) {
case SetRangeValuesMutation.id: {
const params = commandInfo.params as ISetRangeValuesMutationParams;
const { subUnitId, unitId, cellValue } = params;
- const cellMatrix: [number, number][] = [];
+ const ranges: IRange[] = [];
new ObjectMatrix(cellValue).forValue((row, col, value) => {
// When P and V are involved
const result = value && Object.keys(value).some((key) => ['p', 'v'].includes(key));
if (result) {
- cellMatrix.push([row, col]);
+ ranges.push({ startRow: row, endRow: row, startColumn: col, endColumn: col });
}
});
- const rules = collectRule(unitId, subUnitId, cellMatrix);
- rules.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
- });
+ markRulesDirtyByRanges(unitId, subUnitId, ranges);
break;
}
case InsertColMutation.id:
@@ -351,13 +250,7 @@ export class ConditionalFormattingService extends Disposable {
const { range } = params;
const effectRange: IRange = { ...range, endColumn: worksheet.getColumnCount() - 1 };
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
- if (allRules) {
- const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
- effectRule.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
- });
- }
+ markRulesDirtyByRanges(unitId, subUnitId, [effectRange]);
break;
}
case RemoveRowMutation.id:
@@ -370,13 +263,7 @@ export class ConditionalFormattingService extends Disposable {
const { range } = params;
const effectRange: IRange = { ...range, endRow: worksheet.getRowCount() - 1 };
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
- if (allRules) {
- const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
- effectRule.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
- });
- }
+ markRulesDirtyByRanges(unitId, subUnitId, [effectRange]);
break;
}
case MoveRowsMutation.id: {
@@ -393,13 +280,7 @@ export class ConditionalFormattingService extends Disposable {
endColumn: worksheet.getColumnCount() - 1,
};
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
- if (allRules) {
- const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
- effectRule.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
- });
- }
+ markRulesDirtyByRanges(unitId, subUnitId, [effectRange]);
break;
}
case MoveColsMutation.id: {
@@ -416,26 +297,17 @@ export class ConditionalFormattingService extends Disposable {
endColumn: worksheet.getColumnCount() - 1,
};
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
- if (allRules) {
- const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, effectRange)));
- effectRule.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
- });
- }
+ markRulesDirtyByRanges(unitId, subUnitId, [effectRange]);
break;
}
case MoveRangeMutation.id: {
const { unitId, to, from } = commandInfo.params as IMoveRangeMutationParams;
const handleSubUnit = (value: IMoveRangeMutationParams['from']) => {
- const cellMatrix: [number, number][] = [];
+ const ranges: IRange[] = [];
new ObjectMatrix(value.value).forValue((row, col) => {
- cellMatrix.push([row, col]);
- });
- const rules = collectRule(unitId, value.subUnitId, cellMatrix);
- rules.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, value.subUnitId, rule.cfId);
+ ranges.push({ startRow: row, endRow: row, startColumn: col, endColumn: col });
});
+ markRulesDirtyByRanges(unitId, value.subUnitId, ranges);
};
handleSubUnit(to);
handleSubUnit(from);
@@ -443,13 +315,7 @@ export class ConditionalFormattingService extends Disposable {
}
case ReorderRangeMutation.id: {
const { range, unitId, subUnitId } = commandInfo.params as IReorderRangeMutationParams;
- const allRules = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId);
- if (allRules) {
- const effectRule = allRules.filter((rule) => rule.ranges.some((ruleRange) => Rectangle.intersects(ruleRange, range)));
- effectRule.forEach((rule) => {
- this._conditionalFormattingViewModelV2.markRuleDirty(unitId, subUnitId, rule.cfId);
- });
- }
+ markRulesDirtyByRanges(unitId, subUnitId, [range]);
break;
}
}