summaryrefslogtreecommitdiff
path: root/shared/localization/src/getLocAttributes.ts
blob: 2f462db72edd98d0aaa6fbf7ada5d41516be2f94 (plain)
1
2
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { getPageDir } from './getPageDir';

/**
 * Checks if a string contains language script
 * ex. "zh-Hant-HK", "zh-Hant-TW", "zh-Hans-CN"
 * @param {string} locale
 * @returns {boolean}
 */
const hasSupportedLanguageScript = (locale: string): boolean => {
    const SUPPORTED_SCRIPTS = ['-hans-', '-hant-'];

    const formattedLocale = locale.toLowerCase();
    return SUPPORTED_SCRIPTS.some((item) => formattedLocale.includes(item));
};

/**
 *
 * BCP47 https://www.w3.org/International/articles/language-tags/
 *
 * @param {string} language https://en.wikipedia.org/wiki/ISO_639
 * @param {string} region https://en.wikipedia.org/wiki/ISO_3166-1
 * @param {string} script https://en.wikipedia.org/wiki/ISO_15924

 */
const buildBcp47String = (
    language: string,
    region: string,
    script?: string,
): string => {
    let capitalizeScript: string | null = null;
    if (script) {
        capitalizeScript =
            script[0].toUpperCase() + script.substring(1).toLowerCase();
    }
    let bcp47Arr = [
        language.toLowerCase(),
        capitalizeScript,
        region.toUpperCase(),
    ];

    return bcp47Arr.filter((item) => item !== null).join('-');
};

/**
 * @description
 * get values to be used in <html> tag lang and dir attributes.
 *
 * @param {string} locale
 * @returns { { dir: 'rtl' | 'ltr', lang: string }} HTML dir + lang values
 */

export function getLocAttributes(locale: string): {
    dir: 'rtl' | 'ltr';
    lang: string;
} {
    const pageDir = getPageDir(locale);
    let bcp47 = locale;

    const localeStrings = locale.split('-');

    // region index in array
    const regionIndex = hasSupportedLanguageScript(locale) ? 2 : 1;

    const language = localeStrings[0];
    const script = hasSupportedLanguageScript(locale)
        ? localeStrings[1]
        : undefined;
    const region = localeStrings[regionIndex];

    if (language && region) {
        bcp47 = buildBcp47String(language, region, script);
    }

    return {
        dir: pageDir,
        lang: bcp47,
    };
}