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.

7.2 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 { ParseData } from './api';
import type { ParseOptions } from './parse-value';
import { regexp } from '../../common/regexp';
import { LocaleType } from '../../types/enum/locale-type';
import { parseDate, parseNumber, parseTime, tokenize, tokenTypes } from './api';

export const DEFAULT_TEXT_FORMAT = '@@@'; // Compatible with old data
export const DEFAULT_TEXT_FORMAT_EXCEL = '@'; // The default text format in Excel, recommended
export const DEFAULT_NUMBER_FORMAT = 'General'; // null or General are considered the default format

export function isTextFormat(pattern: string | undefined) {
    return pattern === DEFAULT_TEXT_FORMAT || pattern === DEFAULT_TEXT_FORMAT_EXCEL;
}

export function isDefaultFormat(pattern?: string | null) {
    return pattern === null || pattern === undefined || pattern === DEFAULT_NUMBER_FORMAT;
}

export type INumfmtLocaleTag =
    | 'zh-CN'
    | 'zh-TW'
    | 'zh-HK'
    | 'ar'
    | 'cs'
    | 'da'
    | 'nl'
    | 'en'
    | 'fi'
    | 'fr'
    | 'de'
    | 'el'
    | 'hu'
    | 'is'
    | 'id'
    | 'it'
    | 'ja'
    | 'ko'
    | 'nb'
    | 'pl'
    | 'pt'
    | 'ru'
    | 'sk'
    | 'es'
    | 'sv'
    | 'th'
    | 'tr'
    | 'vi';

export function getNumfmtLocaleTag(locale: LocaleType): INumfmtLocaleTag {
    switch (locale) {
        case LocaleType.FR_FR:
            return 'fr';
        case LocaleType.RU_RU:
            return 'ru';
        case LocaleType.VI_VN:
            return 'vi';
        case LocaleType.ZH_CN:
            return 'zh-CN';
        case LocaleType.KO_KR:
            return 'ko';
        case LocaleType.ZH_TW:
            return 'zh-TW';
        case LocaleType.ZH_HK:
            return 'zh-HK';
        case LocaleType.ES_ES:
        case LocaleType.CA_ES:
            return 'es';
        case LocaleType.SK_SK:
            return 'sk';
        case LocaleType.JA_JP:
            return 'ja';
        case LocaleType.PT_BR:
            return 'pt';
        case LocaleType.DE_DE:
            return 'de';
        case LocaleType.IT_IT:
            return 'it';
        case LocaleType.ID_ID:
            return 'id';
        case LocaleType.PL_PL:
            return 'pl';
        case LocaleType.AR_SA:
            return 'ar';
        case LocaleType.EN_US:
        case LocaleType.FA_IR:
        default:
            return 'en';
    }
}

/**
 * Determines whether two patterns are equal, excluding differences in decimal places.
 * This function ignores the decimal part of the patterns and the positive color will be ignored but negative color will be considered.
 * more info can check the test case.
 */
export const isPatternEqualWithoutDecimal = (patternA: string, patternB: string): boolean => {
    if ((patternA && !patternB) || (!patternA && patternB)) {
        return false;
    }

    const getStringWithoutDecimal = (pattern: string): string => {
        const tokens = tokenize(pattern);
        let result = '';
        let isDecimalPart = false;
        let isColorBefore = false;

        for (const token of tokens) {
            if (token.type === tokenTypes.POINT) {
                isDecimalPart = true; // Start ignoring tokens after the decimal point
                continue;
            }
            // for the excel number

            // this if should be before the color token check
            if (isColorBefore && token.type === tokenTypes.MINUS) {
                // ignore the minus token in the decimal part after the color token
                continue;
            }

            if (token.type === tokenTypes.SKIP) {
                // Skip tokens that are not relevant to the string representation
                continue;
            }

            if (token.type === tokenTypes.COLOR) {
                isColorBefore = true; // If we are in the decimal part, we ignore the color tokens
                continue;
            } else {
                isColorBefore = false; // Reset after processing the color part
            }

            if (isDecimalPart && token.type === tokenTypes.ZERO) {
                // If we are in the decimal part, we ignore the number tokens
                continue;
            } else {
                isDecimalPart = false; // Reset after processing the decimal part
            }

            if (!isDecimalPart) {
                result += token.value || '';
            }
        }

        return result;
    };

    const normalizedA = getStringWithoutDecimal(patternA);
    const normalizedB = getStringWithoutDecimal(patternB);

    return normalizedA === normalizedB;
};

const ignoreCommonPatterns = new Set(['m d']);
const ignoreAMPMPatterns = new Set(['h:mm AM/PM', 'hh:mm AM/PM']);
export const currencySymbols = [
    'Rp',
    'zł',
    'NT$',
    'R$',
    'HK$',
    '$',
    '£',
    '¥',
    '¤',
    '֏',
    '؋',
    '৳',
    '฿',
    '៛',
    '₡',
    '₦',
    '₩',
    '₪',
    '₫',
    '€',
    '₭',
    '₮',
    '₱',
    '₲',
    '₴',
    '₸',
    '₹',
    '₺',
    '₼',
    '₽',
    '₾',
    '₿',
    '﷼',
];

const CURRENCY_SYMBOL_PREFIX_REG = new RegExp(`^${regexp.charset(...Array.from(new Set(currencySymbols.join(''))))}+`);

/**
 * Get the numfmt parse value, and filter out the parse error.
 */
export const getNumfmtParseValueFilter = (value: string, options: ParseOptions = {}): ParseData | null => {
    const parseData = parseDate(value, options) ?? parseTime(value, options) ?? parseNumber(value, options);

    if (!parseData) return null;

    const { z } = parseData;

    if (z) {
        /**
         * '1 23' => 'm d' ----- error
         * '2/3' => 'm/d' ----- This is supported by Excel
         */
        if (ignoreCommonPatterns.has(z)) return null;

        /**
         * If the pattern is 'h:mm AM/PM' or 'hh:mm AM/PM', we need to check if the value ends with ' A', ' P', ' AM', or ' PM'.
         * '5A' => 'h:mm AM/PM' ----- error
         * '5 A' => 'h:mm AM/PM' ----- This is supported by Excel
         * '5:00 AM' => 'h:mm AM/PM' ----- correct
         */
        if (ignoreAMPMPatterns.has(z) && !/\s(A|AM|P|PM)$/i.test(value)) return null;

        /**
         * Verify by formatting back to string
         * '1000,' => '#,##0,' ----- error
         * '1000,1.00' => '#,##0.00' ----- error
         * '$1000' => '$#,##0' ----- true
         */
        if (z.includes('#,##0')) {
            if (/[.,]$/.test(value)) return null;

            const normalized = value.replace(CURRENCY_SYMBOL_PREFIX_REG, '').trim();

            if (normalized.includes(',')) {
                const validGrouping = /^-?\d{1,3}(,\d{3})*(\.\d+)?$/.test(normalized);
                if (!validGrouping) return null;
            }
        }
    }

    return parseData;
};