@object-ui/i18n 17.2.0 → 17.5.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 +1817 -1
- package/README.md +26 -13
- package/dist/index.d.ts +3 -1
- package/dist/index.js +14 -1
- package/dist/locales/ar.d.ts +550 -107
- package/dist/locales/ar.js +646 -156
- package/dist/locales/de.d.ts +550 -107
- package/dist/locales/de.js +661 -178
- package/dist/locales/en.d.ts +586 -143
- package/dist/locales/en.js +851 -143
- package/dist/locales/es.d.ts +550 -107
- package/dist/locales/es.js +647 -160
- package/dist/locales/fr.d.ts +550 -107
- package/dist/locales/fr.js +640 -155
- package/dist/locales/index.d.ts +5587 -1157
- package/dist/locales/ja.d.ts +550 -107
- package/dist/locales/ja.js +632 -149
- package/dist/locales/ko.d.ts +550 -107
- package/dist/locales/ko.js +638 -156
- package/dist/locales/pt.d.ts +550 -107
- package/dist/locales/pt.js +639 -157
- package/dist/locales/ru.d.ts +550 -107
- package/dist/locales/ru.js +650 -156
- package/dist/locales/zh.d.ts +588 -145
- package/dist/locales/zh.js +629 -145
- package/dist/pickLocalized.d.ts +21 -0
- package/dist/pickLocalized.js +40 -7
- package/dist/provider.d.ts +125 -1
- package/dist/provider.js +380 -4
- package/dist/useDisplayLocale.d.ts +49 -0
- package/dist/useDisplayLocale.js +55 -0
- package/dist/useObjectLabel.d.ts +8 -2
- package/dist/useObjectLabel.js +28 -8
- package/dist/useSafeTranslation.js +67 -3
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +1 -0
- package/dist/utils/number-display.d.ts +32 -0
- package/dist/utils/number-display.js +32 -0
- package/dist/utils/spec-formatters.d.ts +39 -13
- package/dist/utils/spec-formatters.js +3 -3
- package/package.json +5 -4
package/dist/provider.js
CHANGED
|
@@ -6,6 +6,282 @@
|
|
|
6
6
|
import React, { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
|
7
7
|
import { I18nextProvider, useTranslation } from 'react-i18next';
|
|
8
8
|
import { createI18n, getDirection } from './i18n';
|
|
9
|
+
import { builtInLocales } from './locales/index';
|
|
10
|
+
/**
|
|
11
|
+
* `localStorage` key holding the user's explicit language choice.
|
|
12
|
+
*
|
|
13
|
+
* Follows the console's existing preference-key convention
|
|
14
|
+
* (`objectui-favorites`, `objectui-recent-items`), and sits beside the theme
|
|
15
|
+
* preference the same avatar menu writes — a language switch is a preference,
|
|
16
|
+
* not ephemeral UI state, so it belongs in storage (AGENTS.md §5 #8).
|
|
17
|
+
*
|
|
18
|
+
* Exported so an app that builds its own i18next instance (and therefore owns
|
|
19
|
+
* its bootstrap language — see {@link I18nProviderProps.instance}) can honour
|
|
20
|
+
* the same preference, and so a sign-out flow can clear it.
|
|
21
|
+
*/
|
|
22
|
+
export const LOCALE_STORAGE_KEY = 'objectui-locale';
|
|
23
|
+
/**
|
|
24
|
+
* Read the persisted language choice, or `null` when nothing is stored.
|
|
25
|
+
*
|
|
26
|
+
* Defensive by design: `localStorage` does not exist under SSR and *throws* on
|
|
27
|
+
* access in Safari private mode / partitioned iframes. A language preference is
|
|
28
|
+
* never worth taking the app down for, so every failure degrades to "nothing
|
|
29
|
+
* stored".
|
|
30
|
+
*/
|
|
31
|
+
export function readStoredLanguage() {
|
|
32
|
+
if (typeof window === 'undefined')
|
|
33
|
+
return null;
|
|
34
|
+
try {
|
|
35
|
+
return window.localStorage.getItem(LOCALE_STORAGE_KEY);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function writeStoredLanguage(lang) {
|
|
42
|
+
if (typeof window === 'undefined')
|
|
43
|
+
return;
|
|
44
|
+
try {
|
|
45
|
+
window.localStorage.setItem(LOCALE_STORAGE_KEY, lang);
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
// Storage blocked or full — the switch still applies for this session.
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function clearStoredLanguage() {
|
|
52
|
+
if (typeof window === 'undefined')
|
|
53
|
+
return;
|
|
54
|
+
try {
|
|
55
|
+
window.localStorage.removeItem(LOCALE_STORAGE_KEY);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
// Nothing readable means nothing to purge.
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* `localStorage` key caching the TENANT's server-side locale — a *seed*, not a
|
|
63
|
+
* choice (objectui#4035).
|
|
64
|
+
*
|
|
65
|
+
* Deliberately a separate slot from {@link LOCALE_STORAGE_KEY}, and that
|
|
66
|
+
* separation is the whole point rather than a tidiness preference. The two
|
|
67
|
+
* values have different provenance and therefore different rights:
|
|
68
|
+
*
|
|
69
|
+
* - {@link LOCALE_STORAGE_KEY} is what the *user* picked. It outranks
|
|
70
|
+
* everything and must survive a tenant reconfiguration.
|
|
71
|
+
* - This slot is what the *admin* configured, cached so the next boot can apply
|
|
72
|
+
* it synchronously. It outranks only the environment (browser language).
|
|
73
|
+
*
|
|
74
|
+
* Writing the server seed into the explicit-choice slot would erase that
|
|
75
|
+
* difference permanently: the seed would then be indistinguishable from a
|
|
76
|
+
* deliberate user choice, so it would (a) outrank a later tenant change and pin
|
|
77
|
+
* the device to a stale locale forever, and (b) suppress browser detection for
|
|
78
|
+
* a user who never expressed a preference. Only a real switch promotes a
|
|
79
|
+
* language to the explicit slot — see the `languageChanged` choke point.
|
|
80
|
+
*/
|
|
81
|
+
export const LOCALE_SEED_STORAGE_KEY = 'objectui-locale-seed';
|
|
82
|
+
/**
|
|
83
|
+
* Read the cached tenant locale seed, or `null` when nothing is cached.
|
|
84
|
+
*
|
|
85
|
+
* Same defensive posture as {@link readStoredLanguage}: `localStorage` is
|
|
86
|
+
* absent under SSR and *throws* in Safari private mode / partitioned iframes,
|
|
87
|
+
* and a language seed is never worth taking the app down for.
|
|
88
|
+
*/
|
|
89
|
+
export function readCachedLanguageSeed() {
|
|
90
|
+
if (typeof window === 'undefined')
|
|
91
|
+
return null;
|
|
92
|
+
try {
|
|
93
|
+
return window.localStorage.getItem(LOCALE_SEED_STORAGE_KEY);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Cache the tenant locale the server just answered with — the "revalidate" half
|
|
101
|
+
* of the stale-while-revalidate contract (objectstack#5419, ruling point 2).
|
|
102
|
+
*
|
|
103
|
+
* Call this with whatever `/auth/me/localization` actually returned for an
|
|
104
|
+
* authenticated caller. A `null`/`undefined` locale CLEARS the cache rather
|
|
105
|
+
* than leaving the old value: a tenant that unsets its locale must reach
|
|
106
|
+
* choice-less devices on their next boot, and "keep the last good seed forever"
|
|
107
|
+
* is precisely the being-pinned-by-a-stale-seed failure the ruling forbids.
|
|
108
|
+
*
|
|
109
|
+
* A *failed* fetch must simply not call this — the cache is then left intact,
|
|
110
|
+
* which is the correct stale-while-revalidate behaviour when revalidation
|
|
111
|
+
* cannot complete.
|
|
112
|
+
*/
|
|
113
|
+
export function cacheLanguageSeed(locale) {
|
|
114
|
+
if (typeof window === 'undefined')
|
|
115
|
+
return;
|
|
116
|
+
try {
|
|
117
|
+
if (typeof locale === 'string' && locale.length > 0) {
|
|
118
|
+
window.localStorage.setItem(LOCALE_SEED_STORAGE_KEY, locale);
|
|
119
|
+
}
|
|
120
|
+
else {
|
|
121
|
+
window.localStorage.removeItem(LOCALE_SEED_STORAGE_KEY);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
// Storage blocked or full — this boot simply goes unseeded.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Languages `createI18n(config)` will know about *synchronously*: the built-in
|
|
130
|
+
* packs plus any extra `config.resources`.
|
|
131
|
+
*
|
|
132
|
+
* `hasOwnProperty` rather than `in`: a junk stored value like `constructor`
|
|
133
|
+
* would pass an `in` check against the locale map's prototype.
|
|
134
|
+
*/
|
|
135
|
+
function isStaticallyKnownLanguage(lang, config) {
|
|
136
|
+
const own = Object.prototype.hasOwnProperty;
|
|
137
|
+
return own.call(builtInLocales, lang) || Boolean(config?.resources && own.call(config.resources, lang));
|
|
138
|
+
}
|
|
139
|
+
/** The built-in packs' codes, as a stable identity for consumers' dep arrays. */
|
|
140
|
+
const BUILT_IN_LANGUAGE_CODES = Object.freeze(Object.keys(builtInLocales));
|
|
141
|
+
/**
|
|
142
|
+
* Every language this renderer can produce *without asking the app*: the
|
|
143
|
+
* built-in packs plus `config.resources`.
|
|
144
|
+
*
|
|
145
|
+
* This is the offline/no-backend answer — the set the switcher offers when
|
|
146
|
+
* there is no `loadLocales` wiring, or when the app's locale endpoint cannot
|
|
147
|
+
* be reached (objectui#4039).
|
|
148
|
+
*/
|
|
149
|
+
function resolvableLanguages(config) {
|
|
150
|
+
const extra = Object.keys(config?.resources ?? {}).filter((code) => !BUILT_IN_LANGUAGE_CODES.includes(code));
|
|
151
|
+
return [...BUILT_IN_LANGUAGE_CODES, ...extra];
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Whether `tag` is a well-formed BCP-47 language tag.
|
|
155
|
+
*
|
|
156
|
+
* `Intl.getCanonicalLocales` is the standard's own parser, so this rejects
|
|
157
|
+
* exactly what a locale code cannot be — `constructor`, `__proto__`, `en_US`,
|
|
158
|
+
* `''` all throw `RangeError` — while accepting codes no pack exists for yet
|
|
159
|
+
* (`th`, `pt-BR`). Guarded for runtimes that ship no `Intl`: a language
|
|
160
|
+
* preference is never worth taking the app down for.
|
|
161
|
+
*/
|
|
162
|
+
function isWellFormedLanguageTag(tag) {
|
|
163
|
+
if (typeof Intl === 'undefined' || typeof Intl.getCanonicalLocales !== 'function') {
|
|
164
|
+
return /^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/.test(tag);
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
return Intl.getCanonicalLocales(tag).length === 1;
|
|
168
|
+
}
|
|
169
|
+
catch {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Whether this provider can end up rendering `lang` at all.
|
|
175
|
+
*
|
|
176
|
+
* Wider than {@link isStaticallyKnownLanguage} by exactly one case: when a
|
|
177
|
+
* dynamic {@link I18nProviderProps.loadLanguage} loader is wired, that loader
|
|
178
|
+
* *is* the mechanism that produces app-shipped locales, and nothing can
|
|
179
|
+
* enumerate what it will answer for synchronously — the app's pack for `th`
|
|
180
|
+
* lives behind `GET /api/v1/i18n/translations/th`, not in `config.resources`.
|
|
181
|
+
*
|
|
182
|
+
* This is the lockstep half of objectui#4039. The switcher now offers the
|
|
183
|
+
* app's own locales, so the restore validation had to grow with it or a
|
|
184
|
+
* user-picked app locale would be purged on the next reload — the exact bug
|
|
185
|
+
* objectstack#5418 predicted this fix would otherwise mint. The bound stays
|
|
186
|
+
* honest rather than absent: only well-formed tags qualify, and the app's own
|
|
187
|
+
* locale list adjudicates the choice for real once it lands (see the
|
|
188
|
+
* `provisional` self-heal in {@link I18nProvider}).
|
|
189
|
+
*/
|
|
190
|
+
function canResolveLanguage(lang, config, hasLoader = false) {
|
|
191
|
+
if (isStaticallyKnownLanguage(lang, config))
|
|
192
|
+
return true;
|
|
193
|
+
return hasLoader && isWellFormedLanguageTag(lang);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Adjudicate a tenant locale seed into a language this renderer can actually
|
|
197
|
+
* boot in, or `null` to fall through to the next tier (objectui#4035).
|
|
198
|
+
*
|
|
199
|
+
* {@link canResolveLanguage} is the verdict — the same predicate the language
|
|
200
|
+
* menu uses, deliberately not a second "do we have this locale" check
|
|
201
|
+
* (objectstack#5418 / objectui#4039). Two things are layered on top of it, both
|
|
202
|
+
* of which are about *which question to ask it*, not about second-guessing the
|
|
203
|
+
* answer:
|
|
204
|
+
*
|
|
205
|
+
* **1. Region subtags are normalised away as a fallback.** A tenant locale is a
|
|
206
|
+
* full BCP-47 tag — the platform answers `zh-CN`, not `zh` (see
|
|
207
|
+
* `LocalizationFetchProvider`'s fixtures) — while the packs are keyed by base
|
|
208
|
+
* language. Asking only about `zh-CN` would reject the single most common
|
|
209
|
+
* tenant configuration there is. The exact tag is tried first so a genuine
|
|
210
|
+
* `pt-BR` pack still wins over `pt`; this mirrors `createI18n`'s own browser
|
|
211
|
+
* detection (`navigator.language.split('-')[0]`) and `pickLocalized`'s
|
|
212
|
+
* documented exact-then-base order, so it is this codebase's existing
|
|
213
|
+
* convention rather than a new rule.
|
|
214
|
+
*
|
|
215
|
+
* **2. The seed does NOT get the dynamic loader's credit** (`hasLoader` is left
|
|
216
|
+
* at its default `false`). That credit exists for a *user-picked* value: the
|
|
217
|
+
* user chose it from a menu built out of the app's real locale list, and a
|
|
218
|
+
* stored choice that turns out unshippable is adjudicated afterwards by the
|
|
219
|
+
* `provisional` self-heal. A tenant seed has neither property — it is an
|
|
220
|
+
* arbitrary admin-authored string that passed through no menu, and there is no
|
|
221
|
+
* self-heal behind it. Extending the credit would mean booting into a locale we
|
|
222
|
+
* cannot confirm we ship and then retracting it, i.e. manufacturing exactly the
|
|
223
|
+
* flash that ruling point 3 bounds, on the very first-visit path it bounds it
|
|
224
|
+
* on. Falling through instead is what ruling point 4 asks for, and it is
|
|
225
|
+
* self-correcting in one step: the user switches once, and that switch is a
|
|
226
|
+
* real explicit choice which outranks the seed from then on.
|
|
227
|
+
*/
|
|
228
|
+
function resolveSeedLanguage(seed, config) {
|
|
229
|
+
if (canResolveLanguage(seed, config))
|
|
230
|
+
return seed;
|
|
231
|
+
const base = seed.split('-')[0];
|
|
232
|
+
if (base && base !== seed && canResolveLanguage(base, config))
|
|
233
|
+
return base;
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
/**
|
|
237
|
+
* The tenant tier: a cached server seed, applied only when the user has
|
|
238
|
+
* expressed no choice of their own (objectui#4035).
|
|
239
|
+
*
|
|
240
|
+
* Returns the bootstrap resolution for the seed, or `null` when there is no
|
|
241
|
+
* usable seed and the caller should fall through to browser detection.
|
|
242
|
+
*
|
|
243
|
+
* `provisional` is deliberately always `null` here: that flag marks a value
|
|
244
|
+
* accepted on the loader's optimistic credit so the app's locale list can
|
|
245
|
+
* adjudicate it later, and {@link resolveSeedLanguage} never extends that
|
|
246
|
+
* credit — a seed is either resolvable right now or it falls through.
|
|
247
|
+
*/
|
|
248
|
+
function resolveSeedBootstrap(config) {
|
|
249
|
+
const seed = readCachedLanguageSeed();
|
|
250
|
+
if (!seed)
|
|
251
|
+
return null;
|
|
252
|
+
const resolved = resolveSeedLanguage(seed, config);
|
|
253
|
+
if (!resolved)
|
|
254
|
+
return null;
|
|
255
|
+
return {
|
|
256
|
+
// `detectBrowserLanguage: false` is what makes the tenant tier outrank the
|
|
257
|
+
// environment tier. The admin's deliberate configuration beats the
|
|
258
|
+
// browser's incidental one — ruling point 1.
|
|
259
|
+
config: { ...config, defaultLanguage: resolved, detectBrowserLanguage: false },
|
|
260
|
+
provisional: null,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
function resolveBootstrapConfig(config, persist, hasLoader) {
|
|
264
|
+
// `persistLanguage: false` surfaces (previews, demos, screenshot harnesses)
|
|
265
|
+
// must stay on a fixed language regardless of what is on this origin — that
|
|
266
|
+
// covers the tenant seed too, not just the user's choice.
|
|
267
|
+
if (!persist)
|
|
268
|
+
return { config, provisional: null };
|
|
269
|
+
const stored = readStoredLanguage();
|
|
270
|
+
// No explicit choice at all → the tenant seed gets its turn.
|
|
271
|
+
if (!stored)
|
|
272
|
+
return resolveSeedBootstrap(config) ?? { config, provisional: null };
|
|
273
|
+
if (!canResolveLanguage(stored, config, hasLoader)) {
|
|
274
|
+
clearStoredLanguage();
|
|
275
|
+
// A purged choice is no choice, so this falls to the same tenant tier —
|
|
276
|
+
// otherwise dropping one unshippable stored value would skip the seed and
|
|
277
|
+
// land straight on the browser language.
|
|
278
|
+
return resolveSeedBootstrap(config) ?? { config, provisional: null };
|
|
279
|
+
}
|
|
280
|
+
return {
|
|
281
|
+
config: { ...config, defaultLanguage: stored, detectBrowserLanguage: false },
|
|
282
|
+
provisional: isStaticallyKnownLanguage(stored, config) ? null : stored,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
9
285
|
const ObjectI18nContext = createContext(null);
|
|
10
286
|
/**
|
|
11
287
|
* I18nProvider - Wraps your app with i18n support
|
|
@@ -17,8 +293,19 @@ const ObjectI18nContext = createContext(null);
|
|
|
17
293
|
* </I18nProvider>
|
|
18
294
|
* ```
|
|
19
295
|
*/
|
|
20
|
-
export function I18nProvider({ config, instance: externalInstance, loadLanguage, children }) {
|
|
21
|
-
|
|
296
|
+
export function I18nProvider({ config, instance: externalInstance, loadLanguage, loadLocales, persistLanguage = true, children, }) {
|
|
297
|
+
// A boolean, not `loadLanguage` itself: an inline arrow would change identity
|
|
298
|
+
// every render and rebuild the i18next instance (and with it the language)
|
|
299
|
+
// on each one. What the bootstrap needs to know is only whether a loader
|
|
300
|
+
// exists at all.
|
|
301
|
+
const hasLoader = Boolean(loadLanguage);
|
|
302
|
+
const bootstrap = useMemo(() => {
|
|
303
|
+
if (externalInstance)
|
|
304
|
+
return { instance: externalInstance, provisional: null };
|
|
305
|
+
const resolved = resolveBootstrapConfig(config, persistLanguage, hasLoader);
|
|
306
|
+
return { instance: createI18n(resolved.config), provisional: resolved.provisional };
|
|
307
|
+
}, [externalInstance, config, persistLanguage, hasLoader]);
|
|
308
|
+
const i18nInstance = bootstrap.instance;
|
|
22
309
|
const [language, setLanguage] = useState(i18nInstance.language || 'en');
|
|
23
310
|
const direction = getDirection(language);
|
|
24
311
|
// Track which languages have had app-specific translations loaded
|
|
@@ -27,6 +314,14 @@ export function I18nProvider({ config, instance: externalInstance, loadLanguage,
|
|
|
27
314
|
useEffect(() => {
|
|
28
315
|
const handleLanguageChanged = (lng) => {
|
|
29
316
|
setLanguage(lng);
|
|
317
|
+
// Remember the choice. This is the single choke point every switch runs
|
|
318
|
+
// through — i18next fires `languageChanged` for the context's
|
|
319
|
+
// `changeLanguage` and for a direct `i18n.changeLanguage()` alike — so no
|
|
320
|
+
// switcher can be wired in a way that silently forgets the preference.
|
|
321
|
+
// Bootstrap does NOT fire this event, so restoring a stored language
|
|
322
|
+
// never re-writes it.
|
|
323
|
+
if (persistLanguage)
|
|
324
|
+
writeStoredLanguage(lng);
|
|
30
325
|
// Update document direction for RTL support
|
|
31
326
|
if (typeof document !== 'undefined') {
|
|
32
327
|
document.documentElement.dir = getDirection(lng);
|
|
@@ -49,7 +344,7 @@ export function I18nProvider({ config, instance: externalInstance, loadLanguage,
|
|
|
49
344
|
return () => {
|
|
50
345
|
i18nInstance.off('languageChanged', handleLanguageChanged);
|
|
51
346
|
};
|
|
52
|
-
}, [i18nInstance]);
|
|
347
|
+
}, [i18nInstance, persistLanguage]);
|
|
53
348
|
// Load app-specific translations for the initial language on mount
|
|
54
349
|
useEffect(() => {
|
|
55
350
|
if (!loadLanguage)
|
|
@@ -70,6 +365,79 @@ export function I18nProvider({ config, instance: externalInstance, loadLanguage,
|
|
|
70
365
|
console.warn(`[i18n] Failed to load app translations for '${currentLang}':`, err);
|
|
71
366
|
});
|
|
72
367
|
}, [i18nInstance, loadLanguage]);
|
|
368
|
+
// The app's own locale list (objectui#4039). `null` = not answered yet; `[]`
|
|
369
|
+
// = asked and got nothing usable, which is "I don't know", not "I ship no
|
|
370
|
+
// locales" — both degrade to the offline fallback below.
|
|
371
|
+
const [appLocales, setAppLocales] = useState(null);
|
|
372
|
+
// Asked exactly once per provider, guarded by a ref — the same shape as the
|
|
373
|
+
// `loadedAppLangs` guard on `loadLanguage` above, and for two reasons at
|
|
374
|
+
// once. An inline `loadLocales={() => …}` changes identity every render, so
|
|
375
|
+
// without the guard the answer would set state, the re-render would mint a
|
|
376
|
+
// new arrow, and the new arrow would re-run the effect: a fetch loop. And
|
|
377
|
+
// StrictMode's double-invoked effect must not fire a second request.
|
|
378
|
+
//
|
|
379
|
+
// Deliberately no `cancelled` flag: under StrictMode the cleanup would
|
|
380
|
+
// cancel the only in-flight request while the re-run declines to start
|
|
381
|
+
// another, leaving the list permanently unanswered and the switcher
|
|
382
|
+
// permanently blank. Settling state after unmount is a no-op in React 18 —
|
|
383
|
+
// which is exactly why the `loadLanguage` effect above does the same.
|
|
384
|
+
const hasLocaleLoader = Boolean(loadLocales);
|
|
385
|
+
const askedForLocales = useRef(false);
|
|
386
|
+
useEffect(() => {
|
|
387
|
+
if (!loadLocales || askedForLocales.current)
|
|
388
|
+
return;
|
|
389
|
+
askedForLocales.current = true;
|
|
390
|
+
loadLocales()
|
|
391
|
+
.then((codes) => setAppLocales(Array.isArray(codes) ? codes : []))
|
|
392
|
+
.catch((err) => {
|
|
393
|
+
// A language menu is not worth an unhandled rejection: fall back to the
|
|
394
|
+
// locales this renderer can produce on its own.
|
|
395
|
+
setAppLocales([]);
|
|
396
|
+
console.warn('[i18n] Failed to load the app locale list:', err);
|
|
397
|
+
});
|
|
398
|
+
}, [loadLocales]);
|
|
399
|
+
const offerableLanguages = useMemo(() => {
|
|
400
|
+
const fallback = resolvableLanguages(config);
|
|
401
|
+
// No wiring at all: the built-in packs are the whole truth, as before.
|
|
402
|
+
if (!hasLocaleLoader)
|
|
403
|
+
return fallback;
|
|
404
|
+
if (appLocales === null)
|
|
405
|
+
return null;
|
|
406
|
+
const offerable = appLocales.filter((code) => canResolveLanguage(code, config, hasLoader));
|
|
407
|
+
// An app that answers with nothing this renderer can produce leaves the
|
|
408
|
+
// user with no way to switch at all — strictly worse than the offline
|
|
409
|
+
// fallback, so the fallback wins.
|
|
410
|
+
return offerable.length > 0 ? offerable : fallback;
|
|
411
|
+
}, [config, hasLocaleLoader, appLocales, hasLoader]);
|
|
412
|
+
// Self-heal: a stored language accepted on the loader's credit alone is
|
|
413
|
+
// adjudicated by the app's real list once it lands. Without this, widening
|
|
414
|
+
// the restore validation would reintroduce exactly what it was written to
|
|
415
|
+
// stop — one stale entry locking the UI to a locale with no translations.
|
|
416
|
+
// Scoped to our own optimism: only the bootstrap language, only while the
|
|
417
|
+
// user has not moved on, and never on an empty/failed answer.
|
|
418
|
+
useEffect(() => {
|
|
419
|
+
const provisional = bootstrap.provisional;
|
|
420
|
+
if (!provisional || !appLocales || appLocales.length === 0)
|
|
421
|
+
return;
|
|
422
|
+
if (appLocales.includes(provisional))
|
|
423
|
+
return;
|
|
424
|
+
if ((i18nInstance.language || '') !== provisional)
|
|
425
|
+
return;
|
|
426
|
+
const revertTo = config?.defaultLanguage || config?.fallbackLanguage || 'en';
|
|
427
|
+
void (async () => {
|
|
428
|
+
await i18nInstance.changeLanguage(revertTo);
|
|
429
|
+
// Purge AFTER the switch, not before: every language change persists
|
|
430
|
+
// itself (that is the point of the single choke point in the
|
|
431
|
+
// `languageChanged` handler), so clearing first would just be overwritten
|
|
432
|
+
// with `revertTo` — recording a preference the user never expressed and
|
|
433
|
+
// suppressing browser detection from then on. Ending with nothing stored
|
|
434
|
+
// is what the bootstrap purge has always left behind.
|
|
435
|
+
// Guarded: if the user picked something in the meantime, that choice is
|
|
436
|
+
// theirs to keep.
|
|
437
|
+
if ((i18nInstance.language || '') === revertTo)
|
|
438
|
+
clearStoredLanguage();
|
|
439
|
+
})();
|
|
440
|
+
}, [bootstrap, appLocales, i18nInstance, config]);
|
|
73
441
|
const contextValue = useMemo(() => ({
|
|
74
442
|
language,
|
|
75
443
|
changeLanguage: async (lang) => {
|
|
@@ -89,7 +457,8 @@ export function I18nProvider({ config, instance: externalInstance, loadLanguage,
|
|
|
89
457
|
},
|
|
90
458
|
direction,
|
|
91
459
|
i18n: i18nInstance,
|
|
92
|
-
|
|
460
|
+
offerableLanguages,
|
|
461
|
+
}), [language, direction, i18nInstance, loadLanguage, offerableLanguages]);
|
|
93
462
|
return React.createElement(ObjectI18nContext.Provider, { value: contextValue }, React.createElement(I18nextProvider, { i18n: i18nInstance }, children));
|
|
94
463
|
}
|
|
95
464
|
/**
|
|
@@ -117,6 +486,13 @@ export function useObjectTranslation(ns) {
|
|
|
117
486
|
direction: context?.direction || 'ltr',
|
|
118
487
|
/** The underlying i18next instance */
|
|
119
488
|
i18n,
|
|
489
|
+
/**
|
|
490
|
+
* Languages a switcher may offer (objectui#4039). `null` while the app's
|
|
491
|
+
* locale list is in flight. Outside a provider there is nobody to ask, so
|
|
492
|
+
* the built-in packs are the answer — not `null`, which would leave a
|
|
493
|
+
* standalone switcher permanently blank.
|
|
494
|
+
*/
|
|
495
|
+
offerableLanguages: context ? context.offerableLanguages : BUILT_IN_LANGUAGE_CODES,
|
|
120
496
|
};
|
|
121
497
|
}
|
|
122
498
|
/**
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ObjectUI
|
|
3
|
+
* Copyright (c) 2024-present ObjectStack Inc.
|
|
4
|
+
*
|
|
5
|
+
* This source code is licensed under the MIT license found in the
|
|
6
|
+
* LICENSE file in the root directory of this source tree.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* `useDisplayLocale` — the BCP-47 tag that field / cell / metric renderers
|
|
10
|
+
* format numbers and other `Intl` values with.
|
|
11
|
+
*
|
|
12
|
+
* This composes the two locale channels this repo already has; it does not add
|
|
13
|
+
* a third. The precedence, highest first:
|
|
14
|
+
*
|
|
15
|
+
* 1. **`useLocalization().locale`** — the tenant's resolved regional default
|
|
16
|
+
* (ADR-0053, served by `GET /api/v1/auth/me/localization`). An org that has
|
|
17
|
+
* explicitly configured a display locale means it, so it outranks the UI
|
|
18
|
+
* language. Frequently `undefined`: the endpoint is
|
|
19
|
+
* cosmetic and non-blocking, so an unconfigured or still-loading tenant
|
|
20
|
+
* simply has no answer here (the state objectui#4033 was measured in — a
|
|
21
|
+
* fresh database, console running `zh-CN`).
|
|
22
|
+
*
|
|
23
|
+
* 2. **`useObjectTranslation().language`** — the ACTIVE UI language, i.e. what
|
|
24
|
+
* the user picked in the language switcher. This is the channel that makes
|
|
25
|
+
* grouping and decimal marks follow the user's language when the tenant has
|
|
26
|
+
* stated no regional preference.
|
|
27
|
+
*
|
|
28
|
+
* 3. **`'en'`** — a concrete last resort rather than `undefined`. `undefined`
|
|
29
|
+
* would hand `Intl` the *machine's* locale, which is invisible in review and
|
|
30
|
+
* non-deterministic in CI; `'en'` at least fails the same way everywhere.
|
|
31
|
+
* Note this is `'en'`, not `'en-US'`: the point of objectui#4033 is that
|
|
32
|
+
* `en-US` is not the world's default. In practice step 2 already answers,
|
|
33
|
+
* since `useObjectTranslation` falls back to the react-i18next global
|
|
34
|
+
* instance and ultimately reports `'en'` itself.
|
|
35
|
+
*
|
|
36
|
+
* Provider-safe at every step: `useLocalization` returns `{}` outside its
|
|
37
|
+
* provider and `useObjectTranslation` reads an optional context, so a renderer
|
|
38
|
+
* mounted standalone (tests, docs demos) degrades instead of throwing.
|
|
39
|
+
*
|
|
40
|
+
* **This composition is also the whole `'zh'` ↔ BCP-47 story** (objectui#4468).
|
|
41
|
+
* There is no mapping table anywhere and none is needed: the UI language codes
|
|
42
|
+
* this renderer ships (`'zh'`, `'ja'`, `'de'`, …) are already well-formed
|
|
43
|
+
* BCP-47 language subtags, so `Intl` accepts them verbatim. The one thing a
|
|
44
|
+
* caller must not do is reach past this hook for the raw tenant locale and hand
|
|
45
|
+
* `Intl` the `undefined` it gets on an unconfigured workspace — `undefined`
|
|
46
|
+
* means "the MACHINE's locale", which is neither channel. Every date, number
|
|
47
|
+
* and currency renderer goes through here for exactly that reason.
|
|
48
|
+
*/
|
|
49
|
+
export declare function useDisplayLocale(): string;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ObjectUI
|
|
3
|
+
* Copyright (c) 2024-present ObjectStack Inc.
|
|
4
|
+
*
|
|
5
|
+
* This source code is licensed under the MIT license found in the
|
|
6
|
+
* LICENSE file in the root directory of this source tree.
|
|
7
|
+
*/
|
|
8
|
+
import { useLocalization } from './LocalizationContext';
|
|
9
|
+
import { useObjectTranslation } from './provider';
|
|
10
|
+
/**
|
|
11
|
+
* `useDisplayLocale` — the BCP-47 tag that field / cell / metric renderers
|
|
12
|
+
* format numbers and other `Intl` values with.
|
|
13
|
+
*
|
|
14
|
+
* This composes the two locale channels this repo already has; it does not add
|
|
15
|
+
* a third. The precedence, highest first:
|
|
16
|
+
*
|
|
17
|
+
* 1. **`useLocalization().locale`** — the tenant's resolved regional default
|
|
18
|
+
* (ADR-0053, served by `GET /api/v1/auth/me/localization`). An org that has
|
|
19
|
+
* explicitly configured a display locale means it, so it outranks the UI
|
|
20
|
+
* language. Frequently `undefined`: the endpoint is
|
|
21
|
+
* cosmetic and non-blocking, so an unconfigured or still-loading tenant
|
|
22
|
+
* simply has no answer here (the state objectui#4033 was measured in — a
|
|
23
|
+
* fresh database, console running `zh-CN`).
|
|
24
|
+
*
|
|
25
|
+
* 2. **`useObjectTranslation().language`** — the ACTIVE UI language, i.e. what
|
|
26
|
+
* the user picked in the language switcher. This is the channel that makes
|
|
27
|
+
* grouping and decimal marks follow the user's language when the tenant has
|
|
28
|
+
* stated no regional preference.
|
|
29
|
+
*
|
|
30
|
+
* 3. **`'en'`** — a concrete last resort rather than `undefined`. `undefined`
|
|
31
|
+
* would hand `Intl` the *machine's* locale, which is invisible in review and
|
|
32
|
+
* non-deterministic in CI; `'en'` at least fails the same way everywhere.
|
|
33
|
+
* Note this is `'en'`, not `'en-US'`: the point of objectui#4033 is that
|
|
34
|
+
* `en-US` is not the world's default. In practice step 2 already answers,
|
|
35
|
+
* since `useObjectTranslation` falls back to the react-i18next global
|
|
36
|
+
* instance and ultimately reports `'en'` itself.
|
|
37
|
+
*
|
|
38
|
+
* Provider-safe at every step: `useLocalization` returns `{}` outside its
|
|
39
|
+
* provider and `useObjectTranslation` reads an optional context, so a renderer
|
|
40
|
+
* mounted standalone (tests, docs demos) degrades instead of throwing.
|
|
41
|
+
*
|
|
42
|
+
* **This composition is also the whole `'zh'` ↔ BCP-47 story** (objectui#4468).
|
|
43
|
+
* There is no mapping table anywhere and none is needed: the UI language codes
|
|
44
|
+
* this renderer ships (`'zh'`, `'ja'`, `'de'`, …) are already well-formed
|
|
45
|
+
* BCP-47 language subtags, so `Intl` accepts them verbatim. The one thing a
|
|
46
|
+
* caller must not do is reach past this hook for the raw tenant locale and hand
|
|
47
|
+
* `Intl` the `undefined` it gets on an unconfigured workspace — `undefined`
|
|
48
|
+
* means "the MACHINE's locale", which is neither channel. Every date, number
|
|
49
|
+
* and currency renderer goes through here for exactly that reason.
|
|
50
|
+
*/
|
|
51
|
+
export function useDisplayLocale() {
|
|
52
|
+
const { locale } = useLocalization();
|
|
53
|
+
const { language } = useObjectTranslation();
|
|
54
|
+
return locale || language || 'en';
|
|
55
|
+
}
|
package/dist/useObjectLabel.d.ts
CHANGED
|
@@ -151,7 +151,10 @@ export declare function useObjectLabel(): {
|
|
|
151
151
|
}) => string;
|
|
152
152
|
/**
|
|
153
153
|
* Resolve translated list-view label.
|
|
154
|
-
* Convention (per @objectstack/spec): `{ns}.objects.{objectName}._views.{viewName}.label
|
|
154
|
+
* Convention (per @objectstack/spec): `{ns}.objects.{objectName}._views.{viewName}.label`,
|
|
155
|
+
* where `{viewName}` is the **bare** view name — pass either the bare name or
|
|
156
|
+
* the qualified runtime id, the object prefix is stripped either way. A key
|
|
157
|
+
* that spells the prefix out does not resolve (see `viewSuffixes`).
|
|
155
158
|
*/
|
|
156
159
|
viewLabel: (objectName: string, viewName: string, fallback: string) => string;
|
|
157
160
|
/**
|
|
@@ -371,7 +374,10 @@ export declare function useSafeFieldLabel(): {
|
|
|
371
374
|
}) => string;
|
|
372
375
|
/**
|
|
373
376
|
* Resolve translated list-view label.
|
|
374
|
-
* Convention (per @objectstack/spec): `{ns}.objects.{objectName}._views.{viewName}.label
|
|
377
|
+
* Convention (per @objectstack/spec): `{ns}.objects.{objectName}._views.{viewName}.label`,
|
|
378
|
+
* where `{viewName}` is the **bare** view name — pass either the bare name or
|
|
379
|
+
* the qualified runtime id, the object prefix is stripped either way. A key
|
|
380
|
+
* that spells the prefix out does not resolve (see `viewSuffixes`).
|
|
375
381
|
*/
|
|
376
382
|
viewLabel: (objectName: string, viewName: string, fallback: string) => string;
|
|
377
383
|
/**
|
package/dist/useObjectLabel.js
CHANGED
|
@@ -188,19 +188,36 @@ export function useObjectLabel() {
|
|
|
188
188
|
/**
|
|
189
189
|
* Build suffix candidates for a list-view scoped key.
|
|
190
190
|
*
|
|
191
|
-
* The runtime uses qualified view ids (`<objectName>.<viewName>`) in URLs
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
191
|
+
* The runtime uses qualified view ids (`<objectName>.<viewName>`) in URLs and
|
|
192
|
+
* metadata records, while translation bundles are keyed by the **bare** view
|
|
193
|
+
* name under `_views` — the runtime view identity's own name, stripped of the
|
|
194
|
+
* object prefix. That single spelling is canonical per the objectstack#5164
|
|
195
|
+
* ruling A (2026-08-06): the i18n extractor asks the view composer for the key
|
|
196
|
+
* (objectstack#6124) and `packages/lint` enforces exactly that spelling
|
|
197
|
+
* (objectstack#6038), so this resolver accepts exactly what those produce.
|
|
198
|
+
*
|
|
199
|
+
* Deliberately NOT a second candidate: the prefixed full name
|
|
200
|
+
* (`_views.<objectName>.<viewName>`). Accepting it made this client more
|
|
201
|
+
* lenient than the server-side resolver, which only ever reads the one key
|
|
202
|
+
* (objectstack#5165) — a bundle authored against the prefixed spelling showed
|
|
203
|
+
* translated labels in the Console while every consumer that does not run a
|
|
204
|
+
* second resolution pass (REST boundary, mobile, plain HTTP, SDUI) still got
|
|
205
|
+
* English. A prefixed key now simply misses, and the label falls back to the
|
|
206
|
+
* metadata default on every surface alike, so the authoring mistake is visible
|
|
207
|
+
* instead of half-hidden. It is caught at authoring time by `os lint`'s
|
|
208
|
+
* `translation-target-unknown`, not papered over here.
|
|
209
|
+
*
|
|
210
|
+
* The object-name candidates (`objects.<ns__obj>` then `objects.<obj>`) are a
|
|
211
|
+
* separate axis and stay: they let bundles written against short object names
|
|
212
|
+
* resolve when the runtime presents fully-qualified ones.
|
|
195
213
|
*/
|
|
196
214
|
const viewSuffixes = (objectName, viewName, tail) => {
|
|
197
215
|
const objectNames = [objectName, stripNamespace(objectName)];
|
|
198
216
|
const matchedPrefix = objectNames
|
|
199
217
|
.map((name) => `${name}.`)
|
|
200
218
|
.find((prefix) => viewName.startsWith(prefix));
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
return viewNames.flatMap((name) => objectSuffixes(objectName, `_views.${name}.${tail}`));
|
|
219
|
+
const bareViewName = matchedPrefix ? viewName.slice(matchedPrefix.length) : viewName;
|
|
220
|
+
return objectSuffixes(objectName, `_views.${bareViewName}.${tail}`);
|
|
204
221
|
};
|
|
205
222
|
return {
|
|
206
223
|
/**
|
|
@@ -309,7 +326,10 @@ export function useObjectLabel() {
|
|
|
309
326
|
reportLabel: (reportDef) => resolve(reportSuffixes(reportDef.name, 'label'), reportDef.label ?? reportDef.name),
|
|
310
327
|
/**
|
|
311
328
|
* Resolve translated list-view label.
|
|
312
|
-
* Convention (per @objectstack/spec): `{ns}.objects.{objectName}._views.{viewName}.label
|
|
329
|
+
* Convention (per @objectstack/spec): `{ns}.objects.{objectName}._views.{viewName}.label`,
|
|
330
|
+
* where `{viewName}` is the **bare** view name — pass either the bare name or
|
|
331
|
+
* the qualified runtime id, the object prefix is stripped either way. A key
|
|
332
|
+
* that spells the prefix out does not resolve (see `viewSuffixes`).
|
|
313
333
|
*/
|
|
314
334
|
viewLabel: (objectName, viewName, fallback) => resolve(viewSuffixes(objectName, viewName, 'label'), fallback),
|
|
315
335
|
/**
|