@dloizides/i18n 1.0.1 → 1.2.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.
- package/CHANGELOG.md +19 -0
- package/README.md +27 -0
- package/dist/index.d.mts +23 -1
- package/dist/index.d.ts +23 -1
- package/dist/index.js +42 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +37 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +18 -4
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,25 @@ All notable changes to `@dloizides/i18n` are documented here.
|
|
|
5
5
|
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
|
|
6
6
|
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
EXTRACT-TS-I18N-1 "Fold duplicated i18n and utils into @dloizides/i18n and @dloizides/utils".
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- `createFormatMessage(i18n)` builds the portal `FM(id, p1, p2, p3)` helper that 8 portals carried as a local copy.
|
|
15
|
+
|
|
16
|
+
## [1.1.0] — 2026-10-20
|
|
17
|
+
|
|
18
|
+
D-PAT-15 "Move initI18n out of frontend-devtools so it is dev-only".
|
|
19
|
+
|
|
20
|
+
### Added
|
|
21
|
+
|
|
22
|
+
- `initI18n(options)` + `InitI18nOptions`, moved unchanged from `@dloizides/frontend-devtools`
|
|
23
|
+
(removed there in 2.0.0): wires `react-i18next` into the i18next singleton, runs `.init()` and
|
|
24
|
+
returns the singleton. `i18next` and `react-i18next` are optional peer dependencies, needed only
|
|
25
|
+
by apps that call it.
|
|
26
|
+
|
|
8
27
|
## [1.0.0] — 2026-07-12
|
|
9
28
|
|
|
10
29
|
Initial release. Extracted as the shared i18n runtime for the dloizides RN / RN-web apps, first
|
package/README.md
CHANGED
|
@@ -97,6 +97,33 @@ Prefer **named** in app catalogs. Positional exists so the kit's calls keep work
|
|
|
97
97
|
| `resolveInitialLocale`, `primarySubtag`, `isSupported` | Pure locale resolution. |
|
|
98
98
|
| `readStoredLocale`, `writeStoredLocale`, `applyDocumentLocale`, `browserLanguages` | Environment adapters. |
|
|
99
99
|
|
|
100
|
+
## i18next init factory
|
|
101
|
+
|
|
102
|
+
For apps on i18next + react-i18next (install both; they are optional peers):
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { initI18n } from '@dloizides/i18n';
|
|
106
|
+
import * as Localization from 'expo-localization';
|
|
107
|
+
import en from './locales/en.json';
|
|
108
|
+
|
|
109
|
+
const i18n = initI18n({
|
|
110
|
+
resources: { en: { translation: en } },
|
|
111
|
+
lng: Localization.getLocales()[0]?.languageCode ?? 'en',
|
|
112
|
+
});
|
|
113
|
+
export default i18n;
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
| Option | Default | Notes |
|
|
117
|
+
|---|---|---|
|
|
118
|
+
| `resources` | required | i18next resource bundle. |
|
|
119
|
+
| `lng` | `fallbackLng` | Active language. |
|
|
120
|
+
| `fallbackLng` | `'en'` | Used for missing keys. |
|
|
121
|
+
| `escapeValue` | `false` | React already escapes. |
|
|
122
|
+
| `defaultNS` / `ns` | i18next default | Only for multi-namespace apps. |
|
|
123
|
+
|
|
124
|
+
The init rejection is swallowed (in-memory resources resolve synchronously). Moved here from
|
|
125
|
+
`@dloizides/frontend-devtools` 1.x, which is now a dev-only package.
|
|
126
|
+
|
|
100
127
|
## Catalog conventions
|
|
101
128
|
|
|
102
129
|
Flat, dotted keys, namespaced by screen — `cases.title`, `onboarding.step1.lead`. English is
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
+
import { Resource, i18n } from 'i18next';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* The shared i18n contract.
|
|
@@ -169,4 +170,25 @@ interface LanguageSwitcherProps {
|
|
|
169
170
|
}
|
|
170
171
|
declare function LanguageSwitcher({ colors, accessibilityLabel, testID, }: LanguageSwitcherProps): React.ReactElement;
|
|
171
172
|
|
|
172
|
-
|
|
173
|
+
/** Options for {@link initI18n}: the app's resources and languages; the package owns the init chain. */
|
|
174
|
+
interface InitI18nOptions {
|
|
175
|
+
resources: Resource;
|
|
176
|
+
lng?: string;
|
|
177
|
+
fallbackLng?: string;
|
|
178
|
+
escapeValue?: boolean;
|
|
179
|
+
defaultNS?: string | readonly string[];
|
|
180
|
+
ns?: string | readonly string[];
|
|
181
|
+
}
|
|
182
|
+
/** Wires react-i18next into the i18next singleton, runs `.init()` and returns the singleton. */
|
|
183
|
+
declare function initI18n(options: InitI18nOptions): i18n;
|
|
184
|
+
|
|
185
|
+
/** The slice of an i18next instance that {@link createFormatMessage} needs. */
|
|
186
|
+
interface MessageTranslator {
|
|
187
|
+
t: (id: string, options: Record<string, string>) => string;
|
|
188
|
+
}
|
|
189
|
+
/** Positional-parameter message formatter: `FM(id, p1, p2, p3)` maps to `{{p1}}`..`{{p3}}`. */
|
|
190
|
+
type FormatMessage = (id: string, p1?: string, p2?: string, p3?: string) => string;
|
|
191
|
+
/** Builds the portal `FM()` helper over an initialised i18next instance. */
|
|
192
|
+
declare function createFormatMessage(translator: MessageTranslator): FormatMessage;
|
|
193
|
+
|
|
194
|
+
export { type Catalog, type Catalogs, DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, type FormatMessage, I18nProvider, type I18nProviderProps, type I18nValue, type InitI18nOptions, LanguageSwitcher, type LanguageSwitcherColors, type LanguageSwitcherProps, type LocaleCode, type LocaleOption, type MessageTranslator, type NamedParams, type Translate, applyDocumentLocale, browserLanguages, createFormatMessage, createTranslator, initI18n, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import React from 'react';
|
|
2
|
+
import { Resource, i18n } from 'i18next';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* The shared i18n contract.
|
|
@@ -169,4 +170,25 @@ interface LanguageSwitcherProps {
|
|
|
169
170
|
}
|
|
170
171
|
declare function LanguageSwitcher({ colors, accessibilityLabel, testID, }: LanguageSwitcherProps): React.ReactElement;
|
|
171
172
|
|
|
172
|
-
|
|
173
|
+
/** Options for {@link initI18n}: the app's resources and languages; the package owns the init chain. */
|
|
174
|
+
interface InitI18nOptions {
|
|
175
|
+
resources: Resource;
|
|
176
|
+
lng?: string;
|
|
177
|
+
fallbackLng?: string;
|
|
178
|
+
escapeValue?: boolean;
|
|
179
|
+
defaultNS?: string | readonly string[];
|
|
180
|
+
ns?: string | readonly string[];
|
|
181
|
+
}
|
|
182
|
+
/** Wires react-i18next into the i18next singleton, runs `.init()` and returns the singleton. */
|
|
183
|
+
declare function initI18n(options: InitI18nOptions): i18n;
|
|
184
|
+
|
|
185
|
+
/** The slice of an i18next instance that {@link createFormatMessage} needs. */
|
|
186
|
+
interface MessageTranslator {
|
|
187
|
+
t: (id: string, options: Record<string, string>) => string;
|
|
188
|
+
}
|
|
189
|
+
/** Positional-parameter message formatter: `FM(id, p1, p2, p3)` maps to `{{p1}}`..`{{p3}}`. */
|
|
190
|
+
type FormatMessage = (id: string, p1?: string, p2?: string, p3?: string) => string;
|
|
191
|
+
/** Builds the portal `FM()` helper over an initialised i18next instance. */
|
|
192
|
+
declare function createFormatMessage(translator: MessageTranslator): FormatMessage;
|
|
193
|
+
|
|
194
|
+
export { type Catalog, type Catalogs, DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, type FormatMessage, I18nProvider, type I18nProviderProps, type I18nValue, type InitI18nOptions, LanguageSwitcher, type LanguageSwitcherColors, type LanguageSwitcherProps, type LocaleCode, type LocaleOption, type MessageTranslator, type NamedParams, type Translate, applyDocumentLocale, browserLanguages, createFormatMessage, createTranslator, initI18n, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
package/dist/index.js
CHANGED
|
@@ -3,6 +3,12 @@
|
|
|
3
3
|
var react = require('react');
|
|
4
4
|
var jsxRuntime = require('react/jsx-runtime');
|
|
5
5
|
var reactNative = require('react-native');
|
|
6
|
+
var i18n = require('i18next');
|
|
7
|
+
var reactI18next = require('react-i18next');
|
|
8
|
+
|
|
9
|
+
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
10
|
+
|
|
11
|
+
var i18n__default = /*#__PURE__*/_interopDefault(i18n);
|
|
6
12
|
|
|
7
13
|
// src/createTranslator.ts
|
|
8
14
|
var DEFAULT_FALLBACK_LOCALE = "en";
|
|
@@ -169,6 +175,40 @@ function LanguageSwitcher({
|
|
|
169
175
|
);
|
|
170
176
|
}) });
|
|
171
177
|
}
|
|
178
|
+
var DEFAULT_FALLBACK_LNG = "en";
|
|
179
|
+
var ignoreInitRejection = () => void 0;
|
|
180
|
+
function initI18n(options) {
|
|
181
|
+
const {
|
|
182
|
+
resources,
|
|
183
|
+
lng,
|
|
184
|
+
fallbackLng = DEFAULT_FALLBACK_LNG,
|
|
185
|
+
escapeValue = false,
|
|
186
|
+
defaultNS,
|
|
187
|
+
ns
|
|
188
|
+
} = options;
|
|
189
|
+
i18n__default.default.use(reactI18next.initReactI18next).init({
|
|
190
|
+
lng: lng ?? fallbackLng,
|
|
191
|
+
fallbackLng,
|
|
192
|
+
resources,
|
|
193
|
+
...defaultNS !== void 0 ? { defaultNS } : {},
|
|
194
|
+
...ns !== void 0 ? { ns } : {},
|
|
195
|
+
interpolation: {
|
|
196
|
+
escapeValue
|
|
197
|
+
}
|
|
198
|
+
}).catch(ignoreInitRejection);
|
|
199
|
+
return i18n__default.default;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/createFormatMessage.ts
|
|
203
|
+
function createFormatMessage(translator) {
|
|
204
|
+
return (id, p1, p2, p3) => {
|
|
205
|
+
const options = {};
|
|
206
|
+
if (p1 !== void 0 && p1 !== null) options.p1 = p1;
|
|
207
|
+
if (p2 !== void 0 && p2 !== null) options.p2 = p2;
|
|
208
|
+
if (p3 !== void 0 && p3 !== null) options.p3 = p3;
|
|
209
|
+
return translator.t(id, options);
|
|
210
|
+
};
|
|
211
|
+
}
|
|
172
212
|
|
|
173
213
|
exports.DEFAULT_FALLBACK_LOCALE = DEFAULT_FALLBACK_LOCALE;
|
|
174
214
|
exports.DEFAULT_STORAGE_KEY = DEFAULT_STORAGE_KEY;
|
|
@@ -176,7 +216,9 @@ exports.I18nProvider = I18nProvider;
|
|
|
176
216
|
exports.LanguageSwitcher = LanguageSwitcher;
|
|
177
217
|
exports.applyDocumentLocale = applyDocumentLocale;
|
|
178
218
|
exports.browserLanguages = browserLanguages;
|
|
219
|
+
exports.createFormatMessage = createFormatMessage;
|
|
179
220
|
exports.createTranslator = createTranslator;
|
|
221
|
+
exports.initI18n = initI18n;
|
|
180
222
|
exports.interpolateNamed = interpolateNamed;
|
|
181
223
|
exports.interpolatePositional = interpolatePositional;
|
|
182
224
|
exports.isSupported = isSupported;
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createTranslator.ts","../src/detectLocale.ts","../src/I18nProvider.tsx","../src/LanguageSwitcher.tsx"],"names":["createContext","useState","useCallback","useMemo","jsx","useContext","StyleSheet","View","Pressable","Text"],"mappings":";;;;;;;AAOO,IAAM,uBAAA,GAA0B;AAGvC,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAMO,SAAS,gBAAA,CAAiB,UAAkB,MAAA,EAA6B;AAC9E,EAAA,OAAO,QAAA,CAAS,OAAA;AAAA,IAAQ,YAAA;AAAA,IAAc,CAAC,KAAA,EAAO,IAAA,KAC5C,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,C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MAAA,CAAO,eAAA,GAChB,EAAE,eAAA,EAAiB,MAAA,CAAO,iBAAgB,GAC1C;AAAA,SACR;AAAA,QACA,MAAA,EAAQ,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,OAAO,IAAI,CAAA,CAAA;AAAA,QAChC,OAAA,EAAS,MAAA,CAAO,MAAA,CAAO,IAAI,CAAA;AAAA,QAE3B,0BAAAJ,cAAAA,CAACK,gBAAA,EAAA,EAAK,KAAA,EAAO,CAAC,OAAO,KAAA,EAAO,EAAE,KAAA,EAAO,QAAA,GAAW,OAAO,UAAA,GAAa,MAAA,CAAO,MAAM,CAAA,EAC9E,iBAAO,KAAA,EACV;AAAA,OAAA;AAAA,MAnBK,MAAA,CAAO;AAAA,KAoBd;AAAA,EAEJ,CAAC,CAAA,EACH,CAAA;AAEJ","file":"index.js","sourcesContent":["/**\n * The pure core: catalog lookup + interpolation. No React, no storage, no side effects — so it is\n * trivially unit-testable and reusable outside a component tree (formatters, tests, server render).\n */\nimport type { Catalog, Catalogs, LocaleCode, NamedParams, Translate } from './types';\n\n/** The locale every catalog falls back to, per key. English is authoritative. */\nexport const DEFAULT_FALLBACK_LOCALE = 'en';\n\n/** True for a plain object of named params (as opposed to a positional string/number). */\nfunction isNamedParams(value: unknown): value is NamedParams {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Fill `{name}` placeholders from a params object. An unmatched placeholder is left intact rather\n * than blanked, so a template/param mismatch is visible instead of silently losing text.\n */\nexport function interpolateNamed(template: string, params: NamedParams): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match,\n );\n}\n\n/** Fill `{0}`, `{1}`, `{2}` from positional args (the shared UI kit's calling convention). */\nexport function interpolatePositional(\n template: string,\n params: ReadonlyArray<string | number | undefined>,\n): string {\n return params.reduce<string>(\n (acc, param, index) => (param === undefined ? acc : acc.split(`{${index}}`).join(String(param))),\n template,\n );\n}\n\n/**\n * Look a key up in `locale`, then in `fallbackLocale`, then give back the key itself.\n *\n * The fallback is **per key**, not per catalog: a partially translated locale still shows its\n * translated keys and only falls back for the ones it is missing. That is what lets a new locale\n * ship incrementally instead of all-or-nothing.\n */\nexport function lookup(\n catalogs: Catalogs,\n locale: LocaleCode,\n key: string,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): string {\n const active: Catalog | undefined = catalogs[locale];\n const fallback: Catalog | undefined = catalogs[fallbackLocale];\n return active?.[key] ?? fallback?.[key] ?? key;\n}\n\n/**\n * Build a {@link Translate} bound to one locale. Supports BOTH interpolation styles — see the\n * `Translate` docs for why (positional = the UI kit; named = hand-written app catalogs).\n */\nexport function createTranslator(\n catalogs: Catalogs,\n locale: LocaleCode,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): Translate {\n return (key, p1, p2, p3) => {\n const template = lookup(catalogs, locale, key, fallbackLocale);\n if (isNamedParams(p1)) return interpolateNamed(template, p1);\n return interpolatePositional(template, [p1, p2, p3]);\n };\n}\n","/**\n * Locale resolution + persistence.\n *\n * The resolution order mirrors the v1 AML console (`shared/i18n.js`): a previously stored choice\n * wins, else the browser's preferred language (primary subtag only — `de-AT` → `de`), else the\n * fallback. Storage is best-effort: private mode / a native runtime with no `localStorage` must not\n * throw, it just means the choice does not persist.\n */\nimport type { LocaleCode, LocaleOption } from './types';\n\n/** Default persistence key. Override per app so two apps on one origin don't fight. */\nexport const DEFAULT_STORAGE_KEY = 'dloizides_locale';\n\n/** True when `code` is one of the app's supported locales. Pure. */\nexport function isSupported(locales: readonly LocaleOption[], code: string): boolean {\n return locales.some((l) => l.code === code);\n}\n\n/** `de-AT` → `de`; `EN` → `en`. Pure. */\nexport function primarySubtag(tag: string): string {\n return String(tag).toLowerCase().split('-')[0] ?? '';\n}\n\n/**\n * Pick the locale to start in: stored → browser-preferred → fallback. Pure — the caller supplies\n * the stored value and the browser's language list, which keeps this testable with no globals.\n */\nexport function resolveInitialLocale(\n locales: readonly LocaleOption[],\n stored: string | null,\n preferred: readonly string[],\n fallback: LocaleCode,\n): LocaleCode {\n if (stored && isSupported(locales, stored)) return stored;\n for (const tag of preferred) {\n const primary = primarySubtag(tag);\n if (isSupported(locales, primary)) return primary;\n }\n return fallback;\n}\n\n/** The browser's preferred languages, most-preferred first. `[]` off-web. */\nexport function browserLanguages(): string[] {\n if (typeof navigator === 'undefined') return [];\n const nav = navigator as Navigator & { userLanguage?: string };\n const list = Array.isArray(nav.languages) && nav.languages.length > 0 ? nav.languages : [];\n const single = nav.language ?? nav.userLanguage;\n return list.length > 0 ? [...list] : single ? [single] : [];\n}\n\n/** Read the persisted locale. Never throws (private mode, native, SSR). */\nexport function readStoredLocale(storageKey: string): string | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n return localStorage.getItem(storageKey);\n } catch {\n return null;\n }\n}\n\n/** Persist the locale. Never throws — a failure just means it won't be remembered. */\nexport function writeStoredLocale(storageKey: string, code: LocaleCode): void {\n try {\n if (typeof localStorage === 'undefined') return;\n localStorage.setItem(storageKey, code);\n } catch {\n /* private mode / no storage — the choice simply does not persist */\n }\n}\n\n/**\n * Reflect the locale on the document so CSS can react (`:lang()`, `[dir=\"rtl\"]`). Web-only no-op\n * elsewhere. This is the RTL hook: ship an `rtl: true` locale and the layout can mirror itself\n * without any component changes.\n */\nexport function applyDocumentLocale(locales: readonly LocaleOption[], code: LocaleCode): void {\n if (typeof document === 'undefined') return;\n const option = locales.find((l) => l.code === code);\n document.documentElement.lang = code;\n document.documentElement.dir = option?.rtl ? 'rtl' : 'ltr';\n}\n","/**\n * `I18nProvider` — holds the active locale, exposes a memoized {@link Translate}, persists the\n * user's choice, and reflects `lang`/`dir` on the document.\n *\n * Wiring it to the rest of the shared kit is one line, because {@link Translate} is\n * signature-compatible with the kit's `t` contract:\n *\n * ```tsx\n * <I18nProvider catalogs={CATALOGS} locales={LOCALES}>\n * <KitBridge /> // const { t } = useI18n(); return <UiProvider theme={theme} t={t}>…\n * </I18nProvider>\n * ```\n */\nimport React, { createContext, useCallback, useContext, useMemo, useState } from 'react';\n\nimport { createTranslator, DEFAULT_FALLBACK_LOCALE } from './createTranslator';\nimport {\n applyDocumentLocale,\n browserLanguages,\n DEFAULT_STORAGE_KEY,\n readStoredLocale,\n resolveInitialLocale,\n writeStoredLocale,\n} from './detectLocale';\nimport type { Catalogs, LocaleCode, LocaleOption, Translate } from './types';\n\nexport interface I18nValue {\n /** Resolve a key in the active locale (positional or named interpolation). */\n t: Translate;\n /** The active locale code. */\n locale: LocaleCode;\n /** Switch locale: re-renders consumers, persists the choice, updates `lang`/`dir`. */\n setLocale: (code: LocaleCode) => void;\n /** Every locale the app offers (for a switcher). */\n locales: readonly LocaleOption[];\n}\n\nconst I18nContext = createContext<I18nValue | null>(null);\n\nexport interface I18nProviderProps {\n /** Every locale's catalog. The fallback locale's catalog is required. */\n catalogs: Catalogs;\n /** The locales offered to the user, in display order. */\n locales: readonly LocaleOption[];\n /** Per-key fallback locale. Default `en`. */\n fallbackLocale?: LocaleCode;\n /** localStorage key for the persisted choice. Default `dloizides_locale`. */\n storageKey?: string;\n /** Force a locale (tests / SSR). When set, detection and persistence are skipped. */\n initialLocale?: LocaleCode;\n children: React.ReactNode;\n}\n\nexport function I18nProvider({\n catalogs,\n locales,\n fallbackLocale = DEFAULT_FALLBACK_LOCALE,\n storageKey = DEFAULT_STORAGE_KEY,\n initialLocale,\n children,\n}: I18nProviderProps): React.ReactElement {\n // Resolved once, lazily: stored choice → browser preference → fallback. Reading storage and\n // `navigator` inside the initializer keeps the first paint on the right locale (no flash of\n // English before a `useEffect` corrects it).\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n const resolved = resolveInitialLocale(\n locales,\n readStoredLocale(storageKey),\n browserLanguages(),\n fallbackLocale,\n );\n applyDocumentLocale(locales, resolved);\n return resolved;\n });\n\n const setLocale = useCallback(\n (code: LocaleCode) => {\n setLocaleState(code);\n writeStoredLocale(storageKey, code);\n applyDocumentLocale(locales, code);\n },\n [locales, storageKey],\n );\n\n const t = useMemo(\n () => createTranslator(catalogs, locale, fallbackLocale),\n [catalogs, locale, fallbackLocale],\n );\n\n const value = useMemo<I18nValue>(\n () => ({ t, locale, setLocale, locales }),\n [t, locale, setLocale, locales],\n );\n\n return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;\n}\n\n/** Access the active locale + translate function. Throws outside an {@link I18nProvider}. */\nexport function useI18n(): I18nValue {\n const value = useContext(I18nContext);\n if (value === null) throw new Error('useI18n must be used inside an <I18nProvider>.');\n return value;\n}\n","/**\n * `LanguageSwitcher` — a compact segmented control of locale codes (EN · DE · ES · FR · PT), the\n * same shape as the v1 AML console's `#lang-switcher`.\n *\n * Colours come in as PROPS rather than from a theme context on purpose: it keeps this package\n * dependency-free (no peer dep on the UI kit or a design-token package), so any app — themed or\n * not — can drop it in. Themed apps pass their own tokens, e.g.\n * `colors={{ text: colors.textSecondary, activeText: '#fff', activeBackground: colors.primary }}`.\n */\nimport React, { useCallback } from 'react';\nimport { Pressable, StyleSheet, Text, View, type PressableStateCallbackType } from 'react-native';\n\nimport { useI18n } from './I18nProvider';\nimport type { LocaleCode } from './types';\n\nconst BORDER_RADIUS = 8;\nconst PADDING_H = 9;\nconst PADDING_V = 5;\nconst FONT_SIZE = 12;\nconst GAP = 2;\n/** WCAG 2.5.5: an interactive target must be at least 44×44 px. */\nconst MIN_TARGET = 44;\n\nexport interface LanguageSwitcherColors {\n /** Inactive label colour. */\n text: string;\n /** Active label colour. */\n activeText: string;\n /** Active pill background. */\n activeBackground: string;\n /** Hover/press background for an inactive option. Optional. */\n hoverBackground?: string;\n}\n\nexport interface LanguageSwitcherProps {\n colors: LanguageSwitcherColors;\n /** Accessible name for the group. Default `Language`. */\n accessibilityLabel?: string;\n testID?: string;\n}\n\n/**\n * react-native-web adds `hovered` to the Pressable style-callback state; the core react-native\n * types do not model it. Widen the state rather than casting the whole style callback.\n */\ntype PressableState = PressableStateCallbackType & { hovered?: boolean };\n\nconst styles = StyleSheet.create({\n row: { flexDirection: 'row', alignItems: 'center', gap: GAP },\n option: {\n paddingHorizontal: PADDING_H,\n paddingVertical: PADDING_V,\n borderRadius: BORDER_RADIUS,\n minWidth: MIN_TARGET,\n minHeight: MIN_TARGET,\n alignItems: 'center',\n justifyContent: 'center',\n },\n label: { fontSize: FONT_SIZE, fontWeight: '600' },\n});\n\nexport function LanguageSwitcher({\n colors,\n accessibilityLabel = 'Language',\n testID = 'language-switcher',\n}: LanguageSwitcherProps): React.ReactElement {\n const { locale, setLocale, locales } = useI18n();\n\n const select = useCallback((code: LocaleCode) => () => setLocale(code), [setLocale]);\n\n return (\n <View accessibilityRole=\"radiogroup\" aria-label={accessibilityLabel} style={styles.row} testID={testID}>\n {locales.map((option) => {\n const isActive = option.code === locale;\n return (\n <Pressable\n key={option.code}\n accessibilityHint={`Show the interface in ${option.label}`}\n accessibilityLabel={option.label}\n accessibilityRole=\"radio\"\n accessibilityState={{ selected: isActive }}\n aria-checked={isActive}\n style={({ hovered }: PressableState) => [\n styles.option,\n isActive\n ? { backgroundColor: colors.activeBackground }\n : hovered && colors.hoverBackground\n ? { backgroundColor: colors.hoverBackground }\n : null,\n ]}\n testID={`${testID}-${option.code}`}\n onPress={select(option.code)}\n >\n <Text style={[styles.label, { color: isActive ? colors.activeText : colors.text }]}>\n {option.label}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/createTranslator.ts","../src/detectLocale.ts","../src/I18nProvider.tsx","../src/LanguageSwitcher.tsx","../src/initI18n.ts","../src/createFormatMessage.ts"],"names":["createContext","useState","useCallback","useMemo","jsx","useContext","StyleSheet","View","Pressable","Text","i18n","initReactI18next"],"mappings":";;;;;;;;;;;;;AAOO,IAAM,uBAAA,GAA0B;AAGvC,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAA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GAAI,EAAA,KAAO,MAAA,GAAY,EAAE,EAAA,KAAO,EAAC;AAAA,IACjC,aAAA,EAAe;AAAA,MACb;AAAA;AACF,GACD,CAAA,CACA,KAAA,CAAM,mBAAmB,CAAA;AAE5B,EAAA,OAAOD,qBAAA;AACT;;;AClCO,SAAS,oBAAoB,UAAA,EAA8C;AAChF,EAAA,OAAO,CAAC,EAAA,EAAI,EAAA,EAAI,EAAA,EAAI,EAAA,KAAO;AACzB,IAAA,MAAM,UAAkC,EAAC;AACzC,IAAA,IAAI,EAAA,KAAO,MAAA,IAAa,EAAA,KAAO,IAAA,UAAc,EAAA,GAAK,EAAA;AAClD,IAAA,IAAI,EAAA,KAAO,MAAA,IAAa,EAAA,KAAO,IAAA,UAAc,EAAA,GAAK,EAAA;AAClD,IAAA,IAAI,EAAA,KAAO,MAAA,IAAa,EAAA,KAAO,IAAA,UAAc,EAAA,GAAK,EAAA;AAClD,IAAA,OAAO,UAAA,CAAW,CAAA,CAAE,EAAA,EAAI,OAAO,CAAA;AAAA,EACjC,CAAA;AACF","file":"index.js","sourcesContent":["/**\n * The pure core: catalog lookup + interpolation. No React, no storage, no side effects — so it is\n * trivially unit-testable and reusable outside a component tree (formatters, tests, server render).\n */\nimport type { Catalog, Catalogs, LocaleCode, NamedParams, Translate } from './types';\n\n/** The locale every catalog falls back to, per key. English is authoritative. */\nexport const DEFAULT_FALLBACK_LOCALE = 'en';\n\n/** True for a plain object of named params (as opposed to a positional string/number). */\nfunction isNamedParams(value: unknown): value is NamedParams {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Fill `{name}` placeholders from a params object. An unmatched placeholder is left intact rather\n * than blanked, so a template/param mismatch is visible instead of silently losing text.\n */\nexport function interpolateNamed(template: string, params: NamedParams): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match,\n );\n}\n\n/** Fill `{0}`, `{1}`, `{2}` from positional args (the shared UI kit's calling convention). */\nexport function interpolatePositional(\n template: string,\n params: ReadonlyArray<string | number | undefined>,\n): string {\n return params.reduce<string>(\n (acc, param, index) => (param === undefined ? acc : acc.split(`{${index}}`).join(String(param))),\n template,\n );\n}\n\n/**\n * Look a key up in `locale`, then in `fallbackLocale`, then give back the key itself.\n *\n * The fallback is **per key**, not per catalog: a partially translated locale still shows its\n * translated keys and only falls back for the ones it is missing. That is what lets a new locale\n * ship incrementally instead of all-or-nothing.\n */\nexport function lookup(\n catalogs: Catalogs,\n locale: LocaleCode,\n key: string,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): string {\n const active: Catalog | undefined = catalogs[locale];\n const fallback: Catalog | undefined = catalogs[fallbackLocale];\n return active?.[key] ?? fallback?.[key] ?? key;\n}\n\n/**\n * Build a {@link Translate} bound to one locale. Supports BOTH interpolation styles — see the\n * `Translate` docs for why (positional = the UI kit; named = hand-written app catalogs).\n */\nexport function createTranslator(\n catalogs: Catalogs,\n locale: LocaleCode,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): Translate {\n return (key, p1, p2, p3) => {\n const template = lookup(catalogs, locale, key, fallbackLocale);\n if (isNamedParams(p1)) return interpolateNamed(template, p1);\n return interpolatePositional(template, [p1, p2, p3]);\n };\n}\n","/**\n * Locale resolution + persistence.\n *\n * The resolution order mirrors the v1 AML console (`shared/i18n.js`): a previously stored choice\n * wins, else the browser's preferred language (primary subtag only — `de-AT` → `de`), else the\n * fallback. Storage is best-effort: private mode / a native runtime with no `localStorage` must not\n * throw, it just means the choice does not persist.\n */\nimport type { LocaleCode, LocaleOption } from './types';\n\n/** Default persistence key. Override per app so two apps on one origin don't fight. */\nexport const DEFAULT_STORAGE_KEY = 'dloizides_locale';\n\n/** True when `code` is one of the app's supported locales. Pure. */\nexport function isSupported(locales: readonly LocaleOption[], code: string): boolean {\n return locales.some((l) => l.code === code);\n}\n\n/** `de-AT` → `de`; `EN` → `en`. Pure. */\nexport function primarySubtag(tag: string): string {\n return String(tag).toLowerCase().split('-')[0] ?? '';\n}\n\n/**\n * Pick the locale to start in: stored → browser-preferred → fallback. Pure — the caller supplies\n * the stored value and the browser's language list, which keeps this testable with no globals.\n */\nexport function resolveInitialLocale(\n locales: readonly LocaleOption[],\n stored: string | null,\n preferred: readonly string[],\n fallback: LocaleCode,\n): LocaleCode {\n if (stored && isSupported(locales, stored)) return stored;\n for (const tag of preferred) {\n const primary = primarySubtag(tag);\n if (isSupported(locales, primary)) return primary;\n }\n return fallback;\n}\n\n/** The browser's preferred languages, most-preferred first. `[]` off-web. */\nexport function browserLanguages(): string[] {\n if (typeof navigator === 'undefined') return [];\n const nav = navigator as Navigator & { userLanguage?: string };\n const list = Array.isArray(nav.languages) && nav.languages.length > 0 ? nav.languages : [];\n const single = nav.language ?? nav.userLanguage;\n return list.length > 0 ? [...list] : single ? [single] : [];\n}\n\n/** Read the persisted locale. Never throws (private mode, native, SSR). */\nexport function readStoredLocale(storageKey: string): string | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n return localStorage.getItem(storageKey);\n } catch {\n return null;\n }\n}\n\n/** Persist the locale. Never throws — a failure just means it won't be remembered. */\nexport function writeStoredLocale(storageKey: string, code: LocaleCode): void {\n try {\n if (typeof localStorage === 'undefined') return;\n localStorage.setItem(storageKey, code);\n } catch {\n /* private mode / no storage — the choice simply does not persist */\n }\n}\n\n/**\n * Reflect the locale on the document so CSS can react (`:lang()`, `[dir=\"rtl\"]`). Web-only no-op\n * elsewhere. This is the RTL hook: ship an `rtl: true` locale and the layout can mirror itself\n * without any component changes.\n */\nexport function applyDocumentLocale(locales: readonly LocaleOption[], code: LocaleCode): void {\n if (typeof document === 'undefined') return;\n const option = locales.find((l) => l.code === code);\n document.documentElement.lang = code;\n document.documentElement.dir = option?.rtl ? 'rtl' : 'ltr';\n}\n","/**\n * `I18nProvider` — holds the active locale, exposes a memoized {@link Translate}, persists the\n * user's choice, and reflects `lang`/`dir` on the document.\n *\n * Wiring it to the rest of the shared kit is one line, because {@link Translate} is\n * signature-compatible with the kit's `t` contract:\n *\n * ```tsx\n * <I18nProvider catalogs={CATALOGS} locales={LOCALES}>\n * <KitBridge /> // const { t } = useI18n(); return <UiProvider theme={theme} t={t}>…\n * </I18nProvider>\n * ```\n */\nimport React, { createContext, useCallback, useContext, useMemo, useState } from 'react';\n\nimport { createTranslator, DEFAULT_FALLBACK_LOCALE } from './createTranslator';\nimport {\n applyDocumentLocale,\n browserLanguages,\n DEFAULT_STORAGE_KEY,\n readStoredLocale,\n resolveInitialLocale,\n writeStoredLocale,\n} from './detectLocale';\nimport type { Catalogs, LocaleCode, LocaleOption, Translate } from './types';\n\nexport interface I18nValue {\n /** Resolve a key in the active locale (positional or named interpolation). */\n t: Translate;\n /** The active locale code. */\n locale: LocaleCode;\n /** Switch locale: re-renders consumers, persists the choice, updates `lang`/`dir`. */\n setLocale: (code: LocaleCode) => void;\n /** Every locale the app offers (for a switcher). */\n locales: readonly LocaleOption[];\n}\n\nconst I18nContext = createContext<I18nValue | null>(null);\n\nexport interface I18nProviderProps {\n /** Every locale's catalog. The fallback locale's catalog is required. */\n catalogs: Catalogs;\n /** The locales offered to the user, in display order. */\n locales: readonly LocaleOption[];\n /** Per-key fallback locale. Default `en`. */\n fallbackLocale?: LocaleCode;\n /** localStorage key for the persisted choice. Default `dloizides_locale`. */\n storageKey?: string;\n /** Force a locale (tests / SSR). When set, detection and persistence are skipped. */\n initialLocale?: LocaleCode;\n children: React.ReactNode;\n}\n\nexport function I18nProvider({\n catalogs,\n locales,\n fallbackLocale = DEFAULT_FALLBACK_LOCALE,\n storageKey = DEFAULT_STORAGE_KEY,\n initialLocale,\n children,\n}: I18nProviderProps): React.ReactElement {\n // Resolved once, lazily: stored choice → browser preference → fallback. Reading storage and\n // `navigator` inside the initializer keeps the first paint on the right locale (no flash of\n // English before a `useEffect` corrects it).\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n const resolved = resolveInitialLocale(\n locales,\n readStoredLocale(storageKey),\n browserLanguages(),\n fallbackLocale,\n );\n applyDocumentLocale(locales, resolved);\n return resolved;\n });\n\n const setLocale = useCallback(\n (code: LocaleCode) => {\n setLocaleState(code);\n writeStoredLocale(storageKey, code);\n applyDocumentLocale(locales, code);\n },\n [locales, storageKey],\n );\n\n const t = useMemo(\n () => createTranslator(catalogs, locale, fallbackLocale),\n [catalogs, locale, fallbackLocale],\n );\n\n const value = useMemo<I18nValue>(\n () => ({ t, locale, setLocale, locales }),\n [t, locale, setLocale, locales],\n );\n\n return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;\n}\n\n/** Access the active locale + translate function. Throws outside an {@link I18nProvider}. */\nexport function useI18n(): I18nValue {\n const value = useContext(I18nContext);\n if (value === null) throw new Error('useI18n must be used inside an <I18nProvider>.');\n return value;\n}\n","/**\n * `LanguageSwitcher` — a compact segmented control of locale codes (EN · DE · ES · FR · PT), the\n * same shape as the v1 AML console's `#lang-switcher`.\n *\n * Colours come in as PROPS rather than from a theme context on purpose: it keeps this package\n * dependency-free (no peer dep on the UI kit or a design-token package), so any app — themed or\n * not — can drop it in. Themed apps pass their own tokens, e.g.\n * `colors={{ text: colors.textSecondary, activeText: '#fff', activeBackground: colors.primary }}`.\n */\nimport React, { useCallback } from 'react';\nimport { Pressable, StyleSheet, Text, View, type PressableStateCallbackType } from 'react-native';\n\nimport { useI18n } from './I18nProvider';\nimport type { LocaleCode } from './types';\n\nconst BORDER_RADIUS = 8;\nconst PADDING_H = 9;\nconst PADDING_V = 5;\nconst FONT_SIZE = 12;\nconst GAP = 2;\n/** WCAG 2.5.5: an interactive target must be at least 44×44 px. */\nconst MIN_TARGET = 44;\n\nexport interface LanguageSwitcherColors {\n /** Inactive label colour. */\n text: string;\n /** Active label colour. */\n activeText: string;\n /** Active pill background. */\n activeBackground: string;\n /** Hover/press background for an inactive option. Optional. */\n hoverBackground?: string;\n}\n\nexport interface LanguageSwitcherProps {\n colors: LanguageSwitcherColors;\n /** Accessible name for the group. Default `Language`. */\n accessibilityLabel?: string;\n testID?: string;\n}\n\n/**\n * react-native-web adds `hovered` to the Pressable style-callback state; the core react-native\n * types do not model it. Widen the state rather than casting the whole style callback.\n */\ntype PressableState = PressableStateCallbackType & { hovered?: boolean };\n\nconst styles = StyleSheet.create({\n row: { flexDirection: 'row', alignItems: 'center', gap: GAP },\n option: {\n paddingHorizontal: PADDING_H,\n paddingVertical: PADDING_V,\n borderRadius: BORDER_RADIUS,\n minWidth: MIN_TARGET,\n minHeight: MIN_TARGET,\n alignItems: 'center',\n justifyContent: 'center',\n },\n label: { fontSize: FONT_SIZE, fontWeight: '600' },\n});\n\nexport function LanguageSwitcher({\n colors,\n accessibilityLabel = 'Language',\n testID = 'language-switcher',\n}: LanguageSwitcherProps): React.ReactElement {\n const { locale, setLocale, locales } = useI18n();\n\n const select = useCallback((code: LocaleCode) => () => setLocale(code), [setLocale]);\n\n return (\n <View accessibilityRole=\"radiogroup\" aria-label={accessibilityLabel} style={styles.row} testID={testID}>\n {locales.map((option) => {\n const isActive = option.code === locale;\n return (\n <Pressable\n key={option.code}\n accessibilityHint={`Show the interface in ${option.label}`}\n accessibilityLabel={option.label}\n accessibilityRole=\"radio\"\n accessibilityState={{ selected: isActive }}\n aria-checked={isActive}\n style={({ hovered }: PressableState) => [\n styles.option,\n isActive\n ? { backgroundColor: colors.activeBackground }\n : hovered && colors.hoverBackground\n ? { backgroundColor: colors.hoverBackground }\n : null,\n ]}\n testID={`${testID}-${option.code}`}\n onPress={select(option.code)}\n >\n <Text style={[styles.label, { color: isActive ? colors.activeText : colors.text }]}>\n {option.label}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n","import i18n, { type i18n as I18nInstance, type Resource } from 'i18next';\nimport { initReactI18next } from 'react-i18next';\n\n/** Options for {@link initI18n}: the app's resources and languages; the package owns the init chain. */\nexport interface InitI18nOptions {\n resources: Resource;\n lng?: string;\n fallbackLng?: string;\n escapeValue?: boolean;\n defaultNS?: string | readonly string[];\n ns?: string | readonly string[];\n}\n\nconst DEFAULT_FALLBACK_LNG = 'en';\n\nconst ignoreInitRejection = (): void => undefined;\n\n/** Wires react-i18next into the i18next singleton, runs `.init()` and returns the singleton. */\nexport function initI18n(options: InitI18nOptions): I18nInstance {\n const {\n resources,\n lng,\n fallbackLng = DEFAULT_FALLBACK_LNG,\n escapeValue = false,\n defaultNS,\n ns,\n } = options;\n\n i18n\n .use(initReactI18next)\n .init({\n lng: lng ?? fallbackLng,\n fallbackLng,\n resources,\n ...(defaultNS !== undefined ? { defaultNS } : {}),\n ...(ns !== undefined ? { ns } : {}),\n interpolation: {\n escapeValue,\n },\n })\n .catch(ignoreInitRejection);\n\n return i18n;\n}\n","/** The slice of an i18next instance that {@link createFormatMessage} needs. */\nexport interface MessageTranslator {\n t: (id: string, options: Record<string, string>) => string;\n}\n\n/** Positional-parameter message formatter: `FM(id, p1, p2, p3)` maps to `{{p1}}`..`{{p3}}`. */\nexport type FormatMessage = (id: string, p1?: string, p2?: string, p3?: string) => string;\n\n/** Builds the portal `FM()` helper over an initialised i18next instance. */\nexport function createFormatMessage(translator: MessageTranslator): FormatMessage {\n return (id, p1, p2, p3) => {\n const options: Record<string, string> = {};\n if (p1 !== undefined && p1 !== null) options.p1 = p1;\n if (p2 !== undefined && p2 !== null) options.p2 = p2;\n if (p3 !== undefined && p3 !== null) options.p3 = p3;\n return translator.t(id, options);\n };\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { createContext, useState, useCallback, useMemo, useContext } from 'react';
|
|
2
2
|
import { jsx } from 'react/jsx-runtime';
|
|
3
3
|
import { StyleSheet, View, Pressable, Text } from 'react-native';
|
|
4
|
+
import i18n from 'i18next';
|
|
5
|
+
import { initReactI18next } from 'react-i18next';
|
|
4
6
|
|
|
5
7
|
// src/createTranslator.ts
|
|
6
8
|
var DEFAULT_FALLBACK_LOCALE = "en";
|
|
@@ -167,7 +169,41 @@ function LanguageSwitcher({
|
|
|
167
169
|
);
|
|
168
170
|
}) });
|
|
169
171
|
}
|
|
172
|
+
var DEFAULT_FALLBACK_LNG = "en";
|
|
173
|
+
var ignoreInitRejection = () => void 0;
|
|
174
|
+
function initI18n(options) {
|
|
175
|
+
const {
|
|
176
|
+
resources,
|
|
177
|
+
lng,
|
|
178
|
+
fallbackLng = DEFAULT_FALLBACK_LNG,
|
|
179
|
+
escapeValue = false,
|
|
180
|
+
defaultNS,
|
|
181
|
+
ns
|
|
182
|
+
} = options;
|
|
183
|
+
i18n.use(initReactI18next).init({
|
|
184
|
+
lng: lng ?? fallbackLng,
|
|
185
|
+
fallbackLng,
|
|
186
|
+
resources,
|
|
187
|
+
...defaultNS !== void 0 ? { defaultNS } : {},
|
|
188
|
+
...ns !== void 0 ? { ns } : {},
|
|
189
|
+
interpolation: {
|
|
190
|
+
escapeValue
|
|
191
|
+
}
|
|
192
|
+
}).catch(ignoreInitRejection);
|
|
193
|
+
return i18n;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/createFormatMessage.ts
|
|
197
|
+
function createFormatMessage(translator) {
|
|
198
|
+
return (id, p1, p2, p3) => {
|
|
199
|
+
const options = {};
|
|
200
|
+
if (p1 !== void 0 && p1 !== null) options.p1 = p1;
|
|
201
|
+
if (p2 !== void 0 && p2 !== null) options.p2 = p2;
|
|
202
|
+
if (p3 !== void 0 && p3 !== null) options.p3 = p3;
|
|
203
|
+
return translator.t(id, options);
|
|
204
|
+
};
|
|
205
|
+
}
|
|
170
206
|
|
|
171
|
-
export { DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, I18nProvider, LanguageSwitcher, applyDocumentLocale, browserLanguages, createTranslator, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
|
207
|
+
export { DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, I18nProvider, LanguageSwitcher, applyDocumentLocale, browserLanguages, createFormatMessage, createTranslator, initI18n, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
|
172
208
|
//# sourceMappingURL=index.mjs.map
|
|
173
209
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/createTranslator.ts","../src/detectLocale.ts","../src/I18nProvider.tsx","../src/LanguageSwitcher.tsx"],"names":["useCallback","jsx"],"mappings":";;;;;AAOO,IAAM,uBAAA,GAA0B;AAGvC,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAMO,SAAS,gBAAA,CAAiB,UAAkB,MAAA,EAA6B;AAC9E,EAAA,OAAO,QAAA,CAAS,OAAA;AAAA,IAAQ,YAAA;AAAA,IAAc,CAAC,KAAA,EAAO,IAAA,KAC5C,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,CAAK,MAAA,EAAQ,IAAI,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,IAAI,CAAC,CAAA,GAAI;AAAA,GAC9E;AACF;AAGO,SAAS,qBAAA,CACd,UACA,MAAA,EACQ;AACR,EAAA,OAAO,MAAA,CAAO,MAAA;AAAA,IACZ,CAAC,GAAA,EAAK,KAAA,EAAO,KAAA,KAAW,KAAA,KAAU,SAAY,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,MAAA,CAAO,KAAK,CAAC,CAAA;AAAA,IAC9F;AAAA,GACF;AACF;AASO,SAAS,MAAA,CACd,QAAA,EACA,MAAA,EACA,GAAA,EACA,iBAA6B,uBAAA,EACrB;AACR,EAAA,MAAM,MAAA,GAA8B,SAAS,MAAM,CAAA;AACn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React, no storage, no side effects — so it is\n * trivially unit-testable and reusable outside a component tree (formatters, tests, server render).\n */\nimport type { Catalog, Catalogs, LocaleCode, NamedParams, Translate } from './types';\n\n/** The locale every catalog falls back to, per key. English is authoritative. */\nexport const DEFAULT_FALLBACK_LOCALE = 'en';\n\n/** True for a plain object of named params (as opposed to a positional string/number). */\nfunction isNamedParams(value: unknown): value is NamedParams {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Fill `{name}` placeholders from a params object. An unmatched placeholder is left intact rather\n * than blanked, so a template/param mismatch is visible instead of silently losing text.\n */\nexport function interpolateNamed(template: string, params: NamedParams): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match,\n );\n}\n\n/** Fill `{0}`, `{1}`, `{2}` from positional args (the shared UI kit's calling convention). */\nexport function interpolatePositional(\n template: string,\n params: ReadonlyArray<string | number | undefined>,\n): string {\n return params.reduce<string>(\n (acc, param, index) => (param === undefined ? acc : acc.split(`{${index}}`).join(String(param))),\n template,\n );\n}\n\n/**\n * Look a key up in `locale`, then in `fallbackLocale`, then give back the key itself.\n *\n * The fallback is **per key**, not per catalog: a partially translated locale still shows its\n * translated keys and only falls back for the ones it is missing. That is what lets a new locale\n * ship incrementally instead of all-or-nothing.\n */\nexport function lookup(\n catalogs: Catalogs,\n locale: LocaleCode,\n key: string,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): string {\n const active: Catalog | undefined = catalogs[locale];\n const fallback: Catalog | undefined = catalogs[fallbackLocale];\n return active?.[key] ?? fallback?.[key] ?? key;\n}\n\n/**\n * Build a {@link Translate} bound to one locale. Supports BOTH interpolation styles — see the\n * `Translate` docs for why (positional = the UI kit; named = hand-written app catalogs).\n */\nexport function createTranslator(\n catalogs: Catalogs,\n locale: LocaleCode,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): Translate {\n return (key, p1, p2, p3) => {\n const template = lookup(catalogs, locale, key, fallbackLocale);\n if (isNamedParams(p1)) return interpolateNamed(template, p1);\n return interpolatePositional(template, [p1, p2, p3]);\n };\n}\n","/**\n * Locale resolution + persistence.\n *\n * The resolution order mirrors the v1 AML console (`shared/i18n.js`): a previously stored choice\n * wins, else the browser's preferred language (primary subtag only — `de-AT` → `de`), else the\n * fallback. Storage is best-effort: private mode / a native runtime with no `localStorage` must not\n * throw, it just means the choice does not persist.\n */\nimport type { LocaleCode, LocaleOption } from './types';\n\n/** Default persistence key. Override per app so two apps on one origin don't fight. */\nexport const DEFAULT_STORAGE_KEY = 'dloizides_locale';\n\n/** True when `code` is one of the app's supported locales. Pure. */\nexport function isSupported(locales: readonly LocaleOption[], code: string): boolean {\n return locales.some((l) => l.code === code);\n}\n\n/** `de-AT` → `de`; `EN` → `en`. Pure. */\nexport function primarySubtag(tag: string): string {\n return String(tag).toLowerCase().split('-')[0] ?? '';\n}\n\n/**\n * Pick the locale to start in: stored → browser-preferred → fallback. Pure — the caller supplies\n * the stored value and the browser's language list, which keeps this testable with no globals.\n */\nexport function resolveInitialLocale(\n locales: readonly LocaleOption[],\n stored: string | null,\n preferred: readonly string[],\n fallback: LocaleCode,\n): LocaleCode {\n if (stored && isSupported(locales, stored)) return stored;\n for (const tag of preferred) {\n const primary = primarySubtag(tag);\n if (isSupported(locales, primary)) return primary;\n }\n return fallback;\n}\n\n/** The browser's preferred languages, most-preferred first. `[]` off-web. */\nexport function browserLanguages(): string[] {\n if (typeof navigator === 'undefined') return [];\n const nav = navigator as Navigator & { userLanguage?: string };\n const list = Array.isArray(nav.languages) && nav.languages.length > 0 ? nav.languages : [];\n const single = nav.language ?? nav.userLanguage;\n return list.length > 0 ? [...list] : single ? [single] : [];\n}\n\n/** Read the persisted locale. Never throws (private mode, native, SSR). */\nexport function readStoredLocale(storageKey: string): string | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n return localStorage.getItem(storageKey);\n } catch {\n return null;\n }\n}\n\n/** Persist the locale. Never throws — a failure just means it won't be remembered. */\nexport function writeStoredLocale(storageKey: string, code: LocaleCode): void {\n try {\n if (typeof localStorage === 'undefined') return;\n localStorage.setItem(storageKey, code);\n } catch {\n /* private mode / no storage — the choice simply does not persist */\n }\n}\n\n/**\n * Reflect the locale on the document so CSS can react (`:lang()`, `[dir=\"rtl\"]`). Web-only no-op\n * elsewhere. This is the RTL hook: ship an `rtl: true` locale and the layout can mirror itself\n * without any component changes.\n */\nexport function applyDocumentLocale(locales: readonly LocaleOption[], code: LocaleCode): void {\n if (typeof document === 'undefined') return;\n const option = locales.find((l) => l.code === code);\n document.documentElement.lang = code;\n document.documentElement.dir = option?.rtl ? 'rtl' : 'ltr';\n}\n","/**\n * `I18nProvider` — holds the active locale, exposes a memoized {@link Translate}, persists the\n * user's choice, and reflects `lang`/`dir` on the document.\n *\n * Wiring it to the rest of the shared kit is one line, because {@link Translate} is\n * signature-compatible with the kit's `t` contract:\n *\n * ```tsx\n * <I18nProvider catalogs={CATALOGS} locales={LOCALES}>\n * <KitBridge /> // const { t } = useI18n(); return <UiProvider theme={theme} t={t}>…\n * </I18nProvider>\n * ```\n */\nimport React, { createContext, useCallback, useContext, useMemo, useState } from 'react';\n\nimport { createTranslator, DEFAULT_FALLBACK_LOCALE } from './createTranslator';\nimport {\n applyDocumentLocale,\n browserLanguages,\n DEFAULT_STORAGE_KEY,\n readStoredLocale,\n resolveInitialLocale,\n writeStoredLocale,\n} from './detectLocale';\nimport type { Catalogs, LocaleCode, LocaleOption, Translate } from './types';\n\nexport interface I18nValue {\n /** Resolve a key in the active locale (positional or named interpolation). */\n t: Translate;\n /** The active locale code. */\n locale: LocaleCode;\n /** Switch locale: re-renders consumers, persists the choice, updates `lang`/`dir`. */\n setLocale: (code: LocaleCode) => void;\n /** Every locale the app offers (for a switcher). */\n locales: readonly LocaleOption[];\n}\n\nconst I18nContext = createContext<I18nValue | null>(null);\n\nexport interface I18nProviderProps {\n /** Every locale's catalog. The fallback locale's catalog is required. */\n catalogs: Catalogs;\n /** The locales offered to the user, in display order. */\n locales: readonly LocaleOption[];\n /** Per-key fallback locale. Default `en`. */\n fallbackLocale?: LocaleCode;\n /** localStorage key for the persisted choice. Default `dloizides_locale`. */\n storageKey?: string;\n /** Force a locale (tests / SSR). When set, detection and persistence are skipped. */\n initialLocale?: LocaleCode;\n children: React.ReactNode;\n}\n\nexport function I18nProvider({\n catalogs,\n locales,\n fallbackLocale = DEFAULT_FALLBACK_LOCALE,\n storageKey = DEFAULT_STORAGE_KEY,\n initialLocale,\n children,\n}: I18nProviderProps): React.ReactElement {\n // Resolved once, lazily: stored choice → browser preference → fallback. Reading storage and\n // `navigator` inside the initializer keeps the first paint on the right locale (no flash of\n // English before a `useEffect` corrects it).\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n const resolved = resolveInitialLocale(\n locales,\n readStoredLocale(storageKey),\n browserLanguages(),\n fallbackLocale,\n );\n applyDocumentLocale(locales, resolved);\n return resolved;\n });\n\n const setLocale = useCallback(\n (code: LocaleCode) => {\n setLocaleState(code);\n writeStoredLocale(storageKey, code);\n applyDocumentLocale(locales, code);\n },\n [locales, storageKey],\n );\n\n const t = useMemo(\n () => createTranslator(catalogs, locale, fallbackLocale),\n [catalogs, locale, fallbackLocale],\n );\n\n const value = useMemo<I18nValue>(\n () => ({ t, locale, setLocale, locales }),\n [t, locale, setLocale, locales],\n );\n\n return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;\n}\n\n/** Access the active locale + translate function. Throws outside an {@link I18nProvider}. */\nexport function useI18n(): I18nValue {\n const value = useContext(I18nContext);\n if (value === null) throw new Error('useI18n must be used inside an <I18nProvider>.');\n return value;\n}\n","/**\n * `LanguageSwitcher` — a compact segmented control of locale codes (EN · DE · ES · FR · PT), the\n * same shape as the v1 AML console's `#lang-switcher`.\n *\n * Colours come in as PROPS rather than from a theme context on purpose: it keeps this package\n * dependency-free (no peer dep on the UI kit or a design-token package), so any app — themed or\n * not — can drop it in. Themed apps pass their own tokens, e.g.\n * `colors={{ text: colors.textSecondary, activeText: '#fff', activeBackground: colors.primary }}`.\n */\nimport React, { useCallback } from 'react';\nimport { Pressable, StyleSheet, Text, View, type PressableStateCallbackType } from 'react-native';\n\nimport { useI18n } from './I18nProvider';\nimport type { LocaleCode } from './types';\n\nconst BORDER_RADIUS = 8;\nconst PADDING_H = 9;\nconst PADDING_V = 5;\nconst FONT_SIZE = 12;\nconst GAP = 2;\n/** WCAG 2.5.5: an interactive target must be at least 44×44 px. */\nconst MIN_TARGET = 44;\n\nexport interface LanguageSwitcherColors {\n /** Inactive label colour. */\n text: string;\n /** Active label colour. */\n activeText: string;\n /** Active pill background. */\n activeBackground: string;\n /** Hover/press background for an inactive option. Optional. */\n hoverBackground?: string;\n}\n\nexport interface LanguageSwitcherProps {\n colors: LanguageSwitcherColors;\n /** Accessible name for the group. Default `Language`. */\n accessibilityLabel?: string;\n testID?: string;\n}\n\n/**\n * react-native-web adds `hovered` to the Pressable style-callback state; the core react-native\n * types do not model it. Widen the state rather than casting the whole style callback.\n */\ntype PressableState = PressableStateCallbackType & { hovered?: boolean };\n\nconst styles = StyleSheet.create({\n row: { flexDirection: 'row', alignItems: 'center', gap: GAP },\n option: {\n paddingHorizontal: PADDING_H,\n paddingVertical: PADDING_V,\n borderRadius: BORDER_RADIUS,\n minWidth: MIN_TARGET,\n minHeight: MIN_TARGET,\n alignItems: 'center',\n justifyContent: 'center',\n },\n label: { fontSize: FONT_SIZE, fontWeight: '600' },\n});\n\nexport function LanguageSwitcher({\n colors,\n accessibilityLabel = 'Language',\n testID = 'language-switcher',\n}: LanguageSwitcherProps): React.ReactElement {\n const { locale, setLocale, locales } = useI18n();\n\n const select = useCallback((code: LocaleCode) => () => setLocale(code), [setLocale]);\n\n return (\n <View accessibilityRole=\"radiogroup\" aria-label={accessibilityLabel} style={styles.row} testID={testID}>\n {locales.map((option) => {\n const isActive = option.code === locale;\n return (\n <Pressable\n key={option.code}\n accessibilityHint={`Show the interface in ${option.label}`}\n accessibilityLabel={option.label}\n accessibilityRole=\"radio\"\n accessibilityState={{ selected: isActive }}\n aria-checked={isActive}\n style={({ hovered }: PressableState) => [\n styles.option,\n isActive\n ? { backgroundColor: colors.activeBackground }\n : hovered && colors.hoverBackground\n ? { backgroundColor: colors.hoverBackground }\n : null,\n ]}\n testID={`${testID}-${option.code}`}\n onPress={select(option.code)}\n >\n <Text style={[styles.label, { color: isActive ? colors.activeText : colors.text }]}>\n {option.label}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/createTranslator.ts","../src/detectLocale.ts","../src/I18nProvider.tsx","../src/LanguageSwitcher.tsx","../src/initI18n.ts","../src/createFormatMessage.ts"],"names":["useCallback","jsx"],"mappings":";;;;;;;AAOO,IAAM,uBAAA,GAA0B;AAGvC,SAAS,cAAc,KAAA,EAAsC;AAC3D,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,KAAU,QAAQ,CAAC,KAAA,CAAM,QAAQ,KAAK,CAAA;AAC5E;AAMO,SAAS,gBAAA,CAAiB,UAAkB,MAAA,EAA6B;AAC9E,EAAA,OAAO,QAAA,CAAS,OAAA;AAAA,IAAQ,YAAA;AAAA,IAAc,CAAC,KAAA,EAAO,IAAA,KAC5C,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,CAAK,MAAA,EAAQ,IAAI,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,IAAI,CAAC,CAAA,GAAI;AAAA,GAC9E;AACF;AAGO,SAAS,qBAAA,CACd,UACA,MAAA,EACQ;AACR,EAAA,OAAO,MAAA,CAAO,MAAA;AAAA,IACZ,CAAC,GAAA,EAAK,KAAA,EAAO,KAAA,KAAW,KAAA,KAAU,SAAY,GAAA,GAAM,GAAA,CAAI,KAAA,CAAM,CAAA,CAAA,EAAI,KAAK,CAAA,CAAA,CAAG,CAAA,CAAE,IAAA,CAAK,MAAA,CAAO,KAAK,CAAC,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EACjC,CAAA;AACF","file":"index.mjs","sourcesContent":["/**\n * The pure core: catalog lookup + interpolation. No React, no storage, no side effects — so it is\n * trivially unit-testable and reusable outside a component tree (formatters, tests, server render).\n */\nimport type { Catalog, Catalogs, LocaleCode, NamedParams, Translate } from './types';\n\n/** The locale every catalog falls back to, per key. English is authoritative. */\nexport const DEFAULT_FALLBACK_LOCALE = 'en';\n\n/** True for a plain object of named params (as opposed to a positional string/number). */\nfunction isNamedParams(value: unknown): value is NamedParams {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Fill `{name}` placeholders from a params object. An unmatched placeholder is left intact rather\n * than blanked, so a template/param mismatch is visible instead of silently losing text.\n */\nexport function interpolateNamed(template: string, params: NamedParams): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match,\n );\n}\n\n/** Fill `{0}`, `{1}`, `{2}` from positional args (the shared UI kit's calling convention). */\nexport function interpolatePositional(\n template: string,\n params: ReadonlyArray<string | number | undefined>,\n): string {\n return params.reduce<string>(\n (acc, param, index) => (param === undefined ? acc : acc.split(`{${index}}`).join(String(param))),\n template,\n );\n}\n\n/**\n * Look a key up in `locale`, then in `fallbackLocale`, then give back the key itself.\n *\n * The fallback is **per key**, not per catalog: a partially translated locale still shows its\n * translated keys and only falls back for the ones it is missing. That is what lets a new locale\n * ship incrementally instead of all-or-nothing.\n */\nexport function lookup(\n catalogs: Catalogs,\n locale: LocaleCode,\n key: string,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): string {\n const active: Catalog | undefined = catalogs[locale];\n const fallback: Catalog | undefined = catalogs[fallbackLocale];\n return active?.[key] ?? fallback?.[key] ?? key;\n}\n\n/**\n * Build a {@link Translate} bound to one locale. Supports BOTH interpolation styles — see the\n * `Translate` docs for why (positional = the UI kit; named = hand-written app catalogs).\n */\nexport function createTranslator(\n catalogs: Catalogs,\n locale: LocaleCode,\n fallbackLocale: LocaleCode = DEFAULT_FALLBACK_LOCALE,\n): Translate {\n return (key, p1, p2, p3) => {\n const template = lookup(catalogs, locale, key, fallbackLocale);\n if (isNamedParams(p1)) return interpolateNamed(template, p1);\n return interpolatePositional(template, [p1, p2, p3]);\n };\n}\n","/**\n * Locale resolution + persistence.\n *\n * The resolution order mirrors the v1 AML console (`shared/i18n.js`): a previously stored choice\n * wins, else the browser's preferred language (primary subtag only — `de-AT` → `de`), else the\n * fallback. Storage is best-effort: private mode / a native runtime with no `localStorage` must not\n * throw, it just means the choice does not persist.\n */\nimport type { LocaleCode, LocaleOption } from './types';\n\n/** Default persistence key. Override per app so two apps on one origin don't fight. */\nexport const DEFAULT_STORAGE_KEY = 'dloizides_locale';\n\n/** True when `code` is one of the app's supported locales. Pure. */\nexport function isSupported(locales: readonly LocaleOption[], code: string): boolean {\n return locales.some((l) => l.code === code);\n}\n\n/** `de-AT` → `de`; `EN` → `en`. Pure. */\nexport function primarySubtag(tag: string): string {\n return String(tag).toLowerCase().split('-')[0] ?? '';\n}\n\n/**\n * Pick the locale to start in: stored → browser-preferred → fallback. Pure — the caller supplies\n * the stored value and the browser's language list, which keeps this testable with no globals.\n */\nexport function resolveInitialLocale(\n locales: readonly LocaleOption[],\n stored: string | null,\n preferred: readonly string[],\n fallback: LocaleCode,\n): LocaleCode {\n if (stored && isSupported(locales, stored)) return stored;\n for (const tag of preferred) {\n const primary = primarySubtag(tag);\n if (isSupported(locales, primary)) return primary;\n }\n return fallback;\n}\n\n/** The browser's preferred languages, most-preferred first. `[]` off-web. */\nexport function browserLanguages(): string[] {\n if (typeof navigator === 'undefined') return [];\n const nav = navigator as Navigator & { userLanguage?: string };\n const list = Array.isArray(nav.languages) && nav.languages.length > 0 ? nav.languages : [];\n const single = nav.language ?? nav.userLanguage;\n return list.length > 0 ? [...list] : single ? [single] : [];\n}\n\n/** Read the persisted locale. Never throws (private mode, native, SSR). */\nexport function readStoredLocale(storageKey: string): string | null {\n try {\n if (typeof localStorage === 'undefined') return null;\n return localStorage.getItem(storageKey);\n } catch {\n return null;\n }\n}\n\n/** Persist the locale. Never throws — a failure just means it won't be remembered. */\nexport function writeStoredLocale(storageKey: string, code: LocaleCode): void {\n try {\n if (typeof localStorage === 'undefined') return;\n localStorage.setItem(storageKey, code);\n } catch {\n /* private mode / no storage — the choice simply does not persist */\n }\n}\n\n/**\n * Reflect the locale on the document so CSS can react (`:lang()`, `[dir=\"rtl\"]`). Web-only no-op\n * elsewhere. This is the RTL hook: ship an `rtl: true` locale and the layout can mirror itself\n * without any component changes.\n */\nexport function applyDocumentLocale(locales: readonly LocaleOption[], code: LocaleCode): void {\n if (typeof document === 'undefined') return;\n const option = locales.find((l) => l.code === code);\n document.documentElement.lang = code;\n document.documentElement.dir = option?.rtl ? 'rtl' : 'ltr';\n}\n","/**\n * `I18nProvider` — holds the active locale, exposes a memoized {@link Translate}, persists the\n * user's choice, and reflects `lang`/`dir` on the document.\n *\n * Wiring it to the rest of the shared kit is one line, because {@link Translate} is\n * signature-compatible with the kit's `t` contract:\n *\n * ```tsx\n * <I18nProvider catalogs={CATALOGS} locales={LOCALES}>\n * <KitBridge /> // const { t } = useI18n(); return <UiProvider theme={theme} t={t}>…\n * </I18nProvider>\n * ```\n */\nimport React, { createContext, useCallback, useContext, useMemo, useState } from 'react';\n\nimport { createTranslator, DEFAULT_FALLBACK_LOCALE } from './createTranslator';\nimport {\n applyDocumentLocale,\n browserLanguages,\n DEFAULT_STORAGE_KEY,\n readStoredLocale,\n resolveInitialLocale,\n writeStoredLocale,\n} from './detectLocale';\nimport type { Catalogs, LocaleCode, LocaleOption, Translate } from './types';\n\nexport interface I18nValue {\n /** Resolve a key in the active locale (positional or named interpolation). */\n t: Translate;\n /** The active locale code. */\n locale: LocaleCode;\n /** Switch locale: re-renders consumers, persists the choice, updates `lang`/`dir`. */\n setLocale: (code: LocaleCode) => void;\n /** Every locale the app offers (for a switcher). */\n locales: readonly LocaleOption[];\n}\n\nconst I18nContext = createContext<I18nValue | null>(null);\n\nexport interface I18nProviderProps {\n /** Every locale's catalog. The fallback locale's catalog is required. */\n catalogs: Catalogs;\n /** The locales offered to the user, in display order. */\n locales: readonly LocaleOption[];\n /** Per-key fallback locale. Default `en`. */\n fallbackLocale?: LocaleCode;\n /** localStorage key for the persisted choice. Default `dloizides_locale`. */\n storageKey?: string;\n /** Force a locale (tests / SSR). When set, detection and persistence are skipped. */\n initialLocale?: LocaleCode;\n children: React.ReactNode;\n}\n\nexport function I18nProvider({\n catalogs,\n locales,\n fallbackLocale = DEFAULT_FALLBACK_LOCALE,\n storageKey = DEFAULT_STORAGE_KEY,\n initialLocale,\n children,\n}: I18nProviderProps): React.ReactElement {\n // Resolved once, lazily: stored choice → browser preference → fallback. Reading storage and\n // `navigator` inside the initializer keeps the first paint on the right locale (no flash of\n // English before a `useEffect` corrects it).\n const [locale, setLocaleState] = useState<LocaleCode>(() => {\n if (initialLocale) return initialLocale;\n const resolved = resolveInitialLocale(\n locales,\n readStoredLocale(storageKey),\n browserLanguages(),\n fallbackLocale,\n );\n applyDocumentLocale(locales, resolved);\n return resolved;\n });\n\n const setLocale = useCallback(\n (code: LocaleCode) => {\n setLocaleState(code);\n writeStoredLocale(storageKey, code);\n applyDocumentLocale(locales, code);\n },\n [locales, storageKey],\n );\n\n const t = useMemo(\n () => createTranslator(catalogs, locale, fallbackLocale),\n [catalogs, locale, fallbackLocale],\n );\n\n const value = useMemo<I18nValue>(\n () => ({ t, locale, setLocale, locales }),\n [t, locale, setLocale, locales],\n );\n\n return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;\n}\n\n/** Access the active locale + translate function. Throws outside an {@link I18nProvider}. */\nexport function useI18n(): I18nValue {\n const value = useContext(I18nContext);\n if (value === null) throw new Error('useI18n must be used inside an <I18nProvider>.');\n return value;\n}\n","/**\n * `LanguageSwitcher` — a compact segmented control of locale codes (EN · DE · ES · FR · PT), the\n * same shape as the v1 AML console's `#lang-switcher`.\n *\n * Colours come in as PROPS rather than from a theme context on purpose: it keeps this package\n * dependency-free (no peer dep on the UI kit or a design-token package), so any app — themed or\n * not — can drop it in. Themed apps pass their own tokens, e.g.\n * `colors={{ text: colors.textSecondary, activeText: '#fff', activeBackground: colors.primary }}`.\n */\nimport React, { useCallback } from 'react';\nimport { Pressable, StyleSheet, Text, View, type PressableStateCallbackType } from 'react-native';\n\nimport { useI18n } from './I18nProvider';\nimport type { LocaleCode } from './types';\n\nconst BORDER_RADIUS = 8;\nconst PADDING_H = 9;\nconst PADDING_V = 5;\nconst FONT_SIZE = 12;\nconst GAP = 2;\n/** WCAG 2.5.5: an interactive target must be at least 44×44 px. */\nconst MIN_TARGET = 44;\n\nexport interface LanguageSwitcherColors {\n /** Inactive label colour. */\n text: string;\n /** Active label colour. */\n activeText: string;\n /** Active pill background. */\n activeBackground: string;\n /** Hover/press background for an inactive option. Optional. */\n hoverBackground?: string;\n}\n\nexport interface LanguageSwitcherProps {\n colors: LanguageSwitcherColors;\n /** Accessible name for the group. Default `Language`. */\n accessibilityLabel?: string;\n testID?: string;\n}\n\n/**\n * react-native-web adds `hovered` to the Pressable style-callback state; the core react-native\n * types do not model it. Widen the state rather than casting the whole style callback.\n */\ntype PressableState = PressableStateCallbackType & { hovered?: boolean };\n\nconst styles = StyleSheet.create({\n row: { flexDirection: 'row', alignItems: 'center', gap: GAP },\n option: {\n paddingHorizontal: PADDING_H,\n paddingVertical: PADDING_V,\n borderRadius: BORDER_RADIUS,\n minWidth: MIN_TARGET,\n minHeight: MIN_TARGET,\n alignItems: 'center',\n justifyContent: 'center',\n },\n label: { fontSize: FONT_SIZE, fontWeight: '600' },\n});\n\nexport function LanguageSwitcher({\n colors,\n accessibilityLabel = 'Language',\n testID = 'language-switcher',\n}: LanguageSwitcherProps): React.ReactElement {\n const { locale, setLocale, locales } = useI18n();\n\n const select = useCallback((code: LocaleCode) => () => setLocale(code), [setLocale]);\n\n return (\n <View accessibilityRole=\"radiogroup\" aria-label={accessibilityLabel} style={styles.row} testID={testID}>\n {locales.map((option) => {\n const isActive = option.code === locale;\n return (\n <Pressable\n key={option.code}\n accessibilityHint={`Show the interface in ${option.label}`}\n accessibilityLabel={option.label}\n accessibilityRole=\"radio\"\n accessibilityState={{ selected: isActive }}\n aria-checked={isActive}\n style={({ hovered }: PressableState) => [\n styles.option,\n isActive\n ? { backgroundColor: colors.activeBackground }\n : hovered && colors.hoverBackground\n ? { backgroundColor: colors.hoverBackground }\n : null,\n ]}\n testID={`${testID}-${option.code}`}\n onPress={select(option.code)}\n >\n <Text style={[styles.label, { color: isActive ? colors.activeText : colors.text }]}>\n {option.label}\n </Text>\n </Pressable>\n );\n })}\n </View>\n );\n}\n","import i18n, { type i18n as I18nInstance, type Resource } from 'i18next';\nimport { initReactI18next } from 'react-i18next';\n\n/** Options for {@link initI18n}: the app's resources and languages; the package owns the init chain. */\nexport interface InitI18nOptions {\n resources: Resource;\n lng?: string;\n fallbackLng?: string;\n escapeValue?: boolean;\n defaultNS?: string | readonly string[];\n ns?: string | readonly string[];\n}\n\nconst DEFAULT_FALLBACK_LNG = 'en';\n\nconst ignoreInitRejection = (): void => undefined;\n\n/** Wires react-i18next into the i18next singleton, runs `.init()` and returns the singleton. */\nexport function initI18n(options: InitI18nOptions): I18nInstance {\n const {\n resources,\n lng,\n fallbackLng = DEFAULT_FALLBACK_LNG,\n escapeValue = false,\n defaultNS,\n ns,\n } = options;\n\n i18n\n .use(initReactI18next)\n .init({\n lng: lng ?? fallbackLng,\n fallbackLng,\n resources,\n ...(defaultNS !== undefined ? { defaultNS } : {}),\n ...(ns !== undefined ? { ns } : {}),\n interpolation: {\n escapeValue,\n },\n })\n .catch(ignoreInitRejection);\n\n return i18n;\n}\n","/** The slice of an i18next instance that {@link createFormatMessage} needs. */\nexport interface MessageTranslator {\n t: (id: string, options: Record<string, string>) => string;\n}\n\n/** Positional-parameter message formatter: `FM(id, p1, p2, p3)` maps to `{{p1}}`..`{{p3}}`. */\nexport type FormatMessage = (id: string, p1?: string, p2?: string, p3?: string) => string;\n\n/** Builds the portal `FM()` helper over an initialised i18next instance. */\nexport function createFormatMessage(translator: MessageTranslator): FormatMessage {\n return (id, p1, p2, p3) => {\n const options: Record<string, string> = {};\n if (p1 !== undefined && p1 !== null) options.p1 = p1;\n if (p2 !== undefined && p2 !== null) options.p2 = p2;\n if (p3 !== undefined && p3 !== null) options.p3 = p3;\n return translator.t(id, options);\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dloizides/i18n",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Tiny, dependency-free i18n runtime for React / React Native (RN-web) apps — locale detection, persisted choice, per-key English fallback, positional AND named interpolation, and a themable LanguageSwitcher. Its translate function matches the @dloizides UI-kit's `t` contract, so dropping it into UiProvider localizes every shared component for free. Part of the dloizides.com shared kit.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -10,7 +10,9 @@
|
|
|
10
10
|
"internationalization",
|
|
11
11
|
"localization",
|
|
12
12
|
"translate",
|
|
13
|
-
"dloizides"
|
|
13
|
+
"dloizides",
|
|
14
|
+
"i18next",
|
|
15
|
+
"react-i18next"
|
|
14
16
|
],
|
|
15
17
|
"author": "dloizides",
|
|
16
18
|
"license": "MIT",
|
|
@@ -71,14 +73,16 @@
|
|
|
71
73
|
"security:audit": "npm audit --audit-level=high",
|
|
72
74
|
"deps:outdated": "npm outdated || exit 0",
|
|
73
75
|
"deps:unused": "npx depcheck --ignores \"@types/jest,@types/node,@types/react,@types/react-dom,rimraf,react-native\"",
|
|
74
|
-
"deps:licenses": "npx license-checker --onlyAllow \"MIT;Apache-2.0;ISC;BSD-2-Clause;BSD-3-Clause;0BSD;Unlicense;CC0-1.0\"",
|
|
76
|
+
"deps:licenses": "npx license-checker --production --onlyAllow \"MIT;Apache-2.0;ISC;BSD-2-Clause;BSD-3-Clause;0BSD;Unlicense;CC0-1.0;CC-BY-3.0;CC-BY-4.0;Python-2.0;BlueOak-1.0.0\" && npx license-checker --development --onlyAllow \"MIT;Apache-2.0;ISC;BSD-2-Clause;BSD-3-Clause;0BSD;Unlicense;CC0-1.0;CC-BY-3.0;CC-BY-4.0;Python-2.0;BlueOak-1.0.0;LGPL-3.0;LGPL-3.0-only;LGPL-3.0-or-later\"",
|
|
75
77
|
"deps:health": "npm run deps:outdated && npm run deps:unused",
|
|
76
78
|
"prepublishOnly": "npm run clean && npm run build && npm run test",
|
|
77
79
|
"version": "npm run build"
|
|
78
80
|
},
|
|
79
81
|
"peerDependencies": {
|
|
80
82
|
"react": ">=18.0.0",
|
|
81
|
-
"react-native": ">=0.74.0"
|
|
83
|
+
"react-native": ">=0.74.0",
|
|
84
|
+
"i18next": ">=23.0.0",
|
|
85
|
+
"react-i18next": ">=13.0.0"
|
|
82
86
|
},
|
|
83
87
|
"devDependencies": {
|
|
84
88
|
"@testing-library/dom": "^10.4.0",
|
|
@@ -93,15 +97,25 @@
|
|
|
93
97
|
"eslint": "^8.57.0",
|
|
94
98
|
"eslint-plugin-react": "^7.34.0",
|
|
95
99
|
"eslint-plugin-react-hooks": "^4.6.0",
|
|
100
|
+
"i18next": "^23.0.0",
|
|
96
101
|
"jest": "^29.7.0",
|
|
97
102
|
"jest-environment-jsdom": "^29.7.0",
|
|
98
103
|
"react": "^19.2.4",
|
|
99
104
|
"react-dom": "^19.2.4",
|
|
105
|
+
"react-i18next": "^13.0.0",
|
|
100
106
|
"react-native": "0.81.5",
|
|
101
107
|
"react-native-web": "^0.21.0",
|
|
102
108
|
"rimraf": "^5.0.0",
|
|
103
109
|
"ts-jest": "^29.1.0",
|
|
104
110
|
"tsup": "^8.0.0",
|
|
105
111
|
"typescript": "^5.4.0"
|
|
112
|
+
},
|
|
113
|
+
"peerDependenciesMeta": {
|
|
114
|
+
"i18next": {
|
|
115
|
+
"optional": true
|
|
116
|
+
},
|
|
117
|
+
"react-i18next": {
|
|
118
|
+
"optional": true
|
|
119
|
+
}
|
|
106
120
|
}
|
|
107
121
|
}
|