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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
fix(conditional-formatting): fixed a performance issue during the initialization phase of the conditional format (#2919)
Gpound.liu8ddc701b477a
diff --git a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsxindex f6c1eb7c97..7b187cdbeb 100644--- a/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx+++ b/packages/sheets-conditional-formatting-ui/src/components/panel/rule-edit/dataBar.tsx@@ -19,7 +19,7 @@ import { Checkbox, InputNumber, Radio, RadioGroup, Select } from '@univerjs/desiimport { createInternalEditorID, IUniverInstanceService, LocaleService, UniverInstanceType, useDependency } from '@univerjs/core';import type { Workbook } from '@univerjs/core';import { TextEditor } from '@univerjs/ui';-import { CFRuleType, CFValueType, createDefaultValueByValueType, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';+import { CFRuleType, CFValueType, createDefaultValueByValueType, defaultDataBarNativeColor, defaultDataBarPositiveColor, SHEET_CONDITIONAL_FORMATTING_PLUGIN } from '@univerjs/sheets-conditional-formatting';import type { IConditionalFormattingRuleConfig, IValueConfig } from '@univerjs/sheets-conditional-formatting';import { ColorPicker } from '../../color-picker';import stylesBase from '../index.module.less';@@ -29,7 +29,7 @@ import type { IStyleEditorProps } from './type';const createOptionItem = (text: CFValueType, localeService: LocaleService) => ({ label: localeService.t(`sheet.cf.valueType.${text}`), value: text });-const InputText = (props: { disabled?: boolean; id: string; className: string; type: CFValueType;value: string | number;onChange: (v: string | number) => void }) => {+const InputText = (props: { disabled?: boolean; id: string; className: string; type: CFValueType; value: string | number; onChange: (v: string | number) => void }) => {const { onChange, className, value, type, id, disabled = false } = props;const univerInstanceService = useDependency(IUniverInstanceService);const unitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!.getUnitId();@@ -89,18 +89,16 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {return rule.config?.isGradient ? '1' : '0';});const [positiveColor, positiveColorSet] = useState(() => {- const defaultV = '#abd91a';if (!rule) {- return defaultV;+ return defaultDataBarPositiveColor;}- return rule.config?.positiveColor || defaultV;+ return rule.config?.positiveColor || defaultDataBarPositiveColor;});const [nativeColor, nativeColorSet] = useState(() => {- const defaultV = '#ffbe38';if (!rule) {- return defaultV;+ return defaultDataBarNativeColor;}- return rule.config?.nativeColor || defaultV;+ return rule.config?.nativeColor || defaultDataBarNativeColor;});const commonOptions = [createOptionItem(CFValueType.num, localeService), createOptionItem(CFValueType.percent, localeService), createOptionItem(CFValueType.percentile, localeService), createOptionItem(CFValueType.formula, localeService)];const minOptions = [createOptionItem(CFValueType.min, localeService), ...commonOptions];@@ -150,24 +148,28 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {return rule.isShowValue === undefined ? defaultV : !!rule.isShowValue;});- const getResult = (option: { minValueType: CFValueType ;- minValue: number | string;- maxValueType: CFValueType ;- maxValue: number | string;- isGradient: string;- positiveColor: string;- isShowValue: boolean;- nativeColor: string; }) => {- const config: { min: IValueConfig;- max: IValueConfig;- isGradient: boolean;- positiveColor: string;- nativeColor: string; } = {+ const getResult = (option: {+ minValueType: CFValueType;+ minValue: number | string;+ maxValueType: CFValueType;+ maxValue: number | string;+ isGradient: string;+ positiveColor: string;+ isShowValue: boolean;+ nativeColor: string;+ }) => {+ const config: {+ min: IValueConfig;+ max: IValueConfig;+ isGradient: boolean;+ positiveColor: string;+ nativeColor: string;+ } = {min: { type: option.minValueType, value: option.minValue },max: { type: option.maxValueType, value: option.maxValue },isGradient: option.isGradient === '1',- positiveColor: option.positiveColor,- nativeColor: option.nativeColor,+ positiveColor: option.positiveColor || defaultDataBarPositiveColor,+ nativeColor: option.nativeColor || defaultDataBarNativeColor,};return { config, type: CFRuleType.dataBar, isShowValue: option.isShowValue };};@@ -180,14 +182,16 @@ export const DataBarStyleEditor = (props: IStyleEditorProps) => {return dispose as () => void;}, [isGradient, minValue, minValueType, maxValue, maxValueType, positiveColor, nativeColor, interceptorManager, isShowValue]);- const _handleChange = (option: { minValueType: CFValueType ;- minValue: number | string;- maxValueType: CFValueType ;- maxValue: number | string;- isGradient: string;- positiveColor: string;- isShowValue: boolean;- nativeColor: string; }) => {+ const _handleChange = (option: {+ minValueType: CFValueType;+ minValue: number | string;+ maxValueType: CFValueType;+ maxValue: number | string;+ isGradient: string;+ positiveColor: string;+ isShowValue: boolean;+ nativeColor: string;+ }) => {props.onChange(getResult(option));};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.tsxindex c1f7a02ea9..928b060061 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@@ -14,22 +14,20 @@* limitations under the License.*/-import React, { useEffect, useRef, useState } from 'react';+import React, { useEffect, useMemo, useRef, useState } from 'react';import { Select, Tooltip } from '@univerjs/design';import { useObservable } from '@univerjs/ui';import { useHighlightRange } from '@univerjs/sheets-ui';-import { ICommandService, IUniverInstanceService, LocaleService, Rectangle, UniverInstanceType, useDependency } from '@univerjs/core';-import type { ICellDataForSheetInterceptor, IRange, Workbook } from '@univerjs/core';-import type { ICellPermission } from '@univerjs/sheets';-import { SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';+import { ICommandService, Injector, IUniverInstanceService, LocaleService, Rectangle, UniverInstanceType, useDependency } from '@univerjs/core';+import type { IRange, Workbook } from '@univerjs/core';+import { checkRangesEditablePermission, SetSelectionsOperation, SetWorksheetActiveOperation, SheetsSelectionsService } from '@univerjs/sheets';import { serializeRange } from '@univerjs/engine-formula';import { DeleteSingle, IncreaseSingle, SequenceSingle } from '@univerjs/icons';import GridLayout from 'react-grid-layout';import { debounceTime, Observable } from 'rxjs';-import { UnitAction } from '@univerjs/protocol';import { AddConditionalRuleMutation, CFRuleType, CFSubRuleType, ConditionalFormattingRuleModel, DeleteConditionalRuleMutation, MoveConditionalRuleMutation, SetConditionalRuleMutation } from '@univerjs/sheets-conditional-formatting';-import type { IConditionalFormattingRuleConfig, IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';+import type { IConditionFormattingRule } from '@univerjs/sheets-conditional-formatting';import type { IDeleteCfCommandParams } from '../../../commands/commands/delete-cf.command';import { DeleteCfCommand } from '../../../commands/commands/delete-cf.command';import type { IMoveCfCommand } from '../../../commands/commands/move-cf.command';@@ -113,6 +111,8 @@ export const RuleList = (props: IRuleListProps) => {const selectionManagerService = useDependency(SheetsSelectionsService);const commandService = useDependency(ICommandService);const localeService = useDependency(LocaleService);+ const injector = useDependency(Injector);+const conditionalFormattingI18nController = useDependency(ConditionalFormattingI18nController);const workbook = useObservable(() => univerInstanceService.getCurrentTypeOfUnit$<Workbook>(UniverInstanceType.UNIVER_SHEET), undefined, undefined, [])!;@@ -152,37 +152,11 @@ export const RuleList = (props: IRuleListProps) => {});return _ruleList;} else if (selectValue === '2') {- return ruleList;+ return [...ruleList];}return [];};- const getConditionalFormattingRulesByPermissionCorrect = (rules: (IConditionFormattingRule<IConditionalFormattingRuleConfig>)[]): ((IConditionFormattingRule<IConditionalFormattingRuleConfig> & { disable?: boolean }))[] => {- const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;- const worksheet = workbook.getActiveSheet();- const rulesByPermissionCheck = rules.map((rule) => {- const ranges = rule.ranges;- const haveNotPermission = ranges?.some((range: IRange) => {- const { startRow, startColumn, endRow, endColumn } = range;- for (let row = startRow; row <= endRow; row++) {- for (let col = startColumn; col <= endColumn; col++) {- const permission = (worksheet?.getCell(row, col) as (ICellDataForSheetInterceptor & { selectionProtection: ICellPermission[] }))?.selectionProtection?.[0];- if (permission?.[UnitAction.Edit] === false || permission?.[UnitAction.View] === false) {- return true;- }- }- }- return false;- });- if (haveNotPermission) {- return { ...rule, disable: true };- } else {- return { ...rule };- }- });- return rulesByPermissionCheck;- };-const [ruleList, ruleListSet] = useState(getRuleList);useHighlightRange(currentRuleRanges);@@ -317,11 +291,27 @@ export const RuleList = (props: IRuleListProps) => {});}};+ const ruleListByPermissionCheck = useMemo(() => {+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet();+ return ruleList.filter((rule) => {+ const ranges = rule.ranges;+ const hasPermission = checkRangesEditablePermission(injector, workbook.getUnitId(), worksheet.getSheetId(), ranges);+ return hasPermission;+ });+ }, [ruleList]);- const layout = ruleList.map((rule, index) => ({ i: rule.cfId, x: 0, w: 12, y: index, h: 1, isResizable: false }));+ const layout = ruleListByPermissionCheck.map((rule, index) => ({ i: rule.cfId, x: 0, w: 12, y: index, h: 1, isResizable: false }));- const ruleListByPermissionCheck = getConditionalFormattingRulesByPermissionCorrect(ruleList);- const hasDisableRule = ruleListByPermissionCheck?.some((rule) => rule.disable);+ const isHasAllRuleEditPermission = useMemo(() => {+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;+ const worksheet = workbook.getActiveSheet();+ return ruleList.every((rule) => {+ const ranges = rule.ranges;+ const hasPermission = checkRangesEditablePermission(injector, workbook.getUnitId(), worksheet.getSheetId(), ranges);+ return hasPermission;+ });+ }, [ruleList]);return (<div className={styles.cfRuleList}>@@ -338,7 +328,7 @@ export const RuleList = (props: IRuleListProps) => {<IncreaseSingle /></div></Tooltip>- {(ruleList.length && !hasDisableRule)+ {(ruleList.length && isHasAllRuleEditPermission)? (<Tooltip title={localeService.t('sheet.cf.panel.clear')} placement="bottom"><div className={`${styles.gap} ${styles.icon}`} onClick={handleClear}>@@ -377,7 +367,6 @@ export const RuleList = (props: IRuleListProps) => {}}onMouseLeave={() => currentRuleRangesSet([])}onClick={() => {- if (rule.disable) return;onClick(rule);}}className={`${styles.ruleItem} ${draggingId === index ? styles.active : ''}`}@@ -393,17 +382,15 @@ export const RuleList = (props: IRuleListProps) => {<div className={styles.ruleRange}>{rule.ranges.map((range) => serializeRange(range)).join(',')}</div></div><div className={styles.preview}><Preview rule={rule.rule} /></div>- {!rule.disable && (- <div- className={`${styles.deleteItem} ${draggingId === index ? styles.active : ''}`}- onClick={(e) => {- e.stopPropagation();- handleDelete(rule);- }}- >- <DeleteSingle />- </div>- )}+ <div+ className={`${styles.deleteItem} ${draggingId === index ? styles.active : ''}`}+ onClick={(e) => {+ e.stopPropagation();+ handleDelete(rule);+ }}+ >+ <DeleteSingle />+ </div></div></div>);diff --git a/packages/sheets-conditional-formatting-ui/src/components/preview/index.tsx b/packages/sheets-conditional-formatting-ui/src/components/preview/index.tsxindex 83d6c579f0..240b58df56 100644--- a/packages/sheets-conditional-formatting-ui/src/components/preview/index.tsx+++ b/packages/sheets-conditional-formatting-ui/src/components/preview/index.tsx@@ -18,7 +18,7 @@ import React, { useMemo } from 'react';import { BooleanNumber, ColorKit } from '@univerjs/core';import { SlashSingle } from '@univerjs/icons';import type { IConditionalFormattingRuleConfig } from '@univerjs/sheets-conditional-formatting';-import { CFRuleType, DEFAULT_BG_COLOR, DEFAULT_FONT_COLOR, getColorScaleFromValue, iconMap } from '@univerjs/sheets-conditional-formatting';+import { CFRuleType, DEFAULT_BG_COLOR, DEFAULT_FONT_COLOR, defaultDataBarNativeColor, defaultDataBarPositiveColor, getColorScaleFromValue, iconMap } from '@univerjs/sheets-conditional-formatting';import styles from './index.module.less';export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {@@ -48,17 +48,17 @@ export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {{const { isGradient } = rule.config;const commonStyle = { width: '50%', height: '100%' };- const positiveColor = isGradient ? `linear-gradient(to right, ${rule.config.positiveColor}, rgb(255 255 255))` : rule.config.positiveColor;- const nativeColor = isGradient ? `linear-gradient(to right, rgb(255 255 255),${rule.config.nativeColor})` : rule.config.nativeColor;+ const positiveColor = isGradient ? `linear-gradient(to right, ${rule.config.positiveColor || defaultDataBarPositiveColor}, rgb(255 255 255))` : rule.config.positiveColor;+ const nativeColor = isGradient ? `linear-gradient(to right, rgb(255 255 255),${rule.config.nativeColor || defaultDataBarNativeColor})` : rule.config.nativeColor;return (<div className={styles.cfPreview}>- <div style={{ ...commonStyle, background: nativeColor, border: `1px solid ${rule.config.nativeColor}` }}></div>- <div style={{ ...commonStyle, background: positiveColor, border: `1px solid ${rule.config.positiveColor}` }}></div>+ <div style={{ ...commonStyle, background: nativeColor, border: `1px solid ${rule.config.nativeColor || defaultDataBarNativeColor}` }}></div>+ <div style={{ ...commonStyle, background: positiveColor, border: `1px solid ${rule.config.positiveColor || defaultDataBarPositiveColor}` }}></div></div>);}- case CFRuleType.colorScale:{+ case CFRuleType.colorScale: {return colorList && (<div className={styles.cfPreview}>{colorList.map((item, index) => (@@ -68,14 +68,14 @@ export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {</div>);}- case CFRuleType.iconSet:{+ case CFRuleType.iconSet: {return iconSet && (<div className={styles.cfPreview}>{iconSet.map((base64, index) => (base64 ? <img style={{ height: '100%' }} key={index} src={base64} /> : <SlashSingle key={index} />))}</div>);}- case CFRuleType.highlightCell:{+ case CFRuleType.highlightCell: {const { ul, st, it, bl, bg, cl } = rule.style;const isUnderline = ul?.s === BooleanNumber.TRUE;const isStrikethrough = st?.s === BooleanNumber.TRUE;@@ -83,11 +83,12 @@ export const Preview = (props: { rule?: IConditionalFormattingRuleConfig }) => {const isBold = bl === BooleanNumber.TRUE;const bgColor = bg?.rgb ?? DEFAULT_BG_COLOR;const fontColor = cl?.rgb ?? DEFAULT_FONT_COLOR;- const style = { fontWeight: isBold ? 'bold' : undefined,- fontStyle: isItalic ? 'italic' : undefined,- textDecoration: `${isUnderline ? 'underline' : ''} ${isStrikethrough ? 'line-through' : ''}`.replace(/^ /, '') || undefined,- backgroundColor: bgColor,- color: fontColor,+ const style = {+ fontWeight: isBold ? 'bold' : undefined,+ fontStyle: isItalic ? 'italic' : undefined,+ textDecoration: `${isUnderline ? 'underline' : ''} ${isStrikethrough ? 'line-through' : ''}`.replace(/^ /, '') || undefined,+ backgroundColor: bgColor,+ color: fontColor,};return (<div style={style} className={styles.cfPreview}>diff --git a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.tsindex c1fe0f020c..5dfbafbb7f 100644--- a/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts+++ b/packages/sheets-conditional-formatting-ui/src/controllers/cf.render.controller.ts@@ -15,7 +15,7 @@*/import type { Workbook } from '@univerjs/core';-import { Disposable, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, UniverInstanceType } from '@univerjs/core';+import { Disposable, Inject, IUniverInstanceService, LifecycleStages, OnLifecycle, Range, UniverInstanceType } from '@univerjs/core';import { INTERCEPTOR_POINT, SheetInterceptorService } from '@univerjs/sheets';import { SheetSkeletonManagerService } from '@univerjs/sheets-ui';import { bufferTime, filter } from 'rxjs/operators';@@ -24,7 +24,7 @@ import { IRenderManagerService } from '@univerjs/engine-render';import { ConditionalFormattingRuleModel, ConditionalFormattingService, ConditionalFormattingViewModel, DEFAULT_PADDING, DEFAULT_WIDTH } from '@univerjs/sheets-conditional-formatting';import type { IConditionalFormattingCellData } from '@univerjs/sheets-conditional-formatting';-@OnLifecycle(LifecycleStages.Rendered, SheetsCfRenderController)+@OnLifecycle(LifecycleStages.Starting, SheetsCfRenderController)export class SheetsCfRenderController extends Disposable {constructor(@Inject(SheetInterceptorService) private _sheetInterceptorService: SheetInterceptorService,@Inject(ConditionalFormattingService) private _conditionalFormattingService: ConditionalFormattingService,@@ -37,6 +37,7 @@ export class SheetsCfRenderController extends Disposable {this._initViewModelInterceptor();this._initSkeleton();+ this._initVmEffectByRule();}private _initSkeleton() {@@ -81,6 +82,93 @@ export class SheetsCfRenderController extends Disposable {})).subscribe(markDirtySkeleton));}+ private _initVmEffectByRule() {+ this.disposeWithMe(+ this._conditionalFormattingRuleModel.$ruleChange.subscribe((config) => {+ const { rule, unitId, subUnitId } = config;+ switch (config.type) {+ case 'add': {+ const list = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)!;++ const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {+ map.set(cur, index);+ return map;+ }, new Map<string, number>());+ rule.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, rule.cfId);+ this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);+ });+ });+ this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);+ return;+ }+ case 'delete': {+ rule.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ this._conditionalFormattingViewModel.deleteCellCf(unitId, subUnitId, row, col, rule.cfId);+ });+ });+ this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);+ return;+ }+ case 'set': {+ const oldRule = config.oldRule!;+ const list = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)!;+ const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {+ map.set(cur, index);+ return map;+ }, new Map<string, number>());++ // After each setting, the cache needs to be cleared,+ // and this cleanup is deferred until the end of the calculation.+ // Otherwise the render will flash once+ const dispose = this._conditionalFormattingService.interceptorManager.intercept(this._conditionalFormattingService.interceptorManager.getInterceptPoints().beforeUpdateRuleResult, {+ handler: (config, _, next) => {+ if (unitId === config?.unitId && subUnitId === config.subUnitId && oldRule.cfId === config.cfId) {+ oldRule.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ this._conditionalFormattingViewModel.deleteCellCf(unitId, subUnitId, row, col, oldRule.cfId);+ });+ });+ rule.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, oldRule.cfId);+ this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);+ });+ });+ dispose();+ return;+ }+ next(config);+ },+ });++ rule.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, oldRule.cfId);+ });+ });++ this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);+ return;+ }+ case 'sort': {+ const list = this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)!;+ const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {+ map.set(cur, index);+ return map;+ }, new Map<string, number>());+ rule.ranges.forEach((range) => {+ Range.foreach(range, (row, col) => {+ this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);+ });+ });+ }+ }+ }));+ }+private _initViewModelInterceptor() {this.disposeWithMe(this._sheetInterceptorService.intercept(INTERCEPTOR_POINT.CELL_CONTENT, {handler: (cell, context, next) => {diff --git a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.tsindex 13cf470de1..2f6fdf921e 100644--- a/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts+++ b/packages/sheets-conditional-formatting-ui/src/menu/manage-rule.ts@@ -99,22 +99,22 @@ export const FactoryManageConditionalFormattingRule = (accessor: IAccessor): IMeconst allRule = conditionalFormattingRuleModel.getSubunitRules(workbook.getUnitId(), worksheet.getSheetId()) || [];const ruleList = allRule.filter((rule) => rule.ranges.some((ruleRange) => ranges.some((range) => Rectangle.intersects(range, ruleRange))));- subscriber.next(!!ruleList.length);+ const hasPermission = ruleList.map((rule) => rule.ranges).every((ranges) => {+ return checkRangesEditablePermission(accessor, workbook.getUnitId(), worksheet.getSheetId(), ranges);+ });+ subscriber.next(hasPermission);}));const clearSheetEnable$ = new Observable<boolean>((subscriber) =>- merge(- selectionManagerService.selectionMoveEnd$,- new Observable<null>((commandSubscribe) => {- const disposable = commandService.onCommandExecuted((commandInfo) => {- const { id, params } = commandInfo;- const unitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getUnitId();- if (commandList.includes(id) && (params as { unitId: string }).unitId === unitId) {- commandSubscribe.next(null);- }- });- return () => disposable.dispose();- })- ).pipe(debounceTime(16)).subscribe(() => {+ new Observable<null>((commandSubscribe) => {+ const disposable = commandService.onCommandExecuted((commandInfo) => {+ const { id, params } = commandInfo;+ const unitId = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)?.getUnitId();+ if (commandList.includes(id) && (params as { unitId: string }).unitId === unitId) {+ commandSubscribe.next(null);+ }+ });+ return () => disposable.dispose();+ }).pipe(debounceTime(16)).subscribe(() => {const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET);if (!workbook) return;const worksheet = workbook.getActiveSheet();diff --git a/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts b/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.tsindex 05ad6e7eea..d1cfcf3116 100644--- a/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts+++ b/packages/sheets-conditional-formatting/src/models/conditional-formatting-rule-model.ts@@ -14,25 +14,94 @@* limitations under the License.*/-import { Inject, Injector, Range } from '@univerjs/core';-import { Subject } from 'rxjs';+import { Inject, Injector, Tools } from '@univerjs/core';+import { Observable, Subject } from 'rxjs';+import { bufferTime, filter } from 'rxjs/operators';import { createCfId } from '../utils/create-cf-id';-import { ConditionalFormattingService } from '../services/conditional-formatting.service';import type { IAnchor } from '../utils/anchor';import { findIndexByAnchor, moveByAnchor } from '../utils/anchor';import type { IConditionFormattingRule, IRuleModel } from './type';-import { ConditionalFormattingViewModel } from './conditional-formatting-view-model';type RuleOperatorType = 'delete' | 'set' | 'add' | 'sort';+export class ConditionalFormattingRuleModel {// Map<unitID ,<sheetId ,IConditionFormattingRule[]>>private _model: IRuleModel = new Map();- private _ruleChange$ = new Subject<{ rule: IConditionFormattingRule; unitId: string; subUnitId: string; type: RuleOperatorType }>();- $ruleChange = this._ruleChange$.asObservable();+ private _ruleChange$ = new Subject<{ rule: IConditionFormattingRule; oldRule?: IConditionFormattingRule; unitId: string; subUnitId: string; type: RuleOperatorType }>();+ $ruleChange = this._ruleChange$.asObservable().pipe(+ bufferTime(16),+ filter((list) => !!list.length),+ // Operations for aggregated conditional formatting+ // Adding and then deleting the same conditional format for multiple times will not result in any changes being propagated externally+ // When multiple settings are applied to the same conditional format, only the last setting will be propagated externally.+ (source) => new Observable<{ rule: IConditionFormattingRule; oldRule?: IConditionFormattingRule; unitId: string; subUnitId: string; type: RuleOperatorType }>((observer) => {+ source.subscribe({+ next: (ruleList) => {+ type Item = (typeof ruleList)[0];+ const createKey = (item: Item) => `${item.unitId}_${item.subUnitId}_${item.rule.cfId}`;+ // Adding and then deleting the same conditional format for multiple times will not result in any changes being propagated externally+ const handleCreateAndDelete = (list: Item[]) => {+ //Between the operation can be nullified, do not have to carry out.+ const createIndex = list.findIndex((rule) => rule.type === 'add');+ const deleteIndex = list.findIndex((rule) => rule.type === 'delete');+ if (createIndex !== -1 && deleteIndex !== -1 && deleteIndex > createIndex) {+ list.splice(createIndex, deleteIndex - createIndex + 1);+ }+ };+ // When multiple settings are applied to the same conditional format, only the last setting will be propagated externally.+ const handleSetAndSet = (list: Item[]) => {+ const setList = list.filter((item) => item.type === 'set');+ if (setList.length < 2) {+ return;+ }+ const theLast = setList[setList.length - 1];+ let index = list.length - 1;+ while (index >= 0) {+ const item = list[index];+ if (item.type === 'set' && item !== theLast) {+ list.splice(index, 1);+ }+ index--;+ }+ };++ const result = ruleList.reduce((a, b, index) => {+ const key = createKey(b);+ if (!a[key]) {+ a[key] = [];+ }+ const list = a[key];+ list.push({ ...b, _index: index });+ return a;+ }, {} as Record<string, (Item & { _index: number })[]>);++ for (const key in result) {+ const list = result[key];+ if (list.length >= 2) {+ handleCreateAndDelete(list);+ // handleSetAndSet(list)+ }+ }++ const resultList = Object.keys(result).reduce((a, key) => {+ const list = result[key];+ a.push(...list);+ return a;+ }, [] as (Item & { _index: number })[]).sort((a, b) => a._index - b._index).map((item) => {+ return item;+ });++ resultList.forEach((item) => {+ observer.next(item);+ });+ },+ error: (err) => observer.error(err),+ complete: () => observer.complete(),+ });+ }));constructor(- @Inject(ConditionalFormattingViewModel) private _conditionalFormattingViewModel: ConditionalFormattingViewModel,@Inject(Injector) private _injector: Injector) {// empty@@ -77,11 +146,6 @@ export class ConditionalFormattingRuleModel {const rule = list[index];if (rule) {list.splice(index, 1);- rule.ranges.forEach((range) => {- Range.foreach(range, (row, col) => {- this._conditionalFormattingViewModel.deleteCellCf(unitId, subUnitId, row, col, rule.cfId);- });- });this._ruleChange$.next({ rule, subUnitId, unitId, type: 'delete' });}}@@ -91,46 +155,9 @@ export class ConditionalFormattingRuleModel {const list = this._ensureList(unitId, subUnitId);const oldRule = list.find((item) => item.cfId === oldCfId);if (oldRule) {- const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {- map.set(cur, index);- return map;- }, new Map<string, number>());- // After each setting, the cache needs to be cleared,- // and this cleanup is deferred until the end of the calculation.- // Otherwise the render will flash once- const cloneRange = [...oldRule.ranges];- const conditionalFormattingService = this._injector.get(ConditionalFormattingService);-+ const cloneRule = Tools.deepClone(oldRule);Object.assign(oldRule, rule);- const dispose = conditionalFormattingService.interceptorManager.intercept(conditionalFormattingService.interceptorManager.getInterceptPoints().beforeUpdateRuleResult, {- handler: (config, _, next) => {- if (unitId === config?.unitId && subUnitId === config.subUnitId && oldRule.cfId === config.cfId) {- cloneRange.forEach((range) => {- Range.foreach(range, (row, col) => {- this._conditionalFormattingViewModel.deleteCellCf(unitId, subUnitId, row, col, oldRule.cfId);- });- });- oldRule.ranges.forEach((range) => {- Range.foreach(range, (row, col) => {- this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, oldRule.cfId);- this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);- });- });- dispose();- return;- }- next(config);- },- });-- oldRule.ranges.forEach((range) => {- Range.foreach(range, (row, col) => {- this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, oldRule.cfId);- });- });-- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, oldRule);- this._ruleChange$.next({ rule: oldRule, subUnitId, unitId, type: 'set' });+ this._ruleChange$.next({ rule: oldRule, subUnitId, unitId, type: 'set', oldRule: cloneRule });}}@@ -141,17 +168,6 @@ export class ConditionalFormattingRuleModel {// The new conditional formatting has a higher prioritylist.unshift(rule);}- const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {- map.set(cur, index);- return map;- }, new Map<string, number>());- rule.ranges.forEach((range) => {- Range.foreach(range, (row, col) => {- this._conditionalFormattingViewModel.pushCellCf(unitId, subUnitId, row, col, rule.cfId);- this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);- });- });- this._conditionalFormattingViewModel.markRuleDirty(unitId, subUnitId, rule);this._ruleChange$.next({ rule, subUnitId, unitId, type: 'add' });}@@ -169,15 +185,6 @@ export class ConditionalFormattingRuleModel {const rule = list[curIndex];if (rule) {moveByAnchor(start, end, list, (rule) => rule.cfId);- const cfPriorityMap = list.map((item) => item.cfId).reduce((map, cur, index) => {- map.set(cur, index);- return map;- }, new Map<string, number>());- rule.ranges.forEach((range) => {- Range.foreach(range, (row, col) => {- this._conditionalFormattingViewModel.sortCellCf(unitId, subUnitId, row, col, cfPriorityMap);- });- });this._ruleChange$.next({ rule, subUnitId, unitId, type: 'sort' });}}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.tsindex 2b9234fb1e..b23d52a5a9 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@@ -19,15 +19,16 @@ import { Subject } from 'rxjs';import type { IDataBarRenderParams } from '../render/type';import type { IConditionFormattingRule, IHighlightCell } from './type';+interface ICacheItem { cfId: string; ruleCache?: IHighlightCell['style'] | IDataBarRenderParams; isDirty: boolean }interface ICellItem {- cfList: { cfId: string; ruleCache?: IHighlightCell['style'] | IDataBarRenderParams ;isDirty: boolean }[];+ cfList: ICacheItem[];}export class ConditionalFormattingViewModel {- // Map<unitID ,<sheetId ,ObjectMatrix>>+ // Map<unitID ,<sheetId ,ObjectMatrix>>private _model: Map<string, Map<string, ObjectMatrix<ICellItem>>> = new Map();- private _markDirty$ = new Subject<{ rule: IConditionFormattingRule;unitId: string;subUnitId: string }>();+ private _markDirty$ = new Subject<{ rule: IConditionFormattingRule; unitId: string; subUnitId: string }>();public markDirty$ = this._markDirty$.asObservable();private _ensureMatrix(unitId: string, subUnitId: string) {@@ -129,7 +130,7 @@ export class ConditionalFormattingViewModel {}).filter((item) => !!item).sort((a, b) => a!.priority - b!.priority) as ICellItem['cfList'];- // The smaller the priority, the higher+ // The smaller the priority, the highercell.cfList = sortResult;}}diff --git a/packages/sheets-conditional-formatting/src/render/data-bar.render.ts b/packages/sheets-conditional-formatting/src/render/data-bar.render.tsindex 3e9127f8b7..4812a3f76d 100644--- a/packages/sheets-conditional-formatting/src/render/data-bar.render.ts+++ b/packages/sheets-conditional-formatting/src/render/data-bar.render.ts@@ -21,6 +21,9 @@ import { FIX_ONE_PIXEL_BLUR_OFFSET, SheetExtension, SpreadsheetExtensionRegistryimport type { IDataBarCellData } from './type';export const dataBarUKey = 'sheet-conditional-rule-data-bar';+export const defaultDataBarPositiveColor = '#ffbe38';+export const defaultDataBarNativeColor = '#abd91a';+const EXTENSION_Z_INDEX = 34;export class DataBar extends SheetExtension {diff --git a/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts b/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.tsindex 6e313cbb52..14ff70b1ad 100644--- a/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts+++ b/packages/sheets-conditional-formatting/src/services/calculate-unit/data-bar.ts@@ -19,6 +19,7 @@ import { CFRuleType } from '../../base/const';import type { IDataBarRenderParams } from '../../render/type';import type { IConditionFormattingRule, IDataBar } from '../../models/type';import { ConditionalFormattingFormulaService, FormulaResultStatus } from '../conditional-formatting-formula.service';+import { defaultDataBarNativeColor, defaultDataBarPositiveColor } from '../../render/data-bar.render';import { filterRange, getValueByType, isNullable } from './utils';import type { ICalculateUnit } from './type';import { EMPTY_STYLE } from './type';@@ -89,7 +90,7 @@ export const dataBarCellCalculateUnit: ICalculateUnit = {return;}const v = getSafeValue((max - value) / length * 100);- computeResult.setValue(row, col, { color: ruleConfig.config.nativeColor, startPoint, value: -v, isGradient, isShowValue });+ computeResult.setValue(row, col, { color: ruleConfig.config.nativeColor || defaultDataBarNativeColor, startPoint, value: -v, isGradient, isShowValue });});} else if (min < 0 && max > 0) {const length = Math.abs(max) + Math.abs(min);@@ -103,7 +104,7 @@ export const dataBarCellCalculateUnit: ICalculateUnit = {computeResult.setValue(row, col, { color: ruleConfig.config.positiveColor, startPoint, value: v, isGradient, isShowValue });} else {const v = getSafeValue(Math.min(Math.abs(value) / Math.abs(min), 1) * 100);- computeResult.setValue(row, col, { color: ruleConfig.config.nativeColor, startPoint, value: -v, isGradient, isShowValue });+ computeResult.setValue(row, col, { color: ruleConfig.config.nativeColor || defaultDataBarNativeColor, startPoint, value: -v, isGradient, isShowValue });}});} else if (min >= 0 && max > 0) {@@ -114,7 +115,7 @@ export const dataBarCellCalculateUnit: ICalculateUnit = {return;}const v = getSafeValue((1 - (max - value) / length) * 100);- computeResult.setValue(row, col, { color: ruleConfig.config.positiveColor, startPoint, value: v, isGradient, isShowValue });+ computeResult.setValue(row, col, { color: ruleConfig.config.positiveColor || defaultDataBarPositiveColor, startPoint, value: v, isGradient, isShowValue });});}return computeResult;