@snack-uikit/locale 0.13.0 → 0.13.1-preview-3df2b4f3.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.
Files changed (29) hide show
  1. package/README.md +63 -11
  2. package/dist/cjs/components/LocaleProvider/LocaleProvider.d.ts +33 -7
  3. package/dist/cjs/components/LocaleProvider/LocaleProvider.js +76 -34
  4. package/dist/cjs/components/LocaleProvider/Sample.d.ts +10 -0
  5. package/dist/cjs/components/LocaleProvider/Sample.js +117 -0
  6. package/dist/cjs/components/LocaleProvider/index.d.ts +1 -2
  7. package/dist/cjs/components/LocaleProvider/index.js +8 -3
  8. package/dist/cjs/typeUtils.d.ts +0 -25
  9. package/dist/cjs/types.d.ts +10 -6
  10. package/dist/esm/components/LocaleProvider/LocaleProvider.d.ts +33 -7
  11. package/dist/esm/components/LocaleProvider/LocaleProvider.js +61 -23
  12. package/dist/esm/components/LocaleProvider/Sample.d.ts +10 -0
  13. package/dist/esm/components/LocaleProvider/Sample.js +68 -0
  14. package/dist/esm/components/LocaleProvider/index.d.ts +1 -2
  15. package/dist/esm/components/LocaleProvider/index.js +1 -2
  16. package/dist/esm/typeUtils.d.ts +0 -25
  17. package/dist/esm/types.d.ts +10 -6
  18. package/package.json +2 -2
  19. package/src/components/LocaleProvider/LocaleProvider.tsx +108 -31
  20. package/src/components/LocaleProvider/Sample.tsx +101 -0
  21. package/src/components/LocaleProvider/index.ts +1 -3
  22. package/src/locales/en_GB.ts +3 -1
  23. package/src/typeUtils.ts +0 -49
  24. package/src/types.ts +17 -9
  25. package/dist/cjs/components/LocaleProvider/hooks.d.ts +0 -16
  26. package/dist/cjs/components/LocaleProvider/hooks.js +0 -38
  27. package/dist/esm/components/LocaleProvider/hooks.d.ts +0 -16
  28. package/dist/esm/components/LocaleProvider/hooks.js +0 -30
  29. package/src/components/LocaleProvider/hooks.ts +0 -62
package/README.md CHANGED
@@ -49,20 +49,72 @@ const lang = 'en_GB'; // or 'ru_RU' or 'custom_LANG'
49
49
 
50
50
  [//]: DOCUMENTATION_SECTION_START
51
51
  [//]: THIS_SECTION_IS_AUTOGENERATED_PLEASE_DONT_EDIT_IT
52
-
53
52
  ## LocaleProvider
54
-
55
53
  ### Props
56
-
57
- | name | type | default value | description |
58
- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- | ----------- |
59
- | lang\* | `string` | - | |
60
- | locales | `PartialObjectDeep<Record<string, { Table: { searchPlaceholder: string; noData: { title: string; }; noResults: { title: string; description: string; }; errorData: { title: string; description: string; }; rowsOptionsLabel: string; export: string; groupSelectButton: { ...; }; }; ... 7 more ...; ToastUpload: { ...; }; }>>` | - | |
61
-
54
+ | name | type | default value | description |
55
+ |------|------|---------------|-------------|
56
+ | lang* | "en_GB" \| "ru_RU" | - | |
62
57
  ## useLocale
58
+ ### Props
59
+ | name | type | default value | description |
60
+ |------|------|---------------|-------------|
61
+ | __@iterator@787* | `() => IterableIterator<string>` | - | Iterator |
62
+ | toWellFormed* | `() => string` | - | Returns a string where all lone or out-of-order surrogates have been replaced by the Unicode replacement character (U+FFFD). |
63
+ | isWellFormed* | `() => boolean` | - | Returns true if all leading surrogates and trailing surrogates appear paired and in order. |
64
+ | at* | `(index: number) => string` | - | Returns a new String consisting of the single UTF-16 code unit located at the specified index. @param index The zero-based index of the desired code unit. A negative index will count back from the last item. |
65
+ | replaceAll* | `{ (searchValue: string \| RegExp, replaceValue: string): string; (searchValue: string \| RegExp, replacer: (substring: string, ...args: any[]) => string): string; }` | - | Replace all instances of a substring in a string, using a regular expression or search string. @param searchValue A string to search for. @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. @param searchValue A string to search for. @param replacer A function that returns the replacement text. |
66
+ | matchAll* | `(regexp: RegExp) => IterableIterator<RegExpExecArray>` | - | Matches a string with a regular expression, and returns an iterable of matches containing the results of that search. @param regexp A variable name or string literal containing the regular expression pattern and flags. |
67
+ | trimRight* | `() => string` | - | Removes the trailing white space and line terminator characters from a string. @deprecated A legacy feature for browser compatibility. Use `trimEnd` instead |
68
+ | trimLeft* | `() => string` | - | Removes the leading white space and line terminator characters from a string. @deprecated A legacy feature for browser compatibility. Use `trimStart` instead |
69
+ | trimStart* | `() => string` | - | Removes the leading white space and line terminator characters from a string. |
70
+ | trimEnd* | `() => string` | - | Removes the trailing white space and line terminator characters from a string. |
71
+ | padEnd* | `(maxLength: number, fillString?: string) => string` | - | Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. The padding is applied from the end (right) of the current string. @param maxLength The length of the resulting string once the current string has been padded. If this parameter is smaller than the current string's length, the current string will be returned as it is. @param fillString The string to pad the current string with. If this string is too long, it will be truncated and the left-most part will be applied. The default value for this parameter is " " (U+0020). |
72
+ | padStart* | `(maxLength: number, fillString?: string) => string` | - | Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. The padding is applied from the start (left) of the current string. @param maxLength The length of the resulting string once the current string has been padded. If this parameter is smaller than the current string's length, the current string will be returned as it is. @param fillString The string to pad the current string with. If this string is too long, it will be truncated and the left-most part will be applied. The default value for this parameter is " " (U+0020). |
73
+ | sup* | `() => string` | - | Returns a `<sup>` HTML element @deprecated A legacy feature for browser compatibility |
74
+ | sub* | `() => string` | - | Returns a `<sub>` HTML element @deprecated A legacy feature for browser compatibility |
75
+ | strike* | `() => string` | - | Returns a `<strike>` HTML element @deprecated A legacy feature for browser compatibility |
76
+ | small* | `() => string` | - | Returns a `<small>` HTML element @deprecated A legacy feature for browser compatibility |
77
+ | link* | `(url: string) => string` | - | Returns an `<a>` HTML element and sets the href attribute value @deprecated A legacy feature for browser compatibility |
78
+ | italics* | `() => string` | - | Returns an `<i>` HTML element @deprecated A legacy feature for browser compatibility |
79
+ | fontsize* | `{ (size: number): string; (size: string): string; }` | - | Returns a `<font>` HTML element and sets the size attribute value @deprecated A legacy feature for browser compatibility @deprecated A legacy feature for browser compatibility |
80
+ | fontcolor* | `(color: string) => string` | - | Returns a `<font>` HTML element and sets the color attribute value @deprecated A legacy feature for browser compatibility |
81
+ | fixed* | `() => string` | - | Returns a `<tt>` HTML element @deprecated A legacy feature for browser compatibility |
82
+ | bold* | `() => string` | - | Returns a `<b>` HTML element @deprecated A legacy feature for browser compatibility |
83
+ | blink* | `() => string` | - | Returns a `<blink>` HTML element @deprecated A legacy feature for browser compatibility |
84
+ | big* | `() => string` | - | Returns a `<big>` HTML element @deprecated A legacy feature for browser compatibility |
85
+ | anchor* | `(name: string) => string` | - | Returns an `<a>` HTML anchor element and sets the name attribute to the text value @deprecated A legacy feature for browser compatibility @param name |
86
+ | startsWith* | `(searchString: string, position?: number) => boolean` | - | Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at position. Otherwise returns false. |
87
+ | repeat* | `(count: number) => string` | - | Returns a String value that is made from count copies appended together. If count is 0, the empty string is returned. @param count number of copies to append |
88
+ | normalize* | `{ (form: "NFC" \| "NFD" \| "NFKC" \| "NFKD"): string; (form?: string): string; }` | - | Returns the String value result of normalizing the string into the normalization form named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms. @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default is "NFC" @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default is "NFC" |
89
+ | endsWith* | `(searchString: string, endPosition?: number) => boolean` | - | Returns true if the sequence of elements of searchString converted to a String is the same as the corresponding elements of this object (converted to a String) starting at endPosition – length(this). Otherwise returns false. |
90
+ | includes* | `(searchString: string, position?: number) => boolean` | - | Returns true if searchString appears as a substring of the result of converting this object to a String, at one or more positions that are greater than or equal to position; otherwise, returns false. @param searchString search string @param position If position is undefined, 0 is assumed, so as to search all of the String. |
91
+ | codePointAt* | `(pos: number) => number` | - | Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point value of the UTF-16 encoded code point starting at the string element at position pos in the String resulting from converting this object to a String. If there is no element at that position, the result is undefined. If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos. |
92
+ | substr* | `(from: number, length?: number) => string` | - | Gets a substring beginning at the specified location and having the specified length. @deprecated A legacy feature for browser compatibility @param from The starting position of the desired substring. The index of the first character in the string is zero. @param length The number of characters to include in the returned substring. |
93
+ | length* | `number` | - | Returns the length of a String object. |
94
+ | trim* | `() => string` | - | Removes the leading and trailing white space and line terminator characters from a string. |
95
+ | toLocaleUpperCase* | `{ (locales?: string \| string[]): string; (locales?: LocalesArgument): string; }` | - | Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. |
96
+ | toUpperCase* | `() => string` | - | Converts all the alphabetic characters in a string to uppercase. |
97
+ | toLocaleLowerCase* | `{ (locales?: string \| string[]): string; (locales?: LocalesArgument): string; }` | - | Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. |
98
+ | toLowerCase* | `() => string` | - | Converts all the alphabetic characters in a string to lowercase. |
99
+ | substring* | `(start: number, end?: number) => string` | - | Returns the substring at the specified location within a String object. @param start The zero-based index number indicating the beginning of the substring. @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. If end is omitted, the characters from start through the end of the original string are returned. |
100
+ | split* | `{ (separator: string \| RegExp, limit?: number): string[]; (splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[]; }` | - | Split a string into substrings using the specified separator and return them as an array. @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. @param limit A value used to limit the number of elements returned in the array. @param splitter An object that can split a string. @param limit A value used to limit the number of elements returned in the array. |
101
+ | slice* | `(start?: number, end?: number) => string` | - | Returns a section of a string. @param start The index to the beginning of the specified portion of stringObj. @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. If this value is not specified, the substring continues to the end of stringObj. |
102
+ | search* | `{ (regexp: string \| RegExp): number; (searcher: { [Symbol.search](string: string): number; }): number; }` | - | Finds the first substring match in a regular expression search. @param regexp The regular expression pattern and applicable flags. @param searcher An object which supports searching within a string. |
103
+ | replace* | `{ (searchValue: string \| RegExp, replaceValue: string): string; (searchValue: string \| RegExp, replacer: (substring: string, ...args: any[]) => string): string; (searchValue: { ...; }, replaceValue: string): string; (searchValue: { ...; }, replacer: (substring: string, ...args: any[]) => string): string; }` | - | Replaces text in a string, using a regular expression or search string. Passes a string and {@linkcode replaceValue} to the `[Symbol.replace]` method on {@linkcode searchValue}. This method is expected to implement its own replacement algorithm. Replaces text in a string, using an object that supports replacement within a string. @param searchValue A string or regular expression to search for. @param replaceValue A string containing the text to replace. When the {@linkcode searchValue } is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue } is replaced. @param searchValue A string to search for. @param replacer A function that returns the replacement text. @param searchValue An object that supports searching for and replacing matches within a string. @param replaceValue The replacement text. @param searchValue A object can search for and replace matches within a string. @param replacer A function that returns the replacement text. |
104
+ | match* | `{ (regexp: string \| RegExp): RegExpMatchArray; (matcher: { [Symbol.match](string: string): RegExpMatchArray; }): RegExpMatchArray; }` | - | Matches a string with a regular expression, and returns an array containing the results of that search. Matches a string or an object that supports being matched against, and returns an array containing the results of that search, or null if no matches are found. @param regexp A variable name or string literal containing the regular expression pattern and flags. @param matcher An object that supports being matched against. |
105
+ | localeCompare* | `{ (that: string): number; (that: string, locales?: string \| string[], options?: CollatorOptions): number; (that: string, locales?: LocalesArgument, options?: CollatorOptions): number; }` | - | Determines whether two strings are equivalent in the current locale. Determines whether two strings are equivalent in the current or specified locale. @param that String to compare to target string @param that String to compare to target string @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. @param that String to compare to target string @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. |
106
+ | lastIndexOf* | `(searchString: string, position?: number) => number` | - | Returns the last occurrence of a substring in the string. @param searchString The substring to search for. @param position The index at which to begin searching. If omitted, the search begins at the end of the string. |
107
+ | indexOf* | `(searchString: string, position?: number) => number` | - | Returns the position of the first occurrence of a substring. @param searchString The substring to search for in the string @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. |
108
+ | concat* | `(...strings: string[]) => string` | - | Returns a string that contains the concatenation of two or more strings. @param strings The strings to append to the end of the string. |
109
+ | charCodeAt* | `(index: number) => number` | - | Returns the Unicode value of the character at the specified location. @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. |
110
+ | charAt* | `(pos: number) => string` | - | Returns the character at the specified index. @param pos The zero-based index of the desired character. |
111
+ | toString | `() => string` | function toString() { [native code] } | Returns a string representation of a string. |
112
+ | valueOf | `() => string` | function valueOf() { [native code] } | Returns the primitive value of the specified object. |
113
+ ## createLocaleContext
114
+ ### Props
115
+ | name | type | default value | description |
116
+ |------|------|---------------|-------------|
117
+ | extendedDictionary | `ExtendedDictionary<D>` | - | |
63
118
 
64
- `helper`
65
-
66
- Inner hook to use translations
67
119
 
68
120
  [//]: DOCUMENTATION_SECTION_END
@@ -1,15 +1,41 @@
1
1
  import { ReactNode } from 'react';
2
- import { LocaleDictionary, LocaleLang, OverrideLocales } from '../../types';
2
+ import { Dictionary, DottedTranslationKey, ExtendedDictionary, LocaleDictionary, LocaleLang } from '../../types';
3
3
  export declare const DEFAULT_LANG = "en_GB";
4
- export type LocaleContextType = {
4
+ export type LocaleContextType<D extends Dictionary> = {
5
5
  lang: LocaleLang;
6
- locales: OverrideLocales;
7
- localesByLang: LocaleDictionary;
6
+ localesByLang: LocaleDictionary<D>;
8
7
  };
9
- export declare const LocaleContext: import("react").Context<LocaleContextType>;
10
8
  export type LocaleProviderProps = {
11
9
  lang: LocaleLang;
12
- locales?: OverrideLocales;
13
10
  children: ReactNode;
14
11
  };
15
- export declare function LocaleProvider({ lang: langProp, locales: localesProp, children }: LocaleProviderProps): import("react/jsx-runtime").JSX.Element;
12
+ export type ContextOptions<D extends Dictionary> = {
13
+ extendedDictionary?: ExtendedDictionary<D>;
14
+ };
15
+ type LocaleComponentName<D extends Dictionary> = keyof LocaleDictionary<D>;
16
+ type GetLocaleText<D extends Dictionary, T extends keyof LocaleDictionary<D> | undefined = undefined> = (key: DottedTranslationKey<D, T>) => string;
17
+ export declare function createLocaleContext<D extends Dictionary>({ extendedDictionary }: ContextOptions<D>): {
18
+ LocaleContext: import("react").Context<LocaleContextType<D>>;
19
+ LocaleProvider: ({ lang: langProp, children }: LocaleProviderProps) => import("react/jsx-runtime").JSX.Element;
20
+ useLocale: {
21
+ (): {
22
+ t: GetLocaleText<D>;
23
+ lang: LocaleLang;
24
+ };
25
+ <C extends LocaleComponentName<D> = "Table" | "List" | "Chips" | "Fields" | "SearchPrivate" | "ColorPicker" | "Calendar" | "Toolbar" | "ToastUpload" | keyof D>(componentName: C): {
26
+ t: GetLocaleText<D, C>;
27
+ lang: LocaleLang;
28
+ };
29
+ };
30
+ };
31
+ export declare const LocaleProvider: ({ lang: langProp, children }: LocaleProviderProps) => import("react/jsx-runtime").JSX.Element, useLocale: {
32
+ (): {
33
+ t: GetLocaleText<Dictionary>;
34
+ lang: LocaleLang;
35
+ };
36
+ <C extends string = string>(componentName: C): {
37
+ t: GetLocaleText<Dictionary, C>;
38
+ lang: LocaleLang;
39
+ };
40
+ };
41
+ export {};
@@ -5,48 +5,90 @@ var __importDefault = void 0 && (void 0).__importDefault || function (mod) {
5
5
  "default": mod
6
6
  };
7
7
  };
8
+ var _a;
8
9
  Object.defineProperty(exports, "__esModule", {
9
10
  value: true
10
11
  });
11
- exports.LocaleContext = exports.DEFAULT_LANG = void 0;
12
- exports.LocaleProvider = LocaleProvider;
12
+ exports.useLocale = exports.LocaleProvider = exports.DEFAULT_LANG = void 0;
13
+ exports.createLocaleContext = createLocaleContext;
13
14
  const jsx_runtime_1 = require("react/jsx-runtime");
14
15
  const lodash_merge_1 = __importDefault(require("lodash.merge"));
15
16
  const react_1 = require("react");
16
17
  const locales_1 = require("../../locales");
17
18
  exports.DEFAULT_LANG = 'en_GB';
18
- exports.LocaleContext = (0, react_1.createContext)({
19
- lang: exports.DEFAULT_LANG,
20
- locales: locales_1.LOCALES,
21
- localesByLang: locales_1.LOCALES.en_GB
22
- });
23
- function LocaleProvider(_ref) {
19
+ function mergeLocaleWithExtension(extension) {
20
+ return (0, lodash_merge_1.default)({}, locales_1.LOCALES, extension);
21
+ }
22
+ function createLocaleContext(_ref) {
24
23
  let {
25
- lang: langProp,
26
- locales: localesProp,
27
- children
24
+ extendedDictionary
28
25
  } = _ref;
29
- const locales = (0, react_1.useMemo)(() => {
30
- if (localesProp) {
31
- return (0, lodash_merge_1.default)({}, locales_1.LOCALES, localesProp);
32
- }
33
- return locales_1.LOCALES;
34
- }, [localesProp]);
35
- const lang = (0, react_1.useMemo)(() => langProp.replace('-', '_'), [langProp]);
36
- const localesByLang = (0, react_1.useMemo)(() => {
37
- let localesObj = locales[lang];
38
- if (!localesObj) {
39
- console.warn(`Snack-uikit: localization for lang ${lang} was not found. Make sure you are using correct lang or passed proper locales to LocaleProvider. For now default language (${exports.DEFAULT_LANG}) will be used`);
40
- localesObj = locales[exports.DEFAULT_LANG];
41
- }
42
- return localesObj;
43
- }, [lang, locales]);
44
- return (0, jsx_runtime_1.jsx)(exports.LocaleContext.Provider, {
45
- value: {
46
- lang,
47
- locales,
48
- localesByLang
49
- },
50
- children: children
26
+ const locales = mergeLocaleWithExtension(extendedDictionary);
27
+ const LocaleContext = (0, react_1.createContext)({
28
+ lang: exports.DEFAULT_LANG,
29
+ localesByLang: locales.en_GB
51
30
  });
52
- }
31
+ function LocaleProvider(_ref2) {
32
+ let {
33
+ lang: langProp,
34
+ children
35
+ } = _ref2;
36
+ const lang = (0, react_1.useMemo)(() => langProp.replace('-', '_'), [langProp]);
37
+ const localesByLang = (0, react_1.useMemo)(() => {
38
+ let localesObj = locales[lang];
39
+ if (!localesObj) {
40
+ console.warn(`Snack-uikit: localization for lang ${lang} was not found. Make sure you are using correct lang or passed proper locales to LocaleProvider. For now default language (${exports.DEFAULT_LANG}) will be used`);
41
+ localesObj = locales[exports.DEFAULT_LANG];
42
+ }
43
+ return localesObj;
44
+ }, [lang]);
45
+ return (0, jsx_runtime_1.jsx)(LocaleContext.Provider, {
46
+ value: {
47
+ lang,
48
+ localesByLang
49
+ },
50
+ children: children
51
+ });
52
+ }
53
+ function useLocale(componentName) {
54
+ const {
55
+ localesByLang,
56
+ lang
57
+ } = (0, react_1.useContext)(LocaleContext);
58
+ const locales = (0, react_1.useMemo)(() => {
59
+ if (!componentName) {
60
+ return localesByLang;
61
+ }
62
+ return localesByLang[componentName] || {};
63
+ }, [componentName, localesByLang]);
64
+ const getLocaleText = (0, react_1.useCallback)(key => {
65
+ let translation = '';
66
+ const complexKey = key.split('.');
67
+ if (complexKey.length === 1) {
68
+ translation = locales[key];
69
+ } else {
70
+ translation = complexKey.reduce((acc, cur) => {
71
+ if (typeof acc === 'string') {
72
+ return acc;
73
+ }
74
+ return acc[cur];
75
+ }, locales);
76
+ }
77
+ if (!(translation === null || translation === void 0 ? void 0 : translation.length)) {
78
+ console.warn(`Snack-uikit: the '${key}' key is not found in the current locale '${lang}'.`);
79
+ return key;
80
+ }
81
+ return translation;
82
+ }, [lang, locales]);
83
+ return {
84
+ t: getLocaleText,
85
+ lang
86
+ };
87
+ }
88
+ return {
89
+ LocaleContext,
90
+ LocaleProvider,
91
+ useLocale
92
+ };
93
+ }
94
+ _a = createLocaleContext({}), exports.LocaleProvider = _a.LocaleProvider, exports.useLocale = _a.useLocale;
@@ -0,0 +1,10 @@
1
+ import { ReactNode } from 'react';
2
+ type SampleWrapperProps = {
3
+ children: ReactNode;
4
+ };
5
+ export declare function SampleWrapper({ children }: SampleWrapperProps): import("react/jsx-runtime").JSX.Element;
6
+ export declare function OldDictionaryItemSample(): import("react/jsx-runtime").JSX.Element;
7
+ export declare function NewDictionarySample(): import("react/jsx-runtime").JSX.Element;
8
+ export declare function NewDictSimpleTranslationComponent(): import("react/jsx-runtime").JSX.Element;
9
+ export declare function NewDictDeepTranslationComponent(): import("react/jsx-runtime").JSX.Element;
10
+ export {};
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SampleWrapper = SampleWrapper;
7
+ exports.OldDictionaryItemSample = OldDictionaryItemSample;
8
+ exports.NewDictionarySample = NewDictionarySample;
9
+ exports.NewDictSimpleTranslationComponent = NewDictSimpleTranslationComponent;
10
+ exports.NewDictDeepTranslationComponent = NewDictDeepTranslationComponent;
11
+ const jsx_runtime_1 = require("react/jsx-runtime");
12
+ const LocaleProvider_1 = require("./LocaleProvider");
13
+ const sampleExtensionEn = {
14
+ Table: {
15
+ searchPlaceholder: 'SearchOverriden'
16
+ },
17
+ ButtonPredefined: {
18
+ create: 'Create',
19
+ cancel: 'Cancel',
20
+ refetch: 'Refetch'
21
+ },
22
+ Site: {
23
+ Section: {
24
+ Basic: {
25
+ ShowMore: 'Show More'
26
+ },
27
+ PersonalManager: {
28
+ title: 'More than regular support',
29
+ subtitle: 'Full support for solving your problems and achieving business results'
30
+ }
31
+ }
32
+ }
33
+ };
34
+ const sampleExtensionRu = {
35
+ Table: {
36
+ searchPlaceholder: 'SearchOverriden'
37
+ },
38
+ ButtonPredefined: {
39
+ create: 'Создать',
40
+ cancel: 'Отмена',
41
+ refetch: 'Обновить'
42
+ },
43
+ Site: {
44
+ Section: {
45
+ Basic: {
46
+ ShowMore: 'Показать еще'
47
+ },
48
+ PersonalManager: {
49
+ title: 'Больше чем просто поддержка',
50
+ subtitle: 'Полное сопровождение для решения ваших задач и понятный бизнес-результат'
51
+ }
52
+ }
53
+ }
54
+ };
55
+ const extension = {
56
+ en_GB: sampleExtensionEn,
57
+ ru_RU: sampleExtensionRu
58
+ };
59
+ const {
60
+ LocaleProvider,
61
+ useLocale
62
+ } = (0, LocaleProvider_1.createLocaleContext)({
63
+ extendedDictionary: extension
64
+ });
65
+ function SampleWrapper(_ref) {
66
+ let {
67
+ children
68
+ } = _ref;
69
+ return (0, jsx_runtime_1.jsx)(LocaleProvider, {
70
+ lang: 'ru_RU',
71
+ children: children
72
+ });
73
+ }
74
+ function OldDictionaryItemSample() {
75
+ const {
76
+ t
77
+ } = useLocale('Table');
78
+ return (0, jsx_runtime_1.jsxs)("div", {
79
+ children: [(0, jsx_runtime_1.jsx)("div", {
80
+ children: t('searchPlaceholder')
81
+ }), (0, jsx_runtime_1.jsx)("div", {
82
+ children: t('noResults.title')
83
+ })]
84
+ });
85
+ }
86
+ function NewDictionarySample() {
87
+ const {
88
+ t
89
+ } = useLocale();
90
+ return (0, jsx_runtime_1.jsxs)("div", {
91
+ children: [(0, jsx_runtime_1.jsx)("div", {
92
+ children: t('Table.searchPlaceholder')
93
+ }), (0, jsx_runtime_1.jsx)("div", {
94
+ children: t('Table.noResults.title')
95
+ }), (0, jsx_runtime_1.jsx)("div", {
96
+ children: t('ButtonPredefined.create')
97
+ }), (0, jsx_runtime_1.jsx)("div", {
98
+ children: t('Site.Section.PersonalManager.title')
99
+ })]
100
+ });
101
+ }
102
+ function NewDictSimpleTranslationComponent() {
103
+ const {
104
+ t
105
+ } = useLocale('ButtonPredefined');
106
+ return (0, jsx_runtime_1.jsx)("div", {
107
+ children: t('create')
108
+ });
109
+ }
110
+ function NewDictDeepTranslationComponent() {
111
+ const {
112
+ t
113
+ } = useLocale('Site');
114
+ return (0, jsx_runtime_1.jsx)("div", {
115
+ children: t('Section.PersonalManager.title')
116
+ });
117
+ }
@@ -1,2 +1 @@
1
- export { type LocaleProviderProps, LocaleProvider } from './LocaleProvider';
2
- export { useLocale } from './hooks';
1
+ export { type LocaleProviderProps, LocaleProvider, useLocale, createLocaleContext } from './LocaleProvider';
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.useLocale = exports.LocaleProvider = void 0;
6
+ exports.createLocaleContext = exports.useLocale = exports.LocaleProvider = void 0;
7
7
  var LocaleProvider_1 = require("./LocaleProvider");
8
8
  Object.defineProperty(exports, "LocaleProvider", {
9
9
  enumerable: true,
@@ -11,10 +11,15 @@ Object.defineProperty(exports, "LocaleProvider", {
11
11
  return LocaleProvider_1.LocaleProvider;
12
12
  }
13
13
  });
14
- var hooks_1 = require("./hooks");
15
14
  Object.defineProperty(exports, "useLocale", {
16
15
  enumerable: true,
17
16
  get: function () {
18
- return hooks_1.useLocale;
17
+ return LocaleProvider_1.useLocale;
18
+ }
19
+ });
20
+ Object.defineProperty(exports, "createLocaleContext", {
21
+ enumerable: true,
22
+ get: function () {
23
+ return LocaleProvider_1.createLocaleContext;
19
24
  }
20
25
  });
@@ -1,28 +1,3 @@
1
- type Primitive = null | undefined | string | number | boolean | symbol | bigint;
2
- type BuiltIns = Primitive | void | Date | RegExp;
3
- export type PartialDeep<T> = T extends BuiltIns | ((...arguments_: unknown[]) => unknown) | (new (...arguments_: unknown[]) => unknown) ? T : T extends Map<infer KeyType, infer ValueType> ? PartialMapDeep<KeyType, ValueType> : T extends Set<infer ItemType> ? PartialSetDeep<ItemType> : T extends ReadonlyMap<infer KeyType, infer ValueType> ? PartialReadonlyMapDeep<KeyType, ValueType> : T extends ReadonlySet<infer ItemType> ? PartialReadonlySetDeep<ItemType> : T extends object ? PartialObjectDeep<T> : unknown;
4
- /**
5
- Same as `PartialDeep`, but accepts only `Map`s and as inputs. Internal helper for `PartialDeep`.
6
- */
7
- type PartialMapDeep<KeyType, ValueType> = unknown & Map<PartialDeep<KeyType>, PartialDeep<ValueType>>;
8
- /**
9
- Same as `PartialDeep`, but accepts only `Set`s as inputs. Internal helper for `PartialDeep`.
10
- */
11
- type PartialSetDeep<T> = unknown & Set<PartialDeep<T>>;
12
- /**
13
- Same as `PartialDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `PartialDeep`.
14
- */
15
- type PartialReadonlyMapDeep<KeyType, ValueType> = unknown & ReadonlyMap<PartialDeep<KeyType>, PartialDeep<ValueType>>;
16
- /**
17
- Same as `PartialDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `PartialDeep`.
18
- */
19
- type PartialReadonlySetDeep<T> = unknown & ReadonlySet<PartialDeep<T>>;
20
- /**
21
- Same as `PartialDeep`, but accepts only `object`s as inputs. Internal helper for `PartialDeep`.
22
- */
23
- type PartialObjectDeep<ObjectType extends object> = {
24
- [KeyType in keyof ObjectType]?: PartialDeep<ObjectType[KeyType]>;
25
- };
26
1
  /**
27
2
  * https://stackoverflow.com/a/73179989
28
3
  */
@@ -1,7 +1,11 @@
1
1
  import { LOCALES } from './locales';
2
- import { PartialDeep, PathsToProps } from './typeUtils';
3
- export type KnownLocaleLang = keyof typeof LOCALES;
4
- export type LocaleLang = KnownLocaleLang | string;
5
- export type LocaleDictionary = typeof LOCALES.en_GB;
6
- export type OverrideLocales = PartialDeep<Record<LocaleLang, LocaleDictionary>>;
7
- export type DottedTranslationKey<C extends keyof LocaleDictionary | undefined = undefined> = C extends keyof LocaleDictionary ? PathsToProps<LocaleDictionary[C], string> : PathsToProps<LocaleDictionary, string>;
2
+ import { PathsToProps } from './typeUtils';
3
+ export type LocaleLang = keyof typeof LOCALES;
4
+ export type TranslatedEntity = {
5
+ [key: string]: string | TranslatedEntity;
6
+ };
7
+ export type Dictionary = Record<string, TranslatedEntity>;
8
+ export type LocaleDictionary<D extends Dictionary> = typeof LOCALES.en_GB & D;
9
+ export type Locales<D extends Dictionary> = Record<LocaleLang, LocaleDictionary<D>>;
10
+ export type DottedTranslationKey<D extends Dictionary, C extends keyof LocaleDictionary<D> | undefined = undefined> = C extends keyof LocaleDictionary<D> ? PathsToProps<LocaleDictionary<D>[C], string> : PathsToProps<LocaleDictionary<D>, string>;
11
+ export type ExtendedDictionary<D> = Record<LocaleLang, D>;
@@ -1,15 +1,41 @@
1
1
  import { ReactNode } from 'react';
2
- import { LocaleDictionary, LocaleLang, OverrideLocales } from '../../types';
2
+ import { Dictionary, DottedTranslationKey, ExtendedDictionary, LocaleDictionary, LocaleLang } from '../../types';
3
3
  export declare const DEFAULT_LANG = "en_GB";
4
- export type LocaleContextType = {
4
+ export type LocaleContextType<D extends Dictionary> = {
5
5
  lang: LocaleLang;
6
- locales: OverrideLocales;
7
- localesByLang: LocaleDictionary;
6
+ localesByLang: LocaleDictionary<D>;
8
7
  };
9
- export declare const LocaleContext: import("react").Context<LocaleContextType>;
10
8
  export type LocaleProviderProps = {
11
9
  lang: LocaleLang;
12
- locales?: OverrideLocales;
13
10
  children: ReactNode;
14
11
  };
15
- export declare function LocaleProvider({ lang: langProp, locales: localesProp, children }: LocaleProviderProps): import("react/jsx-runtime").JSX.Element;
12
+ export type ContextOptions<D extends Dictionary> = {
13
+ extendedDictionary?: ExtendedDictionary<D>;
14
+ };
15
+ type LocaleComponentName<D extends Dictionary> = keyof LocaleDictionary<D>;
16
+ type GetLocaleText<D extends Dictionary, T extends keyof LocaleDictionary<D> | undefined = undefined> = (key: DottedTranslationKey<D, T>) => string;
17
+ export declare function createLocaleContext<D extends Dictionary>({ extendedDictionary }: ContextOptions<D>): {
18
+ LocaleContext: import("react").Context<LocaleContextType<D>>;
19
+ LocaleProvider: ({ lang: langProp, children }: LocaleProviderProps) => import("react/jsx-runtime").JSX.Element;
20
+ useLocale: {
21
+ (): {
22
+ t: GetLocaleText<D>;
23
+ lang: LocaleLang;
24
+ };
25
+ <C extends LocaleComponentName<D> = "Table" | "List" | "Chips" | "Fields" | "SearchPrivate" | "ColorPicker" | "Calendar" | "Toolbar" | "ToastUpload" | keyof D>(componentName: C): {
26
+ t: GetLocaleText<D, C>;
27
+ lang: LocaleLang;
28
+ };
29
+ };
30
+ };
31
+ export declare const LocaleProvider: ({ lang: langProp, children }: LocaleProviderProps) => import("react/jsx-runtime").JSX.Element, useLocale: {
32
+ (): {
33
+ t: GetLocaleText<Dictionary>;
34
+ lang: LocaleLang;
35
+ };
36
+ <C extends string = string>(componentName: C): {
37
+ t: GetLocaleText<Dictionary, C>;
38
+ lang: LocaleLang;
39
+ };
40
+ };
41
+ export {};
@@ -1,28 +1,66 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import merge from 'lodash.merge';
3
- import { createContext, useMemo } from 'react';
3
+ import { createContext, useCallback, useContext, useMemo } from 'react';
4
4
  import { LOCALES } from '../../locales';
5
5
  export const DEFAULT_LANG = 'en_GB';
6
- export const LocaleContext = createContext({
7
- lang: DEFAULT_LANG,
8
- locales: LOCALES,
9
- localesByLang: LOCALES.en_GB,
10
- });
11
- export function LocaleProvider({ lang: langProp, locales: localesProp, children }) {
12
- const locales = useMemo(() => {
13
- if (localesProp) {
14
- return merge({}, LOCALES, localesProp);
15
- }
16
- return LOCALES;
17
- }, [localesProp]);
18
- const lang = useMemo(() => langProp.replace('-', '_'), [langProp]);
19
- const localesByLang = useMemo(() => {
20
- let localesObj = locales[lang];
21
- if (!localesObj) {
22
- console.warn(`Snack-uikit: localization for lang ${lang} was not found. Make sure you are using correct lang or passed proper locales to LocaleProvider. For now default language (${DEFAULT_LANG}) will be used`);
23
- localesObj = locales[DEFAULT_LANG];
24
- }
25
- return localesObj;
26
- }, [lang, locales]);
27
- return _jsx(LocaleContext.Provider, { value: { lang, locales, localesByLang }, children: children });
6
+ function mergeLocaleWithExtension(extension) {
7
+ return merge({}, LOCALES, extension);
28
8
  }
9
+ export function createLocaleContext({ extendedDictionary }) {
10
+ const locales = mergeLocaleWithExtension(extendedDictionary);
11
+ const LocaleContext = createContext({
12
+ lang: DEFAULT_LANG,
13
+ localesByLang: locales.en_GB,
14
+ });
15
+ function LocaleProvider({ lang: langProp, children }) {
16
+ const lang = useMemo(() => langProp.replace('-', '_'), [langProp]);
17
+ const localesByLang = useMemo(() => {
18
+ let localesObj = locales[lang];
19
+ if (!localesObj) {
20
+ console.warn(`Snack-uikit: localization for lang ${lang} was not found. Make sure you are using correct lang or passed proper locales to LocaleProvider. For now default language (${DEFAULT_LANG}) will be used`);
21
+ localesObj = locales[DEFAULT_LANG];
22
+ }
23
+ return localesObj;
24
+ }, [lang]);
25
+ return _jsx(LocaleContext.Provider, { value: { lang, localesByLang }, children: children });
26
+ }
27
+ function useLocale(componentName) {
28
+ const { localesByLang, lang } = useContext(LocaleContext);
29
+ const locales = useMemo(() => {
30
+ if (!componentName) {
31
+ return localesByLang;
32
+ }
33
+ return (localesByLang[componentName] || {});
34
+ }, [componentName, localesByLang]);
35
+ const getLocaleText = useCallback(key => {
36
+ let translation = '';
37
+ const complexKey = key.split('.');
38
+ if (complexKey.length === 1) {
39
+ translation = locales[key];
40
+ }
41
+ else {
42
+ translation = complexKey.reduce((acc, cur) => {
43
+ if (typeof acc === 'string') {
44
+ return acc;
45
+ }
46
+ return acc[cur];
47
+ }, locales);
48
+ }
49
+ if (!(translation === null || translation === void 0 ? void 0 : translation.length)) {
50
+ console.warn(`Snack-uikit: the '${key}' key is not found in the current locale '${lang}'.`);
51
+ return key;
52
+ }
53
+ return translation;
54
+ }, [lang, locales]);
55
+ return {
56
+ t: getLocaleText,
57
+ lang,
58
+ };
59
+ }
60
+ return {
61
+ LocaleContext,
62
+ LocaleProvider,
63
+ useLocale,
64
+ };
65
+ }
66
+ export const { LocaleProvider, useLocale } = createLocaleContext({});
@@ -0,0 +1,10 @@
1
+ import { ReactNode } from 'react';
2
+ type SampleWrapperProps = {
3
+ children: ReactNode;
4
+ };
5
+ export declare function SampleWrapper({ children }: SampleWrapperProps): import("react/jsx-runtime").JSX.Element;
6
+ export declare function OldDictionaryItemSample(): import("react/jsx-runtime").JSX.Element;
7
+ export declare function NewDictionarySample(): import("react/jsx-runtime").JSX.Element;
8
+ export declare function NewDictSimpleTranslationComponent(): import("react/jsx-runtime").JSX.Element;
9
+ export declare function NewDictDeepTranslationComponent(): import("react/jsx-runtime").JSX.Element;
10
+ export {};