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(sheets-conditional-formatting): support stop-if-true rules (#7945)

wpxp123456ecf7c92da196
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/ar-SA.ts b/packages/sheets-conditional-formatting-ui/src/locale/ar-SA.ts
index f513ffffc0..49b12e7d69 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/ar-SA.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/ar-SA.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'الإيقاف إذا تحقق الشرط',
createRule: 'إنشاء قاعدة',
clear: 'مسح كل القواعد',
range: 'نطاق التطبيق',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/ca-ES.ts b/packages/sheets-conditional-formatting-ui/src/locale/ca-ES.ts
index a181b0745f..4ac6a1a820 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/ca-ES.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/ca-ES.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Atura si és cert',
createRule: 'Crea regla',
clear: 'Esborra totes les regles',
range: 'Aplica rang',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/de-DE.ts b/packages/sheets-conditional-formatting-ui/src/locale/de-DE.ts
index fa1da1953a..82c84b002c 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/de-DE.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/de-DE.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Anhalten, wenn wahr',
createRule: 'Regel erstellen',
clear: 'Alle Regeln löschen',
range: 'Bereich anwenden',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/en-US.ts b/packages/sheets-conditional-formatting-ui/src/locale/en-US.ts
index 4c1cd0b66b..88b1d216a5 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/en-US.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/en-US.ts
@@ -51,6 +51,7 @@ const locale = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Stop If True',
createRule: 'Create Rule',
clear: 'Clear All Rules',
range: 'Apply Range',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/es-ES.ts b/packages/sheets-conditional-formatting-ui/src/locale/es-ES.ts
index e4707c0baa..03cdf057ba 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/es-ES.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/es-ES.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Detener si es verdadero',
createRule: 'Crear regla',
clear: 'Borrar todas las reglas',
range: 'Aplicar rango',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/fa-IR.ts b/packages/sheets-conditional-formatting-ui/src/locale/fa-IR.ts
index 5f8dcaf5ce..7910c07eec 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/fa-IR.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/fa-IR.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'توقف در صورت درست بودن',
createRule: 'ایجاد قانون',
clear: 'پاک کردن همه قوانین',
range: 'اعمال محدوده',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/fr-FR.ts b/packages/sheets-conditional-formatting-ui/src/locale/fr-FR.ts
index 69a31b6d91..b2008d7954 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/fr-FR.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/fr-FR.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Interrompre si vrai',
createRule: 'Créer une règle',
clear: 'Effacer toutes les règles',
range: 'Appliquer la plage',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/id-ID.ts b/packages/sheets-conditional-formatting-ui/src/locale/id-ID.ts
index 0ed241a96c..9e46d757bb 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/id-ID.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/id-ID.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Hentikan Jika Benar',
createRule: 'Buat Aturan',
clear: 'Hapus Semua Aturan',
range: 'Terapkan Rentang',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/it-IT.ts b/packages/sheets-conditional-formatting-ui/src/locale/it-IT.ts
index cfdf1dc96a..47b54810b0 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/it-IT.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/it-IT.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Interrompi se vero',
createRule: 'Crea Regola',
clear: 'Cancella Tutte le Regole',
range: 'Applica Intervallo',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/ja-JP.ts b/packages/sheets-conditional-formatting-ui/src/locale/ja-JP.ts
index aee163a160..d7d7349777 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/ja-JP.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/ja-JP.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '≤',
},
panel: {
+ stopIfTrue: '条件を満たす場合は停止',
createRule: '新しいルール',
clear: 'ルールのクリア',
range: '適用先',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/ko-KR.ts b/packages/sheets-conditional-formatting-ui/src/locale/ko-KR.ts
index 01fc791bb9..1c468c940b 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/ko-KR.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/ko-KR.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '≤',
},
panel: {
+ stopIfTrue: '참이면 중지',
createRule: '규칙 만들기',
clear: '모든 규칙 지우기',
range: '적용 범위',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/pl-PL.ts b/packages/sheets-conditional-formatting-ui/src/locale/pl-PL.ts
index c3f5430e6b..9f52f7adb7 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/pl-PL.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/pl-PL.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Zatrzymaj, gdy warunek jest prawdziwy',
createRule: 'Utwórz regułę',
clear: 'Wyczyść wszystkie reguły',
range: 'Zakres zastosowania',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/pt-BR.ts b/packages/sheets-conditional-formatting-ui/src/locale/pt-BR.ts
index a0f52cb6fa..3c57250222 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/pt-BR.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/pt-BR.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Parar se Verdadeiro',
createRule: 'Criar Regra',
clear: 'Limpar Todas as Regras',
range: 'Aplicar ao Intervalo',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/ru-RU.ts b/packages/sheets-conditional-formatting-ui/src/locale/ru-RU.ts
index aa722faa77..d7b2d5ebc8 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/ru-RU.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/ru-RU.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Остановить, если истина',
createRule: 'Создать правило',
clear: 'Очистить все правила',
range: 'Применить диапазон',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/sk-SK.ts b/packages/sheets-conditional-formatting-ui/src/locale/sk-SK.ts
index 3ad7c10f73..fd9e0ab1f6 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/sk-SK.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/sk-SK.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Zastaviť, ak je pravda',
createRule: 'Vytvoriť pravidlo',
clear: 'Vymazať všetky pravidlá',
range: 'Rozsah použitia',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/vi-VN.ts b/packages/sheets-conditional-formatting-ui/src/locale/vi-VN.ts
index d0c8b3fea0..dd5f30a037 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/vi-VN.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/vi-VN.ts
@@ -52,6 +52,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: 'Dừng nếu đúng',
createRule: 'Tạo quy tắc mới',
clear: 'Xóa tất cả quy tắc',
range: 'Phạm vi áp dụng',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/zh-CN.ts b/packages/sheets-conditional-formatting-ui/src/locale/zh-CN.ts
index eb665a80e6..60c85ea992 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/zh-CN.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/zh-CN.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: '如果为真则停止',
createRule: '新增规则',
clear: '清空所有规则',
range: '应用范围',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/zh-HK.ts b/packages/sheets-conditional-formatting-ui/src/locale/zh-HK.ts
index dbed77ecb7..fbe24d5142 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/zh-HK.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/zh-HK.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: '若為真則停止',
createRule: '新增規則',
clear: '清空所有規則',
range: '應用範圍',
diff --git a/packages/sheets-conditional-formatting-ui/src/locale/zh-TW.ts b/packages/sheets-conditional-formatting-ui/src/locale/zh-TW.ts
index dbed77ecb7..fbe24d5142 100644
--- a/packages/sheets-conditional-formatting-ui/src/locale/zh-TW.ts
+++ b/packages/sheets-conditional-formatting-ui/src/locale/zh-TW.ts
@@ -53,6 +53,7 @@ const locale: typeof enUS = {
lessThanOrEqual: '<=',
},
panel: {
+ stopIfTrue: '若為真則停止',
createRule: '新增規則',
clear: '清空所有規則',
range: '應用範圍',
diff --git a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx
index 073a571b41..9eda5f39be 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/__tests__/ConditionFormattingPanel.spec.tsx
@@ -17,7 +17,7 @@
import type { IRange } from '@univerjs/core';
import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';
import type { Root } from 'react-dom/client';
-import { BooleanNumber, createIdentifier, LocaleService, LocaleType } from '@univerjs/core';
+import { BooleanNumber, createIdentifier, LocaleService, LocaleType, RedoCommand, UndoCommand } from '@univerjs/core';
import { LexerTreeBuilder } from '@univerjs/engine-formula';
import { IRenderManagerService } from '@univerjs/engine-render';
import { SetWorksheetActiveOperation } from '@univerjs/sheets';
@@ -153,6 +153,7 @@ function createPanelTestBed() {
styleRule: 'Style rule',
submit: 'Submit',
cancel: 'Cancel',
+ stopIfTrue: 'Stop If True',
},
operator: {
containsText: 'Contains text',
@@ -181,6 +182,9 @@ function createPanelTestBed() {
},
ruleType: {
highlightCell: 'Highlight cell',
+ dataBar: 'Data bar',
+ colorScale: 'Color scale',
+ iconSet: 'Icon set',
},
preview: {
describe: {
@@ -233,7 +237,7 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
currentTestBed = undefined;
});
- it('adds a text highlight rule to the active selection from the rule editor', async () => {
+ it.each([false, true])('adds a text highlight rule with stopIfTrue=%s only after submission', async (stopIfTrue) => {
currentTestBed = createPanelTestBed();
container = document.createElement('div');
document.body.appendChild(container);
@@ -255,12 +259,20 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
});
const textInput = container.querySelector('input[type="text"]') as HTMLInputElement;
+ const stopCheckbox = Array.from(container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'))
+ .find((input) => input.closest('label')?.textContent === 'Stop If True');
+ expect(stopCheckbox?.checked).toBe(false);
await act(async () => {
writeInput(textInput, 'overdue');
+ if (stopIfTrue) {
+ stopCheckbox!.click();
+ }
await Promise.resolve();
});
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId) ?? []).toEqual([]);
+
await act(async () => {
clickButton(container!, 'Submit');
await Promise.resolve();
@@ -270,7 +282,7 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([
expect.objectContaining({
ranges: [expect.objectContaining(ACTIVE_RANGE)],
- stopIfTrue: false,
+ stopIfTrue,
rule: expect.objectContaining({
type: CFRuleType.highlightCell,
subType: CFSubRuleType.text,
@@ -349,12 +361,18 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
if (!numberInput) {
throw new Error('Number condition input was not rendered');
}
+ const stopCheckbox = Array.from(container.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'))
+ .find((input) => input.closest('label')?.textContent === 'Stop If True');
+ expect(stopCheckbox?.checked).toBe(true);
await act(async () => {
writeInput(numberInput, '25');
+ stopCheckbox!.click();
await Promise.resolve();
});
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)?.[0]).toEqual(originalRule);
+
await act(async () => {
clickButton(container!, 'Submit');
await Promise.resolve();
@@ -365,7 +383,7 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
expect.objectContaining({
cfId: 'cf-active',
ranges: [expect.objectContaining(ACTIVE_RANGE)],
- stopIfTrue: true,
+ stopIfTrue: false,
rule: expect.objectContaining({
type: CFRuleType.highlightCell,
subType: CFSubRuleType.number,
@@ -376,6 +394,74 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
]);
expect(editorExitRequests).toBe(1);
expect(container.textContent).toContain('Show');
+ expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.checked).toBe(false);
+
+ await act(async () => {
+ expect(await currentTestBed!.commandService.executeCommand(UndoCommand.id)).toBe(true);
+ await new Promise((resolve) => setTimeout(resolve, 32));
+ });
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)?.[0]).toEqual(originalRule);
+ expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.checked).toBe(true);
+
+ await act(async () => {
+ expect(await currentTestBed!.commandService.executeCommand(RedoCommand.id)).toBe(true);
+ await new Promise((resolve) => setTimeout(resolve, 32));
+ });
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)?.[0]).toEqual(
+ expect.objectContaining({ stopIfTrue: false, rule: expect.objectContaining({ value: 25 }) })
+ );
+ expect(container.querySelector<HTMLInputElement>('input[type="checkbox"]')?.checked).toBe(false);
+ });
+
+ it.each([
+ ['Data bar', CFRuleType.dataBar],
+ ['Color scale', CFRuleType.colorScale],
+ ['Icon set', CFRuleType.iconSet],
+ ])('hides stopIfTrue when converting a highlight rule to %s and clears it on submission', async (optionText, type) => {
+ currentTestBed = createPanelTestBed();
+ const originalRule = { ...createNumberHighlightRule('cf-active', 10), stopIfTrue: true };
+ await currentTestBed.commandService.executeCommand(AddCfCommand.id, {
+ unitId: currentTestBed.unitId,
+ subUnitId: currentTestBed.subUnitId,
+ rule: originalRule,
+ });
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <ConditionFormattingPanel rule={originalRule} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ container!.querySelector('[data-u-comp="select"]')!
+ .dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, button: 0 }));
+ await Promise.resolve();
+ });
+ const option = Array.from(document.querySelectorAll('[data-slot="dropdown-menu-radio-item"]'))
+ .find((element) => element.textContent === optionText)!;
+ expect(option).toBeDefined();
+ await act(async () => {
+ option.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(container.textContent).not.toContain('Stop If True');
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)?.[0]).toEqual(originalRule);
+ await act(async () => {
+ clickButton(container!, 'Submit');
+ await Promise.resolve();
+ });
+ expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)?.[0]).toEqual(
+ expect.objectContaining({ stopIfTrue: false, rule: expect.objectContaining({ type }) })
+ );
+ expect(container.textContent).toContain('Show');
+ expect(container.textContent).not.toContain('Stop If True');
});
it.each([true, false])('returns to the manager without saving with an editor-exit callback: %s', async (withCallback) => {
@@ -420,6 +506,13 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
expect(container.textContent).toContain('Style type');
expect(editorExitRequests).toBe(0);
+ await act(async () => {
+ const stopCheckbox = Array.from(container!.querySelectorAll<HTMLInputElement>('input[type="checkbox"]'))
+ .find((input) => input.closest('label')?.textContent === 'Stop If True');
+ stopCheckbox!.click();
+ await Promise.resolve();
+ });
+
await act(async () => {
clickButton(container!, 'Cancel');
await Promise.resolve();
@@ -431,6 +524,7 @@ describe('ConditionFormattingPanel and RuleEdit', () => {
expect(currentTestBed.ruleModel.getSubunitRules(currentTestBed.unitId, currentTestBed.subUnitId)).toEqual([
expect.objectContaining({
cfId: 'cf-active',
+ stopIfTrue: false,
rule: expect.objectContaining({
type: CFRuleType.highlightCell,
subType: CFSubRuleType.number,
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx
index ea29a482dc..7297b8b36f 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleEdit.tsx
@@ -23,9 +23,6 @@ import type {
ISetCfCommandParams,
} from '@univerjs/sheets-conditional-formatting';
import type { ComponentType } from 'react';
-import type { LocaleKey } from '../../locale/types';
-import type { IConditionalColorPickerProps } from '../ColorPicker';
-import type { IStyleEditorProps } from './rule-edit/type';
import {
ICommandService,
InterceptorManager,
@@ -33,7 +30,7 @@ import {
LocaleService,
UniverInstanceType,
} from '@univerjs/core';
-import { Button, Select } from '@univerjs/design';
+import { Button, Checkbox, Select } from '@univerjs/design';
import { deserializeRangeWithSheet, serializeRange } from '@univerjs/engine-formula';
import {
RemoveSheetMutation,
@@ -51,6 +48,9 @@ import {
import { FormulaEditor, RangeSelector } from '@univerjs/sheets-formula-ui';
import { useDependency } from '@univerjs/ui';
import { useEffect, useMemo, useRef, useState } from 'react';
+import type { LocaleKey } from '../../locale/types';
+import type { IConditionalColorPickerProps } from '../ColorPicker';
+import type { IStyleEditorProps } from './rule-edit/type';
import { ColorScaleStyleEditor } from './rule-edit/ColorScale';
import { DataBarStyleEditor } from './rule-edit/DataBar';
import { FormulaStyleEditor } from './rule-edit/Formula';
@@ -89,6 +89,7 @@ export const RuleEdit = (props: IRuleEditProps) => {
const subUnitId = getSubUnitId(univerInstanceService);
const [errorText, setErrorText] = useState<string | undefined>(undefined);
+ const [stopIfTrue, setStopIfTrue] = useState(!!props.rule?.stopIfTrue);
const rangeResult = useRef<IRange[]>(props.rule?.ranges ?? []);
const rangeSelectorTouched = useRef(false);
@@ -186,6 +187,9 @@ export const RuleEdit = (props: IRuleEditProps) => {
}
}
}, [ruleType]);
+ const supportsStopIfTrue = StyleEditor === HighlightCellStyleEditor
+ || StyleEditor === RankStyleEditor
+ || StyleEditor === FormulaStyleEditor;
useEffect(() => {
// If the child table which the rule being edited is deleted, exit edit mode
@@ -244,12 +248,12 @@ export const RuleEdit = (props: IRuleEditProps) => {
}
let rule = {} as IConditionFormattingRule;
if (props.rule && props.rule.cfId) {
- rule = { ...props.rule, ranges, rule: result };
+ rule = { ...props.rule, ranges, rule: result, stopIfTrue: result.type === CFRuleType.highlightCell && stopIfTrue };
commandService.executeCommand(SetCfCommand.id, { unitId, subUnitId, rule } as ISetCfCommandParams);
props.onCancel();
} else {
const cfId = conditionalFormattingRuleModel.createCfId(unitId, subUnitId);
- rule = { cfId, ranges, rule: result, stopIfTrue: false };
+ rule = { cfId, ranges, rule: result, stopIfTrue: result.type === CFRuleType.highlightCell && stopIfTrue };
commandService.executeCommand(AddCfCommand.id, { unitId, subUnitId, rule } as IAddCfCommandParams);
props.onCancel();
}
@@ -320,6 +324,13 @@ export const RuleEdit = (props: IRuleEditProps) => {
ColorPickerComponent={ColorPickerComponent}
FormulaEditorComponent={FormulaEditorComponent}
/>
+ {supportsStopIfTrue && (
+ <div className="univer-mt-4">
+ <Checkbox checked={stopIfTrue} onChange={(checked) => setStopIfTrue(!!checked)}>
+ {localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.stopIfTrue')}
+ </Checkbox>
+ </div>
+ )}
<div className="univer-mt-4 univer-flex univer-justify-end univer-gap-2">
<Button onClick={handleCancel}>{localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.cancel')}</Button>
<Button variant="primary" onClick={handleSubmit}>
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx
index 0631285a94..456f9de355 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/RuleList.tsx
@@ -22,7 +22,6 @@ import type {
IMoveCfCommandParams,
} from '@univerjs/sheets-conditional-formatting';
import type { ComponentType } from 'react';
-import type { LocaleKey } from '../../locale/types';
import {
ICommandService,
Injector,
@@ -31,7 +30,7 @@ import {
Rectangle,
UniverInstanceType,
} from '@univerjs/core';
-import { clsx, DraggableList, Select, Tooltip } from '@univerjs/design';
+import { Checkbox, clsx, DraggableList, Select, Tooltip } from '@univerjs/design';
import { serializeRange } from '@univerjs/engine-formula';
import { DeleteIcon, GripVerticalIcon, IncreaseIcon } from '@univerjs/icons';
import {
@@ -42,6 +41,7 @@ import {
} from '@univerjs/sheets';
import {
AddConditionalRuleMutation,
+ CFRuleType,
ClearWorksheetCfCommand,
ConditionalFormattingRuleModel,
DeleteCfCommand,
@@ -54,6 +54,7 @@ import { useHighlightRange } from '@univerjs/sheets-ui';
import { useDependency, useObservable } from '@univerjs/ui';
import { useMemo, useState } from 'react';
import { debounceTime, filter, map, merge, Observable, share, startWith } from 'rxjs';
+import type { LocaleKey } from '../../locale/types';
import { ConditionalFormattingI18nController } from '../../controllers/cf.i18n.controller';
import { getRuleDescribe } from '../../utils/get-rule-describe';
import { ConditionalFormattingRulePreview } from '../ConditionalFormattingRulePreview';
@@ -292,8 +293,8 @@ export function RuleList(props: IRuleListProps) {
itemRender={(rule) => (
<div
className={clsx(`
- univer-group univer-relative univer-flex univer-items-center univer-justify-between
- univer-rounded univer-py-2 univer-pl-5 univer-pr-8
+ univer-group univer-relative univer-flex univer-flex-wrap univer-items-center
+ univer-justify-between univer-rounded univer-py-2 univer-pl-5 univer-pr-8
hover:univer-bg-gray-100
rtl:univer-pl-8 rtl:univer-pr-5
dark:hover:!univer-bg-gray-700
@@ -342,6 +343,18 @@ export function RuleList(props: IRuleListProps) {
<div>
<ConditionalFormattingRulePreview rule={rule.rule} />
</div>
+ {rule.rule.type === CFRuleType.highlightCell && (
+ <div className="univer-pointer-events-none univer-mt-2 univer-w-full">
+ <Checkbox
+ className="univer-max-w-full"
+ contentClassName="univer-min-w-0"
+ checked={!!rule.stopIfTrue}
+ disabled
+ >
+ {localeService.t<LocaleKey>('sheets-conditional-formatting-ui.panel.stopIfTrue')}
+ </Checkbox>
+ </div>
+ )}
<div
className={clsx(`
univer-absolute univer-right-1 univer-hidden univer-size-6 univer-cursor-pointer
diff --git a/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx b/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx
index a0db80d471..a3dcc896e3 100644
--- a/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx
+++ b/packages/sheets-conditional-formatting-ui/src/views/panel/__tests__/RuleList.spec.tsx
@@ -83,7 +83,7 @@ function createNumberHighlightRule(cfId: string, range: IRange, value: number):
};
}
-async function createRuleListTestBed() {
+async function createRuleListTestBed(stopIfTrue = false) {
const testBed = createCfUiTestBed();
testBed.injector.add([ConditionalFormattingI18nController]);
@@ -121,6 +121,7 @@ async function createRuleListTestBed() {
selectedRange: 'Selected range',
createRule: 'Create rule',
clear: 'Clear rules',
+ stopIfTrue: 'Stop If True',
},
preview: {
describe: {
@@ -135,7 +136,7 @@ async function createRuleListTestBed() {
await testBed.commandService.executeCommand(AddCfCommand.id, {
unitId: testBed.unitId,
subUnitId: testBed.subUnitId,
- rule: createNumberHighlightRule('cf-active', ACTIVE_RANGE, 10),
+ rule: { ...createNumberHighlightRule('cf-active', ACTIVE_RANGE, 10), stopIfTrue },
});
await testBed.commandService.executeCommand(AddCfCommand.id, {
unitId: testBed.unitId,
@@ -162,6 +163,40 @@ describe('RuleList', () => {
currentTestBed = undefined;
});
+ it.each([false, true])('opens the rule from its read-only stopIfTrue=%s display without toggling it', async (stopIfTrue) => {
+ currentTestBed = await createRuleListTestBed(stopIfTrue);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ const openedRuleIds: string[] = [];
+
+ await act(async () => {
+ root!.render(
+ <RediContext.Provider value={{ injector: currentTestBed!.injector }}>
+ <RuleList onClick={(rule) => openedRuleIds.push(rule.cfId)} onCreate={() => undefined} />
+ </RediContext.Provider>
+ );
+ await Promise.resolve();
+ });
+
+ const row = container.querySelector('[data-draggable-list-item-id="cf-active"]')!;
+ const label = row.querySelector('[data-u-comp="checkbox"]')!;
+ const checkbox = label.querySelector('input')!;
+ expect(checkbox.checked).toBe(stopIfTrue);
+ expect(checkbox.disabled).toBe(true);
+
+ // The display's icon and label both belong to the surrounding rule's edit target.
+ const target = stopIfTrue ? label.lastElementChild! : checkbox.parentElement!.lastElementChild!;
+ await act(async () => {
+ target.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await Promise.resolve();
+ });
+
+ expect(openedRuleIds).toEqual(['cf-active']);
+ expect(checkbox.checked).toBe(stopIfTrue);
+ expect(currentTestBed.ruleModel.getRule(currentTestBed.unitId, currentTestBed.subUnitId, 'cf-active')?.stopIfTrue).toBe(stopIfTrue);
+ });
+
it('shows only conditional formatting rules intersecting the current sheet selection in selected-range mode', async () => {
currentTestBed = await createRuleListTestBed();
container = document.createElement('div');
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 6611240fe3..5fc8eed908 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
@@ -14,7 +14,9 @@
* limitations under the License.
*/
-import type { IStyleData, Nullable } from '@univerjs/core';
+import type { Nullable } from '@univerjs/core';
+import { CellValueType, dateKit, Range, Tools } from '@univerjs/core';
+import { ERROR_TYPE_SET, FormulaResultStatus } from '@univerjs/engine-formula';
import type {
IAverageHighlightCell,
IFormulaHighlightCell,
@@ -25,8 +27,6 @@ import type {
ITimePeriodHighlightCell,
} from '../type';
import type { IContext } from './base-calculate-unit';
-import { CellValueType, dateKit, Range, Tools } from '@univerjs/core';
-import { ERROR_TYPE_SET, FormulaResultStatus } from '@univerjs/engine-formula';
import { CFNumberOperator, CFSubRuleType, CFTextOperator, CFTimePeriodOperator } from '../../base/const';
import { ConditionalFormattingFormulaService } from '../../services/conditional-formatting-formula.service';
import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';
@@ -54,7 +54,7 @@ const sortRangesByTopLeft = <T extends { startRow: number; startColumn: number }
return a.startColumn - b.startColumn;
});
-export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConfig>, Nullable<IStyleData>> {
+export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConfig>, boolean> {
// eslint-disable-next-line max-lines-per-function
override preComputing(row: number, col: number, context: IContext): void {
const ruleConfig = context.rule.rule as IHighlightCell;
@@ -430,7 +430,6 @@ export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConf
}
}
};
- const result = run();
- return result ? ruleConfig.style : {};
+ return !!run();
}
}
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 291e855d10..a3911148cd 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
@@ -15,11 +15,11 @@
*/
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 } from '@univerjs/core';
import { Subject } from 'rxjs';
import { bufferTime, filter, map } from 'rxjs/operators';
+import type { BaseCalculateUnit, IContext } from './calculate-unit-v2/base-calculate-unit';
+import type { IConditionFormattingRule } from './type';
import { CFRuleType, CFSubRuleType } from '../base/const';
import { ConditionalFormattingFormulaService } from '../services/conditional-formatting-formula.service';
import { ColorScaleCalculateUnit } from './calculate-unit-v2/color-scale-calculate-unit';
@@ -38,7 +38,7 @@ export class ConditionalFormattingViewModel extends Disposable {
/**
* 1nd-level cache
*/
- private _cellCache = new LRUMap<string, { cfId: string; result: any; priority: number }[]>(CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH);
+ private _cellCache = new LRUMap<string, { cfId: string; result: any; matched: boolean; priority: number }[]>(CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH);
private _markDirty$ = new Subject<{ cfId: string; unitId: string; subUnitId: string; isImmediately?: boolean }>();
private _cacheClear$ = new Subject<void>();
@@ -98,10 +98,16 @@ export class ConditionalFormattingViewModel extends Disposable {
if (!calculateUnit) {
return null;
}
- return {
- cfId: rule.cfId,
- result: calculateUnit.getCell(row, col),
- };
+ const result = calculateUnit.getCell(row, col);
+ if (rule.rule.type === CFRuleType.highlightCell) {
+ const matched = result === true;
+ let style = result;
+ if (result != null) {
+ style = matched ? rule.rule.style : {};
+ }
+ return { cfId: rule.cfId, result: style, matched };
+ }
+ return { cfId: rule.cfId, result, matched: !!result };
}).filter((e) => !!e).map((e, index) => ({ ...e, priority: index }));
return result;
}
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts
index ec31857bda..e67fd282c5 100644
--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting-style-composer.service.spec.ts
@@ -14,127 +14,239 @@
* limitations under the License.
*/
-import { Injector } from '@univerjs/core';
-import { Subject } from 'rxjs';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { CFRuleType } from '../../base/const';
-import { ConditionalFormattingRuleModel } from '../../models/conditional-formatting-rule-model';
-import { ConditionalFormattingViewModel } from '../../models/conditional-formatting-view-model';
+import type { ICellData } from '@univerjs/core';
+import { BooleanNumber, CellValueType } from '@univerjs/core';
+import {
+ ErrorType,
+ OtherFormulaMarkDirty,
+ SetFormulaCalculationResultMutation,
+ SetOtherFormulaMutation,
+} from '@univerjs/engine-formula';
+import { SetRangeValuesMutation } from '@univerjs/sheets';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import type { IConditionalFormattingRuleConfig, IConditionFormattingRule, INumberHighlightCell } from '../../models/type';
+import { CFNumberOperator, CFRuleType, CFSubRuleType, CFValueType } from '../../base/const';
+import { AddConditionalRuleMutation } from '../../commands/mutations/add-conditional-rule.mutation';
+import { MoveConditionalRuleMutation } from '../../commands/mutations/move-conditional-rule.mutation';
+import { SetConditionalRuleMutation } from '../../commands/mutations/set-conditional-rule.mutation';
+import { createTestBed } from '../../models/calculate-unit-v2/__tests__/test.util';
+import { IIconSetType } from '../../models/icon-map';
+import { ConditionalFormattingFormulaService } from '../conditional-formatting-formula.service';
import { ConditionalFormattingStyleComposer } from '../conditional-formatting-style-composer.service';
-describe('ConditionalFormattingStyleComposer', () => {
- let service: ConditionalFormattingStyleComposer;
- const rules = new Map<string, unknown>();
- let cellCfs: Array<{ cfId: string; result: unknown; priority: number }>;
- let ruleChange$: Subject<void>;
- let markDirty$: Subject<void>;
- let cacheClear$: Subject<void>;
- const getCellCfs = vi.fn(() => cellCfs);
-
- class TestConditionalFormattingRuleModel {
- $ruleChange = ruleChange$;
-
- getRule(_unitId: string, _subUnitId: string, cfId: string) {
- return rules.get(cfId);
- }
- }
+const RANGES = [{ startRow: 0, endRow: 0, startColumn: 0, endColumn: 2 }];
- class TestConditionalFormattingViewModel {
- markDirty$ = markDirty$;
- cacheClear$ = cacheClear$;
+const createHighlightConfig = (style: INumberHighlightCell['style'] = {}, value = 0): INumberHighlightCell => ({
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value,
+ style,
+});
- getCellCfs = getCellCfs;
- }
+const COLOR_SCALE: IConditionalFormattingRuleConfig = {
+ type: CFRuleType.colorScale,
+ config: [
+ { index: 0, color: '#ffeeaa', value: { type: CFValueType.num, value: 0 } },
+ { index: 1, color: '#ffeeaa', value: { type: CFValueType.num, value: 10 } },
+ ],
+};
+const DATA_BAR: IConditionalFormattingRuleConfig = {
+ type: CFRuleType.dataBar,
+ isShowValue: false,
+ config: {
+ min: { type: CFValueType.num, value: 0 },
+ max: { type: CFValueType.num, value: 10 },
+ isGradient: false,
+ positiveColor: '#38bdf8',
+ nativeColor: '#ff0000',
+ },
+};
+const ICON_SET: IConditionalFormattingRuleConfig = {
+ type: CFRuleType.iconSet,
+ isShowValue: false,
+ config: [{
+ operator: CFNumberOperator.greaterThanOrEqual,
+ value: { type: CFValueType.num, value: 0 },
+ iconType: IIconSetType.threeArrows,
+ iconId: '0',
+ }],
+};
+
+// Exercise the calculation, viewport cache, and composer together so empty styles cannot hide a match.
+describe('ConditionalFormattingStyleComposer', () => {
+ let testBed: ReturnType<typeof createTestBed>;
+ let service: ConditionalFormattingStyleComposer;
beforeEach(() => {
- rules.clear();
- cellCfs = [];
- ruleChange$ = new Subject();
- markDirty$ = new Subject();
- cacheClear$ = new Subject();
- getCellCfs.mockClear();
- const injector = new Injector();
- injector.add([ConditionalFormattingRuleModel, { useClass: TestConditionalFormattingRuleModel as never }]);
- injector.add([ConditionalFormattingViewModel, { useClass: TestConditionalFormattingViewModel as never }]);
- injector.add([ConditionalFormattingStyleComposer]);
- service = injector.get(ConditionalFormattingStyleComposer);
+ vi.useFakeTimers();
+ testBed = createTestBed();
+ testBed.getConditionalFormattingService();
+ service = testBed.get(ConditionalFormattingStyleComposer);
+ });
+
+ afterEach(() => {
+ testBed.univer.dispose();
+ vi.useRealTimers();
});
+ const addRule = (cfId: string, rule: IConditionalFormattingRuleConfig, stopIfTrue = false) => {
+ const wrapper: IConditionFormattingRule = { cfId, ranges: RANGES, rule, stopIfTrue };
+ testBed.commandService.syncExecuteCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule: wrapper,
+ });
+ return wrapper;
+ };
+
+ const compose = () => service.composeStyle(testBed.unitId, testBed.subUnitId, 0, 1);
+
it('merges matched conditional styles in rule priority order', () => {
- rules.set('color-scale', { stopIfTrue: false, rule: { type: CFRuleType.colorScale } });
- rules.set('highlight', { stopIfTrue: false, rule: { type: CFRuleType.highlightCell } });
- cellCfs = [
- { cfId: 'color-scale', result: '#ffeeaa', priority: 1 },
- { cfId: 'highlight', result: { cl: { rgb: '#333333' } }, priority: 2 },
- ];
+ addRule('highlight', createHighlightConfig({ cl: { rgb: '#333333' }, bg: { rgb: '#ff0000' } }));
+ addRule('color-scale', COLOR_SCALE);
- expect(service.composeStyle('book-1', 'sheet-1', 1, 1)).toEqual({
- style: { cl: { rgb: '#333333' }, bg: { rgb: '#ffeeaa' } },
+ expect(compose()).toEqual({
+ style: { cl: { rgb: '#333333' }, bg: { rgb: 'rgb(255,238,170)' } },
});
});
it('composes highlight, data bar, and icon set rules on the same cell', () => {
- const dataBar = {
- color: '#38bdf8',
- isGradient: false,
- isShowValue: true,
- startPoint: 0,
- value: 50,
- };
- const iconSet = {
- iconId: '0',
- iconType: '3Arrows',
- isShowValue: true,
- };
- rules.set('highlight', { stopIfTrue: false, rule: { type: CFRuleType.highlightCell } });
- rules.set('data-bar', { stopIfTrue: false, rule: { type: CFRuleType.dataBar } });
- rules.set('icon-set', { stopIfTrue: false, rule: { type: CFRuleType.iconSet } });
- cellCfs = [
- { cfId: 'icon-set', result: iconSet, priority: 1 },
- { cfId: 'data-bar', result: dataBar, priority: 2 },
- { cfId: 'highlight', result: { bg: { rgb: '#fff7cc' } }, priority: 3 },
- ];
+ addRule('highlight', createHighlightConfig({ bg: { rgb: '#fff7cc' } }));
+ addRule('data-bar', DATA_BAR);
+ addRule('icon-set', ICON_SET);
- expect(service.composeStyle('book-1', 'sheet-1', 1, 1)).toEqual({
+ expect(compose()).toEqual({
style: { bg: { rgb: '#fff7cc' } },
- dataBar,
- iconSet,
- isShowValue: true,
+ dataBar: {
+ color: '#38bdf8',
+ isGradient: false,
+ isShowValue: false,
+ startPoint: 0,
+ value: expect.closeTo(20),
+ },
+ iconSet: { iconId: '0', iconType: IIconSetType.threeArrows, isShowValue: false },
+ isShowValue: false,
});
});
- it('stops evaluating lower-priority rules after a matched stop-if-true rule', () => {
- rules.set('stop', { stopIfTrue: true, rule: { type: CFRuleType.highlightCell } });
- rules.set('ignored', { stopIfTrue: false, rule: { type: CFRuleType.colorScale } });
- cellCfs = [
- { cfId: 'stop', result: { bg: { rgb: '#ff0000' } }, priority: 1 },
- { cfId: 'ignored', result: '#00ff00', priority: 2 },
- ];
+ it.each([
+ createHighlightConfig({ bg: { rgb: '#ff0000' } }),
+ COLOR_SCALE,
+ DATA_BAR,
+ ICON_SET,
+ ])('suppresses lower-priority $type after an empty-style stop rule matches', async (config) => {
+ addRule('lower', config);
+ expect(compose()).not.toEqual({ style: {} });
+ addRule('stop', createHighlightConfig(), true);
+ addRule('higher', createHighlightConfig({ cl: { rgb: '#333333' } }));
+ await vi.advanceTimersByTimeAsync(100);
+
+ expect(compose()).toEqual({ style: { cl: { rgb: '#333333' } } });
+ expect(testBed.getConditionalFormattingViewModel().getCellCfs(testBed.unitId, testBed.subUnitId, 0, 1))
+ .toContainEqual(expect.objectContaining({ cfId: 'stop', result: {}, matched: true }));
+ });
- expect(service.composeStyle('book-1', 'sheet-1', 1, 1)).toEqual({
- style: { bg: { rgb: '#ff0000' } },
- });
+ it.each([
+ { value: 100, stopIfTrue: true },
+ { value: 0, stopIfTrue: false },
+ ])('continues after an empty-style rule with threshold $value and stopIfTrue=$stopIfTrue', ({ value, stopIfTrue }) => {
+ addRule('lower', createHighlightConfig({ bg: { rgb: '#00ff00' } }));
+ addRule('stop', createHighlightConfig({}, value), stopIfTrue);
+
+ expect(compose()).toEqual({ style: { bg: { rgb: '#00ff00' } } });
});
- it('reuses the composed result until conditional formatting changes', () => {
- rules.set('highlight', { stopIfTrue: false, rule: { type: CFRuleType.highlightCell } });
- cellCfs = [{ cfId: 'highlight', result: { cl: { rgb: '#333333' } }, priority: 1 }];
- const first = service.composeStyle('book-1', 'sheet-1', 1, 1);
- const second = service.composeStyle('book-1', 'sheet-1', 1, 1);
+ it('stops lower-priority rules after a nonempty-style rule matches', () => {
+ addRule('lower', createHighlightConfig({ cl: { rgb: '#333333' } }));
+ addRule('stop', createHighlightConfig({ bg: { rgb: '#ff0000' } }), true);
- expect(second).toBe(first);
- expect(getCellCfs).toHaveBeenCalledOnce();
+ expect(compose()).toEqual({ style: { bg: { rgb: '#ff0000' } } });
+ });
- markDirty$.next();
- service.composeStyle('book-1', 'sheet-1', 1, 1);
- expect(getCellCfs).toHaveBeenCalledTimes(2);
+ it('refreshes the stop state after changing cell values and rule order', async () => {
+ testBed.commandService.registerCommand(SetRangeValuesMutation);
+ addRule('lower', createHighlightConfig({ bg: { rgb: '#00ff00' } }));
+ addRule('stop', createHighlightConfig({}, 1), true);
+ expect(compose()).toEqual({ style: {} });
- ruleChange$.next();
- service.composeStyle('book-1', 'sheet-1', 1, 1);
- expect(getCellCfs).toHaveBeenCalledTimes(3);
+ testBed.commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ cellValue: { 0: { 1: { v: 1, t: CellValueType.NUMBER } } },
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ expect(compose()).toEqual({ style: { bg: { rgb: '#00ff00' } } });
+ expect(testBed.getConditionalFormattingViewModel().getCellCfs(testBed.unitId, testBed.subUnitId, 0, 1))
+ .toContainEqual(expect.objectContaining({ cfId: 'stop', result: {}, matched: false }));
+
+ testBed.commandService.syncExecuteCommand(SetRangeValuesMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ cellValue: { 0: { 1: { v: 2, t: CellValueType.NUMBER } } },
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ expect(compose()).toEqual({ style: {} });
+
+ testBed.commandService.syncExecuteCommand(MoveConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ start: { id: 'lower', type: 'self' },
+ end: { id: 'stop', type: 'before' },
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ expect(compose()).toEqual({ style: { bg: { rgb: '#00ff00' } } });
+ });
+
+ it('reuses composed results and invalidates them after editing stopIfTrue', async () => {
+ addRule('lower', createHighlightConfig({ bg: { rgb: '#00ff00' } }));
+ const stop = addRule('stop', createHighlightConfig(), true);
+ const first = compose();
+ expect(compose()).toBe(first);
+ expect(first).toEqual({ style: {} });
+
+ testBed.commandService.syncExecuteCommand(SetConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule: { ...stop, stopIfTrue: false },
+ });
+ await vi.advanceTimersByTimeAsync(100);
+ expect(compose()).toEqual({ style: { bg: { rgb: '#00ff00' } } });
+ });
- cacheClear$.next();
- service.composeStyle('book-1', 'sheet-1', 1, 1);
- expect(getCellCfs).toHaveBeenCalledTimes(4);
+ it('updates an empty-style formula stop rule when asynchronous results arrive', () => {
+ testBed.commandService.registerCommand(SetFormulaCalculationResultMutation);
+ testBed.commandService.registerCommand(SetOtherFormulaMutation);
+ testBed.commandService.registerCommand(OtherFormulaMarkDirty);
+ addRule('lower', createHighlightConfig({ bg: { rgb: '#00ff00' } }));
+ addRule('stop', {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.formula,
+ value: '=A1>0',
+ style: {},
+ }, true);
+ expect(compose()).toEqual({ style: { bg: { rgb: '#00ff00' } } });
+ expect(testBed.getConditionalFormattingViewModel().getCellCfs(testBed.unitId, testBed.subUnitId, 0, 1))
+ .toContainEqual(expect.objectContaining({ cfId: 'stop', result: undefined, matched: false }));
+
+ const formula = testBed.get(ConditionalFormattingFormulaService)
+ .getSubUnitFormulaMap(testBed.unitId, testBed.subUnitId)
+ ?.getValues()[0];
+ expect(formula).toBeDefined();
+ const results: Array<{ cell: ICellData; stopped: boolean }> = [
+ { cell: { t: CellValueType.BOOLEAN, v: BooleanNumber.TRUE }, stopped: true },
+ { cell: { t: CellValueType.BOOLEAN, v: BooleanNumber.FALSE }, stopped: false },
+ { cell: { t: CellValueType.NUMBER, v: 1 }, stopped: true },
+ { cell: { t: CellValueType.STRING, v: ErrorType.DIV_BY_ZERO }, stopped: false },
+ ];
+ for (const { cell, stopped } of results) {
+ testBed.commandService.syncExecuteCommand(SetFormulaCalculationResultMutation.id, {
+ unitData: {},
+ unitOtherData: {
+ [testBed.unitId]: { [testBed.subUnitId]: { [formula!.formulaId]: { 0: { 1: [[cell]] } } } },
+ },
+ });
+ expect(compose()).toEqual(stopped ? { style: {} } : { style: { bg: { rgb: '#00ff00' } } });
+ }
});
});
diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts
index a86f671322..c133b399fb 100644
--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts
+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts
@@ -14,20 +14,27 @@
* limitations under the License.
*/
+import type { Workbook } from '@univerjs/core';
import { ICommandService, Injector, IResourceManagerService, IUniverInstanceService } from '@univerjs/core';
+import { RemoveOtherFormulaMutation } from '@univerjs/engine-formula';
import {
CopySheetCommand,
InsertColMutation,
InsertRowMutation,
+ InsertSheetMutation,
MoveColsMutation,
MoveRangeMutation,
MoveRowsMutation,
RemoveSheetCommand,
+ RemoveSheetMutation,
ReorderRangeMutation,
SetRangeValuesMutation,
SheetInterceptorService,
} from '@univerjs/sheets';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { CFNumberOperator, CFRuleType, CFSubRuleType } from '../../base/const';
+import { AddConditionalRuleMutation } from '../../commands/mutations/add-conditional-rule.mutation';
+import { createTestBed } from '../../models/calculate-unit-v2/__tests__/test.util';
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';
@@ -252,3 +259,72 @@ describe('ConditionalFormattingService', () => {
expect(markRuleDirty.mock.calls.length).toBeGreaterThanOrEqual(6);
});
});
+
+it('preserves stop-if-true priority when copying a sheet, undoing, and redoing', async () => {
+ vi.useFakeTimers();
+ const testBed = createTestBed();
+ try {
+ const service = testBed.getConditionalFormattingService();
+ const ruleModel = testBed.getConditionalFormattingRuleModel();
+ const workbook = testBed.get(IUniverInstanceService).getUnit<Workbook>(testBed.unitId)!;
+ testBed.commandService.registerCommand(InsertSheetMutation);
+ testBed.commandService.registerCommand(RemoveSheetMutation);
+ testBed.commandService.registerCommand(RemoveOtherFormulaMutation);
+ const ranges = [{ startRow: 0, endRow: 0, startColumn: 1, endColumn: 1 }];
+ const base = {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.number,
+ operator: CFNumberOperator.greaterThan,
+ value: 0,
+ };
+ for (const rule of [
+ { cfId: 'red', ranges, stopIfTrue: false, rule: { ...base, style: { bg: { rgb: '#ff0000' } } } },
+ { cfId: 'stop', ranges, stopIfTrue: true, rule: { ...base, style: {} } },
+ { cfId: 'higher', ranges, stopIfTrue: false, rule: { ...base, style: { cl: { rgb: '#333333' } } } },
+ ]) {
+ testBed.commandService.syncExecuteCommand(AddConditionalRuleMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: testBed.subUnitId,
+ rule,
+ });
+ }
+ const source = service.composeStyle(testBed.unitId, testBed.subUnitId, 0, 1);
+ expect(source).toEqual({ style: { cl: { rgb: '#333333' } } });
+ const sourceRules = ruleModel.getSubunitRules(testBed.unitId, testBed.subUnitId)!;
+ const targetSubUnitId = 'copied';
+ const insertParams = {
+ unitId: testBed.unitId,
+ index: 1,
+ sheet: { ...workbook.getActiveSheet()!.getConfig(), id: targetSubUnitId, name: targetSubUnitId },
+ };
+ const { redos, undos } = testBed.get(SheetInterceptorService).onCommandExecute({
+ id: CopySheetCommand.id,
+ params: { unitId: testBed.unitId, subUnitId: testBed.subUnitId, targetSubUnitId },
+ });
+ for (let attempt = 0; attempt < 2; attempt++) {
+ expect(testBed.commandService.syncExecuteCommand(InsertSheetMutation.id, insertParams)).toBe(true);
+ for (const mutation of redos) {
+ expect(testBed.commandService.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);
+ }
+ await vi.advanceTimersByTimeAsync(100);
+ expect(service.composeStyle(testBed.unitId, targetSubUnitId, 0, 1)).toEqual(source);
+ const copiedRules = ruleModel.getSubunitRules(testBed.unitId, targetSubUnitId)!;
+ expect(copiedRules.map(({ cfId, ...rule }) => rule))
+ .toEqual(sourceRules.map(({ cfId, ...rule }) => rule));
+ expect(copiedRules.every((rule) => !sourceRules.some((sourceRule) => sourceRule.cfId === rule.cfId))).toBe(true);
+ expect(sourceRules.map((rule) => rule.cfId)).toEqual(['higher', 'stop', 'red']);
+
+ expect(testBed.commandService.syncExecuteCommand(RemoveSheetMutation.id, {
+ unitId: testBed.unitId,
+ subUnitId: targetSubUnitId,
+ })).toBe(true);
+ for (const mutation of undos) {
+ expect(testBed.commandService.syncExecuteCommand(mutation.id, mutation.params)).toBe(true);
+ }
+ expect(ruleModel.getSubunitRules(testBed.unitId, targetSubUnitId)).toEqual([]);
+ }
+ } finally {
+ testBed.univer.dispose();
+ vi.useRealTimers();
+ }
+});
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
index 495a0f59a3..ca076dad9d 100644
--- 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
@@ -14,9 +14,9 @@
* limitations under the License.
*/
+import { Disposable, Inject, LRUMap, merge } from '@univerjs/core';
import type { IConditionFormattingRule, IHighlightCell } from '../models/type';
import type { IDataBarCellData, IDataBarRenderParams, IIconSetCellData, IIconSetRenderParams } from '../render/type';
-import { Disposable, Inject, LRUMap, merge } from '@univerjs/core';
import { CFRuleType } from '../base/const';
import { ConditionalFormattingRuleModel } from '../models/conditional-formatting-rule-model';
import { CONDITIONAL_FORMATTING_VIEWPORT_CACHE_LENGTH, ConditionalFormattingViewModel } from '../models/conditional-formatting-view-model';
@@ -70,7 +70,7 @@ export class ConditionalFormattingStyleComposer extends Disposable {
matchedRules.push({ rule, cacheItem });
- if (stopIfTrueIndex === -1 && rule.stopIfTrue && this._isRuleMatched(rule, cacheItem.result)) {
+ if (stopIfTrueIndex === -1 && rule.stopIfTrue && cacheItem.matched) {
stopIfTrueIndex = matchedRules.length - 1;
}
}
@@ -132,12 +132,4 @@ export class ConditionalFormattingStyleComposer extends Disposable {
}
}
}
-
- 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 0ab9a7b8db..73d18b6018 100644
--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts
@@ -28,9 +28,6 @@ import type {
IReorderRangeMutationParams,
ISetRangeValuesMutationParams,
} 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 { IRuleModelJson } from '../models/type';
import {
Disposable,
ICommandService,
@@ -57,6 +54,9 @@ import {
SetRangeValuesMutation,
SheetInterceptorService,
} 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 { IRuleModelJson } from '../models/type';
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';
@@ -192,7 +192,8 @@ export class ConditionalFormattingService extends Disposable {
const redos: IMutationInfo[] = [];
const undos: IMutationInfo[] = [];
- ruleList.forEach((item) => {
+ // AddRule prepends, so copy lower-priority rules first.
+ ruleList.slice().reverse().forEach((item) => {
const params: IAddConditionalRuleMutationParams = {
unitId,
subUnitId: targetSubUnitId,