/ shared / localization / src / getLocAttributes.ts
getLocAttributes.ts
 1  import { getPageDir } from './getPageDir';
 2  
 3  /**
 4   * Checks if a string contains language script
 5   * ex. "zh-Hant-HK", "zh-Hant-TW", "zh-Hans-CN"
 6   * @param {string} locale
 7   * @returns {boolean}
 8   */
 9  const hasSupportedLanguageScript = (locale: string): boolean => {
10      const SUPPORTED_SCRIPTS = ['-hans-', '-hant-'];
11  
12      const formattedLocale = locale.toLowerCase();
13      return SUPPORTED_SCRIPTS.some((item) => formattedLocale.includes(item));
14  };
15  
16  /**
17   *
18   * BCP47 https://www.w3.org/International/articles/language-tags/
19   *
20   * @param {string} language https://en.wikipedia.org/wiki/ISO_639
21   * @param {string} region https://en.wikipedia.org/wiki/ISO_3166-1
22   * @param {string} script https://en.wikipedia.org/wiki/ISO_15924
23  
24   */
25  const buildBcp47String = (
26      language: string,
27      region: string,
28      script?: string,
29  ): string => {
30      let capitalizeScript: string | null = null;
31      if (script) {
32          capitalizeScript =
33              script[0].toUpperCase() + script.substring(1).toLowerCase();
34      }
35      let bcp47Arr = [
36          language.toLowerCase(),
37          capitalizeScript,
38          region.toUpperCase(),
39      ];
40  
41      return bcp47Arr.filter((item) => item !== null).join('-');
42  };
43  
44  /**
45   * @description
46   * get values to be used in <html> tag lang and dir attributes.
47   *
48   * @param {string} locale
49   * @returns { { dir: 'rtl' | 'ltr', lang: string }} HTML dir + lang values
50   */
51  
52  export function getLocAttributes(locale: string): {
53      dir: 'rtl' | 'ltr';
54      lang: string;
55  } {
56      const pageDir = getPageDir(locale);
57      let bcp47 = locale;
58  
59      const localeStrings = locale.split('-');
60  
61      // region index in array
62      const regionIndex = hasSupportedLanguageScript(locale) ? 2 : 1;
63  
64      const language = localeStrings[0];
65      const script = hasSupportedLanguageScript(locale)
66          ? localeStrings[1]
67          : undefined;
68      const region = localeStrings[regionIndex];
69  
70      if (language && region) {
71          bcp47 = buildBcp47String(language, region, script);
72      }
73  
74      return {
75          dir: pageDir,
76          lang: bcp47,
77      };
78  }