Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(conditionformat): fix condition format rule stopif true err (#6823)

VicKun79ac91055222
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx
index f079e73917..cdc10be51f 100644
--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-list/index.tsx
@@ -370,7 +370,12 @@ export const RuleList = (props: IRuleListProps) => {
>
{getRuleDescribe(rule, localeService)}
</div>
- <div className="univer-text-xs univer-text-gray-400">
+ <div
+ className="
+ univer-max-w-[250px] univer-overflow-hidden univer-text-ellipsis univer-text-xs
+ univer-text-gray-400
+ "
+ >
{rule.ranges.map((range) => serializeRange(range)).join(',')}
</div>
</div>
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
index 3a5bf33f42..d083cd4cb2 100644
--- 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
@@ -29,6 +29,74 @@ describe('Test conditional formatting highlight', () => {
});
describe('Test Number', async () => {
+ it('Should apply higher-priority rule style when multiple rules are matched', () => {
+ const lowerPriorityRule: 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: '#FFC000' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.between,
+ value: [0, 10],
+ },
+ };
+
+ const higherPriorityRule: 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: '#FFFF00' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.between,
+ value: [0, 10],
+ },
+ };
+
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, lowerPriorityRule);
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, higherPriorityRule);
+
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#FFFF00' } } });
+ });
+
+ it('Should not stop at stopIfTrue rule when the rule is not matched', () => {
+ const shouldApplyLaterRule: 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],
+ },
+ };
+
+ const stopIfTrueButNotMatched: IConditionFormattingRule<INumberHighlightCell> = {
+ ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
+ cfId: testBed.getConditionalFormattingRuleModel().createCfId(testBed.unitId, testBed.subUnitId),
+ stopIfTrue: true,
+ rule: {
+ style: { bg: { rgb: '#FF0000' } },
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value: 100,
+ },
+ };
+
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, shouldApplyLaterRule);
+ testBed.getConditionalFormattingRuleModel().addRule(testBed.unitId, testBed.subUnitId, stopIfTrueButNotMatched);
+
+ const result = testBed.getConditionalFormattingService().composeStyle(testBed.unitId, testBed.subUnitId, 1, 1);
+ expect(result).toEqual({ style: { bg: { rgb: '#2AEAEA' } } });
+ });
+
it('Is CFNumberOperator.between', async () => {
const params: IConditionFormattingRule<INumberHighlightCell> = {
ranges: [{ startRow: 0, startColumn: 0, endRow: 2, endColumn: 2 }],
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
index 4faaede4fd..62837411dc 100644
--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
@@ -28,6 +28,17 @@ interface IConfig {
value: any;
type: CFSubRuleType;
}
+
+const isFormulaResultMatched = (value: unknown) => value === true || value === 1 || value === 'TRUE';
+
+const sortRangesByTopLeft = <T extends { startRow: number; startColumn: number }>(ranges: T[]) => [...ranges].sort((a, b) => {
+ if (a.startRow !== b.startRow) {
+ return a.startRow - b.startRow;
+ }
+
+ return a.startColumn - b.startColumn;
+});
+
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 {
@@ -106,7 +117,8 @@ export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConf
case CFSubRuleType.formula: {
const _ruleConfig = ruleConfig as IFormulaHighlightCell;
const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
- conditionalFormattingFormulaService.registerFormulaWithRange(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value, context.rule.ranges);
+ const normalizedRanges = sortRangesByTopLeft(context.rule.ranges);
+ conditionalFormattingFormulaService.registerFormulaWithRange(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value, normalizedRanges);
const result = conditionalFormattingFormulaService.getFormulaMatrix(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value);
if (result && result.status === FormulaResultStatus.SUCCESS) {
this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
@@ -374,16 +386,31 @@ export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConf
return uniqueCacheValue && uniqueCacheValue !== 1;
}
case CFSubRuleType.formula: {
- // const _ruleConfig = ruleConfig as IFormulaHighlightCell;
+ const _ruleConfig = ruleConfig as IFormulaHighlightCell;
+ const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
+
+ // The formula engine stores results at relative offsets from the first range's top-left.
+ const firstRange = sortRangesByTopLeft(context.rule.ranges)[0];
+ const relativeRow = row - firstRange.startRow;
+ const relativeCol = col - firstRange.startColumn;
+
+ const formulaResult = conditionalFormattingFormulaService.getFormulaResultWithCoords(
+ context.unitId,
+ context.subUnitId,
+ context.rule.cfId,
+ _ruleConfig.value,
+ relativeRow,
+ relativeCol
+ );
+
+ if (formulaResult.status === FormulaResultStatus.SUCCESS && formulaResult.result !== undefined) {
+ return isFormulaResultMatched(formulaResult.result);
+ }
+
const cache = preComputingResult?.value;
if (cache) {
- // The formula result matrix starts from (0,0), but we need to use relative coordinates
- // based on the first range's start position
- const firstRange = context.rule.ranges[0];
- const relativeRow = row - firstRange.startRow;
- const relativeCol = col - firstRange.startColumn;
const value = cache.getValue(relativeRow, relativeCol);
- return value === true;
+ return isFormulaResultMatched(value);
}
return false;
}
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 6037c63f1e..3655407592 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
@@ -153,7 +153,12 @@ export class ConditionalFormattingFormulaService extends Disposable {
if (formulaMap.getValue(cfFormulaId, ['id'])) {
return;
}
- const formulaId = this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formulaText, ranges, undefined, OtherFormulaBizType.CONDITIONAL_FORMATTING, cfId);
+ // Always sort ranges by top-left so the formula engine uses a consistent anchor (ranges[0])
+ // regardless of the call path (e.g. rule-add event vs preComputing).
+ const sortedRanges = [...ranges].sort((a, b) =>
+ a.startRow !== b.startRow ? a.startRow - b.startRow : a.startColumn - b.startColumn
+ );
+ const formulaId = this._registerOtherFormulaService.registerFormulaWithRange(unitId, subUnitId, formulaText, sortedRanges, undefined, OtherFormulaBizType.CONDITIONAL_FORMATTING, cfId);
formulaMap.addValue({
formulaText,
unitId,
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 174e0cfec2..82463c22b8 100644
--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
@@ -59,6 +59,44 @@ export class ConditionalFormattingService extends Disposable {
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(Injector) private _injector: Injector,
@@ -73,6 +111,11 @@ 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);
@@ -94,7 +137,7 @@ export class ConditionalFormattingService extends Disposable {
matchedRules.push({ rule, cacheItem });
- if (stopIfTrueIndex === -1 && rule.stopIfTrue) {
+ if (stopIfTrueIndex === -1 && rule.stopIfTrue && this._isRuleMatched(rule, cacheItem.result)) {
stopIfTrueIndex = matchedRules.length - 1;
}
}
@@ -111,34 +154,20 @@ export class ConditionalFormattingService extends Disposable {
for (let i = effectiveRules.length - 1; i >= 0; i--) {
const { rule, cacheItem } = effectiveRules[i];
- const type = rule.rule.type;
-
- if (type === CFRuleType.highlightCell) {
- cacheItem.result && merge(result, { style: cacheItem.result });
- } else if (type === CFRuleType.colorScale) {
- const ruleCache = cacheItem.result;
- if (ruleCache && typeof ruleCache === 'string') {
- const preStyle = result.style || {};
- result.style = { ...preStyle, bg: { rgb: ruleCache } };
- }
- } else if (type === CFRuleType.dataBar) {
- const ruleCache = cacheItem.result as IDataBarRenderParams;
- if (ruleCache) {
- result.dataBar = ruleCache;
- result.isShowValue = ruleCache.isShowValue;
- }
- } else if (type === CFRuleType.iconSet) {
- const ruleCache = cacheItem.result as IIconSetRenderParams;
- if (ruleCache) {
- result.iconSet = ruleCache;
- result.isShowValue = ruleCache.isShowValue;
- }
- }
+ 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;
+ }
+
private _initSnapshot() {
const toJson = (unitID: string) => {
const map = this._conditionalFormattingRuleModel.getUnitRules(unitID);
@@ -157,7 +186,7 @@ export class ConditionalFormattingService extends Disposable {
}
try {
return JSON.parse(json);
- } catch (err) {
+ } catch {
return {};
}
};