@tolgee/format-icu 4.9.3-rc.04b22e6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ jest.autoMockOff();
2
+ import { FormatIcuCreator } from './FormatIcuCreator';
3
+
4
+ describe('format icu', () => {
5
+ it('formats simple string', () => {
6
+ const formatter = FormatIcuCreator();
7
+ const result = formatter.format({
8
+ translation: 'result is {number, number}',
9
+ params: { number: 42000 },
10
+ language: 'en',
11
+ });
12
+ expect(result).toEqual('result is 42,000');
13
+ });
14
+
15
+ it('fixes invalid locale', () => {
16
+ const formatter = FormatIcuCreator() as any;
17
+ expect(formatter.getLocale('en_GB')).toEqual('en-GB');
18
+ expect(formatter.getLocale('en_GB-nonsenceeeee')).toEqual('en-GB');
19
+ expect(formatter.getLocale('cs CZ')).toEqual('cs-CZ');
20
+ });
21
+ });
@@ -0,0 +1,44 @@
1
+ import IntlMessageFormat from 'intl-messageformat';
2
+ import type { FinalFormatterInterface } from '@tolgee/core';
3
+
4
+ export const FormatIcuCreator = (): FinalFormatterInterface => {
5
+ const locales = new Map() as Map<string, string>;
6
+
7
+ function isLocaleValid(locale: string) {
8
+ try {
9
+ return Boolean(Intl.NumberFormat.supportedLocalesOf(locale).length);
10
+ } catch {
11
+ return false;
12
+ }
13
+ }
14
+
15
+ function getLocale(language: string) {
16
+ if (!locales.get(language)) {
17
+ let localeCandidate: string = String(language).replace(/[^a-zA-Z]/g, '-');
18
+ while (!isLocaleValid(localeCandidate)) {
19
+ localeCandidate =
20
+ localeCandidate.split('-').slice(0, -1).join('-') || 'en';
21
+ }
22
+ locales.set(language, localeCandidate);
23
+ }
24
+ return locales.get(language);
25
+ }
26
+
27
+ const format: FinalFormatterInterface['format'] = ({
28
+ translation,
29
+ language,
30
+ params,
31
+ }) => {
32
+ const ignoreTag = !Object.values(params || {}).find(
33
+ (p) => typeof p === 'function'
34
+ );
35
+
36
+ const locale = getLocale(language);
37
+
38
+ return new IntlMessageFormat(translation, locale, undefined, {
39
+ ignoreTag,
40
+ }).format(params);
41
+ };
42
+
43
+ return Object.freeze({ getLocale, format });
44
+ };
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export { FormatIcu } from './FormatIcu';