lngs-to-load.ts 1.3 KB
Newer Older
P
Peter Pan 已提交
1
import {FallbackLng} from 'i18next';
P
Peter Pan 已提交
2

P
Peter Pan 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
export const lngsToLoad = (initialLng: string | null, fallbackLng: FallbackLng | false, otherLanguages?: string[]) => {
    const languages = [];

    if (initialLng) {
        languages.push(initialLng);
    }

    if (fallbackLng) {
        if (typeof fallbackLng === 'string' && fallbackLng !== initialLng) {
            languages.push(fallbackLng);
        }

        if (Array.isArray(fallbackLng)) {
            languages.push(...fallbackLng);
        } else if (initialLng && typeof fallbackLng !== 'string') {
            if (typeof fallbackLng[initialLng] === 'string') {
                languages.push(fallbackLng[initialLng]);
            } else if (Array.isArray(fallbackLng[initialLng])) {
                languages.push(...fallbackLng[initialLng]);
            }
        }

        if (!Array.isArray(fallbackLng) && typeof fallbackLng !== 'string' && fallbackLng.default) {
            languages.push(fallbackLng.default);
        }
    }

    if (initialLng && initialLng.includes('-') && Array.isArray(otherLanguages)) {
        const [languageFromLocale] = initialLng.split('-');
        otherLanguages.forEach(otherLanguage => {
            if (otherLanguage === languageFromLocale) {
                languages.push(otherLanguage);
            }
        });
    }

    return languages;
};