vite-bundled-i18n 0.2.14 → 0.2.15
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/README.md +15 -3
- package/dist/react/I18nProvider.d.ts +21 -5
- package/dist/react.js +30 -15
- package/dist/react.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -98,8 +98,10 @@ import { I18nProvider } from 'vite-bundled-i18n/react'
|
|
|
98
98
|
import { i18n } from './i18n'
|
|
99
99
|
import App from './App'
|
|
100
100
|
|
|
101
|
+
// Provider blocks rendering until dictionaries are loaded.
|
|
102
|
+
// fallback is shown during loading (null = blank screen).
|
|
101
103
|
createRoot(document.getElementById('root')!).render(
|
|
102
|
-
<I18nProvider instance={i18n}>
|
|
104
|
+
<I18nProvider instance={i18n} fallback={<div>Loading...</div>}>
|
|
103
105
|
<App />
|
|
104
106
|
</I18nProvider>,
|
|
105
107
|
)
|
|
@@ -124,16 +126,26 @@ export function ProductsPage() {
|
|
|
124
126
|
}
|
|
125
127
|
```
|
|
126
128
|
|
|
127
|
-
Use `I18nBoundary` to
|
|
129
|
+
Use `I18nBoundary` to handle per-page scope loading without early returns:
|
|
128
130
|
|
|
129
131
|
```tsx
|
|
130
132
|
import { I18nBoundary } from 'vite-bundled-i18n/react'
|
|
131
133
|
|
|
132
|
-
<I18nBoundary scope="products.index" fallback={<
|
|
134
|
+
<I18nBoundary scope="products.index" fallback={<Skeleton />}>
|
|
133
135
|
<ProductsPage />
|
|
134
136
|
</I18nBoundary>
|
|
135
137
|
```
|
|
136
138
|
|
|
139
|
+
**Navigation lifecycle:** The provider persists across page navigations (Inertia, React Router, Next.js App Router). Dictionaries load once on init. Each page's scope loads on mount via `useI18n(scope)` — only the page content waits, not the layout. Previously visited pages are instant (scope is cached).
|
|
140
|
+
|
|
141
|
+
For small apps, preload all scopes upfront:
|
|
142
|
+
|
|
143
|
+
```tsx
|
|
144
|
+
<I18nProvider instance={i18n} fallback={<Spinner />} preloadScopes={['products.index', 'cart', 'account']}>
|
|
145
|
+
<App />
|
|
146
|
+
</I18nProvider>
|
|
147
|
+
```
|
|
148
|
+
|
|
137
149
|
### Vue
|
|
138
150
|
|
|
139
151
|
```ts
|
|
@@ -3,7 +3,7 @@ import type { I18nInstance, NestedTranslations } from '../core/types';
|
|
|
3
3
|
/**
|
|
4
4
|
* Props for the {@link I18nProvider} component.
|
|
5
5
|
*/
|
|
6
|
-
interface I18nProviderProps {
|
|
6
|
+
export interface I18nProviderProps {
|
|
7
7
|
/** The i18n instance returned by `createI18n()`. */
|
|
8
8
|
instance: I18nInstance;
|
|
9
9
|
/** Child components that will have access to translations. */
|
|
@@ -11,10 +11,26 @@ interface I18nProviderProps {
|
|
|
11
11
|
/**
|
|
12
12
|
* Pre-loaded translations from SSR. When provided, the provider adds these
|
|
13
13
|
* resources to the store immediately and skips dictionary fetching.
|
|
14
|
-
* Format: Record<namespace, NestedTranslations>
|
|
15
|
-
* Example: { shared: { ok: 'OK' }, global: { appName: 'Store' } }
|
|
16
14
|
*/
|
|
17
15
|
serverResources?: Record<string, NestedTranslations>;
|
|
16
|
+
/**
|
|
17
|
+
* Rendered while dictionaries are loading on init. Default: renders children
|
|
18
|
+
* immediately (dictionaries load in background).
|
|
19
|
+
* Set to `null` for blank screen, or `<Spinner />` for a loading indicator.
|
|
20
|
+
* Once dictionaries are loaded, this is never shown again.
|
|
21
|
+
*/
|
|
22
|
+
fallback?: ReactNode;
|
|
23
|
+
/**
|
|
24
|
+
* Scopes to eagerly preload on mount (alongside dictionaries).
|
|
25
|
+
* Use for small apps where you want all translations available immediately,
|
|
26
|
+
* or to prefetch scopes for pages the user is likely to visit.
|
|
27
|
+
*/
|
|
28
|
+
preloadScopes?: string[];
|
|
29
|
+
/**
|
|
30
|
+
* If true, render children before dictionaries finish loading.
|
|
31
|
+
* Dictionary keys will return fallback strings until loaded.
|
|
32
|
+
* Default: false (children wait for dictionaries).
|
|
33
|
+
*/
|
|
34
|
+
eager?: boolean;
|
|
18
35
|
}
|
|
19
|
-
export declare function I18nProvider({ instance, children, serverResources }: I18nProviderProps): import("react/jsx-runtime").JSX.Element;
|
|
20
|
-
export {};
|
|
36
|
+
export declare function I18nProvider({ instance, children, serverResources, fallback, preloadScopes, eager, }: I18nProviderProps): import("react/jsx-runtime").JSX.Element;
|
package/dist/react.js
CHANGED
|
@@ -13,46 +13,61 @@ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
|
13
13
|
var I18nContext = createContext(null);
|
|
14
14
|
//#endregion
|
|
15
15
|
//#region src/react/I18nProvider.tsx
|
|
16
|
-
function I18nProvider({ instance, children, serverResources }) {
|
|
16
|
+
function I18nProvider({ instance, children, serverResources, fallback, preloadScopes, eager = false }) {
|
|
17
17
|
const [hydrated] = useState(() => {
|
|
18
|
-
if (serverResources) return true;
|
|
19
|
-
if (typeof window !== "undefined" && window.__I18N_RESOURCES__) return true;
|
|
20
|
-
return false;
|
|
21
|
-
});
|
|
22
|
-
const [version, setVersion] = useState(() => {
|
|
23
18
|
if (serverResources) {
|
|
24
19
|
const locale = instance.getLocale();
|
|
25
20
|
for (const [namespace, data] of Object.entries(serverResources)) instance.addResources(locale, namespace, data);
|
|
26
|
-
return
|
|
21
|
+
return true;
|
|
27
22
|
}
|
|
28
23
|
const win = typeof window !== "undefined" ? window : void 0;
|
|
29
24
|
if (win?.__I18N_RESOURCES__) {
|
|
30
25
|
const serverData = win.__I18N_RESOURCES__;
|
|
31
26
|
for (const [namespace, data] of Object.entries(serverData.resources)) instance.addResources(serverData.locale, namespace, data);
|
|
32
27
|
delete win.__I18N_RESOURCES__;
|
|
33
|
-
return
|
|
28
|
+
return true;
|
|
34
29
|
}
|
|
35
|
-
return
|
|
30
|
+
return false;
|
|
36
31
|
});
|
|
32
|
+
const [dictsReady, setDictsReady] = useState(() => {
|
|
33
|
+
if (hydrated) return true;
|
|
34
|
+
if (instance.getDictionaryNames().length === 0) return true;
|
|
35
|
+
const locale = instance.getLocale();
|
|
36
|
+
const dictNs = instance.getDictionaryNamespaces();
|
|
37
|
+
return dictNs.length > 0 && dictNs.every((ns) => instance.isNamespaceLoaded(locale, ns));
|
|
38
|
+
});
|
|
39
|
+
const [version, setVersion] = useState(hydrated ? 1 : 0);
|
|
37
40
|
useEffect(() => {
|
|
38
41
|
setGlobalInstance(instance);
|
|
39
42
|
const unsub = instance.onLocaleChange(() => {
|
|
40
43
|
setVersion((v) => v + 1);
|
|
41
44
|
});
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
45
|
+
const locale = instance.getLocale();
|
|
46
|
+
const promises = [];
|
|
47
|
+
if (!hydrated && !dictsReady) {
|
|
48
|
+
if (instance.getDictionaryNames().length > 0) promises.push(instance.loadAllDictionaries(locale));
|
|
49
|
+
}
|
|
50
|
+
if (preloadScopes && preloadScopes.length > 0) {
|
|
51
|
+
for (const scope of preloadScopes) if (!instance.isScopeLoaded(locale, scope)) promises.push(instance.loadScope(locale, scope));
|
|
46
52
|
}
|
|
53
|
+
if (promises.length > 0) Promise.all(promises).then(() => {
|
|
54
|
+
setDictsReady(true);
|
|
55
|
+
setVersion((v) => v + 1);
|
|
56
|
+
});
|
|
47
57
|
return unsub;
|
|
48
|
-
}, [
|
|
58
|
+
}, [
|
|
59
|
+
instance,
|
|
60
|
+
hydrated,
|
|
61
|
+
preloadScopes
|
|
62
|
+
]);
|
|
49
63
|
const contextValue = useMemo(() => ({
|
|
50
64
|
instance,
|
|
51
65
|
version
|
|
52
66
|
}), [instance, version]);
|
|
67
|
+
const showChildren = eager || dictsReady;
|
|
53
68
|
return /* @__PURE__ */ jsx(I18nContext.Provider, {
|
|
54
69
|
value: contextValue,
|
|
55
|
-
children
|
|
70
|
+
children: showChildren ? children : fallback ?? null
|
|
56
71
|
});
|
|
57
72
|
}
|
|
58
73
|
//#endregion
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":[],"sources":["../src/react/context.ts","../src/react/I18nProvider.tsx","../src/react/useI18n.ts","../src/react/DevToolbar.tsx","../src/react/I18nBoundary.tsx"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n","import { useEffect, useState, useMemo, type ReactNode } from 'react';\nimport { I18nContext } from './context';\nimport { setGlobalInstance } from '../core/t';\nimport type { I18nInstance, NestedTranslations } from '../core/types';\n\n/**\n * Props for the {@link I18nProvider} component.\n */\ninterface I18nProviderProps {\n /** The i18n instance returned by `createI18n()`. */\n instance: I18nInstance;\n /** Child components that will have access to translations. */\n children: ReactNode;\n /**\n * Pre-loaded translations from SSR. When provided, the provider adds these\n * resources to the store immediately and skips dictionary fetching.\n * Format: Record<namespace, NestedTranslations>\n * Example: { shared: { ok: 'OK' }, global: { appName: 'Store' } }\n */\n serverResources?: Record<string, NestedTranslations>;\n}\n\n/**\n * React context provider for translations.\n *\n * On mount, it sets the global i18n instance and loads all dictionary\n * bundles (one HTTP request per named dictionary, in declaration order).\n * Re-renders children when dictionaries finish loading and when the\n * locale changes.\n *\n * @example\n * ```tsx\n * import { createI18n } from 'vite-bundled-i18n';\n * import { I18nProvider } from 'vite-bundled-i18n/react';\n *\n * const i18n = createI18n({ ... });\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * </I18nProvider>\n * );\n * }\n * ```\n */\ninterface WindowWithI18n extends Window {\n __I18N_RESOURCES__?: {\n locale: string;\n resources: Record<string, NestedTranslations>;\n };\n}\n\nexport function I18nProvider({ instance, children, serverResources }: I18nProviderProps) {\n const [hydrated] = useState(() => {\n if (serverResources) {\n return true;\n }\n if (typeof window !== 'undefined' && (window as WindowWithI18n).__I18N_RESOURCES__) {\n return true;\n }\n return false;\n });\n\n const [version, setVersion] = useState(() => {\n if (serverResources) {\n const locale = instance.getLocale();\n for (const [namespace, data] of Object.entries(serverResources)) {\n instance.addResources(locale, namespace, data);\n }\n return 1;\n }\n\n // Auto-hydrate from server-injected global\n const win = typeof window !== 'undefined' ? (window as WindowWithI18n) : undefined;\n if (win?.__I18N_RESOURCES__) {\n const serverData = win.__I18N_RESOURCES__;\n for (const [namespace, data] of Object.entries(serverData.resources)) {\n instance.addResources(serverData.locale, namespace, data);\n }\n delete win.__I18N_RESOURCES__;\n return 1;\n }\n\n return 0;\n });\n\n useEffect(() => {\n setGlobalInstance(instance);\n\n const unsub = instance.onLocaleChange(() => {\n setVersion((v) => v + 1);\n });\n\n if (!hydrated) {\n const hasDicts = instance.getDictionaryNames().length > 0;\n if (hasDicts) {\n instance.loadAllDictionaries(instance.getLocale()).then(() => {\n setVersion((v) => v + 1);\n });\n }\n }\n\n return unsub;\n }, [instance, hydrated]);\n\n const contextValue = useMemo(\n () => ({ instance, version }),\n [instance, version],\n );\n\n return (\n <I18nContext.Provider value={contextValue}>\n {children}\n </I18nContext.Provider>\n );\n}\n","import { useContext, useEffect, useState, useMemo } from 'react';\nimport { I18nContext } from './context';\nimport { createTranslations } from '../core/getTranslations';\nimport type { UseI18nResult, ValidScope } from '../core/types';\n\n/**\n * React hook for accessing translations.\n *\n * Can be called with or without a scope:\n *\n * **Without scope** — accesses only dictionary translations (shared, global, etc.).\n * Use this in layout components, navigation, footers, and other app-wide UI.\n *\n * **With scope** — triggers loading of the scope bundle (one HTTP request for all\n * namespaces that page needs). Use this in route/page components.\n *\n * Keys are always fully qualified (e.g., `'products.show.title'`), regardless of scope.\n *\n * @param scope - Optional bundle identifier (e.g., `'products.show'`).\n * Triggers loading of the scope bundle via `/__i18n/{locale}/{scope}.json`.\n * @returns An object with `t` (translation function), `ready` (loading state),\n * and `locale` (current locale code)\n * @throws If called outside of an `I18nProvider`\n *\n * @example\n * ```tsx\n * // Dictionary-only access\n * const { t, ready } = useI18n();\n * t('shared.ok', 'OK');\n *\n * // Bundle + dictionary access\n * const { t, ready } = useI18n('products.show');\n * t('products.show.title', 'Product Details');\n * t('shared.ok', 'OK'); // dictionaries still work\n * ```\n */\nexport function useI18n(scope?: ValidScope): UseI18nResult {\n const ctx = useContext(I18nContext);\n\n if (!ctx) {\n throw new Error(\n 'vite-bundled-i18n: useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider instance={...}>.',\n );\n }\n\n const { instance, version } = ctx;\n const locale = instance.getLocale();\n const [scopeReady, setScopeReady] = useState(() => {\n if (!scope) return true;\n return instance.isScopeLoaded(locale, scope);\n });\n const [loadedScopeKey, setLoadedScopeKey] = useState<string | null>(null);\n\n // Load scope bundle if needed — one HTTP request per scope\n const scopeKey = scope ? `${locale}:${scope}` : null;\n useEffect(() => {\n if (!scopeKey || !scope) return;\n if (scopeKey === loadedScopeKey) return;\n\n let cancelled = false;\n instance.loadScope(locale, scope).then(() => {\n if (!cancelled) {\n setLoadedScopeKey(scopeKey);\n setScopeReady(true);\n }\n });\n\n return () => { cancelled = true; };\n }, [scopeKey, scope, locale, instance, loadedScopeKey]);\n\n // Re-create the translator object whenever locale or loaded resources change.\n const translations = useMemo(\n () => createTranslations(instance, locale),\n // version is not read directly here, but it must participate so the\n // translator object is recreated after dictionary/scope loads.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [instance, locale, version],\n );\n\n return {\n t: translations.t,\n get: translations.get,\n has: translations.has,\n exists: translations.exists,\n tryGet: translations.tryGet,\n require: translations.require,\n translations,\n ready: scopeReady,\n locale,\n };\n}\n","import { useContext, useState } from 'react';\nimport { I18nContext } from './context';\nimport type { KeyUsageEntry } from '../core/types';\n\nconst RESOLUTION_COLORS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: '#4ade80',\n 'fallback-locale': '#facc15',\n 'fallback-string': '#fb923c',\n 'key-as-value': '#f87171',\n};\n\nconst RESOLUTION_LABELS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: 'Primary',\n 'fallback-locale': 'Fallback Locale',\n 'fallback-string': 'Fallback String',\n 'key-as-value': 'Key as Value',\n};\n\n/**\n * Dev-only toolbar overlay that displays translation diagnostics\n * for the current page. Reads key usage data from the i18n instance\n * via {@link I18nContext}.\n *\n * Renders nothing in production or when used outside an `I18nProvider`.\n *\n * @example\n * ```tsx\n * import { DevToolbar } from 'vite-bundled-i18n/react';\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * <DevToolbar />\n * </I18nProvider>\n * );\n * }\n * ```\n */\nexport function DevToolbar() {\n // Skip in production — always render in test (import.meta.env may not exist)\n const isDev =\n typeof import.meta !== 'undefined' && import.meta.env\n ? import.meta.env.DEV\n : true;\n\n const ctx = useContext(I18nContext);\n\n const [open, setOpen] = useState(false);\n\n if (!isDev) return null;\n if (!ctx) return null;\n\n const { instance } = ctx;\n const usage = instance.getKeyUsage();\n const locale = instance.getLocale();\n\n // Deduplicate keys for display — keep the first occurrence\n const uniqueKeys = new Map<string, KeyUsageEntry>();\n for (const entry of usage) {\n if (!uniqueKeys.has(entry.key)) {\n uniqueKeys.set(entry.key, entry);\n }\n }\n\n const groups: Array<{ type: KeyUsageEntry['resolvedFrom']; entries: KeyUsageEntry[] }> = [\n { type: 'primary', entries: [] },\n { type: 'fallback-locale', entries: [] },\n { type: 'fallback-string', entries: [] },\n { type: 'key-as-value', entries: [] },\n ];\n\n for (const entry of uniqueKeys.values()) {\n const group = groups.find((g) => g.type === entry.resolvedFrom);\n if (group) group.entries.push(entry);\n }\n\n const primaryCount = groups[0].entries.length;\n const fallbackCount =\n groups[1].entries.length + groups[2].entries.length;\n const missingCount = groups[3].entries.length;\n const totalKeys = uniqueKeys.size;\n\n return (\n <>\n {/* Toggle button */}\n <button\n data-testid=\"i18n-toolbar-toggle\"\n onClick={() => setOpen((v) => !v)}\n style={{\n position: 'fixed',\n bottom: 16,\n right: 16,\n zIndex: 99999,\n width: 44,\n height: 44,\n borderRadius: 22,\n border: 'none',\n background: missingCount > 0 ? '#dc2626' : '#2563eb',\n color: '#fff',\n fontSize: 14,\n fontWeight: 700,\n cursor: 'pointer',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n boxShadow: '0 2px 8px rgba(0,0,0,0.3)',\n fontFamily: 'system-ui, sans-serif',\n }}\n aria-label={open ? 'Close i18n toolbar' : 'Open i18n toolbar'}\n >\n {totalKeys}\n </button>\n\n {/* Panel */}\n {open && (\n <div\n data-testid=\"i18n-toolbar-panel\"\n style={{\n position: 'fixed',\n bottom: 68,\n right: 16,\n zIndex: 99999,\n width: 380,\n maxHeight: 480,\n background: 'rgba(0, 0, 0, 0.92)',\n color: '#f1f5f9',\n borderRadius: 10,\n boxShadow: '0 4px 24px rgba(0,0,0,0.4)',\n fontFamily: 'system-ui, sans-serif',\n fontSize: 13,\n overflow: 'hidden',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n {/* Header */}\n <div\n style={{\n padding: '12px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n }}\n >\n <span style={{ fontWeight: 600, fontSize: 14 }}>i18n DevToolbar</span>\n <span\n style={{\n background: '#2563eb',\n color: '#fff',\n padding: '2px 10px',\n borderRadius: 12,\n fontSize: 12,\n fontWeight: 600,\n }}\n >\n {locale}\n </span>\n </div>\n\n {/* Summary */}\n <div\n style={{\n padding: '10px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n gap: 16,\n flexWrap: 'wrap',\n fontSize: 12,\n }}\n >\n <span>\n Total: <strong>{totalKeys}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS.primary }}>\n Primary: <strong>{primaryCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['fallback-locale'] }}>\n Fallback: <strong>{fallbackCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['key-as-value'] }}>\n Missing: <strong>{missingCount}</strong>\n </span>\n </div>\n\n {/* Key list */}\n <div style={{ overflowY: 'auto', flex: 1, padding: '8px 0' }}>\n {groups.map(\n (group) =>\n group.entries.length > 0 && (\n <div key={group.type} style={{ marginBottom: 8 }}>\n <div\n style={{\n padding: '4px 16px',\n fontSize: 11,\n fontWeight: 700,\n textTransform: 'uppercase',\n letterSpacing: '0.05em',\n color: RESOLUTION_COLORS[group.type],\n }}\n >\n {RESOLUTION_LABELS[group.type]} ({group.entries.length})\n </div>\n {group.entries.map((entry) => (\n <div\n key={`${entry.key}-${entry.namespace}-${entry.scope ?? ''}`}\n style={{\n padding: '4px 16px 4px 24px',\n display: 'flex',\n alignItems: 'baseline',\n gap: 8,\n }}\n >\n <span\n style={{\n width: 6,\n height: 6,\n borderRadius: 3,\n background: RESOLUTION_COLORS[entry.resolvedFrom],\n flexShrink: 0,\n alignSelf: 'center',\n }}\n />\n <span\n style={{\n fontFamily: 'ui-monospace, monospace',\n fontSize: 12,\n wordBreak: 'break-all',\n }}\n >\n {entry.key}\n </span>\n <span\n style={{\n fontSize: 11,\n color: '#94a3b8',\n marginLeft: 'auto',\n flexShrink: 0,\n }}\n >\n {entry.namespace}\n {entry.scope ? ` / ${entry.scope}` : ''}\n </span>\n </div>\n ))}\n </div>\n ),\n )}\n {totalKeys === 0 && (\n <div style={{ padding: '16px', textAlign: 'center', color: '#64748b' }}>\n No keys used yet\n </div>\n )}\n </div>\n </div>\n )}\n </>\n );\n}\n","import { type ReactNode } from 'react';\nimport { useI18n } from './useI18n';\n\nexport interface I18nBoundaryProps {\n /** Scope to load (e.g., 'products.index') */\n scope: string;\n /** Rendered while translations are loading */\n fallback?: ReactNode;\n /** Rendered once translations are ready */\n children: ReactNode;\n}\n\n/**\n * Boundary component that handles translation loading.\n * Children only render once the scope is ready, avoiding\n * rules-of-hooks violations from early returns in child components.\n *\n * @example\n * ```tsx\n * <I18nBoundary scope=\"products.index\" fallback={<Spinner />}>\n * <ProductsPage />\n * </I18nBoundary>\n * ```\n */\nexport function I18nBoundary({ scope, fallback = null, children }: I18nBoundaryProps) {\n const { ready } = useI18n(scope);\n\n if (!ready) return <>{fallback}</>;\n return <>{children}</>;\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,IAAa,cAAc,cAAuC,KAAK;;;ACgCvE,SAAgB,aAAa,EAAE,UAAU,UAAU,mBAAsC;CACvF,MAAM,CAAC,YAAY,eAAe;AAChC,MAAI,gBACF,QAAO;AAET,MAAI,OAAO,WAAW,eAAgB,OAA0B,mBAC9D,QAAO;AAET,SAAO;GACP;CAEF,MAAM,CAAC,SAAS,cAAc,eAAe;AAC3C,MAAI,iBAAiB;GACnB,MAAM,SAAS,SAAS,WAAW;AACnC,QAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,gBAAgB,CAC7D,UAAS,aAAa,QAAQ,WAAW,KAAK;AAEhD,UAAO;;EAIT,MAAM,MAAM,OAAO,WAAW,cAAe,SAA4B,KAAA;AACzE,MAAI,KAAK,oBAAoB;GAC3B,MAAM,aAAa,IAAI;AACvB,QAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,WAAW,UAAU,CAClE,UAAS,aAAa,WAAW,QAAQ,WAAW,KAAK;AAE3D,UAAO,IAAI;AACX,UAAO;;AAGT,SAAO;GACP;AAEF,iBAAgB;AACd,oBAAkB,SAAS;EAE3B,MAAM,QAAQ,SAAS,qBAAqB;AAC1C,eAAY,MAAM,IAAI,EAAE;IACxB;AAEF,MAAI,CAAC;OACc,SAAS,oBAAoB,CAAC,SAAS,EAEtD,UAAS,oBAAoB,SAAS,WAAW,CAAC,CAAC,WAAW;AAC5D,gBAAY,MAAM,IAAI,EAAE;KACxB;;AAIN,SAAO;IACN,CAAC,UAAU,SAAS,CAAC;CAExB,MAAM,eAAe,eACZ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AAA,UAAG,UAAY,CAAA;AAClC,QAAO,oBAAA,UAAA,EAAG,UAAY,CAAA"}
|
|
1
|
+
{"version":3,"file":"react.js","names":[],"sources":["../src/react/context.ts","../src/react/I18nProvider.tsx","../src/react/useI18n.ts","../src/react/DevToolbar.tsx","../src/react/I18nBoundary.tsx"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n","import { useEffect, useState, useMemo, type ReactNode } from 'react';\nimport { I18nContext } from './context';\nimport { setGlobalInstance } from '../core/t';\nimport type { I18nInstance, NestedTranslations } from '../core/types';\n\n/**\n * Props for the {@link I18nProvider} component.\n */\nexport interface I18nProviderProps {\n /** The i18n instance returned by `createI18n()`. */\n instance: I18nInstance;\n /** Child components that will have access to translations. */\n children: ReactNode;\n /**\n * Pre-loaded translations from SSR. When provided, the provider adds these\n * resources to the store immediately and skips dictionary fetching.\n */\n serverResources?: Record<string, NestedTranslations>;\n /**\n * Rendered while dictionaries are loading on init. Default: renders children\n * immediately (dictionaries load in background).\n * Set to `null` for blank screen, or `<Spinner />` for a loading indicator.\n * Once dictionaries are loaded, this is never shown again.\n */\n fallback?: ReactNode;\n /**\n * Scopes to eagerly preload on mount (alongside dictionaries).\n * Use for small apps where you want all translations available immediately,\n * or to prefetch scopes for pages the user is likely to visit.\n */\n preloadScopes?: string[];\n /**\n * If true, render children before dictionaries finish loading.\n * Dictionary keys will return fallback strings until loaded.\n * Default: false (children wait for dictionaries).\n */\n eager?: boolean;\n}\n\n/**\n * React context provider for translations.\n *\n * On mount, it sets the global i18n instance and loads all dictionary\n * bundles (one HTTP request per named dictionary, in declaration order).\n * Re-renders children when dictionaries finish loading and when the\n * locale changes.\n *\n * @example\n * ```tsx\n * import { createI18n } from 'vite-bundled-i18n';\n * import { I18nProvider } from 'vite-bundled-i18n/react';\n *\n * const i18n = createI18n({ ... });\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * </I18nProvider>\n * );\n * }\n * ```\n */\ninterface WindowWithI18n extends Window {\n __I18N_RESOURCES__?: {\n locale: string;\n resources: Record<string, NestedTranslations>;\n };\n}\n\nexport function I18nProvider({\n instance,\n children,\n serverResources,\n fallback,\n preloadScopes,\n eager = false,\n}: I18nProviderProps) {\n // Hydrate from SSR data synchronously (before first render)\n const [hydrated] = useState(() => {\n if (serverResources) {\n const locale = instance.getLocale();\n for (const [namespace, data] of Object.entries(serverResources)) {\n instance.addResources(locale, namespace, data);\n }\n return true;\n }\n\n const win = typeof window !== 'undefined' ? (window as WindowWithI18n) : undefined;\n if (win?.__I18N_RESOURCES__) {\n const serverData = win.__I18N_RESOURCES__;\n for (const [namespace, data] of Object.entries(serverData.resources)) {\n instance.addResources(serverData.locale, namespace, data);\n }\n delete win.__I18N_RESOURCES__;\n return true;\n }\n\n return false;\n });\n\n // Track whether dictionaries have been loaded (Phase 1)\n const [dictsReady, setDictsReady] = useState(() => {\n if (hydrated) return true;\n // No dictionaries configured → ready immediately\n const dictNames = instance.getDictionaryNames();\n if (dictNames.length === 0) return true;\n // All dictionary namespaces already in cache (e.g. added via addResources) → ready\n const locale = instance.getLocale();\n const dictNs = instance.getDictionaryNamespaces();\n return dictNs.length > 0 && dictNs.every(ns => instance.isNamespaceLoaded(locale, ns));\n });\n\n const [version, setVersion] = useState(hydrated ? 1 : 0);\n\n useEffect(() => {\n setGlobalInstance(instance);\n\n const unsub = instance.onLocaleChange(() => {\n setVersion((v) => v + 1);\n });\n\n const locale = instance.getLocale();\n const promises: Promise<void>[] = [];\n\n // Phase 1: Load dictionaries (if not hydrated and not already cached)\n if (!hydrated && !dictsReady) {\n if (instance.getDictionaryNames().length > 0) {\n promises.push(instance.loadAllDictionaries(locale));\n }\n }\n\n // Eagerly preload scopes (runs regardless of dict state)\n if (preloadScopes && preloadScopes.length > 0) {\n for (const scope of preloadScopes) {\n if (!instance.isScopeLoaded(locale, scope)) {\n promises.push(instance.loadScope(locale, scope));\n }\n }\n }\n\n if (promises.length > 0) {\n Promise.all(promises).then(() => {\n setDictsReady(true);\n setVersion((v) => v + 1);\n });\n }\n\n return unsub;\n }, [instance, hydrated, preloadScopes]);\n\n const contextValue = useMemo(\n () => ({ instance, version }),\n [instance, version],\n );\n\n // Gate rendering until dictionaries are ready (unless eager mode)\n const showChildren = eager || dictsReady;\n\n return (\n <I18nContext.Provider value={contextValue}>\n {showChildren ? children : (fallback ?? null)}\n </I18nContext.Provider>\n );\n}\n","import { useContext, useEffect, useState, useMemo } from 'react';\nimport { I18nContext } from './context';\nimport { createTranslations } from '../core/getTranslations';\nimport type { UseI18nResult, ValidScope } from '../core/types';\n\n/**\n * React hook for accessing translations.\n *\n * Can be called with or without a scope:\n *\n * **Without scope** — accesses only dictionary translations (shared, global, etc.).\n * Use this in layout components, navigation, footers, and other app-wide UI.\n *\n * **With scope** — triggers loading of the scope bundle (one HTTP request for all\n * namespaces that page needs). Use this in route/page components.\n *\n * Keys are always fully qualified (e.g., `'products.show.title'`), regardless of scope.\n *\n * @param scope - Optional bundle identifier (e.g., `'products.show'`).\n * Triggers loading of the scope bundle via `/__i18n/{locale}/{scope}.json`.\n * @returns An object with `t` (translation function), `ready` (loading state),\n * and `locale` (current locale code)\n * @throws If called outside of an `I18nProvider`\n *\n * @example\n * ```tsx\n * // Dictionary-only access\n * const { t, ready } = useI18n();\n * t('shared.ok', 'OK');\n *\n * // Bundle + dictionary access\n * const { t, ready } = useI18n('products.show');\n * t('products.show.title', 'Product Details');\n * t('shared.ok', 'OK'); // dictionaries still work\n * ```\n */\nexport function useI18n(scope?: ValidScope): UseI18nResult {\n const ctx = useContext(I18nContext);\n\n if (!ctx) {\n throw new Error(\n 'vite-bundled-i18n: useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider instance={...}>.',\n );\n }\n\n const { instance, version } = ctx;\n const locale = instance.getLocale();\n const [scopeReady, setScopeReady] = useState(() => {\n if (!scope) return true;\n return instance.isScopeLoaded(locale, scope);\n });\n const [loadedScopeKey, setLoadedScopeKey] = useState<string | null>(null);\n\n // Load scope bundle if needed — one HTTP request per scope\n const scopeKey = scope ? `${locale}:${scope}` : null;\n useEffect(() => {\n if (!scopeKey || !scope) return;\n if (scopeKey === loadedScopeKey) return;\n\n let cancelled = false;\n instance.loadScope(locale, scope).then(() => {\n if (!cancelled) {\n setLoadedScopeKey(scopeKey);\n setScopeReady(true);\n }\n });\n\n return () => { cancelled = true; };\n }, [scopeKey, scope, locale, instance, loadedScopeKey]);\n\n // Re-create the translator object whenever locale or loaded resources change.\n const translations = useMemo(\n () => createTranslations(instance, locale),\n // version is not read directly here, but it must participate so the\n // translator object is recreated after dictionary/scope loads.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [instance, locale, version],\n );\n\n return {\n t: translations.t,\n get: translations.get,\n has: translations.has,\n exists: translations.exists,\n tryGet: translations.tryGet,\n require: translations.require,\n translations,\n ready: scopeReady,\n locale,\n };\n}\n","import { useContext, useState } from 'react';\nimport { I18nContext } from './context';\nimport type { KeyUsageEntry } from '../core/types';\n\nconst RESOLUTION_COLORS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: '#4ade80',\n 'fallback-locale': '#facc15',\n 'fallback-string': '#fb923c',\n 'key-as-value': '#f87171',\n};\n\nconst RESOLUTION_LABELS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: 'Primary',\n 'fallback-locale': 'Fallback Locale',\n 'fallback-string': 'Fallback String',\n 'key-as-value': 'Key as Value',\n};\n\n/**\n * Dev-only toolbar overlay that displays translation diagnostics\n * for the current page. Reads key usage data from the i18n instance\n * via {@link I18nContext}.\n *\n * Renders nothing in production or when used outside an `I18nProvider`.\n *\n * @example\n * ```tsx\n * import { DevToolbar } from 'vite-bundled-i18n/react';\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * <DevToolbar />\n * </I18nProvider>\n * );\n * }\n * ```\n */\nexport function DevToolbar() {\n // Skip in production — always render in test (import.meta.env may not exist)\n const isDev =\n typeof import.meta !== 'undefined' && import.meta.env\n ? import.meta.env.DEV\n : true;\n\n const ctx = useContext(I18nContext);\n\n const [open, setOpen] = useState(false);\n\n if (!isDev) return null;\n if (!ctx) return null;\n\n const { instance } = ctx;\n const usage = instance.getKeyUsage();\n const locale = instance.getLocale();\n\n // Deduplicate keys for display — keep the first occurrence\n const uniqueKeys = new Map<string, KeyUsageEntry>();\n for (const entry of usage) {\n if (!uniqueKeys.has(entry.key)) {\n uniqueKeys.set(entry.key, entry);\n }\n }\n\n const groups: Array<{ type: KeyUsageEntry['resolvedFrom']; entries: KeyUsageEntry[] }> = [\n { type: 'primary', entries: [] },\n { type: 'fallback-locale', entries: [] },\n { type: 'fallback-string', entries: [] },\n { type: 'key-as-value', entries: [] },\n ];\n\n for (const entry of uniqueKeys.values()) {\n const group = groups.find((g) => g.type === entry.resolvedFrom);\n if (group) group.entries.push(entry);\n }\n\n const primaryCount = groups[0].entries.length;\n const fallbackCount =\n groups[1].entries.length + groups[2].entries.length;\n const missingCount = groups[3].entries.length;\n const totalKeys = uniqueKeys.size;\n\n return (\n <>\n {/* Toggle button */}\n <button\n data-testid=\"i18n-toolbar-toggle\"\n onClick={() => setOpen((v) => !v)}\n style={{\n position: 'fixed',\n bottom: 16,\n right: 16,\n zIndex: 99999,\n width: 44,\n height: 44,\n borderRadius: 22,\n border: 'none',\n background: missingCount > 0 ? '#dc2626' : '#2563eb',\n color: '#fff',\n fontSize: 14,\n fontWeight: 700,\n cursor: 'pointer',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n boxShadow: '0 2px 8px rgba(0,0,0,0.3)',\n fontFamily: 'system-ui, sans-serif',\n }}\n aria-label={open ? 'Close i18n toolbar' : 'Open i18n toolbar'}\n >\n {totalKeys}\n </button>\n\n {/* Panel */}\n {open && (\n <div\n data-testid=\"i18n-toolbar-panel\"\n style={{\n position: 'fixed',\n bottom: 68,\n right: 16,\n zIndex: 99999,\n width: 380,\n maxHeight: 480,\n background: 'rgba(0, 0, 0, 0.92)',\n color: '#f1f5f9',\n borderRadius: 10,\n boxShadow: '0 4px 24px rgba(0,0,0,0.4)',\n fontFamily: 'system-ui, sans-serif',\n fontSize: 13,\n overflow: 'hidden',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n {/* Header */}\n <div\n style={{\n padding: '12px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n }}\n >\n <span style={{ fontWeight: 600, fontSize: 14 }}>i18n DevToolbar</span>\n <span\n style={{\n background: '#2563eb',\n color: '#fff',\n padding: '2px 10px',\n borderRadius: 12,\n fontSize: 12,\n fontWeight: 600,\n }}\n >\n {locale}\n </span>\n </div>\n\n {/* Summary */}\n <div\n style={{\n padding: '10px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n gap: 16,\n flexWrap: 'wrap',\n fontSize: 12,\n }}\n >\n <span>\n Total: <strong>{totalKeys}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS.primary }}>\n Primary: <strong>{primaryCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['fallback-locale'] }}>\n Fallback: <strong>{fallbackCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['key-as-value'] }}>\n Missing: <strong>{missingCount}</strong>\n </span>\n </div>\n\n {/* Key list */}\n <div style={{ overflowY: 'auto', flex: 1, padding: '8px 0' }}>\n {groups.map(\n (group) =>\n group.entries.length > 0 && (\n <div key={group.type} style={{ marginBottom: 8 }}>\n <div\n style={{\n padding: '4px 16px',\n fontSize: 11,\n fontWeight: 700,\n textTransform: 'uppercase',\n letterSpacing: '0.05em',\n color: RESOLUTION_COLORS[group.type],\n }}\n >\n {RESOLUTION_LABELS[group.type]} ({group.entries.length})\n </div>\n {group.entries.map((entry) => (\n <div\n key={`${entry.key}-${entry.namespace}-${entry.scope ?? ''}`}\n style={{\n padding: '4px 16px 4px 24px',\n display: 'flex',\n alignItems: 'baseline',\n gap: 8,\n }}\n >\n <span\n style={{\n width: 6,\n height: 6,\n borderRadius: 3,\n background: RESOLUTION_COLORS[entry.resolvedFrom],\n flexShrink: 0,\n alignSelf: 'center',\n }}\n />\n <span\n style={{\n fontFamily: 'ui-monospace, monospace',\n fontSize: 12,\n wordBreak: 'break-all',\n }}\n >\n {entry.key}\n </span>\n <span\n style={{\n fontSize: 11,\n color: '#94a3b8',\n marginLeft: 'auto',\n flexShrink: 0,\n }}\n >\n {entry.namespace}\n {entry.scope ? ` / ${entry.scope}` : ''}\n </span>\n </div>\n ))}\n </div>\n ),\n )}\n {totalKeys === 0 && (\n <div style={{ padding: '16px', textAlign: 'center', color: '#64748b' }}>\n No keys used yet\n </div>\n )}\n </div>\n </div>\n )}\n </>\n );\n}\n","import { type ReactNode } from 'react';\nimport { useI18n } from './useI18n';\n\nexport interface I18nBoundaryProps {\n /** Scope to load (e.g., 'products.index') */\n scope: string;\n /** Rendered while translations are loading */\n fallback?: ReactNode;\n /** Rendered once translations are ready */\n children: ReactNode;\n}\n\n/**\n * Boundary component that handles translation loading.\n * Children only render once the scope is ready, avoiding\n * rules-of-hooks violations from early returns in child components.\n *\n * @example\n * ```tsx\n * <I18nBoundary scope=\"products.index\" fallback={<Spinner />}>\n * <ProductsPage />\n * </I18nBoundary>\n * ```\n */\nexport function I18nBoundary({ scope, fallback = null, children }: I18nBoundaryProps) {\n const { ready } = useI18n(scope);\n\n if (!ready) return <>{fallback}</>;\n return <>{children}</>;\n}\n"],"mappings":";;;;;;;;;;;;AA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A,cAAc,KACb,oBAAC,OAAD;KAAK,OAAO;MAAE,SAAS;MAAQ,WAAW;MAAU,OAAO;MAAW;eAAE;KAElE,CAAA,CAEJ;;GACF;IAEP,EAAA,CAAA;;;;;;;;;;;;;;;;ACzOP,SAAgB,aAAa,EAAE,OAAO,WAAW,MAAM,YAA+B;CACpF,MAAM,EAAE,UAAU,QAAQ,MAAM;AAEhC,KAAI,CAAC,MAAO,QAAO,oBAAA,UAAA,EAAA,UAAG,UAAY,CAAA;AAClC,QAAO,oBAAA,UAAA,EAAG,UAAY,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vite-bundled-i18n",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.15",
|
|
5
5
|
"description": "Route-aware i18n for Vite apps with typed keys, scope bundles, dictionary ownership, and compiled production output.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"types": "./dist/index.d.ts",
|