@dloizides/i18n 1.0.1
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 +28 -0
- package/LICENSE +21 -0
- package/README.md +108 -0
- package/dist/index.d.mts +172 -0
- package/dist/index.d.ts +172 -0
- package/dist/index.js +190 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +173 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +107 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to `@dloizides/i18n` are documented here.
|
|
4
|
+
|
|
5
|
+
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
|
|
6
|
+
adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [1.0.0] — 2026-07-12
|
|
9
|
+
|
|
10
|
+
Initial release. Extracted as the shared i18n runtime for the dloizides RN / RN-web apps, first
|
|
11
|
+
consumed by the PROOViD AML v2 console (which needed parity with the v1 console's 5 locales).
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- `I18nProvider` + `useI18n()` — active locale, memoized `t`, persisted choice, `lang`/`dir` on the
|
|
16
|
+
document.
|
|
17
|
+
- `createTranslator` / `lookup` / `interpolateNamed` / `interpolatePositional` — the pure,
|
|
18
|
+
React-free core.
|
|
19
|
+
- **Dual interpolation**: positional `{0}` (so the `t` matches the `@dloizides` UI kit's
|
|
20
|
+
`UiTranslate` contract and localizes every shared component for free) *and* named `{count}` (for
|
|
21
|
+
readable hand-written catalogs).
|
|
22
|
+
- **Per-key** English fallback, so a partially translated locale ships incrementally rather than
|
|
23
|
+
all-or-nothing. A missing key renders as the key itself.
|
|
24
|
+
- Locale resolution: stored → browser language (primary subtag) → fallback, resolved during the
|
|
25
|
+
first render so there is no flash of the fallback language.
|
|
26
|
+
- `LanguageSwitcher` — segmented locale control. Colours are **props**, not a theme context, so the
|
|
27
|
+
package depends on nothing.
|
|
28
|
+
- RTL hook via `applyDocumentLocale` (`<html dir>`); no RTL locale ships yet.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 dloizides
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# @dloizides/i18n
|
|
2
|
+
|
|
3
|
+
Tiny, dependency-free i18n runtime for React / React Native (RN-web) apps.
|
|
4
|
+
|
|
5
|
+
Locale detection, a persisted choice, **per-key** English fallback, **both** positional and named
|
|
6
|
+
interpolation, and a themable `LanguageSwitcher`.
|
|
7
|
+
|
|
8
|
+
## Why this one
|
|
9
|
+
|
|
10
|
+
Its `t` is signature-compatible with the `@dloizides` UI kit's translate contract
|
|
11
|
+
(`UiTranslate` = `(key, p1?, p2?, p3?) => string`). So handing `useI18n().t` to `UiProvider`
|
|
12
|
+
localizes **every shared component** — `DataTable`, `FilterBar`, `Pager`, `StatCard`,
|
|
13
|
+
`StatusBadge`, `ModalDropdown` — with zero per-component work.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @dloizides/i18n
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Peer deps: `react >=18`, `react-native >=0.74` (RN-web counts).
|
|
22
|
+
|
|
23
|
+
## Quick start
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
import { I18nProvider, useI18n, LanguageSwitcher, type Catalogs, type LocaleOption } from '@dloizides/i18n';
|
|
27
|
+
import { UiProvider } from '@dloizides/ui-feedback';
|
|
28
|
+
|
|
29
|
+
const LOCALES: LocaleOption[] = [
|
|
30
|
+
{ code: 'en', label: 'EN' },
|
|
31
|
+
{ code: 'de', label: 'DE' },
|
|
32
|
+
];
|
|
33
|
+
|
|
34
|
+
const CATALOGS: Catalogs = {
|
|
35
|
+
en: { 'cases.title': 'Cases', 'cases.count': '{count} results' },
|
|
36
|
+
de: { 'cases.title': 'Fälle', 'cases.count': '{count} Ergebnisse' },
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Bridge the locale into the shared UI kit — this is the whole integration.
|
|
40
|
+
function KitBridge({ children }: { children: React.ReactNode }) {
|
|
41
|
+
const { t } = useI18n();
|
|
42
|
+
return <UiProvider theme={theme} t={t}>{children}</UiProvider>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export default function App() {
|
|
46
|
+
return (
|
|
47
|
+
<I18nProvider catalogs={CATALOGS} locales={LOCALES}>
|
|
48
|
+
<KitBridge>
|
|
49
|
+
<Screen />
|
|
50
|
+
</KitBridge>
|
|
51
|
+
</I18nProvider>
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function Screen() {
|
|
56
|
+
const { t } = useI18n();
|
|
57
|
+
return (
|
|
58
|
+
<>
|
|
59
|
+
<Text>{t('cases.title')}</Text>
|
|
60
|
+
<Text>{t('cases.count', { count: 12 })}</Text>
|
|
61
|
+
<LanguageSwitcher colors={{ text: '#667', activeText: '#fff', activeBackground: '#4f46e5' }} />
|
|
62
|
+
</>
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Interpolation — two styles, one `t`
|
|
68
|
+
|
|
69
|
+
| Style | Call | Template | Used by |
|
|
70
|
+
|---|---|---|---|
|
|
71
|
+
| **Positional** | `t('stat', 'CPU', '9')` | `Metric {0} is {1}` | the shared UI kit (its `t` contract is positional) |
|
|
72
|
+
| **Named** | `t('count', { count: 12 })` | `{count} results` | hand-written app catalogs (more readable, reorder-safe) |
|
|
73
|
+
|
|
74
|
+
Prefer **named** in app catalogs. Positional exists so the kit's calls keep working.
|
|
75
|
+
|
|
76
|
+
## Behaviour worth knowing
|
|
77
|
+
|
|
78
|
+
- **Per-key fallback.** A locale missing one key falls back to English *for that key only* — the
|
|
79
|
+
rest of the locale still shows translated. Locales can therefore ship incrementally instead of
|
|
80
|
+
all-or-nothing.
|
|
81
|
+
- **A missing key renders as the key.** Visibly wrong beats silently blank.
|
|
82
|
+
- **Resolution order:** stored choice → browser language (primary subtag, so `de-AT` → `de`) →
|
|
83
|
+
fallback. Resolved lazily during the first render, so there is no flash of English.
|
|
84
|
+
- **Storage never throws.** Private mode / native / SSR just means the choice isn't remembered.
|
|
85
|
+
- **RTL hook.** `applyDocumentLocale` sets `<html lang dir>`; mark a locale `rtl: true` and CSS using
|
|
86
|
+
logical properties or `[dir="rtl"]` mirrors itself. No RTL locale ships today — the hook is there.
|
|
87
|
+
|
|
88
|
+
## API
|
|
89
|
+
|
|
90
|
+
| Export | Purpose |
|
|
91
|
+
|---|---|
|
|
92
|
+
| `I18nProvider` | Holds the locale, memoizes `t`, persists the choice, sets `lang`/`dir`. |
|
|
93
|
+
| `useI18n()` | `{ t, locale, setLocale, locales }`. |
|
|
94
|
+
| `LanguageSwitcher` | Segmented locale control. Colours come in as **props**, so this package depends on no theme. |
|
|
95
|
+
| `createTranslator(catalogs, locale, fallback?)` | Pure `t` — usable outside React (tests, formatters, SSR). |
|
|
96
|
+
| `lookup`, `interpolateNamed`, `interpolatePositional` | The pure primitives, exported for tests/tooling. |
|
|
97
|
+
| `resolveInitialLocale`, `primarySubtag`, `isSupported` | Pure locale resolution. |
|
|
98
|
+
| `readStoredLocale`, `writeStoredLocale`, `applyDocumentLocale`, `browserLanguages` | Environment adapters. |
|
|
99
|
+
|
|
100
|
+
## Catalog conventions
|
|
101
|
+
|
|
102
|
+
Flat, dotted keys, namespaced by screen — `cases.title`, `onboarding.step1.lead`. English is
|
|
103
|
+
authoritative: every key MUST exist in `en`. Keep catalogs as plain JSON/TS objects so they can be
|
|
104
|
+
handed to translators and diffed.
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The shared i18n contract.
|
|
5
|
+
*
|
|
6
|
+
* `Translate` is deliberately signature-compatible with the `@dloizides` UI kit's translate
|
|
7
|
+
* contract (`UiTranslate` / `FeedbackTranslate`: `(key, p1?, p2?, p3?) => string`). That is the
|
|
8
|
+
* whole trick: hand a `Translate` to `UiProvider`'s `t` and every shared component (DataTable,
|
|
9
|
+
* FilterBar, Pager, StatCard, StatusBadge, ModalDropdown…) is localized for free, with no
|
|
10
|
+
* per-component work.
|
|
11
|
+
*/
|
|
12
|
+
/** A BCP-47 primary subtag, e.g. `en`, `de`, `pt`. */
|
|
13
|
+
type LocaleCode = string;
|
|
14
|
+
/** One locale's flat key → string map. Keys are dotted, e.g. `cases.title`. */
|
|
15
|
+
type Catalog = Readonly<Record<string, string>>;
|
|
16
|
+
/** Every locale's catalog, keyed by locale code. The fallback locale must be present. */
|
|
17
|
+
type Catalogs = Readonly<Record<LocaleCode, Catalog>>;
|
|
18
|
+
/** Named interpolation values, e.g. `{ count: 3 }` for the template `"{count} results"`. */
|
|
19
|
+
type NamedParams = Readonly<Record<string, string | number>>;
|
|
20
|
+
/**
|
|
21
|
+
* Resolve a key to a localized string.
|
|
22
|
+
*
|
|
23
|
+
* Two interpolation styles are supported, so one function serves both worlds:
|
|
24
|
+
* - **Positional** — `t('analytics.statHint', label)` fills `{0}`, `{1}`, `{2}`. This is what the
|
|
25
|
+
* shared UI kit emits, so the signature must stay `(key, p1?, p2?, p3?)`.
|
|
26
|
+
* - **Named** — `t('leaders.count', { count: 12 })` fills `{count}`. This is what the hand-written
|
|
27
|
+
* app catalogs use (and what the v1 AML console's catalogs already use), which is why existing
|
|
28
|
+
* translations can be reused verbatim.
|
|
29
|
+
*
|
|
30
|
+
* A missing key returns the key itself — a visibly wrong string beats a silently blank UI.
|
|
31
|
+
*/
|
|
32
|
+
type Translate = (key: string, p1?: string | number | NamedParams, p2?: string | number, p3?: string | number) => string;
|
|
33
|
+
/** A selectable locale: its code, the label shown in the switcher, and its writing direction. */
|
|
34
|
+
interface LocaleOption {
|
|
35
|
+
code: LocaleCode;
|
|
36
|
+
/** Short display label for the switcher, e.g. `EN`. */
|
|
37
|
+
label: string;
|
|
38
|
+
/** Right-to-left script. Defaults to false. No RTL locale ships today; the hook exists. */
|
|
39
|
+
rtl?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The pure core: catalog lookup + interpolation. No React, no storage, no side effects — so it is
|
|
44
|
+
* trivially unit-testable and reusable outside a component tree (formatters, tests, server render).
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/** The locale every catalog falls back to, per key. English is authoritative. */
|
|
48
|
+
declare const DEFAULT_FALLBACK_LOCALE = "en";
|
|
49
|
+
/**
|
|
50
|
+
* Fill `{name}` placeholders from a params object. An unmatched placeholder is left intact rather
|
|
51
|
+
* than blanked, so a template/param mismatch is visible instead of silently losing text.
|
|
52
|
+
*/
|
|
53
|
+
declare function interpolateNamed(template: string, params: NamedParams): string;
|
|
54
|
+
/** Fill `{0}`, `{1}`, `{2}` from positional args (the shared UI kit's calling convention). */
|
|
55
|
+
declare function interpolatePositional(template: string, params: ReadonlyArray<string | number | undefined>): string;
|
|
56
|
+
/**
|
|
57
|
+
* Look a key up in `locale`, then in `fallbackLocale`, then give back the key itself.
|
|
58
|
+
*
|
|
59
|
+
* The fallback is **per key**, not per catalog: a partially translated locale still shows its
|
|
60
|
+
* translated keys and only falls back for the ones it is missing. That is what lets a new locale
|
|
61
|
+
* ship incrementally instead of all-or-nothing.
|
|
62
|
+
*/
|
|
63
|
+
declare function lookup(catalogs: Catalogs, locale: LocaleCode, key: string, fallbackLocale?: LocaleCode): string;
|
|
64
|
+
/**
|
|
65
|
+
* Build a {@link Translate} bound to one locale. Supports BOTH interpolation styles — see the
|
|
66
|
+
* `Translate` docs for why (positional = the UI kit; named = hand-written app catalogs).
|
|
67
|
+
*/
|
|
68
|
+
declare function createTranslator(catalogs: Catalogs, locale: LocaleCode, fallbackLocale?: LocaleCode): Translate;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Locale resolution + persistence.
|
|
72
|
+
*
|
|
73
|
+
* The resolution order mirrors the v1 AML console (`shared/i18n.js`): a previously stored choice
|
|
74
|
+
* wins, else the browser's preferred language (primary subtag only — `de-AT` → `de`), else the
|
|
75
|
+
* fallback. Storage is best-effort: private mode / a native runtime with no `localStorage` must not
|
|
76
|
+
* throw, it just means the choice does not persist.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/** Default persistence key. Override per app so two apps on one origin don't fight. */
|
|
80
|
+
declare const DEFAULT_STORAGE_KEY = "dloizides_locale";
|
|
81
|
+
/** True when `code` is one of the app's supported locales. Pure. */
|
|
82
|
+
declare function isSupported(locales: readonly LocaleOption[], code: string): boolean;
|
|
83
|
+
/** `de-AT` → `de`; `EN` → `en`. Pure. */
|
|
84
|
+
declare function primarySubtag(tag: string): string;
|
|
85
|
+
/**
|
|
86
|
+
* Pick the locale to start in: stored → browser-preferred → fallback. Pure — the caller supplies
|
|
87
|
+
* the stored value and the browser's language list, which keeps this testable with no globals.
|
|
88
|
+
*/
|
|
89
|
+
declare function resolveInitialLocale(locales: readonly LocaleOption[], stored: string | null, preferred: readonly string[], fallback: LocaleCode): LocaleCode;
|
|
90
|
+
/** The browser's preferred languages, most-preferred first. `[]` off-web. */
|
|
91
|
+
declare function browserLanguages(): string[];
|
|
92
|
+
/** Read the persisted locale. Never throws (private mode, native, SSR). */
|
|
93
|
+
declare function readStoredLocale(storageKey: string): string | null;
|
|
94
|
+
/** Persist the locale. Never throws — a failure just means it won't be remembered. */
|
|
95
|
+
declare function writeStoredLocale(storageKey: string, code: LocaleCode): void;
|
|
96
|
+
/**
|
|
97
|
+
* Reflect the locale on the document so CSS can react (`:lang()`, `[dir="rtl"]`). Web-only no-op
|
|
98
|
+
* elsewhere. This is the RTL hook: ship an `rtl: true` locale and the layout can mirror itself
|
|
99
|
+
* without any component changes.
|
|
100
|
+
*/
|
|
101
|
+
declare function applyDocumentLocale(locales: readonly LocaleOption[], code: LocaleCode): void;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `I18nProvider` — holds the active locale, exposes a memoized {@link Translate}, persists the
|
|
105
|
+
* user's choice, and reflects `lang`/`dir` on the document.
|
|
106
|
+
*
|
|
107
|
+
* Wiring it to the rest of the shared kit is one line, because {@link Translate} is
|
|
108
|
+
* signature-compatible with the kit's `t` contract:
|
|
109
|
+
*
|
|
110
|
+
* ```tsx
|
|
111
|
+
* <I18nProvider catalogs={CATALOGS} locales={LOCALES}>
|
|
112
|
+
* <KitBridge /> // const { t } = useI18n(); return <UiProvider theme={theme} t={t}>…
|
|
113
|
+
* </I18nProvider>
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
interface I18nValue {
|
|
118
|
+
/** Resolve a key in the active locale (positional or named interpolation). */
|
|
119
|
+
t: Translate;
|
|
120
|
+
/** The active locale code. */
|
|
121
|
+
locale: LocaleCode;
|
|
122
|
+
/** Switch locale: re-renders consumers, persists the choice, updates `lang`/`dir`. */
|
|
123
|
+
setLocale: (code: LocaleCode) => void;
|
|
124
|
+
/** Every locale the app offers (for a switcher). */
|
|
125
|
+
locales: readonly LocaleOption[];
|
|
126
|
+
}
|
|
127
|
+
interface I18nProviderProps {
|
|
128
|
+
/** Every locale's catalog. The fallback locale's catalog is required. */
|
|
129
|
+
catalogs: Catalogs;
|
|
130
|
+
/** The locales offered to the user, in display order. */
|
|
131
|
+
locales: readonly LocaleOption[];
|
|
132
|
+
/** Per-key fallback locale. Default `en`. */
|
|
133
|
+
fallbackLocale?: LocaleCode;
|
|
134
|
+
/** localStorage key for the persisted choice. Default `dloizides_locale`. */
|
|
135
|
+
storageKey?: string;
|
|
136
|
+
/** Force a locale (tests / SSR). When set, detection and persistence are skipped. */
|
|
137
|
+
initialLocale?: LocaleCode;
|
|
138
|
+
children: React.ReactNode;
|
|
139
|
+
}
|
|
140
|
+
declare function I18nProvider({ catalogs, locales, fallbackLocale, storageKey, initialLocale, children, }: I18nProviderProps): React.ReactElement;
|
|
141
|
+
/** Access the active locale + translate function. Throws outside an {@link I18nProvider}. */
|
|
142
|
+
declare function useI18n(): I18nValue;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* `LanguageSwitcher` — a compact segmented control of locale codes (EN · DE · ES · FR · PT), the
|
|
146
|
+
* same shape as the v1 AML console's `#lang-switcher`.
|
|
147
|
+
*
|
|
148
|
+
* Colours come in as PROPS rather than from a theme context on purpose: it keeps this package
|
|
149
|
+
* dependency-free (no peer dep on the UI kit or a design-token package), so any app — themed or
|
|
150
|
+
* not — can drop it in. Themed apps pass their own tokens, e.g.
|
|
151
|
+
* `colors={{ text: colors.textSecondary, activeText: '#fff', activeBackground: colors.primary }}`.
|
|
152
|
+
*/
|
|
153
|
+
|
|
154
|
+
interface LanguageSwitcherColors {
|
|
155
|
+
/** Inactive label colour. */
|
|
156
|
+
text: string;
|
|
157
|
+
/** Active label colour. */
|
|
158
|
+
activeText: string;
|
|
159
|
+
/** Active pill background. */
|
|
160
|
+
activeBackground: string;
|
|
161
|
+
/** Hover/press background for an inactive option. Optional. */
|
|
162
|
+
hoverBackground?: string;
|
|
163
|
+
}
|
|
164
|
+
interface LanguageSwitcherProps {
|
|
165
|
+
colors: LanguageSwitcherColors;
|
|
166
|
+
/** Accessible name for the group. Default `Language`. */
|
|
167
|
+
accessibilityLabel?: string;
|
|
168
|
+
testID?: string;
|
|
169
|
+
}
|
|
170
|
+
declare function LanguageSwitcher({ colors, accessibilityLabel, testID, }: LanguageSwitcherProps): React.ReactElement;
|
|
171
|
+
|
|
172
|
+
export { type Catalog, type Catalogs, DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, I18nProvider, type I18nProviderProps, type I18nValue, LanguageSwitcher, type LanguageSwitcherColors, type LanguageSwitcherProps, type LocaleCode, type LocaleOption, type NamedParams, type Translate, applyDocumentLocale, browserLanguages, createTranslator, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The shared i18n contract.
|
|
5
|
+
*
|
|
6
|
+
* `Translate` is deliberately signature-compatible with the `@dloizides` UI kit's translate
|
|
7
|
+
* contract (`UiTranslate` / `FeedbackTranslate`: `(key, p1?, p2?, p3?) => string`). That is the
|
|
8
|
+
* whole trick: hand a `Translate` to `UiProvider`'s `t` and every shared component (DataTable,
|
|
9
|
+
* FilterBar, Pager, StatCard, StatusBadge, ModalDropdown…) is localized for free, with no
|
|
10
|
+
* per-component work.
|
|
11
|
+
*/
|
|
12
|
+
/** A BCP-47 primary subtag, e.g. `en`, `de`, `pt`. */
|
|
13
|
+
type LocaleCode = string;
|
|
14
|
+
/** One locale's flat key → string map. Keys are dotted, e.g. `cases.title`. */
|
|
15
|
+
type Catalog = Readonly<Record<string, string>>;
|
|
16
|
+
/** Every locale's catalog, keyed by locale code. The fallback locale must be present. */
|
|
17
|
+
type Catalogs = Readonly<Record<LocaleCode, Catalog>>;
|
|
18
|
+
/** Named interpolation values, e.g. `{ count: 3 }` for the template `"{count} results"`. */
|
|
19
|
+
type NamedParams = Readonly<Record<string, string | number>>;
|
|
20
|
+
/**
|
|
21
|
+
* Resolve a key to a localized string.
|
|
22
|
+
*
|
|
23
|
+
* Two interpolation styles are supported, so one function serves both worlds:
|
|
24
|
+
* - **Positional** — `t('analytics.statHint', label)` fills `{0}`, `{1}`, `{2}`. This is what the
|
|
25
|
+
* shared UI kit emits, so the signature must stay `(key, p1?, p2?, p3?)`.
|
|
26
|
+
* - **Named** — `t('leaders.count', { count: 12 })` fills `{count}`. This is what the hand-written
|
|
27
|
+
* app catalogs use (and what the v1 AML console's catalogs already use), which is why existing
|
|
28
|
+
* translations can be reused verbatim.
|
|
29
|
+
*
|
|
30
|
+
* A missing key returns the key itself — a visibly wrong string beats a silently blank UI.
|
|
31
|
+
*/
|
|
32
|
+
type Translate = (key: string, p1?: string | number | NamedParams, p2?: string | number, p3?: string | number) => string;
|
|
33
|
+
/** A selectable locale: its code, the label shown in the switcher, and its writing direction. */
|
|
34
|
+
interface LocaleOption {
|
|
35
|
+
code: LocaleCode;
|
|
36
|
+
/** Short display label for the switcher, e.g. `EN`. */
|
|
37
|
+
label: string;
|
|
38
|
+
/** Right-to-left script. Defaults to false. No RTL locale ships today; the hook exists. */
|
|
39
|
+
rtl?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The pure core: catalog lookup + interpolation. No React, no storage, no side effects — so it is
|
|
44
|
+
* trivially unit-testable and reusable outside a component tree (formatters, tests, server render).
|
|
45
|
+
*/
|
|
46
|
+
|
|
47
|
+
/** The locale every catalog falls back to, per key. English is authoritative. */
|
|
48
|
+
declare const DEFAULT_FALLBACK_LOCALE = "en";
|
|
49
|
+
/**
|
|
50
|
+
* Fill `{name}` placeholders from a params object. An unmatched placeholder is left intact rather
|
|
51
|
+
* than blanked, so a template/param mismatch is visible instead of silently losing text.
|
|
52
|
+
*/
|
|
53
|
+
declare function interpolateNamed(template: string, params: NamedParams): string;
|
|
54
|
+
/** Fill `{0}`, `{1}`, `{2}` from positional args (the shared UI kit's calling convention). */
|
|
55
|
+
declare function interpolatePositional(template: string, params: ReadonlyArray<string | number | undefined>): string;
|
|
56
|
+
/**
|
|
57
|
+
* Look a key up in `locale`, then in `fallbackLocale`, then give back the key itself.
|
|
58
|
+
*
|
|
59
|
+
* The fallback is **per key**, not per catalog: a partially translated locale still shows its
|
|
60
|
+
* translated keys and only falls back for the ones it is missing. That is what lets a new locale
|
|
61
|
+
* ship incrementally instead of all-or-nothing.
|
|
62
|
+
*/
|
|
63
|
+
declare function lookup(catalogs: Catalogs, locale: LocaleCode, key: string, fallbackLocale?: LocaleCode): string;
|
|
64
|
+
/**
|
|
65
|
+
* Build a {@link Translate} bound to one locale. Supports BOTH interpolation styles — see the
|
|
66
|
+
* `Translate` docs for why (positional = the UI kit; named = hand-written app catalogs).
|
|
67
|
+
*/
|
|
68
|
+
declare function createTranslator(catalogs: Catalogs, locale: LocaleCode, fallbackLocale?: LocaleCode): Translate;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Locale resolution + persistence.
|
|
72
|
+
*
|
|
73
|
+
* The resolution order mirrors the v1 AML console (`shared/i18n.js`): a previously stored choice
|
|
74
|
+
* wins, else the browser's preferred language (primary subtag only — `de-AT` → `de`), else the
|
|
75
|
+
* fallback. Storage is best-effort: private mode / a native runtime with no `localStorage` must not
|
|
76
|
+
* throw, it just means the choice does not persist.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
/** Default persistence key. Override per app so two apps on one origin don't fight. */
|
|
80
|
+
declare const DEFAULT_STORAGE_KEY = "dloizides_locale";
|
|
81
|
+
/** True when `code` is one of the app's supported locales. Pure. */
|
|
82
|
+
declare function isSupported(locales: readonly LocaleOption[], code: string): boolean;
|
|
83
|
+
/** `de-AT` → `de`; `EN` → `en`. Pure. */
|
|
84
|
+
declare function primarySubtag(tag: string): string;
|
|
85
|
+
/**
|
|
86
|
+
* Pick the locale to start in: stored → browser-preferred → fallback. Pure — the caller supplies
|
|
87
|
+
* the stored value and the browser's language list, which keeps this testable with no globals.
|
|
88
|
+
*/
|
|
89
|
+
declare function resolveInitialLocale(locales: readonly LocaleOption[], stored: string | null, preferred: readonly string[], fallback: LocaleCode): LocaleCode;
|
|
90
|
+
/** The browser's preferred languages, most-preferred first. `[]` off-web. */
|
|
91
|
+
declare function browserLanguages(): string[];
|
|
92
|
+
/** Read the persisted locale. Never throws (private mode, native, SSR). */
|
|
93
|
+
declare function readStoredLocale(storageKey: string): string | null;
|
|
94
|
+
/** Persist the locale. Never throws — a failure just means it won't be remembered. */
|
|
95
|
+
declare function writeStoredLocale(storageKey: string, code: LocaleCode): void;
|
|
96
|
+
/**
|
|
97
|
+
* Reflect the locale on the document so CSS can react (`:lang()`, `[dir="rtl"]`). Web-only no-op
|
|
98
|
+
* elsewhere. This is the RTL hook: ship an `rtl: true` locale and the layout can mirror itself
|
|
99
|
+
* without any component changes.
|
|
100
|
+
*/
|
|
101
|
+
declare function applyDocumentLocale(locales: readonly LocaleOption[], code: LocaleCode): void;
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* `I18nProvider` — holds the active locale, exposes a memoized {@link Translate}, persists the
|
|
105
|
+
* user's choice, and reflects `lang`/`dir` on the document.
|
|
106
|
+
*
|
|
107
|
+
* Wiring it to the rest of the shared kit is one line, because {@link Translate} is
|
|
108
|
+
* signature-compatible with the kit's `t` contract:
|
|
109
|
+
*
|
|
110
|
+
* ```tsx
|
|
111
|
+
* <I18nProvider catalogs={CATALOGS} locales={LOCALES}>
|
|
112
|
+
* <KitBridge /> // const { t } = useI18n(); return <UiProvider theme={theme} t={t}>…
|
|
113
|
+
* </I18nProvider>
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
|
|
117
|
+
interface I18nValue {
|
|
118
|
+
/** Resolve a key in the active locale (positional or named interpolation). */
|
|
119
|
+
t: Translate;
|
|
120
|
+
/** The active locale code. */
|
|
121
|
+
locale: LocaleCode;
|
|
122
|
+
/** Switch locale: re-renders consumers, persists the choice, updates `lang`/`dir`. */
|
|
123
|
+
setLocale: (code: LocaleCode) => void;
|
|
124
|
+
/** Every locale the app offers (for a switcher). */
|
|
125
|
+
locales: readonly LocaleOption[];
|
|
126
|
+
}
|
|
127
|
+
interface I18nProviderProps {
|
|
128
|
+
/** Every locale's catalog. The fallback locale's catalog is required. */
|
|
129
|
+
catalogs: Catalogs;
|
|
130
|
+
/** The locales offered to the user, in display order. */
|
|
131
|
+
locales: readonly LocaleOption[];
|
|
132
|
+
/** Per-key fallback locale. Default `en`. */
|
|
133
|
+
fallbackLocale?: LocaleCode;
|
|
134
|
+
/** localStorage key for the persisted choice. Default `dloizides_locale`. */
|
|
135
|
+
storageKey?: string;
|
|
136
|
+
/** Force a locale (tests / SSR). When set, detection and persistence are skipped. */
|
|
137
|
+
initialLocale?: LocaleCode;
|
|
138
|
+
children: React.ReactNode;
|
|
139
|
+
}
|
|
140
|
+
declare function I18nProvider({ catalogs, locales, fallbackLocale, storageKey, initialLocale, children, }: I18nProviderProps): React.ReactElement;
|
|
141
|
+
/** Access the active locale + translate function. Throws outside an {@link I18nProvider}. */
|
|
142
|
+
declare function useI18n(): I18nValue;
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* `LanguageSwitcher` — a compact segmented control of locale codes (EN · DE · ES · FR · PT), the
|
|
146
|
+
* same shape as the v1 AML console's `#lang-switcher`.
|
|
147
|
+
*
|
|
148
|
+
* Colours come in as PROPS rather than from a theme context on purpose: it keeps this package
|
|
149
|
+
* dependency-free (no peer dep on the UI kit or a design-token package), so any app — themed or
|
|
150
|
+
* not — can drop it in. Themed apps pass their own tokens, e.g.
|
|
151
|
+
* `colors={{ text: colors.textSecondary, activeText: '#fff', activeBackground: colors.primary }}`.
|
|
152
|
+
*/
|
|
153
|
+
|
|
154
|
+
interface LanguageSwitcherColors {
|
|
155
|
+
/** Inactive label colour. */
|
|
156
|
+
text: string;
|
|
157
|
+
/** Active label colour. */
|
|
158
|
+
activeText: string;
|
|
159
|
+
/** Active pill background. */
|
|
160
|
+
activeBackground: string;
|
|
161
|
+
/** Hover/press background for an inactive option. Optional. */
|
|
162
|
+
hoverBackground?: string;
|
|
163
|
+
}
|
|
164
|
+
interface LanguageSwitcherProps {
|
|
165
|
+
colors: LanguageSwitcherColors;
|
|
166
|
+
/** Accessible name for the group. Default `Language`. */
|
|
167
|
+
accessibilityLabel?: string;
|
|
168
|
+
testID?: string;
|
|
169
|
+
}
|
|
170
|
+
declare function LanguageSwitcher({ colors, accessibilityLabel, testID, }: LanguageSwitcherProps): React.ReactElement;
|
|
171
|
+
|
|
172
|
+
export { type Catalog, type Catalogs, DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, I18nProvider, type I18nProviderProps, type I18nValue, LanguageSwitcher, type LanguageSwitcherColors, type LanguageSwitcherProps, type LocaleCode, type LocaleOption, type NamedParams, type Translate, applyDocumentLocale, browserLanguages, createTranslator, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var react = require('react');
|
|
4
|
+
var jsxRuntime = require('react/jsx-runtime');
|
|
5
|
+
var reactNative = require('react-native');
|
|
6
|
+
|
|
7
|
+
// src/createTranslator.ts
|
|
8
|
+
var DEFAULT_FALLBACK_LOCALE = "en";
|
|
9
|
+
function isNamedParams(value) {
|
|
10
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
11
|
+
}
|
|
12
|
+
function interpolateNamed(template, params) {
|
|
13
|
+
return template.replace(
|
|
14
|
+
/\{(\w+)\}/g,
|
|
15
|
+
(match, name) => Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
function interpolatePositional(template, params) {
|
|
19
|
+
return params.reduce(
|
|
20
|
+
(acc, param, index) => param === void 0 ? acc : acc.split(`{${index}}`).join(String(param)),
|
|
21
|
+
template
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
function lookup(catalogs, locale, key, fallbackLocale = DEFAULT_FALLBACK_LOCALE) {
|
|
25
|
+
const active = catalogs[locale];
|
|
26
|
+
const fallback = catalogs[fallbackLocale];
|
|
27
|
+
return active?.[key] ?? fallback?.[key] ?? key;
|
|
28
|
+
}
|
|
29
|
+
function createTranslator(catalogs, locale, fallbackLocale = DEFAULT_FALLBACK_LOCALE) {
|
|
30
|
+
return (key, p1, p2, p3) => {
|
|
31
|
+
const template = lookup(catalogs, locale, key, fallbackLocale);
|
|
32
|
+
if (isNamedParams(p1)) return interpolateNamed(template, p1);
|
|
33
|
+
return interpolatePositional(template, [p1, p2, p3]);
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// src/detectLocale.ts
|
|
38
|
+
var DEFAULT_STORAGE_KEY = "dloizides_locale";
|
|
39
|
+
function isSupported(locales, code) {
|
|
40
|
+
return locales.some((l) => l.code === code);
|
|
41
|
+
}
|
|
42
|
+
function primarySubtag(tag) {
|
|
43
|
+
return String(tag).toLowerCase().split("-")[0] ?? "";
|
|
44
|
+
}
|
|
45
|
+
function resolveInitialLocale(locales, stored, preferred, fallback) {
|
|
46
|
+
if (stored && isSupported(locales, stored)) return stored;
|
|
47
|
+
for (const tag of preferred) {
|
|
48
|
+
const primary = primarySubtag(tag);
|
|
49
|
+
if (isSupported(locales, primary)) return primary;
|
|
50
|
+
}
|
|
51
|
+
return fallback;
|
|
52
|
+
}
|
|
53
|
+
function browserLanguages() {
|
|
54
|
+
if (typeof navigator === "undefined") return [];
|
|
55
|
+
const nav = navigator;
|
|
56
|
+
const list = Array.isArray(nav.languages) && nav.languages.length > 0 ? nav.languages : [];
|
|
57
|
+
const single = nav.language ?? nav.userLanguage;
|
|
58
|
+
return list.length > 0 ? [...list] : single ? [single] : [];
|
|
59
|
+
}
|
|
60
|
+
function readStoredLocale(storageKey) {
|
|
61
|
+
try {
|
|
62
|
+
if (typeof localStorage === "undefined") return null;
|
|
63
|
+
return localStorage.getItem(storageKey);
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function writeStoredLocale(storageKey, code) {
|
|
69
|
+
try {
|
|
70
|
+
if (typeof localStorage === "undefined") return;
|
|
71
|
+
localStorage.setItem(storageKey, code);
|
|
72
|
+
} catch {
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function applyDocumentLocale(locales, code) {
|
|
76
|
+
if (typeof document === "undefined") return;
|
|
77
|
+
const option = locales.find((l) => l.code === code);
|
|
78
|
+
document.documentElement.lang = code;
|
|
79
|
+
document.documentElement.dir = option?.rtl ? "rtl" : "ltr";
|
|
80
|
+
}
|
|
81
|
+
var I18nContext = react.createContext(null);
|
|
82
|
+
function I18nProvider({
|
|
83
|
+
catalogs,
|
|
84
|
+
locales,
|
|
85
|
+
fallbackLocale = DEFAULT_FALLBACK_LOCALE,
|
|
86
|
+
storageKey = DEFAULT_STORAGE_KEY,
|
|
87
|
+
initialLocale,
|
|
88
|
+
children
|
|
89
|
+
}) {
|
|
90
|
+
const [locale, setLocaleState] = react.useState(() => {
|
|
91
|
+
if (initialLocale) return initialLocale;
|
|
92
|
+
const resolved = resolveInitialLocale(
|
|
93
|
+
locales,
|
|
94
|
+
readStoredLocale(storageKey),
|
|
95
|
+
browserLanguages(),
|
|
96
|
+
fallbackLocale
|
|
97
|
+
);
|
|
98
|
+
applyDocumentLocale(locales, resolved);
|
|
99
|
+
return resolved;
|
|
100
|
+
});
|
|
101
|
+
const setLocale = react.useCallback(
|
|
102
|
+
(code) => {
|
|
103
|
+
setLocaleState(code);
|
|
104
|
+
writeStoredLocale(storageKey, code);
|
|
105
|
+
applyDocumentLocale(locales, code);
|
|
106
|
+
},
|
|
107
|
+
[locales, storageKey]
|
|
108
|
+
);
|
|
109
|
+
const t = react.useMemo(
|
|
110
|
+
() => createTranslator(catalogs, locale, fallbackLocale),
|
|
111
|
+
[catalogs, locale, fallbackLocale]
|
|
112
|
+
);
|
|
113
|
+
const value = react.useMemo(
|
|
114
|
+
() => ({ t, locale, setLocale, locales }),
|
|
115
|
+
[t, locale, setLocale, locales]
|
|
116
|
+
);
|
|
117
|
+
return /* @__PURE__ */ jsxRuntime.jsx(I18nContext.Provider, { value, children });
|
|
118
|
+
}
|
|
119
|
+
function useI18n() {
|
|
120
|
+
const value = react.useContext(I18nContext);
|
|
121
|
+
if (value === null) throw new Error("useI18n must be used inside an <I18nProvider>.");
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
var BORDER_RADIUS = 8;
|
|
125
|
+
var PADDING_H = 9;
|
|
126
|
+
var PADDING_V = 5;
|
|
127
|
+
var FONT_SIZE = 12;
|
|
128
|
+
var GAP = 2;
|
|
129
|
+
var MIN_TARGET = 44;
|
|
130
|
+
var styles = reactNative.StyleSheet.create({
|
|
131
|
+
row: { flexDirection: "row", alignItems: "center", gap: GAP },
|
|
132
|
+
option: {
|
|
133
|
+
paddingHorizontal: PADDING_H,
|
|
134
|
+
paddingVertical: PADDING_V,
|
|
135
|
+
borderRadius: BORDER_RADIUS,
|
|
136
|
+
minWidth: MIN_TARGET,
|
|
137
|
+
minHeight: MIN_TARGET,
|
|
138
|
+
alignItems: "center",
|
|
139
|
+
justifyContent: "center"
|
|
140
|
+
},
|
|
141
|
+
label: { fontSize: FONT_SIZE, fontWeight: "600" }
|
|
142
|
+
});
|
|
143
|
+
function LanguageSwitcher({
|
|
144
|
+
colors,
|
|
145
|
+
accessibilityLabel = "Language",
|
|
146
|
+
testID = "language-switcher"
|
|
147
|
+
}) {
|
|
148
|
+
const { locale, setLocale, locales } = useI18n();
|
|
149
|
+
const select = react.useCallback((code) => () => setLocale(code), [setLocale]);
|
|
150
|
+
return /* @__PURE__ */ jsxRuntime.jsx(reactNative.View, { accessibilityRole: "radiogroup", "aria-label": accessibilityLabel, style: styles.row, testID, children: locales.map((option) => {
|
|
151
|
+
const isActive = option.code === locale;
|
|
152
|
+
return /* @__PURE__ */ jsxRuntime.jsx(
|
|
153
|
+
reactNative.Pressable,
|
|
154
|
+
{
|
|
155
|
+
accessibilityHint: `Show the interface in ${option.label}`,
|
|
156
|
+
accessibilityLabel: option.label,
|
|
157
|
+
accessibilityRole: "radio",
|
|
158
|
+
accessibilityState: { selected: isActive },
|
|
159
|
+
"aria-checked": isActive,
|
|
160
|
+
style: ({ hovered }) => [
|
|
161
|
+
styles.option,
|
|
162
|
+
isActive ? { backgroundColor: colors.activeBackground } : hovered && colors.hoverBackground ? { backgroundColor: colors.hoverBackground } : null
|
|
163
|
+
],
|
|
164
|
+
testID: `${testID}-${option.code}`,
|
|
165
|
+
onPress: select(option.code),
|
|
166
|
+
children: /* @__PURE__ */ jsxRuntime.jsx(reactNative.Text, { style: [styles.label, { color: isActive ? colors.activeText : colors.text }], children: option.label })
|
|
167
|
+
},
|
|
168
|
+
option.code
|
|
169
|
+
);
|
|
170
|
+
}) });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
exports.DEFAULT_FALLBACK_LOCALE = DEFAULT_FALLBACK_LOCALE;
|
|
174
|
+
exports.DEFAULT_STORAGE_KEY = DEFAULT_STORAGE_KEY;
|
|
175
|
+
exports.I18nProvider = I18nProvider;
|
|
176
|
+
exports.LanguageSwitcher = LanguageSwitcher;
|
|
177
|
+
exports.applyDocumentLocale = applyDocumentLocale;
|
|
178
|
+
exports.browserLanguages = browserLanguages;
|
|
179
|
+
exports.createTranslator = createTranslator;
|
|
180
|
+
exports.interpolateNamed = interpolateNamed;
|
|
181
|
+
exports.interpolatePositional = interpolatePositional;
|
|
182
|
+
exports.isSupported = isSupported;
|
|
183
|
+
exports.lookup = lookup;
|
|
184
|
+
exports.primarySubtag = primarySubtag;
|
|
185
|
+
exports.readStoredLocale = readStoredLocale;
|
|
186
|
+
exports.resolveInitialLocale = resolveInitialLocale;
|
|
187
|
+
exports.useI18n = useI18n;
|
|
188
|
+
exports.writeStoredLocale = writeStoredLocale;
|
|
189
|
+
//# sourceMappingURL=index.js.map
|
|
190
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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,CAAK,MAAA,EAAQ,IAAI,CAAA,GAAI,MAAA,CAAO,MAAA,CAAO,IAAI,CAAC,CAAA,GAAI;AAAA,GAC9E;AACF;AAGO,SAAS,qBAAA,CACd,UACA,MAAA,E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AI,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"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { createContext, useState, useCallback, useMemo, useContext } from 'react';
|
|
2
|
+
import { jsx } from 'react/jsx-runtime';
|
|
3
|
+
import { StyleSheet, View, Pressable, Text } from 'react-native';
|
|
4
|
+
|
|
5
|
+
// src/createTranslator.ts
|
|
6
|
+
var DEFAULT_FALLBACK_LOCALE = "en";
|
|
7
|
+
function isNamedParams(value) {
|
|
8
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
9
|
+
}
|
|
10
|
+
function interpolateNamed(template, params) {
|
|
11
|
+
return template.replace(
|
|
12
|
+
/\{(\w+)\}/g,
|
|
13
|
+
(match, name) => Object.prototype.hasOwnProperty.call(params, name) ? String(params[name]) : match
|
|
14
|
+
);
|
|
15
|
+
}
|
|
16
|
+
function interpolatePositional(template, params) {
|
|
17
|
+
return params.reduce(
|
|
18
|
+
(acc, param, index) => param === void 0 ? acc : acc.split(`{${index}}`).join(String(param)),
|
|
19
|
+
template
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
function lookup(catalogs, locale, key, fallbackLocale = DEFAULT_FALLBACK_LOCALE) {
|
|
23
|
+
const active = catalogs[locale];
|
|
24
|
+
const fallback = catalogs[fallbackLocale];
|
|
25
|
+
return active?.[key] ?? fallback?.[key] ?? key;
|
|
26
|
+
}
|
|
27
|
+
function createTranslator(catalogs, locale, fallbackLocale = DEFAULT_FALLBACK_LOCALE) {
|
|
28
|
+
return (key, p1, p2, p3) => {
|
|
29
|
+
const template = lookup(catalogs, locale, key, fallbackLocale);
|
|
30
|
+
if (isNamedParams(p1)) return interpolateNamed(template, p1);
|
|
31
|
+
return interpolatePositional(template, [p1, p2, p3]);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// src/detectLocale.ts
|
|
36
|
+
var DEFAULT_STORAGE_KEY = "dloizides_locale";
|
|
37
|
+
function isSupported(locales, code) {
|
|
38
|
+
return locales.some((l) => l.code === code);
|
|
39
|
+
}
|
|
40
|
+
function primarySubtag(tag) {
|
|
41
|
+
return String(tag).toLowerCase().split("-")[0] ?? "";
|
|
42
|
+
}
|
|
43
|
+
function resolveInitialLocale(locales, stored, preferred, fallback) {
|
|
44
|
+
if (stored && isSupported(locales, stored)) return stored;
|
|
45
|
+
for (const tag of preferred) {
|
|
46
|
+
const primary = primarySubtag(tag);
|
|
47
|
+
if (isSupported(locales, primary)) return primary;
|
|
48
|
+
}
|
|
49
|
+
return fallback;
|
|
50
|
+
}
|
|
51
|
+
function browserLanguages() {
|
|
52
|
+
if (typeof navigator === "undefined") return [];
|
|
53
|
+
const nav = navigator;
|
|
54
|
+
const list = Array.isArray(nav.languages) && nav.languages.length > 0 ? nav.languages : [];
|
|
55
|
+
const single = nav.language ?? nav.userLanguage;
|
|
56
|
+
return list.length > 0 ? [...list] : single ? [single] : [];
|
|
57
|
+
}
|
|
58
|
+
function readStoredLocale(storageKey) {
|
|
59
|
+
try {
|
|
60
|
+
if (typeof localStorage === "undefined") return null;
|
|
61
|
+
return localStorage.getItem(storageKey);
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function writeStoredLocale(storageKey, code) {
|
|
67
|
+
try {
|
|
68
|
+
if (typeof localStorage === "undefined") return;
|
|
69
|
+
localStorage.setItem(storageKey, code);
|
|
70
|
+
} catch {
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function applyDocumentLocale(locales, code) {
|
|
74
|
+
if (typeof document === "undefined") return;
|
|
75
|
+
const option = locales.find((l) => l.code === code);
|
|
76
|
+
document.documentElement.lang = code;
|
|
77
|
+
document.documentElement.dir = option?.rtl ? "rtl" : "ltr";
|
|
78
|
+
}
|
|
79
|
+
var I18nContext = createContext(null);
|
|
80
|
+
function I18nProvider({
|
|
81
|
+
catalogs,
|
|
82
|
+
locales,
|
|
83
|
+
fallbackLocale = DEFAULT_FALLBACK_LOCALE,
|
|
84
|
+
storageKey = DEFAULT_STORAGE_KEY,
|
|
85
|
+
initialLocale,
|
|
86
|
+
children
|
|
87
|
+
}) {
|
|
88
|
+
const [locale, setLocaleState] = useState(() => {
|
|
89
|
+
if (initialLocale) return initialLocale;
|
|
90
|
+
const resolved = resolveInitialLocale(
|
|
91
|
+
locales,
|
|
92
|
+
readStoredLocale(storageKey),
|
|
93
|
+
browserLanguages(),
|
|
94
|
+
fallbackLocale
|
|
95
|
+
);
|
|
96
|
+
applyDocumentLocale(locales, resolved);
|
|
97
|
+
return resolved;
|
|
98
|
+
});
|
|
99
|
+
const setLocale = useCallback(
|
|
100
|
+
(code) => {
|
|
101
|
+
setLocaleState(code);
|
|
102
|
+
writeStoredLocale(storageKey, code);
|
|
103
|
+
applyDocumentLocale(locales, code);
|
|
104
|
+
},
|
|
105
|
+
[locales, storageKey]
|
|
106
|
+
);
|
|
107
|
+
const t = useMemo(
|
|
108
|
+
() => createTranslator(catalogs, locale, fallbackLocale),
|
|
109
|
+
[catalogs, locale, fallbackLocale]
|
|
110
|
+
);
|
|
111
|
+
const value = useMemo(
|
|
112
|
+
() => ({ t, locale, setLocale, locales }),
|
|
113
|
+
[t, locale, setLocale, locales]
|
|
114
|
+
);
|
|
115
|
+
return /* @__PURE__ */ jsx(I18nContext.Provider, { value, children });
|
|
116
|
+
}
|
|
117
|
+
function useI18n() {
|
|
118
|
+
const value = useContext(I18nContext);
|
|
119
|
+
if (value === null) throw new Error("useI18n must be used inside an <I18nProvider>.");
|
|
120
|
+
return value;
|
|
121
|
+
}
|
|
122
|
+
var BORDER_RADIUS = 8;
|
|
123
|
+
var PADDING_H = 9;
|
|
124
|
+
var PADDING_V = 5;
|
|
125
|
+
var FONT_SIZE = 12;
|
|
126
|
+
var GAP = 2;
|
|
127
|
+
var MIN_TARGET = 44;
|
|
128
|
+
var styles = StyleSheet.create({
|
|
129
|
+
row: { flexDirection: "row", alignItems: "center", gap: GAP },
|
|
130
|
+
option: {
|
|
131
|
+
paddingHorizontal: PADDING_H,
|
|
132
|
+
paddingVertical: PADDING_V,
|
|
133
|
+
borderRadius: BORDER_RADIUS,
|
|
134
|
+
minWidth: MIN_TARGET,
|
|
135
|
+
minHeight: MIN_TARGET,
|
|
136
|
+
alignItems: "center",
|
|
137
|
+
justifyContent: "center"
|
|
138
|
+
},
|
|
139
|
+
label: { fontSize: FONT_SIZE, fontWeight: "600" }
|
|
140
|
+
});
|
|
141
|
+
function LanguageSwitcher({
|
|
142
|
+
colors,
|
|
143
|
+
accessibilityLabel = "Language",
|
|
144
|
+
testID = "language-switcher"
|
|
145
|
+
}) {
|
|
146
|
+
const { locale, setLocale, locales } = useI18n();
|
|
147
|
+
const select = useCallback((code) => () => setLocale(code), [setLocale]);
|
|
148
|
+
return /* @__PURE__ */ jsx(View, { accessibilityRole: "radiogroup", "aria-label": accessibilityLabel, style: styles.row, testID, children: locales.map((option) => {
|
|
149
|
+
const isActive = option.code === locale;
|
|
150
|
+
return /* @__PURE__ */ jsx(
|
|
151
|
+
Pressable,
|
|
152
|
+
{
|
|
153
|
+
accessibilityHint: `Show the interface in ${option.label}`,
|
|
154
|
+
accessibilityLabel: option.label,
|
|
155
|
+
accessibilityRole: "radio",
|
|
156
|
+
accessibilityState: { selected: isActive },
|
|
157
|
+
"aria-checked": isActive,
|
|
158
|
+
style: ({ hovered }) => [
|
|
159
|
+
styles.option,
|
|
160
|
+
isActive ? { backgroundColor: colors.activeBackground } : hovered && colors.hoverBackground ? { backgroundColor: colors.hoverBackground } : null
|
|
161
|
+
],
|
|
162
|
+
testID: `${testID}-${option.code}`,
|
|
163
|
+
onPress: select(option.code),
|
|
164
|
+
children: /* @__PURE__ */ jsx(Text, { style: [styles.label, { color: isActive ? colors.activeText : colors.text }], children: option.label })
|
|
165
|
+
},
|
|
166
|
+
option.code
|
|
167
|
+
);
|
|
168
|
+
}) });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export { DEFAULT_FALLBACK_LOCALE, DEFAULT_STORAGE_KEY, I18nProvider, LanguageSwitcher, applyDocumentLocale, browserLanguages, createTranslator, interpolateNamed, interpolatePositional, isSupported, lookup, primarySubtag, readStoredLocale, resolveInitialLocale, useI18n, writeStoredLocale };
|
|
172
|
+
//# sourceMappingURL=index.mjs.map
|
|
173
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +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,QAA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U,QAAA,EAAS;AAAA,QACzC,cAAA,EAAc,QAAA;AAAA,QACd,KAAA,EAAO,CAAC,EAAE,OAAA,EAAQ,KAAsB;AAAA,UACtC,MAAA,CAAO,MAAA;AAAA,UACP,QAAA,GACI,EAAE,eAAA,EAAiB,MAAA,CAAO,gBAAA,EAAiB,GAC3C,OAAA,IAAW,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,0BAAAA,GAAAA,CAAC,IAAA,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.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"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dloizides/i18n",
|
|
3
|
+
"version": "1.0.1",
|
|
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
|
+
"keywords": [
|
|
6
|
+
"react",
|
|
7
|
+
"react-native",
|
|
8
|
+
"react-native-web",
|
|
9
|
+
"i18n",
|
|
10
|
+
"internationalization",
|
|
11
|
+
"localization",
|
|
12
|
+
"translate",
|
|
13
|
+
"dloizides"
|
|
14
|
+
],
|
|
15
|
+
"author": "dloizides",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/openmindednewby/i18n.git"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/openmindednewby/i18n#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/openmindednewby/i18n/issues"
|
|
24
|
+
},
|
|
25
|
+
"main": "./dist/index.js",
|
|
26
|
+
"module": "./dist/index.mjs",
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": {
|
|
30
|
+
"react-native": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"default": "./dist/index.js"
|
|
33
|
+
},
|
|
34
|
+
"browser": {
|
|
35
|
+
"types": "./dist/index.d.ts",
|
|
36
|
+
"default": "./dist/index.js"
|
|
37
|
+
},
|
|
38
|
+
"require": {
|
|
39
|
+
"types": "./dist/index.d.ts",
|
|
40
|
+
"default": "./dist/index.js"
|
|
41
|
+
},
|
|
42
|
+
"import": {
|
|
43
|
+
"types": "./dist/index.d.mts",
|
|
44
|
+
"default": "./dist/index.mjs"
|
|
45
|
+
},
|
|
46
|
+
"default": {
|
|
47
|
+
"types": "./dist/index.d.ts",
|
|
48
|
+
"default": "./dist/index.js"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist",
|
|
54
|
+
"README.md",
|
|
55
|
+
"CHANGELOG.md"
|
|
56
|
+
],
|
|
57
|
+
"sideEffects": false,
|
|
58
|
+
"engines": {
|
|
59
|
+
"node": ">=18.0.0"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"build": "rimraf dist && tsup",
|
|
63
|
+
"build:watch": "tsup --watch",
|
|
64
|
+
"test": "jest",
|
|
65
|
+
"test:watch": "jest --watch",
|
|
66
|
+
"test:coverage": "jest --coverage",
|
|
67
|
+
"lint": "eslint src --ext .ts,.tsx",
|
|
68
|
+
"lint:fix": "eslint src --ext .ts,.tsx --fix",
|
|
69
|
+
"typecheck": "tsc --noEmit",
|
|
70
|
+
"clean": "rimraf dist",
|
|
71
|
+
"security:audit": "npm audit --audit-level=high",
|
|
72
|
+
"deps:outdated": "npm outdated || exit 0",
|
|
73
|
+
"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\"",
|
|
75
|
+
"deps:health": "npm run deps:outdated && npm run deps:unused",
|
|
76
|
+
"prepublishOnly": "npm run clean && npm run build && npm run test",
|
|
77
|
+
"version": "npm run build"
|
|
78
|
+
},
|
|
79
|
+
"peerDependencies": {
|
|
80
|
+
"react": ">=18.0.0",
|
|
81
|
+
"react-native": ">=0.74.0"
|
|
82
|
+
},
|
|
83
|
+
"devDependencies": {
|
|
84
|
+
"@testing-library/dom": "^10.4.0",
|
|
85
|
+
"@testing-library/jest-dom": "^6.6.3",
|
|
86
|
+
"@testing-library/react": "^16.1.0",
|
|
87
|
+
"@types/jest": "^29.5.0",
|
|
88
|
+
"@types/node": "^20.19.32",
|
|
89
|
+
"@types/react": "^19.0.0",
|
|
90
|
+
"@types/react-dom": "^19.0.0",
|
|
91
|
+
"@typescript-eslint/eslint-plugin": "^7.0.0",
|
|
92
|
+
"@typescript-eslint/parser": "^7.0.0",
|
|
93
|
+
"eslint": "^8.57.0",
|
|
94
|
+
"eslint-plugin-react": "^7.34.0",
|
|
95
|
+
"eslint-plugin-react-hooks": "^4.6.0",
|
|
96
|
+
"jest": "^29.7.0",
|
|
97
|
+
"jest-environment-jsdom": "^29.7.0",
|
|
98
|
+
"react": "^19.2.4",
|
|
99
|
+
"react-dom": "^19.2.4",
|
|
100
|
+
"react-native": "0.81.5",
|
|
101
|
+
"react-native-web": "^0.21.0",
|
|
102
|
+
"rimraf": "^5.0.0",
|
|
103
|
+
"ts-jest": "^29.1.0",
|
|
104
|
+
"tsup": "^8.0.0",
|
|
105
|
+
"typescript": "^5.4.0"
|
|
106
|
+
}
|
|
107
|
+
}
|