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.

20.7 KB
Raw Blame
/**
 * Copyright 2023-present DreamNum Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type { 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,
    IHighlightCell,
    INumberHighlightCell,
    IRankHighlightCell,
    ITextHighlightCell,
    ITimePeriodHighlightCell,
} from '../type';
import type { IContext } from './base-calculate-unit';
import { CFNumberOperator, CFSubRuleType, CFTextOperator, CFTimePeriodOperator } from '../../base/const';
import { ConditionalFormattingFormulaService } from '../../services/conditional-formatting-formula.service';
import { BaseCalculateUnit, CalculateEmitStatus } from './base-calculate-unit';
import {
    compareWithNumber,
    filterRange,
    getCellValue,
    isFloatsEqual,
    isNullable,
    serialTimeToTimestamp,
} from './utils';

interface IConfig {
    value: any;
    type: CFSubRuleType;
}

const isFormulaResultMatched = (value: unknown) => value === true || value === 1 || value === 'TRUE';

const sortRangesByTopLeft = <T extends { startRow: number; startColumn: number }>(ranges: T[]) => [...ranges].sort((a, b) => {
    if (a.startRow !== b.startRow) {
        return a.startRow - b.startRow;
    }

    return a.startColumn - b.startColumn;
});

export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConfig>, 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;
        const ranges = filterRange(context.rule.ranges, context.worksheet.getMaxRows() - 1, context.worksheet.getMaxColumns() - 1);
        // eslint-disable-next-line max-lines-per-function, complexity
        const getCache = () => {
            switch (ruleConfig.subType) {
                case CFSubRuleType.average: {
                    let sum = 0;
                    let count = 0;
                    ranges.forEach((range) => {
                        Range.foreach(range, (row, col) => {
                            const cell = context.getCellValue(row, col);
                            const v = getCellValue(cell);
                            if (cell && cell.t === CellValueType.NUMBER && !isNullable(v)) {
                                sum += Number(v) || 0;
                                count++;
                            }
                        });
                    });
                    return { value: sum / count, type: ruleConfig.subType };
                }
                case CFSubRuleType.uniqueValues:
                case CFSubRuleType.duplicateValues: {
                    const cacheMap: Map<any, number> = new Map();
                    ranges.forEach((range) => {
                        Range.foreach(range, (row, col) => {
                            const cell = context.getCellValue(row, col);
                            const v = getCellValue(cell);
                            if (!isNullable(v)) {
                                const cache = cacheMap.get(v);
                                if (cache) {
                                    cacheMap.set(v, cache + 1);
                                } else {
                                    cacheMap.set(v, 1);
                                }
                            }
                        });
                    });
                    return { value: cacheMap, type: ruleConfig.subType };
                }
                case CFSubRuleType.rank: {
                    let allValue: number[] = [];
                    ranges.forEach((range) => {
                        Range.foreach(range, (row, col) => {
                            const cell = context.getCellValue(row, col);
                            const v = getCellValue(cell);
                            if (cell && cell.t === CellValueType.NUMBER && !isNullable(v)) {
                                allValue.push(Number(v) || 0);
                            }
                        });
                    });
                    allValue.sort((a, b) => b - a);
                    const configRule = context.rule.rule as IRankHighlightCell;
                    if (configRule.isPercent) {
                        if (configRule.isBottom) {
                            allValue = allValue.slice().reverse();
                        }

                        // Calculate the index directly based on the threshold percentage.
                        const threshold = Tools.clamp(configRule.value, 0, 100) / 100;
                        const targetIndex = Math.floor(threshold * allValue.length);
                        // Ensure the index is within bounds
                        const safeIndex = Tools.clamp(targetIndex - 1, 0, allValue.length - 1);
                        return { value: allValue[safeIndex], type: ruleConfig.subType };
                    }

                    const targetIndex = Math.floor(Tools.clamp(configRule.isBottom ? (configRule.value - 1) : configRule.value, 0, allValue.length));
                    if (configRule.isBottom) {
                        return { value: allValue[allValue.length - targetIndex - 1], type: ruleConfig.subType };
                    } else {
                        return { value: allValue[Math.max(targetIndex - 1, 0)], type: ruleConfig.subType };
                    }
                }
                case CFSubRuleType.formula: {
                    const _ruleConfig = ruleConfig as IFormulaHighlightCell;
                    const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);
                    const normalizedRanges = sortRangesByTopLeft(context.rule.ranges);
                    conditionalFormattingFormulaService.registerFormulaWithRange(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value, normalizedRanges);
                    const result = conditionalFormattingFormulaService.getFormulaMatrix(context.unitId, context.subUnitId, context.rule.cfId, _ruleConfig.value);
                    if (result && result.status === FormulaResultStatus.SUCCESS) {
                        this._preComputingStatus$.next(CalculateEmitStatus.preComputingEnd);
                        return {
                            value: result.result,
                            type: ruleConfig.subType,
                        };
                    } else {
                        this._preComputingStatus$.next(CalculateEmitStatus.preComputing);
                    }
                    return null;
                }
                case CFSubRuleType.timePeriod: {
                    const subRuleConfig = ruleConfig as ITimePeriodHighlightCell;
                    switch (subRuleConfig.operator) {
                        case CFTimePeriodOperator.last7Days: {
                            const today = dateKit().startOf('day');
                            return {
                                value: {
                                    start: today.subtract(6, 'day').valueOf(),
                                    end: today.endOf('day').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.lastMonth: {
                            const month = dateKit().startOf('month').subtract(1, 'month');
                            return {
                                value: {
                                    start: month.valueOf(),
                                    end: month.endOf('month').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.lastWeek: {
                            return {
                                value: {
                                    start: dateKit().startOf('week').subtract(1, 'week').valueOf(),
                                    end: dateKit().endOf('week').subtract(1, 'week').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.nextMonth: {
                            const month = dateKit().startOf('month').add(1, 'month');
                            return {
                                value: {
                                    start: month.valueOf(),
                                    end: month.endOf('month').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.nextWeek: {
                            return {
                                value: {
                                    start: dateKit().startOf('week').add(1, 'week').valueOf(),
                                    end: dateKit().endOf('week').add(1, 'week').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.thisMonth: {
                            return {
                                value: {
                                    start: dateKit().startOf('month').valueOf(),
                                    end: dateKit().endOf('month').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.thisWeek: {
                            return {
                                value: {
                                    start: dateKit().startOf('week').valueOf(),
                                    end: dateKit().endOf('week').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.today: {
                            return {
                                value: {
                                    start: dateKit().startOf('day').valueOf(),
                                    end: dateKit().endOf('day').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.tomorrow: {
                            return {
                                value: {
                                    start: dateKit().startOf('day').add(1, 'day').valueOf(),
                                    end: dateKit().endOf('day').add(1, 'day').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                        case CFTimePeriodOperator.yesterday: {
                            return {
                                value: {
                                    start: dateKit().startOf('day').subtract(1, 'day').valueOf(),
                                    end: dateKit().endOf('day').subtract(1, 'day').valueOf(),
                                },
                                type: ruleConfig.subType,
                            };
                        }
                    }
                }
            }
        };
        const result = getCache();
        this.setPreComputingCache(result);
    }

    // eslint-disable-next-line max-lines-per-function
    protected override getCellResult(row: number, col: number, preComputingResult: Nullable<IConfig>, context: IContext) {
        const cellValue = context.getCellValue(row, col);
        const ruleConfig = context.rule.rule as IHighlightCell;
        // eslint-disable-next-line max-lines-per-function, complexity
        const run = () => {
            switch (ruleConfig.subType) {
                case CFSubRuleType.number: {
                    const subRuleConfig = ruleConfig as INumberHighlightCell;
                    const value = cellValue?.v;
                    if (cellValue?.t !== CellValueType.FORCE_STRING && (ERROR_TYPE_SET as Set<unknown>).has(value)) {
                        return false;
                    }
                    // Excel compares an empty cell as zero. Text (including a formula's
                    // empty string) and booleans sort above numbers without coercion.
                    if (value != null && (cellValue?.t === CellValueType.BOOLEAN || (cellValue?.t !== CellValueType.NUMBER && typeof value !== 'number'))) {
                        return [CFNumberOperator.notEqual, CFNumberOperator.notBetween, CFNumberOperator.greaterThan, CFNumberOperator.greaterThanOrEqual].includes(subRuleConfig.operator);
                    }
                    return compareWithNumber({ operator: subRuleConfig.operator, value: subRuleConfig.value ?? 0 }, Number(value ?? 0));
                }
                case CFSubRuleType.text: {
                    const subRuleConfig = ruleConfig as ITextHighlightCell;
                    const value = getCellValue(cellValue);
                    const v = isNullable(value) ? '' : String(value);
                    const condition = subRuleConfig.value || '';
                    switch (subRuleConfig.operator) {
                        case CFTextOperator.beginsWith: {
                            return v.startsWith(condition);
                        }
                        case CFTextOperator.containsBlanks: {
                            return /^\s*$/.test(v);
                        }
                        case CFTextOperator.notContainsBlanks: {
                            return !/^\s*$/.test(v);
                        }
                        case CFTextOperator.containsErrors: {
                            return (ERROR_TYPE_SET as Set<unknown>).has(v);
                        }
                        case CFTextOperator.notContainsErrors: {
                            return !(ERROR_TYPE_SET as Set<unknown>).has(v);
                        }
                        case CFTextOperator.containsText: {
                            return v.indexOf(condition) > -1;
                        }
                        case CFTextOperator.notContainsText: {
                            return v.indexOf(condition) === -1;
                        }
                        case CFTextOperator.endsWith: {
                            return v.endsWith(condition);
                        }
                        case CFTextOperator.equal: {
                            return v === condition;
                        }
                        case CFTextOperator.notEqual: {
                            return v !== condition;
                        }
                        default: {
                            return false;
                        }
                    }
                }
                case CFSubRuleType.timePeriod: {
                    const value = getCellValue(cellValue);
                    if (isNullable(value) || Number.isNaN(Number(value)) || cellValue?.t !== CellValueType.NUMBER || !preComputingResult) {
                        return;
                    }
                    const v = serialTimeToTimestamp(Number(value), context.workbook.getDateSystem());
                    const { start, end } = preComputingResult.value!;
                    return v >= start && v <= end;
                }
                case CFSubRuleType.average: {
                    const value = cellValue && cellValue.v;
                    const v = Number(value);
                    const isNumber = cellValue?.t === CellValueType.NUMBER;
                    const subRuleConfig = ruleConfig as IAverageHighlightCell;

                    if (!isNumber) {
                        if (CFNumberOperator.notEqual === subRuleConfig.operator) {
                            return true;
                        }
                        return false;
                    }

                    if (isNullable(value) || Number.isNaN(v) || !preComputingResult) {
                        return false;
                    }

                    const average = preComputingResult.value;

                    switch (subRuleConfig.operator) {
                        case CFNumberOperator.greaterThan: {
                            return v > average;
                        }
                        case CFNumberOperator.greaterThanOrEqual: {
                            return v >= average;
                        }
                        case CFNumberOperator.lessThan: {
                            return v < average;
                        }
                        case CFNumberOperator.lessThanOrEqual: {
                            return v <= average;
                        }
                        case CFNumberOperator.equal: {
                            return isFloatsEqual(v, average);
                        }
                        case CFNumberOperator.notEqual: {
                            return !isFloatsEqual(v, average);
                        }
                        default: {
                            return false;
                        }
                    }
                }
                case CFSubRuleType.rank: {
                    const value = getCellValue(cellValue);

                    const v = Number(value);

                    if (isNullable(value) || Number.isNaN(v) || cellValue?.t !== CellValueType.NUMBER || !preComputingResult) {
                        return false;
                    }

                    const targetValue = preComputingResult.value;
                    const subRuleConfig = ruleConfig as IRankHighlightCell;
                    if (subRuleConfig.isBottom) {
                        return v <= targetValue;
                    } else {
                        return v >= targetValue;
                    }
                }
                case CFSubRuleType.uniqueValues: {
                    const value = getCellValue(cellValue);

                    if (isNullable(value) || !preComputingResult) {
                        return false;
                    }
                    const uniqueCache = preComputingResult.value;
                    return uniqueCache.get(value) === 1;
                }
                case CFSubRuleType.duplicateValues: {
                    const value = getCellValue(cellValue);

                    if (isNullable(value) || !preComputingResult) {
                        return false;
                    }
                    const uniqueCacheValue = preComputingResult.value.get(value);

                    return uniqueCacheValue && uniqueCacheValue !== 1;
                }
                case CFSubRuleType.formula: {
                    const _ruleConfig = ruleConfig as IFormulaHighlightCell;
                    const conditionalFormattingFormulaService = context.accessor.get(ConditionalFormattingFormulaService);

                    // The formula engine stores results at relative offsets from the first range's top-left.
                    const firstRange = sortRangesByTopLeft(context.rule.ranges)[0];
                    const relativeRow = row - firstRange.startRow;
                    const relativeCol = col - firstRange.startColumn;

                    const formulaResult = conditionalFormattingFormulaService.getFormulaResultWithCoords(
                        context.unitId,
                        context.subUnitId,
                        context.rule.cfId,
                        _ruleConfig.value,
                        relativeRow,
                        relativeCol
                    );

                    if (formulaResult.status === FormulaResultStatus.SUCCESS && formulaResult.result !== undefined) {
                        return isFormulaResultMatched(formulaResult.result);
                    }

                    const cache = preComputingResult?.value;
                    if (cache) {
                        const value = cache.getValue(relativeRow, relativeCol);
                        return isFormulaResultMatched(value);
                    }
                    return false;
                }
            }
        };
        return !!run();
    }
}